GameMaker: Pointing to an off-screen object


Illustration

This intermediate example demonstrates, how to create a rather nice interface element being an arrow that points between a on-screen object (normally player) and a off-screen location, that needs to be reached. In this case, arrow indicates exact direction to target, and is made to clamp accurately to screen edges (preserving direction vector), to avoid confusion on behalf of player.
Such feature is specifically useful for exploration games, where goal(s) may be at different distance from player, and some guidance is required.

Download

Source code follows,

var sx, sy, tx, ty, dx, dy, mx, my, vx, vy, vl;
sx = src.x; sy = src.y // source position
tx = dst.x; ty = dst.y // destination position
dx = tx - sx; dy = ty - sy // difference
vl = sqrt(dx * dx + dy * dy) // distance
if (vl != 0) {
    vx = dx / vl; vy = dy / vl
} else {
    vx = 0; vy = 0;
}
if (vl > inner * 2) {
    vl -= inner
    image_alpha = 1
} else {
    image_alpha = max(0, (vl - inner) / inner)
    vl /= 2
}
image_angle = point_direction(sx, sy, tx, ty)
if (vy < 0) {
    vl = min(vl, ((view_yview + pad) - sy) / vy)
} else if (vy > 0) {
    vl = min(vl, ((view_yview + view_hview - pad) - sy) / vy)
}
if (vx < 0) {
    vl = min(vl, ((view_xview + pad) - sx) / vx)
} else if (vx > 0) {
    vl = min(vl, ((view_xview + view_wview - pad) - sx) / vx)
}
x = sx + vx * vl
y = sy + vy * vl

Where src is source object (usually, player); dst is destination object (exit, etc.), pad is distance between the pointing object and view borders, and inner is the distance to goal under which the pointing object should start to fade out.

It to be put into Step\End Step event.

Related posts:

7 thoughts on “GameMaker: Pointing to an off-screen object

  1. Trying to do exactly what you have put in the code, by my code requires the arrow pointing to a background tile. This is because the map is randomly generated and the “exit” tile (that i want the arrow pointing to) is randomly placed when the backgrounds are being put down. Everytime i run your code, it gives me an error saying FATAL ERROR and pointing to the line of code

    tx = dst.x; ty = dst.y // destination position

    which for me is tx = background5.x ; ty = background5.y;

    • You can’t retrieve tile’ coordinates like that, but if you place the tile by your own code, you could store the position in a pair of global variables and use them instead.

Leave a Reply

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