简体   繁体   English

Pygame:我怎样才能让精灵始终向右移动?

[英]Pygame: How can I make a sprite always move to the right?

I want my sprite (a 2d top down fighter plane) to always move to the sprites'a right. 我希望我的雪碧(2d自上而下的战斗机)始终向右移动。 I currently have it so the plane rotates to where the mouse pointer is. 我目前拥有它,因此飞机可以旋转到鼠标指针所在的位置。 Now I need the plane to always be moving and so you can rotate it with your mouse while the plane is flying. 现在,我需要飞机一直在移动,因此您可以在飞机飞行时用鼠标旋转它。 A short code example would be excellent as I am not very experienced. 简短的代码示例将非常有用,因为我经验不足。 The sprite is "plane.png". 子画面为“ plane.png”。 I am using Python 2.7 if that matters. 如果这很重要,我正在使用Python 2.7。 Thanks! 谢谢!

There are actually a few things you may want to clarify before you start implementing anything. 在开始执行任何操作之前,实际上可能需要澄清一些事情。 First, do you actually want the sprite to move in relation to the window , or do you want the sprite to stay stationary and have the background scroll, giving the player the impression that the sprite is moving across your game's landscape? 首先,您实际上是想让精灵相对于窗口移动,还是要让精灵保持静止并具有背景滚动,从而给玩家留下精灵在游戏风景中移动的印象?

Assuming you want the sprite itself to move, you'd want to create a method within the sprite's object that constantly updates it's x position to a slightly higher number 假设您想让精灵本身移动,您想在精灵对象内创建一个方法,该方法不断将其x位置更新为稍高的数字

while True:
    xpos += 1
    display_image = pygame.image.load(plane.png)
    display.blit(display_image, [xpos, ypos])

The above snippet while increment the x position of your sprite by 1 every frame. 上面的代码段将子画面的x位置每帧增加1。 If you haven't already set a limit to the number of frames rendered per second, I'd suggest taking a look at creating a clock in pygame and calling the tick function every time the game loop runs 如果您尚未设置每秒渲染的帧数的限制,我建议您看一下在pygame创建时钟并在每次游戏循环运行时调用tick函数

Alternatively, you could do the same as above, but pass in the mouse cursor's current coordinates to have the sprite follow your cursor. 或者,您可以执行与上述相同的操作,但传入鼠标光标的当前坐标以使精灵跟随您的光标。

If you'd rather have the sprite stay stationary and move the background, you could do the same thing for each element of your background, just in reverse. 如果您希望精灵保持静止并移动背景,则可以对背景的每个元素执行相同的操作,只是相反。

while True:
    xpos -= 1
    display_image = pygame.image.load(background.png)
    display.blit(display_image, [xpos, ypos]

Hope this is helpful! 希望这会有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM