- Home /
How to check where a player is looking
I'm trying to make a script that will teleport a player to a location after checking to make sure the player is looking a certain direction.
For example, I want the player to be facing a texture that looks like a door, and then walk into the door which will teleport the player. Right now my problem is the player will get teleported if he just walks into the trigger while looking in any direction.
Here is the code I'm using right now:
var target : Transform;
function Update ()
{
}
function OnTriggerEnter (col : Collider)
{
if(col.gameObject.tag == "teleport")
{
Check();
}
}
function Check ()
{
if (Physics.Raycast (transform.position,transform.TransformDirection (Vector3.forward)))
{
this.transform.position = target.position;
}
}
I'm new to Javascript so, if it isn't too troubling, please explain what I need to do.
Thanks.
Answer by robertbu · Dec 18, 2013 at 12:31 AM
There are a few ways to approach this problem depending on what you mean by "Looking." One way is to have two collider, one is the trigger that is somewhere in front of the door, and the second collider would be on the door itself. Then you could code it this way:
function Check ()
{
var hit : RaycastHit;
if (Physics.Raycast (transform.position,transform.forward) && hit.collider.name == "Door")
{
this.transform.position = target.position;
}
}
This will check to make sure the forward vector of the character impacts the collider of a game object with the name 'Door'.
Answer by stevethorne · Dec 17, 2013 at 10:20 PM
You want to use transform.TransformDirection( transform.forward );
Edit: As a matter of fact, I'm fairly certain "transform.forward" is already in world space, so you wouldn't even need to use transform.TransformDirection.
Where do I put that at though? I replaced - if (Physics.Raycast (transform.position,transform.TransformDirection (Vector3.forward))) - and now its just - if (transform.TransformDirection( transform.forward )) - I'm sorry if this is a stupid question, but I'm still new to Unity and Java and don't quite understand it. Thanks.
I edited my answer:
if ( Physics.Raycast ( transform.position, transform.forward ) )
try this, if it's not in world space then you might have to use this:
if ( Physics.Raycast ( transform.position, transform.TransformDirection( transform.forward ) ) )