Python Turtle 如何创建碰撞
Python Turtle how to create collision
我正在尝试使用 Turtle 创建乒乓球,但是我遇到了碰撞系统问题。我为此使用了一个基本的毕达哥拉斯函数,但是,当球击中保险杠时,它会卡在保险杠上并开始摇晃。我不确定如何解决这个问题。这是碰撞和保险杠代码。
turtle.register_shape('bar.gif')
lbump = turtle.Turtle()
lbump.color('white')
lbump.shape('bar.gif')
lbump.penup()
lbump.speed(0)
lbump.setposition(-285,0)
rbump = turtle.Turtle()
rbump.color('white')
rbump.shape('bar.gif')
rbump.penup()
rbump.speed(0)
rbump.setposition(285,0)
ball = turtle.Turtle()
ball.color('white')
ball.shape('circle')
ball.penup()
ball.speed(0)
ball.setposition(0,0)
ballspeedx = -5
ballspeedy = 0 #To test collison#
def isCollision(t1, t2):
distance = math.sqrt(math.pow(t1.xcor()-t2.xcor(),2)+math.pow(t1.ycor()-t2.ycor(),2))
if distance < 30:
return True
else:
return False
def ball_move():
while True:
global ballspeedy
global ballspeedx
x = ball.xcor() + ballspeedx
y = ball.ycor() + ballspeedy
if y > 285 or y < -285:
ballspeedy *= -1
if x < -295 or x > 295:
x = 0
y = 0
if isCollision(lbump, ball):
ballspeedx *= -1
if isCollision(rbump, ball):
ballspeedx *= -1
ball.setposition(x,y)
可能是这样的原因:当检测到碰撞(isCollision
returns True
)并且x速度的符号被切换时,球没有时间以获得与保险杠足够的距离,直到循环的下一次迭代。因此,下一次迭代 isCollision
仍在检测碰撞并再次更改速度符号。
因此,x 速度符号在每次迭代中从正切换为负,反之亦然,您会看到抖动效果。
如果我是对的,这个编辑是我想到的解决问题的最简单方法:
if isCollision(lbump, ball):
ballspeedx = abs(ballspeedx)
if isCollision(rbump, ball):
ballspeedx = -1 * abs(ballspeedx)
当然可以实施更精细的解决方案。
我正在尝试使用 Turtle 创建乒乓球,但是我遇到了碰撞系统问题。我为此使用了一个基本的毕达哥拉斯函数,但是,当球击中保险杠时,它会卡在保险杠上并开始摇晃。我不确定如何解决这个问题。这是碰撞和保险杠代码。
turtle.register_shape('bar.gif')
lbump = turtle.Turtle()
lbump.color('white')
lbump.shape('bar.gif')
lbump.penup()
lbump.speed(0)
lbump.setposition(-285,0)
rbump = turtle.Turtle()
rbump.color('white')
rbump.shape('bar.gif')
rbump.penup()
rbump.speed(0)
rbump.setposition(285,0)
ball = turtle.Turtle()
ball.color('white')
ball.shape('circle')
ball.penup()
ball.speed(0)
ball.setposition(0,0)
ballspeedx = -5
ballspeedy = 0 #To test collison#
def isCollision(t1, t2):
distance = math.sqrt(math.pow(t1.xcor()-t2.xcor(),2)+math.pow(t1.ycor()-t2.ycor(),2))
if distance < 30:
return True
else:
return False
def ball_move():
while True:
global ballspeedy
global ballspeedx
x = ball.xcor() + ballspeedx
y = ball.ycor() + ballspeedy
if y > 285 or y < -285:
ballspeedy *= -1
if x < -295 or x > 295:
x = 0
y = 0
if isCollision(lbump, ball):
ballspeedx *= -1
if isCollision(rbump, ball):
ballspeedx *= -1
ball.setposition(x,y)
可能是这样的原因:当检测到碰撞(isCollision
returns True
)并且x速度的符号被切换时,球没有时间以获得与保险杠足够的距离,直到循环的下一次迭代。因此,下一次迭代 isCollision
仍在检测碰撞并再次更改速度符号。
因此,x 速度符号在每次迭代中从正切换为负,反之亦然,您会看到抖动效果。
如果我是对的,这个编辑是我想到的解决问题的最简单方法:
if isCollision(lbump, ball):
ballspeedx = abs(ballspeedx)
if isCollision(rbump, ball):
ballspeedx = -1 * abs(ballspeedx)
当然可以实施更精细的解决方案。