Stop sprite from ghosting through another sprite

2019-09-18 23:56发布

问题:

Ok so I've just started learning java (I usually program in Objective-C). My first game is a game similar to Pokémon, however, its a lot more simplified obviously...

The trouble I'm having is I can't find a way to stop 2 sprites from 'ghosting' through each other. On screen I have borders set up (boundaries), A player sprite, and an Enemy sprite.

public void playerUpdate(GameContainer gc, int delta) throws SlickException
{
    Input input = gc.getInput();

    // Right Key Pressed
    if (input.isKeyDown(Input.KEY_RIGHT) && (leftKeyPressed == false)
            && (upKeyPressed == false) && (downKeyPressed == false))
    {
        player = walkRight;
        playerX += speed * delta;
        rightKeyPressed = true;
        if (playerX >= Main.getWindowWidth() - pImageWidth)
        {
            playerX -= speed * delta;
        }
    } else if (rightKeyPressed == true) 
    {
        player = standRight; 
        rightKeyPressed = false;
    } 

^^ this is where I need to implement the collision detection. I have added rectangles to each image for collision detection, however, I'm not after a way to make one disappear. I need a way to stop one sprite from walking through another.

Any ideas?

I have tried using

if (this.playerBoundingBox.intersects(Enemy.getEnemyBoundingBox())
{
    playerX += speed * delta;
}

However, when i implement this the player gets stuck and can not be freed.

Thanks guys

回答1:

Collision detection is a broad and deep topic, and there are many ways to implement it.

I'd strongly recommend reading The Guide To Implementing 2D Platformers, which should give you some great advice. I've implemented a 2D platform engine using the Sonic Retro Physics Guide, which was really useful.

In my game Clover: A Curious Tale I (needlessly!) implemented a more complicated hybrid of per-pixel collision with bounding boxes. The approach was to work out the desired movement path, and then check pixel-by-pixel to see if anything was in the way - if it was, only move as far as that pixel-minus-one.

Creating a 2D engine that is flawless in all circumstances is a very tall order, and not something you should attempt. Having some limits on things like size of an actor, and the maximum speed anything can travel in a single tick will make your life easier. Omitting things that can push the player will be much easier, as then you only have to do the collision detection once and in one 'direction' (ie when the player moves, rather than when all the other actors move).