GMS 2 Making an object spawn and move to 1 of 3 places

J

Jason Pickel

Guest
Hello. So I'm making a platformer, and I've been having an issue with this one part where I'm trying to get an object to randomly go to 1 of 3 areas and turn into something else.

I've been using this code, and it works relatively well, aside from that sometimes the object spawns and stays there, and when the object goes to the 3rd spot, it spawns a bit under where the others do.

if irandom_range(0,2) = 0
{
move_towards_point(obj_spawn.x, obj_spawn.y, spd);
}
else
if irandom_range(0,2) = 1
{
move_towards_point(obj_spawn2.x, obj_spawn2.y, spd);
}
else
if irandom_range(0,2) = 2
{
move_towards_point(obj_spawn3.x, obj_spawn3.y, spd);
}

If anybody has any thoughts on how I could fix this, or how amateur it is, I'd love the feedback
Thank you!
 

jo-thijs

Member
Hello. So I'm making a platformer, and I've been having an issue with this one part where I'm trying to get an object to randomly go to 1 of 3 areas and turn into something else.

I've been using this code, and it works relatively well, aside from that sometimes the object spawns and stays there, and when the object goes to the 3rd spot, it spawns a bit under where the others do.

if irandom_range(0,2) = 0
{
move_towards_point(obj_spawn.x, obj_spawn.y, spd);
}
else
if irandom_range(0,2) = 1
{
move_towards_point(obj_spawn2.x, obj_spawn2.y, spd);
}
else
if irandom_range(0,2) = 2
{
move_towards_point(obj_spawn3.x, obj_spawn3.y, spd);
}

If anybody has any thoughts on how I could fix this, or how amateur it is, I'd love the feedback
Thank you!
Hi and welcome to the GMC!

The function irandom_rang will prouce a new result every time you call it,
so you generate up to 3 random numbers in that piece of code, whereas you only meant to produce 1.

Using a switch-structure would solve this issue:
Code:
switch irandom_range(0,2) {
case 0:
    move_towards_point(obj_spawn.x, obj_spawn.y, spd);
    break;
case 1:
    move_towards_point(obj_spawn2.x, obj_spawn2.y, spd);
    break;
case 2:
    move_towards_point(obj_spawn3.x, obj_spawn3.y, spd);
    break;
}
There is however an even nicer solution in your case: using arays:
Code:
var targets = [obj_spawn, obj_spawn2, obj_spawn3];
var target = targets[irandom(array_length_1d(targets) - 1)];
move_towards_point(target.x, target.y, spd);
 

Guitarmike

Member
What jo-thijs said. Plus, watch out for this:

Code:
if irandom_range(0,2) = 0
use == not =. Why? In many programming languages = functions as an assignment operator. "if x = 5" will actually change x to the value of 5 and return true, even if x's value started out as something else. GML is not one of these languages but it's a good habit to develop using the unambiguous comparison operator "=="
 
Top