libgdx анимация внутри прямоугольника - обнаружение столкновений - прямоугольники

Я пишу RPG-игру, похожую на стиль покемонов (вид сверху вниз). Сейчас я работаю над проблемой обнаружения столкновений. Я хочу создать обнаружение столкновений на основе прямоугольников. Проблема в том, что мне трудно нарисовать прямоугольник вокруг анимации, которую я ранее установил. Я искал в Google и YouTube ответ / учебник о том, как решить эту проблему, но пока ничего не нашел.

Player.class

public class Player {

public Vector2 position; 
private float moveSpeed;
private SpriteBatch batch;

//animation
public Animation an;
private Texture tex;
public TextureRegion currentFrame;
private TextureRegion[][] frames;
private float frameTime;


public Player(Vector2 position){
    this.position = position;
    moveSpeed = 5f;
    createPlayer();
}

public void createPlayer(){
    tex = new Texture("Sprites/image.png");
    frames = TextureRegion.split(tex, tex.getWidth()/3, tex.getHeight()/4);
    an = new Animation(0.10f, frames[0]);
}

public void render(float delta){
    handleInput();
    frameTime += delta;
    currentFrame = an.getKeyFrame(frameTime, true);
}

public void handleInput(){
    if(Gdx.input.isKeyPressed(Keys.UP)){
        an = new Animation(0.10f, frames[3]);
        position.y += moveSpeed;
    }
    if(Gdx.input.isKeyPressed(Keys.DOWN)){
        an = new Animation(0.10f, frames[0]);
        position.y -= moveSpeed;
    }
    if(Gdx.input.isKeyPressed(Keys.LEFT)){
        an = new Animation(0.10f, frames[1]);
        position.x -= moveSpeed;
    }
    if(Gdx.input.isKeyPressed(Keys.RIGHT)){
        an = new Animation(0.10f, frames[2]);
        position.x += moveSpeed;    
    }
    if(!Gdx.input.isKeyPressed(Keys.ANY_KEY)){
        an = new Animation(0.10f, frames[0]);
    }
}

public void dispose(){
    batch.dispose();
}

public float getX(){
    return position.x;
}

public float getY(){
    return position.y;
}

public int getWidth(){
    return 32;
}

public int getHeight(){
    return 32;
}

}

WorldRenderer.class

public class WorldRenderer {

private OrthogonalTiledMapRenderer renderer;
public OrthographicCamera camera;
private Player player;

//Tilemap
private TiledMapTileLayer collision;
private TiledMap map;


public WorldRenderer() {
    map = new TmxMapLoader().load("maps/testMap.tmx");
    renderer = new OrthogonalTiledMapRenderer(map);

    //Tiled layers
    collision = (TiledMapTileLayer) map.getLayers().get("collision");

    player = new Player(new Vector2(100, 100));
    camera = new OrthographicCamera();
    camera.viewportWidth = Gdx.graphics.getWidth()/2;
    camera.viewportHeight = Gdx.graphics.getHeight()/2;

}
public void render (float delta) {      
    camera.update();
    renderer.setView(camera);
    renderer.render();

    player.render(delta);


    // Calculate tile size in pixels
    MapProperties prop = renderer.getMap().getProperties();
    int mapWidth = prop.get("width", Integer.class); //how many tiles in map
    int mapHeight = prop.get("height", Integer.class);
    int tilePixelWidth = prop.get("tilewidth", Integer.class); //size of each tile
    int tilePixelHeight = prop.get("tileheight", Integer.class);

    // Calculate total map size
    int worldSizeX = mapWidth * tilePixelWidth;
    int worldSizeY = mapHeight * tilePixelHeight;

    // Calculate min/max camera points inside the map
    float minCameraX = camera.zoom * (camera.viewportWidth / 2); 
    float maxCameraX = worldSizeX - minCameraX;
    float minCameraY = camera.zoom * (camera.viewportHeight / 2);
    float maxCameraY = worldSizeY - minCameraY;

    // set the camera to either the player or the min/max of the camera based on player position
    camera.position.set(
            Math.min(maxCameraX, Math.max(player.position.x + 32 / 2, minCameraX)),
            Math.min(maxCameraY, Math.max(player.position.y + 32 / 2, minCameraY)),
            0);
    camera.update();
    renderer.getSpriteBatch().setProjectionMatrix(camera.combined);



    renderer.getSpriteBatch().begin();
    renderer.getSpriteBatch().draw(player.currentFrame, player.position.x, player.position.y);
    renderer.getSpriteBatch().end();
}

}

1 ответ

Решение

Если вы хотите обнаружить столкновение между двумя прямоугольниками, есть пример, который я использовал со спрайтами.

public class TestSpriteOne extends Sprite{  
    private Rectangle rectangle;

Добавьте в конструктор.

rectangle = new Rectangle(getX(), getY(), getWidth(), getHeight());

В методе обновления

rectangle.setPosition(getX(), getY());

Это новый нетход

public Rectangle getColliderActor(){
    return this.rectangle;
}

Другие классы

public class TestSpriteTwo extends Sprite{
    private Rectangle rectangle;

В конструкторе.

rectangle = new Rectangle(getX(), getY(), getWidth(), getHeight());

В методе обновления

rectangle.setPosition(getX(), getY());

В новом методе

public Rectangle getColliderActor(){
   return this.rectangle;
}

// Вызов в классе TestSpriteOne

boolean hasCollided = TestSpriteTwo.getColliderActor().overlaps(getColliderActor());

// Вызов в классе GameScreen

boolean hasCollided = TestSpriteOne.getColliderActor().overlaps(TestSpriteTwo.getColliderActor());

Он перекрывает, перекрывает ли этот прямоугольник другой прямоугольник, поэтому переменная hasCollided станет истинной.

Редактировать: если анимация меняет свою ширину или высоту, вы можете изменить размер прямоугольника в методе обновления

rectangle.setSize (width, height);
Другие вопросы по тегам