Make 2D character face player

Announcements, support questions, and discussion for the Dialogue System.
Post Reply
artbygp
Posts: 8
Joined: Thu Nov 14, 2019 12:51 pm

Make 2D character face player

Post 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.
User avatar
Tony Li
Posts: 22055
Joined: Thu Jul 18, 2013 1:27 pm

Re: Make 2D character face player

Post 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.
artbygp
Posts: 8
Joined: Thu Nov 14, 2019 12:51 pm

Re: Make 2D character face player

Post by artbygp »

Thank you, Toni. I will give this a shot.
Post Reply