- Home /
How to make an object to look at Raycast Hit Point?
I raycasted a ray and stored its collision point data in hitTarget var. I tried to make the object look at this point by LookAt(hitTarget) but it seems that the parameter inside LookAt() must be a Transform variable. I also tried to create an empty object at the hitTarget position and change its position every frame to match the new hitTarget position but I can't make my object(e.g Turret) to look at this empty. How can I achieve that, which is making the object I want to look at the hit point position?
Looking at an empty should have worked just fine -- both probably had some other error.
But, LookAt doesn't need to be aimed at an actual thing. It will gladly LookAt a rayhit, or 2 meters above Bob's head, or a point midway between two cats. You just need to compute the point.
It really wants a point to look at (a Vector3.) Taking a transform is just a shorthand for the position of that transform. Often you want to look at transform $$anonymous$$arla. You can write just LookAt($$anonymous$$arla)
and it fills in LookAt($$anonymous$$arla.position.)
Answer by Anxo · Jan 29, 2013 at 02:00 PM
RaycastHit.point returns a vector3. Ref
transform.LookAt can take a Transform or a Vector3. It will point the Z axis of your object in that direction. Ref
So if you just need some object to look at the hit point of some ray then you could do something like this.
using UnityEngine;
using System.Collections;
public class example : MonoBehaviour {
public Transform turret;
void Update() {
RaycastHit hit;
if (Physics.Raycast(transform.position, Vector3.forward, out hit)){
Vector3 hitPosition = hit.point;
turret.LookAt(hitPosition);
}
}
}
And to fix it up to look at a Transform (as the OP was thinking,) use hitTarget.transform