0

当我单击 Space 时,我希望子弹移动。首先,当按下空格键时,子弹图像会被 blitted,同时计时器会启动,当它达到 5000 毫秒时,图像的 x 值应该会改变。这是我的代码:

SDL_Rect bulletRect;
bulletRect.x = dstX+31;  //dstX/Y is the source destination of another image where the bullet should be drawn
bulletRect.y = dstY+10.5;
SDL_Surface *bullet = IMG_Load(bullet.png");


if (drawBullet) //bool set to true in the space key event.
    {            
        SDL_BlitSurface(bullet, NULL, screen, &bulletRect);

        //timer
        my_timer.start(); //starts the timer

        if (SDL_GetTicks() == 5000) //if 5 sec 
        {
            bulletRect.x += 10;
        }
    }

图像仅被 blitted,但 5 秒后没有任何反应。怎么了?

4

2 回答 2

0

You should have SDL_GetTicks() >= 5000, instead of checking for ==5000, otherwise you'll only enter the condition if you happen to hit 5000 by pure luck.

from SDL's documentation, SDL_GetTicks function: Returns the number of milliseconds since SDL library initialization. This value wraps around if the program runs for more than 49.7 days

so if you're checking that it's been 5 seconds since it moved last (not sure what else you could be trying to do here) you want to store the current number of ticks and use that to compare against during the next loop (check that the difference between previous and current is > 5000)

于 2013-06-11T20:51:10.230 回答
0

你的条件陈述

if (SDL_GetTicks() == 5000) //if 5 sec 
{
    bulletRect.x += 10;
}

在语句内

if (drawBullet) //bool set to true in the space key event

这意味着您只需在按下空格键时检查一次计时器。将其移到 if(drawBullet) 之外

于 2013-06-11T21:20:22.397 回答