- Home /
How to do something when an object is in the player sights.
Greetings,
I will describe my question as follows.
Lets say that my first person controller has a crosshair. I want to do something of the sort:
if(player is looking at object && player is within certain distance) { ///// }
Wich functions could I use to do something like this?
Comment
Answer by tanoshimi · Mar 08, 2015 at 12:25 PM
You only need one function: Raycast. It is discussed extensively on this site, in tutorials, and elsewhere on the web.
Answer by Cherno · Mar 08, 2015 at 12:27 PM
public GameObject playerCamera;
publich float threshold = 10f;
void Update() {
Ray ray = new Ray(playerCamera.transform.position, playerCamera.transform.forward);
RaycastHit hit = new RaycastHit();
if(Physics.Raycast(ray, out hit, 1000f) {
if(Vector3.Distance(playerCamera.transform.position, hit.point) < threshold) {
Debug.Log("Object " + hit.collider.gameObject.name + " is within threshold.");
}
}
}