Collision

Hi I have a problem with my code where parts of it need to be defined but i dont know where about to do it since i used structures here is my code any pointers would be really helpful thank you.

the code from my cpp file
1
2
3
4
5
6
7
8
9
10
11
void Pacman::CheckGhostCollisions()
{
	//Implement collision detection between the ghosts and pacman 
	for (int i = 0; i < GHOSTCOUNT; i++)
	{
if (CollisionCheck(pacman.x, pacman.y, pacmanWidth, pacmanHeight, _ghosts[i]->x, _ghosts[i]->y, _ghosts[i]->width, _ghosts[i]->height))
    _pacman->Dead = true;// Collision occurred
		
	}

}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 bool CollisionCheck(int x1, int y1, int width1, int height1, int x2, 
int y2, int width2, int height2)
{
	int left1 = x1;
	int left2 = x2;
	int right1 = x1 + width1;
	int right2 = x2 + width2;
	int top1 = y1;
	int top2 = y2;
	int bottom1 = y2 + height1;
	int bottom2 = y2 + height2;
	if (bottom1 < top2)
		return false;
	if (top1 > bottom2)
		return false;
	if (right1 < left2)
		return false;
	if (left1 > right2)
		return false;

	return true;
	}


here are my structures for my code that are in my header file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct Player
{
	Vector2* Position;
	Rect* SourceRect;
	Texture2D* Texture;
	int Direction;
	int Frame;
	int CurrentFrameTime;
	bool Dead;
	int x; 
	int y; 
	int width; 
	int height;

};


1
2
3
4
5
6
7
8
9
10
11
12
struct MovingEnemy
{
	Rect* Position;
	Rect* sourceRect;
	Texture2D* texture;
	int direction;
	float speed;
	int x;
	int y;
	int width;
	int height;
};
If you described a creature as a center(x, y) and a single delta, d, for the +/- height and width, you could detect collision as:
1
2
3
4
5
6
7
8
9
10
11
for (size_i i = 0; i pacman.IsAlive() && != ghosts.size(); ++i)
{
    const ghost& : ghosts[i];
    if (abs(pacman.getX() - ghost.getX()) <= d ||
        abs(pacman.getY() - ghost.getY()) <= d)
    {
        // We're dead!
        pacman.Dead(true);
        break;
    }
}


You'd describe creature as:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Creature
{
    int x, y, d;

public:
    // ...
};

class Player : public Creature
{
// ...
};

class Ghost : public Creature
{
// ...
};
Last edited on
Topic archived. No new replies allowed.