Why this isn't working?
Any ideas?
void Update ()
{
int x = Screen.width / 2;
int y = Screen.height / 2;
Ray ray = playerCam.GetComponent<Camera>().ScreenPointToRay(new Vector3(x, y));
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
distance = hit.distance;
{
var p = hit.collider.GetComponent<Transform>(); //This isn't working :(
if (p != null && distance > -3.0f)
{
lookingAt = p.gameObject;
}
}
}
Answer by Pengocat · Jan 21, 2017 at 02:04 PM
The scope brackets are kind of pointless when not part of the if statement. Also you don't need to use GetComponent to use the gameobject since you already got that. You Find gameobjects which hit already has and you GetComponents on that gameobject so in this case it is redundant. Lastly how can the distance ever be negative? Here is my example of how you probably want it to look.
if (Physics.Raycast(ray, out hit))
{
if (hit.distance > 3.0f)
{
lookingAt = hit.collider.gameObject;
}
}
Your answer
Follow this Question
Related Questions
How would I project a Gameobject onto the surface of another? 0 Answers
Cannot properly access player position 1 Answer
How to get the position of a gameObject based on its index in an array? 0 Answers
If you want to destroy the game object, please call 'Destroy' on the game object instead. 1 Answer
How To Make An Object Appear In Front Of Player Without Cloning? 1 Answer