Java : 2D Collision Detection

Posted by neko on Game Development See other posts from Game Development or by neko
Published on 2013-10-17T15:37:43Z Indexed on 2013/10/17 16:26 UTC
Read the original article Hit count: 280

Filed under:
|
|

I'm been working on 2D rectangle collision for weeks and still cannot get this problem fixed. The problem I'm having is how to adjust a player to obstacles when it collides. I'm referencing this link. The player sometime does not get adjusted to obstacles. Also, it sometimes stuck in obstacle guy after colliding. Here, the player and the obstacle are inheriting super class Sprite

I can detect collision between the two rectangles and the point by ;

public Point getSpriteCollision(Sprite sprite, double newX, double newY) {
    // set each rectangle
    Rectangle spriteRectA = new Rectangle(
        (int)getPosX(), (int)getPosY(), getWidth(), getHeight());
    Rectangle spriteRectB = new Rectangle(
        (int)sprite.getPosX(), (int)sprite.getPosY(), sprite.getWidth(), sprite.getHeight());

    // if a sprite is colliding with the other sprite
    if (spriteRectA.intersects(spriteRectB)){
        System.out.println("Colliding");
        return new Point((int)getPosX(), (int)getPosY());
    }
    return null;
}

and to adjust sprites after a collision:

// Update the sprite's conditions 
public void update() { // only the player is moving for simplicity
    // collision detection on x-axis (just x-axis collision detection at this moment)
    double newX = x + vx; // calculate the x-coordinate of sprite move

    Point sprite = getSpriteCollision(map.getSprite().get(1), newX, y);// collision coordinates (x,y)
    if (sprite == null) { // if the player is no colliding with obstacle guy
        x = newX; // move
    } else { // if collided
        if (vx > 0) { // if the player was moving from left to right
            x = (sprite.x - vx); // this works but a bit strange    
        } else if (vx < 0) {
            x = (sprite.x + vx); // there's something wrong with this too
        }
    }
    vx=0;
    y+=vy;
    vy=0;
}

I think there is something wrong in update() but cannot fix it. Now I only have a collision with the player and an obstacle guy but in future, I'm planning to have more of them and making them all collide with each other. What would be a good way to do it?

Thanks in advance.

© Game Development or respective owner

Related posts about java

Related posts about 2d