Movement question

D

dupe you

Guest
I have this so far in the step event.

How come the else { speed = 0 } doesn't need to be placed after every keyboard_check for the instance to stop moving & why does it only work when placed after the first if statement?

It works how I wanted it to, yet I'm failing to understand the logic.
if (keyboard_check(vk_left))
{
move_towards_point(x-1,y,4)
}
else { speed = 0 }
if (keyboard_check(vk_right))
{
move_towards_point(x+1,y,4)
}
if (keyboard_check(vk_up))
{
move_towards_point(x,y-1,4)
}
if (keyboard_check(vk_down))
{
move_towards_point(x,y+1,4)
}
 
I'm going to take a whack at answering this cause I'm curious to see if I get it right.

The keyboard_check is already a temporary function making your else statement moot. When the keyboard_check(vk_left) is no longer active, it sets it back to 0 and your movement stops.
Does it still work without the "Else" statement even being there?
 
D

dupe you

Guest
Without the else statement the instance continually moves in the last direction that the keyboard_check issued.
 

Nidoking

Member
That's an... interesting way to do it. Your logic is faulty, but the result achieves what you wanted to achieve. That said, fix it. Accidental correctness in programming is a problem waiting for you to turn your back on it so it can break and you'll never find it because you KNOW this was working before.

Here's what's happening:
If you're holding left, it goes left. Presumably, you're not holding any other directions at the same time, so the remaining checks fail and going left wins the day.
If you're not holding left, it stops. Then, it has three more checks for the other directions. Again, the last one in the list that's being held will be the direction you go. If all of the checks fail, then stopping was the last movement thing it did, so it will stop.

What you SHOULD do is use the various checks in combination to determine the direction of movement, if any, and have a single line for movement in that direction, or stop if the result of all of the checks is no movement.
 
Top