Search code examples
collision-detection

Making a bullet collide with an enemy in DirectX


I'm trying to work on a project for school but I'm really struggling to make my bullets hit the enemy object perfectly. So far they kinda occasionally collide in a random location on the enemy but that only works some of the time which is frustrating!

This is what I have so far:

     for (int i = 0; i < 200; i++){ // 200 is number of bullets I use
            for (int k = 0; k < game.enemiesVec.size(); k++){
            if ((((bullets[i].pos.x + 0.15f) >(game.enemiesVec[k].x))) && ((bullets[k].pos.x - 0.15f) < (game.enemiesVec[k].x)) &&
                (((bullets[i].pos.y) < (game.enemiesVec[k].y -0.15f)) && ((bullets[k].pos.y) > (game.enemiesVec[k].y +0.15f)))){
     //do stuff            
     game.enemiesVec[k].x = 5;
            }
            }
    }

I'm clueless tbh, I know I need to somehow maybe get the radius of the object so it has a bigger area to collide with but I've no idea!

Hopefully someone can help!


Solution

  • Increasing the size of the enemies may fix the problem in some situations, but aren't preventing the problem completely. Your bullets are probably moved every frame leading to "jumps" of their position. Now you are testing each frame their current position against the enemies, but this approach disregards the movement between the frames. So if you would increase the radius to a size bigger than the maximum distance a bullet can move in one frame, you could avoid the situation, but this would lead to fat enemies and there are still edge cases, like if the bullet would only hit a small corner of the bounding rectangles. One real solution would be to test a line against the bounding rectangles and not a single point. The line would consist of the start of the movement and lead to the end. If this line collides with the rectangle, the bullet has hit the enemy on its path. I've drawn a little image to show the situation:

    PointIntersectionProblem

    With the line-rectangle intersection tests, you would also get rid of the random intersection points in the enemy body, because you could compute the entry point.