我正在为 GBA 模拟器编写一个游戏,该模拟器以经典街机游戏“凤凰”为模型,在该游戏中,一艘船向其上方的目标发射子弹。我目前的游戏运行良好,但我希望能够一次发射多发子弹。
我创建了一个较小的源文件只是为了测试我如何做到这一点,所以没有砖 block 或船等,只有子弹的来源和背景颜色。
我试图通过创建一个包含 5 个“子弹”结构的数组来为包含 5 颗子弹的飞船创建一个“弹匣”,每个结构都包含自己的 x 和 y 坐标。每个子弹还分配给它一个 bool 标志以确定它是否被发射,允许在按下 A 时循环搜索数组以找到尚未发射的子弹并发射它。
我认为这会奏效,但作为初学者,我觉得我可能错过了一些东西。 当它运行时,我可以发射一颗子弹,它会按预期在屏幕上显示动画,但我无法发射第二颗,直到第一颗子弹离开屏幕并且它的标志重置为“false”。
也许你能帮我找出代码中的问题?
谢谢。
#include <stdint.h>
#include "gba.h"
const int MAG_SIZE = 5;
bool bulletFired[MAG_SIZE] = {false};
struct bullet {
int x;
int y;
} bullet[MAG_SIZE];
bool isPressed(uint16_t keys, uint16_t key)
{ // Uses REG_KEYINPUT and a specified key mask to determine if the key is pressed
return (keys & key) == 0;
}
void DrawBullet(int bulletXPos, int bulletYPos)
{ // Fires bullet from player craft
PlotPixel8(bulletXPos, bulletYPos, 2);
}
int main()
{
REG_DISPCNT = MODE4 | BG2_ENABLE;
bool isPressed(uint16_t keys, uint16_t key);
void DrawBullet(int bulletXPos, int bulletYPos);
SetPaletteBG(0, RGB(0, 0, 10)); // Blue
SetPaletteBG(1, RGB(31, 31 ,31)); // White
SetPaletteBG(2, RGB(25, 0, 0)); // Red
ClearScreen8(0);
while (true)
{
WaitVSync();
ClearScreen8(0);
uint16_t currKeys = REG_KEYINPUT;
for (int n = 0; n < 5; n++)
{
if ( bulletFired[n] )
{
bullet[n].y--;
DrawBullet(bullet[n].x, bullet[n].y);
if ( bullet[n].y < 1 )
{
bulletFired[n] = false;
}
}
}
if (isPressed(currKeys, KEY_A))
{ // Key A is pressed
for (int n = 0; n < 5; n++)
{
if ( !bulletFired[n] )
{
bulletFired[n] = true;
bullet[n].x = 120;
bullet[n].y = 134;
}
}
}
FlipBuffers();
}
return 0;
}
最佳答案
问题就在这里
if (isPressed(currKeys, KEY_A))
{ // Key A is pressed
for (int n = 0; n < 5; n++)
{
if ( !bulletFired[n] )
{
bulletFired[n] = true;
bullet[n].x = 120;
bullet[n].y = 134;
}
}
}
当您检测到按键时,您会立即发射所有可用的子弹。
你想要这样的东西:
if (isPressed(currKeys, KEY_A))
{ // Key A is pressed
for (int n = 0; n < 5; n++)
{
if ( !bulletFired[n] )
{
bulletFired[n] = true;
bullet[n].x = 120;
bullet[n].y = 134;
//EXIT THE LOOP
break;
}
}
}
跳出循环。您可能还想在发射子弹或等待完全按下按键之间插入一个时间延迟,因为您仍可能会非常快速地发射子弹。
关于c++ - GBA C++ : How to draw multiple animating pixels using arrays?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27132837/