Path Finding Help

J. Baker

Member
I haven't used GMS in some time now. How do I click on the screen and make the player move to that point while avoiding walls?

Thanks!
 

J. Baker

Member
Not much. Just started. Square walls and a square player. Generic graphics for testing purposes, basically.
 

woods

Member
this will get you pointed in the right direction at least...

first hit on google search "gml click to move"



global left pressed
Code:
xx = mouse_x;
yy = mouse_y;
create
Code:
enum mouse
{
    none
}

xx = mouse.none;
yy = mouse.none;

spd = 4;
step
Code:
if (xx != mouse.none && yy != mouse.none)

{
    move_towards_point(xx, yy, spd);
}
else
{
    speed = 0;   
}

if (distance_to_point(xx, yy) < spd + 2)
{
    xx = mouse.none;
    yy = mouse.none;
}
 

J. Baker

Member
Thanks for the reply and code but its the avoiding of walls (path finding) to the point of the mouse click that I need to figure out. ;)
 

J. Baker

Member
Thank you. That does work but with an issue. It gets confused for complex walls/solids but if you keep your walls simple it works fine. Will keep working on this. Thanks for the help!
 
I have a series of tutorials on procedural generation that incorporates pathfinding into them, you can check it out in my signature. That being said, pathfinding is a complex topic and there's no "one size fits all" solution. But maybe you'll be able to get some ideas from what I've written/linked.
 

J. Baker

Member
Ok, I got it with the following but Player1 overlaps the walls when moving around them. I made both Player1 and the Wall solid. I guess I need some kind of collision check or offset.

:EDIT
Removed code for the better one below.
 
Last edited:

J. Baker

Member
Finally, this one has no memory leak and is simple to use. Events and code for "Player" object.

Create
GML:
gs = 32; // Grid size.

global.grid = mp_grid_create(0, 0, room_width / gs, room_height / gs, gs, gs);
mp_grid_add_instances(global.grid, Wall, false); // We avoid the Wall object.

xx = Player.x;
yy = Player.y;

path = path_add(); // We add a path so when we left click, there's one to destroy. Solves memory leak.

// This has nothing to do with the code but how the "Player" functions on the path.
// The "Player" sprite was edited to have a origin of center.
// Now the "Player" object will not overlap the wall when following the path.
Glob Left Pressed
GML:
if path_exists(path)
{
path_delete(path); // Lets delete the old path. We don't need any memory leaks.
}

xx = mouse_x;
yy = mouse_y;

path = path_add(); // Now lets create a new path on left click.

if mp_grid_path(global.grid, path, Player.x, Player.y, xx, yy, 1)
{
    path_start(path, 2, path_action_stop, 0);
}
 
Last edited:
Top