Platform game collisions with Block

Posted by Sri Harsha Chilakapati on Game Development See other posts from Game Development or by Sri Harsha Chilakapati
Published on 2012-10-27T12:19:05Z Indexed on 2012/10/27 17:18 UTC
Read the original article Hit count: 266

I am trying to create a platform game and doing wrong collision detection with the blocks.

Here's my code

// Variables
GTimer jump = new GTimer(1000);
boolean onground = true;

// The update method
public void update(long elapsedTime){
    MapView.follow(this);
    // Add the gravity
    if (!onground && !jump.active){
        setVelocityY(4);
    }
    // Jumping
    if (isPressed(VK_SPACE) && onground){
        jump.start();
        setVelocityY(-4);
        onground = false;
    }
    if (jump.action(elapsedTime)){
        // jump expired
        jump.stop();
    }
    // Horizontal movement
    setVelocityX(0);
    if (isPressed(VK_LEFT)){
        setVelocityX(-4);
    }
    if (isPressed(VK_RIGHT)){
        setVelocityX(4);
    }
}

// The collision method
public void collision(GObject other){
    if (other instanceof Block){
        // Determine the horizontal distance between centers
        float h_dist = Math.abs((other.getX() + other.getWidth()/2) - (getX() + getWidth()/2));
        // Now the vertical distance
        float v_dist = Math.abs((other.getY() + other.getHeight()/2) - (getY() + getHeight()/2));
        // If h_dist > v_dist horizontal collision else vertical collision
        if (h_dist > v_dist){
            // Are we moving right?
            if (getX()<other.getX()){
                setX(other.getX()-getWidth());
            }
            // Are we moving left?
            else if (getX()>other.getX()){
                setX(other.getX()+other.getWidth());
            }
        } else {
            // Are we moving up?
            if (jump.active){
                jump.stop();
            }
            // We are moving down
            else {
                setY(other.getY()-getHeight());
                setVelocityY(0);
                onground = true;
            }
        }
    }
}

The problem is that the object jumps well but does not fall when moved out of platform. Here's an image describing the problem.

error

I know I'm not checking underneath the object but I don't know how. The map is a list of objects and should I have to iterate over all the objects???

Thanks

© Game Development or respective owner

Related posts about java

Related posts about collision-detection