Home > database >  Getting transform.Translate behavior using Rigidbodys in Unity
Getting transform.Translate behavior using Rigidbodys in Unity

Time:04-27

My goal is to achieve behavior that is exactly like tranform.Translate(), just without breaking collision detection. I'm currently dealing with some rather thin walls and the GameObject (using the "Continuous" collision detection mode) will pass through the walls whether I use transform.Translate() or Rigidbody.MovePosition() . The ONLY way I have been able to fix this is by using something like rbody.AddForce(force, ForceMode.VelocityChange), however, this now produces "slidey" behavior. Does anyone know how I can achieve the behavior of transform.Translate while maintaining accurate collision?

EDIT: I tried adjusting rbody.velocity directly, but now there is another issue. When moving into a wall at an angle, the GameObject will completely halt. The desired behavior is for the GameObject to move where it's able to. (see attached image)

CodePudding user response:

I will explain what I would try (don't know if it works). I would have the Rigidbody in a parent GameObject of the game object of interest. In the OnCollisionEnter of this parent GameObject I would have some logic that gives this parent GameObject the same rotation as the wall is colliding with and the inverted rotation to the child go so that you have the child not rotated at all and the parent GameObject aligned with the wall. By aligned I mean both with their local axis at the same rotation. Then with either Rigidbody constraint or moving the transform you should be able to move the parent GameObject along the plane of the wall, as you aligned the axis system with the one of the wall in the logic I mentioned.

Hope that makes sense.

CodePudding user response:

From the comments it seems what you're wanting is to be able to move the Rigidbody at a constant speed. For 3D movement you can use something like this:

Vector3 targetVelocity = Vector3.forward * moveSpeed;
rigidbody.AddRelativeForce((targetVelocity - rigidbody.velocity), ForceMode.VelocityChange);

For 2D movement you can use something like this:

Vector3 v = rigidbody.velocity;
v.x = moveSpeed;

(Both in FixedUpdate().) This should move the object at a constant velocity equal to moveSpeed without bypassing collision detection.

  • Related