I want to make a simple flappy bird clone while I'm in vacation(The firt time I try game programming since high school) so after looking at ligdx wiki and sort of adapting the code to fit my needs I had something like this:
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Rectangle;
public class FlappyBall implements ApplicationListener {
Texture ballImage;
Texture chaoImage;
Texture canoImage;
OrthographicCamera camera;
SpriteBatch batch;
Rectangle ball;
int score = 0;
final float gravity = 9.0f;
#Override
public void create() {
ballImage = new Texture(Gdx.files.internal("crystalball_small.png"));
//chaoImage = new Texture(Gdx.files.internal("Flappy-Ground.png"));
camera = new OrthographicCamera(800,480);
camera.setToOrtho(false, 800, 480);
batch = new SpriteBatch();
ball = new Rectangle();
ball.x = 128;
ball.y = 20;
ball.width = 64;
ball.height = 64;
}
#Override
public void dispose() {
ballImage.dispose();
//chaoImage.dispose();
}
#Override
public void render() {
// cleans the screen
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
// rendenring ball
batch.setProjectionMatrix(camera.combined);
batch.begin();
batch.draw(ballImage, ball.x, ball.y);
batch.end();
// jump(not tested)
if (Gdx.input.isTouched()) {
ball.y += 10;
}
// apply gravity(not tested)
while (ball.y < 480)
ball.y -= gravity * Gdx.graphics.getDeltaTime();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}
however this code ends up showing a blank screen that can't even be closed when I press the X button(in order to close it I need to terminate its process in eclipse or use the xkill command :/)
Ps.:That's my Main.java file:
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
public class Main {
public static void main(String[] args) {
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
cfg.title = "Flappy Ball";
cfg.useGL20 = false;
cfg.width = 800;
cfg.height = 480;
new LwjglApplication(new FlappyBall(), cfg);
}
}
Ps².:The compiler shows no errors when this code is being executed
Thanks :D
Your render method will probably never finish it's first frame. The while loop will keep going until ball.y becomes greater than or equal to 480. This will never happen because you are subtracting a positive number.
while (ball.y < 480)
ball.y -= gravity * Gdx.graphics.getDeltaTime();
I would rather change it in something like this:
float change = gravity * Gdx.graphics.getDeltaTime();
if(ball.y - change >= 0)
ball.y -= change;
Related
I've been learning about libgdx recently. In the process of following the instructions on their libgdx wiki I ran into some problems.
Specifically in the GameScreen class at the 99th line I changed the code inside so that it goes back to the previous screen (MainMenuScreen class) and yes you see when the mouse is pressed it worked (I mean go back to the screen before ) but a very very short time after, the screen AUTOMATICALLY switches to the GameScreen class (like I click the mouse once but it makes me 1 more redundant task). I guess when I click on the GameScreen screen it did the code in the if statement on line 99 to go to MainMenuScreen screen. In that screen at line 32 I guess it was true after I got to this screen because when I change the key is listened then it works fine (only converts once). I was intending to try implementing InputProcessor on each screen class but now I'm avoiding it for some reason. Can someone give me some advice recommend.Thank you
Here is the source code for the MainMenuScreen class.
package com.mygdx.game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.utils.ScreenUtils;
//import com.mygdx.game.Drop;
public class MainMenuScreen implements Screen {
final Drop game;
OrthographicCamera camera;
public MainMenuScreen(final Drop gam) {
game = gam;
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
}
#Override
public void render(float delta) {
ScreenUtils.clear(0, 0, 0.2f, 1);
camera.update();
game.batch.setProjectionMatrix(camera.combined);
game.batch.begin();
game.font.draw(game.batch, "Welcome to Drop!!! ", 100, 150);
game.font.draw(game.batch, "Tap anywhere to begin!", 100, 100);
game.batch.end();
if (Gdx.input.isTouched()) { //I guess right after switching to this screen this conditional sentence was true before
game.setScreen(new GameScreen(game));
dispose();
}
}
#Override
public void resize(int width, int height) {
}
#Override
public void show() {
}
#Override
public void hide() {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
}
}
Here is source code for the GameScreen class
package com.mygdx.game;
import java.util.Iterator;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ScreenUtils;
import com.badlogic.gdx.utils.TimeUtils;
public class GameScreen implements Screen {
final Drop game;
Texture dropImage;
Texture bucketImage;
//Sound dropSound;
//Music rainMusic;
OrthographicCamera camera;
Rectangle bucket;
Array<Rectangle> raindrops;
long lastDropTime;
int dropsGathered;
public GameScreen(final Drop gam) {
this.game = gam;
// load the images for the droplet and the bucket, 64x64 pixels each
dropImage = new Texture(Gdx.files.internal("drop.png"));
bucketImage = new Texture(Gdx.files.internal("bucket.png"));
// load the drop sound effect and the rain background "music"
//dropSound = Gdx.audio.newSound(Gdx.files.internal("drop.wav"));
//rainMusic = Gdx.audio.newMusic(Gdx.files.internal("rain.mp3"));
//rainMusic.setLooping(true);
// create the camera and the SpriteBatch
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
// create a Rectangle to logically represent the bucket
bucket = new Rectangle();
bucket.x = 800 / 2 - 64 / 2; // center the bucket horizontally
bucket.y = 20; // bottom left corner of the bucket is 20 pixels above
// the bottom screen edge
bucket.width = 64;
bucket.height = 64;
// create the raindrops array and spawn the first raindrop
raindrops = new Array<Rectangle>();
spawnRaindrop();
}
private void spawnRaindrop() {
Rectangle raindrop = new Rectangle();
raindrop.x = MathUtils.random(0, 800 - 64);
raindrop.y = 480;
raindrop.width = 64;
raindrop.height = 64;
raindrops.add(raindrop);
lastDropTime = TimeUtils.nanoTime();
}
#Override
public void render(float delta) {
// clear the screen with a dark blue color. The
// arguments to clear are the red, green
// blue and alpha component in the range [0,1]
// of the color to be used to clear the screen.
ScreenUtils.clear(0, 0, 0.2f, 1);
// tell the camera to update its matrices.
camera.update();
// tell the SpriteBatch to render in the
// coordinate system specified by the camera.
game.batch.setProjectionMatrix(camera.combined);
// begin a new batch and draw the bucket and
// all drops
game.batch.begin();
game.font.draw(game.batch, "Drops Collected: " + dropsGathered, 0, 480);
game.batch.draw(bucketImage, bucket.x, bucket.y);
for (Rectangle raindrop : raindrops) {
game.batch.draw(dropImage, raindrop.x, raindrop.y);
}
game.batch.end();
// process user input
if (Gdx.input.justTouched()) { //This conditional works fine
/* Vector3 touchPos = new Vector3();
touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(touchPos);
bucket.x = touchPos.x - 64 / 2;
*/
game.setScreen(new MainMenuSceen(game)); //Screen switch
}
if (Gdx.input.isKeyPressed(Keys.LEFT))
bucket.x -= 200 * Gdx.graphics.getDeltaTime();
if (Gdx.input.isKeyPressed(Keys.RIGHT))
bucket.x += 200 * Gdx.graphics.getDeltaTime();
// make sure the bucket stays within the screen bounds
if (bucket.x < 0)
bucket.x = 0;
if (bucket.x > 800 - 64)
bucket.x = 800 - 64;
// check if we need to create a new raindrop
if (TimeUtils.nanoTime() - lastDropTime > 1000000000)
spawnRaindrop();
// move the raindrops, remove any that are beneath the bottom edge of
// the screen or that hit the bucket. In the later case we play back
// a sound effect as well.
Iterator<Rectangle> iter = raindrops.iterator();
while (iter.hasNext()) {
Rectangle raindrop = iter.next();
raindrop.y -= 200 * Gdx.graphics.getDeltaTime();
if (raindrop.y + 64 < 0)
iter.remove();
if (raindrop.overlaps(bucket)) {
dropsGathered++;
//dropSound.play();
iter.remove();
}
}
}
#Override
public void resize(int width, int height) {
}
#Override
public void show() {
// start the playback of the background music
// when the screen is shown
//rainMusic.play();
}
#Override
public void hide() {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
dropImage.dispose();
bucketImage.dispose();
//dropSound.dispose();
//rainMusic.dispose();
}
}
Here is source for Drop class
package com.mygdx.game;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class Drop extends Game {
SpriteBatch batch;
BitmapFont font;
public void create() {
batch = new SpriteBatch();
// Use LibGDX's default Arial font.
font = new BitmapFont();
this.setScreen(new MainMenuScreen(this));
}
public void render() {
super.render(); // important!
}
public void dispose() {
batch.dispose();
font.dispose();
}
}
Your analysis of the problem seems correct to me. The method Gdx.input.isTouched() will immediately return true, if the screen is still being touched after you changed to the main menu.
Also you the solution that you already tried seems correct:
I was intending to try implementing InputProcessor on each screen class
When using an InputProcessor you will get one event (the method call to touchDown or touchUp) when the screen is touched, and don't need to pull the touch event using the isTouched method.
A problem when implementing InputProcessor with both classes probably is, that you can only set one to be the input processor of the game using the method Gdx.input.setInputProcessor. (When setting the second input processor, the first one is removed).
A solution to this problem is the InputMultiplexer. You can add this multiplexer as the input processor of the game (using Gdx.input.setInputProcessor(multiplexer)) and then add your input processors (the main menu and game objects) to this multiplexer: multiplexer.addProcessor(mainMenu) or ((InputMultiplexer) Gdx.input.getInputProcessor()).addProcessor(game).
This way you can handle touch events instead of pulling the touched state in both of your classes.
i want to create a jump of my player that is smooth it goes up then down
its a 2D side scroller like Mario
iv'e tried wait and make jumps slow by using a lot of steps and i cant figure it out
player control class:
package com.mygdx.game;
import java.lang.Thread.State;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
#SuppressWarnings("unused")
public class PlayerController {
static int speed = 1;
public static int jump = 0;
static void keyInput() {
jump++;
if (Gdx.input.isKeyPressed(Keys.A)) {
main.playerX += speed;
main.backgroundSpriteX += speed;
}
if (Gdx.input.isKeyPressed(Keys.D)) {
main.playerX -= speed;
main.backgroundSpriteX -= speed;
}
if (Gdx.input.isKeyPressed(Keys.W)) {
//this is where i want to be able to jump
}
}
static void Controller() {
main.player = new Sprite(main.texture);
main.playerX = (main.canvisWidth * 0);
main.playerY = (main.canvisHeight * 0); //can be 0
}
}
main class:
package com.mygdx.game;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class main implements ApplicationListener {
public static final int backgroundSpriteY = 0;
public static final int backgroundSprite2Y = 0;
public static int canvisWidth = 800;
public static int canvisHeight = 480;
public static int backgroundSpriteX = 0;
public static Texture texture;
public static int backgroundSprite2X = -canvisWidth;
public static Sprite player;
public static int playerX;
public static int playerY;
static SpriteBatch spriteBatch;
static int Jumpframes = 0;
private double playerSize = .4;
public void create() {
WorldObjects.shapeRender.setAutoShapeType(true);
spriteBatch = new SpriteBatch();
texture = new Texture(Gdx.files.internal("imageedit_3_3813241913.png"));
PlayerController.Controller();
WorldSetup.start();
player.setSize((float) (player.getWidth() * playerSize), (float) (player.getHeight() * playerSize));
}
public void render() {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
PlayerController.keyInput();
WorldController.Scroll();
spriteBatch.begin();
spriteBatch.draw(WorldSetup.backgroundTexture, backgroundSpriteX, backgroundSpriteY);
spriteBatch.draw(WorldSetup.backgroundTexture2, backgroundSprite2X, backgroundSprite2Y);
spriteBatch.draw(texture, playerX, playerY, player.getWidth(), player.getHeight());
spriteBatch.end();
WorldSetup.WorldRender();
//Jumpframes++;
}
public void resize(int width, int height) {
}
public void pause() {
}
public void resume() {
}
public void dispose() {
}
}
i want to have a slow jump like a Mario sort of jump and i cant seem to create a slow/smooth jump
I’d like 20 frame jump going up 30 pixels starting fast and slowing down
I think what you need is a 2D Physics Engine for Games, The the popular one is Box2D
lots of tutorials on this, like Brent Aureli's works, to jump your character you just apply force on it like
player.b2body.applyForceToCenter(0, 80f, true);
hope this helps
You can maybe get away from recording the start jump position like this... instead of using the buttons to directly alter their position, use the buttons to alter their velocity then use their current position plus xvelocity and yvelocity to calculate next position. when they press jump they get a increased y and every frame you reduce that until they land on a platform then set it back to 0.
This is a simple android game with a bucket and raindrop. The game is about catching a raindrop into the bucket. The problem is with the bucket because the position of the bucket is not corresponding to the position of touch input.
The second problem is because I don't know how to insert a small window with raindrops counter. I need the counter with a number of raindrops I caught into the bucket.
Here is the code of my android game:
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.TimeUtils;
import java.util.Iterator;
public class MyGdxGame extends ApplicationAdapter {
private Texture dropImage;
private Texture bucketImage;
private Sound dropSound;
private Music rainMusic;
private OrthographicCamera camera;
private SpriteBatch spriteBatch;
private Rectangle bucket;
private Array<Rectangle> raindrops;
private long lastDropTime;
#Override
public void create () {
dropImage = new Texture(Gdx.files.internal("droplet.png"));
bucketImage = new Texture(Gdx.files.internal("bucket.png"));
dropSound = Gdx.audio.newSound(Gdx.files.internal("drop.wav"));
rainMusic = Gdx.audio.newMusic(Gdx.files.internal("rain.mp3"));
rainMusic.setLooping(true);
rainMusic.play();
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 400);
spriteBatch = new SpriteBatch();
bucket = new Rectangle();
bucket.height = 64;
bucket.width = 64;
bucket.x = 800 / 2 - 64 / 2;
bucket.y = 20;
raindrops = new Array<Rectangle>();
createRainDrops();
}
#Override
public void render () {
Gdx.gl.glClearColor(0, 0, 0.2f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
spriteBatch.setProjectionMatrix(camera.combined);
spriteBatch.begin();
spriteBatch.draw(bucketImage, bucket.x, bucket.y);
for (Rectangle raindrop: raindrops){
spriteBatch.draw(dropImage, raindrop.x, raindrop.y);
}
spriteBatch.end();
Touch input hendling:
if (Gdx.input.isTouched()){
bucket.x = Gdx.input.getX() - 64 / 2;
bucket.x = Gdx.input.getX();
}
I know that my solution is with Vector3 but don't know exactly how?
When I tried to play the game my touch position is not in a real position!
if (bucket.x < 0){
bucket.x = 0;
}
if (bucket.y > 800 - 64){
bucket.x = 800 - 64;
}
if (TimeUtils.nanoTime() - lastDropTime > 1000000000){
createRainDrops();
}
Iterator<Rectangle> iterator = raindrops.iterator();
while (iterator.hasNext()){
Rectangle raindrop = iterator.next();
raindrop.y -= 200 * Gdx.graphics.getDeltaTime();
if (raindrop.y + 64 < 0){
iterator.remove();
}
if (raindrop.overlaps(bucket)){
dropSound.play();
iterator.remove();
}
}
}
#Override
public void dispose () {
dropSound.dispose();
rainMusic.dispose();
bucketImage.dispose();
dropImage.dispose();
spriteBatch.dispose();
}
private void createRainDrops() {
Rectangle raindrop = new Rectangle();
raindrop.width = 64;
raindrop.height = 64;
raindrop.y = 480;
raindrop.x = MathUtils.random(0, 800 - 64);
raindrops.add(raindrop);
lastDropTime = TimeUtils.nanoTime();
}
}
You forgot about y coordinate:
if (Gdx.input.isTouched()){
bucket.x = Gdx.input.getX() - bucket.getWidth() / 2;
bucket.y = Gdx.input.getY() - bucket.getHeight() / 2;
}
For raindrops counter you can use BitmapFont
spriteBatch = new SpriteBatch();
font = new BitmapFont(Gdx.files.internal("Font.fnt"),
Gdx.files.internal("Font.png"), false);
and in render method
spriteBatch.begin();
font.draw(spriteBatch, "some string", x, y);
spriteBatch.end();
This question already has an answer here:
How to make player get destroyed through camera?
(1 answer)
Closed 5 years ago.
I've been having some trouble making the player get destroyed through the camera. In my application, I made the camera follow the player(the ball). But the camera can only follow the ball upwards. So what I want to accomplish is, when the player(the ball) reaches the bottom of the interface(the screen) it gets destroyed. After it gets destroyed it would be good, if a new activity(new screen) pops up, that says "Game over". Thanks a lot for the great support. Please take a look at the interface of the application.
package com.luca.tuninga;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.utils.viewport.Viewport;
public class MyGdxGame extends ApplicationAdapter {
public static float APP_FPS = 60f;
public static int V_WIDTH = 480;
public static int V_HEIGHT = 640;
Box2DDebugRenderer b2dr;
World world;
Body ballBody;
OrthographicCamera camera;
float cameraMaxY;
#Override
public void create() {
world = new World(new Vector2(0, -9.8f), false);
b2dr = new Box2DDebugRenderer();
camera = new OrthographicCamera();
camera.setToOrtho(false, V_WIDTH, V_HEIGHT);
cameraMaxY = camera.position.y;
ballBody = createBall();
createWalls();
}
private void update() {
world.step(1f / APP_FPS, 6, 2);
if (Gdx.input.isTouched()) {
ballBody.setLinearVelocity(0, MathUtils.clamp(ballBody.getLinearVelocity().y, 0, 3));
ballBody.applyForceToCenter(new Vector2(0, 650f), false);
}
if (ballBody.getPosition().y * 32 > cameraMaxY) {
camera.translate(0, (ballBody.getPosition().y * 32) - cameraMaxY);
camera.update();
cameraMaxY = camera.position.y;
}
}
#Override
public void render() {
Gdx.gl.glClearColor(.25f, .25f, .25f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
update();
b2dr.render(world, camera.combined.cpy().scl(32f));
}
#Override
public void dispose() {
super.dispose();
world.dispose();
}
private Body createBall() {
Body body;
BodyDef def = new BodyDef();
def.type = BodyDef.BodyType.DynamicBody;
def.fixedRotation = true;
def.position.set(camera.position.x/ 32 + .5f, camera.position.y/ 32);
def.position.set(camera.position.x, camera.position.y);
def.gravityScale = 3;
CircleShape shape = new CircleShape();
shape.setRadius(0.5f);
body = world.createBody(def);
body.createFixture(shape, 1.0f);
return body;
}
private void createWalls() {
Body body;
BodyDef def = new BodyDef();
def.type = BodyDef.BodyType.StaticBody;
def.fixedRotation = true;
PolygonShape shape = new PolygonShape();
shape.setAsBox(1, 200 / 32);
for(int i = 0; i < 20 ; i++) {
def.position.set(1.01f, i * (200 / 32));
body = world.createBody(def);
body.createFixture(shape, 1.0f);
def.position.set(V_WIDTH / 32 - 1, i * (200 / 32));
body = world.createBody(def);
body.createFixture(shape, 1.0f);
}
}
}
#Override
public void render() {
Gdx.gl.glClearColor(.25f, .25f, .25f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
if (ballBody.getPosition().y < camera.position.y){
destroyBall();
} else if (ballBody.getPosition().y > camera.position.y + 300){
camera.position.set(ballBody.getPosition().y - 300);
}
update();
b2dr.render(world, camera.combined.cpy().scl(32f));
}
I hope this works. You can write destroyBall() method yourself.
I'm currently trying to make a breakout clone using java and libgdx. I'm currently experiencing trouble getting the ball to bounce off of the blocks at the appropriate angle. In short the problem I'm having is that the ball moves 12 pixels every frame and doesn't always line up with the edge of a brick. If anyone has any suggestions on a better way to move the ball or a different way to check collision it would be much appreciated!
Main game class
package com.kyleparker.breakout;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.utils.Array;
public class BreakoutGameScreen implements ApplicationListener {
Texture dropImage;
Sound dropSound;
Music rainMusic;
SpriteBatch batch;
OrthographicCamera camera;
Rectangle bucket;
Paddle paddle;
//Brick bricks[];
Array<Brick> bricks;
Ball ball;
#Override
public void create() {
// load the images for the droplet, 64x64 pixels
dropImage = new Texture(Gdx.files.internal("droplet.png"));
// load the drop sound effect and the rain background "music"
dropSound = Gdx.audio.newSound(Gdx.files.internal("drop.wav"));
rainMusic = Gdx.audio.newMusic(Gdx.files.internal("rain.mp3"));
// start the playback of the background music immediately
rainMusic.setLooping(true);
rainMusic.play();
// create the camera and the SpriteBatch
camera = new OrthographicCamera();
camera.setToOrtho(false, 1280, 720);
batch = new SpriteBatch();
paddle = new Paddle(new Texture(Gdx.files.internal("bucket.png")));
bricks = new Array<Brick>();
populateBricks();
ball = new Ball(new Texture(Gdx.files.internal("bucket.png")), paddle, bricks);
}
private void populateBricks() {
bricks.add(new Brick(200,100));
for (int i = 0; i < 5; i++) {
for (int j = 0; j <= 7; j++) {
bricks.add(new Brick (j * 144 + 76, i * 80 + 300)); //Offsets each new brick
}
}
}
#Override
public void render() {
// clear the screen with a dark blue color. The
// arguments to glClearColor are the red, green
// blue and alpha component in the range [0,1]
// of the color to be used to clear the screen.
Gdx.gl.glClearColor(0, 0, 0.2f, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
// tell the camera to update its matrices.
camera.update();
// tell the SpriteBatch to render in the
// coordinate system specified by the camera.
batch.setProjectionMatrix(camera.combined);
// begin a new batch and draw the bucket and
// all drops
batch.begin();
paddle.render(batch, camera);
ball.move();
ball.render(batch, camera);
for (int x = bricks.size - 1; x > 0; x--) {
bricks.get(x).render(batch,camera);
}
batch.end();
}
#Override
public void dispose() {
// dispose of all the native resources
dropImage.dispose();
dropSound.dispose();
rainMusic.dispose();
batch.dispose();
paddle.dispose();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}
Ball class
package com.kyleparker.breakout;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.utils.Array;
public class Ball{
Texture ballImage;
Rectangle ball;
private int xdir;
private int ydir;
Paddle paddle;
Array<Brick> bricks;
final int BALL_SPEED = 12;
public Ball(Texture ballImage, Paddle paddle, Array<Brick> bricks) {
// load the ball image
this.ballImage = ballImage;
xdir = 1;
ydir = -1;
// create a Rectangle for the balls collision
ball = new Rectangle();
ball.x = 1280 / 2 - 64 / 2; // center the ball
ball.y = 100; // put the ball 200px away from the bottom of the screen
ball.width = 64;
ball.height = 64;
this.paddle = paddle;
this.bricks = bricks;
}
public void render(SpriteBatch batch, OrthographicCamera camera) {
// draw the paddle onto the batch of the level
batch.draw(ballImage, ball.x, ball.y);
}
public void move() {
ball.x += xdir * BALL_SPEED;
ball.y += ydir * BALL_SPEED;
if (ball.x <= 0) {
setXDir(1);
}
if (ball.x >= 1280 - 64) {
setXDir(-1);
}
if (ball.y <= 0) {
setYDir(1);
}
if (ball.y >= 720 - 64) {
setYDir(-1);
}
if (ball.overlaps(paddle.getRect())) {
setYDir(1);
}
for (int i = 0; i < bricks.size; i++) {
if (ball.overlaps(bricks.get(i).getRect())) {
if ((ball.x == (bricks.get(i).getRect().x + 128)))
{
setXDir(1);
bricks.get(i).setDestroyed(true);
System.out.println("Collision RIGHT");
}
if (((ball.x + 64) == bricks.get(i).getRect().x))
{
setXDir(-1);
bricks.get(i).setDestroyed(true);
System.out.println("Collision LEFT");
}
if ((ball.y == (bricks.get(i).getRect().y + 64)))
{
setYDir(1);
bricks.get(i).setDestroyed(true);
System.out.println("Collision TOP");
}
if (((ball.y + 64) == bricks.get(i).getRect().y))
{
setYDir(-1);
bricks.get(i).setDestroyed(true);
System.out.println("Collision BOTTOM");
}
}
}// end of for
}
public void setXDir(int x) {
xdir = x;
}
public void setYDir(int y) {
ydir = y;
}
public int getYDir() {
return ydir;
}
public int getXDir() {
return xdir;
}
public Rectangle getRect() {
// return the collision rectangle for checking overlaps
return ball;
}
public void dispose() {
// dispose of all the native resources
ballImage.dispose();
}
}// end of class
Brick code just in case
package com.kyleparker.breakout;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
public class Brick{
Texture brickImage;
Rectangle brick;
boolean destroyed;
public Brick(int x, int y) {
brickImage = new Texture(Gdx.files.internal("brick.png"));
// create a Rectangle for the bricks collision
brick = new Rectangle();
brick.x = x;
brick.y = y;
brick.width = 128;
brick.height = 64;
destroyed = false;
}
public void render(SpriteBatch batch, OrthographicCamera camera) {
// draw the brick onto the batch of the level
batch.draw(brickImage, brick.x, brick.y);
}
public boolean isDestroyed() {
// return the collision rectangle for checking overlaps
return destroyed;
}
public void setDestroyed(boolean destroyed)
{
this.destroyed = destroyed;
if (this.destroyed == true) {
dispose();
brick.x = -1000;
brick.y = -1000;
}
}
public Rectangle getRect() {
return brick;
}
public void dispose() {
// dispose of all the native resources
brickImage.dispose();
}
}
Don't worry about the fact that the ball doesn't always line up with an object for which the collision needs handled -- that's not actually relevant. You can (and should) handle your collisions less 'precisely.' That is, the ball's path is fixed, so you can calculate its position at any future point. Check its position, calculate its position in the next frame (which you have to do to draw it anyway), and add some code to handle the collision that is going to happen, rather than trying to detect and handle the collision which has happened. You can slow down the ball if you really want a clean reflection, or you can speed up your framerate, or you can let the ball be partially 'absorbed' by the object before it reflects:
public class Ball {
. . .
public void move() {
. . .
if (collisionObject.overlaps(new Rectangle(ball.x + xdir, ball.y + ydir, ball.width, ball.height))) {
//a collision will have occurred in the next frame
//handle the collision however you please
}
}
}
I also note that your BALL_SPEED field is inaccurately named. As presently coded, the ball always moves at a 45° angle, with a speed of about 17 pixels per frame (in that direction). You've coded its x- and y-offset as 12 pixels, but if (when?) you change the ball's direction, you'll find that the speed fluctuates wildly depending on what values are placed in for the xdir and ydir fields. For example, if you were to (somewhat) randomize these, but keep the rest of your code as-is, you might find that xdir = 2 and ydir = 4 on one instance, and xdir = 6 and ydir = 12 on another. Note these describe the same direction, but the second version will move three times as fast.
To properly handle the ball's direction and speed, assign an angle, and calculate the xdir and ydir values through the appropriate trigonometric functions (xdir = BALL_SPEED * Math.cos(ballAngle) and ydir = BALL_SPEED * Math.sin(ballAngle)).
I would use box2d for the whole thing. That you haven't used box2d probably means you have no experience in it, so that would be a little hurdle, but I'm sure you'll be able to wrap your head around it quickly. Here's a link for that: http://code.google.com/p/libgdx/wiki/PhysicsBox2D