- Home /
LookAt() doesn't really do what I want
Hey guys :D
I'm making an action RPG game and of course, I have enemies. When I walk in their sight, I call the lookAt function and make it look to the target inside my player. That part works, but if I turn, the enemy also turns and then basically moonwalks towards me and only faces me if I look at him. What should I do? (It's probably something really stupid I'm overlooking ;/)
this is the code I have for it:
void OnTriggerStay(Collider other)
{
if (other.CompareTag("Player") && !enemyHP.isDead)
{
transform.LookAt(transform.position + player.transform.rotation * Vector3.forward, player.transform.rotation * Vector3.up);
Vector3 direction = other.transform.position - transform.position;
if (Physics.Raycast(transform.position, direction.normalized, out hit))
{
if (hit.collider.gameObject == player)
{
if (hit.distance <= 9 && hit.distance > 2.5f)
{
ai.Chase();
attack = false;
}
else if (hit.distance <= 2.5f)
{
ai.Attack();
attack = true;
}
else
{
ai.Idle();
attack = false;
}
}
}
}
}
Hope you guys can help me
Answer by NoseKills · Aug 07, 2016 at 09:30 AM
You have a pretty complicated formula where you factor in the player's rotation when setting the look direction of the enemy.
transform.LookAt(transform.position + player.transform.rotation * Vector3.forward, player.transform.rotation * Vector3.up);
All that's required should be to set it to look at the player position (how the player is rotated shouldn't be factored into the equation of where the enemy should look, unless there's some requirement you didn't tell about)
transform.LookAt(player.transform.position);
Hey @Nose$$anonymous$$ills,
I use this calcuation, because this guy is is always backwards without it. Does it maybe have to do something with the canvas I put in the enemy?
thanks for reacting man.
I checked it, it always faces the other way if I use any other calculation
The documentation is pretty clear. You can make it look at a world position or another transform so either
transform.LookAt(player.transform.position);
or just
transform.LookAt(player.transform);
should work.
If this doesn't work, you should figure out what the external reason for this problem is.
If it's "always" looking in exactly the opposite direction, then the model is probably set up so that the nose of the model faces in the negative transform.forward direction. If that's so, it would be clearest to fix the model. If that's not possible, you can mirror the position of the LookAt() target to be in the opposite direction.
var toTarget = player.transform.position - transform.position;
var mirroredTarget = transform.position - toTarget;
transform.LookAt(mirroredTarget);
Thanks man, it worked
I put the model in an empty gameobject and the gameobject was okay, but I (for some reason) rotatd the model within the object