# GMS 2 Help with object collision.

Discussion in 'Programming' started by Gasil, Mar 15, 2019.

1. ### GasilMember

Joined:
Mar 18, 2018
Posts:
55
This is the code I'm using for movement:

dir = 0;
dirFinal = 0;
dirX = x
dirY = y
Vel = 5 //Movement speed.
Vel2 = 3 //Rotation speed

Code:
```if(keyboard_check(ord("W")))
{
var xx = lengthdir_x(vel, dirFinal);
var yy = lengthdir_y(vel, dirFinal);
dirX += xx;
dirY += yy;
}

if(keyboard_check(ord("S")))
{
var xx = lengthdir_x(vel, dirFinal);
var yy = lengthdir_y(vel, dirFinal);
dirX -= xx;
dirY -= yy;
}

if(keyboard_check(ord("D")))
{
dirFinal -= vel2;
}

if(keyboard_check(ord("A")))
{
dirFinal += vel2;
}

dir = lerp(dir, dirFinal, 0.2);
x = lerp(x, dirX, 0.5);
y = lerp(y, dirY, 0.5);```
Could you help me to code some collisions using an object and a simple function like place_free or place_meeting? I tried it myself but I was just making my obj player to get stuck in the object; the lengthdir function is messing me up.

Thank you.

2. ### CloseRangeMember

Joined:
Jul 2, 2016
Posts:
693
Code:
```x = lerp(x, dirX, 0.5);
y = lerp(y, dirY, 0.5);```
change this to this:

Code:
```var o = obj_wall; // the object to collide with
var nx = lerp(x, dirX, 0.5); // the new x
var ny = lerp(y, dirY, 0.5);
var dx = sign(nx - x); // returns -1, 1, or 0 based on direction you are moving
var dy = sign(ny - y);

if(place_meeting(nx, y, o)) {
while(!place_meeting(x+dx, y, o))
x += dx;
nx = x;
}
if(place_meeting(x, ny, o)) {
while(!place_meeting(x, y+dy, o))
y += dy;
ny = y;
}
x = nx;
y = ny;```

3. ### GasilMember

Joined:
Mar 18, 2018
Posts:
55
Oooh it makes so much sense now D: Let me try it up, thank you!

4. ### GasilMember

Joined:
Mar 18, 2018
Posts:
55
Hello. I tried the code, it seems the collisions are working well, the player doesn't get stuck anymore, however, if I move towards an obj_wall and hold the movemenet key long enough, the player clips through to the other side and gets snapped in the opposite direction D: I'll fiddle with it a little to see if I adress that, but if you discover what's the issue please do let me know.

EDIT: I drew x and y on the screen, when the player stops by hitting a wall, pushing the keys still makes the X or Y to increment still until it excedes the object's position.