- Home /
How to check in which direction an object is facing?
Hi,
I want to be able to check whether an object is looking at another object. Any ideas on how to do this would be great.
Thanks
Answer by Griffo · Oct 03, 2012 at 04:09 PM
Use something like below, where on the global script the var rayCastHitName holds the result of the ray cast.
private var globalVars : GameObject; // Referance to the GameObject with the GlobalVars on
private var hit : RaycastHit;
function Awake(){
globalVars = GameObject.Find("Global Vars"); // Find the gameObject with the GlobalVars.js attached to it
}
function Update(){
if (Physics.Raycast (transform.position,transform.forward,hit, 10)) {
globalVars.GetComponent(GlobalVars).rayCastHitTag = hit.collider.gameObject.tag;
}
}
Answer by Griffo · Oct 03, 2012 at 02:44 PM
Use a ray cast http://docs.unity3d.com/Documentation/ScriptReference/Physics.Raycast.html then check to see if it hits the player
if(hit.collider.gameObject.tag == "Player"){
Or use print to see what its hitting
print("Can not see you " + hit.collider.gameObject.name + " in the way");
Thanks for the reply, Griffo.
Well the objects I'm using don't have colliders and are simply Transforms. I was wondering if there's possibly a way this could be achieved using something similar to;
if(obj1.TransformDirection(obj2.position) == true)
Great - I think I'll use this method then and add the colliders onto the objects. $$anonymous$$y other question is, do you know how to project a ray from an object that isn't the object the script is attached to? I have it stored in a global variable so have access to it already. Then be able to use the line you have above: if(hit.collider.gameObject.tag == "Player")
Your answer
![](https://koobas.hobune.stream/wayback/20220613081825im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to change use transform.LookAt to make the bottom of an object look at something? 0 Answers
Make object face center of circle without flipping in 2D space. 0 Answers
How to snap a model to the direction being moved in, without also rotating the character controller 3 Answers
Moving while facing the camera 0 Answers