About

Monday 18 May 2015

Unity3D tutorial | Game Object Looking at another gameobject

This tutorial will help you find how your one game object can look at another object at all times.

Scenario: 

We have enemies and player in a scene. Player is constantly moving from one place to another. Enemies should be intelligent enough to look towards the player every frame.

Solution:

This can done like:


function Update () {

 // get direction of player
        _direction = (Target.gameObject.transform.position - transform.position).normalize
         
        // create the rotation we need to be in to look at the target
        _lookRotation = Quaternion.LookRotation(_direction);
         //rotate us over time according to speed until we are in the required rotation
         transform.rotation = Quaternion.Slerp(transform.rotation, _lookRotation, Time.deltaTime * RotationSpeed);

}


Throw this script of any enemy object and pass the "Target" variable of player as reference to it. And it is all done

If any question, plz ask me.

No comments:

Post a Comment