Thursday, 26 March 2015

Unity 5: Follow the player

    1 Hour Code/Assets

    By applying this simple script to an enemy GameObject they will follow any tag named player. I have not created a system that allows for more then one player. This also allows for variable speed, for each GameObject but it is easy to remove.

    public float SpeedMax = 10f;
    public float SpeedMin = 7f;
    public int rotationSpeed = 5;
    public Vector3 direction = new Vector3(0,0,0);
    public static float moveSpeed;

    Transform target; //the enemy's target var moveSpeed = 3; //move speed var rotationSpeed = 3; //speed of turning
    Transform myTransform; //current transform data of this enemy

    void Awake()
    {
        myTransform = transform;//cache transform data for easy access/preformance
    }

    void Start()
    {
        target = GameObject.FindWithTag("Player").transform; //target the player
        moveSpeed = Random.Range(SpeedMin, SpeedMax);
    }


    void Update ()
    {
        myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
        myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
    }

No comments:

Post a Comment