I am trying to remove created bullets when (bullet.position.y <= 0). But the game gives error. I can not remove created bullets. How can I fix it? I used one texture ( 64 x 64 ) and these are my classes:
Game1 (Main Class)
package com.outlook.anil136.game1;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import java.util.ArrayList;
public class Game1 extends ApplicationAdapter {
private ShapeRenderer shapeRenderer;
private SpriteBatch batch;
private OrthographicCamera camera;
private Texture blueTexture;
private Player player1;
private ArrayList<Bullet> bullets;
private Sprite blueSprite;
#Override
public void create () {
shapeRenderer = new ShapeRenderer();
batch = new SpriteBatch();
camera = new OrthographicCamera();
camera.setToOrtho(false, 480, 800);
blueTexture = new Texture("BlueRectangle.png");
player1 = new Player(blueTexture, new Vector2(240, 600));
bullets = new ArrayList<Bullet>();
blueSprite = new Sprite(blueTexture);
}
#Override
public void render () {
Gdx.gl.glClearColor(0.1f, 0.1f, 0.1f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
shapeRenderer.setProjectionMatrix(camera.combined);
shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
shapeRenderer.rectLine(0, 401, 480, 401, 2);
shapeRenderer.end();
batch.setProjectionMatrix(camera.combined);
batch.begin();
player1.draw(batch);
for (Bullet bullet : bullets) {
bullet.draw(batch);
bullet.update(Gdx.graphics.getDeltaTime());
if (bullet.position.y <= 0)
bullet.remove(bullets);
}
blueSprite.setPosition(416, 736);
blueSprite.setColor(1, 1, 1, 0.5f);
blueSprite.draw(batch);
batch.end();
player1.update(Gdx.graphics.getDeltaTime());
for (int i = 0; i < 20; i++) {
Vector3 touchPosition = camera.unproject(new Vector3(Gdx.input.getX(i), Gdx.input.getY(i), 0));
if (Gdx.input.isTouched(i) && touchPosition.y >= 401 && touchPosition.y > 64 && !new Rectangle(416, 736, 64, 64).contains(touchPosition.x, touchPosition.y))
player1.touchPosition = touchPosition;
if (Gdx.input.justTouched() && new Rectangle(416, 736, 64, 64).contains(touchPosition.x, touchPosition.y))
bullets.add(new Bullet(blueTexture, new Vector2(player1.position), -player1.speed));
}
if (player1.position.y + 32 > 800)
player1.position.y = 768;
else if (player1.position.y - 32 < 402)
player1.position.y = 434;
}
#Override
public void dispose () {
shapeRenderer.dispose();
batch.dispose();
blueTexture.dispose();
}
}
Player
package com.outlook.anil136.game1;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import java.util.ArrayList;
import javafx.scene.input.KeyCode;
import sun.security.provider.SHA;
public class Game1 extends ApplicationAdapter {
private ShapeRenderer shapeRenderer;
private SpriteBatch batch;
private OrthographicCamera camera;
private Texture blueTexture;
private Player player1;
public static ArrayList<Bullet> bullets;
private Sprite blueSprite;
#Override
public void create () {
shapeRenderer = new ShapeRenderer();
batch = new SpriteBatch();
camera = new OrthographicCamera();
camera.setToOrtho(false, 480, 800);
blueTexture = new Texture("BlueRectangle.png");
player1 = new Player(blueTexture, new Vector2(240, 600));
bullets = new ArrayList<Bullet>();
blueSprite = new Sprite(blueTexture);
}
#Override
public void render () {
Gdx.gl.glClearColor(0.1f, 0.1f, 0.1f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
shapeRenderer.setProjectionMatrix(camera.combined);
shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
shapeRenderer.rectLine(0, 401, 480, 401, 2);
shapeRenderer.end();
batch.setProjectionMatrix(camera.combined);
batch.begin();
player1.draw(batch);
for (Bullet bullet : bullets) {
bullet.draw(batch);
bullet.update(Gdx.graphics.getDeltaTime());
if (bullet.position.y <= 0)
bullet.remove(bullets);
}
blueSprite.setPosition(416, 736);
blueSprite.setColor(1, 1, 1, 0.5f);
blueSprite.draw(batch);
batch.end();
player1.update(Gdx.graphics.getDeltaTime());
for (int i = 0; i < 20; i++) {
Vector3 touchPosition = camera.unproject(new Vector3(Gdx.input.getX(i), Gdx.input.getY(i), 0));
if (Gdx.input.isTouched(i) && touchPosition.y >= 401 && touchPosition.y > 64 && !new Rectangle(416, 736, 64, 64).contains(touchPosition.x, touchPosition.y))
player1.touchPosition = touchPosition;
if (Gdx.input.justTouched() && new Rectangle(416, 736, 64, 64).contains(touchPosition.x, touchPosition.y))
bullets.add(new Bullet(blueTexture, new Vector2(player1.position), -player1.speed));
}
if (player1.position.y + 32 > 800)
player1.position.y = 768;
else if (player1.position.y - 32 < 402)
player1.position.y = 434;
}
#Override
public void dispose () {
shapeRenderer.dispose();
batch.dispose();
blueTexture.dispose();
}
}
Bullet
package com.outlook.anil136.game1;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
import java.util.ArrayList;
public class Bullet {
private Texture texture;
Vector2 position;
private int speed;
public Bullet(Texture texture, Vector2 position, int speed) {
this.texture = texture;
this.position = position;
this.speed = speed;
}
public void draw(SpriteBatch batch) {
batch.draw(texture, position.x - 16, position.y - 16, 32, 32);
}
public void update(float deltaTime) {
position.y += speed;
}
public void remove(ArrayList<Bullet> bullets) {
bullets.remove(this);
}
}
You can't remove elements from list when you are iterating it. To remove elements when iterating you need to mark bullet to remove and after iterating actually remove all marked bullets from the main list.
List<Bullet> bulletsToRemove = new ArrayList<Bullet>();
for (Bullet bullet : bullets) {
bullet.draw(batch);
bullet.update(Gdx.graphics.getDeltaTime());
if (bullet.position.y <= 0)
bulletsToRemove.add(bullet);
}
bullets.removeAll(bulletsToRemove);
Related
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 am trying make create a ContactListener derived class in Libgdx using Bullet wrapper for collision detection like in this tutorial but in separate classes. It separate classes for rendering and game world. In render() method of class Render I pass an Array of model instances to this derived class. But when I run it gives an because Array size is zero. Here is the derived class :
package com.anutrix.brickbreaker3d.Helpers;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.physics.bullet.collision.ContactListener;
import com.badlogic.gdx.utils.Array;
public class CollisionListener extends ContactListener {
private Array<ModelInstance> instances;
public CollisionListener() {
this.instances = new Array<ModelInstance>();
}
public void setModelInstances(Array<ModelInstance> instances) {
this.instances = instances;
}
#Override
public boolean onContactAdded(int userValue0, int partId0, int index0, int userValue1, int partId1, int index1) {
//instances.get(colObj1Wrap.getCollisionObject().getUserValue()).collided = false;error
Gdx.app.log("instances.size", Integer.toString(instances.size));//zero
Gdx.app.log("ddhbdfhd", "fhfgjfgj");
return true;
}
}
Here is the Renderer class:
package com.anutrix.brickbreaker3d.gameWorld;
import com.anutrix.brickbreaker3d.gameObjects.Ball;
import com.anutrix.brickbreaker3d.gameObjects.Brick;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.physics.bullet.DebugDrawer;
import com.badlogic.gdx.physics.bullet.collision.btCollisionDispatcher;
import com.badlogic.gdx.physics.bullet.collision.btCollisionWorld;
import com.badlogic.gdx.physics.bullet.collision.btDbvtBroadphase;
import com.badlogic.gdx.physics.bullet.collision.btDefaultCollisionConfiguration;
import com.badlogic.gdx.physics.bullet.linearmath.btIDebugDraw;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;
public class GameRenderer implements Disposable {
private GameWorld gameWorld;
private PerspectiveCamera cam;
public ModelBatch modelBatch;
private CameraInputController camController;
private Environment environment;
public Array<ModelInstance> instances;
ModelBuilder mb = new ModelBuilder();
btCollisionDispatcher dispatcher;
public GameRenderer(GameWorld world) {
this.modelBatch = new ModelBatch();
this.environment = new Environment();
this.instances = new Array<ModelInstance>();
gameWorld = world;
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(10f, 10f, 0f);
cam.lookAt(0, 0, 0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
}
public void render() {
//Gdx.app.log("GameRenderer", "render");
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Gdx.gl.glClearColor(0f, 0.2f, 0.2f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
for (Brick b : gameWorld.bricks) {
b.getObject().setUserValue(instances.size);
instances.add(b.getModelInstance());
}
for (Ball b : gameWorld.balls) {
b.getObject().setUserValue(instances.size);
instances.add(b.getModelInstance());
}
gameWorld.collisionListener.setModelInstances(instances);
modelBatch.begin(cam);
modelBatch.render(instances, environment);
modelBatch.end();
instances.clear();
}
#Override
public void dispose() {
modelBatch.dispose();
}
}
What am I doing wrong? Inside setModelInstances() the instances.size is correct. But after each call to it, the instances.size is equal to 0 .
Also I wasn't sure of pass by reference(since Java uses pass by value). So is it better(if it works) if I call setInstances() just once?
Both your CollisionListener#instances and GameRenderer#instances point to the same reference after your call to gameWorld.collisionListener.setModelInstances(instances); inside your GameRenderer#render() method.
Then, at the end of the method, you are invoking:
instances.clear();
This would be clearing out instances. So, the size would become 0 when you call render.
Instead, inside your setModelInstances method, you could create a new Array instance like this:
public void setModelInstances(Array<ModelInstance> instances) {
this.instances = new Array<>(instances);
}
Hope this helps!
I'm trying to make an Avoider game, which is 95% done, however, when I try to add infinite obstacles, the game looks like this from the beginning(no errors):How the game looks
I have no idea what I'm doing wrong, could somebody please help me? It would be truly and greatly appreciated since this is the last thing I need to do to get my game working. The code in my GameScreen:
package com.circlecrashavoider;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.Manifold;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.circlecrashavoider.entities.FloorEntity;
import com.circlecrashavoider.entities.ObstacleEntity;
import com.circlecrashavoider.entities.ObstacleEntity2;
import com.circlecrashavoider.entities.PlayerEntity;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Random;
public class GameScreen extends BaseScreen {
private Stage stage;
private World world;
private PlayerEntity player;
private List<FloorEntity> floorList = new ArrayList<FloorEntity>();
private List<ObstacleEntity> obstacleList = new ArrayList<ObstacleEntity>();
private List<ObstacleEntity2> obstacle2List = new ArrayList<ObstacleEntity2>();
public GameScreen(MainGame game) {
super(game);
stage = new Stage(new FitViewport(1024, 620));
world = new World(new Vector2(0, -10), true);
world.setContactListener(new ContactListener() {
private boolean areCollided(Contact contact, Object userA, Object userB) {
return (contact.getFixtureA().getUserData().equals(userA) && contact.getFixtureB().getUserData().equals(userB)) ||
(contact.getFixtureA().getUserData().equals(userB) && contact.getFixtureB().getUserData().equals(userA));
}
#Override
public void beginContact(Contact contact) {
if (areCollided(contact, "player", "floor")) {
player.setJumping(false);
if (Gdx.input.isTouched()) {
player.setMustJump(true);
}
}
if (areCollided(contact, "player", "obstacle")) {
player.setAlive(false);
System.out.println("GAME OVER");
}
if (areCollided(contact, "player", "obstacle2")) {
player.setAlive(false);
System.out.println("GAME OVER");
}
}
#Override
public void endContact(Contact contact) {
}
#Override
public void preSolve(Contact contact, Manifold oldManifold) {
}
#Override
public void postSolve(Contact contact, ContactImpulse impulse) {
}
});
}
#Override
public void show() {
}
private float spawnTime = 4f;
private float timer = 0;
public void update(float deltaTime) {
timer += deltaTime;
if (timer >= spawnTime) {
this.spawnEntity();
spawnTime = MathUtils.random(2f, 4f);
timer = 0;
}
}
private void spawnEntity(){
Texture floorTexture = game.getManager().get("floor.png");
Texture overfloorTexture = game.getManager().get("overfloor.png");
Texture overfloor2Texture = game.getManager().get("overfloor2.png");
Texture obstacleTexture = game.getManager().get("obstacle.png");
Texture obstacle2Texture = game.getManager().get("obstacle2.png");
//Spawn your object
floorList.add(new FloorEntity(world, floorTexture, overfloorTexture,overfloor2Texture, 0, 1000, 1));
floorList.add(new FloorEntity(world, floorTexture, overfloorTexture,overfloor2Texture ,8, 10 ,5));
floorList.add(new FloorEntity(world, floorTexture, overfloorTexture,overfloor2Texture ,10, 10 ,8));
floorList.add(new FloorEntity(world, floorTexture, overfloorTexture,overfloor2Texture ,34 , 3 ,5));
floorList.add(new FloorEntity(world, floorTexture, overfloorTexture,overfloor2Texture ,19 , 8 ,4));
floorList.add(new FloorEntity(world, floorTexture, overfloorTexture,overfloor2Texture ,24 , 8 ,1.5f));
floorList.add(new FloorEntity(world, floorTexture, overfloorTexture,overfloor2Texture ,27 , 5 , 2));
obstacleList.add(new ObstacleEntity(world, obstacleTexture, 6, 1));
stage.addActor(player);
for (FloorEntity floor: floorList) {
stage.addActor(floor);
}
for (ObstacleEntity obstacle : obstacleList) {
stage.addActor(obstacle);
}
}
#Override
public void render(float delta) {
Gdx.gl20.glClearColor(0.5f, 0.6f, 1, 3f);
Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act();
world.step(delta, 6, 2);
stage.draw();
}
#Override
public void dispose() {
stage.dispose();
world.dispose();
}
}
The code in my MainGame class:
package com.circlecrashavoider;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Texture;
import com.circlecrashavoider.scene2d.Box2DScreen;
import com.circlecrashavoider.scene2d.Scene2DScreen;
public class MainGame extends Game {
private AssetManager manager;
public AssetManager getManager() {
return manager;
}
#Override
public void create() {
manager = new AssetManager();
manager.load("floor.png", Texture.class);
manager.load("overfloor.png", Texture.class);
manager.load("overfloor2.png", Texture.class);
manager.load("obstacle.png", Texture.class);
manager.load("obstacle2.png", Texture.class);
manager.load("crash.png", Texture.class);
manager.load("player.png", Texture.class);
manager.finishLoading();
setScreen(new GameScreen(this));
}
}
The code of the PlayerEntity, FloorEntity and ObstacleEntity classes are in this post https://stackoverflow.com/questions/35678654/issues-getting-android-studio-game-to-run. On this link you will find the Code you need Fuat Coskun
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;