- Home /
Looking at an Object (y-axis included)
Hello there :)
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!");
}
}
}
Answer by ZefanS · Nov 13, 2015 at 03:03 AM
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: http://answers.unity3d.com/questions/46594/initiate-raycast-from-center-of-camera.html
Your answer
Follow this Question
Related Questions
Path finding using Raycasting inside of Unity(JavaScript) 1 Answer
Raycasting problems 1 Answer
Setting Scroll View Width GUILayout 1 Answer
Make A Laser? 1 Answer
cast a ray to hit an object in the center of the screen 1 Answer