- Home /
Transform.LookAt Seems To Cause Issues
Hi all, I'm making a "following" script for an object to follow the player if they are within range/sight.
bool canSeePlayer () {
RaycastHit hit;
Vector3 rayDirection = player.position - transform.position;
float distanceToPlayer = Vector3.Distance( player.position, transform.position );
if(Physics.Raycast( transform.position, rayDirection, out hit)) {
if((hit.transform.tag == "Player") && (distanceToPlayer <= rearDetectionThreshold)){
//Debug.Log("PLAYER GOT TOO CLOSE");
return true;
}
}
if(Vector3.Angle(rayDirection, transform.forward) < fieldOfViewRange ) {
if(Physics.Raycast( transform.position, rayDirection, out hit)) {
//Debug.Log (hit.transform.tag + " " + distanceToPlayer.ToString());
if((hit.transform.tag == "Player") && (distanceToPlayer < frontDetectionThreshold)){
//Debug.Log("CAN SEE PLAYER");
return true;
}
else {
//Debug.Log("CAN'T SEE PLAYER");
return false;
}
}
}
return false;
}
void Update () {
if( canSeePlayer() ) {
//Debug.Log ("MOVE WOLF MOVE");
transform.LookAt(player);
transform.position = Vector3.MoveTowards(transform.position, player.position, .1f);
}
}
Should be pretty self-explanatory what the code does, uses rays and distances to determine if the player is seen or in range by the object the script is attached to (a cube in this case). It works just as intended, except when I use the transform.LookAt(player) line.
What happens then is that all of the sudden it stops being able to see the player after it changes its direction via lookat. So I'm just not sure what's happening. My line where I print the tag the ray is supposed to be hitting, I get untagged. Which is curious, my player character is definitely tagged as "Player" Again, no issues with the detection when I don't have the cube adjust its direction.
I don't know why it would be inconsistent.
try using Debug.DrawRay() to ensure your rayDirection is correct.
That's a useful thing; unfortunately it seems that the ray is "hitting" the player.
Debug.DrawRay(transform.position, rayDirection);
Is what you had in $$anonymous$$d right?
It draws a white line between my cube and player
Answer by Wuzseen · Dec 19, 2012 at 11:18 PM
So, in what amounts to basically the silliest thing ever, I had a small sphere as a child of my cube so I could tell what was the "front" of the object. This sphere had a collider on it, which messed up the Raycast.
Your answer
Follow this Question
Related Questions
Have An Object Rotate Around Transform A So That Transform B is Looking at Transform C (C#) 0 Answers
Object moves toward another object when close 2 Answers
How to make AI look at player 0 Answers
Rigidbody to follow player around 1 Answer
Move object along ray cast using object's AddForce or velocity but not transform 1 Answer