Python龟鼠不直接跟随

Python turtle mouse does not follow directly

如何在不使用 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)

如果你只 setheadingspeed 它只是转向那个方向并且不会移动。如果您尝试使用此代码,它会起作用——只是我使用了 ship.goto(x, y),它会转到 (x, y)。但是,当您在鼠标移动时更改鼠标时,它会先转到 (x, y),然后再转到新的鼠标位置。我几乎只是想让它跟随鼠标,但我做不到。

我相信下面的代码可以为您提供所需的动作。它只使用 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()