Drew U
Drew U

Reputation: 483

Unity transform.LookAt() not updating with a moving target

My camera casts a ray to the centre of the screen and I have an object that looks at that direction. The problem is, I made it such that certain keys rotate the camera, so there's a new centre, and the ray from the camera moves too but the object doesn't look at the new direction

Here's my code:

 void Update (){
 int x = Screen.width / 2;
 int y = Screen.height / 2;

 //Get centre of screen from camera
 Ray ray = Camera.main.ScreenPointToRay (new Vector3 (x, y));
 Debug.DrawRay (ray.origin, ray.direction * 1000, new Color (1f, 0.922f, 0.016f, 1f));

 //Set object direction
 object.transform.LookAt (ray.direction);
 }

I'd really appreciate some help with this, thank you!

Upvotes: 0

Views: 1518

Answers (2)

Mini
Mini

Reputation: 453

Well the ray would be starting from the camera and going towards the middle of the screen. So if you wanted the object to look at the camera every Update, the direction would be wrong, but also what if the object wasn't in the center of the screen? If I'm misinterpreting your question, please comment and explain further. I think a better way to get the forward direction of the camera would be to use Camera.main.transform.forward, and you could put that in a Physics.Raycast as well. To have something always look at the camera you could try object.transform.LookAt(Camera.main.transform.position, -Vector3.Up);.

Edit: Also, if you mean the have the object look the same direction as the camera, you could always try object.transform.forward = Camera.main.transform.forward, or keep up with object.transform.rotation = Quaternion.LookRotation(Camera.main.transform.forward, Transform.up);

Alright new idea:

Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
RaycastHit hit;
if(Physics.Raycast(ray, out hit))
{
    Vector3 point = hit.point;
    object.transform.LookAt(point, Vector3.Up);
}

Upvotes: 0

Drew U
Drew U

Reputation: 483

I found a solution. Instead of looking at ray direction, I got a point from the ray using GetPoint and made the object look at that. It's working fine now.

Upvotes: 1

Related Questions