- Home /
Why is my enemy stopping before it reaches the player?
Hi, I have a problem with my enemy. The enemy is a model with a rigidbody attached to it. It is supposed to move towards the player over a map with lots of trees and some hills.
Everything works fine until the enemy gets relatively close to the player(about 40 map squares) and stops. To be exact it kind of jerks back and forth without moving towards its target. I have been trying a lot of things but the thing just won't work. Here is my code for the enemy moving:
var player:Transform;
var speed:float = 20;
function Start()
{
player = GameObject.Find("First Person Controller").gameObject.transform;
}
function Update ()
{
transform.rotation = Quaternion.Slerp(transform.rotation,Quaternion.LookRotation(player.position-transform.position), speed);
rigidbody.AddForce((player.position-transform.position)*speed*Time.deltaTime);
}
As I said the enemy is a rigidbody and it has a mass of 10. Can anyone help?
Thank You,
is your collider of your player is bigger then its $$anonymous$$esh ? it might be bouncing of the collider mesh/box/sphere...
The distance it stops at varies depending on the enemy and all the enemies use the same prefab. It couldn't be the colliders.
Good thinking though.
Answer by ScroodgeM · Aug 17, 2012 at 03:41 PM
this line
rigidbody.AddForce((player.position-transform.position)*speed*Time.deltaTime);
gets lower and lower while time, cause distance gets lower. methinks speed should not depends on distance. and a little hint - apply physics in FixedUpdate
void FixedUpdate() { rigidbody.AddForce((player.position-transform.position).normalized * speed); }
Thanks for the reply! The thing is working now. A little note on the FixedUpdate:
The example you gave me is in C# would the function look the same in javascript with a 'function' ins$$anonymous$$d of 'void'?