C Sharp Rotate

I need help.

I have a targeting script and I want my player to rotate and look ato the enemy when targeted. How would I do it. if my enemy is a transform.

I want to be able to toggle on and off this code as well.

Well, there are several ways that you can do this. Since you have no code attached, I’m assuming you haven’t tried using LookAt().

In your player’s script, simply use:

transform.LookAt( enemyTransformHere, Vector3.up );

http://unity3d.com/support/documentation/ScriptReference/Transform.LookAt.html

Now, this particular method included in the Unity Engine is very limiting, and I’m also going to assume that you are going to want additional parameters, which this method may hinder against. You’d have to provide more detail depending on your specific situations in that case.

Transform targetTransform = null;

void Update()
{
    if(targetTransform != null)
        this.transform.LookAt(targetTransform, Vector3.up);
}

Then all you’d need to do it set the targetTransform value to be the transform you wish to target… i.e.

  public void SetTarget(Transform p_transform)
  {
        targetTransform = p_transform;
  }

SetTarget(yourEnemyTarget); // to target

SetTarget(null); // to clear

To add smoothing:

  void Update()
  {
        if(targetTransform != null)
        {
              Quaternion curRot = this.transform.localRotation;
              Quaternion lookRot = Quaternion.LookRotation(targetTransform.position - this.transform.position, Vector3.up);
              this.transform.localRotation = Quaternion.Lerp(curRot, lookRot, Time.smoothDeltaTime);
        }
  }