-3

i'm trying to cause my object to move diagonally in 45deg. When it hits SCREEN WIDTH it should bounce up, im making somewhere a big mistake but can't figure it out.

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);       
    }
pkk
  • 1
  • 5

1 Answers1

2

Your incorrect test

if (ball_x = SCREEN_WIDTH)

is setting the ball_x position to SCREEN_WIDTH which as a boolean test will be true and so the next code block will be executed. I think you were trying to test

if (ball_x == SCREEN_WIDTH)

But that's incorrect too, it should be

if (ball_x >= SCREEN_WIDTH)

and even that is still too simple, you need to reposition the ball if it is off-screen.

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

So suppose you have

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

This evaluates to 39 - (40-39) = 38, which as the ball overshot by 1, rebounds by 1.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56