Making draggable objects collide with walls


Dennis Wiklund


I have tried a lot of ways of getting a specific game-mechanic to work and i cant for the life of me figure it out.

Heres the thing.
I want a game were you as a player drag your character over the screen with the mouse (later touch with ios).
Just like this:

The idea is that when the character is released he will fall to the ground and stay there.
My problem is that I can't figure out a smart way to make it collide with walls (during drag). I dont want the player to drag the object through walls or obstacles.

I can make it so when the character hits the wall it falls down and gets disconected from the mouse-cursor. But i want it wo slide along the walls of the cursor is on the other side of the wall.

I tried using physics, but that doesnt work since i have to set:
phy_position_x = mouse_x;
and this overwrites the collission.

Any good ideas of how to get this working?

(Sorry for bad eng, i did not pay attention in school obviusly).

Last edited by a moderator:


Have the character move dependant on the delta of the mouse, for example:

var dx, dy, r;

dx = mouse_x - mouse_xprev;
dy = mouse_y - mouse_yprev;
r = 8; //Makes sure the mouse is nearby when moving the character

if(abs(mouse_x - char.x) < r){char.x += dx;}
if(abs(mouse_y - char.y) < r){char.y += dy;}

mouse_xprev = mouse_x;
mouse_yprev = mouse_y;
Now, you can use collision_line(...), collision_point(...), or even collision_rectangle(...) to check for collision before moving the character, and don't when there is a collision. Such as:

if(abs(mouse_x - char.x) < r && !collision_line(char.x, char.y, char.x + dx, char.y, solid, false, true))
char.x += dx;


Also, if your character already has collision detection routines you could exploit those too. Set the dx and dy in Quackertree's code to character's vspd and hspd (or whatever your code calls the x and y deltas) and let your movement & collision checking handle the rest. Your code however may need some changes so it doesn't mess up values that have been set from external source.