Looking at an Object (y-axis included)

Hello there :slight_smile:

I want to check if my FPS is looking at a certain object. I’ve used Raycasting and it works, BUT I can only rotate the ray on the x-axis, not the y-axis. How can I change that?

Here’s my code:

function Update () {
	var forward = transform.TransformDirection(Vector3.forward);
	var hit : RaycastHit;
	Debug.DrawRay(transform.position, forward*20, Color.green);
	
	if(Physics.Raycast(transform.position, forward, hit, 20)){
		if(hit.collider.gameObject.name == "Papier"){
			Debug.Log("Hit!");
		}
	}
}

In this case you are sending the Raycast straight forward out from the player. Instead you want to send it straight out of the camera. This is the Raycast I use for this:

#pragma strict

public var camTransform : Transform;

function Update()
{
    var hit: RaycastHit; 
    if (Physics.Raycast(camTransform.position, camTransform.forward, hit, 20))
    {
    		//Check what it hit
    }
}

The key point is to use the camera’s transform, which, in the case of the above snippet, you assign in the inspector by dragging in the GameObject with the player’s camera attached.

*Based on the answer here: Initiate RayCast From Center of Camera? - Questions & Answers - Unity Discussions