Collision detection on enemy with wall when there is none

1k views Asked by At

I am trying to develop basic enemy AI on a simple platformer game after following Shaun Spalding's gamemaker 2 platformer tutorials on youtube. My code is the exact same as his on the tutorial but for some reason, when my enemy detects collision with the wall he turns around as he is suppose to and then detects another collision where there is none, causing him to turn around again.

This is my code:

// Horizontal collision
if (place_meeting(x+hsp, y, oWall)) {
    show_debug_message(hsp)
    while (!place_meeting(x+sign(hsp), y, oWall)) {
        x += sign(hsp); // slows down I think
    }
    hsp = -hsp;
}

x += hsp; 

The -hsp part is where he turns around. Somehow, he is detecting another collision as soon as he does so, even though the value of hsp is inverted. Can anyone possibly point me in the direction of why this may be occuring?

(Value of hsp initialized at 3 and never changed only for inversion).

1

There are 1 answers

2
Steven On

Is it turning back to the wall after a short while, or is it stuck and is flickering to left and right rapidly? Both could involve that the collision point isn't updating well.

When I face with collision problems, I'll use a crosshair sprite, and draw it at the same position as where it should be colliding. that way I've a visible view of the 'collision point'.

Another cause could be the sprite's origin point, that determines at which position the x and y appears, and that the sprite by turning collides with the wall itself. Keep in mind that the origin point is at the center of it's collision mask, to avoid been stuck in a wall.

EDIT: Another possibility: the collision point still checks inside the sprite. For that, you could also try using an offset that keeps the collision point away from the sprite collision, but to let that work, you'll need to keep the inverse direction away from your horizontal speed. Something like this:

// Horizontal collision
_offset = 15; //moves the collision point away to check in front of the sprite. value depends on the size of the sprite.
_dir = 1; //the direction, should only be 1 or -1
          //hsp should no longer be used to inverse, use a new variable (like _dir) instead
collisionPoint = (hsp + offset) * _dir;
if (place_meeting(x + collisionPoint , y, oWall)) {
    show_debug_message(collisionPoint)
    while (!place_meeting(x+sign(collisionPoint), y, oWall)) {
        x += sign(collisionPoint); // slows down I think
    }
    _dir = -_dir
}

x += hsp * _dir;