Leo Smart -4 years ago 64
C# Question

# How to I make it so my enemy doesn't change it's height when the target jumps?

I have been writing a script for enemy movement in my game, but when the target(Player) jumps, the enemy begins to gradually float up to the same y position the target was in. I would like it if the enemy stayed at the same position as the ground, but I have not found out how I would be able to do that. I am new to Unity, so the only thing I could think of was adding a rigidbody to the enemy but that did not seem to work. Would anyone have any Idea on how to do this? Here is my script:

`````` public class EnemyMovement : MonoBehaviour {
//target
public Transform Player;
//the distace the enemy will begin walking towards the player
public float walkingDistance = 10.0f;
//the speed it will take the enemy to move
public float speed = 10.0f;
private Vector3 Velocity = Vector3.zero;
void Start(){
}
void Update(){
transform.LookAt (Player);
//finding the distance between the enemy and the player
float distance = Vector3.Distance(transform.position, Player.position);
if(distance < walkingDistance){
//moving the enemy towards the player
transform.position = Vector3.SmoothDamp(transform.position,
Player.position, ref Velocity, speed);
}
}
``````

Just set the `y` value before doing the movement

``````public class EnemyMovement : MonoBehaviour {
//target
public Transform Player;
//the distace the enemy will begin walking towards the player
public float walkingDistance = 10.0f;
//the speed it will take the enemy to move
public float speed = 10.0f;
private Vector3 Velocity = Vector3.zero;
void Start(){
}
void Update(){
transform.LookAt (Player);
Vector3 target = Player.position;
target.y = transform.position.y;
//finding the distance between the enemy and the player
float distance = Vector3.Distance(transform.position, target);
if(distance < walkingDistance){
//moving the enemy towards the player
transform.position = Vector3.SmoothDamp(transform.position,
target, ref Velocity, speed);
}
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download