- Home /
Vector 3 Angles
Is there a way for my player to detect if it's facing a specific tagged object this way? I know the script isn't correct, I just need a little assistance:
function OnControllerColliderHit(hit : ControllerColliderHit){
if(hit.collider.tag == "Scramble" && !controller.isGrounded && Vector3.Angle(hit.collider.tag == "Scramble".transform.forward, transform.position - hit.collider.tag.transform.position) < 45){
WallScramble();
}
}
Answer by robertbu · Jun 13, 2014 at 08:45 PM
You can calculate the angle this way:
var v = hit.transform.position - transform.position;
var angle = Vector3.Angle(v, transform.forward);
'angle' will be unsigned and be the angle between the forward of the character controller and the object. You'll have to define how great an angle means facing in the direction of the hit object. Note, depending on how you are using this, you may want to set v.y = 0.0 before calling Vector3.Angle() so that object height is taken out of the calculation.
Answer by paul_hayes · Jun 13, 2014 at 09:01 PM
There are two ways that I can think of. One is to check to see if the collision point is in front of the player character controller. But a better way might be to perform a Raycast using the forward direction of the player character, and seeing if you hit the object that was the character controller collided with.
function OnControllerColliderHit(hit : ControllerColliderHit){
var ray : Ray = new Ray (transform.position, transform.forward);
var rayHit : RaycastHit;
var isLookingAt : boolean = hit.collider.Raycast(ray,rayHit,100f);
if(hit.collider.tag == "Scramble" && !controller.isGrounded && isLookingAt){
WallScramble();
}
}