Enemy Directions

I reversed the direction by multiplying the y-axis on the distance variable by -1 and inputting it as the new value (so whether it is -1 or 1 it will change to the opposite when multiplied by -1). It’s nice to see the introduction of the select node, but I found it unnecessarily complex to check which way it is going.
I renamed the distance variable to movementDirection as it made more sense to me, sorry if it adds confusion.

1 Like

Well done.

It may surprise you, but it is actually ‘unnecessarily complex’ to multiply the value by -1 to change direction, even if it is the way most seasoned developers would do it. You will find countless lectures here that will use

private void OnCollisionEnter2D(Collider2D collision)
{
    if (movementDirection == 1)
    {
        movementDirection = -1;
    }
    else
    {
        movementDirection = 1;
    }
}

over

private void OnCollisionEnter2D(Collider2D collision) => movementDirection *= -1;

I think this may simply be for understanding and better readability and with visual graphs this may even be more true since it can become quite harrowing trying to untangle connectors and nodes to figure out exactly what is happening.

Not saying you’re wrong, though. Multiplying by -1 is the way I would personally do it, too

I see your point. I did the change because it made more sense to me, but often it is difficult to know if a favored approach is intuitive to others or even your future self. What we really want is a way to easily switch between exactly to possible directions. It goes either up or down, so if it goes one way choose the other.
A switch statement could do it, but I don’t know if that’s possible in visual scripting… and if statements have the added benefit of being far easier to read and intuit.

switch(movementDirection)
{
case 1:                                       //is it 1?
        movementDirection = -1;   //then change it to -1
        break;                                //and don't try any more cases
case -1:                                     //is it -1?  
        movementDirection = 1;    //then change it to 1 
        break;                                //and don't try any more cases
default:                                      //for all other cases
        movementDirection = 1;    //correct the direction to 1
        break;                                //and don't try any more cases
}

I think I have this bad habit of overcomplicating things, when I’m trying to clarify them.

I used this “multiply the whole vector by -1 approach”, too and it works.

But the vectors x,y and z values are all multiplied by -1. That is ok here, because x and z are both 0, but you have the effect, that an item changes x-direction (and z-direction) too, what you do not want, if it collides with a wall at an angle different from 90°.

Privacy & Terms