Having a problem with a game that i'm making
Posted: Fri Feb 13, 2009 7:22 pm
So I made a simple game a few days ago. Now i'm rewriting parts of it to make it better. My problem is that you can shoot at enemies, but when the projectile hits instead of the projectile destroying itself; it resets to 0,0 and then when it hits its target again it crashes.
my AMMO structure
my projectile creation code
My projectile handling code
code to fire the projectile
As far as i can tell the problem is that the projectile is getting double free'd somewhere in the DrawAmmo Function, but that shouldn't happen as ammo is getting set to NULL and i have if()s around all my Free()s
my AMMO structure
Code: Select all
struct AMMO
{
SDL_Rect box;
struct PARTICLESYS *particles; //not used yet
unsigned char target;
unsigned char status;
};
Code: Select all
struct AMMO *DoAmmo(unsigned char type)
{
struct AMMO *ammo;
ammo=malloc(sizeof(struct AMMO));
switch(type)
{
case 1:
ammo->box.x=player.x;
ammo->box.y=player.y;
ammo->box.h=5;
ammo->box.w=5;
ammo->status=1;
ammo->target=ctarget; //current target
break;
default:
break;
}
return ammo;
}
Code: Select all
void DrawAmmo(struct AMMO *ammo)
{
int d;
if(ammo!=NULL)
{
switch(ammo->status)
{
case 1:
ammo->box.h=5;
ammo->box.w=5;
SDL_FillRect(screen,&ammo->box,SDL_MapRGB(screen->format,255,0,0));
if(ammo->box.x>targets[ammo->target]->box.x) ammo->box.x-=3;
if(ammo->box.x<targets[ammo->target]->box.x) ammo->box.x+=3;
if(ammo->box.y>targets[ammo->target]->box.y) ammo->box.y-=3;
if(ammo->box.y<targets[ammo->target]->box.y) ammo->box.y+=3;
d=distance(ammo->box.x,ammo->box.y,targets[ammo->target]->box.x,targets[ammo->target]->box.y);
if(ammo->box.x==targets[ammo->target]->box.x&&ammo->box.y==targets[ammo->target]->box.y||d<10)
{
printf("ammo hit\n%d\n",d);
targets[ammo->target]->health-=20;
if(targets[ammo->target]->status==1) //turn the target hostile if they're currently neutral
{
targets[ammo->target]->status=2;
targets[ammo->target]->color=SDL_MapRGB(screen->format,255,0,0);
}
killtarget(targets[ammo->target]);
free(ammo);
ammo=NULL;
printf("ammo freed\n%x\n",ammo); //this stuff happens, but for some reason ammo is getting double free'd
}
break;
default:
break;
}
}
}
Code: Select all
if(playerm>10) //playerm=player mana
{
if(ammo!=NULL) //to prevent memory leaks
{
free(ammo);
ammo=NULL;
}
ammo=DoAmmo(1);
playerm-=10;
for(count=0;count!=5;count++)
{
if(targets[count]->status==3) targets[count]->status=2; //unfreezes all frozen targets
}
}