In javascript , I would like to know how to check if the player if facing an object.
EG.
I have a cube, and I want this script to be on the cube
if (player is facing cube)
{
//do action
}
Does anyone know how I could do this?
Thank You.
In javascript , I would like to know how to check if the player if facing an object.
EG.
I have a cube, and I want this script to be on the cube
if (player is facing cube)
{
//do action
}
Does anyone know how I could do this?
Thank You.
I don’t know how you’ve structured your code (i.e. if the script will be on the player, the cube, or a 3rd object). A solution is to compare the angle between the forward of the player and a vector between the player and the cube. If it is below some threshold, it is facing the cube.
var cubeDir = transform.position - player.position;
var angle = Vector3.Angle(cubeDir, player.forward);
if (angle < someValue) {
Debug.Log("I'm facing the player");
}
Attach this script to your player game object. Use threshold to change the accuracy of facing a target
var threshold : float = 0.3f;
var target : GameObject;
var dir : Vector3 = (target.transform.position - transform.position).normalized;
var direction : Vector3 = Vector3.Dot(dir, transform.forward);
if( direction >= threshold )
{
// code here
}
This may not be the exact solution but this links below will lead to the solution. 10 mins and you are set
Raycasting Tutorials —
sorry, as I dont know their exact use i could not give the exact solution