在tkin中如何使对象跟随鼠标

2024-04-29 07:32:24 发布

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

我正在尝试制作一个agar.io克隆,我有鼠标的坐标,但我不知道如何让玩家朝着鼠标移动,而不仅仅是直接指向鼠标。到目前为止,我得到了鼠标的坐标:

def mouseCoords(self):
    rawMouseX, rawMouseY =   tk.winfo_pointerx(), tk.winfo_pointery()
    self.mousecoords = rawMouseX  - tk.winfo_rootx(), rawMouseY - tk.winfo_rooty()
    return self.mousecoords

我想要一种方法来使用这两个对象的tag将点和文本移向鼠标。在

编辑:

我试着用这个代码让圆点朝着鼠标移动,但它只朝着8个不同的方向移动,并不总是直接朝着鼠标移动。在

以下是完整(未完成)代码:

^{pr2}$

Tags: 代码ioselfdef鼠标tk指向agar
2条回答

我想出来了:

def moveTowardMouse(self):
    selfx, selfy = self.coords()
    mousex, mousey = self.mousecoords
    directDist = math.sqrt(((mousex-selfx) ** 2) + ((mousey-selfy) ** 2))
    self.speed = 4
    movex = (mousex-selfx) / directDist
    movey = (mousey-selfy) / directDist
    self.canvas.move('User', movex*self.speed, movey*self.speed)

要使播放器向各个方向移动,需要使用播放器和鼠标坐标与参考轴的角度。然后用这个角度找出移动播放器的x和y距离。在

我使用math模块中的atan2方法来计算角度。在

修改代码

## imports for Python 2.7, change as appropriate
from Tkinter import *
import tkSimpleDialog as simpledialog
import time, random, numpy, math


class PlayerSprite:
    def __init__(self, canvas):
        self.canvas = canvas
        self.endgame = False
        self.id = self.canvas.create_oval(350, 350, 400, 400, tag='User', fill=random.choice(colors))
        self.id2 = self.canvas.create_text(375, 375, text=nick, font=('Helvetica', 15), tag='User')
    def coords(self):
        print(self.canvas.coords('User'))
        return self.canvas.coords('User')
    def mouseCoords(self):
        rawMouseX, rawMouseY =   tk.winfo_pointerx(), tk.winfo_pointery()
        self.mousecoords = rawMouseX  - tk.winfo_rootx(), rawMouseY - tk.winfo_rooty()
        return self.mousecoords
    def moveTowardMouse(self):   # Problem function?
        ## Use center of the of the oval/player as selfx, selfy
        selfx, selfy = (self.coords()[0]+self.coords()[2])/2, (self.coords()[1]+self.coords()[3])/2
        mousex, mousey = self.mousecoords
        movex = (mousex-selfx)
        movey = (mousey-selfy)

        speed = 2 ## Player speed
        theta = math.atan2(movey, movex) ## angle between player and mouse position, relative to positive x

        ## Player speed in terms of x and y coordinates
        x = speed*math.cos(theta)
        y = speed*math.sin(theta)

        self.canvas.move('User', x, y)


tk = Tk()
nick = simpledialog.askstring('nickname', 'Nickname')
tk.title("My Agar.io Clone")
tk.wm_attributes('-topmost', 1)
tk.resizable(0, 0)
canvas = Canvas(tk, width=750, height=750)
center =  (canvas.winfo_reqwidth()/2), (canvas.winfo_reqheight()/2)
colors = ['red', 'blue', 'green', 'yellow']

canvas.pack()

player = PlayerSprite(canvas)
player.mouseCoords()

while player.endgame == False:
    try:
        player.moveTowardMouse()
        player.mouseCoords()
        tk.update_idletasks()
        tk.update()
        time.sleep(.005)
    except:# KeyboardInterrupt:
        print('CRL-C recieved, quitting')
        tk.quit()
        break

相关问题 更多 >