Adam Morton Adam Morton - 3 months ago 8
C# Question

Enemy collision detection

Using theses variables how would i go about colliding pacman with a munchie?
I already have movement and the ceiling down it do sent have to be given the code more like explain what I would have to do.

Pacman variables
private Point frameSize = new Point(32, 32); // Pacman image size
private Point currentFrame = new Point(1, 0); // Start frame
private Point sheetSize = new Point(2, 4); // Spritesheet size
private Vector2 pacmanPos; // Pacman position in pixels
private int pacmanSpeed = 8; // Pacman movement speed in pixels

// Game
SpriteBatch spriteBatch;
Texture2D munchie1, munchie2, pacman;

// Sounds
SoundEffect collisionSound;

// Random number generator
Random rand = new Random();

// Total number of munchies
private int noOfMunchies = 5;

Vector2[] munchiePos;
private int munchieSize;
private int[] munchieAnimationCount;

private int timeSinceLastFrame = 0;
private int milliSecondsPerFrame = 500; // 2 Frames Per Second (fps)

Mir Mir
Answer

Since you've defined munchieSize but not pacmanSize I suppose that you're considering your actor a dot. In that case, assuming that pacman's and the munchies' coordinates are relative to the same system, it will be enough to check in each frame or collision test iteration if pacman's position's vector is contained in any of the munchies' bounding box.

You can do it this way, consider that my code is just a reference and you should use your own types to achieve the result.

var munchies = new PointF[5];
const int munchySize = 10;
var pacmanPos = new PointF();
var collidesWith = munchies.
    Where(m => new RectangleF(m, new SizeF(munchySize, munchySize)).Contains(pacmanPos));
var collisionHappened = collidesWith.Any();
Comments