因此,在将Tkinter用于我们的游戏之后,我们决定移至Pyglet。但是我遇到的问题之一是运动,在Tkinter中,我能够制作出平滑的运动系统,但是在pyglet中,我所能做的就是使角色以抖动的方式运动。
import pyglet
from pyglet.window import key, Window
from pyglet import clock
from threading import Timer
X = 5 #Speed of the player
w = 0 #Controls +y movement
a = 0 #Controls -x movement
s = 0 #Controls -y movement
d = 0 #Controls +x movement
window = Window(width = 500, height = 500) #Defines window
MainChar = pyglet.image.load("Mainchar.png") #Loads the Mainchar.png
Player = pyglet.sprite.Sprite(MainChar, x = 0, y = 0) #Makes MainChar into a sprite
@window.event
def on_key_press(symbol, modifiers): #Looks for a keypress
print("keypress")
if symbol == key.W:
global w
global a
global s
global d
w = True
elif symbol == key.A:
a = True
elif symbol == key.S:
s = True
elif symbol == key.D:
d = True
@window.event
def on_key_release(symbol, modifiers):
print("keyup")
if symbol == key.W:
w = False
elif symbol == key.A:
a = False
elif symbol == key.S:
s = False
elif symbol == key.D:
d = False
@window.event
def moveT():
print("cycle")
def moveD():
if w == True:
Player.y += 0.1
elif a == True:
Player.x -= 5
elif s == True:
Player.y -= 5
elif d == True:
Player.x += 5
moveT()
moveTimer = Timer(0.01, moveD)
moveTimer.start()
@window.event
def on_draw():
window.clear()
Player.draw()
moveT()
pyglet.app.run()
我将w,a,s和d当作布尔变量的原因是这样,因此我可以在按住键而不是按键的情况下移动字符。
任何帮助都会很棒,在此先谢谢您!
答案 0 :(得分:1)
问题是您使用的是Python threading
。这不会触发重新绘制pyglet窗口。
您必须使用pyglet.clock
并计划每次滴答时钟时要调用的函数。这会导致pyglet窗口也被更新,并且会触发on_draw()
事件。例如:
@window.event
def moveT(dt):
if w == True:
Player.y += 0.1
elif s == True:
Player.y -= 5
if a == True:
Player.x -= 5
elif d == True:
Player.x += 5
pyglet.clock.schedule_interval(moveT, 1 / 60)
还必须在w
中将global
声明为a
,s
,d
和on_key_release
。
import pyglet
from pyglet.window import key, Window
from pyglet import clock
X = 5 #Speed of the player
w, a, s, d = False, False, False, False
window = Window(width = 500, height = 500) #Defines window
MainChar = pyglet.image.load("Mainchar.png")
Player = pyglet.sprite.Sprite(MainChar, x = 0, y = 0)
@window.event
def on_key_press(symbol, modifiers): #Looks for a keypress
global w, a, s, d
if symbol == key.W:
w = True
elif symbol == key.A:
a = True
elif symbol == key.S:
s = True
elif symbol == key.D:
d = True
@window.event
def on_key_release(symbol, modifiers):
global w, a, s, d
if symbol == key.W:
w = False
elif symbol == key.A:
a = False
elif symbol == key.S:
s = False
elif symbol == key.D:
d = False
@window.event
def moveT(dt):
if w == True:
Player.y += 0.1
elif s == True:
Player.y -= 5
if a == True:
Player.x -= 5
elif d == True:
Player.x += 5
@window.event
def on_draw():
window.clear()
Player.draw()
pyglet.clock.schedule_interval(moveT, 1 / 60)
pyglet.app.run()