简体   繁体   中英

How to delete a char image being called as a function in a loop in C?

I'm creating a game. I have a function, which draws a character image at random locations using a loop. I have collision logic which all works perfectly fine. The issue I'm having is that I don't know how to get the character image to delete from the game upon collision. The image is one of many of the same kind within the game display, so I specifically want to be able to delete the character image at the specific location, and decrease the stored total stored number if images of that type within the game, to return it on a scoreboard.

I've tried deleting the desired iteration of the called function in the same way you would if it was an array item, but that was just giving errors.

void drawEnemy(){
   drawEnemyImage(x[i], y[i], enemyImage);
}

void drawAllEnemies(){
   for(int i = 0; i < numEnemies; i++){
   drawEnemy(i);
   }
}
// (i also have collision logic here but it's not needed for the problem)

void returnCollision(){
    for (int i = 0; i < numEnemies; i++){
        if(collision() == true)
            return;
}

From this code, I can only presume you want to delete the enemy character image. Ok then. We would usually do something like this:

void deleteEnemy(int i) {
    --numEnemies;
    if (i == numEnemies) return;
    memmove(x + i, x + i + 1, (numEnemies - i) * sizeof(x[0]));
    memmove(y + i, y + i + 1, (numEnemies - i) * sizeof(y[0]));
}

Now the enemy in the middle of the arrays is gone. I'm assuming x and y are arrays of integers or something like that. If you have memory to free first, you would place the appropriate free() call before the if .

Please use better variables names for globals. enemyx and enemyy would be huge improvement already.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM