- Home /
How to stop the enemy from jumping when chasing the player ?
Hi, this is for a 2D side scrolling game. The enemy chases the player when in range, but if the player jumps the enemy jumps as well(follows in up direction too) which does not look too good. How can i stop the enemy from jumping(chase only on x direction) when chasing the player ? This is the code:
var enemy: Transform;
var player: GameObject;
var dir: Vector3;
var speed: float;
var observed: boolean;
var sightDistance: int = 50;
function Update () {
if(Vector3.Distance(enemy.position,transform.position)< sightDistance){
if(observed){
dir = player.transform.position - transform.position;
dir = dir.normalized;
transform.Translate(dir*speed,Space.World);
}
else{
transform.eulerAngles.y = Mathf.PingPong(Time.time*20,90)-45; }
}
}
function OnTriggerEnter (other: Collider){
if(player)observed = true;
}
I also added this part to the code - now he doesn't jump that high anymore but still jumps:
if(rigidbody.velocity.y > 0) {
rigidbody.velocity.y = 0;
}
Constraining the y position from the Inspector does not work(enemy is a rigidbody). Thank you very much !
Answer by unfoundfate · Apr 21, 2012 at 01:28 PM
Try using rigidbody.AddForce(dir*speed);
http://unity3d.com/support/documentation/ScriptReference/Rigidbody.AddForce.html