- Home /
[js] How To Check If The Player Is Facing An Object
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.
Answer by robertbu · Apr 13, 2014 at 05:55 PM
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");
}
The code would be on the cube, so could you edit the answer so it could be so that the script is on the cube?
I edited the answer. It assumes Javascript and that you have an initialized variable called 'player' which is the transform of the Player.
Thanks, but how would I know what the 'someValue' would be?
Also, I'm sorry but how would I initialize the variable that find the transform of the player. I tried doing transform.Find but it gives me an error when I do that.
Typically to initialize the player variable you would put this in the top of the file:
var player : Transform;
Then you can drag and drop the Player game object onto the 'player' variable in the Inspector. Alternately you can do:
private var player : Transform;
function Start() {
player = GameObject.Find("Player").transform;
}
Replace "Player" string in the Find() call with whatever you've named your Player.
As for 'someValue', replace it with whatever angle you consider facing. It is in degrees. Start with 45.0 and then adjust it. The smaller the angle, the more directly the player needs to be facing the cube to be considered facing.
Answer by akauper · Apr 13, 2014 at 06:49 PM
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
}
Answer by sami1592 · Apr 13, 2014 at 06:54 PM
This may not be the exact solution but this links below will lead to the solution. 10 mins and you are set :D
Raycasting Tutorials ---
sorry, as I dont know their exact use i could not give the exact solution :(
Your answer
Follow this Question
Related Questions
Moving an object 0 Answers
How does unity/javascript handle object references? 1 Answer
Saving Object Position in Float NOT Object 1 Answer
Cannot access sprite of a gameobject 1 Answer