#⚛️┃physics
1 messages · Page 83 of 1
Because in your physics settings you probably have it so it keeps a small gap
Your object is in the range of centimeters
Box2d isade to work in yhe the range of meters
public Vector3 getTorqueNeededForAcceleration(Vector3 acceleration)
{
Vector3 tensor = myRB.inertiaTensor;
float torque_x = tensor.x * acceleration.x;
float torque_y = tensor.y * acceleration.y;
float torque_z = tensor.z * acceleration.z;
return new Vector3(torque_x, torque_y, torque_z);
}
This does not work if the input vector is of the form [0,0,z]
#854851968446365696 for how to share code
You also don't need this function. Just call AddTorque with https://docs.unity3d.com/ScriptReference/ForceMode.Acceleration.html
AddTorque accepts a forcemode argument
@timid dove I'm using add force at position to achieve desired torque for a helicopter controller.
I'm not sure how that's relevant to the code you posted or what you said before
Well that's why I need to calculate torque needed for a given angular acceleration manually. I'm wondering if that function I posted is correctly using the inertia tensor.
It depends whether you're considering the input vector as local or world space and how you're interpreting the result and what you're doing with it
Inertia tensor is a local space thing for the Rigidbody
I'm using world space. That must be it.
Well, without that I'm a bit stumped. I created a new project with two objects and there is no gap. Simlar settings that you have except I zero'd the offsets. Without seeing specifics of the projects, I can only throw guesses at you. Like try zero'ing the offsets. What is the scale/ie, how zoomed in are you? I will say this, Iapinozz said could be true. It could be magnified if your scale is quite small. Look at this sample I built. Looks good, but you see there is a gap. My offset is zero. now, That could be eliminated by changing offset and he is right, Unity does keep a small gap and that's intentional to keep things from "falling" through the floor.
see above, sorry I forgot to hit reply
If the colliders get too close for physics to calculate in time, things will pass through that aren't intended to pass through and weird stuff happens. Moving your offset won't cause that, it will just help your player be closer to the "floor".
if you take the default gap unity adds, plus your offset, divided by the scale of your project, that could be your result.
Goodnight guys, I have some domino tiles on a makeshift table (plane) that I want to react to one domino. That one domino would come down on the table so hard that it causes the rest on the table to move (like what slamming something on a table does to other objects on it). However, I am stuck as to how I would go about implementing this effect. Any pointers? Thanks!
Hi, I am making a 2d platformer game based on physics. player needs to jump over some hanging planks to cross some areas. I did all moments of player with forces, problem is that when player is on hanging planks the planks are moving by player...player can not be on plank, also plank gets parent for the player while player is on plank. I do not understand the problem. plz help
#💻┃unity-talk message for further details
I think this could be achieved using AddExplosionForce on rigidbodies.
I did something kind of similar
What you'd do is either OverlapSphere or sphereCastAll to get all of the dominoes in the area you want to affect with this impact
then using a foreach loop, you can one-by-one do your addExplosionForce method to the rigidbodies.
@raw yarrow You can get the collision points as well, in your OnCollisionEnter, you should also be able to get relative velocity for each collision point
Thanks for the reply! I ended up doing something similar (adding a upward impulse force to the rigidbodies of the tiles on the table as one domino hit the table), going to try out the AddExplosionForce to see if it produces better results though. Thanks again!
Thanks for the reply! This method would work as well, It just seems as if it would be more work with my setup (setting up the different tags and such). Definitely a fallback option if my current solution begins to show noticeable flaws. Thanks for replying again!
How can I make something like Tribes Ascend's core mechanic in Unity 3D?(Im still a begginer)
I'm having an issue. Whenever I'm right next to a slope, the raycast I'm using thinks I'm at the slope and thus I can't move my character
{
Vector2 CheckPos = GroundCollider.bounds.center - new Vector3(0, GroundCollider.bounds.extents.y);
//Debug.Log(CheckPos);
SlopeCheckHor(CheckPos);
SlopeCheckVer(CheckPos);
}
void SlopeCheckHor(Vector2 CheckPos)
{
RaycastHit2D Front = Physics2D.Raycast(CheckPos, Vector2.right, GroundCollider.bounds.extents.x*3, LayerMask.GetMask("Ground"));
RaycastHit2D Back = Physics2D.Raycast(CheckPos, -Vector2.right, GroundCollider.bounds.extents.x*3, LayerMask.GetMask("Ground"));
if (Front)
{
onSlope = true;
SlopeSideAngle = Vector2.Angle(Front.normal, Vector2.up);
}
else if (Back)
{
onSlope = true;
SlopeSideAngle = Vector2.Angle(Back.normal, Vector2.up);
}
else
{
SlopeSideAngle = 0;
onSlope = false;
}
}```
this is my raycast's code
I need a byte serializer/deserializer for a physics object cloner in a modified Farseer Physics Engine. Looking to pay someone talented for this, PM me
has anyone used puppetmaster with the newest unity version? nothing seem to work. muscles are all over the place
whats wrong with my prop muscle?
normal muscles seem fine, but the gizmos draws 100 lines for one prop muscle
if only unity had its native ragdoll tool. now i have to go back to unity 2020 because there are so many bugs now with puppetmaster
so pls unity buy puppetmaster, or create your own tool and keep it updated! its an essential tool!
Do you guys know any free alternative to Dynamic bones ?
"Dynamic Bone applies physics to character's bones or joints" what does that even mean?
bonecolliders?
Dynamic Bone apply physics to character's bones or joints.
With simple setup, your character's hair, cloth, breasts or any part will move realistically.
Unity Asset Store: http://u3d.as/7fH
Web Demo: https://dl.dropboxusercontent.com/s/tgjybiv2lckhgag/DynamicBone.html
Blog: http://willhongcom.blogspot.com/
If you are not sure is Dynamic Bone wor...
Allow you to define how a chain of bones behave when their attachment move arround
hmmm so its and alternative for doing bone weights and joints settings manually?
It allows you to define the softness of the material and then it does the rest. Also you can interact with the chain with coliders
seems like people are using this for vr chat only
But yeah i guess we can do it manually
It has a lot of popularity in vrchat cause every avatar use it, though its a popular asset regardless
k
I've seen many games using it.
But i'm trying to make something i can publish the source code from, so i cant use a paid asset
Its litteraly the first result in the unity asset store
"Cloth component is built into unity.... not exactly the same, but you can use it in place of dynamic bones in most instances." https://www.reddit.com/r/VRchat/comments/a5oihq/help_probably_a_silly_question_but_are_there_any/
24 votes and 27 comments so far on Reddit
Yeah i saw thoose posts. I'm not sure on the second repo if its really something that works without the addon, or if its a placeholder for vrchat creator to setup their bones without the addon
I'll try that though thanks
but you can edit the script and rerelease it
Oh, yeah you're right !
I didnt think of that
they wont be able to like build the source, but for modding kit its probably enought
i figured this sht. i need a parent constraint for my weapons that are not a propmuscle(cant child them to a metarigg object). if i set a gameObject as a child of a animation target(under metarigg section) the muscle go totally crazy. why is that suddenly appearing under 2021.2?
when I generate a map for my game, its made up of tiles with box colliders for the ground. These ground tile colliders line up perfectly (as far as I can tell), however when crossing the boundary between them there is sometimes a collision, as if there is a "lip" between them. It messes up player and enemy movement briefly. Is there some easy way to fix this? Im guessing I could instead generate a continuous mesh for the ground, but it seems like a lot of effort
If you make the ground colliders overlap a little bit it will probably solve the problem
if you're using a tilemap for your tiles then using a tilemap collider is probably a good idea and should solve it, too
ive never heard of tilemap, ill look at that
it sounds like you're working in 2D, so making edge colliders so you have one big continuous collider shouldn't be that hard, either
its 3d
ah, well then I'm not sure tilemap will be a good fit either
overlapping didnt really work, now it seems like there are 2 lips 😦
Anyone know how to stop rigidbodies on moving objects from doing this ?
Your image is not terribly clear. What exactly is it doing that you don't like?
Sorry 😅 I'd like the rigidbody on top of the moving platform to stay positioned stationary relative to the platform. Not pull back from the forwards velocity
here's the workflow I've been trying to get under control. I have the cape in blender with other objects on the main rig. I send it to unity, I make it a prefab, I take off all the other objects but leave the rig and the cape. then I add the cloth component to the cape. I set constraints on the top of the cape to let the bottom flow smoothly. I then build slots/overlay/recipe for it and put it on the character. the problem I'm having is the cape bunches up together on the bottom and doesn't really flow when he runs, it just kinda flaps side to side.
also the cape swings around his neck a bunch
Does anyone here believe that that Unity's physics engine (or any C# physics engine that uses floating point math) is cross-platform deterministic? I'm fully aware that it is NOT deterministic, but recently another developer asked me this question so I figure I'd ask the community.
@runic surge Big source of nondeterministic behaviour in rollback networked games is not being able to full replicate the state the of the physics simulation
That'd be the internal states held in the physics engine other than velocity, angular velocity, position, rotation
If you want to totally avoid state transferring, you'd probably wanna use fixed points
But if you'll be having some state transferring, then unity.physics, a stateless floating point physics engine should be fine
The chaos that's produced by the floating point processing divergences might be negligible for some sort of games I think
Maybe you can avoid state syncing
Or sync the states every 5 seconds to keep the divergence in check
!help
if you have more than one collider on an object and you use that one object on the cloth component will it register all colliders?
maybe freeze the rigidbody when it touches the platform, and only allow movement if the player is pressing the input keys
Mathf.Infinity using the System namespace?
Situation: I want to make drag-and-drop elements in / for a GUI. Would it be better for optimization or development to simply calculate the movement and rigidbody physics inside a separate collision group (e.g. , and not inside a Canvas object? If possible, I'd like to calculate physics with the drag and drop elements. If any further clarification is needed, please tell me so I can elaborate further in future questions
What you mean exactly? You don’t mean unlimited as infinity ig. You can put any numbers on the Quaternion.Euler, it’s not limited to [0, 180] range
I don’t get what you mean and not #⚛️┃physics related. Maybe try to ask in #💻┃code-beginner
It’s either me not understanding or your question being unclear. It seems skary didn’t understand you either…
!help
Hello guys. I have been running into this problem for a while and I thought that I could get some help. The issue is that wheel colliders just fall thru the ground. I don't know why. When I place them beside the car they work perfectly but when I put them back they just fall down as if I didn't have wheel colliders. Here is a screenshot of the properties:
my problem is that when it's enabled again, it's getting influenced by that force again in addition to the player applying force
If it's such a no-no to directly modify the velocity of a Rigidbody, what's the best way to make sure the entity does ever move faster than we want it to?
In my case it's a character that I'm moving, it has a max run speed. I'm using AddForce to move it because I DO WANT acceleration and braking (not just instant movement and stopping).
Most solutions I find online are doing it the no-no way of just setting the velocity directly if it's greater than the limit.
Such limits are a valid post process to apply to velocity. In most cases though it ends up being simpler to make a kinematic motor/controller that inherently follows the right rules vs you fixing a realistic simulation to become unrealistic but more fun. This velocity no-no attitude is mostly grounded in this observation and the assumption that whoever sets velocity directly (in this discord) doesn’t know how to use physics correctly.
The only situation where you would use simulated physics (forces) is when you need complex interactions of objects (collisions or other forces) that are realistic and with little to no changes to the default behavior.
So I have to should write my own "acceleration" system then?
Hardly a system.
Well..."implementation".
it depends on the design of your game. Maybe sim physics are the right way for you
Either approach is eventually a bunch of work and you kinda need to guess which one will cause you less trouble
Understood. Thanks.
Hey guys do you know why the collider doesn't follow my navmesh agent?
i added a kinematic rigidbody and box collider and i have a navmeshagent using setDestination to move to where the cursor clicks. I read in the docs that a kinematic rigidbody can be used with navmesh but it's not moving
So looks like the mesh the collider is on cannot have a parent... is this a bug?
Hey everyone, does non-convex mesh collider, without rigidbody, is still cost expensive?
Because after couple collisions with it I would replace that object with cloned objects with sphere colliders and rigidbody.
Not sure if that's way less performant than making couple of sphere colliders instead of mesh one
A couple spheres is probably faster than a complicated concave mesh, but you'd have to profile it I guess. As long as the collider is static it shouldn't matter all that much either way.
That's what I thought, I just have a mesh collider on a object without rigid body, so it won't be moved at all, just detect collisions if player like run into it.
@timid dove thanks
Anyone?
is the navmeshagent component on the root object?
yes
And the collider?
If not on the root object try again by adding it on root object
Or try capsule collider
Having trouble getting ontrigger2d to fire. One object has a collider2d + rigidbody2d and is set to IsTrigger. The other object has a collider2d. I have a script setup on the object that has the rigidbody that has the OnTrigger2d function with a debug.log printout. I drag the objects into each other and the script doesn't fire. Anyone see something obviously wrong here? Of note: I made these objects and attached everything while the editor was running, don't know if that matters?
nvm think I figured it out
Those 2 objects were already inside another collider, so ontriggerenter2d had fired earlier
Okay, so i've been trying to remove collision between two rigidbodies connected by a joint. one is kinematic, with only a box collider and the other is made of a compound collider. Initially i just tried keeping "Enable collision" false, which did not work. I then tried removing collision when the joint is added, and adding it back when the joint is removed
//sets whether or not the hand's colliders will collide with col
public void IgnoreCollision(Collider col, bool Active)
{
Debug.Log("Ignoring collision between " + col.gameObject.name + " and " + gameObject.name);
Physics.IgnoreCollision(HandCollider, col, Active);
Physics.IgnoreCollision(FingerCollider, col, Active);
}
this also did not work. i don't want to use layers, as i could have two objects grabbing one object, and as such would need a layer for each hand, and three layers for the potential grab states(LeftNoCollide, RightNoCollide, BothNoCollide. don't need a fourth as we can just use the layer the object was already using for that)
what might be going wrong? what should i do? any help is appreciated!
i should add that disabling the colliders, while a potential solution, does not work in my case as i would still like the hands to be able to collide with other things
Hello, I am changing a joint's connectedAnchor from a script but the joint wont get updated unless I select the item in the editor or move its rigid body, it seems physics are sleep thus the joint is not updated. Do you know how to force physics to wake up? Thank you
Change from kinematic to dynamic
if it is kinematic
It is not
anyone know why my raycast detects my model when it's from from WITHIN my model?
i imported the model via .fbx, but did not check "generate colliders" on the import settings. but the trigger fires everytime it starts from within the model mesh. it's like the model came with a hidden mesh collider, but i can't find it
Raycast hits only happen with colliders so you could just have your code print out which object has the collider
yeah, I have. it keeps printing out the name of the gameobject from within which the raycast is fired from.
until i move the starting point of the raycast out of the model, then it works fine. it's not the mesh of the model, looks like it's colliding with the bone of the model, but the bone seems to have a hidden collider?
nvm i know the issue, it's colliding with an external collider on that gameobject, so looks like my collision matrix isn't right.
That works, thank you!
any ideas why two rigidbodies connected by a configurable joint could be colliding?
You still need state transferring with fixed points. For example, if someone joins my match late, my options are send full state or to replay all inputs...so sending state is preferred to avoid unnecessary computation
but thank you for your response - I appreciate it
I'm making a sort of doom/Quake style game and I'm looking for advice regarding my map's collision. Currently I'm using a set of mesh colliders for each room. I made a basic version of the map for mesh collision detection. My problem is that I keep seeing that mesh colliders are terrible and that I should use box colliders. Is it worth spending the time to box collide everything or should I stick with the basic version of my map with mesh colliders?
You can use box colliders if you have enough time
Its worth it only if you gain something by using box colliders (sphere and capsule are even faster). Almost always box colliders are faster but you should use profiler to see if physics performance is a problem to begin with. If the mesh collider mesh is simple enough (convex is also better for performance), the difference may be negligible
Like what?
so which object are we looking at
Seems like you have a separate object for the collider and the "Wheel Transform"?
merche?
Mesh sorry
Just position them properly - not sure what else to say
Move them to where they need to be
the postition is good
hello why I cant send code block
I know how to send it doesnt let me
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == ("Player"))
{
ScoringSystem.theScore += 100;
SaveManager.instance.money += 100;
SaveManager.instance.Save();
Destroy(gameObject);
Hi I have multiple objects with mesh collider and they are using same tag .I have this scripts that detects it and gives a score but I wanted to give only 100 score but it gives multiple because some cars have 5-6 mesh colliders how I can make it detect multiple and gives 100 every time ?
thanks it worked
Someone can help me with the collider please
i dont know why my left wheel is like this
i dont know if is a colliderr problem
my left wheel car collider is reverse
So this is probably the noobest of questions, but I'm taking a Unity class to finish my software dev certificate, and I'm trying to make a 2d virtual pinball game for the final. The physics seem to LARGELY work fine, but when I try to use the flippers to hit the ball back up the table, a lot of the time it sees like the flippers miss the collision entirely--like one frame they're below the ball, next frame they're ABOVE the ball, but the ball just keeps going like it was never touched. I get the feeling that this may be because I'm moving the flippers by changing the Z rotation by 15 degrees every frame until they get to their top position (since that feels roughly about how quick flippers on a real pinball table move), so unity MAY just be calculating the discrete positions, even though I've enabled "Interpolation" on the flipper rigidbodies and "Extrapolation" on the ball's rigidbody. But I'm sure there has to be some kind of way around this because games do stuff like this all the time?
Unfortunately I can't send my code, because we all have to use Visual Scripting for this class, and I hate it. At least C# is helpful with its debug logs. 🙄
What do you mean by "reverse"?
You need to move the flippers in a physics aware way like MovePosition/MoveRotation, you can't teleport them
Hm. I'll look into this, thank you
look
Top = Right Side
Down = Left side
Look the wheel you will understand
"Rotates the Rigidbody to the specified angle by calculating the appropriate angular velocity required to rotate the Rigidbody to that angle during the next physics update. During the move, angular drag won't affect the body. This causes the object to rapidly move from the existing angle to the specified angle."
hm. so does this "teleport" to the angle in one frame while also calculating the physics, or is there some sort of way to control the speed of this movement
ohhh ok i figured out how it works, thank you so much!!
Yes
i have wheel transform and wheel collider
Hello guys
i need help
i have created a car
But the left side of the car for the wheels is reverse in game
i dont know why
he need to be like that
I am not so sure but... you might want to check the normals on the modeling app (like blender perhaps)
Is it bad to scale a mesh to crazy large sizes? Should I be making them large in Blender then exporting them so they're not such a large scale?
If this isn't the right channel, my apologies. Does this harm performance?
Is the Havok package just slightly usable in a project?
All I need is a solid Rigidbody for my player because Unity's is really unreliable it turns out
I don't need any debugging tools, just a player rigidbody and that's it
Can Havok provide that in its current state?
Generally all objects should have a scale of 1 when in their default state in a scene. It does not affect performance meaningfully if they are not but makes working with them much more convenient. any vertices that are roughly 8000 units or more away from the origin will experience some form of noticeable floating point inaccuracy when the scene is layed out for human scale.
Good to know. Thank you for the quick response!
what's unreliable about physx?
Specifically the OnCollisionEnter/Stay/Exit
They're very random it seems
and there's just a lot of features that I'd like to have
but dont
Compared to Unity Physics simulation, Havok Physics for Unity offers:
Better simulation performance: Havok Physics for Unity is a stateful engine, which means simulation time is over two times faster than Unity Physics in scenes that have a significant number of rigid bodies. This is due to automatic sleeping of inactive rigid bodies and other advanced caching techniques.
Higher simulation quality: Havok Physics for Unity is a mature engine which is robust to many use cases. In particular, it offers welding, a feature that allows for stable stacking and for smoothing out contact points when rigid bodies slide quickly over each other.
Deep profiling and debugging of physics simulations using the Havok Visual Debugger (only available on Windows). This industry leading tool can help you identify fine-grained, real-time multithreaded performance data that shows exactly where cycles are spent across all cores of the target system.
Right
But is that in its current state?
Because I'm pretty sure the package is only at around 0.1.2
there is no reason why a package can't do exactly that at version 0.1.2, its just a wrapper around the havok physics engine anyway
also you can read all that in the docs yourself
Anybody has a good knowledge resource or tutorial on ArticulationBody? I appreciate any help
One of the things I cannot figure out is why I cannot move an ArticulationBody
Is like something else is updating the position of the root object
the articulation body is probably updating its position. This is similar behavior to what you'd see with a character controller.
I haven't used articulation body in particular, so I can't give detailed advice, but I can make guesses based on the rest of the physics system if you have other specific issues
with character controller, if you want to move it using the transform component (ie warp its position instead of moving normally) you need to disable the CC or call Physics.SyncTransforms() after your move
otherwise the CC thinks the object is in a different place than the transform thinks it is, and the CC drives the transform's position so it just snaps back to where it was
Thanks, this is intended to be used with direct manipulation, e.g. the Player grabbing this chain in VR
why are you using articulation body instead of regular rbs + joints? What's your scenario?
because I have spent 1 week trying to make joints stable but they still explode
I was told to look into articulation body as they say are more stable
I have done an extensive research on joints and ways to stabilize them
but still on long complicated chains they break and explode
specially with direct manipulation, even if this manipulation happens in FixedUpdate
yeah, the problem with direction manipulation is that you move things outside of the normal constraints of the physics system
and it requires huge forces to fulfil the constraints in the physics system
if its possible at all
what's the chain for?
depending on what you need it to do, verlet integration might be a better way to go
something like this: https://github.com/GaryM-exkage/Verlet-Chain-Unity
Thanks, its not really for a chain but for a physics blendable soft sword simulation
does it need to push on things, or just be pushed by things?
both
okay, verlet might be hard then
So figured out the ArticulatedBody root can be moved with a physics joint
problem now is that I go back to my initial point of failure
which is that joint breaking because the Articulated Rig wont concede
Thus something has to give up and is the joint
I wonder if you disable Compute Parent Anchor and then set the anchor point to the position of the GO you're moving every fixed update if that'll be stable
I can try that
or... actually, I'm not sure that would do what I thought at first
you can try it, but I think it might just not move
yeah, I'm saying do it more like IK
the root AB (articulated body) doesnt have a parent anchor
have a target that you're trying to follow
it is being grabbed now with a joint
so you mean modifying the transform of the AB root on FixedUpate?
I can try that
I was saying have 2 objects. A target, and the AB root. in FixedUpdate you drive the AB root toward the target (not quite sure how--this is the part that wasn't thought out well)
but you only manipulate the target directly. The physics system does everything that moves the AB root
yeah, setting the transform on an AB root would do nothing as it is being overwritten by the AB itself as you said
not sure how to drive it
just tested it
I guess that is what a Fixed joint would do
but fixed joint breaks
can you screenshot your root AB inspector?
Ignore the Follow Script, this is what I just tested but doesnt work
I have been trying to find ways to stabilize Joints, one of my attempts was to clamp the position of the bodies on Fixed Update, this seems to work but as pointed out by someone it can lead in sometimes the objects hitting other colliders with massive forces
okay, crazy idea. You have a root AB that is fixed at a specific place in the world (immovable), and this object becomes the first child of that. You use X/Y/Z Drive to move its position, give it another child that has a sphere joint to do rotation
immovable (root) > position > rotation > your current chain
all of them ABs?
yeah
wont work
Abs are aware of the hierarchy
so the root will become the immovable
but what I can try
is that but the child 0 would be driving position and child 1 will work as a hinge
no, you move the position AB using a prismatic joint
I guess you might need 3
and you'd be moving it like it was a motor. So you'd have to feed forces into it rather than a position
this would not be a simple system
but it is a lot closer to how AB are supposed to be used
That could be very difficult if I want to match the exact position of the VR Hand by just using forces
I think I could automate a rocket landing if I could figure that one
yeah, its a classic controls problem. Big thing in mechanical engineering
even harder, It is like automating a ship landing in a comet x)
match the velocity of the moving hand with forces at all times
yeah, I don't think AB are going to make your life easier for this problem. They're designed to better simulate real world physics, but moving the root outside of unity's physics simulation is an inherently non-physical situation.
yeah I see that
but looking at it now I have 1 joint that breaks rather than having a rig of joints that could fail
if I find a way to stabilize this joint
any guess on stabilization?
I can try clamping the position again
I'm not sure... trying to detect when the joint has broken and trying to calm the simulation down in that case might be what I'd try
like... if the velocity exceeds some threshold, turn off all the ABs, reposition everything, turn them on, then call Physics.SyncTransforms
yeah I have tried that, zeroing all forces and reseting the position
will try that again
Thanks a lot for the help
it is!
Im getting this weird error
A joint can't connect the body to itself.
When removing the connectedArticulationBody from the joint by code
_joint.connectedArticulationBody = null;
Not sure why it is complaining
why does this hinge component go beyond its limits?
not only that it starts in this position
Hi, so I want to make a 2d swinging mechanism on ropes, but I don't really have a clue how. When the player is near a block that has the layer on it like an ID, it will launch a grappling hook onto it. So it's not just where the player wants randomly in the air but on a specific thing.
Anyone know how to correct this hinge joint behaviour?
It should be rotating between -90 and 0
If I disable preprocessing nothing happens, enabling collision has no effect either
Freezing everything apart from the Z axis causes the correct rotation but it does the same thing in the center of where it should be
Looks like you need an exorcist
I remade it and now it just doesn't move 😦
If you are trying to make door opening just make an animation and play it on a click
anybody around? how would you create a shopping cart driven by a ragdoll?
hey guys im very very very new to unity and i was trying to make a rigidbody and it gave me this error
can someone tell me why it says this and how i can fix it
It tells you exactly what the problem is and how to fix it. Use google for words you don’t understand
ok
When a Raycast is fired from Update, is it still calculated in FixedUpdate/Fixed Timestep?
Theres no way Raycast is called in update, executed on fixedupdate and the result of the raycast is then processed on the same update function (so its calculated instantly on update, not in fixedupdate). I dont know how frequently collider positions are updated tho
Is there any limit to torque added by AddTorque();
no i didn't mean angular velocity limit
i meant torque limit
i described the problem in more detail in #💻┃code-beginner
check my messages there
Im making a punching bag (2d)
The bag consists of the bag itself, a chain connected to the bag as well as the plank connected to a wall (see picture)
How can I make it so the bag and chain react to punches on the bag while simultaneously making them all look connected to each other?
Hey, currently I have this as my player movement script
body.velocity = new Vector2(Input.GetAxis("Horizontal") * Speed, body.velocity.y);
And I have a material on my RigidBody2D that is set to 0 friction when touching a wall. I can confirm this when I look at the Material in the inspector. However, my character sticks to walls when I hold d towards a wall on the right or a for a wall on the left, regardless of this. What am I doing wrong here?
what about the material on the wall?
in 2D friction is always averaged between the two objects
Short answer is: with Joints
hi can someone please tell me why I cant I disable the rigidbody component
How to create a magnet like effect when an object is near to the magnet
I would say add force on sphere overlap
Thanks bro
Hey how do I make that BoxCollider2D detects collision but when object rides into it, it won't affect it, only detect collision and not slowing object ?
Sounds like you just want to tick "Is Trigger" on the collider?
yea
and also
i am using in other object trigger
and it triggers other function
when I am using ontrigger
so how to separate them
and
how to make collider doesn't affect speed of object, collision
like a ghost collision
You'll get collision/trigger events on anything with a Rigidbody, so remove the RB from the object you dont want the events on
Maybe I'm misunderstanding you, the second part just sounds like a Trigger again
hm
I will try
Oh instead of having interaction script on object, i had it on car bruuh
yay it works now
thank
you
how does one make a bounding box to hold numerous flying objects within it
i am trying to see if i can confine a boid simulation within a transparent cuboid
*translucent
Hey people. Rigid body setup does collide with colliders, but never registers OnCollisionEnter. Any help?
For what reasons would my physicsMaterial2D NOT be affecting the rigidbody2D I put it on??
like the paramaters just do nothing when updated in the script
on start if the bounciness is set to 1, the rigidbody will bounce
however if something in the script sets it to 0, and I can see in the inspector that this works, it just wont affect the rigidbody
and no matter what, friction just won't affect the rigidbody.
actually, just set the friction to always be 0 and it works. however when I try to change it in a script, it changes the material but no longer affects the rigidbody properly. (it seems to be setting to default parameters, as the friction lets me stick to walls and I don't bounce anymore.)
I did a bit more testing, if I set the friction to always be the same, it works fine. if I change the bounciness in a script, it stops working but friction still stays whatever it is constantly set at. Vice versa for changing friction, bounciness still works fine.
Apparently this is a bug that has been around for 7 YEARS?
what
the fuck
I swear this should be used often enough that every single person has to have found out about it
what the heck
unreal is better 💪
Unreal2d? 😂
unreal is better 💪
@glass nexus Don't spam the channel.
@pearl crater Make sure you are accessing the correct referenced object and it's not a cloned property issue.
I definitely am, I'm dragging it in editor.
apparently you cant change physicsMaterial2D properties during runtime
When you accessing it in the script
or you can change them, but not apply them
I'm making a public PhysicsMaterial2D and then dragging and dropping it in in-editor
You probably mixed up about struct properties. Entire struct object has to be initialized to assign
When you change struct property on the object you don't actually change it on the object
Same thing when you need to access position. Transform.position.x is a struct property, assigning it won't do anything unless you create new Vector3 to swap
so how would I initialize a PhysicsMaterial2D properly??
@pearl crater have you tried disabling and enabling the collider adter changing the friction?
I can't do that, it would screw up a lot of other code.
How so?
Doesn't look like it's a struct issue, likely you have some mix up with the reference, or physics object indeed has to be refreshed somehow.
@pearl crater Just tested it. Doesn't matter code or in the inspector Collider2D holds on to the previous instance of the physics material and it doesn't trigger refresh until you toggle off/on the collider
alr. I figured it out though anyways, thank you
Same thing in 3d btw. So it's an expected behavior.
I haven't tested if the same happens if you assign the same material again.
It might trigger object update properly
is there an efficient way to make a custom physics system without iterating over literally every other object
Why you need custom physics engine?
Are all of the objects dynamic or do you have static colliders too?
not interested in all of the features of unity's one + better understanding an control
technically all objects are dynamic but not all of them actually move
what i mean is that my moving platforms are made of the same stuff as my walls atm
There are all kinds of optimizations that go into physics engines. I can only recommend doing a lot of reading/studying existing engines to gain an understanding
I think some sort of aabb tree could work for dynamic objects too
oh yeah, i should have mentioned that its aabb only
With binary tree type of approach you could probably repeatedly split the scene into smaller pieces (aabbs) so you dont need to iterate through all the objects
The more physics objects you have there, the less likely you are to get any gains over builtin physx. Also would suggest looking into contact modifications on unity 2021 lts if needing bit more control.. And actually understanding how physics engines work so one can design systems that work nicely
@odd bear ^
If you still need more control, there are bullet physics wrappers for unity with full source access.. And dots version aka unity physics that ships with full c# source code and lots of physics solver stages you can manually adjust/spoof out of the box
DOTS physics use ECS though so that is not for everyone or every use case
Just trying to say that there are alernatives to just doing same thing from scratch - unless the whole point is to just learn how to build these things
In majority of cases doing your own physics engine is just overkill and is likely to be way slower
hello, i'm not sure if this is the right channel, but i have a game idea (related to physics), where you can go around the maps to change physics constants and equations
maybe to solve puzzles
but 100% of physics is just too hard, so i think ill make the part that affects movement
not all the ones that affect movement, so no temperature etc, unless someone wants to give that a try
Hey, trying to use .FBX file that I have exported from Blender, but when I'm trying to use the Rigidbody component, it says
Non-convex MeshCollider with non-kinematic Rigidbody is no longer supported since Unity 5.```
Any help?
That means you cant use dynamic non convex mesh colliders
Ok, so what can I do about it?
Depends on the mesh, its very common to make the collider out of multiple primitive colliders (aka compound collider) like box, sphere and capsule colliders
how do i make a standing ragdoll?
Its possible to have multiple Fixed Update methods for physics? For example far objects have 30 tics per second and close objects have 60 tics per second.
you can do something like this (code below), but physics will always run at the globally defined update rate, usually you'd disable physics entirely for distant objects and maybe use kinematic interpolation.
long _fixedFrame;
float nextSlowUpdate;
private void SlowFixedUpdate(float dt) {
}
private voud FixedUpdate(){
if (_fixedFrame % 2 == 0)
SlowFixedUpdate(Time.fixedDeltaTime * 0.5f);
}
private voud FixedUpdate(){
if (nextSlowUpdate <= Time.fixedTime)
{
SlowFixedUpdate(slowInterval);
nextSlowUpdate = Time.fixedTime + slowInterval;
}
}
I did something like that and Its apparently making far objects fall slower.
if you apply your forces in that kind of slow update you apply less force but the sim still runs at the speed
you gain close to nothing by doing that
I see.
The friction force is calculated using the force pushing an object into the surface right?
Like gravity pushes the player into the ground so that force is used to add friction (multiplied by the coefficient from the physics material)
or does unity/physx do it differently
Friction uses the coulomb friction model, which is based around the concepts of 2 coefficients: the static friction coefficient and the dynamic friction coefficient (sometimes called kinetic friction). Friction resists relative lateral motion of two solid surfaces in contact. These two coefficients define a relationship between the normal force exerted by each surface on the other and the amount of friction force that is applied to resist lateral motion. Static friction defines the amount of friction that is applied between surfaces that are not moving lateral to each-other. Dynamic friction defines the amount of friction applied between surfaces that are moving relative to each-other.
looks like it does it the way you described (more or less)
help? how do i make a 3d ragdoll stand?
It's based on the normal force, yes
Is there a way to make a rope kind swing after the player jumps on it or starts to climb? I'm using a 2d hinge joint rope. If anyone needs code or to see how the rope is setup I can send screenshots, much appreciated!
If you could have a look at this question it would be greatly appreciated https://forum.unity.com/threads/attach-kinematic-collider-to-non-kinematic-collider.1285772/ dont want to just copy and paste the contents cause its long.
hmm you can, add animator/humanoid avatar, or active ragdoll via scripting, or add Hinge Joints at the bottom of the legs connected to shins
well will it still be interactable with animations?
when i tested it, its kind of janky and returns to the animation pretty quickly
you are looking to create active ragdolls with configurable joints
How i can create collision between cloth with mesh collider object ?. In documentation cloth only work for sphere and capsule collider.
I followed this tutorial https://www.youtube.com/watch?v=p8e4Kpl9b28 to make a trajectory line for my game (a 3d version of castle crusher). In the video he used obstacles that didn't have rigidbodies, but my game has rigidbodies and they keep flying all over the place when I run the game. If I create a physics scene
_simulationScene = SceneManager.CreateScene("Simulation", new CreateSceneParameters(LocalPhysicsMode.Physics3D));
can the objects in the physics scene interact with my normal scene?
The blue dots are the trajectory path. The first screenshot is before I press play, then second is after a second or two.
Hi, how would I be able to reset my articulation body to a previous state ? I have something that stores position, rotation etc and replaces it at runtime but it doesn't move
They cannot interact. You can read about it here https://docs.unity3d.com/Manual/physics-multi-scene.html
Thanks. Back to the drawing board to figure out why this is happening then.
Are you sure you're properly spawning objects that shouldn't interact in the other scene?
public void CreatePhysicsScene(GameObject ballPrefab)
{
_ghostProjectile = Instantiate(ballPrefab);
_ghostProjectile.GetComponent<Renderer>().enabled = false;
_simulationScene = SceneManager.CreateScene("Simulation", new CreateSceneParameters(LocalPhysicsMode.Physics3D));
_physicsScene = _simulationScene.GetPhysicsScene();
SceneManager.MoveGameObjectToScene(_ghostProjectile.gameObject, _simulationScene);
foreach (Transform obj in _obstaclesParent)
{
var ghostObj = Instantiate(obj.gameObject, obj.position, obj.rotation);
ghostObj.GetComponent<Renderer>().enabled = false;
SceneManager.MoveGameObjectToScene(ghostObj, _simulationScene);
if (!ghostObj.isStatic) _spawnedObjects.Add(obj, ghostObj.transform);
if (ghostObj.TryGetComponent(out Destructable destructable)) Destroy(destructable);
}
}
This is pretty much straight from the tutorial, although I changed it so it doesn't instantiate the ball fresh every time so a few lines are different.
I've just noticed there is one wall (an empty object with several of those pillars as children) that pops up when I run the game. I don't understand why there would be just this one object that is being put in the world while all the others are going in the simulation scene.
Got it! So it was throwing an error that I have been ignoring, but now I realize that it was important. Some objects don't have a renderer, so where I was doing .enabled = false it would error out of the function and the part where it was moved to the physics scene wasn't running.
Yeah it's never good to ignore errors.
Also instead of manually moving the objects to the other scene you can set the other scene as the active scene. Then Instantiate will put them directly in that scene
So like in this method you could do this:
_simulationScene = SceneManager.CreateScene("Simulation", new CreateSceneParameters(LocalPhysicsMode.Physics3D));
Scene oldScene = SceneManager.GetActiveScene();
SceneManager.SetActiveScene(simulationScene);
// the rest of the code here with all the Instantiates
SceneManager.SetActiveScene(oldScene);```
Then you wouldn't need any of the SceneManager.MoveGameObjectToScene stuff
Just a thought 😛
I'm having some trouble with my springjoint. It's bouncing me away from the object even though i have minimum distance set to 0, why would this be happening?
Anyone have any experience with Physics.OverlapBox?
Cant get the boxes to rotate, the red is boxes marking themselves as colliding with that block, the transform is slowly rotating and im setting the rotation of the collider to that rotation:
Collider[] hitColliders = Physics.OverlapBox(castCenter, castSize/ 2, transform.rotation, groundCollisionMask.value);
Why I cant use Non Kinematic Rigidbody with custom Mesh?
Most likely because it would be quite bad for performance. If you set it convex, it works tho
Man Unity devs have good taste of humour, maybe lets decide ppl if you want it enabled or disabled instead of forcing it off.
I decide of performance of my game.
No, they dont have taste of humour. They decided to upgrade their physics engine to newer and more performant version for unity 5 https://blog.unity.com/technology/high-performance-physics-in-unity-5. One limitation of that newer version is that it doesnt support dynamic concave colliders anymore, I think its worth trade-off tho. You can always make your colliders out of multiple primitive and convex colliders so you can do the same but with less overhead
Why do I have different rigidbody behavior when I have selected something else in hierarchy?
Exactly this. https://answers.unity.com/questions/1728313/hierarchy-selection-impacts-game-behavior-why-woul.html
But when I have the object selected it works fine. When I have something else selected. It goes crazy.
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
Your code is probably framerate dependent.
I did not download your mystery file
I might do that. Thanks for your help!
@timid dove Maybe this will now work. https://youtu.be/islv2MqUbhg
Simply. When I have opened the object with scripts in inspector everything works as intended. But when it is not selected in inspector it just get broken. Idk what framerate dependent means?
As I mendtioned your code is framerate dependent
meaning it does different things whent he framerate is different
the behavior depends on the framerate
If you share your code I might be able to help diagnose why
Yea, I tried googling that, but didn't found a help.
Can I send the code to your DM?
note that having a Rigidbody inspector open is known to have a large effect on framerate which explains the inspector thing.
no
post it here
#854851968446365696 see the code posting part
you're almost definitely inappropriately factoring Time.deltaTime into an AddForce or setting velocity.
Emm.. it's way to big to be posted here it jumps into a *.txt file
so you didn't read #854851968446365696 then
You're calling _rigidbody.AddForce(jumpForce * Vector2.up); in Update
when your framerate is faster that will happen more times
so the jump will be higher
physics stuff like this needs to go in FixedUpdate
Okay. I hope i will manage to fixed it. Thanks. And sorry for me being stupid
yep, thanks that was easy. Still learning. Sorry
What is the most performant way to get the velocity of an object in it's local transform?
I am using the velocity for my characters animator and need to use the velocity using the local directions otherwise the characters animations only match on when the rotation is 0
You can do space transformation from world to local space. That would be Transform.InverseTransformDirection(directionVector)
I'll try it thanks
I have encountered a weird problem, i have a script where i set my velocity of my rigidbody and also log the rigidbody it's velocity this all seems to actually update but for some reason my character is just staying in place
animations and stuff all update but the character never moves even tho it's velocity is like 5 m/s
Only the rotation is frozen
it does fall slowly (because i always set Y to 0) but it never wants to move forward or sideways
I have no clue why this is happening
private void FixedUpdate()
{
//velocity = body.velocity;
Vector3 localVelocity = transform.InverseTransformDirection(velocity);
anim.SetFloat("velocityX", localVelocity.x);
anim.SetFloat("velocityZ", localVelocity.z);
Vector3 desiredVelocity = new Vector3(playerInput.x, 0.0f, playerInput.y) * maxSpeed;
float maxSpeedChange = maxAcceleration * Time.fixedDeltaTime;
velocity.x = Mathf.MoveTowards(velocity.x, desiredVelocity.x, maxSpeedChange);
velocity.z = Mathf.MoveTowards(velocity.z, desiredVelocity.z, maxSpeedChange);
body.velocity = velocity;
Debug.Log("Updated velocity: " + velocity + "Actual body velocity: " + body.velocity);
}
This is the fixedupdate function other things i have is just the input in the update function and the rigidbody/animator in awake i fetch
It logs my value and all that but i just don't get why it's not moving forward/sideways or anything
the character does fall down because of the gravity that still works a little bit but i am stuck
I figured it out lol it was the root motion setting that was turned on
It took me a while tho i hope i never forget this mistake again
would I use quadratic equation if I need to predict where a rigid body will be when it gets launched in the air?
I'm trying to make a turret that can hit a moving target in the air
The kinematic equations are what you need
Parametric kinematic equations
would it be hard to implement?
The problem though is that discrete physics simulation like Unity's don't follow perfect parabolic paths
Depends if you're decent at algebra or not
I think using parabola you get super close tho (assuming theres no drag). Fixed timestep of 0.02 is still quite frequent
Why Joints even when everything is fixed seem to drag behind the object they are attached if that object is moving?
How is the moving object being moved?
on Fixed Updated trough script
I....have a performance concern with a game I'm working on. Can't go into detail about it, I'm under NDA, but
Hypothetically speaking
Is there any reason why an object in a scene should have both a 2D and a 3D collider on it?
My understanding is that this would be redundant at best and a performance problem at worst
Hey I'm having a huge issue with trying to make a flail. For the most part it works, but once you start moving the handle around the chain starts going crazy. I'm using configurable joints with limited angle, and using position drive to keep the links together (I tried setting position to locked but it doesn't even work hanging regular)
Light objects have issue following heavier objects they are FixedJoint'ed to
Thanks, is this a bug on a specific version? Should I report this?
I also have that problem, not sure if is a bug on Unity. As a workaround I have a script that every update clamps the position of each link relatively to each other so they dont explode
It seems a bug since we should not need an extra script to do what a joint is supposed to do
No this is a common issue in physics engines because the way joints work
Thanks I will try this
i made a cube with rigidbody to make a physics object so i can push around stuff. i get an error about non convex geometry and not supported since unity 5 but now that its convex its shaking everywhere on the floor
i can push it though which is good but how do i not make it shake around
Well, convex works… but why are you not using box collider?
im sorry im very very very new i dont know much about colliders and stuff
There are 3 different ”primitive” colliders in unity: box collider, sphere collider and capsule collider. You should use the primitive colliders over mesh colliders whenever possible as those are faster to calculate
ok thank you
Hello, why physic joints work well when the camera is looking at them but they break as soon as they are no longer in the camera view?
Anyone know if there's a premade tool/library for splitting a complex concave mesh into approximate compound colliders? Crucially, I need to find something that can be used during gameplay, we cannot do the work manually, we're dealing with UGC so there's no way to predict what meshes the player might end up making.
I'm trying to put the centerOfMass below the WheelColliders but every time I do it makes the wheels all "soft" and turn into the turns, rather than away like it would realistically. Thoughts?
OH WAIT NVM. I completely forgot ForceAppPointDistance exists lmao 💀
Does anybody have any experience with this issue?
i have a rigidbody cube standing on a platform with 0 drag, 0 friction and gravity enabled. it is pushed by this script https://gdl.space/atuxuvileb.cpp. now what happens is it stops shortly after the push because of gravity (i think). i need to know the distance it travels. it kinda messes up with my mind like do we need s = vt in a case like this or gravity and velocity is enough? explain where i'm wrong
do both the platform and the object itself have 0 friction? Is the physics material with 0 friction applied to both the rigidbody and collider of each?
It should not stop when sliding on a horizontal platform with no friction or drag.
I have this but everytime i press play, the cube falls down extremely fast, could it be the scaling with the mass? putting the mass to 0.0005 doesn't change anything
it is the scaling that makes it seem like it is falling quickly. It is falling at the same rate as any other object would (accelerating 9.8 m/s/s), but compared to its size that is a long distance.
We work in AR and putting normal size would make it extremely big, how can i change that?
in the physics settings (Edit > Project Settings > Physics I think) you can change the default gravity value. You can also change the camera settings to make things appear bigger or smaller. I haven't worked in AR before, but you should still be able to work with camera settings to get the size right instead of needing to scale it
We changed physics and it worked, but couldn't make it work with changing the camera settings. I guess i'm giong to try with changed physics on the phone and then come back if anything isn't working out yet, thanks for the advice!
Aight it kinda worked, but after implementing a jump, it falls with high speed again 🥲
Can I get some assistance with this?
Issue seems to come from angular limits on the joint if I set all limits to 0 then everything works fine (even still has some springiness, oddly)
I would still like to use the angular limits, and solutions?
Any unity developer who has experience in following game mechanic
https://www.zwodnik.com/app/android/dragon-fly-free/
plz dm me. I will pay for correct help.
Hello, it seems OnCollisionEnter(Collision other) does not gets called when the other collider is a CharacterController. Any idea on how to detect a collision with a Character Controller?
Hi!
I'm not quite sure if that's the right place to ask, but I'm currently working on an outer space game with a huge galaxy (Was thinking of 1 unity unit = ~100-1000 metres). My plan was to move the "galaxy" around the, through a rigidbody controlled spaceship and not the spaceship itself, due to floating point precision limitation.
My question would now be, if it is somehow possible to prevent the rigidbody from applying the calculated position/rotation directly to the coordinate system and instead of that, writing it into a custom defined vector/quaternion which I can take for my own calculations? I hope it's understandable what I'm trying to achieve 😄
Thanks in advance!
Is circle collider or box collider better for a custom 2d character controller?
You could create a physics scene and handle your collisions there
You'd have to keep track of your colliders and objects yourself
Ah thanks for your advice! Didn't know that something like that in Unity exists. Will have a look into it.
neither is "better". it's up to you what you want. I think the point where it matters is following 🔽 , if you use circle, the character will fall and "bounce" from the wall and box would still stay on the surface and fall straight down if you move left little bit more. circle collider would also allow you to climb to higher platforms ⏬
thanks a lot
I want to do a trajectory, but when I use this formula the line is acting like there is way more power than there should be. I've copied and pasted formulas from a couple of places and it has the same effect every time.
return startPosition + (velocity * t) + 0.5f * Physics.gravity * (t * t);
Here is what it should look like compared to what it does:
The second image is what it should be.
there are 3 variables involved here: startPosition, velocity and t
Did you take their log while running the simulation/game ?
Looks like what I would expect.
Here's a bit broader view of the code.
public override void CalculateTrajectory(Vector3 startPosition, Vector3 velocity)
{
lineRenderer.positionCount = steps;
for (int i = 0; i < steps; i++)
{
lineRenderer.SetPosition(i, PointAtTime(i * interval, startPosition, velocity));
}
}
private Vector3 PointAtTime(float t, Vector3 startPosition, Vector3 velocity)
{
print("Start: " + startPosition + " velocity: " + velocity + " Time: " + t);
return startPosition + (velocity * t) + 0.5f * Physics.gravity * (t * t);* t;
}
This is called each update by another class.
interval and steps are class variables I set in the inspector.
interval is set to 0.2, steps is currently set to 50
does your rigidbody have drag = 0? If not, that equation is incorrect
The drag is 0, angular drag is 0.05. I tried changing angular drag to 0 and the projectile still falls a lot faster than the line.
These time steps look really big. Default fixed delta time is 0.02, not 0.2
Is mass relevant? A heavier object should have a different curve than a lighter one, but none of the stuff I looked at on this used mass anywhere.
Would the time steps mess with the curve shape?
no, good point. They shouldn't
mass is irrelevant as long as there is no drag/air resistance/friction
light object and heavy object should have the same curve
assuming your setting a starting velocity and not applying a starting force to it
Oh, I do use add force with impulse. How would that change the equation?
divide start velocity by mass and I think you'll get the right answer
Impulse = Force * time = mass * acceleration * time = mass * (change in velocity) * time
so change in velocity = impulse / (mass * time)
(though change in velocity has an implicit /time in it, so that part cancels out)
That was it. I didn't think about the fact that I'm using add force instead of setting velocity directly.
Does it make more sense to set velocity or add force when shooting a projectile, or are either method common?
it doesn't matter that much
it kind of depends on your game which I would prefer
if there are lots of different kinds of projectile and I want them to behave somewhat realistically (ie bouncing around and such) then I would probably set their masses individually and tune the force
but if I want fine control of how each one flies then I would set the velocity directly instead
if there is just one type of projectile I would probably choose to set the velocity because then the number I put in has more meaning to me
though if the mass of it is 1 then they will be the same anyway
lots of different factors to consider 🤷♂️
and its just not a big deal either way
cool, well thanks for the help, I'm working on my final project for a class and this was hanging me up.
no problem. good luck!
Not sure if this would be of use on your physics issue or not, but you could try playing with the physics configuration and tweaking the solver iteration counts, and experimenting with the mass of the objects in your chain. Low masses joined together along with higher masses, from my understanding, can contribute to instability.
I had similar problems with 2D hinge joints and making some adjustments helped a lot. Not sure if it will yield you good results, but worth toying around with.
Hello i have a question. I have a 2D Jump and Run game, when my GameObject jumps on an Oblique surface, he jumps twice as high as on a even ground and i dont know why. Does anyone know the reason for that?
Presumably there's a bug in your code, which nobody here has seen except you.
I m using the Character Controller 2D from brackeys
that doesn't do anything on its own
You need another script along with it
I was following the Tutorial of his YouTube Channel
The movement is working fine but on oblique edges my gameobject jumps Higher
so question, why when my bullet speed increases it does not hit properly anymore? i've already set the RB to Continuous and interpolate but it still does not registrate
Can anyone tell me why my Rigidbody won't wake up when I change focus? https://vimeo.com/manage/videos/717066509
Edit: Resolved it by adding the velocity on the rigidbody captured the frame before it was deactivated
How are you moving the bullet?
@timid dove
is TilemapCollider's optimization good?
I think it is. Atleast its a lot better than using lot of individual game objects
How about creating a custom collision system, that dynamically spawns colliders only on nearby tiles? Would that have better optimization?
or does getting all tiles and constantly switching colliders take more ram
Maybe, but id guess unity have optimized the tilemap to be about as fast as possible
The thing is, physics unity unity in general are pretty fast because the colliders are stored in an aabb tree kind of thing which makes it super fast to check collisions and id imagine tilemap optimizes that even further
ok
You can always use profiler to see if physics performance is a problem to begin with, id not bother making anything fancy unless thats really needed
Is it possible to set up a Mesh Collider to only receive raycast hits, but not be used for actual collision detection and physics?
Working on a UGC game, having massive performance issues with moderate-sized levels with lots of level objects. Each level object has a Mesh Collider on it for the sole purpose of being selectable with in-game level editing tools. But the physics system is still picking up these colliders and it just absolutely chugs the game to 0 FPS
Can't use Is Trigger because not all objects are convex
We've run out of Unity layers too so I can't create a special layer just for the mesh colliders
....what do I do?
can you split up the objects into smaller objects?
can you turn off or remove the colliders when level editing tools are not active?
Nope, while some level objects in the game are made by our artists, others are procedurally generated with smearable brushes (think, LittleBigPlanet)
And those smeared objects could be literally any shape
Convex or concave
that doesn't mean you cant split them up, just that its a little harder
I CAN turn off the colliders when level editing tools aren't active, theoretically. That being said, the performance issues are there even when editing the level, specifically when the level is unpaused.
We don't need 3D mesh colliders for actual physics either
We use 2D physics and Polygon Colliders for that.
The Mesh Colliders are just there as raycast hit targets, so you can click on objects in the level to select them for editing
The really weird thing is that, well, should mesh colliders even be considered by the 2D physics system?
I think running both the 3D and 2D physics systems in parallel is probably your problem
why can't you use the polygon colliders for selection?
Maybe. But I thought that only 2D colliders worked with 2D rigid bodies, and that only 3D colliders worked with 3D rigid bodies.
I'm...not exactly sure. My guess is the fact we're dealing with 2.5D here
yes, but you have two different physics simulations running
so, a level object can be behind another one
Hmmmmm
this might actually solve the problem
I should risk breaking my NDA more often 😛
Thanks y'all!
Only concern I have is, that second method seems to be hitting objects in the background first, rather than objects in the foreground
camera is at z = -10 by default. Are you casting from the correct direction?
I'm using Camera.ScreenPointToRay()
to generate the ray from the position of the mouse cursor on-screen
🤷♂️ I dunno.. play with it
Yes just put those colliders in a layer that collides with nothing.
Using the layer collision matrix
What did you use all your layers for? You can probably reclaim some other layers by redesigning something else in the game
Hello, i was wondering if anyone knows a good starting point for bicycle physics / motorcycle physics?
I have had some interest in bicycle physics since it's just a fun thing to do, but don't really have an idea how to get started.
The things i am wondering about is how best to do the wheels for example, wheel colliders don't seem suitable to me.
Are there any resources maybe that talk about implementing such physics in games that are easily applicable in Unity?
Is there an equivalent of RaycastHit.textureCoord but for RaycastHit2D?
There are some scenarios in this game's level editor where we still need to do 3D raycasts. I won't go into detail because NDA. But it's still something I need to do.
So my question now is... for these edge cases, could I theoretically do an initial Physics2D.GetRayIntersection() to find the object I want to edit, and then, when I do, attach a temporary MeshCollider to that one object that's set as "Is Trigger?"
Because then I could do a second raycast to that exact same object- but get all of the extra information you get froma 3D raycast hit.
My question about this is... how expensive is this to do?
No idea. If attaching a new collider is prohibitively expensive, I expect enabling the colliders when needed would be faster than attaching them and I assume disabled colliders have very low overhead. Just doing a 2nd raycast should be fine.
You might need to sync physics after attaching the collider for it to register properly. If you're doing that every frame it's probably bad, but once in a while is likely okay.
I decided on just enabling/disabling them as needed
Is there a way to locate all Rigidbody2Ds that are set to Continuous?
my FPS is tanking again and 60% of CPU time is spent on SolveContinuousIslandTask
I dont think thats possible because RaycastHit.tectureCoord works only for mesh colliders and mesh colliders doesnt exist on 2d
really basic problem here
but
uh
ball not bouncing
bounciness of material is 1
this is my floor
nvm
I have an object with a Mesh Collider on it. In my code I have an OnCollisionEnter working correctly for it.
But physics is also being applied for these collisions, which I don't want.
Is Trigger is greyed out on the Mesh Collider as you can see. If I check Convex, then I can check Is Trigger, but then no collisions are registered and OnCollisionEnter is never called.
Basically, does anyone know how to make a Mesh Collider not interact with physics, but register collisions?
change it from on collision enter to ontriggerenter
because you have the script saying collision it removes the option for is trigger
triggers cant collide
Commented out the code entirely, still greyed unfortunately
you need to mark it convex, mark it as a trigger, and change OnCollisionEnter to OnTriggerEnter
I think I tried this and it just stopped registering collisions - ultimately changed it to 2 box colliders which worked, less precise but a lot better for performance and I can sacrifice the detail in this case
OnCollisionEnter doesn't work with triggers
Triggers don't work unless it's Convex.
If you don't want physics for the collision you need a trigger
if you need a trigger you need Convex or to build the collider out of primitives.
Is this the right place to talk about maths ? (Rotation matrix for example)
@civic marsh Its fine whats the question
Alright, should have asked the question first.
I'm still a beginner in linear algebra and I'd like to know how I could "estimate" this rotation matrix.
It's the Approach #1 : https://stackoverflow.com/a/53559963
@civic marsh So you want to have this rotation matrix
And then you wanna do the check as if the box was axis aligned?
Exactly, apply the matrix to the point in order to check if it's in the box
as if it's aa
I think the confusing part here is how to use the rotation matrix to have the point in the cubes local coordinate system
R' * p
should be the point in cube space I think
Where R' is the inverse of this rotation matrix
@civic marsh
Isn't multiplying R by p enough ?
It might be just
R * p yeah
Alright, where my problem lies is in finding the rotation matrix
I don't know how to get it, the columns are the locals ok, but the rest of it is a mystery to me
its no big deal
its literally like this
ill make this simple for you
first column is transform.right
second is transform.up
third is transform.forward
you dont need the a,b,c,d's
its literally the local right,up,forward
in world space
what you get from transform.up,right,forward
Alright, what do I fill the rest of the rotation matrix with ?
oh wait
you also gotta scale it with transform scale
instead of using transform.right
you can use transform.right * transform.scale.x
or this:
transform.right * transform.scale.x * 0.5f
also do for y and z of course
and that'll be your rotation matrix
3x3
what do you mean rest of the matrix?
3 vectors already fill the matrix
I'll get back to you in a bit, sorry
Oh I see I'm dumb, the components of the 3 vectors are placed vertically in the matrix
yeah
Hey guys, I'm trying to make a robot that uses physics, what I mean is I want it to move but also be physically influenced by hits/movement/damage
So far I have it working great moving forward using
rb.transform.position = Vector3.Lerp(transform.position, transform.position + -transform.right * 0.1f, Time.deltaTime * 2);```
(my model has a wrong transform so ignore the weird transform directions)
What i'm trying to figure out is how to lerp the rotation as well, i've tried stuff like
```cs
rb.transform.rotation = Quaternion.Lerp(rb.transform.rotation, Quaternion.Eueler(rb.transform.rotation.x, rb.transform.rotation.y + 1, rb.transform.rotation.z), time.deltaTime * 2);
And it's just not working great, any advice on physical (rigidbody) rotation or just physical enemy movement in general?
Okay I got some rotation working with this code
rb.transform.rotation = Quaternion.RotateTowards(rb.transform.rotation,
Quaternion.Euler(rb.transform.rotation.x, rb.transform.rotation.y + 1, rb.transform.rotation.z), Time.deltaTime * 12);
but the issue is it doesn't actually increment the Y value, it just goes to 0, I was expecting it to keep incrementing
transform.rotation.x/y/z are not euler angles. They are quaternion values. If you want euler angles, use transform.eulerAngles
also, setting the rotation and position of an object directly like this will break physics on the object. You're overriding any changes the rigidbody might try to make to the object. If that's what you want, that's fine, but since you posted in #⚛️┃physics I'm assuming its not what you were hoping for
Long story short, I'm using VR, and I'm applying these changes in fixedupdate so (somehow) it's working really smoothly. I think it's because I'm altering the rigidbody values as opposed to the transform values. I'm not sure. The goal is to have robots I can pick up and mess around with that are still trying to "navigate" so to speak.
I'll try with euler angles, thanks for your help!
That worked perfectly, @jovial wraith , here's the line specifically
rb.transform.eulerAngles = Vector3.Lerp(rb.transform.eulerAngles, new Vector3(rb.transform.eulerAngles.x, rb.transform.eulerAngles.y + 1, rb.transform.eulerAngles.z), Time.deltaTime * 16);```
Many thanks!
Hey guys! I really need help, I can't advance my project with this feature for like 14 days now, I just can't figure it out. I have to get to know, if there is a specific tagged object between 2 positions (2D)
I tried raycasts, but they dont seem to work the way they are supposed to. I rly need help pls.
Simplified:
rb.transform.rotation = Quaternion.Slerp(rb.transform.rotation, rb.transform.rotation * Quaternion.Euler(0, 1, 0), 16 * Time.deltaTime);```
But that's a very weird usage of Lerp/Slerp
It's for a robot that's more or less a roomba
If you do something like:
rb.transform.rotation *= Quaternion.Euler(0, 16 * Time.deltaTime, 0);``` I think you'll get a similar result that's easier to understand (rotating by 16 degrees per second on the y axis)
I don't think Lerp is going to add anything of value here, the way you are using it.
It will not create a smoothing effect for example
Ah yeah I see what you're saying, because it's just incrementing itself already
Good point!!
Do physics calculations (collisions and triggers) on nested colliders not work when building using the Dedicated Server option?
Essentially what I need to know is why a convex mesh collider wouldn't detect collisions just because there's no camera.
Well this one popped up earlier today:
Raycasts should be good to solve this problem yeah. Though you provided details, it's not enough to help you.
Show what you tried and where it does not work
Yea, so I cannot imagine what might be the problem, i used separate layers for raycasts and the raycasts just didnt find anything, i also had colliders on them
also if i raycast it with a click, then its ok, but if i want to raycast between 2 points in 2D then i cannot find anything 😦
Hard to help you because you dont know yet what you don't know yet ^^ and we don't see what you don't show ^^
Though from what you said I could try a guess : are you sure you're using the 2D variant ? Physics2D.Raycast and not just Physics.Raycast ?
That could explain why it works from camera
what is Rigidbody.GetRelativePointVelocity(Vector3 relativePoint) ?
I understand GetPointVelocity as this : if the rigidbody only has linear velocity, the function will return the same value as rigidbody.velocity. But if it is rotating, then it will consider angularVelocity as well. In which case a point farther from the centre of mass will have a higher value. But i don't understand what GetRelativePointVelocity. Even in the documention, the explaination isn't clear and the example actually doesn't use GetRelativePointVelocity but instead uses GetPointVelocity(transform.TransformPoint(localPoint)). So i thought they are both same but they are giving different values. Can someone explain with an example what it is.
I'm pretty sure you can think of it as roughly this:
Vector3 GetRelativePointVelocity(Vector3 relativePoint) {
Vector3 worldPoint = transform.TransformPoint(relativePoint);
Vector3 worldVel = rb.GetPointVelocity(worldPoint);
return transform.InverseTransformVector(worldVel);
}```
basically - you put in a local position, and you get out the local velocity of that position
so like for a wheel - if you put Vector3.zero (the center of the wheel) you'll always get 0 out for the relative point velocity
but if you put a point on the outside of the wheel you'll get the velocity of that part of the wheel relative to the center - so it'll be a forward velocity at the top of the wheel, negative at the bottom
local velocity of a local point
I think that's what it does but maybe best to experiment a little to confirm
The documentation doesn't really specify if the output velocity is in local or world space
ok. that gives me a better idea. Thanks.
Yea, im sure I used 2D version, can u help me one on one after tomorrow sometime pls?
No sorry. Fell free to post here, anybody can help
I'm trying to use Physics.ComputePenetration(...) to create my own custom character controller. The function returns only a boolean for if we collided, a Vector3 for the direction to depenetrate our collider, and a distance to multiply that direction with
This works pretty well for discrete collision checks
but it comes with the limitation of not returning the position of where we actually collided, which is what I'm trying to figure out
Similarly to how, in OnCollisionEnter, you can call collider.GetContacts(0).point to find the point of the collision
You can check out my stack overflow post for more information on what I'm asking: https://stackoverflow.com/questions/72521999/get-point-of-collision-from-physics-computepenetration
Thank you in advance
Im a little confused about something. I have some models with rigid bodies on them and apply some torque. They don't seem to rotate around their center of mass. When I add a collider and edit it so the center matches the COM it looks like it takes that as the center of mass. However when I set the collider to trigger this effect dissapears and the COM is wrong again. 🤷♂️ What is the sensible/correct way to set the COM correctly for rigidbodies?
How can I get the red vector? I want to add force in that direction...
I'm trying to add that force to other GameObject, but in the direction of the red arrow...
Ok thanks alot @timid dove
Hey could someone help me with this?
I have two capsules with a charactercontroller on each.
My problem is that if the two capsules move into eachother one will "slide" above or below
how can i stop this from happening?
i was checking out rigidbody vs collider
so what's the point of only having a collider?
Read the other answer
- Raycasts and other physics queries
- Other objects with Rigidbodies collide with them
thanks!
how are rigidbody bounds defined?
does it just use the union of all the colliders on an object or something?
Rigidbodies don't have bounds
The shape of the body is indeed composed from all child Colliders
oh wow
Don't know if this is the right channel but, how would I go about rotating a rigidbody with the x axis of mouse input by using add torque?
The example in the documentation for AddTorque does literally exactly that.
https://docs.unity3d.com/ScriptReference/Rigidbody.AddTorque.html
changing the scale of an object preserves everything on it right? colliders, RBs, etc.?
Wdym by "preserves"?
say, if i had a collider/RB on this box
and then i dilated it by a factor of 2
the collider/RB would go along with the new shape
Yes, kind of
Colliders are trying their best to stretch to the new scale but primitive colliders can only change their parameters, the primitive shape will never change. For example, if you scale a sphere collider along one axis, the sphere will grow in radius but you cant get ellipsoid by scaling a sphere collider. If you scale a capsule collider, only the radius and height will change to match the new size.
How can I push rigidbodies with CharacterController? it seems that CharacterController annihilates rigidbody features
cannot even push a carrot
fine, I have decided to create children object with RB and collider and it seems working
CC + RB at the same time is asking for trouble
pick one or the other
no it does not cover the functionality i want from my player
not only move through CC but also affect the environment involving physics
I said under the picture that I've made a player object both CC and RB and it works fine
There's a solution for that. Example code here:
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnControllerColliderHit.html
If your RB is kinematic though you will at least not get a complete disaster movement wise
it's cool I didn't know it obviously
however I think making a script for pushing objects is little much work to do compared if you simply put RB into a child object
it will not push realistically the way you have it. More like just teleporting into where they are and they will be displaced away
but not a realistic push impulse
Has anyone had issues with Physics.Raycast not detecting when an object is removed, the hit data doesn't update. It works fine in Physics.Raycast2D
So cast a ray, it detects when the object appears, all good, but when that object disappears.
I guess i need a collider on the world edge
Thanks, sometimes typing out the problem helps. Thanks for listening
Ok, no that didn't work, but the 2D Physics works fine, come on Unity
Ok, seems the hit data stays until its replaced, different from 2D. So rather than check for any hit data, i'm now looking for certain layers. Works fine
If you move an object via the Transform, you will need to make sure to sync transform changes to the physics engine before doing physics queries if you want them to notice the change
That could be it
also yes if you are reusing a RaycastHit variable make sure you're not reading stale data
https://docs.unity3d.com/ScriptReference/Physics.SyncTransforms.html < To sync xform data to the physics engine
I'm using a layermask, so when the ray gets filtered out by that, the old data stays. I was looking for a flush ray data method, however, checking the layer of the collision object seems to work, as its no longer in the scene. Weird it works in 2D, regardless. Thanks for the SyncTransform method, it didn't solve it, but a useful thing to know about. Cheers
I find it rare to ever need to reuse a RaycastHit variable. But even if you do, Raycast will always clear it out
The only way that wouldn't happen is if you have some code path where Raycast is not called
Now the other possibility is you are not properly checking for whether the raycast hit anything or not
you should generally have a structure like:
if (Physics.Raycast(...out RaycastHit hit, ...)) {
// hit
}
else {
// miss
}```
Which is indeed different from 2D
I have that, i followed the docs
"flush ray data" doesn't really make sense
Right, i was thinking the same, this bug took me by surprise
However, if you run a test, that above if statement lets you in when the object is removed from the scene EDIT: my mistake here, without going into it, i was expecting the hit data to be cleared, the if statement does work, but the data doesn't clear
Thanks for your replies
i am using 2D physics for particle collision, but I need to be able to rotate the particle system in 3D space. if I rotate my system too perpendicular to the x/y plane, collisions will break. Is there some way I can create a localized 2D physics world that I can rotate in 3D space?
i want to use 2D physics so that I can use concave triggers to control how a particle behaves in a simulated material. here i'm just having the particles bounce off the collider, but I want to have particles slow down or diffuse through different materials represented by triggers. with 3D physics, i'd need to set up several convex triggers to conform to complex shapes
I have an object with a rigidbody where I am setting it's position using transform.position before using AddForce to it's rigidbody in the same frame. For some reason, seemingly randomly, the position wont update before the force is applied, causing the object to stay at it's original location and then moving forward due to the AddForce call. When I instead set the position using rigidbody.position, it works as expected, except I can see the object at it's old location for a split second, I'm assuming this is until the next physics step. When I use both transform.position and rigidbody.position in the same Update loop, it works as intended, moving to the new position and then applying the force. Anyone know why this is happening?
Gotta do this after moving the xform: https://docs.unity3d.com/ScriptReference/Physics.SyncTransforms.html
or do what you did - moving both manually to basically manually sync that one transform -> RB
this works, thanks so much
dunno where you guys learn this stuff from
experience
I realized the physics chat might be a better place for this... I'm having issues with my player clipping through terrain. I just made a basic terrain with a few hills, and when moving fast the player can clip through them and fall through the earth. I have a rigidbody on my player with Collision Detection set to Continuous, and a capsule collider. The terrain has a Terrain Collider, and I've tried adding a kinematic rigidbody to it with continuous collision detection as well, but the character can still pass through a hill and disappear.
I'm moving the player using rigidBody.MovePosition.. movement using addforce felt a little too slip and slide.
Use rigidbody.velocity then. MovePosition doesnt care of the collision detection mode, it works as if it is always discrete
Can anyone confirm or deny whether raycasts (in 2d physics) respect interpolated positions of rigidbodies? In particular, if a raycast shot towards the very corner of a collider on an interpolated rigidbody (using the interpolated position to determine where that corner is) could miss the collider, since the interpolated position of the corner is just slightly in a different position than the non-interpolated position in the physics simulation?
Trying to track down a bug. Stops happening when I turn off interpolation, so that's my best guess.
Well, I guess I should have just tried instead of asking. If anyone wants to know, answer is: yes, the raycast can miss if you use the interpolated position
Afaik interpolation only affects the position of transfrom and the visual appearance but doesnt do anything to physics (position of rb and colliders)
Hey, does anyone know how to make a prismatic joint ?
Someone help me 1 on 1 with screenshare with 2D raycasts pls 😦 I watched like all tutorials about it 😦
does anyone know if it's possible to create a compound collider in unity with trigger colliders instead of regular colliders? cant find anything on google. like this
-- parent (kinematic rigidbody)
-- child (box collider set to trigger)
-- child (box collider set to trigger)
-- child (box collider set to trigger)
documentation only mentions the use case of colliders with isTrigger = false
the problem is that i get multiple on trigger enters/exits, expect to only receive one?
found out that with a mesh collider like this, dents in mesh are not considered, meaning I cannot access cubes inside because they are overlayed with collider of the box. Can it be fixed?
Is the mesh collider set as convex?
Wut
okey it seems impossible for unity to create dented mesh colliders so I can use various shapes to build my collider afterall
Why isnt non convex an option? It needs to be dynamic?
Having some issues with a child model position, it slowly loses sync with the parent position. Has anyone dealt with this issue? I'm thinking i maybe need to run a worldspace check to align them again, its maybe down to the 32 bit floats for the position running out of decimals, so i'm getting quantisation errors, not sure
do you have a rigidbody on the child? If so, that's probably the problem. Rigidbodies are meant to move independently. Putting a kinematic rigidbody on the child would probably work fine, but I'm not sure what purpose it would serve. Just using a collider on the child and no rigidbody is probably what you want.
there is nothing on the child, just an animator
It goes - player -> model -> mixamo
The player has the Rigidboby + Box Collider and the movement script.
The model is just an empty Gameobject.
The Mixamo has the Animator on it
I think it has something todo with the Mixamo animation tbh, its slowly losing sync. Pain in the ass
when it comes to putting coliders on my hands which one do i chose
Ok, solved my issues by getting rid of all children, and packing everything onto one game object. Its way messier, but things stay in sync now. Not sure how larger projects get built
I have been working on the physisc following a video by valem tutorials HE has provided me a package that has these great models the issue is if you look in the bottom right the left hand prescense is broken this means i cant use any animations for the left hand any help
Newbie question regarding character joints. How to configure the swing axis? I mean, what does it mean exactly? if my character is in T Pose facing Z axis and I want to configure the left elbow joint which is aligned with X axis in T pose, what vector3 value should I use for the left elbow?
Does the swing means which axis will be used as rotation? Which means I'd need 0,1,0 since it'll rotate around Y axis ?
yes
It means you are rotating around that axis
Thats the save way with torque and angular velocity vectors as well
i also had a question about character joints! well, maybe character joints? im making a game with a frog character and procedural climbing. I wanted a add a tounge that had a active ragdoll look, but character joints were giving me a headache
is there a good way to get an elastic look with physics objects
Hello guys!
I was wondering if you have a clue how it would be possible to achieve so many rigidbodies in the scene for mobile? Is there a system or package for this?
https://play.google.com/store/apps/details?id=com.cinna.collectcubes&hl=en&gl=US
Suggestions for making my ball move more realisticly
First you have to tell what you have done so far and in what way its not ”realistic”
ive made a ball but when it rolls it loses its momentum to quickly
Have you tried changing the angular drag?
no but i have moved on to making a jump button so ill try that then continue on
how do i make active ragdolls?
ok so how do i fix this
Ok but from what I tried, this didn't work the way I was expecting. In the end, I just changed number until the red axis aligned with whatever 2 different angles I need while the swing only have 1 numbers for both sides.
Hey guys, new to unity here. I'm trying to do pixel perfect collisions for a pixel-art game using Kinematic Rigid Bodies. I'm having an issue where the purple-border square sprite there is colliding with the tilemap, despite them both having what I assume are perfectly configured Box Colliders of 32 pixels of length (or the tilemap equivalent of that). Why exactly is this? Should I tackle the colliders from a different approach for pixel perfect collisions?
Nevermind, figured out it's the default contact offset. I'm gonna have to make the colliders' length a pixel thinner or each side since I can't set the offset to 0
Can someone help me set up a 2D raycast and scan if an object is there please? 😦
Scan what? Where? Can you show what you have tried so far and what went wrong?
I can't wrap my head around raycasts. Why doesn't this work:
```csharp
var hit = Physics2D.Raycast(
templatePrefab.transform.position,
transform.TransformDirection(Vector2.down),
Mathf.Infinity,
LayerMask.NameToLayer("Ally")
);
if (hit.collider == null) ...
I'm trying to check if there is a GO with the Ally layer underneath the templatePrefab GameObject. The Ally and template GameObjects have a collider and RigidBody
Use Debug.DrawRay and Debug.DrawLine to figure out where the ray is going/what its hitting. Btw that whole transformdirection stuff is exactly same as -transform.up
Cool, thanks ^^ I'll try
Does Rigidbody2D.Cast put the RaycastHit2Ds in the results in any particular order? I would like to solve collision according to the first hit along the length of the ray, wondering if i have to do that sorting process myself
The thing is, that what I ve done, kindof broke the whole project and i didnt have a clue what, so i just went back to a working stage
I know that even tho I tried to raycast, I even tried to see it with DebugRaycast but I just couldnt find where it was raycasting from and to
it raycasted on a completely other position
I already got the Positions (from & to) for the raycast, It works when i have to spawn something, but when i tried to raycast from those positions, it just puts it on a completely bad position
You should show the code, its impossible to help if thats all we know
undocumented, but I would assume it's not in any particular order because similar things like RaycastAll don't have a guaranteed order either
Thanks 👍
It seems to naturally order them by fraction but as it's undocumented I guess it could be purely coincidental
I'm a bit confused as to whether or not I should have a kinematic rigidbody on my prefab, or if I should remove the rigidbody component all together, and just update the objects transform.position. I'm rendering thousands of objects in game which are based on real-world objects (position data obtained through an API), and thus I don't need the Unity physics engine to move these objects. However, I do need colliders on these objects in order to detect user interaction with the objects. When these objects move (based on the updated position from the API), should I update the position by doing transform.position = {new position}? Or should I attach a kinematic rigid body and use rigidbody.movePosition? Thanks!
Hello, I have a problem with physics. I've made a simple car model and tried to get some good and somewhat realistic physics for it, yet after I added the rigidbody, collider for the car itself and the wheel colliders, i've noticed that the car behaves rather strangely (as shown in the picture). To clarify, it's standing on a perfectly flat plane, and without even moving it, it just sways to one side or another. I'm not sure, but I think there's just something about physics I don't know. Any ideas why does this happen? Thanks in advance
Edit: I think I've found an answer, or at least a clue. It turns out that lowering the center of mass actually causes problems like this (the center of mass is moved only on the Y axis, so it's not off to the side).
you should use kinematic rigidbodies. If the object does not have a rigidbody but it does have colliders, the physics system assumes that it is a static object and moving it will cause performance issues and cause raycasts and such to be unreliable.
Moving static rigidbodies was issue prior to unity 5 😂, thats ”fixed” ages ago. I dont know about raycasts
I'm having a really weird issue with a ragdoll I made via the ragdoll wizard. Whenever the enemy dies, it spawns a ragdoll by instantiating the enemy model (which is just a ragdoll with the animator component turned on) and disabling the animator component on the ragdoll, as well as disabling the enemy model as well. However, it seems like over time, the enemy model's ragdoll becomes more inaccurate? It's hard to explain, so here's a video of it, and the relevant portions of code. Does anyone know if there's something wrong with this method of creating ragdolls?
if (curHealth <= 0 && isDead == false)
{
GameObject ragdoll = Instantiate(model, new Vector3(transform.position.x, transform.position.y, transform.position.z), transform.rotation);
ragdoll.GetComponent<Animator>().enabled = false;
ragdoll.AddComponent<SelfDelete>();
model.SetActive(false);
StartCoroutine("respawn");
}
...
IEnumerator respawn()
{
yield return new WaitForSeconds(respawnTime);
model.SetActive(true);
}
(Oddly enough, it seemed to work when I wasn't creating copies of the model, but I didn't exactly stress test that approach much)
@jovial wraith And by ”fixing” I mean its changed to work in a way you gain less by using static colliders but you dont get huge performance inpact every time you move them. Static colliders werent never really broken but people just didnt know how to use them properly and therefore caused a lot of performance issues, because of that unity decided to make this change to unity 5 and later versions
Anyone know what's wrong with my ContactFilter2D? It's filtering out the slope collision, and I made sure the layer name is correct. Am I not setting the object's layer correct or something? I'm just using the dropdown from the editor on the slope object.
ContactFilter2D filter = new ContactFilter2D();
mask = LayerMask.NameToLayer("Slope");
filter.SetLayerMask(mask);
int total = slopeCollider.Cast(frameVelocity, filter, castResults, frameVelocity.magnitude);
Hi. Could somebody help with veeeeery newbie basic stuff ? i've got a thing which is supposed to be a character and another supposed to be a plateform. The first one has a rigidbody 2d and the other one a box collider and although they're on the same layer order they don't collide.
Thanks
ah, I stand corrected. Thanks for the info! My comment about raycasts was because I assumed that moving the transform would cause the same kinds of issues as things that are fixed by Physics.SyncTransforms(). If unity is in fact updating collider positions with transform positions efficiently, then all my assumptions about implications are off.
does the one with a rigidbody have a collider? Is it kinematic, dynamic, or static? Is either one marked as a trigger collider? Is the box collider a BoxCollider2D?
LayerMask.NameToLayer returns the index of the layer, not the bitmask associated with that layer and no others. You should be using LayerMask.GetMask
does anyone know how to do layer collisions but in 2d?
exactly the same way you do it in 3d
say more. What specifically is not working?
nothing i just figured it out
Thanks.It's 2d collider and not triggered
Ok it's resolved and that was silly the one with the rigid body didnthave any collider
as a game grows do all colldier and bodies make performances problems ?
is there a way to use one collider for multiple objects for example
with a prefab or something ?
You have to say filter.useLayerMask = true
Also Yes it's GetMask
The reason its now faster is because (if I understood correctly) dynamic objects shares the same aabb tree with static objects (or atleast static uses similiar structure with dynamic) and moving static objects doesnt automatically trigger expensive aabb tree rebuild. It seems nowadays Physics.autoSyncTransforms is set false by default and shouldnt be set true which I understand means that when you move static object, the colliders and rigidbody will not update their positions until beginning of the next physics update. So I think you still need to call Physics.SyncTransforms if you want to use raycasts in update method before the next physics step.
Thank you!
Tried that but since I was using the wrong "layer getter" it never worked. Thanks!
Been trying to make a 3d snake skeleton out of joints and spheres like in Snake Pass. I can kind of get the slither effect to work, but it's a far cry from working the way I want it to haha
I have a Rigidbody gameobject with 2 hinges. One hinge connects to the chain link I made perfectly while the other separates the anchor and the connected anchor. Any clue how I can make sure they never separate?
Fixed it
does anyone have experience improving performance of vehicles / wheel colliders?
If i make my whole stage with mesh collider of the shape like these modular rocks, is it feasible?
Are mesh cols of these size (and just around ~300 vertx) as stage feasible, or definitely a no go and gotta rebuild it with primitives cols?
In this tutorial series, I cover the creation of modular rock assets from start to finish.
Learn a quick and easy workflow for creating beautiful, game-ready, modular rocks that can be used to create large cliff faces.
This 8 part tutorial series will take you through 3DS MAX, Zbrush and UE4
You will learn how to quickly block out your rock i...
Use profiler to figure that out. Because every collision check goes through the broad phase, most of the colliders will be ignored and only very few needs to be checked triangle by triangle. I have heard that mesh colliders can increase startup times drastically but im not sure if thats true anymore these days.
Question, how do i prevent my tree's trunk from swaying?
Hello
I hope I'm asking in proper channel, my question is: if one material has friction combine "average" and the other one has friction combine selected "multiply" which is being used when two objects are rubbing each other?
is using transform.translate bad for movement?
i feel like it'll mess up
with the colliders & whatnot
might cause a bit of clipping?
never used physics material
which physics material you are using
Uhm okay, thought this is the most basic thing in Unity
What do you use then?
i used this material at starting , but i never explored it , so can't say
Alright, fine. Thanks for checking 
how do i
make collisions
without rigid body
rigid body just messes up everything in my movement system
When you want to move object thats affected by physics, always use the Rigidbody component, not Transform.
yeah that's what i thought
Rigidbody.position isnt much better tho. .velocity and .AddForce will most likely give better results
if you use a rigidbody only to have it move by itself after you set its velocity, you are often better off using a kinematic rigidbody and move it with Rigidbody.MovePosition() in each fixed update directly. An active (non-kinematic) rigidbody makes only sense if you actually want force simulation.
so i'm just doing a simple double jump
AddForce makes it so that the double jump is often much less smaller than the first jump
so i just changed the y velocity every jump
yes, you are basically fighting the physics simulation, which you can do if you know exactly how that works and keep it minimally invasive, else you are setting yourself up for a lot of annoying edge cases and lots of tweaking work
the alternative is to make the character move with a custom motion function that can behave exactly as you like and disregard any physically correct movement.
usually in a game you do not need or want physically correct movement unless it is a simulation game
could you elaborate a bit on this?
what exactly is unclear?
custom motion function
what would this manipulate?
i know https://docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html was mentioned earlier but
it would seem really nasty to get gravity and that stuff in with the jumping & horizontal movement & all that?
why do you think that?
that just seems to be a fancier version of transform.translate
i don't know what this is supposed to mean
to make a kinematic controller you do something like this (oversimplified):
Vector3 _transientVelocity;
bool _isGrounded;
void FixedUpdate() {
_isGrounded = Physics.Raycast(transform.position + Vector3.up * 0.1f, Vector3.down, 0.2f);
if (!_isGrounded)
_transientVelocity += Vector.down * 9.81f;
_transientVelocity += movementAction.ReadValue<Vector2>().ToXZ();
rigidbody.MovePosition(transform.position + _transientVelocity * Time.fixedDeltatime);
}
oh dear god
but since controllers are more complicated you'd split that up into multiple updates, maybe focusing on input, rotation, velocity and post processing separately and then just update the rigidbody with the result. in each step you can do completely custom behaviour
ah ic, tysm!
wait, why's this better than updating rb.velocity & having it handle the rest?
because it allows you to do custom behaviour that does not fight the force-simulation engine, if you'd do custom physics with an active force simulation you'd be constantly dancing (wrestling) with it to do what you need. And i feel i have said this before: realistic forces are usually only desirable in simulation games (also physics puzzles) or as visual effect.
the ease by which you can make a character jump or a cube move with forces belies the complexity involved in making it actually achieve decent game feel. Either way you pick (forces or kinematic) will be difficult in its own way.
Anyone use the Contact Mods API?
I'm having some issues with fast moving continuous dynamic rigidbodies getting stuck on colliders that are set to ignore the contact pair and I'm wondering if its a bug
Why isn't my CharacterController detecting collisions with my Tilemap?
They're both on the same Z access.
because CharacterController uses 3D physics, and Tilemap uses 2D physics
the two physics types can't interact with each other
Oh man.
Thank you.
I ended up just disabling collisions on character controller
But that's good to know
Is it pretty much recommended to not bother with the character controller for 2D? The only thing I am really using it for so far is Move. I suppose I can just update the Transform instead. I don't really want to move by applying forces