Handmade Hero»Forums»Code
Shazan Shums
159 posts
Some day I will make quality software. Programming FTW.
Collision Detection --- Detecting Sides....
Edited by Shazan Shums on
I need help detecting sides for my pong clone.
And left collsion not working.
I have Wall enities on all 4 sides.
But it bounces only when hitting the center.

Here's the code,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
struct minkowskirect{

    v2 Center;
    v2 Dim;
};


internal
minkowskirect MinkowskiSum(entity* A,entity* B){
    minkowskirect Result = {};
    Result.Center = (A->Pos - B->Pos);
    Result.Dim = 0.5*(A->Dim + B->Dim);
    return Result;
}


internal
b32 CheckCollision(entity* Test,entity* A){
    b32 Result = false;
    minkowskirect Rect = MinkowskiSum(A,Test);

 if(AbsoluteValue(Rect.Center.x) < Rect.Dim.x && AbsoluteValue(Rect.Center.y) < Rect.Dim.y){
       /* collision! */
    float wy = Rect.Dim.x * Rect.Center.y;
    float hx = Rect.Dim.y * Rect.Center.x;

    #define CollideTop 1
    #define CollideLeft 2
    #define CollideRight 3
    #define CollideBottom 4
    
    if (wy > hx)
        if (wy > -hx)
            Result = CollideTop;/* collision at the top */
        else
            Result = CollideLeft;/* on the left */
    else
        if (wy > -hx)
            Result = CollideRight;/* on the right */
        else
            Result = CollideBottom;/* at the bottom */

    return Result;
    }



here's main ball collision code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
Ball->Pos = MoveEntity(Ball,Input);
            b32 BallCollided = CheckCollision(Player,Ball)|CheckCollision(Enemy,Ball)|CheckCollision(WallRight,Ball)|CheckCollision(WallLeft,Ball)|CheckCollision(WallTop,Ball)|CheckCollision(WallBottom,Ball);
            if(BallCollided) {
                switch (BallCollided){
                    case CollideTop:{
                    Ball->ddPos.y = -Ball->ddPos.y; 
                    }break;
                    case CollideBottom:{
                    Ball->ddPos.y = -Ball->ddPos.y; 
                    }break;
                    case CollideLeft:{
                    Ball->ddPos.x = -Ball->ddPos.x; 
                    }break;
                    case CollideRight:{
                    Ball->ddPos.x = -Ball->ddPos.x; 
                    }break;
                    default: break;
                }
                Ball->Pos = MoveEntity(Ball,Input);
            }
Shazan Shums
159 posts
Some day I will make quality software. Programming FTW.
Collision Detection --- Detecting Sides....
Anyways fixed it ,Guess is was a typo.

Can someone help me on a formula on bouncing the ball when hit the pad.