xna - Collision detection - minor problem -


at minute, removes 1 or 2 asteroids, not appear on screen, think there's flaw in method, i'm not sure what...

    public void collisiondetection()     {         (int = 0; < ship.bullets.count; i++)         {             rectangle shiprectangle = new 

rectangle((int)ship.shipposition.x, (int)ship.shipposition.y, shiptexture.width, shiptexture.height);

            (j = 0; j < asteroidpositions.count; j++)             {                 asteroidrectangle = new rectangle((int)asteroidpositions[j].x, 

(int)asteroidpositions[j].y, asteroidtexture.width, asteroidtexture.height);

                vector2 position1 = asteroidpositions[j];                 vector2 position2 = ship.bullets[i];                  float cathetus1 = math.abs(position1.x - position2.x);                 float cathetus2 = math.abs(position1.y - position2.y);                  cathetus1 *= cathetus1;                 cathetus2 *= cathetus2;                  distance = (float)math.sqrt(cathetus1 + 

cathetus2);

                if ((int)distance < asteroidtexture.width)                 {                     score += 20;                     asteroidpositions.removeat(j);                     j--;                 }              }                 if (shiprectangle.intersects(asteroidrectangle))                 {                     lives--;                     asteroidpositions.removeat(j);                 }              if (lives == 0)                 exit();         } 

i think got of code wrong. should separate x , y axis during distance comparison, if y distance smaller width and x distance smaller height there collision.

i assume position middle of object otherwise algorithm far more complicated. assume bullet has virtually no size , x.axis width , y.axis height. without seeing rest of code hard tell ;-)

my suggestion:

                vector2 asteroidposition = asteroidpositions[j];                 vector2 shipposotion = ship.bullets[i];                  float distancex = math.abs(asteroidposition.x - shipposotion.x);                 float distancey = math.abs(asteroidposition.y - shipposotion.y);                  if ((int)distancex < asteroidtexture.width , (int)distancey < asteroidtexture.height )                 {                     score += 20;                     asteroidpositions.removeat(j);                     j--;                 } 

this code not tested @ all, don't have clue language is. take inspiration. hope work out.

p.s.: if interested mail source code of asteroid shooting game did while ago study it…


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

c# - How to execute a particular part of code asynchronously in a class -