为什么在pygame上两个运动对象之间的碰撞不起作用? [英] why collision between two moving objects on pygame dont work?

查看:67
本文介绍了为什么在pygame上两个运动对象之间的碰撞不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用pygame做蛇游戏(游戏中有两条蛇),我想检测出蛇头何时与另一个蛇体碰撞,对两者都进行检测,这是一个特殊的情况,当两个头都碰撞时,我目前正在做蛇头与另一条蛇的身体之间的碰撞,如果其中一条蛇被冻结而另一条正在移动,则可以正常工作,但是如果两条蛇都在移动,则碰撞不起作用这是移动蛇的代码:

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]

请记住,移动另一条蛇的代码是相同的,但是蛇变成了snake2,new_pos变成了new_pos2,等等

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

冲突代码:

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))

推荐答案

您需要评估 snake 的头是否在 snake2 列表中,包括snake2的头. snake2 :

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()

并且如果 snake2 的头部在 snake 中:

if snake2[0] in snake:
    gameOverRed() 

如果要检测蛇的头部是否碰撞,则必须分别比较 snake [0] snake2 [0] :

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() 

这篇关于为什么在pygame上两个运动对象之间的碰撞不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆