Skip to content Skip to sidebar Skip to footer

My Collision Detection Isn't Working

I'm trying to make a simple game where you are pacman and need to collect cherries while avoiding the ghosts. I can't seem to figure out how to check for collision and i've tried s

Solution 1:

i dont see any atempt in your code at collision detection but it is very simple especally in 2D.

lets say you have 2 objects - A (pacman) and B (cherry)

if you want to know if they have collided then you need to do a point to point calculation.

Imagine drawing a circle round both that just fits, get the radius of the circle and then checking if distance between the two centre points of the circles is less than the circle radius. like so:-

float x, y;
float CircleRadius = 2.0f;
x = SmallModel->GetX() - LargeModel->GetX();    
y = SmallModel->GetY() - LargeModel->GetY();    


float collisionDist = sqrt( x*x + y*y);  

if (collisionDist < sphereRadius)
{
// Collision occurred…
}

its as easy as that

Solution 2:

You have an if condition somewhere in your code wherein you are doing console.log('hi') and I think this is your collision detection attempt though it's not clear. Here's a javascript solution for radius detection, similar to Rob85's approach:

functionisColliding(pacman, bonusItem) {
    var dx = pacman.x - bonusItem.x;
    var dy = pacman.y - bonusItem.y;
    var rr = pacman.radius + bonusItem.radius;
    if (dx * dx + dy * dy < rr * rr)
        returntrue;
    elsereturnfalse;
}

This assumes you give a 'hitbox' to your pacman and bonusItem objects in addition to the x and y coordinate properties. The idea is you test two circles colliding.

varpacman= {
    speed:256,
    x:0,
    y:0,
    height:50,
    width:50,
    radius:(height+width)/4//roughlyhalftheaveragehw
};varcherry= {
    x:100,
    y:100,
    height:56,
    width:56,
    radius:(height+width)/4;//roughlyhalftheaveragehw
};

I think circle-circle collision is simplest, so a good place to start and certainly adequate for Pacman and all of its complexity.

There's thorough coverage on circle-square collision in this post: Circle-Rectangle collision detection (intersection)

Moreover, you can consider doing a check of every pixel in your sprites. I never tried it, but this post looks helpful: Can someone explain per-pixel collision detection?

You may also consider using square-square collision detection. In general, here's a great article by Mozilla Developer Network: 2d collision detection

Post a Comment for "My Collision Detection Isn't Working"