Stop sprite from ghosting through another sprite

北城以北 提交于 2019-12-11 17:59:10

问题


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).



来源:https://stackoverflow.com/questions/11202572/stop-sprite-from-ghosting-through-another-sprite

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!