如何在cocos2d(python)中让按键触发图像移动?

2024-09-30 00:33:17 发布

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

我正在编写以下程序,基于cocos2d编程指南中的一些introductory lessons(用于2d游戏设计)。在

这个程序有两个类,HelloWorld和KeyDisplay。在

HelloWorld显示了一只鸟的图像和短语“给这只鸟一些比萨饼!”。使用cocos.actions.ScaleBycocos.actions.Reverse每隔2秒对短语进行放大和缩小。效果很好。在

KeyDisplay接受用户键盘输入,并使用on-key-press功能在屏幕上写入字符。它也在正常工作。在

接下来我想通过KeyDisplay修改HelloWorld中正在进行的事情。例如,我想更改图像的比例(sprite.scale)或更改图像的位置(sprite.position)。这需要HelloWorld和KeyDisplay类对象相互通信。在

不幸的是,KeyDisplay类不知道HelloWorld类,因此无法访问变量。例如,如果我试图设置精灵比例=0.5在on_key_press函数中,我得到一个错误。在

KeyDisplay有没有办法响应keypress事件,修改HelloWorld类中的精灵和其他变量?我想这既是一个python编程问题,也是一个cocos2d游戏设计问题。通常我需要在HelloWorld类中创建sprite和label(在__init__(self)方法中)。到目前为止,我还没有被允许在全球范围内创建精灵或标签。谢谢你的建议。在

import cocos
import pyglet
# note: needed to change something in the operating system before importing cocos, running this command:
# defaults write org.python.python ApplePersistenceIgnoreState NO



class HelloWorld(cocos.layer.ColorLayer):
    def __init__(self):
        super( HelloWorld, self ).__init__( 64,64,224,255)
        self.world_width = 1000
        self.world_height = 1000
        self.px_width = 1000
        self.px_height = 1000

        label = cocos.text.Label('Get this bird some pizza!',
                       font_name='Times New Roman',
                       font_size=32,
                       anchor_x='center', anchor_y='center')

        label.position = 320,100
        self.add( label )
        sprite = cocos.sprite.Sprite('bower-bird.jpeg')
        sprite.position = 320,320
        sprite.scale = 1
        self.add( sprite, z=1 )

        scale = cocos.actions.ScaleBy(3, duration=2)
        label.do( cocos.actions.Repeat( scale + cocos.actions.Reverse( scale) ) )
        #sprite.do( cocos.actions.Repeat( scale + cocos.actions.Reverse( scale) ) )


class KeyDisplay(cocos.layer.Layer):

    # If you want that your layer receives director.window events
    # you must set this variable to 'True'
    is_event_handler = True

    def __init__(self):

        super( KeyDisplay, self ).__init__()

        self.text = cocos.text.Label("", x=100, y=280 )

        # To keep track of which keys are pressed:
        self.keys_pressed = set()
        self.update_text()
        self.add(self.text)

    def update_text(self):
        key_names = [pyglet.window.key.symbol_string (k) for k in self.keys_pressed]
        text = 'Keys: '+','.join (key_names)
        # Update self.text
        self.text.element.text = text

    def on_key_press (self, key, modifiers):
        """This function is called when a key is pressed.
        'key' is a constant indicating which key was pressed.
        'modifiers' is a bitwise or of several constants indicating which
            modifiers are active at the time of the press (ctrl, shift, capslock, etc.)
        """
        self.keys_pressed.add (key)
        self.update_text()

    def on_key_release (self, key, modifiers):
        """This function is called when a key is released.

        'key' is a constant indicating which key was pressed.
        'modifiers' is a bitwise or of several constants indicating which
            modifiers are active at the time of the press (ctrl, shift, capslock, etc.)

        Constants are the ones from pyglet.window.key
        """

        self.keys_pressed.remove (key)
        self.update_text()

    def update_text(self):
        key_names = [pyglet.window.key.symbol_string (k) for k in self.keys_pressed]
        text = 'Keys: '+','.join (key_names)
        # Update self.text
        self.text.element.text = text

#start it up ... 

cocos.director.director.init()
hello_layer = HelloWorld ()
main_scene = cocos.scene.Scene (hello_layer, KeyDisplay())
cocos.director.director.run (main_scene)

Tags: thekeytextselfactionsinitisdef
1条回答
网友
1楼 · 发布于 2024-09-30 00:33:17

这是来自gituser:JPwright的一个示例 基本上创建一个Move类(“Me”类),然后在sprite的“do”函数中调用它。“步骤”功能本质上就是“完成”的功能

import pyglet
from pyglet.window import key

import cocos
from cocos import actions, layer, sprite, scene
from cocos.director import director

# Player class

class Me(actions.Move):

  # step() is called every frame.
  # dt is the number of seconds elapsed since the last call.
  def step(self, dt):

    super(Me, self).step(dt) # Run step function on the parent class.

    # Determine velocity based on keyboard inputs.
    velocity_x = 100 * (keyboard[key.RIGHT] - keyboard[key.LEFT])
    velocity_y = 100 * (keyboard[key.UP] - keyboard[key.DOWN])

    # Set the object's velocity.
    self.target.velocity = (velocity_x, velocity_y)

# Main class

def main():
  global keyboard # Declare this as global so it can be accessed within class methods.

  # Initialize the window.
  director.init(width=500, height=300, autoscale=False, resizable=True)

  # Create a layer and add a sprite to it.
  player_layer = layer.Layer()
  me = sprite.Sprite('bower-bird.jpeg')
  player_layer.add(me)

  # Set initial position and velocity.
  me.position = (100, 100)
  me.velocity = (0, 0)

  # Set the sprite's movement class.
  me.do(Me())

  # Create a scene and set its initial layer.
  main_scene = scene.Scene(player_layer)

  # Attach a KeyStateHandler to the keyboard object.
  keyboard = key.KeyStateHandler()
  director.window.push_handlers(keyboard)

  # Play the scene in the window.
  director.run(main_scene)

if __name__ == '__main__':
    main()

相关问题 更多 >

    热门问题