Python乌龟鼠标不会直接跟随

时间:2019-01-31 21:01:29

标签: python turtle-graphics

如何在不使用turtle.goto(x,y)turtle.speed(speed)的情况下使乌龟移动?我正在制作的游戏需要这个。鼠标在哪里,我想使其朝该方向移动。但是当我更改它时,它会到达那个位置,然后到我的鼠标:

turtle.heading(angle)

如果您仅import turtle screen = turtle.Screen() screen.title("Test") screen.bgcolor("white") screen.setup(width=600, height=600) ship = turtle.Turtle() ship.speed(1) ship.shape("triangle") ship.penup() ship.goto(0,0) ship.direction = "stop" ship.turtlesize(3) turtle.hideturtle() def onmove(self, fun, add=None): if fun is None: self.cv.unbind('<Motion>') else: def eventfun(event): fun(self.cv.canvasx(event.x) / self.xscale, -self.cv.canvasy(event.y) / self.yscale) self.cv.bind('<Motion>', eventfun, add) def goto_handler(x, y): onmove(turtle.Screen(), None) ship.setheading(ship.towards(x, y)) #this is where you use the x,y cordinates and I have seat them to got to x,y and set heading ship.goto(x,y) onmove(turtle.Screen(), goto_handler) onmove(screen, goto_handler) setheading,它只是那样旋转而不会移动。如果您尝试使用此代码,则可以正常工作-只是我使用speed使其进入ship.goto(x, y)。但是,当您移动鼠标时,它会先转到(x, y),然后再转到新的鼠标位置。我几乎只是想让它跟随鼠标,但是我做不到。

1 个答案:

答案 0 :(得分:0)

我相信以下代码可为您提供所需的动作。它仅使用onmove()来隐藏目标的位置,并使用ontimer()来瞄准并移动乌龟。包裹目标后,它也会停止:

from turtle import Screen, Turtle, Vec2D

def onmove(self, fun, add=None):
    if fun is None:
        self.cv.unbind('<Motion>')
    else:
        def eventfun(event):
            fun(Vec2D(self.cv.canvasx(event.x) / self.xscale, -self.cv.canvasy(event.y) / self.yscale))

        self.cv.bind('<Motion>', eventfun, add)

def goto_handler(position):
    global target

    onmove(screen, None)
    target = position
    onmove(screen, goto_handler)

def move():
    if ship.distance(target) > 5:
        ship.setheading(ship.towards(target))
        ship.forward(5)

    screen.ontimer(move, 50)

screen = Screen()
screen.title("Test")
screen.setup(width=600, height=600)

ship = Turtle("triangle")
ship.turtlesize(3)
ship.speed('fast')
ship.penup()

target = (0, 0)

onmove(screen, goto_handler)

move()

screen.mainloop()