Urgent help,

Hello everyone
I’m kinda having a trouble with making an enemy stopping at certain distance with this script the game is 2D game

and here’s the script I have for enemy (following) purpose

using UnityEngine;
using System.Collections;

public class FacePlayer : MonoBehaviour {

    public float rotSpeed = 180f;

    public Transform player;

    void Update () {
    if (player == null)
        {
        GameObject go = GameObject.Find ("Player");

            if (go != null){
                player = go.transform;
            }
        }

        if (player == null)
            return;

        Vector3 dir = player.position - transform.position;
        dir.Normalize ();

        float zAngle = Mathf.Atan2 (dir.y, dir.x) * Mathf.Rad2Deg - 90;

        Quaternion desiredRot = Quaternion.Euler (0, 0, zAngle);

        transform.rotation = Quaternion.RotateTowards (transform.rotation, desiredRot, rotSpeed * Time.deltaTime);
    }
}

So what am I missing? I tried in update function tried this

        if (Vector3.Distance (transform.position, Player.position) > maxDistance)

and I added the maxDistance value but the enemy starts moving forward and keeps going forward for some reason.

Thanks in advance!

Urgent help??? I thought you were trapped in a lift or something… Seriously choose a better title…

Anyways, for your non urgent problem, where is the code that moves the enemy? The Update method above rotates the enemy but I cant see any movement code? Your if statement is fine, have you tried Debug.log on both transforms, the enemy and player, to see if they are what you expect.

1 Like

lol, well I am trapped in this code, and also another problem but I’m not gonna bother asking about it it’s not easy to fix however thanks a ton for your quick response, here’s the movement script

using UnityEngine;
using System.Collections;

public class EnemyMovement : MonoBehaviour {
   
    public float maxSpeed = 2f;
   
    void Update ()
    {

        Vector3 pos = transform.position;
       
        Vector3 velocity = new Vector3 (0, maxSpeed * Time.deltaTime, 0);
       
        pos += transform.rotation * velocity;
       
        transform.position = pos;
    }
}

Thanks a ton!

regards.

Ok so add your if statement around all the code in the update method of that script.

1 Like

Thanks man! worked like a charm!
regards

No problem! Good luck on your project!