Game Development Reference
In-Depth Information
spd=random_range(1,8);
dir=choose(0,1);
dir2=choose(-1,1);
Now, we need to add a step event. Here, we will control the object's movement based on
the three variables we just initialized in the create event.
To start with, we need to check which direction the object is meant to move in. We do this
using an if statement to check the dir variable. If it is equal to 0, we execute our hori-
zontal movement code; if it is equal to 1, we execute our vertical movement code.
For the actual movement, we will be using dir2 to decide whether we should be moving
left, right, up, or down.
For this, we are going to use some simple math. Instead of having an if statement check
the value and add or subtract from the object's x value, respectively, we can shorten and
optimize our code just by adding to the x value.
By adding our speed variable multiplied by dir2 , the object will move left and right ac-
cording to the dir2 variable. This works because multiplying a value by 1 simply equals
the original value, but multiplying a value by a -1 equals negative the original number.
When we add a negative number to the x value of an object, we actually end up subtract-
ing from the x value. So, while dir2 is equal to 1, the object will move right; and then
when dir2 is equal to -1, the object will move left.
This is our step event code:
if (dir=0){ //horizontal
x+=spd*dir2;
}
if (dir=1){ //verticle
y+=spd*dir2;
}
As you can see, vertical is the same as horizontal, except we edit the y value of the object
instead of the x value.
The last thing we need to do is make the enemy change directions when it collides with a
wall. Add a collision event with the wall object and drag in a code block.
Search WWH ::




Custom Search