1
Hello, I’m developing a game in which the enemy follows the player to try to capture him. But he follows the player backwards, face back, or sideways. Is there any way that the enemy follows the player facing him?
void Awake ()
{
player = GameObject.FindGameObjectWithTag ("Player").transform;
playerHealth = player.GetComponent <PlayerHealth> ();
enemyHealth = GetComponent <EnemyHealth> ();
Enemy = GameObject.FindGameObjectWithTag ("Enemy");
nav = GetComponent <NavMeshAgent> ();
}
void Update ()
{
Enemy.transform.LookAt(player);
if(enemyHealth.currentHealth > 0 && playerHealth.currentHealth > 0)
{
nav.SetDestination(player.position);
transform.Rotate(player.position);
}
else
{
nav.enabled = false;
}
}
}
Enemy.transform.LookAt(player);
does just that. Only its objectEnemy
needs to have been built so that the front is correct. In Unity, the front isVector3.forward
, that the vector(0, 0, 1)
(i.e., the Z axis, from the source towards the camera). You need to check the modeling tool that used how it is exporting the axis of the object.– Luiz Vieira
I understood, but the Lookat is not working in any way, the way the enemy model starts it.
– Lucas Campanelli
Can you make a [mcve] that reproduces the problem? It can be another project, with a cube following another, if you do not want to share something of your own project. Then I can try to reproduce here to give you some hint.
– Luiz Vieira
Man, sorry it took me so long to respond, but I finally solved the problem. The component "Animator" that plays the animation of Enemy running and whatnot, was for some reason blocking the y-axis. What I did was, I created a Empty Game Object and put all the motion scripts etc... and inside put the Enemy template with only Animator. Thanks for the help!
– Lucas Campanelli
Ah, okay. The reason was very simple: if there is an animator being executed with changes in any property (either rotation, translation or scale), any external change will be ignored because in the next frame the animator will change that value again. That’s why what you did worked (and, in fact, it’s the right way when animation will be independent of external movement). :)
– Luiz Vieira
P.S.: I voted to close as "not to be reproducible", because there is a chance that this question is lost. But, if you create an answer explaining what happened and what you did to solve, I take the vote to close and still give you the +1 in the answer (depending on the quality of it, of course).
– Luiz Vieira