- Home /
Rotate only Y-axis of some object toward another
I have rotation of some object to be (270,yRotation,0). How to achieve my object only rotates around y-axis toward some another object in move?
Answer by clunk47 · Dec 16, 2012 at 05:00 PM
Here is a really easy way to do this. Attach this script to a turret or something that is going to look at your player. Just drag the player, or whatever you want the "turret" to look at, onto the slot for "Player" in the inspector. This example is in C#.
using UnityEngine;
using System.Collections;
public class EXAMPLE : MonoBehaviour
{
public Transform player;
Vector3 target;
void Update ()
{
target = new Vector3(player.position.x, this.transform.position.y, player.position.z);
transform.LookAt(target);
}
}
Notice the trick here is to change the target Y to your own Y. That way LookAt doesn't want to look up or down.
It looks like the OPs object might be looking up, so the trick would be to change the target Z into your own Z.
Object follows player, however, it's in disposition, facing upward ins$$anonymous$$d of forward. What may be the cause to it?
Be sure the axes of your object are correct (X is left / right, Y is up / down, Z is forward / back. Sometimes if you have an imported model(especially fbx or blender) the axes can be off. If this is the case, you would need to create an empty gameObject and make it the parent of your model, then remove the script from your model and attach it to the model's new parent (the new empty gameObject).
Oh, dear, after some time I have finally managed to work this out :) The code I applied was this var direction = player.position-transform.position; direction .y = 270;
transform.rotation = Quaternion.LookRotation(direction ); And it works just smooth and perfect as I wanted it to work. :)
Answer by Aloan · Apr 06, 2014 at 05:22 AM
Clunk47! Thank you! your codes does perfectly what I wanted! Now my quad trees and quad people all rotate to me nicely. No more tilting like they were falling or leaning over! this is marvelous! I've been looking for this code for days!
Answer by Map-Builder · Dec 17, 2012 at 02:13 PM
transform.rotation = Quaternion.LookRotation(targetObject.position - transform.position, Vector3(0,1,0));
// Vector3(0,1,0) keep heads up along that vector (y+)
Should work properly
Right idea, but not helpful numbers.
LookAt has a "free spin" after it aims. You control it with a 2nd input saying which way counts as "up." If you leave it out, it automatically uses `Vector3(0,1,0)`.
If the object is aimed mostly up, something like `Vector(0,0,-1)` would try to have the top part face the camera (well, if the camera is south of you.)
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Rotate GameObject using Coroutine 2 Answers
object rotation to another vector not changing 0 Answers
problem with object rotation 1 Answer
How do I delete an object in my Project 2 Answers