首页 > 解决方案 > 我如何让乌龟对象与另一个对象面对相同的方向?

问题描述

因此,就上下文而言,我正在使用 python 海龟图形制作射击游戏。我试图找到可以多次尝试的东西,但无济于事。例如,我尝试过

def direction():
 wn.onkey(lambda: shuttle.setheading(90), 'Up')
 wn.onkey(lambda: shuttle.setheading(180), 'Left')
 wn.onkey(lambda: shuttle.setheading(0), 'Right')
 wn.onkey(lambda: shuttle.setheading(270), 'Down')

direction()


bullet.setheading(direction())

if bullet.distance(shuttle) < 15:
28  -    if shuttle.setheading == 90:
29  -      bullet.setheading(90)
30  -    if shuttle.setheading == 180:
31  -      bullet.setheading(180)
32  -    if shuttle.setheading == 0:
33  -      bullet.setheading(0)
34  -    if shuttle.setheading == 270:
35  -      bullet.setheading(270)

我为行号道歉,但删除它们似乎太麻烦了。

标签: pythonturtle-graphics

解决方案


假设你有 2 只海龟:turtle1turtle2. 要转向turtle2的方向turtle1,请使用以下代码:

turtle2.setheading(turtle1.heading())

仅供参考:在您的第一个代码片段中,direction返回None,因为它只添加事件,所以它不起作用。

注意:我建议将 tkinter 用于游戏,因为 turtle 是为教育用途而创建的,而且速度非常慢。


推荐阅读