Consider this scenario: you have an arrow sprite that can point left or right. You often need to switch it from left to right (e.g. after an object collides with it), so you give it a variable ‘direction’ which is either ‘left’ or ‘right’. Here’s what the switching code might look like:
Condition: Object collides with Arrow
Action:
Condition: Variable 'direction' of Arrow is = 'left'
Action: Do 'right' to variable 'direction' of Arrow
Condition: Variable 'direction' of Arrow is = 'right'
Action: Do 'left' to variable 'direction' of Arrow
You also want to give the arrow a random direction when it’s first created. Here’s how that might look:
Condition: At the beginning of the scene
Action: Do = Random(1) to scene variable initial_direction
Condition: Scene variable 'initial_direction' is = 0
Action: Do 'left' to variable 'direction' of Arrow
Condition: Scene variable 'initial_direction' is = 1
Action: Do 'right' to variable 'direction' of Arrow
Now that code (should) work, but it’s cumbersome and repetitive. Here’s what I believe is a simpler solution…
Use integers for left and right; -1 being left and 1 being right. When you want to switch direction, simply multiply the current direction by -1. Example: if the arrow is facing left (-1), when you multiply by -1 you get 1 (right). And if the arrow is facing right (1), when you multiply by -1 you get -1 (left). This also has the benefit of matching the x and y coordinate system GDevelop uses (so it’s easy to make objects move in the given direction just by multiplying the direction integer by an amount (negative amounts move left and positive amounts move right (the same can be used for up and down too!)))
As for choosing an initial direction randomly, you can’t just do
RandomInRange(-1, 1)
as 33.33% of the time you’ll get 0 (and then have to re-calculate the random value and that just adds more code). Instead, use
(Random(1) * 2) - 1
That gives a random number (0 or 1, with a 50/50 chance of either), which you then multiply by 2 (so 0 stays 0 and 1 becomes 2), and then you subtract 1 (so 0 becomes -1 and 2 becomes 1).
Using these ideas, here’s how the above code can be simplified:
Condition: Object collides with Arrow
Action: Do *-1 to variable 'direction' of Arrow
Condition: At the beginning of the scene
Action: Do = (Random(1) * 2) - 1 to variable 'direction' of Arrow
I love finding elegant solutions to problems, so thought to share this in the hope that it helps someone else too