why collision between two moving objects on pygame dont work?

耗尽温柔 提交于 2021-02-10 05:13:46

问题


I am doing a snake game(there is two snakes on the game) with pygame and i want to detect when the snake head collides with the another snake body, do that for both and a special case when the both heads collides, im doing currently the collision between the snake head and the other snake body, it works fine if one of the snakes is frozen and the other is moving, but if both is moving the collision just dont work heres the code that moves the snakes:

new_pos = None
        if direction == 'DOWN':
            new_pos = (snake[0][0], snake[0][1] + size)
        if direction == 'UP':
            new_pos = (snake[0][0], snake[0][1] - size)
        if direction == 'LEFT':
            new_pos = (snake[0][0] - size, snake[0][1])
        if direction == 'RIGHT':
            new_pos = (snake[0][0] + size, snake[0][1])
        if new_pos:
            snake = [new_pos] + snake
            del snake[-1]

keep in mind that the code that movements the other snake is the same but snake turns into snake2, new_pos into new_pos2, etc

collision code:

if snake2[0] in snake[1:]:
            gameOverBlue()

if snake2[0] in snake[1:]:
            gameOverRed()

edit: i figured I should put the code that makes the snake too:

#snake
    size = 15
    s_pos = 60
    snake = [(s_pos + size * 2, s_pos),(s_pos + size, s_pos),(s_pos, s_pos)]
    s_skin = pygame.Surface((size, size))
    s_skin.fill((82,128,208))
#snake2
    size2 = 15
    s2_pos = 195
    snake2 = [(s2_pos + size2 * 2, s2_pos),(s2_pos + size2, s2_pos),(s2_pos, s2_pos)]
    s2_skin = pygame.Surface((size2, size2))
    s2_skin.fill((208,128,82))

回答1:


You need to evaluate whether the head of snake is in the list snake2, including the head of snake2:

if snake[0] in snake2:
    gameOverBlue()

and if the head of snake2 is in snake:

if snake2[0] in snake:
    gameOverRed() 

If you want to detect if the heads of the snakes are colliding the you have to compare snake[0] and snake2[0] separately:

if snake[0] == snake2[0]:
    print("heads are colliding")

if snake[0] in snake2[1:]:
    gameOverBlue()
if snake2[0] in snake[1:]:
    gameOverRed() 


来源:https://stackoverflow.com/questions/64539458/why-collision-between-two-moving-objects-on-pygame-dont-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!