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);
	}
}

}

You should set "_destination" with your player transform in inspector.

–

2 Answers

2

I think you could use addforce with a rigidbody to make it work as you intend it to. I’m on my phone now, but Google addforce and see if you can make it work!

Ok so i have three starting enemies and they follow my character but when i make a prefab and put the prefab in my "spawner" the enemies stay in one area and don't move except fot the original three, when i check the prefab the destination wont allow me to put my Player transform in. any idea how to fix this?[116992-screenshot-20.png|116992]

–

Vector3 toPlayer = playerPos - enemyPos;
toPlayer.y = 0;
then use this vector (now with only x,z delta in it ) to move towards the player.
I suggest you normalize it now, toPlayer.Normalize() so it is unit length = 1
Then you can move at desired speed based on a speed multiplier.
pos = pos + toPlayer * runSpeed * Time.DeltaTime;