- Home /
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.
Answer by Rod-Green · Nov 07, 2011 at 10:28 PM
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);
}
}
Yes. And what if I would like to make it rotate smoothly
Smoothing requires a lerp.. I added the method at the bottom of my answer.
Thank you! Can you help me another question please!
http://answers.unity3d.com/questions/184053/targeting-multiple-enemys.html
Answer by dannyskim · Nov 07, 2011 at 10:37 PM
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220613034500im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Flip over an object (smooth transition) 3 Answers
Make object face direction only on one axis 1 Answer
move the object where camera look 0 Answers
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer