- Home /
Enemy follow script problem
Hey guys, this might be a really simple question but I just can't seem to figure it out, I have a follow script attached to my "Enemies" and it works, they rotate towards the player and follow him till they are a certain distance away.
However, the enemies seem to move along the y axis to match the players height (resulting in the enemies partialy going throught the terrain) so I changed it to follow the main cam which is a first person cam attached to the player (now the enemies are floating above ground to match the cams height) so my question is how do I stop the gameobjects from moving along the y axis? No rigidbodies are attached to enemies just a trigger and a collider. Here's my script; p.s have tried with rigidbodies and constrants, gravity, etc.
public Transform player;
public float moveSpeed = 5f;
public float minDist = 2f;
// Use this for initialization
void Start () {
player = GameObject.FindGameObjectWithTag ("MainCamera").transform;
}
// Update is called once per frame
void Update () {
transform.LookAt (player);
if (Vector3.Distance (transform.position, player.position) >= minDist) {
transform.position += transform.forward * moveSpeed * Time.fixedDeltaTime;
}
}
}
Answer by AndreiMarian · Dec 23, 2016 at 01:20 PM
The simplest and straightforward solution that comes to mind is to just use the x and z components, like this:
// at beginning of class:
private Vector3 displacement;
// Update or whatever you use:
displacement = transform.forward * moveSpeed * Time.fixedDeltaTime;
transform.position += new Vector3(displacement.x, 0, displacement.z) ;
or be done with it by using:
transform.position += Vector3.Scale(transform.forward * moveSpeed * Time.fixedDeltaTime, new Vector3(1, 0, 1)) ;
Worked perfectly, thank you. This script is my first "translation" from javascript to c# so thanks for fixing it
Answer by javad_atrd · Dec 23, 2016 at 04:32 PM
//if enemy must go in y axis if (Vector3.Distance (transform.position, player.position) >= minDist) {
transform.position += transform.up* moveSpeed * Time.fixedDeltaTime;
}
also check enemy rotation to see what axis is he r... if blue line (Z) is looking at Top so your script is ok
thanks for the reply, but its the opposite im after, restrict movement on the y axis
Your answer
![](https://koobas.hobune.stream/wayback/20220612103319im_/https://answers.unity.com/themes/thub/images/avi.jpg)