How to: rigidbody.MovePosition to player's position
Scripting noob here. I have a game populated with large amounts of enemies, so I decided to switch them from CharacterControllers to kinematic rigidbodies to optimize, since I've read on here that there's much less overhead when doing so.
What I'm trying to do is very simple. I need to have my AI enemies move towards the "target" GameObject, which is assigned in the editor. According to the script reference, this should work:
rigidbody.MovePosition (target.position);
However, it makes my enemy teleport to my player object, not actually travel there like how characterController.Move does.
How can I achieve the same effect as characterController.Move() for a rigidbody?
Answer by Lovrenc · Jan 06, 2013 at 01:25 AM
public float movementSpeed= 5f; //for instance
void Update() {
Vector3 direction = (target.transform.position - transform.position).normalized;
rigidbody.MovePosition(transform.position + direction * movementSpeed * Time.deltaTime);
}
EDIT: fixed a bug.
Thanks for the reply. This does not work, unfortunately.
It just zeroes out the position of the GameObject, rgardless of where it is placed in the editor.
I tried a very similar line that worked really well with CharacterController, but for some reason it doesn't do anything with a rigidbody.
Ah that works wonderfully. The GameObject is jittery though, but I've seen that issue mentioned in multiple other threads; I'll search for a fix.
Thanks for all of your help!
Hello. I know this is an old thread but have you found a solution for the jittery-ness? I used the same code and encountered the exact same problem.
shouldn't you be using FixedUpdate ()
ins$$anonymous$$d?
Remember that RigidBody.is$$anonymous$$inematic should be set to true to allow for smooth transition as explained in the Rigidbody.$$anonymous$$ovePosition() docummentation.
Answer by zzeeshann · May 12, 2016 at 02:37 PM
rigidbody is depreciated use GetComponent()
Vector3 direction = (target.transform.position - transform.position).normalized; GetComponent().MovePosition(transform.position + direction movementSpeed Time.deltaTime);
Your answer
Follow this Question
Related Questions
Control speed of a rigidbody that move to a fixed distance 2 Answers
rigidbody.MovePosition to rigidbody.velocity 0 Answers
Moving RigidBody Smoothly 0 Answers
Moving a cube with RigidBody. MovePostition, it randomly stops moving 0 Answers
Gravity issue on MouvementController using RigidBody when going down a slope 0 Answers