sdl运动在45度

时间:2015-01-08 20:13:57

标签: c++ c sdl motion

我试图让我的物体以45度的角度对角移动。当它达到SCREEN WIDTH时它应该反弹,我在某个地方犯了一个大错,但无法弄明白。

distance = 0;
etiSpeed = 1;

t2 = SDL_GetTicks();
delta = (t2 - t1) * 0.001;
t1 = t2;

distance += etiSpeed * delta;



    ball_x = ball_x * distance * ball_x_vel;
    ball_y = ball_y  * distance * ball_y_vel;

    if (ball_x < SCREEN_WIDTH)
    {
        ball_x_vel = 1;
        DrawSurface(screen, ball, ball_x, ball_y);
    }

else if (ball_x = SCREEN_WIDTH)
    {
        ball_x_vel = -1;
       DrawSurface(screen, ball, ball_x, ball_y);       
    }

1 个答案:

答案 0 :(得分:2)

您的错误测试

if (ball_x = SCREEN_WIDTH)

ball_x位置设置为SCREEN_WIDTH,因为布尔测试将为真,因此将执行下一个代码块。我想你正试图测试

if (ball_x == SCREEN_WIDTH)

但这也不正确,应该是

if (ball_x >= SCREEN_WIDTH)

即使这仍然太简单,如果球在屏幕外,你需要重新定位球。

if (ball_x >= SCREEN_WIDTH)
    ball_x = (SCREEN_WIDTH - 1) - (ball_x -(SCREEN_WIDTH-1));

假设你有

#define SCREEN_WIDTH 40
...
ball_x = 40;
if (ball_x >= SCREEN_WIDTH)
    ball_x = (SCREEN_WIDTH - 1) - (ball_x -(SCREEN_WIDTH-1));

这评估为39 - (40-39)= 38,当球超过1时,反弹1。