Python龟鼠不直接跟随

2024-04-24 03:46:57 发布

您现在位置:Python中文网/ 问答频道 /正文

如果不使用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),然后转到新的鼠标位置。我只想让它跟着鼠标走,但我做不到。你知道吗


Tags: selfnoneeventdef鼠标screencvhandler
1条回答
网友
1楼 · 发布于 2024-04-24 03:46:57

我相信下面的代码给了你想要的动作。它只使用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()

相关问题 更多 >