python - 碰撞检测程序在 Turtle 中不起作用

标签 python collision-detection turtle-graphics

当我运行该程序时,它卡住并且无法工作。该程序的要点是,当由键绑定(bind)控制的用户控制的 turtle 的 x 和 y 位置坐标与其他 turtle 的 x 和 y 位置坐标的距离小于 10 像素时,打印出一些内容。

import turtle
import random
wn = turtle.Screen()
wn.setup(width = 450, height = 450)
player = turtle.Turtle()
player2 = turtle.Turtle()

def up():

    y  = player.ycor()
    y = y + 5
    player.sety(y)
    if y>=310:
        player.sety(y-15)

def down():
    y = player.ycor()
    y = y - 5
    player.sety(y)
    if y<-310:
        player.sety(y+15)


def left():
    x = player.xcor()
    x = x - 5
    player.setx(x)
    if x<=-625:
        player.setx(x+15)


def right():
    x = player.xcor()
    x = x + 5
    player.setx(x)
    if x>=625:
        player.setx(x-15)

player.penup()
player.setpos(0,0)
player.showturtle()
player.shape("square")
wn.bgcolor("green")
player2.shape("square")
player2.penup()
player2.setpos(300,300)
player2.showturtle()

turtle.listen()
turtle.onkeypress(up,"Up")

turtle.onkeypress(left,"Left")

turtle.onkeypress(right,"Right")

turtle.onkeypress(down, "Down")


def checkcollision(player,player2):
        if abs(player.xcor() - player2.xcor()) < 10 and abs(player.ycor() - player2.ycor()) < 10:
            player.write("collision")


while True:
    checkcollision(player,player2)

最佳答案

我认为它卡住是因为代码中的循环:

while True:
    checkcollision(player,player2)

它总是检查碰撞,将该代码移动到移动函数UpDownLeftRight 等等,然后在移动后调用它。

关于python - 碰撞检测程序在 Turtle 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60609836/

相关文章:

python-3.x - 在 IPython (Py 3.4) 笔记本中使用 turtle

python - 如何检索所有用户名以及每个用户的 bool 标志以指示其组成员资格?

python - Plotly:如何在 x 轴上仅绘制月份和日期? (忽略年份)

python - 为什么我的带有 if-elif 语句的递归函数返回 None?

javascript - p5.j​​s 中的 Angular 碰撞 Angular

ios - 仅检测矩形物理体一侧的碰撞 - Swift3

如果 blitted 到特定表面,则 C++ SDL 冲突

Python:如何将pymouse坐标转换为turtle坐标

python - 螺旋图 turtle 蟒

python - 裁剪矩阵的 nan 行和列,但保持正方形