• Advertisement
Sign in to follow this  

Bounding Box Collision Glitching Problem (Pygame)

This topic is 1336 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

So far the "Bounding Box" method is the only one that I know. It's efficient enough to deal with simple games. Nevertheless, the game I'm developing is not that simple anymore and for that reason, I've made a simplified example of the problem. (It's worth noticing that I don't have rotating sprites on my game or anything like that. After showing the code, I'll explain better).

Here's the whole code:

from pygame import *

DONE = False
screen = display.set_mode((1024,768))
class Thing():
    def __init__(self,x,y,w,h,s,c):
        self.x = x
        self.y = y
        self.w = w
        self.h = h
        self.s = s
        self.sur = Surface((64,48))
        draw.rect(self.sur,c,(self.x,self.y,w,h),1)
        self.sur.fill(c)
    def draw(self):
        screen.blit(self.sur,(self.x,self.y))
    def move(self,x):
        if key.get_pressed()[K_w] or key.get_pressed()[K_UP]:
            if x == 1:
                self.y -= self.s
            else:
                self.y += self.s
        if key.get_pressed()[K_s] or key.get_pressed()[K_DOWN]:
            if x == 1:
                self.y += self.s
            else:
                self.y -= self.s
        if key.get_pressed()[K_a] or key.get_pressed()[K_LEFT]:
            if x == 1:
                self.x -= self.s
            else:
                self.x += self.s
        if key.get_pressed()[K_d] or key.get_pressed()[K_RIGHT]:
            if x == 1:
                self.x += self.s
            else:
                self.x -= self.s
    def warp(self):
        if self.y < -48:
             self.y = 768
        if self.y > 768 + 48:
             self.y = 0
        if self.x < -64:
             self.x = 1024 + 64
        if self.x > 1024 + 64:
             self.x = -64
r1 = Thing(0,0,64,48,1,(0,255,0))
r2 = Thing(6*64,6*48,64,48,1,(255,0,0))
while not DONE:
    screen.fill((0,0,0))
    r2.draw()
    r1.draw()
    # If not intersecting, then moves, else, it moves in the opposite direction.
    if not ((((r1.x + r1.w) > (r2.x - r1.s)) and (r1.x < ((r2.x + r2.w) + r1.s))) and (((r1.y + r1.h) > (r2.y - r1.s)) and (r1.y < ((r2.y + r2.h) + r1.s)))):
        r1.move(1)
    else:
        r1.move(0)
    r1.warp()
    if key.get_pressed()[K_ESCAPE]:
        DONE = True
    for ev in event.get():
        if ev.type == QUIT:
            DONE = True
    display.update()
quit()

The problem:

 

In my actual game, the grid is fixed and each tile has 64 by 48 pixels. I know how to deal with collision perfectly if I moved by that size. Nevertheless, obviously, the player moves really fast.

In the example, the collision is detected pretty well (Just as I see in many examples throughout the internet). The problem is that if I put the player to move WHEN IS NOT intersecting, then, when it touches the obstacle, it does not move anymore. Giving that problem, I began switching the directions, but then, when it touches and I press the opposite key, it "glitches through". My actual game has many walls, and the player will touch them many times, and I can't afford letting the player go through them.

The code-problem illustrated:

 

When the player goes towards the wall (Fine).

 

PisxG.jpg

 

When the player goes towards the wall and press the opposite direction. (It glitches through).

 

o3oIs.jpg

 

Here is the logic I've designed before implementing it:

 

Ddlez.jpg

I don't know any other method, and I really just want to have walls fixed in a grid, but move by 1 or 2 or 3 pixels (Slowly) and have perfect collision without glitching-possibilities. What do you suggest?

Edited by EricsonWillians

Share this post


Link to post
Share on other sites
Advertisement

Disclaimer: I just woke up, my brain might not have fully started yet.

 

I think this isn't due to your intersection test, but due to your movement logic.

Consider what happens if you are intersecting (i.e. fail the intersection test), and you attempt to move right.

 

Intersect is true, so move(0) will be called.

K_Right is pressed.

x is not 1, so you will subtract the speed.

 

Result: You go left.

 

While there are probably more elegant solutions (see disclaimer above), I do have a suggestion which I believe will work in your case.

Note that if movement speed is too high (if you move more than a wall's dimensions) you'll go through.

 

Do the movement, then check for intersection. If there was intersection, clamp your position based on the intersected object's dimensions.

Share this post


Link to post
Share on other sites

Thank you very much for your answer lactose. I think I understood what you mean. I'll try to apply it in this test-code. In my actual game, I gave up this idea. Way too much headache. Instead, I'm moving by 64w and 48h pixels. I could not do this because of the speed of the movement, but then I've found a decent solution to the problem in this question of gamedev.stackexchange.

 

I'm using a "cooldown" logic based on the clock.tick() at each frame. The movement is not as smooth as if I was moving by 1 or 3 pixels each (Of course), but the collisions are perfect and I can move through my maze, touching the walls randomly without having to worry myself.

Share this post


Link to post
Share on other sites

Really, you should separate your actual moving of the object from checking the input.

 

What I mean is, instead of calling only Move, call HandleInput() on your Thing() class (for the player only, obviously), then call move.  In HandleInput(), check for key presses, and set the Thing's velocity to speed*(Keypress Idrection).  In Move, you test: if the object is moved by velocity, does it intersect?  If so, don't change the object's location, otherwise, go ahead and change the object's location and continue.

 

In pseudocode

HandleInput():
  # reset velocity since we don't know key states
  self.Velocity = 0
  if KeyPressed(MOVE_UP):
    self.Velocity.y = -self.Speed
  if KeyPressed(MOVE_RIGHT):
    self.Velocity.x = self.Speed

  if KeyPressed(MOVE_DOWN):
    self.Velocity.y = self.Speed

  if KeyPressed(MOVE_LEFT):
    self.Velocity.x = -self.Speed
 
Move():
  self.x += self.Velocty.x
  self.y += self.Velocity.y
  # This would check against all other Thing's in the world
  If (IsIntersectingWithOtherObjects(self):
    # it's hit something, move it back to where it was
    self.x -= self.Velocity.x
    self.y -= self.Velocity.y


 

If you were making a platformer type game, I'd suggest you split the move and test intersecting checks by changing x, then testing, and then changing y and testing.  That way, if only the x intersects, you don't stop both x and y movements.

Share this post


Link to post
Share on other sites

Keep in mind that if you do that, with large velocities, you can end up with never being able to get very close to a wall. E.g. if there's a 20 unit gap, and your movement speed is 25 units, moving towards the collision thing will make you stay at that 20 gap distance, instead of closing the gap and touching the wall.

 

Other than that, I agree with splitting input handling and movement logic.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement