Page 1 of 1
Make 2D character face player
Posted: Wed Nov 27, 2019 8:09 am
by artbygp
Hello Toni, I am trying to figure out how to make an NPC turn directly towards the player. I am making a 2d top-down game so perhaps there is another way instead of using LookAt(). I gave it a shot, but the NPC disappears, and I am thinking its meant for 3D only.
BTW, I had the liberty to buy Code Complete, and I am blown away by the magnitude and knowledge I am absorbing from the book. I didn't know software architecture is so important. Thank you again for your advice.
Re: Make 2D character face player
Posted: Wed Nov 27, 2019 9:18 am
by Tony Li
Hi,
You're correct that LookAt() is meant for 3D. It rotates the transform in 3D to face another 3D position.
You can write a
custom sequencer command or, if you always want the NPC to face the player, you can give the NPC a script with an
OnConversationStart method. In the OnConversationStart method, make the NPC face the player.
If your 2D character only faces left or right, check if the player is to the left of the NPC -- for example: player.position.x < npc.position.x. If so, make sure the 2D character is facing left. This depends on how you're handling the NPC's direction. If you're flipping the SpriteRenderer's X value from right to left, for example:
Code: Select all
GetComponent<SpriteRenderer>().flipX = true;
If you're flipping the X scale between 1 and -1, for example:
Code: Select all
transform.localScale = new Vector3(-1, 1, 1);
And do something similar if the player is to the right of the NPC.
If your 2D character faces more directions, such as up/down/left/right, or 8 directions, then you'll need to use a little more logic to decide which is the best direction to face.
Re: Make 2D character face player
Posted: Thu Nov 28, 2019 6:47 am
by artbygp
Thank you, Toni. I will give this a shot.