I’m making a 2D platformer, and I have multiple NPC’s sharing the same script. Basically, what I want to happen is that the NPC will face the direction where the player currently is. So when the player is on the left side of the NPC, the NPC will simply face left, and if the player goes to the right side of the NPC, the NPC will then face right. I did this by making a gameobject called “FaceRight” with a 2DBoxCollider on the right side of the NPC, and another one called “FaceLeft” with a 2DBoxCollider of its own, on the left side of the NPC.
The Script for that goes like this:
public class FaceRight : MonoBehaviour
{
void Awake()
{
flipFacingDirection = FindObjectOfType<FlipFacingDirection>();
}
FlipFacingDirection flipFacingDirection;
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.tag == "Player")
{
flipFacingDirection.FlipSpriteX(true);
}
}
}
public class FaceLeft : MonoBehaviour
{
void Awake()
{
flipFacingDirection = FindObjectOfType<FlipFacingDirection>();
}
FlipFacingDirection flipFacingDirection;
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.tag == "Player")
{
flipFacingDirection.FlipSpriteX(false);
}
}
}
That will then call the FlipFacingDirection script I made, which simply toggles the flip boolean on the sprite renderer.
Here’s that script:
public class FlipFacingDirection : MonoBehaviour
{
// Reference to the SpriteRenderer component
[SerializeField] SpriteRenderer spriteRenderer;
// void Awake()
// {
// // Get the SpriteRenderer component attached to this GameObject
// spriteRenderer = GetComponent<SpriteRenderer>();
// }
// Function to flip the sprite horizontally
public void FlipSpriteX(bool flip)
{
spriteRenderer.flipX = flip;
}
}
Works perfectly fine! But the problem is, if I make another NPC game object and give it the same scripts, it goes wrong as theyre affecting each other. For instance, NPC A’s BoxCollider Trigger, will flip NPC B instead of A.
If I may add, I won’t be coding or doing game dev long term, I simply want this to work for this project so I can finally finish it, as I will move on to different things soon! With that in mind, please set aside “good coding practices” when giving feedback. Much Appreciated!
