Here's the line I'm getting the error on:
bucket.x = touchPos.x - 64 / 2;
Here's the full code block:
package com.badlogic.drop;
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.Vector3;
import java.awt.Rectangle;
public class Drop extends ApplicationAdapter {
private Texture dropImage;
private Texture bucketImage;
private Sound dropSound;
private Music rainMusic;
private OrthographicCamera camera;
private SpriteBatch batch;
private Rectangle bucket;
#Override
public void create () {
// load the images for the droplet and the bucket, 64x64 pixels each
dropImage = new Texture(Gdx.files.internal("droplet.png"));
bucketImage = new Texture(Gdx.files.internal("bucket.png"));
//instantiating the rectangle and specify its initial values
bucket = new Rectangle();
bucket.x = 800 / 2 - 64 / 2;
bucket.y = 20;
bucket.width = 64;
bucket.height = 64;
// setting the camera to show an area of the game world that is 800x480 units wide
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
// creating the sprite batch
batch = new SpriteBatch();
// 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();
}
#Override
public void render () {
Gdx.gl.glClearColor(0, 0, 0.2f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// render the bucket
batch.setProjectionMatrix(camera.combined);
batch.begin();
batch.draw(bucketImage, bucket.x, bucket.y);
batch.end();
// telling the camera to make sure its updated
camera.update();
// making the button move through touch
if(Gdx.input.isTouched()) {
Vector3 touchPos = new Vector3();
touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(touchPos);
bucket.x = touchPos.x - 64 / 2;
}
}
}
The error I'm receiving is telling me I have an incompatible types: Possible lossy conversion from float to int
Thanks in advance for the help, this is my first time posting to stackoverflow, I hope I formatted this correctly if you have any other questions let me know. :)
Based on the error message, your touchPos.x is a float. The compiler is telling you that when you try to put a floating-point value into an integer type, you will lose the fractional part (and if the number is really big, it might not fit), and you have to explicitly okay the conversion with a cast:
bucket.x = (int) (touchPos.x - 64) / 2;
Note also that you almost certainly meant the above version with parentheses; standard order of operations applies in Java. If you didn't, make your code clearer by just subtracting 32 instead.
Related
So i am having trouble keeping a display of the score in a game i am creating. I was wondering how would i go about doing that? this is what i have so far:
package com.catgame.game;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputProcessor;
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.BitmapFont;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class CatGame extends ApplicationAdapter implements InputProcessor {
SpriteBatch batch;
Sprite cat;
OrthographicCamera camera;
final float CAT_WIDTH = 0.75f;
final float CAT_HEIGHT = 0.50f;
Sound meow;
int score = 0;
String scorePrint;
BitmapFont scoreFont;
#Override
public void create () {
batch = new SpriteBatch();
cat = new Sprite(new Texture(Gdx.files.internal("Cat.png")));
cat.setSize(CAT_WIDTH,CAT_HEIGHT);
scoreFont = new BitmapFont(Gdx.files.internal("score.fnt"));
float aspectRatio = (float)Gdx.graphics.getHeight()/
(float)Gdx.graphics.getWidth();
scoreFont.getData().setScale(0.5f);
camera = new OrthographicCamera(CAT_HEIGHT * aspectRatio,
CAT_HEIGHT);
camera.position.set(CAT_WIDTH/2,CAT_HEIGHT/2,0);
meow = Gdx.audio.newSound(Gdx.files.internal("Meow.wav"));
Gdx.input.setInputProcessor(this);
scorePrint = "Hello";
}
#Override
public void render () {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
batch.begin();
batch.setProjectionMatrix(camera.combined);
//cat.draw(batch);
scoreFont.draw(batch,scorePrint,camera.position.x,camera.position.y);
batch.end();
}
I have tried scoreFont.draw() method but it doesn't seem to work. not sure why, maybe my positioning is wrong since I have an ortho camera or something. But When i tried to used the draw font, nothing appeared. The red circle in the image below shows where i would want the score around.
http://imgur.com/gallery/ywFF6SZ/new
Draw your font in render method and change your font colour or background colour.It might be possible because you black background colour match with BitmapFont colour.
You need to draw the score (or whatever you want to see on screen) inside the render function, because each render clears the canvas and redraws.
You are drawing the font too big. When you don't specify a scale for the font before drawing it, it draws it at a scale of one font pixel to one world unit. In your case, your camera height is less than one, so you are only seeing a fraction of one pixel of the first letter in your text, which is likely just empty space. Call setScale on the font after setting up your camera, using the appropriate scale to get it down to the size you want.
I have just started with LibGdx and I have figured out how to center text with it. Now I am having trouble with center justifying text. I was wondering if someone can help. I have attach my code for centering. Thank you in advance.
package com.tutorials.game;
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.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.GlyphLayout;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class TextDemo extends ApplicationAdapter {
SpriteBatch batch;
BitmapFont font;
String myText;
GlyphLayout layout = new GlyphLayout();
#Override
public void create () {
batch = new SpriteBatch();
font = new BitmapFont(Gdx.files.internal("myFont.fnt"));
myText = "I took one, one cause you left me\n"
+ "Two, two for my family\n"
+ "Three, three for my heartache";
layout.setText(font,myText);
}
#Override
public void render () {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
float x = Gdx.graphics.getWidth()/2 - layout.width/2;
float y = Gdx.graphics.getHeight()/2 + layout.height/2;
batch.begin();
font.draw(batch,layout,x,y);//Center Text
batch.end();
}
You can use following setText() method instead and set targetWidth to screen width, Aligh.center, and set wrap to true. Also, set x = 0 so the text is centered across the whole screen.
import com.badlogic.gdx.graphics.g2d.GlyphLayout;
public void setText(BitmapFont font,
java.lang.CharSequence str,
Color color,
float targetWidth,
int halign,
boolean wrap)
Updated example:
#Override
public void create () {
batch = new SpriteBatch();
font = new BitmapFont(Gdx.files.internal("myFont.fnt"));
myText = "I took one, one cause you left me\n"
+ "Two, two for my family\n"
+ "Three, three for my heartache";
layout.setText(font,myText,Color.BLACK,Gdx.graphics.getWidth(),Align.center,true);
}
#Override
public void render () {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
float x = 0;
float y = Gdx.graphics.getHeight()/2 + layout.height/2;
batch.begin();
font.draw(batch,layout,x,y);//Center Text
batch.end();
}
Instead of using the font.draw method, use the following one instead...
public TextBounds drawMultiLine (Batch batch, CharSequence str, float x, float y, float alignmentWidth, HAlignment alignment)
alignmentWidth is the max width you want your text to take up. Any more than that and it will wrap. Set it to something stupidly high if you don't want wrapping.
'alignment' is the key thing and takes an HAlignment enum and can be either LEFT, RIGHT or CENTER
The batch, str, x and y parameters are the same as you're already doing.
I am following a tutorial on creating a game with LibGdx from some ebook. the tutorial has steps for creating a game called "Canyon Bunny". Its a simple 2D game. but i keep getting this annoying error! (i also used to get the error on a different tutorial of the same genre)
i am in the early stages of the development for this game. and i am doing some test (of which i follow to the letter from the tutorial). I use a MAC and a i have tried many solutions with no luck at all.
Exception in thread "LWJGL Application" java.lang.NullPointerException
at com.Adel.CanyonBunny.game.WorldUpdater.updateTestObjects(WorldUpdater.java:83)
at com.Adel.CanyonBunny.game.WorldUpdater.update(WorldUpdater.java:76)
at com.Adel.CanyonBunny.CanyonBunnyMain.render(CanyonBunnyMain.java:39)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:207)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:114)
It is truly one of the most frustrating things a striving programmer can face.
ill get the code of all the classes in case that's related somehow...
This is CanyonBunnyMain in the general program:
package com.Adel.CanyonBunny;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
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.Adel.CanyonBunny.game.*;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.Application;
public class CanyonBunnyMain implements ApplicationListener {
private static final String TAG = CanyonBunnyMain.class.getName();
private WorldUpdater worldUpdater;
private WorldRenderer worldRenderer ;
private boolean paused ;
public void create() {
//I'll set the log to debug for the developing process
Gdx.app.setLogLevel(Application.LOG_DEBUG) ;
worldUpdater = new WorldUpdater();
worldRenderer = new WorldRenderer() ;
// since, upon creation, the game is not paused, then:
paused = false ;
}
public void render() {
if (paused = true) {
//update the game by the time passed since the last update
worldUpdater.update(Gdx.graphics.getDeltaTime()) ;
}
//sets the screen color to: CornFlower Blue
Gdx.gl.glClearColor(0x64 / 255.0f, 0x95 / 255.0f, 0xed / 255.0f, 0xff / 255.0f);
//clears the screen to prevent flickering
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT) ;
//Render the game to the screen
worldRenderer.render();
}
public void resize (int w, int h) {
worldRenderer.resize(w, h) ;
}
public void pause () {
paused = true ;
}
public void resume() {
paused = false ;
}
public void dispose() {
worldRenderer.dispose() ;
} }
this is the WorldRenderer (general program too) :
package com.Adel.CanyonBunny.game;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.MathUtils;
public class WorldRenderer {
private OrthographicCamera cam;
private SpriteBatch batch ;
private WorldUpdater updater;
public void WorldRenderer(WorldUpdater worldUpdater) { }
public void init() { }
public void render() { }
public void resize(int w, int h) { }
public void dispose() { }
}
this is the main class (from the desktop project: the one that i run on my MAC) :
package com.Adel.CanyonBunny;
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 = "CanyonBunny";
cfg.useGL20 = false;
cfg.width = 800;
cfg.height = 480;
new LwjglApplication(new CanyonBunnyMain(), cfg);
}
}
Any help will be wonderful.
tell me should you need extra data
this is the WorldUpdater class for those who asked:
package com.Adel.CanyonBunny.game;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.math.MathUtils;
public class WorldUpdater {
private final String TAG = WorldUpdater.class.getName();
public Sprite[] testSprites;
public int selectedSprite;
public WorldRenderer worldRenderer;
public void worldUpdater() {
init() ;
}
public void init() {
initTestObjects() ;
}
private void initTestObjects() {
// create new array of 5 sprites
testSprites = new Sprite[5] ;
// Create empty POT-sized Pixmap with 8 bit RGBA pixel data
int w = 32;
int h = 32;
Pixmap pixmap = createProceduralPixmap(w, h) ;
//create a new texture from Pixmap data
Texture texture = new Texture(pixmap) ;
//create sprites using the just created texture
for (int i = 0; i < testSprites.length; i++) {
Sprite spr = new Sprite(texture) ;
spr.setSize(1,1) ;
//set origin to sprite's center
spr.setOrigin(spr.getWidth() / 2.0f, spr.getHeight() / 2.0f) ;
float randomX = MathUtils.random(-2.0f, 2.0f) ;
float randomY = MathUtils.random(-2.0f, 2.0f) ;
spr.setPosition(randomX, randomY) ;
//put new sprite into array
testSprites[i] = spr ;
}
//set first sprite as the selected one
selectedSprite = 0 ;
}
private Pixmap createProceduralPixmap(int width, int height) {
Pixmap pixmap = new Pixmap(width, height , Format.RGBA8888) ;
//fill the square with red color at 50% opacity
pixmap.setColor(1, 0, 0, 0.5f) ;
pixmap.fill() ;
//draw a yellow X in the pixmap
pixmap.setColor(1, 1, 0 , 1) ;
pixmap.drawLine(0, 0, width, height) ;
pixmap.drawLine(width, 0, 0, height);
//draw a cyan-colored border around the square
pixmap.setColor(0, 1, 1, 1) ;
pixmap.drawRectangle(0, 0, width, height) ;
return pixmap;
}
public void update(float deltaTime) {
updateTestObjects(deltaTime);
}
private void updateTestObjects(float deltaTime) {
//get current rotation from the selected sprite
float rotation = testSprites[selectedSprite].getRotation();
//rotate sprite by 90 degrees per second
rotation += 90 * deltaTime;
//wrap around at 360 degrees
rotation %= 360 ;
testSprites[selectedSprite].setRotation(rotation);
}
}
Also, when i check this line out in Debugging mode:
testSprites = new Sprite[5] ;
"testSprites" keeps showing null.
i hope this clears up some details!
thanks again.
The problem is with your "constructors", mainly in the updater (as the renderer does nothing):
public void worldUpdater() { ... }
Constructors should not specify return types - that's part of how the compiler recognizes them as constructors. As it is in your code, it's just a method you could call on an existing object instance. Change it like so:
public WorldUpdater() { ... }
Note the lack of a return type and the uppercase W.
You can change the renderer the same way. (But then you will have to pass the updater to its constructor in the main class.)
Also, Nine Magics is right that the way you store renderer and updater references in each other doesn't make much sense, even if it's not related to this problem. I see no reason why an updater class would need to know about its renderer, I'd remove that field.
In your WorldRenderer you specify this:
public void WorldRenderer(WorldUpdater worldUpdater) { }
And WorldRendere also carries an instance of an worldUpdater?
private WorldUpdater updater;
But on your main file you create an instance of both renderer and updater?
worldUpdater = new WorldUpdater();
worldRenderer = new WorldRenderer() ;
I don't know, I might have tired eyes or something but this seems too complex. Can it be that you are refering to a wrong instance of WorldUpdater? Might edit this if I can wrap my head around it better.
I'm developing my first android game with libgdx, using as a base this amazing tutorial (http://www.kilobolt.com/day-11-supporting-iosandroid--splashscreen-menus-and-tweening.html). Everything works properly except for the tweening that I’m using in the splash screen to show the logo of my “company”. The weird part is that the logo works just fine in the desktop version, but in the android version is not being showed.
I’m using the same class that they used in the app developed in the tutorial. By the way, this app’s splash screen works fine in both versions.
I have compared my app and the tutorial’s app, but I found no differences except for this on the package explorer. I don't know if it means something:
http://i1223.photobucket.com/albums/dd507/victormmenendez/tut.jpg
package com.victor.Screens;
import aurelienribon.tweenengine.BaseTween;
import aurelienribon.tweenengine.Tween;
import aurelienribon.tweenengine.TweenCallback;
import aurelienribon.tweenengine.TweenEquations;
import aurelienribon.tweenengine.TweenManager;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.victor.TweenAccessors.SpriteAccessor;
import com.victor.FZHelpers.AssetLoader;
import com.victor.FZombies.FZGame;
public class SplashScreen implements Screen
{
private TweenManager manager;
private SpriteBatch batcher;
private Sprite sprite;
private FZGame game;
public SplashScreen(FZGame game)
{
this.game = game;
}
#Override
public void show()
{
sprite = new Sprite(AssetLoader.logo);
sprite.setColor(1, 1, 1, 0);
float width = Gdx.graphics.getWidth();
float height = Gdx.graphics.getHeight();
float desiredWidth = width * .4f;
float scale = desiredWidth / sprite.getWidth();
sprite.setSize(sprite.getWidth() * scale, sprite.getHeight() * scale);
sprite.setPosition((width / 2) - (sprite.getWidth() / 2), (height / 2) - (sprite.getHeight() / 2));
setupTween();
batcher = new SpriteBatch();
}
private void setupTween()
{
Tween.registerAccessor(Sprite.class, new SpriteAccessor());
manager = new TweenManager();
TweenCallback cb = new TweenCallback()
{
#Override
public void onEvent(int type, BaseTween<?> source)
{
game.setScreen(new GameScreen());
}
};
Tween.to(sprite, SpriteAccessor.ALPHA, .8f).target(1).ease(TweenEquations.easeInOutQuad).repeatYoyo(1, .4f).setCallback(cb).setCallbackTriggers(TweenCallback.COMPLETE).start(manager);
}
#Override
public void render(float delta)
{
manager.update(delta);
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
batcher.begin();
sprite.draw(batcher);
batcher.end();
}
}
Thank you very much for your help. I'm sorry if in any moment I couldn’t explain myself, but English is not my primary language. If you need any extra piece of code, I can add it.
You need to make sure you export the tween jar files in your Build Path. For Eclipse, you can Right-click on the project, choose "Build Path" > "Configure Build Path", go to the "Order and Export" tab on the right side, and make sure that the tween jar files are checked in the list there.
I've tried to get my text to appear, but I cannot get it on screen. I've played with the numbers a few times and found out that LibGDX drew the font to abnormally large sizes, but I don't exactly know if I still need to scale the font size smaller, or if I'm drawing them offscreen. I've copied the entire code and pasted it below.
I used Hiero to make a 256x256 bitmapfont of ariel black on white background.
package com.me.manners;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.me.input.Input;
public class Choice implements Screen
{
private PerspectiveCamera camera;
private SpriteBatch batch;
private Texture arrowT;
private Sprite arrowS;
private BitmapFont font;
private String str1 = "Hello World!";
private Input input = new Input();
private Manners game;
public Choice(Manners game)
{
this.game = game;
camera = new PerspectiveCamera();
batch = new SpriteBatch();
font = new BitmapFont(Gdx.files.internal("data/choice/ariel.fnt"), Gdx.files.internal("data/choice/ariel.png"),false);
Gdx.input.setInputProcessor(input);
arrowT = new Texture(Gdx.files.internal("data/choice/arrow.png"));
arrowT.setFilter(TextureFilter.Linear, TextureFilter.Linear);
arrowS = new Sprite(new TextureRegion(arrowT, 0, 0, 64, 64));
arrowS.setSize(0.125f, 0.25f);
arrowS.setPosition(-0.75f, 0);
}
#Override
public void dispose() {
batch.dispose();
arrowT.dispose();
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined);
batch.begin();
arrowS.draw(batch);
font.setColor(1.0f,1.0f,0.0f,1.0f);
font.setScale(0.5f,0.5f);
font.draw(batch, str1, Gdx.graphics.getWidth()*0.5f, Gdx.graphics.getHeight()*0.5f);
batch.end();
}
}
I think your game is 2D game, so using camera = new OrthographicCamera(viewportWidth, viewportHeight) can fix your problem.
phucvin makes a very good observation. It seems your game is 2d ,so you should use an OrtographicCamera. I would recommend you to use big numbers, because the BitmapFont will render using its correct pixel size (thus thats the reason you saw very big letters).
camera = new OrthographicCamera(480, 320); //for example.
Of course you will need to change the Sprite size to something bigger
arrowS.setSize(100, 20); //for example
Or using a second camera with low viewport values for the sprites.