Rafael Carmona
Rafael Carmona

Reputation: 61

Collision detection algorithm in python

I am writing a small game, consisting of a labyrinth, a player character and a set number of enemies. Both the PC and the enemies belong to a given class, and they update their movement every several milliseconds according to a criteria specified by me. (All of these restrictions are part of the assignment). Now, I am trying to write a criteria so that neither the enemies nor the PC will move to a square occupied by a labyrinth wall. For this, I used the following method (all of this within the Game class I am making):

def isNotWall(self,x,y):

        self.wallXI = 0
        self.wallXF = 0
        self.wallYI = 0
        self.wallYF = 0
        for wall in self.wallList:
            self.wallXI = wall[0]*self.grid + 1
            self.wallXF = (wall[0]+1)*self.grid
            self.wallYI = wall[1]*self.grid + 1
            self.wallYF = (wall[1]+1)*self.grid
            if self.wallXI < x < self.wallXF and self.wallYI < y < self.wallYF:
                return False


        return True

Where wallList is a list containing the x and y coordinates for every wall in array coordinates, and grid is the size of each grid square (32 pixels, in this case).

Now, for an example of how I implemented this:

if snake[1] > self.heroe_x:
            if self.isNotWall(snake[1] - 30,snake[2]):
                snake[1] = snake[1] - 30 * segundos

Where snake[1] is the x-coordinate in pixels, snake[2] is y, and segundos is how many milliseconds have passed, so that the enemy will move the appropriate number of pixels.

According to this, the snake (and the character) should not move in a certain direction if their location at the end of the movement is occupied by a wall. However, this only works partially, the behaviour is erratic, some walls only work in one direction, and often the characters get stuck inside walls or stopped cold for no reason.

Any help with fixing these flaws would be appreciated. I realize this question isn't very concise, but due to my inexperience with the language, I could not think of a way to make the question more specific, and no previous answers have helped me. Thanks in advance!

Upvotes: 3

Views: 1544

Answers (1)

Samy Arous
Samy Arous

Reputation: 6814

if you only check the final position, wouldn't the snake hit a wall if it's in the way. Say the wall is only 15 square from the snake?

Also, the snake is moving 30*segundos but you are only checking if there is a wall 30 square away

if snake[1] > self.heroe_x:
    next_position_x = snake[1] - (30 * segundos)
    if self.isNotWall(next_position_x,snake[2]):
        snake[1] = next_position_x

If I were you, I would implement a real path finding algorithm and make the walls passing cost infinite so that it will never cross one.

http://en.wikipedia.org/wiki/Pathfinding

Also check this library

http://lib2dp.sourceforge.net/

Upvotes: 1

Related Questions