GameMaker: Orbiting


Interactive demo. Mouseover to activate, drag planets around.

This is an example of making an instance orbit around other instance in GameMaker.

In contrast to other similar examples (and commonly given advice of the kind), it allows to define orbiting speed in a common way (pixels/frame instead of degrees/frame).

This is accomplished by calculating the distance to orbit' center (from current position), calculating the orbit' length, and thus converting pixel speed to degree speed.

New position is then calculated and instance' speed is adjusted for it to reach it the next frame.
This allows to use direction in collision calculations as per usual.

Overall, the code is simple enough but documented regardless.

Download GMK

Code follows,

var cx, cy, crad, clen, cdir, cnext, nx, ny;
// retrieve variables for later use:
cx = obj_sun.x;
cy = obj_sun.y;
crad = point_distance(cx, cy, x, y);
// find "length" of circle:
clen = crad * pi * 2;
// find current angle on circle:
cdir = point_direction(cx, cy, x, y);
// find next angle on circle:
cnext = cdir + vel * 360 / clen;
// find coordinates of next point:
nx = cx + lengthdir_x(crad, cnext);
ny = cy + lengthdir_y(crad, cnext);
// set speed vector to reach that point in next step:
hspeed = nx - x;
vspeed = ny - y;

Where vel is the object's velocity (px/step) and obj_sun is the thing to orbit around.
Code is to be included in Step event.

Have fun!

Related posts:

3 thoughts on “GameMaker: Orbiting

    • In simplest case you would modify step event code to set next angle to be 270 + sin(t) * c (where “t” is changed over time and “c” is swing arc). For actual pendulum physics you would need to incorporate some extra code to handle velocity and acceleration while still modifying that “next angle” variable in the end. I believe that GameMaker Community forums did contain at least a couple of such examples.

  1. the problem is that in the GMC forums they all work by modifing de x y variables directly, instead of using hspeed and vspeed.
    And what do you mean by “swing arc”? is it the angle in that moment?

Leave a Reply

Your email address will not be published. Required fields are marked *