2013-05-26 87 views
-1

如果我調用移動球/發現碰撞的函數,它不起作用。但如果我用「ball1」替換「b」的函數內容,它確實有效。爲了解決這個問題,我嘗試了很多很多很多的東西,但都無濟於事。我很抱歉代碼太長了,但我擔心如果我只包含一段代碼,它將無法修復。改變結構的vals的調用函數的問題

代碼:

#include "SDL/SDL.h" 
#include "SDL/SDL_image.h" 
#include <math.h> 
#include <stdbool.h> 

#define SCREEN_WIDTH 500 
#define SCREEN_HEIGHT 500 
#define SCREEN_BPP 32 
#define GRAVITY 1 

SDL_Surface *image = NULL; 
SDL_Surface *screen = NULL; 
SDL_Event event; 

SDL_Surface *loadImage(char *filename) { 
    SDL_Surface *optimizedImage = NULL; 
    SDL_Surface *loadedImage = IMG_Load(filename); 
    if (loadedImage != NULL) { 
     optimizedImage = SDL_DisplayFormat(loadedImage); /*optimizes image*/ 
     SDL_FreeSurface(loadedImage); 
    } 

    return optimizedImage; 
} 

void applySurface(int x, int y, SDL_Surface *source, SDL_Surface *destination) { 
    SDL_Rect offset; 
    offset.x = x; 
    offset.y = y; 

    SDL_BlitSurface(source, NULL, destination, &offset); 
} 

bool initSDL(void) { 
    if (SDL_Init(SDL_INIT_EVERYTHING) == -1) { 
     return NULL; 
    } 
    screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE); 

    if (screen == NULL) { 
     return NULL; 
    } 

    SDL_WM_SetCaption("Bounce", NULL); 
    return true; 
} 

/*Cleans all needed things*/ 
void cleanUp(SDL_Surface *image) { 
    SDL_FreeSurface(image); 
    SDL_Quit(); 
} 

/*The Ball structure for OOP*/ 
struct Ball { 
    int x; 
    int y; 
    int vy; 
    int vx; 
    SDL_Surface *image; 
}; 

/*initialize a Ball structure*/ 
struct Ball ball_initBall(int x, int y, int vy, int vx, char *filename) { 
    struct Ball b; 
    b.x = x; 
    b.y = y; 
    b.vy = vy; 
    b.vx = vx; 
    b.image = loadImage(filename); 

    return b; 
} 

void ball_move(struct Ball b) { 
    b.x += b.vx; 
    b.y += b.vy; 
    b.vy += GRAVITY; 
} 

void ball_wallCollide(struct Ball b) { 
    if (b.x <= 1 || b.x >= 500 - 48) { 
     b.vx *= -1; 
    } 

    if (b.y <= 1 || b.y >= 500 - 49) { 
     b.vy *= -0.95; 
    } 
} 

int main(int argc, char *argv[]) { 
    bool running = true; 
    initSDL(); 

    struct Ball ball1 = ball_initBall(SCREEN_HEIGHT/2, SCREEN_WIDTH/2, 1, 3, "resources/ball.jpg"); 

    while (running) { 
     applySurface(ball1.x, ball1.y, ball1.image, screen); 


     ball_move(ball1); 
     ball_wallCollide(ball1); 

     while (SDL_PollEvent(&event)) { 
      if (event.type == SDL_QUIT) { 
       running = false; 
      } 
     } 
     SDL_Flip(screen); 
     SDL_FillRect(screen, &screen->clip_rect, SDL_MapRGB(screen->format, 0, 0, 0)); 
     SDL_Delay(50); 
    } 
    cleanUp(ball1.image); 
    return 0; 
} 
+1

定義「不工作」的地址。你到目前爲止嘗試過哪些調試? –

+0

是的,我應該有。球不動。 –

回答

0

ball_moveball_wallCollide把他們Ball參數的值。這意味着他們會獲得調用者實例的副本。如果你想更新調用者的實例,你需要傳遞一個指向該實例的指針。

void ball_move(struct Ball* b) { 
    b->x += b->vx; 
    b->y += b->vy; 
    b->vy += GRAVITY; 
} 

和變革的要求傳遞Ball的更新

ball_move(&ball1); 
+0

哦,謝謝!我永遠不會想到這一點! –