Push back rectangle where collision happens

Posted by Tifa on Game Development See other posts from Game Development or by Tifa
Published on 2013-06-29T06:00:35Z Indexed on 2013/06/29 10:30 UTC
Read the original article Hit count: 384

Filed under:
|

I have a tile collision on a game I am creating but the problem is once a collision happens for example a collision happens in right side my sprite cant move to up and bottom :( thats because i set the speed to 0. I thinks its wrong. here is my code:

int startX, startY, endX, endY;
    float pushx = 0,pushy = 0;
    // move player
    if(Gdx.input.isKeyPressed(Input.Keys.LEFT)){
        dx=-1;
        currentWalk = leftWalk;

    }
    if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)){
        dx=1;
        currentWalk = rightWalk;

    }
    if(Gdx.input.isKeyPressed(Input.Keys.DOWN)){
        dy=-1;
        currentWalk = downWalk;
    }
    if(Gdx.input.isKeyPressed(Input.Keys.UP)){
        dy=1;
        currentWalk = upWalk;
    }



    sr.setProjectionMatrix(camera.combined);
    sr.begin(ShapeRenderer.ShapeType.Line);
    Rectangle koalaRect = rectPool.obtain();
    koalaRect.set(player.getX(), player.getY(), pw, ph /2 );

    float oldX = player.getX(), oldY = player.getY(); // THIS LINE WAS ADDED

    player.setXY(player.getX() + dx * Gdx.graphics.getDeltaTime() * 4f, player.getY() + dy * Gdx.graphics.getDeltaTime() * 4f); // THIS LINE WAS MOVED HERE FROM DOWN BELOW



        if(dx> 0) {
            startX = endX = (int)(player.getX() + pw);
        } else {
            startX = endX = (int)(player.getX()  );
        }
        startY = (int)(player.getY());
        endY = (int)(player.getY() + ph);
        getTiles(startX, startY, endX, endY, tiles);

        for(Rectangle tile: tiles) {
            sr.rect(tile.x,tile.y,tile.getWidth(),tile.getHeight());
            if(koalaRect.overlaps(tile)) {

                    //dx = 0;
                    player.setX(oldX); // THIS LINE CHANGED
                    Gdx.app.log("x","hit  " + player.getX() + " " + oldX);
                    break;

            }
        }

        if(dy > 0) {
            startY = endY = (int)(player.getY() + ph );
        } else {
            startY = endY = (int)(player.getY() );
        }
        startX = (int)(player.getX());
        endX = (int)(player.getX() + pw);
        getTiles(startX, startY, endX, endY, tiles);

        for(Rectangle tile: tiles) {
            if(koalaRect.overlaps(tile)) {
                //dy = 0;
                player.setY(oldY); // THIS LINE CHANGED
                //Gdx.app.log("y","hit" + player.getY() + " " + oldY);
                break;
            }
        }


    sr.rect(koalaRect.x,koalaRect.y,koalaRect.getWidth(),koalaRect.getHeight() / 2);
    sr.setColor(Color.GREEN);
    sr.end();

I want to push back the sprite when a collision happens but i have no idea how :D pls help

© Game Development or respective owner

Related posts about java

Related posts about libgdx