我如何使射击多个子弹功能正确使用for循环

How do I made shooting multiple bullets function correctly using a for loop?

本文关键字:循环 for 功能 子弹 何使 射击      更新时间:2023-10-16

我正在制作一款使用SDL的c++ shmup游戏的原型…现在,我只是试图在不使用类的情况下使基础工作。现在,我有了它,所以它可以发射多发子弹,但它的行为很奇怪,我认为这是因为计数器被重置的方式…子弹会出现和消失,有些会一直在原来的位置闪烁,有时会延迟再次射击,即使屏幕上没有限制……有时玩家角色会突然跳到右边,只能上下移动。我如何解决这个问题,使它顺利拍摄?我已经包含了所有相关的代码…

[edit]请注意,我打算清理它,并把它全部移动到一个类一旦我弄清楚了…这只是一个简单的原型,所以我可以把游戏的基础编程进去。

[edit2] ePos是敌人的位置,pPos是玩家的位置。

//global
SDL_Surface *bullet[10] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL };
bool shot[10];
int shotCount = 0;
SDL_Rect bPos[10];
//event handler
case SDLK_z: printf("SHOT!"); shot[shotCount] = true; ++shotCount; break; 
//main function
for(int i = 0; i <= 9; i++)
{
    shot[i] = false;  
    bullet[i] = IMG_Load("bullet.png");
}
//game loop
for(int i = 0; i <= shotCount; i++)
{    
    if(shot[i] == false)
    {
        bPos[i].x = pPos.x;
        bPos[i].y = pPos.y; 
    }
    if(shot[i] == true)
    { 
        bPos[i].y -= 8;
        SDL_BlitSurface(bullet[i], NULL, screen, &bPos[i]);
        if( (bPos[i].y + 16 == ePos.y + 16) || (bPos[i].x + 16 == ePos.x + 16) )
        {
            shot[i] = false;
        }
        else if(bPos[i].y == 0)
        {
            shot[i] = false;
        }
    }
}
if(shotCount >= 9) { shotCount = 0; }

这是我在评论中建议的东西。这只是我随口写出来的,但它能让你大致了解我在说什么。

class GameObject
{
    public:
        int x;
        int y;
        int width;
        int height;
        int direction;
        int speed;
    GameObject()
    {
        x = 0;
        y = 0;
        width = 0;
        height = 0;
        direction = 0;
        speed = 0;
    }
    void update()
    {
        // Change the location of the object.
    }
    bool collidesWidth(GameObject *o)
    {
        // Test if the bullet collides with Enemy.
        // If it does, make it invisible and return true
    }
}
GameObject bullet[10];
GameObject enemy[5];
while(true)
{
    for(int x=0; x<=10;x++)
    {
        bullet[x].update();
        for(int y=0;y<=5;y++)
        {
            if(bullet[x].collidesWith(&enemy[y])
            {
                // Make explosion, etc, etc.
            }
        }
    }
}