Hey Unity answers!
So recently I’ve been working on a new camera system for my game, but what I really need to know is how to use Quaternion.LookRotation on one axis. There’s already a lot of answers on the forums but they’re all for JS. I really need to know for c#!
This is the code that I’m using to look on all axis:
using UnityEngine;
using System.Collections;
public class LookAt : MonoBehaviour
{
public Transform target;
void Update ()
{
Vector3 relativePos = target.position - transform.position;
transform.rotation = Quaternion.LookRotation(relativePos);
}
}
Thanks for y’alls help!
Even though the question is quite old I did come across this problem recently and solved it like this. Entries in the rotationMask are 1 for the affected axes and 0 for the fixed axes.
public Transform target;
public Vector3 rotationMask;
void Update ()
{
Vector3 lookAtRotation = Quaternion.LookRotation(target.position - transform.position).eulerAngles;
transform.rotation = Quaternion.Euler(Vector3.Scale(lookAtRotation, rotationMask));
}
hi, this example Lock rotation only on Y axis :
Vector3 relativePos = target.position - transform.position;
Quaternion LookAtRotation = Quaternion.LookRotation( relativePos );
Quaternion LookAtRotationOnly_Y = Quaternion.Euler(transform.rotation.eulerAngles.x, LookAtRotation.eulerAngles.y, transform.rotation.eulerAngles.z);
transform.rotation = LookAtRotationOnly_Y;
Quaternion.LookRotation() takes one vector3 as an argument, if you want to rotate around specific axis, then pass direction such as Vector3.right or Vector3.left. Depends on your need.
So, statement will be:
transform.rotation = Quaternion.LookRotation(Vector3.left);
Keep in mind:
Vector3.left means new Vector3(-1, 0, 0) in c#, it’s also same for other directions.
This is the answer that I use. I am fairly certain it’s not the best in terms of efficiency, but it does work. Does anyone have any ideas on how to get the same effect with better efficiency?
Vector3 originalRotation = this.transform.rotation.eulerAngles;
Vector3 targetDir = target.transform.position - transform.position;
float step = rotationSpeed * Time.deltaTime;
Vector3 newDir = Vector3.RotateTowards(transform.forward, targetDir, step, 0.0F);
Debug.DrawRay(transform.position, newDir.normalized * 1000f, Color.red, 0.1f);
transform.rotation = Quaternion.LookRotation(newDir);
transform.rotation = Quaternion.Euler(originalRotation.x, this.transform.rotation.eulerAngles.y, originalRotation.z);