I am using Quaternion.LookRotation to change the rotation of a gameobject to a new rotation determined by a ray trace. Here is the script:
using UnityEngine;
public class Example : MonoBehaviour
{
public float speed = 0.5f;
private Vector3 targetPos;
private Vector3 startPos;
private Vector3 mousePos;
public void Start()
{
startPos = transform.position;
}
public void Update()
{
mousePos = Input.mousePosition;
Ray mouseCast = Camera.main.ScreenPointToRay(mousePos);
Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
RaycastHit hit;
float rayLength;
if (Physics.Raycast(mouseCast, out hit, 9999))
{
Debug.DrawLine(mousePos, targetPos, Color.blue);
targetPos = new Vector3(hit.point.x, 0f, hit.point.z);
if (Vector3.Distance(targetPos, transform.position) >= 0.5f)
{
Quaternion rot = Quaternion.LookRotation(targetPos);
transform.rotation = Quaternion.Slerp(transform.rotation, rot, speed * Time.deltaTime);
Debug.Log(targetPos);
}
}
}
}
I’m currently getting this result in my scene:
This is the desired result however I want the X axis to also change. For example when I use something simple like transform.LookAt(targetPos) I get the desired result however I can’t do this function overtime like I can with RotateTowards. This is the result I get using LookAt instead of RotateTowards:
The latter method is what I ideally want to achieve however I don’t want the rotation to happen in just one frame I want the turret to slowly pan over to the new rotation just like the first method. How can I pull both these methods together to fit my needs?
It IS looking in multiple axes, but the data you’re sending it is on a flat plane.
Unlike transform.LookAt, Quaternion.LookRotation has NO idea of the object it will be applied to. That means it doesn’t know where it’s looking from. So instead of feeding it a position, as you’re doing, what you actually need to do is feed it a direction vector. You can get a direction vector by subtracting two positions.
These two pieces of code will produce identical results:
Thank you for the solution it worked perfectly, so is the reason why it works with LookAt because of the Vector3 WorldUp parameter so it can actually find the ray trace hit position? Again thank you for the quick reply
The reason it works with LookAt is because LookAt knows where your object is.
Try this. Currently, your turret’s base is at (0,0,0) and your actual turret is above that. Try moving your turret, say, to the left. Now aim at a point in between the old spot and the new spot. With transform.LookAt, it’ll look right at the point you’re aiming at. With Quaternion.LookRotation [without subtracting transform.position], it’ll be looking in the wrong direction entirely. No matter where your turret’s position is, Quaternion.LookRotation will always point as if the turret is looking from (0,0,0) because it’s treating a position as a direction vector. That’s why you need to subtract the turret’s position when using LookRotation.