我正在努力做到这一点,所以当按下 WASD 键时,角色会朝那个方向移动并面向那个方向。我有图片,但是当我尝试将它实现到代码中时,它似乎不起作用。当我按下按键时图像正在移动,但是当我按下按键进入另一个方向时它没有加载图像;它只是停留在idle_anim
。我错过了什么吗?还是我只是做错了?
这是我的代码供参考:
import cocos
from cocos.director import director
from cocos.scene import Scene
from cocos.layer import Layer
from cocos.sprite import Sprite
from cocos.text import Label
from cocos.actions import Move
import pyglet
from pyglet.window import Window
from pyglet.window import key
from pyglet.window.key import KeyStateHandler
keys = KeyStateHandler()
class MoveChar(Move):
def step(self, dt):
super(MoveChar, self).step(dt)
velocity_x = 100 * (keyboard[key.D] - keyboard[key.A])
velocity_y = 100 * (keyboard[key.W] - keyboard[key.S])
self.target.velocity = (velocity_x, velocity_y)
class Player(Layer):
def __init__(self):
super(Player, self).__init__()
# self.name = name
# self.hp = hp
# self.atk = atk
# self.defense = defense
# self.spd = spd
idle_img = pyglet.image.load("sprites/idle.png")
idle_img_grid = pyglet.image.ImageGrid(
idle_img, 1, 1, item_width=48, item_height=48)
idle_anim = pyglet.image.Animation.from_image_sequence(
idle_img_grid[0:], 0.17, loop=True)
spr = Sprite(idle_anim)
spr.position = 200, 500
spr.velocity = (0, 0)
spr.do(MoveChar())
self.add(spr)
if keys[key.A]:
left_img = pyglet.image.load("sprites/left.png")
left_img_grid = pyglet.image.ImageGrid(
left_img, 1, 3, item_width=48, item_height=48)
left_anim = pyglet.image.Animation.from_image_sequence(
left_img_grid[0:], 0.17, loop=True)
spr = Sprite(left_anim)
spr.position = 200, 500
spr.velocity = (0, 0)
spr.do(MoveChar())
self.add(spr)
if keys[key.D]:
right_img = pyglet.image.load("sprites/right.png")
right_img_grid = pyglet.image.ImageGrid(
right_img, 1, 3, item_width=48, item_height=48)
right_anim = pyglet.image.Animation.from_image_sequence(
right_img_grid[0:], 0.17, loop=True)
spr = Sprite(right_anim)
spr.position = 200, 500
spr.velocity = (0, 0)
spr.do(MoveChar())
self.add(spr)
if keys[key.W]:
up_img = pyglet.image.load("sprites/up.png")
up_img_grid = pyglet.image.ImageGrid(
up_img, 1, 3, item_width=48, item_height=48)
up_anim = pyglet.image.Animation.from_image_sequence(
up_img_grid[0:], 0.17, loop=True)
spr = Sprite(up_anim)
spr.position = 200, 500
spr.velocity = (0, 0)
spr.do(MoveChar())
self.add(spr)
if keys[key.S]:
down_img = pyglet.image.load("sprites/down.png")
down_img_grid = pyglet.image.ImageGrid(
down_img, 1, 3, item_width=48, item_height=48)
down_anim = pyglet.image.Animation.from_image_sequence(
down_img_grid[0:], 0.17, loop=True)
spr = Sprite(down_anim)
spr.position = 200, 500
spr.velocity = (0, 0)
spr.do(MoveChar())
self.add(spr)
if __name__ == '__main__':
director.init(width=1280, height=720, caption="Title")
director.window.pop_handlers()
player_layer = Player()
keyboard = KeyStateHandler()
director.window.push_handlers(keyboard)
test_scene = Scene()
test_scene.add(player_layer, 0)
director.run(test_scene)