- Home /
C#, Problem with If Statements and GO Position Comparisons.
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);
}
}
}
code seems okay. try looking at what's going on in the animation state machine. make sure transitions have their conditions correct. don't forget that mecanim will use the first transition that fulfills all conditions, meaning sometimes you have to add an explicit condition along the lines of "and this other parameter is false", to prevent mecanim going there, even if some other transition has more conditions and fulfills all of them.
Answer by czanesimmons · Jan 14, 2019 at 04:36 AM
I finally figured it out! difX and difY were being defined in Start, but it never updated those starting values. All I had to do was move those two lines into the if(dMan.dialogueActive) statement!
So:
Update()
{
if(dMan.dialogueActive)
{ difX = transform.position.x - dialogueTarget.position.x;
difY = transform.position.y - dialogueTarget.position.y;
LookInDirection();
}
}
Thanks so much for the help! (and sorry for the accidental triple post xD)
OHHH, WOW. I am so, SO sorry... I should have noticed that right away. No thanks necessary, as I wasn't helpful at all. Shame on me :-/ please downvote my previous comment, as I can't do it myself even though I fully deserve it.
Your answer
Follow this Question
Related Questions
Sprite image not changing 0 Answers
Unable to make 2D enemy zigzag : Top Down View 1 Answer