Hi guys, I’m working on a 2D rpg, and I’m trying to write a script to be held by an NPC that’ll trigger a directional animation based on where the player (dialogueTarget) is on interaction. It works perfectly along the X axis, but if you interact with the NPC from above or below, it will just play an X axis animation (left or right, depending on which dialogueTarget is closest to.)
I wrote the script from scratch, so it’s entirely possible I went about this all wrong.
I have a feeling there might be something wrong with how the If statements are structured in LookInDirection();
Could you guys take a look and let me know what you think?
private Animator anim;
private DialogueManager dMan;
private float difX;
private float difY;
public Transform dialogueTarget;
Start();
{
anim = GetComponent<Animator>();
dMan = FindObjectOfType<DialogueManager>();
difX = transform.position.x - dialogueTarget.position.x;
difY = transform.position.y - dialogueTarget.position.y;
}
Update();
{
if(dMan.dialogueActive)
{
LookInDirection();
}
}
LookInDirection();
{
if(Mathf.Abs(difX) < Mathf.Abs(difY))
{
if(transform.position.y < dialogueTarget.position.y)
{
anim.SetFloat("x", 0);
anim.SetFloat("y", 1);
}
else if(transform.position.y > dialogueTarget.position.y)
{
anim.SetFloat("x", 0);
anim.SetFloat("y", -1);
}
}
if (Mathf.Abs(difX) > Mathf.Abs(difY))
{
if(transform.position.x < dialogueTarget.position.x)
{
anim.SetFloat("x", 1);
anim.SetFloat("y", 0);
}
else if(transform.position.x > dialogueTarget.position.x)
{
anim.SetFloat("x", -1);
anim.SetFloat("y", 0);
}
}
}