In this chapter, we are going to do something simple, create a game boundary which consists of the width and height of the screen where the player and the enemy is going to move around.

First, we will limit the x movement of the enemy within the width of the game scene by including the x movement control feature within the width of the game scene.

 public void createEnemy(Vector2 position) {
        enemy = new Enemy(world, enemyRegion, enemyMissile, em);
        if(position.x <= enemyRegion.getRegionWidth())
            position.x = 4;
        else if(position.x >= viewpostwidth-enemyRegion.getRegionWidth())
            position.x -= enemyRegion.getRegionWidth();
        enemy.createBodyFixture(position);
        enemy_list.add(enemy);
    }

Next, we create a method to limit the x and y movement of the player within the player object.

public void checkPosition() {
        // adjust the x position
        if(body.getPosition().x <= planeRegion.getRegionWidth()) {
            body.applyForceToCenter(50.0f, 50,  false);
            body.setLinearVelocity(50, 50);
        } else if(body.getPosition().x >= viewposrtwidth - planeRegion.getRegionWidth()) {
            body.applyForceToCenter(-50, -50,  false);
            body.setLinearVelocity(-50, -50);
        }
        //adjust the y position
        if(body.getPosition().y <= planeRegion.getRegionHeight()) {
            body.applyForceToCenter(50f, 50,  false);
            body.setLinearVelocity(50, 50);
        } else if(body.getPosition().y >= viewportheight - planeRegion.getRegionHeight()) {
            body.applyForceToCenter(-50,-50,  false);
            body.setLinearVelocity(-50, -50);
        }

    }

As you can see, the plane will bounce to another direction when it has came near to the game boundary.

Finally, we will call the player to check it’s own position in the MainActivity class.

private void updatePlayerPosition() {
		player.checkPosition();
	}

This is fast! And the code above will ensure all enemies and the player will only move within the game boundary.

Please follow and like us:

Leave a Reply

Your email address will not be published. Required fields are marked *