- Home /
Rotate object towards target without influencing AddForce
Hello, I want my zombie to walk towards my player. I already solved this. Now i want that the zombie not only walks toward my player, but also look at him.
First my moving script (I use a rigidbody):
// Move
// Calculate how fast we should be moving
Vector3 targetVelocity = player.transform.position - this.transform.position;
targetVelocity = Vector3.Normalize (targetVelocity);
targetVelocity = transform.TransformDirection (targetVelocity);
targetVelocity *= movementSpeed;
// Apply a force that attempts to reach our target velocity
Vector3 velocity = rigidbody.velocity;
Vector3 velocityChange = targetVelocity - velocity;
// Clamp velocityChange
velocityChange.x = Mathf.Clamp (velocityChange.x, -maxVelocityChange, maxVelocityChange);
velocityChange.z = Mathf.Clamp (velocityChange.z, -maxVelocityChange, maxVelocityChange);
velocityChange.y = 0;
// Rotate velocityChange to avoid
velocityChange = Quaternion.AngleAxis (avoidInDegrees, Vector3.up) * velocityChange;
rigidbody.AddForce (velocityChange, ForceMode.VelocityChange);
// Apply gravity
rigidbody.AddForce (new Vector3 (0, Physics.gravity.y * rigidbody.mass, 0));
I tried it with the following line and then my zombie looks at my player, but he walks toward him in a circle and not straight as it should be.
// Look
transform.LookAt (player.transform.position);
I know where the problem is, but i can not solve it. Thanks for your help!
EDIT: I found a solution: Just delete
targetVelocity = transform.TransformDirection (targetVelocity);
and you will be fine if you are running the same issue as me. And add
// Look
transform.LookAt (player.transform.position);
and you will be fine.
what you can do is make a child object with the zombie graphics and then put a LookAt for the child object while the parent does all the physics moving
Your answer
![](https://koobas.hobune.stream/wayback/20220613174202im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Add Force to the right of the rigidbody, not right of the screen 1 Answer
Prevent Rigidbody From Rotating 3 Answers
Making RigidBody face direction for movement 1 Answer
Rigidbody.addforce then rigidbody.rotation and movement along transform.forward 2 Answers
how to stop a player moving thought the walls in a 2d game 1 Answer