编写 Robotron: 2084 的 twin-stick 动作 | Wireframe #38
新闻快讯!在我们开始讲解 Robotron: 2084 的代码之前,有一些关于 Wireframe 的重要消息要分享:从第 39 期开始,这本杂志将改为月刊。
新的 116 页期刊将包含更多深入专题、更多前瞻与评测,以及更多让这本杂志独具特色的游戏开发指南。这一变化意味着我们将能够带来新的订阅优惠,并总体上让杂志在当前充满挑战的全球环境中更具可持续性。
至于现有订阅者,我们会给大家发送邮件,说明订阅方式将如何变化,并提供一些特别的免费期刊,以感谢大家一直以来的支持。
第一期月刊将于6 月 4 日推出,之后的刊物将在每个月的第一个星期四出版。你将能够在线订购一本,或者在购买必需品时,在指定的超市和报刊亭找到它。
现在我们回到常规节目……
使用这个 Python 和 Pygame 重现的街机经典,朝一个方向移动并朝另一个方向射击。Raspberry Pi 自家的麦克·鲍利代码见此处。

Robotron: 2084 经常被列在“史上最佳游戏”榜单中,并且多年来已在众多系统上被重制和重新发布。
Robotron: 2084
Robotron: 2084 于 1982 年发布,普及了 twin-stick shooter 的概念。它为玩家提供了两个摇杆,使他们能够朝一个方向移动,同时朝另一个方向射击敌人。在这里,我将向你展示如何使用 Python 和 Pygame 重现这些操控。我们没有摇杆,只有键盘,所以我们将用方向键来控制移动,并且WASD to control the direction of fire.
移动控制使用一个global variable, a few if statements, and two built-in Pygame functions: on_key_down and on_key_up. The on_key_down function is called when a key on the keyboard is pressed, so when the player presses the right arrow key, for example, I set the x direction of the player to be a positive 1. Instead of setting the movement to 1, instead, I’ll add 1 to the direction. The on_key_down function is called when a button’s released. A key being released means the player doesn’t want to travel in that direction anymore and so we should do the opposite of what we did earlier – we take away the 1 or -1 we applied in the on_key_up function.
我们对每个方向键重复这个过程。将玩家向update() function is the last part of my movement; I apply a move speed and then use a playArea rect to clamp the player’s position.

竞技场背景和坦克精灵图是在Piskel。坦克的独立精灵图让炮塔可以独立于履带旋转。
转向与射击
现在来讲瞄准和旋转。当我的玩家瞄准时,我希望他们设定子弹发射的方向,其工作方式与移动类似。这一次的区别在于,当玩家按下瞄准键时,我直接设定方向,而不是调整数值。如果我的玩家向上瞄准,然后松开该键,射击就会停止。我们接下来的挑战是把这个方向转换为炮塔的旋转。
Pygame 中的 Actors 可以按角度旋转,因此我需要找到一种方法,把一组 x 和 y 方向转换为旋转角度。为此,我使用 math 模块的atan2 function to find the arc tangent of two points. The function returns a result in radians, so it needs to be converted. (You’ll also notice I had to adjust mine by 90 degrees. If you want to avoid having to do this, create a sprite that faces right by default.)
我使用了一个名为‘shooting’的标志来控制发射子弹,当设置为True, causes my turret to turn and fire. My bullets are dictionaries; I could have used a class, but the only thing I need to keep track of is an actor and the bullet’s direction.

这是 Mac 的代码片段,它用 Python 创建了一个简单的双摇杆射击机制。要让它在你的系统上运行,你需要安装 Pygame Zero。并且要下载完整代码及全部资源,请点击此处。
你可以查看update function and see how I’ve implemented a fire rate for the turret as well. You can edit the update function to take a single parameter, dt, which stores the time since the last frame. By adding these up, you can trigger a bullet at precise intervals and then reset the timer.
这段代码只是一个开始——你可以添加敌人,也许还有其他玩家武器,以打造一个完整的射击体验。
获取你的 Wireframe issue 38
你可以在本期杂志中阅读更多类似内容Wireframe issue 38,现可通过 Raspberry Pi Press 官方渠道直接订购——支持全球配送。[19] 免费下载第40期电子版
如果你想要一份方便的电子版杂志,也可以免费下载 issue 38的PDF格式版本。


2条评论
Jeff
感谢课程和杂志!
Nathanael Gura
这正是我一直想做的!!这将为我提供这些游戏如何工作以及如何组合在一起的详细说明,谢谢!!
评论已关闭