2D assets rendering problems - java

I'm new in 2D programming and right now I'm trying to make a 2D game with some clouds and pipes which are scrolled in the bottom of the screen.
It was easy to deal with the clouds, but I'm having some problems with the pipes- I want to render them like the ones in flappy bird, but horizontally in my case.I can't figure out what is wrong with my code.
Screenshot
public class GameRenderer {
private GameWorld myWorld;
private OrthographicCamera cam;
private ShapeRenderer shapeRenderer;
private SpriteBatch batcher;
private int midPointY;
private int gameHeight;
// Game Objects
private Margarine marg;
private ScrollHandler scroller;
private Clouds cloud1, cloud2, cloud3;
private Pipe pipe1, pipe2, pipe3;
// Game Assets
private TextureRegion cloud;
private TextureRegion pipe;
public GameRenderer(GameWorld world, int gameHeight, int midPointY) {
myWorld = world;
this.gameHeight = gameHeight;
this.midPointY = midPointY;
cam = new OrthographicCamera();
cam.setToOrtho(false, 136, gameHeight);
batcher = new SpriteBatch();
batcher.setProjectionMatrix(cam.combined);
shapeRenderer = new ShapeRenderer();
shapeRenderer.setProjectionMatrix(cam.combined);
// Call helper methods to initialize instance variables
initGameObjects();
initAssets();
}
private void initGameObjects() {
marg = myWorld.getMargarine();
scroller = myWorld.getScroller();
cloud1 = scroller.getCloud1();
cloud2 = scroller.getCloud2();
cloud3 = scroller.getCloud3();
pipe1 = scroller.getPipe1();
pipe2 = scroller.getPipe2();
pipe3 = scroller.getPipe3();
}
private void initAssets() {
cloud = AssetLoader.cloud;
pipe = AssetLoader.pipe;
}
public void render(float runTime) {
Gdx.gl.glClearColor(102 / 255.0f, 102 / 255.0f, 255 / 255.0f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
shapeRenderer.begin(ShapeType.Filled);
shapeRenderer.end();
batcher.begin();
//clouds
batcher.draw(cloud, cloud1.getX(), cloud1.getY(), cloud1.getWidth(),
cloud1.getHeight());
batcher.draw(cloud, cloud2.getX(), cloud2.getY(), cloud2.getWidth(),
cloud2.getHeight());
batcher.draw(cloud, cloud3.getX(), cloud3.getY(), cloud3.getWidth(),
cloud3.getHeight());
//pipes
batcher.draw(pipe, pipe1.getX(), pipe1.getY(), pipe1.getWidth(),
pipe1.getHeight());
batcher.draw(pipe, pipe1.getX(), pipe1.getY() + pipe1.getHeight() + 45,
pipe1.getWidth(), midPointY + 66 - (pipe1.getHeight() + 45));
batcher.draw(pipe, pipe2.getX(), pipe2.getY(), pipe2.getWidth(),
pipe2.getHeight());
batcher.draw(pipe, pipe2.getX(), pipe2.getY() + pipe2.getHeight() + 45,
pipe2.getWidth(), midPointY + 66 - (pipe2.getHeight() + 45));
batcher.draw(pipe, pipe3.getX(), pipe3.getY(), pipe3.getWidth(),
pipe3.getHeight());
batcher.draw(pipe, pipe3.getX(), pipe3.getY() + pipe3.getHeight() + 45,
pipe3.getWidth(), midPointY + 66 - (pipe3.getHeight() + 45));
//margarine
batcher.draw(AssetLoader.marg, marg.getX(), marg.getY(),
marg.getWidth(), marg.getHeight());
batcher.end();
}
}
public class Pipe extends Scrollable {
private Random r;
// When Pipe's constructor is invoked, invoke the super (Scrollable)
// constructor
public Pipe(float x, float y, int width, int height, float scrollSpeed) {
super(x, y, width, height, scrollSpeed);
// Initialize a Random object for Random number generation
r = new Random();
}
#Override
public void reset(float newX) {
// Call the reset method in the superclass (Scrollable)
super.reset(newX);
// Change the height to a random number
height = r.nextInt(90) + 15;
}
}
public ScrollHandler(float yPos) {
cloud1= new Clouds(80, 0, 30, 80, SCROLL_SPEED);
cloud2 = new Clouds(50 , cloud1.getTailY(), 30, 80, SCROLL_SPEED);
cloud3 = new Clouds(10, cloud2.getTailY(), 30, 80, SCROLL_SPEED);
pipe1 = new Pipe(210, 0, 22, 60, SCROLL_SPEED);
pipe2 = new Pipe(0, pipe1.getTailY() + PIPE_GAP, 22, 70, SCROLL_SPEED);
pipe3 = new Pipe(0, pipe1.getTailY() + PIPE_GAP, 22, 60, SCROLL_SPEED);
}
public void update(float delta) {
// Update our objects
cloud1.update(delta);
cloud2.update(delta);
cloud3.update(delta);
pipe1.update(delta);
pipe2.update(delta);
pipe3.update(delta);
if (cloud1.isScrolledDown()) {
cloud1.reset(cloud3.getTailY());
} else if (cloud2.isScrolledDown()) {
cloud2.reset(cloud1.getTailY());
} else if (cloud3.isScrolledDown()) {
cloud3.reset(cloud2.getTailY());
}
if (pipe1.isScrolledDown()) {
pipe1.reset(pipe3.getTailY() + PIPE_GAP);
} else if (pipe2.isScrolledDown()) {
pipe2.reset(pipe1.getTailY() + PIPE_GAP);
} else if (pipe3.isScrolledDown()) {
pipe3.reset(pipe2.getTailY() + PIPE_GAP);
}
}
public Clouds getCloud1() {
return cloud1;
}
public Clouds getCloud2() {
return cloud2;
}
public Clouds getCloud3() {
return cloud3;
}
public Pipe getPipe1() {
return pipe1;
}
public Pipe getPipe2() {
return pipe2;
}
public Pipe getPipe3() {
return pipe3;
}
}

Solved. By mistake I switched the height and the width.

Related

Libgdx: how to detect if an enemy was touched?

I want to add to the score of my game +1 when an enemy was touched, I tried two methods addListener and touchDown but not worked for me or I didn't use them right.
How can I do that my (enemy object is linked to an userData and Actor classes, I regroup many different sizes for my enemy in an enum class also those enemies move from the top of the screen to bot. How to detect if an enemy was touched?
public class GameStage extends Stage {
// This will be our viewport measurements while working with the debug renderer
private static final int VIEWPORT_WIDTH = 13;
private static final int VIEWPORT_HEIGHT = 20;
private World world;
private Ground ground;
private Enemy enemy;
private final float TIME_STEP = 1 / 300f;
private float accumulator = 0f;
private Rectangle bounds;
private Vector3 touchPoint = new Vector3();;
private int score;
private String yourScoreName;
BitmapFont yourBitmapFontName;
private SpriteBatch batch;
private OrthographicCamera camera;
private Box2DDebugRenderer renderer;
public GameStage() {
world = WorldUtils.createWorld();
renderer = new Box2DDebugRenderer();
Gdx.input.setInputProcessor(this);
batch = new SpriteBatch();
score = 0;
yourScoreName = "score: 0";
yourBitmapFontName = new BitmapFont();
setUpWorld();
setUpCamera();
}
public void setUpWorld(){
world = WorldUtils.createWorld();
setUpGround();
createEnemy();
}
private void setUpGround(){
ground = new Ground (WorldUtils.createGround(world));
addActor(ground);
}
private void createEnemy() {
enemy = new Enemy(WorldUtils.createEnemy(world));
// (1) *****using addListener method
enemy.addListener(new InputListener()
{
#Override
public boolean touchDown(InputEvent event, float x, float y,
int pointer, int button)
{
score++;
yourScoreName = "score: " + score;
return true;
}
});
/*enemy.addListener(new ClickListener() {
public void clicked() {
world.destroyBody(enemy.getBody());
}});*/
//bounds = new Rectangle(enemy.getX(), enemy.getY(), enemy.getWidth(), enemy.getHeight());
addActor(enemy);
}
private void setUpCamera() {
camera = new OrthographicCamera(VIEWPORT_WIDTH, VIEWPORT_HEIGHT);
camera.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2, 0f);
camera.update();
}
#Override
public void act(float delta) {
super.act(delta);
checkEnemy();
// Fixed timestep
accumulator += delta;
while (accumulator >= delta) {
world.step(TIME_STEP, 6, 2);
accumulator -= TIME_STEP;
}
//TODO: Implement interpolation
}
private void checkEnemy(){
final Body body = enemy.getBody();
UserData userData = enemy.getUserData();
bounds = new Rectangle(enemy.getBody().getPosition().x, enemy.getBody().getPosition().y, enemy.getUserData().getWidth(), enemy.getUserData().getHeight());
// bounds = new Rectangle(body.getPosition().x, body.getPosition().y,userData.getWidth() ,userData.getHeight());
if (!BodyUtils.enemyInBounds(body,userData)){
world.destroyBody(body);
createEnemy();}
}
public World getWorld(){
return world;
}
// (2) ****using TouchDown method
#Override
public boolean touchDown(int x, int y, int pointer, int button) {
// Need to get the actual coordinates
translateScreenToWorldCoordinates(x, y);
// score++;
// yourScoreName = "score: " + score;
if(enemyTouched(touchPoint.x,touchPoint.y)){
// world.destroyBody(enemy.getBody());
score++;
yourScoreName = "score: " + score;
}
return super.touchDown(x, y, pointer, button);
}
private boolean enemyTouched(float x, float y) {
return bounds.contains(x, y);
}
private void translateScreenToWorldCoordinates(int x, int y) {
getCamera().unproject(touchPoint.set(x, y, 0));
}
#Override
public void draw() {
super.draw();
batch.begin();
yourBitmapFontName.setColor(1.0f, 1.0f, 1.0f, 1.0f);
yourBitmapFontName.draw(batch, yourScoreName, 25, 100);
batch.end();
enemy.setBounds(enemy.getBody().getPosition().x,enemy.getBody().getPosition().y,enemy.getUserData().getWidth(),enemy.getUserData().getHeight());
renderer.render(world, camera.combined);
}
}
A screen from my game:
It should work the way you did it (with the addListener() method). But you have to set the correct bounds of the actor (width, height, position): actor.setBounds(x, y, width, height). I would use the body to get these values. You can also use a ClickListener instead of the InputListener.

Filling a HUD in Java

I've decided on making a HUD with the picture above, but I don't know what command in Java I need to use so as I can fill the top half and the bottom half separately.
I only know how to use the g.fillRect(); command, and it will take around twenty of these commands to fill said half.
public class HUD {
private Player player;
private BufferedImage image;
private Font font;
private Font font2;
private int Phealth = Player.getHealth();
public HUD(Player p) {
player = p;
try {
image = ImageIO.read(getClass().getResourceAsStream("/HUD/HUD_TEST.gif"));
font = new Font("Arial", Font.PLAIN, 10);
font2 = new Font("SANS_SERIF", Font.BOLD, 10);
}
catch(Exception e) {
e.printStackTrace();
}
}
public void draw(Graphics2D g) {
g.drawImage(image, 0, 10, null);
g.setFont(font2);
g.setColor(Color.black);
g.drawString("Health:", 30, 22);
g.drawString("Mana:", 25, 47);
g.setFont(font);
g.drawString(Player.getHealth() + "/" + player.getMaxHealth(), 64, 22);
g.drawString(player.getCubes() / 100 + "/" + player.getMaxCubes() / 100, 55, 47);
g.setColor(Color.red);
g.fillRect(1, 25, Phealth * 25, 4);
g.setColor(Color.blue);
g.fillRect(1, 31, player.getCubes() / 33, 4);
}
}
This is the code for the HUD so far.
Any help in filling the shape will help.
Removed Idea #1! (It didn't seem to work.)
Okay, Idea #2:
Image1
Image2
Image3
So, there are 3 .png images.
Draw Image1 first, followed by drawing Image2 and Image3 directly on top of it.
To fill up either the red/blue bars, clip Image2 and Image3 accordingly (i.e. cut away their left sides)
Take a look at this on clipping.
This will require some minor calculations on how much to clip, based on the HP/Mana of the Player, but it should be good enough.
This is what it should look like (Clipping and overlaying done in Paint)
UPDATE (Problem solved, using Idea #2!):
Code:
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
#SuppressWarnings("serial")
public class TestGraphics extends JFrame implements ActionListener
{
JPanel utilBar = new JPanel();
JButton hpUpBtn = new JButton("HP++");
JButton hpDownBtn = new JButton("HP--");
JButton mpUpBtn = new JButton("MP++");
JButton mpDownBtn = new JButton("MP--");
GraphicsPanel drawingArea = new GraphicsPanel();
TestGraphics()
{
setSize(600, 500);
setLayout(new BorderLayout());
add(utilBar, BorderLayout.NORTH);
utilBar.setLayout(new GridLayout(1, 4));
utilBar.add(hpUpBtn);
utilBar.add(hpDownBtn);
utilBar.add(mpUpBtn);
utilBar.add(mpDownBtn);
add(drawingArea, BorderLayout.CENTER);
hpUpBtn.addActionListener(this);
hpDownBtn.addActionListener(this);
mpUpBtn.addActionListener(this);
mpDownBtn.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == hpUpBtn) {
drawingArea.incHp();
}
else if (e.getSource() == hpDownBtn) {
drawingArea.decHp();
}
else if (e.getSource() == mpUpBtn) {
drawingArea.incMp();
}
else if (e.getSource() == mpDownBtn) {
drawingArea.decMp();
}
System.out.println("Player HP: " + drawingArea.getHp() +
" Player MP: " + drawingArea.getMp());
drawingArea.revalidate();
drawingArea.repaint();
}
public static void main(String[]agrs)
{
new TestGraphics();
}
}
#SuppressWarnings("serial")
class GraphicsPanel extends JPanel {
private static int baseX = 150;
private static int baseY = 150;
private static final int BAR_FULL = 287;
private static final int BAR_EMPTY = 8;
private BufferedImage image1 = null;
private BufferedImage image2 = null;
private BufferedImage image3 = null;
private int playerHp = 100;
private int playerMp = 100;
public GraphicsPanel() {
try {
// All 3 images are the same as those posted in answer
image1 = ImageIO.read(
getClass().getResourceAsStream("/Image1.png"));
image2 = ImageIO.read(
getClass().getResourceAsStream("/Image2.png"));
image3 = ImageIO.read(
getClass().getResourceAsStream("/Image3.png"));
} catch (Exception e) {
e.printStackTrace();
}
}
public void incHp() { playerHp += (playerHp < 100) ? 5 : 0; }
public void decHp() { playerHp -= (playerHp > 0) ? 5 : 0; }
public void incMp() { playerMp += (playerMp < 100) ? 5 : 0; }
public void decMp() { playerMp -= (playerMp > 0) ? 5 : 0; }
public int getHp() { return playerHp; }
public int getMp() { return playerMp; }
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Clear the graphics
g.setClip(null);
g.setColor(Color.BLACK);
g.fillRect(0, 0, 600, 600);
g.drawImage(image1, baseX, baseY, null);
int hpPerc = (int) ((BAR_FULL - BAR_EMPTY) * (playerHp / 100.0));
g.setClip(baseX + BAR_EMPTY + hpPerc, 0, 600, 500);
g.drawImage(image2, baseX, baseY, null);
g.setClip(null);
int mpPerc = (int) ((BAR_FULL - BAR_EMPTY) * (playerMp / 100.0));
g.setClip(baseX + BAR_EMPTY + mpPerc, 0, 600, 500);
g.drawImage(image3, baseX, baseY + 78, null);
g.setClip(null);
}
}

Android problems with Viewport

When i run the game in Desktop works fine, but when i run it in my android device, the image looks cuted in a half and when i use the PLAY button the game closes, anyone can help me? thank you.
public class GameScreen extends AbstractScreen {
private Viewport viewport;
private Camera camera;
private SpriteBatch batch;
private Texture texture;
private float escala;
private Paddle Lpaddle, Rpaddle;
private Ball ball;
private BitmapFont font;
private int puntuacion, puntuacionMaxima;
private Preferences preferencias;
private Music music;
private Sound sonidoex;
public GameScreen(Main main) {
super(main);
preferencias = Gdx.app.getPreferences("PuntuacionAppPoints");
puntuacionMaxima = preferencias.getInteger("puntuacionMaxima");
music =Gdx.audio.newMusic(Gdx.files.internal("bgmusic.mp3"));
music.play();
music.setVolume((float) 0.3);
music.setLooping(true);
sonidoex = Gdx.audio.newSound(Gdx.files.internal("explosion5.wav"));
}
public void create(){
camera = new PerspectiveCamera();
viewport = new FitViewport(800, 480, camera);
}
public void show(){
batch = main.getBatch();
texture = new Texture(Gdx.files.internal("spacebg.png"));
Texture texturaBola = new Texture(Gdx.files.internal("bola.png"));
ball = new Ball(Gdx.graphics.getWidth() / 2 - texturaBola.getWidth() / 2, Gdx.graphics.getHeight() / 2 - texturaBola.getHeight() / 2);
Texture texturaPala= new Texture(Gdx.files.internal("pala.png"));
Lpaddle = new LeftPaddle(80, Gdx.graphics.getHeight()/2 -texturaPala.getHeight() /2);
Rpaddle = new RightPaddle(Gdx.graphics.getWidth() -100, Gdx.graphics.getHeight()/2 - texturaPala.getHeight() /2, ball);
font = new BitmapFont();
font.setColor(Color.WHITE);
font.setScale(1f);
puntuacion = 0;
}
public void render(float delta){
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
updatePuntuacion();
Lpaddle.update();
Rpaddle.update();
ball.update(Lpaddle, Rpaddle);
batch.begin();
batch.draw(texture, 0, 0,texture.getWidth(), texture.getHeight());
ball.draw(batch);
Lpaddle.draw(batch);
Rpaddle.draw(batch);
font.draw(batch, "Points: " + Integer.toString(puntuacion), Gdx.graphics.getWidth() / 4 ,Gdx.graphics.getHeight() - 5);
font.draw(batch, "High score: " + Integer.toString(puntuacionMaxima),Gdx.graphics.getWidth() - Gdx.graphics.getWidth() / 4 ,Gdx.graphics.getHeight() - 5);
batch.end();
}
private void updatePuntuacion(){
if(ball.getBordes().overlaps(Lpaddle.getBordes())) {
puntuacion = puntuacion + 1;
if(puntuacion > puntuacionMaxima)
puntuacionMaxima = puntuacion;
}
if(ball.getBordes().x <= 0)
sonidoex.play();
if(ball.getBordes().x <= 0)
puntuacion =0;
if(ball.getBordes().x <=0)
Gdx.input.vibrate(1000);
if(ball.getBordes().x <=0)
Screens.juego.setScreen(Screens.MAINSCREEN);
ball.comprobarPosicionBola();
}
public void hide(){
font.dispose();
texture.dispose();
}
#Override
public void dispose(){
preferencias.putInteger("puntuacionMaxima", puntuacionMaxima);
preferencias.flush();
}
public void resize(int width, int height){
float widthImage = texture.getWidth();
float heightImage = texture.getHeight();
float r = heightImage / widthImage;
if(heightImage > height) {
heightImage = height;
widthImage = heightImage / r;
}
if(widthImage > width) {
widthImage = width;
heightImage = widthImage * r;
}
escala = width / widthImage;
if(Gdx.app.getType()== ApplicationType.Android)
viewport.update(width, height);
}
}
Firstly, use an orthograpic camera.
camera=new OrthographicCamera(800,480);
camera.position.set(800/2f,480/2f,0);
viewport=new FitViewport(800,480,camera);
Now 0,0 is in the left bottom corner of your screen.
And before doing batch.begin don't forget to set your projection matrix
batch.setProjectionMatrix(camera.combined);
batch.begin();
////
////
batch.end();

Libgdx - Adding button/image controls in game world?

I am still new in libgdx and confused, i want some button in my games(always in bottom left screen) for make some event (use item, create soldier,etc). Where can i put this button in my games class? I have worldController class, worldRenderer class and GameScreen class (like in canyon bunny from libgdx ebook)
I have tried add stage and button in worldRenderer class then draw it in one of renderGui methods but nothing is shown. So, how to insert button to inside my game world?
Thanks...
public class WorldRenderer implements Disposable {
private OrthographicCamera camera;
public SpriteBatch batch;
private Stage stage = new Stage();
private Button btnItem;
private Skin skinLibgdx = new Skin(
Gdx.files.internal(Constants.SKIN_LIBGDX_UI),
new TextureAtlas(Constants.TEXTURE_ATLAS_LIBGDX_UI));
private WorldController worldController;
private OrthographicCamera cameraGUI;
public float w = Constants.VIEWPORT_GUI_WIDTH/1366;
public float h = Constants.VIEWPORT_GUI_HEIGHT/768;
public WorldRenderer (WorldController worldController) {
this.worldController = worldController;
init();
}
private void init () {
batch = new SpriteBatch();
camera = new OrthographicCamera(Constants.VIEWPORT_WIDTH, Constants.VIEWPORT_HEIGHT);
camera.position.set(0, 0, 0);
camera.update();
btnItem = new Button(skinLibgdx);
btnItem.addListener(new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
// TODO Auto-generated method stub
System.out.println("ABC");
}
});
stage.addActor(btnItem);
//background = new ParallaxBackground(layers,camera,batch);
cameraGUI = new OrthographicCamera(Constants.VIEWPORT_GUI_WIDTH,
Constants.VIEWPORT_GUI_HEIGHT);
cameraGUI.position.set(0, 0, 0);
cameraGUI.setToOrtho(true); // flip y-axis
cameraGUI.update();
}
public void render () {
renderWorld(batch);
renderGui(batch);
}
private void renderWorld (SpriteBatch batch) {
//background.render();
worldController.cameraHelper.applyTo(camera);
batch.setProjectionMatrix(camera.combined);
batch.begin();
worldController.level.render(batch);
batch.end();
}
public void resize (int width, int height) {
//camera.viewportWidth = (Constants.VIEWPORT_HEIGHT / height) *width;
camera.update();
cameraGUI = new OrthographicCamera(Constants.VIEWPORT_GUI_WIDTH,
Constants.VIEWPORT_GUI_HEIGHT);
cameraGUI.position.set(0, 0, 0);
cameraGUI.setToOrtho(true); // flip y-axis
cameraGUI.update();
}
#Override
public void dispose() {
// TODO Auto-generated method stub
batch.dispose();
}
private void renderGuiScore (SpriteBatch batch) {
float x = -15;
float y = -15;
batch.draw(Assets.instance.enemies.soldiers,x, y, 50, 50, 100, 100, 0.35f, -0.35f, 0);
Assets.instance.fonts.defaultBig.draw(batch,
"" + worldController.score,
x + 75, y + 37);
//stage.draw(); i have try draw in this line too but UI become dissapear
}
private void renderGuiExtraLive (SpriteBatch batch) {
float x = cameraGUI.viewportWidth - 50 - Constants.LIVES_START*50;
float y = -15*h;
for (int i = 0; i < Constants.LIVES_START; i++) {
if (worldController.lives <= i)
batch.setColor(0.5f, 0.5f, 0.5f, 0.5f);
batch.draw(Assets.instance.hero.hero1,
x + i * 50, y, 50, 50, 120, 100, 0.35f, -0.35f, 0);
batch.setColor(1, 1, 1, 1);
}
}
private void renderGuiHealth (SpriteBatch batch) {
float x = 50;
float y = -15*h;
for (int i = 0; i < Constants.LIVES_START; i++) {
if (worldController.lives <= i)
batch.setColor(Color.RED);
float health = worldController.level.hero.getHealth();
Assets.instance.fonts.defaultBig.draw(batch,
"" + Math.round(health),
x + 75, y + 37);
}
}
private void renderGuiEnergy (SpriteBatch batch) {
float x = 125;
float y = -15*h;
for (int i = 0; i < Constants.LIVES_START; i++) {
if (worldController.lives <= i)
batch.setColor(Color.GREEN);
float energy = worldController.level.hero.getEnergy();
Assets.instance.fonts.defaultBig.draw(batch,
"" + Math.round(energy),
x + 75, y + 37);
}
}
private void renderGuiPlasma (SpriteBatch batch) {
float x = 200;
float y = -15*h;
for (int i = 0; i < Constants.LIVES_START; i++) {
if (worldController.lives <= i)
batch.setColor(Color.BLACK);
Assets.instance.fonts.defaultBig.draw(batch,
"" + worldController.level.hero.getUltimateEnergy() + "-" + worldController.level.hero.getPower() + "-" + worldController.plasma,
x + 75, y + 37);
}
}
private void renderGui (SpriteBatch batch) {
batch.setProjectionMatrix(cameraGUI.combined);
batch.begin();
// draw collected gold coins icon + text
// (anchored to top left edge)
renderGuiScore(batch);
// draw extra lives icon + text (anchored to top right edge)
renderGuiExtraLive(batch);
//draw Health
renderGuiHealth(batch);
//draw Energy
renderGuiEnergy(batch);
//draw Plasma
renderGuiPlasma(batch);
batch.end();
stage.draw();
}
}
You have forgotten:
stage.act();
And set the input processor:
Gdx.input.setInputProcessor(stage);

Why isn't the LinkedList going through all the entities?

I am trying to develop collision detection. For some reason, the collision is working for the last entity in the LinkedList. I have tried my best to debug it using the console to see where it's stopping, but I had no luck. All the other entities are not working, only the last one is. Here is the code :
public class Player implements Entity {
Image player;
public float x = 100f;
public float y = 100f;
boolean canGoLeft = true;
boolean canGoRight = true;
boolean canGoUp = true;
boolean canGoDown = true;
public float speed = 0.15f;
public Rectangle leftRect;
public Rectangle rightRect;
public Rectangle topRect;
public Rectangle bottomRect;
int i = 0;
Entities entities = new Entities();
public Player() {
}
public void update(GameContainer game, int delta) {
if(Keyboard.isKeyDown(Keyboard.KEY_D)) {
if(canGoRight) {
x += speed * delta;
}
}
if(Keyboard.isKeyDown(Keyboard.KEY_A)) {
if(canGoLeft) {
x -= speed * delta;
}
}
if(Keyboard.isKeyDown(Keyboard.KEY_W)) {
if(canGoUp) {
y -= speed * delta;
}
}
if(Keyboard.isKeyDown(Keyboard.KEY_S)) {
if(canGoDown) {
y += speed * delta;
}
}
for(Entity entity : Game.entities.entities) {
checkCollisions(entity);
}
}
public void render(GameContainer game, Graphics g) {
leftRect = new Rectangle(x, y + 5, 2, 80);
rightRect = new Rectangle(x + 45, y + 5, 2, 80);
topRect = new Rectangle(x + 6, y, 36, 2);
bottomRect = new Rectangle(x + 6, y + 90, 36, 2);
//rect = new Rectangle(200, 100, 60, 88);
try {
player = new Image("res/Player.png");
player.setFilter(Image.FILTER_NEAREST);
} catch (SlickException e) {
e.printStackTrace();
}
player.draw(x, y, 60, 88);
//g.draw(leftRect);
//g.draw(rightRect);
//g.draw(topRect);
//g.draw(bottomRect);
}
public void checkCollisions(Entity entity) {
// Collision Detection
canGoLeft = !leftRect.intersects(entity.getRect());
canGoRight = !rightRect.intersects(entity.getRect());
canGoDown = !bottomRect.intersects(entity.getRect());
canGoUp = !topRect.intersects(entity.getRect());
}
public Rectangle getRect() {
return null;
}
}
It is iterating through your entire list, but checkCollisions overwrites the value of canGoLeft, canGoRright, etc. every time it is called.
You should do something like
canGoLeft = canGoLeft && !leftRect.intersects(entity.getRect());

Categories