简体   繁体   中英

Collision Detection for fast-moving objects

I am writing my first game for android, and have run into an issue with collision checking. The game consists of a scrolling scene in which a block jumps when tapped, and must land on varying height buildings. The issue is, the the block often ends up through the floor, due to frames not updating fast enough. I have tried putting the collision detection in a separate thread, and whilst this does improve detection slightly, it is still not great. Whilst I do compensate by setting the height manually for the next frame, I fear that for slower devices than my Nexus 5 the object will simply fall through the building, as it does occasionally on this device. My code is as follows:

public void physics() {

        // Generate Player Rectangle
        player.set(x1,y1, x2,y2);
        // Check building rectangle
        if (player.intersects(x1,y1,x2,y2)) {
            character.collide();
        }
    }

Can anyone point me in the right direction for detecting this with more accuracy? I haven't been able to find an answer which suits my need. Thanks!

Assuming that the object's X or Y velocity is added to the object's coordinates each step event, the "receiving" object (eg the ground or the wall) must always have a larger width or height than the velocity of the moving object.

If your object's X coordinate increases by 1000 each step, and the width of the wall is only 32, it is highly unlikely the bounds of the projectile will intersect with the wall. The easy solution is to set the bounds of the "receiving" object to encompass where the projectile might be.

For example:

public void onStep()
{
    for (Wall wall : wall_items) // Assuming wall_items is iterable
    {
        // Do not modify walls behind or above projectile
        if (wall.x > this.x == false) continue;
        if (wall.y > this.y == false) continue; // Skip and continue loop

        wall.width = this.width + this.velocity_x;
        wall.height = this.height + this.velocity_y;
    }

    this.x += this.velocity_x;
    this.y += this.velocity_y;
}

Now, when the projectile is moving, the projectile MUST land in the bounds of the wall that is in the way of the flying projectile. I hope this gives you a better understanding of collision detection.

Edit: The conditions to check if the walls are behind or above the projectile should continue not return , as you still want to remain in the onStep() method. My apologies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM