- Home /
Making an Object Rotate to Face Another Object
Alright. So, in the project I'm working on, I have an object that I want to turn to face another object. Simply put: how. Although it seems like a good option, I can't get transform variables to work. Also, for extra credit, can I make it reference a different object (with the same name) in each scene? Alternatively, the objects being rotated towards are immobile, so making the object rotate towards a given point would work as well. Thanks!
Answer by rasheedqw · Sep 15, 2013 at 04:11 AM
var damping:int=2;
var target:Transform;
var lookPos = target.position - transform.position;
lookPos.y = 0;
var rotation = Quaternion.LookRotation(lookPos);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
someone else came up with the code but it worked for me
This solution would have taken me forever to figure out. Thank you!
Answer by Mortennobel · Aug 28, 2011 at 09:12 PM
Take a look at Transform.LookAt
http://unity3d.com/support/documentation/ScriptReference/Transform.LookAt.html
Alright, thanks. Is there a way to do this and make the rotation only occur about the z-axis?
Add a rigidbody to your object and check off freeze rotation under Constraints for x or y.
@FTheCloud, this won't work: rigidbody constraints only affect physics.
I'm having a similar problem. I want it to only rotate on the Y-axis.
first you need to store the initial rotation than after you use transform.lookat, update localRotation.x and localRotation.z only. Thus rotating and facing other object with only y rotation. Quaternion initialRotation;
void Start(){
//store initial rotation
initialRotation = Quaternion.Euler(new Vector3(this.transform.localRotation.eulerAngles.x,this.transform.localRotation.eulerAngles.y,this.transform.localRotation.eulerAngles.z);
}
void Update()
{
// Rotate the camera every frame so it keeps looking at the target
this.transform.LookAt(target);
//keep existing "y" rotation and set "x" and "z" rotation from intitalRotation
this.transform.localRotation = Quaternion.Euler (new Vector3 (initialRotation .x, this.transform.localRotation.y, initialRotation .z));
}
Your answer
Follow this Question
Related Questions
Object Rotation around a point at different Heights 0 Answers
Gun should point at mouse position 3 Answers
How to rotate a quad 1 Answer
Make an object point to another which keeping its forward along an axis 0 Answers
Applying a rotation to a point? 2 Answers