当前位置: 首页 > 知识库问答 >
问题:

矩形之间的碰撞检测

周通
2023-03-14

在我的自上而下游戏中,当我的玩家通过婴儿床时,我该如何让他发生碰撞?我用的是交叉矩形。

这是我的密码

Rectangle player = new Rectangle();
Rectangle babycrib = new Rectangle();
Rectangle intersection = new Rectangle(); 


// Load the sprite sheet as a texture
    cat = new Texture(Gdx.files.internal("spriteCatsheet.png"));
    catsprite = new Sprite(cat);
    player = new Rectangle();
    player.x = Gdx.graphics.getWidth() - player.width - 350; 

    baby = new Texture(Gdx.files.internal("baby.png"));
    sprite_baby = new Sprite(baby);
    babycrib = new Rectangle();
    sprite_baby.setPosition(180,4000);

更新方法

   public void update(){
    deltaTime = Gdx.graphics.getDeltaTime();
    camera.update();   
}

在渲染方法中

// check collision
    Intersector.intersectRectangles(player, babycrib, intersection);
     if(intersection.x > player.x)
        //Intersects with right side
     if(intersection.y > player.y)
            //Intersects with top side
     if(intersection.x + intersection.width < player.x + player.width)
                //Intersects with left side
     if(intersection.y + intersection.height < player.y + player.height)
                    //Intersects with bottom side
     Intersector.overlaps(player,babycrib);

这是完整的代码

 public class GameScreen implements Screen ,InputProcessor {

final MyGdxGame game;
// Constant rows and columns of the sprite sheet
private static final int FRAME_COLS = 8, FRAME_ROWS = 4;
private boolean peripheralAvailable;
// Objects used
Animation<TextureRegion> walkAnimation; // Must declare frame type (TextureRegion)
Texture left_paw,right_paw;

Texture baby,cat;
SpriteBatch spriteBatch;
Sprite catsprite,sprite_baby;
ImageButton moveBackward,moveForward;
Viewport viewport;
private Stage stage;
private static float fade;
// A variable for tracking elapsed time for the animation
float stateTime;
private TextureRegion myTextureRegion;
TextureRegion textureRegion;
private TextureRegionDrawable myTexRegionDrawable;

OrthographicCamera camera;
Rectangle player = new Rectangle();
Rectangle babycrib = new Rectangle();
Rectangle intersection = new Rectangle();


float deltaTime;
int progressKnobX = 18;
Float fadeTime = 1f;

public GameScreen(final MyGdxGame game) {
    this.game = game;
    stage = new Stage(new StretchViewport( 720, 1280));
    camera = new OrthographicCamera(1280 ,720);
    Gdx.input.setCatchBackKey(true);
    camera.update();
    Gdx.graphics.setContinuousRendering(true);
    Gdx.graphics.requestRendering();
    camera.setToOrtho(false, 720, 1280);
    Gdx.input.setInputProcessor(stage);
    spriteBatch = new SpriteBatch();
    Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    Gdx.input.setInputProcessor( this);
    peripheralAvailable = Gdx.input.isPeripheralAvailable(Input.Peripheral.Accelerometer);
    viewport = new ScreenViewport();

    baby = new Texture(Gdx.files.internal("equip/baby.png"));
    sprite_baby = new Sprite(baby);
    babycrib = new Rectangle();
    sprite_baby.setPosition(180,4000);


    // Load the sprite sheet as a texture
    cat = new Texture(Gdx.files.internal("spriteCatsheet.png"));
    catsprite = new Sprite(cat);
    player = new Rectangle();
    player.x = Gdx.graphics.getWidth() - player.width - 350; //250;  //550 // 410
    // Use the split utility method to create a 2D array of TextureRegions. This is
    // possible because this sprite sheet contains frames of equal size and they are
    // all aligned.
    TextureRegion[][] tmp = TextureRegion.split(cat, cat.getWidth() /   FRAME_COLS , cat.getHeight()/ FRAME_ROWS);
    // Place the regions into a 1D array in the correct order, starting from the top
    // left, going across first. The Animation constructor requires a 1D array.
    TextureRegion[] walkFrames = new TextureRegion[FRAME_COLS * FRAME_ROWS];
    int index = 0;
    for (int i = 0; i < FRAME_ROWS; i++) {
        for (int j = 0; j < FRAME_COLS; j++) {
            walkFrames[index++] = tmp[i][j];
        }
    }
    // Initialize the Animation with the frame interval and array of frames
    walkAnimation = new Animation<TextureRegion>(0.099f, walkFrames);
    // Instantiate a SpriteBatch for drawing and reset the elapsed animation
    // time to 0
    spriteBatch = new SpriteBatch();
    stateTime = 0f;
    //left_control
    left_paw = new Texture(Gdx.files.internal("left_paw.png"));
    myTextureRegion = new TextureRegion(left_paw);
    myTexRegionDrawable = new TextureRegionDrawable(myTextureRegion);
    moveBackward = new ImageButton(myTexRegionDrawable); //Set the button up
    moveBackward.getStyle().imageUp = new TextureRegionDrawable(new TextureRegion(new Texture(Gdx.files.internal("left_paw.png"))));
    //the hover
    moveBackward.getStyle().imageDown = new TextureRegionDrawable(new TextureRegion(new Texture(Gdx.files.internal("left_paw_hover.png"))));
    moveBackward.setPosition(10,25);
    stage.addActor(moveBackward); //Add the button to the stage to perform rendering and take input.
    Gdx.input.setInputProcessor(stage);
    moveBackward.addListener(new InputListener(){
        @Override
        public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
            System.out.println("Left Button Pressed");
            //Start Animation
            progressKnobX = progressKnobX - 4;
            Gdx.graphics.setContinuousRendering(true);
            motionState=MotionState.NONE;
        }
        @Override
        public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
            System.out.print("Released");
            Gdx.graphics.setContinuousRendering(false);
            motionState=MotionState.DOWN;
            return true;
        }
    });
    stage.addActor(moveBackward);
    //right_control
    right_paw = new Texture(Gdx.files.internal("right_paw.png"));
    myTextureRegion = new TextureRegion(right_paw);
    myTexRegionDrawable = new TextureRegionDrawable(myTextureRegion);
    moveForward = new ImageButton(myTexRegionDrawable); //Set the button up
    moveForward.getStyle().imageUp = new TextureRegionDrawable(new TextureRegion(new Texture(Gdx.files.internal("right_paw.png"))));
    //the hover
    moveForward.getStyle().imageDown = new TextureRegionDrawable(new TextureRegion(new Texture(Gdx.files.internal("right_paw-hover.png"))));
    moveForward.setPosition(517,25);
    stage.addActor(moveForward); //Add the button to the stage to perform rendering and take input.
    Gdx.input.setInputProcessor(stage);
    moveForward.addListener(new InputListener(){
        @Override
        public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
            System.out.println("Right Button Pressed");
            progressKnobX = progressKnobX + 4;

            motionState=MotionState.NONE;
        }
        @Override
        public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
            motionState=MotionState.UP;
            return true;
        }
    });
    stage.addActor(moveForward);
}
public enum State
{
    PAUSE,
    RUN,
    RESUME,
    STOPPED
}
private State state = State.RUN;

MotionState motionState=MotionState.NONE;
enum MotionState {
    NONE {
        @Override
        public boolean update(Rectangle player) {
            return true;
        }
    },

    UP {
        @Override
        public boolean update(Rectangle player) {
            player.y += 300 * Gdx.graphics.getDeltaTime();
            return false;
        }
    },
    DOWN{
        @Override
        public boolean update(Rectangle player) {
            player.y -= 300 * Gdx.graphics.getDeltaTime();
            return false;
        }
    },
    LEFT{
        @Override
        public boolean update(Rectangle player)  {
            player.x -= 100 * Gdx.graphics.getDeltaTime();
            return false;
        }
    },
    RIGHT{
        @Override
        public boolean update(Rectangle player) {
            player.x  += 100 * Gdx.graphics.getDeltaTime();
            return false;
        }
    };
    public abstract boolean update(Rectangle player);
}

@Override
public void show() {
}
public void update(){
deltaTime = Gdx.graphics.getDeltaTime();
camera.position.x += 10;
camera.position.y += 10;
camera.update();
}
@Override
public void render(float delta) {
    // clear previous frame
    Gdx.gl.glClearColor(0.294f, 0.294f, 0.294f, 1f);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // Clear screen
    stateTime += Gdx.graphics.getDeltaTime(); // Accumulate elapsed animation time
    camera.update();
    update();
    spriteBatch.begin();
    stateTime += Gdx.graphics.getDeltaTime();
    TextureRegion currentFrame = walkAnimation.getKeyFrame(stateTime, true);
    camera.position.x = player.getX() + 100; //190
    camera.position.y = player.getY() + 180;
    camera.position.x = 350;
    update();
    spriteBatch.setProjectionMatrix(camera.combined);
    spriteBatch.draw(currentFrame,player.x, player.y);
    sprite_baby.draw(spriteBatch);


    if(Gdx.input.isKeyPressed(Input.Keys.DOWN)) motionState = MotionState.DOWN;
    if(Gdx.input.isKeyPressed(Input.Keys.UP)) motionState=MotionState.UP;
    if(Gdx.input.isKeyPressed(Input.Keys.LEFT)) motionState=MotionState.LEFT;
    if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)) motionState=MotionState.RIGHT;

    if(motionState.update(player)) motionState=MotionState.NONE;


    // check collision
    Intersector.intersectRectangles(player, babycrib, intersection);
    if(intersection.x > player.x)
        //Intersects with right side
        if(intersection.y > player.y)
            //Intersects with top side
            if(intersection.x + intersection.width < player.x + player.width)
                //Intersects with left side
                if(intersection.y + intersection.height < player.y + player.height)
                    //Intersects with bottom side
                    Intersector.overlaps(player,babycrib);
    //Intersects with bottom side


    if(!player.overlaps(babycrib)){
        Gdx.app.log("babycrib overlaps", "yes");
    }

    //Mobile acceleration
    if (Gdx.input.isPeripheralAvailable(Input.Peripheral.Accelerometer)) {
        player.x -= Gdx.input.getAccelerometerX();
    }
    if (player.x < 0) {
        player.x = 0;
        player.x += Gdx.graphics.getDeltaTime() *20 *delta;
    }
    if (player.x > Gdx.graphics.getWidth()-player.getWidth() -150) {
        player.x = Gdx.graphics.getWidth()-player.getWidth() -150;
    }
    if(this.state==State.RESUME) {
        switch (state) {
            case RUN:
                //do suff here
                break;
            case PAUSE:
                break;
            case RESUME:
                break;
            default:
                break;
        }
    }
    spriteBatch.end();
    stage.act(); //acting a stage to calculate positions of actors etc
    stage.draw(); //drawing it to render all
}


@Override
public void resize(int width, int height) {
    viewport.update(width, height);
    camera.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2, 0);
    camera.update();
}
@Override
public void pause() {

}
@Override
public void resume() {

}

@Override
public boolean keyDown(int keycode) {
    return false;
}

@Override
public boolean keyUp(int keycode) {
    return false;
}
@Override
public boolean keyTyped(char character) {
    return false;
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    return false;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
    return false;
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
    return false;
}
@Override
public boolean mouseMoved(int screenX, int screenY) {
    return false;
}
@Override
public boolean scrolled(int amount) {
    return false;
}
@Override
public void hide() {
}
@Override
public void dispose() { // SpriteBatches and Textures must always be disposed
}
}

谁能告诉我矩形碰撞检测的正确实现是什么?没有重叠,我是这个框架的新手。致谢和预付款:)

共有3个答案

西门嘉澍
2023-03-14

设置矩形的宽度和高度,例如:

player = new Rectangle();
player.setWidth( catsprite.getWidth() );    
player.setHeight( catsprite.getHeight() );

babycrib = new Rectangle();
babycrib.setWidth( babysprite.getWidth() );
babycrib.setHeight( babysprite.getHeight() );
司空修贤
2023-03-14

你的代码有些混乱,可能是因为你是这个框架的新手,所以我不能确切地说出哪里出了问题。

但是在碰撞检测点,看起来你只是更新了宽度和高度都为零的< code>player矩形的位置。也不改变大小为零的< code>babycrib矩形的位置。

您正在使用 :

< code>babycrib 矩形

不要为精灵创建新的矩形Sprite 有自己的矩形类型的边界数据成员因此请使用边界而不是新的矩形。

每当你想访问sprite_baby矩形使用sprite_baby.getBoundingRectangle(),当你想catsprite的矩形使用catsprite.getBoundingRectangle()

如果不想在代码中进行更多更改,请将Sprite的矩形引用保留为rectanglevariable,

sprite_baby = new Sprite(baby);
babycrib = sprite_baby.getBoundingRectangle();

catsprite = new Sprite(cat);
player = catsprite.getBoundingRectangle();
姬衡
2023-03-14

您可以使用播放器.包含(婴儿克里布)进行常规碰撞检测。您也可以使用“部门间”来实现此目的,但这也会计算发生的重叠区域。

if (Intersector.intersectRectangles(player, babycrib, intersection))
{
  //player and babycrib are intersecting...
  if (intersection.contains(babyRoom))
  {
    //Collision happened in baby room.
  }
}
 类似资料:
  • 我已经在这里呆了2-3周了,我仍然无法进行适当的碰撞检测。我用矩形创建了一个迷宫。我希望我的对象(在矩形中)每当我的对象与任何墙壁碰撞时停止,并能够移动到任何地方(或滑下墙壁)。我的墙壁(矩形)具有负坐标,如下所示: 我目前正在使用SO中发现的重叠方法。以下是我的CollisionManager类中的方法: 我有一个功能可以保存对象所做的所有位置移动。因此,当发生碰撞时,对象会恢复到最后一次移动之

  • 问题内容: 我遇到一个问题,即一个矩形与另一个矩形发生碰撞。所以我的问题是,如何获取相交方法以检查碰撞?还是在这种情况下还有其他方法可以处理碰撞? 我正在创建一个回合制战斗游戏(类似于《最终幻想》或《龙骑传奇》),其中玩家的角色在屏幕的右侧,而敌人在屏幕的左侧。玩家和敌人轮流进攻。因此,当玩家攻击时,子画面动画会从右到左在屏幕上移动,直到停在敌人面前,进行攻击并返回到其起始坐标。玩家和敌人周围都有

  • 我遇到了一个问题,显示一个矩形与另一个矩形发生了碰撞。所以我的问题是,如何让Intersect方法检查碰撞?或者在这种情况下有其他方法来处理碰撞吗? 我正在制作一个回合制战斗游戏(类似于《最终幻想》或《龙骑兵传说》),其中玩家的角色位于屏幕的右侧,敌人位于屏幕左侧。玩家和敌人轮流攻击。因此,当玩家攻击时,精灵动画会在屏幕上从右向左移动,直到它停在敌人面前,攻击并返回到其起始坐标。玩家和敌人都有一个

  • 因此,我创建了一个方法来检测球形球和矩形球之间的碰撞。我把它分成了4部分;它检测圆的顶部、圆的左侧、圆的底部、圆的右侧和矩形之间的碰撞。其中的两个工作是检测圆上的左点和矩形之间的碰撞,以及检测圆上的右点和矩形之间的碰撞。但是,不起作用的是,如果最上面的点或最下面的点接触矩形,就不会检测到碰撞,正如我记录if语句以查看是否输入它时所看到的那样。下面是我的代码(方法。getr()获取圆圈半径): 我已

  • 我正在编写一个游戏,涉及碰撞的一个移动的圆,由用户控制,和一个移动的矩形,由计算机控制。 完整的代码可以在这里找到:游戏 我在圆和矩形之间的碰撞检测方面遇到了麻烦。当矩形是静态的,碰撞检测工作完美。当圆和矩形的边缘在任一边接触时,程序就会按照它应该的方式进行操作。 这是碰撞检测功能。 谢谢。

  • 我在游戏中使用libGDX库。I用于检测两个矩形之间碰撞检测的用户重叠方法。 我想检测矩形上的触摸侧(顶部、底部、左侧或右侧): 谁能给我这个代码,但这需要快速的方法。 谢啦