- Home /
Simple movement problem. Need units to stop dead on collision.
Should be a fairly simple problem, but it is giving me some trouble.
I've got some "2d" rectangular units with trigger boxes being moved around using the translate function. When they collide I need them to stop dead, but they should still be able to freely move away from each other and parallel to the other unit's edge.
Related questions have suggestions like "use triggers" which I am already doing.
My current solution is to maintain an old position from a fraction of a second ago and revert to that position OnTriggerEnter and OnTriggerStay. This results in some unsightly jerkiness, and worst of all, the tendency of two moving units to become stuck together.
How do you get objects to stop dead when colliding without sticking or jerking?
Answer by RetepTrun · Jan 23, 2013 at 01:46 AM
Maybe you could do a really short raycast like a milimeter infront of them. So you could have logic like
if(someting right in front of me){
stop
}
Going to have to do something similar to this, but raycasting wont work because the unit is a rectangle and can move any direction, so it could catch an edge anywhere.
Answer by SmooveB · Jan 23, 2013 at 07:11 PM
I ended up adding four long triggers. One to each side of the unit as children of the unit just outside the units main collision. OnTriggerEnter, these triggers stop any movment by the unit in the direction of that trigger.
So if the front trigger enters a trigger, then the main movement script gets set to something like:
horazontalMove = Mathf.Min(0,horazontalAxis)
Or if the back trigger enters a trigger then it has the main script do something like:
horazontalMove = Mathf.Max(0,horazontalAxis)
I would still like to know a solution that relies more on code and less on strange uses of the tool, but for now this works fine.
Answer by Loius · Jan 23, 2013 at 07:29 PM
Use rigidbody.velocity = Vector3.zero
Or if you're using triggers (which can't collide physically), you need to manually locate where they should be.
For instance, to force me and him apart such that we're exactly touching (where xWidth is the distance from the center point to the edge along the X axis):
if ( me.x + me.xWidth > him.x - him.xWidth ) me.x = him.x - him.xWidth - me.xWidth
You can use OnTriggerEnter to catch 'collisions', and then just run that for each relevant axis against the thing you hit.