_id
int64
0
49
text
stringlengths
71
4.19k
15
Libgdx Scene2d and Box2d light Currently I am using scene2d and I want to implement shadows using Box2d light. I want shadows under characters but when I draw something after render() , it draws nothing. For example, in draw() method of an actor, public void draw(Batch batch, float delta) super.draw(batch,delta) ray handler.render() batch.draw(Something......) But when draw before render, it shows no problem. public void draw(Batch batch, float delta) super.draw(batch,delta) batch.draw(Something......) ray handler.render() How can I solve this problem?
15
Is reusing BitmapFonts possible in GDX? I'm loading multiple labels (100 ) with different font types (max 10), but they have different sizes. As I read the code and did the research, it's not possible to 'reuse' the font. For instance, I have 5 labels made with GILL SANS font but these labels must have different scales (font scales). Should I really make 5 different BitmapFont objects for different scales (AND LOAD THESE TERRIBLE GRAPHICS AGAIN AND AGAIN) or is there any way to optimize this (without loading .fnt and .png again)? One load takes 2mbs of RAM (huge png) 2ms which is unacceptable for 100 labels. Edit I've check that. Label caches fonts so you can scale the same font and use setFontScale() on each label. But what about TextField?
15
libgdx images go out of proportion on some devices I'm trying to develop a simple game using libgdx. The game works perfectly on emulator ( Nexus 5x API 26 x86 ). But when I generated its apk and tested on my phone(Samsung J7), the images somehow seem to go out of proportion. I dont know if the problem is libgdx specific or something else is causing the problem. I suspect that the issue is about the different screen sizes or resolution. This is how I want it to be. This is how it appears. The images appear to be enlarged. The app seems to work as expected on larger mobile screens but the images do not scale well to smaller screens. Does libGdx or the android not automatically resize images according to the hardware being run on ? Any help would be highly appreciated. Edit boy new Texture("boyfinal.png") batch.draw(boy, Gdx.graphics.getWidth() 4 boy.getWidth() 2, boyY )
15
Steering behaviours collision avoidance with rectangles I'm trying to implement collision avoidance steering behaviour using rectangles. Most of the tutorials I've found are with circles, and there's a substantial difference. For example, I've been reading this http gamedevelopment.tutsplus.com tutorials understanding steering behaviors collision avoidance gamedev 7777 My current approach first, detect the nearest rectangle as done in the article. I create a point called ahead in front of my entity and then check if that point is inside the rectangle. After calculating the nearest object, I decompose my rectangle in a set of points, equally spaced in the rectangle walls. My entity will flee those points. EDIT I've also proven to convert my rectangle in an electromagnetic repulsive rectangle with 4 bars of homogeneus charged. It didn't worked. I also tried the "containment" section described in Craig Reynolds' website and it also didn't worked properly. That works reasonably well my entities try to avoid the rectangle. However, they sometimes get a bit into it, and when they're near the rectangle they start flipping to left and right quickly. That is not a very natural behaviour, so I think I want to prove another thing. I've read this in gamedev SO Wall avoidance steering I think that this could be what I need, approximately. However, I need some guidance on this. First, the answer speakes about a dot product of the wall boid vectors (let's call them WBi). Which is the another vector I have to multiply with? In the code sample is noted as partsList but I don't know what it is. So, first question what is this second vector? In my opinion, this algorithm as a very important flow. If the force is exerted in the direction of normal of the wall, and by chance my entity goes with velocity normal to the wall, it will stop. This, I think, could be a rare event because more steering forces are involved... Second question there is a way to avoid this? Is this effect important enough to take care of it even if I have more forces? In fact, I need an algorithm capable of detecting and avoding rectangles with steering behaviors or, at less, a way to move my entities in a space with obstacles using something compatible with steering behaviors, because I use them for coordinate movement. Take in account that some combinations of rectangles could create convex shapes. EDITS The rectangles aren't rotated.
15
Is using camera and viewport in Libgdx always necessary? I understand that camera and viewport are important to keep virtual measurement units and handle different aspect ratios and resolutions when building games with worlds bigger than the screen (e.g. side scrollers map based games). I am not sure whether it is the proper way to go for a simple game that fits on the screen entirely like a puzzle or card game for example. Is it still better to use camera and viewport in this case, or is it more simple, effective (and hence better) to use directly screen absolute coordinates for these types of games? Or to put it in other way what are the advantages to use camera and viewport for games that fit on the screen entirely?
15
What libgdx project files can I ignore from version control? In an automatically created libgdx project, what files can I safely tell Git (or other revision control systems) to ignore? I'm considering these android .settings android bin desktop .settings desktop bin html .settings html gwt unitCache html war WEB INF classes html war WEB INF deploy html war assets html war .settings bin Am I missing some? Is there a complete list somewhere?
15
Libgdx FPS drop drawing alot of text i'm drawing text above monster head and it's fine. But when there is to many monsters and their name gets render every second cause fps go down. When i disable the font drawing, then the fps is fine. Any id a how to tackle this perfomence issue? Thanks.
15
How to create a polygon button in LibGDX? I need to make a button not a standard square shape, but a polygon shape.How to create a polygon button in LibGDX?
15
How to work with libddx and Android studio I am new in game development.I am getting problem with libgdx. when i download libgdx i get zip file.where is setup
15
How do I draw an object that I always want to appear in the same place on screen on a scrolling orthographic camera using lib gdx? So I want to make an endless scroller game and the orthographinc camera is scrolling downward so i want the character to stay with the camera. I'm not sure how to aproach this i've been looking a lot online but couldn't find anything that works. The 2 ways I thought about doing it is to either make the object scroll at the same speed as the camera or in someway draw the object on the cameras "graph". This is the first game i'm making with libgdx so any help or suggestions are appreciated. ) Thanks This is the gamescreen package com.ounceoftech.mygame import com.badlogic.gdx.Game import com.badlogic.gdx.Gdx import com.badlogic.gdx.Input.Keys import com.badlogic.gdx.Screen import com.badlogic.gdx.graphics.GL20 import com.badlogic.gdx.graphics.OrthographicCamera import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.math.Vector3 public class GameScreen implements Screen OrthographicCamera camera SpriteBatch batch Vector3 touch ship ship Game game public static int ship x 540 26 public GameScreen(Game game) this.game game camera new OrthographicCamera() camera.setToOrtho(false, 1080, 1920) batch new SpriteBatch() touch new Vector3() ship new ship() Override public void render(float delta) Gdx.gl.glClearColor(255F, 255F, 0F, 1F) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) camera.position.y 5 camera.update() generalUpdate(touch, camera) batch.setProjectionMatrix(camera.combined) batch.begin() Rendering Code batch.draw(ship.image, ship x, ship.bounds.y) batch.end() public void generalUpdate(Vector3 touch, OrthographicCamera camera) ship x Gdx.input.getAccelerometerX() 2 if(ship x lt 0) ship x 0 if(ship x gt 1027) ship x 1027 This is the object player package com.ounceoftech.mygame import com.badlogic.gdx.graphics.g2d.TextureRegion import com.badlogic.gdx.math.Rectangle import com.badlogic.gdx.math.Vector3 public class ship public TextureRegion image public Rectangle bounds public ship() image Assets.spriteShip bounds new Rectangle(GameScreen.ship x, 1600, 53, 256)
15
How should I separate drawing from system collision? Well, in my game while I'm drawing I have to verify the collision between the views. After a collision, I have to draw some things. But I can't draw them with a batch but with a stage. So I have to begin and end a lot of batches and this makes my game very slow. Here is the part of code which I talked about for(int i 0 i lt 1000 i ) if(i lt 999) list.get(i 1).xTubo list.get(i).xTubo list.get(i).distanza for(int j 0 j lt 60 j ) if( (xPersonaggio list.get(i).xTubo j xPersonaggio list.get(i).xTubo j 3) amp amp yPersonaggio lt list.get(i).altezza 50) batch.begin() if(ySalto 0) batch.draw((TextureRegion) animation.getKeyFrame(time, true), orthographicCamera.position.x 300, 60 ySalto) else batch.draw(textureAtlas.createSprite("h"), orthographicCamera.position.x 300, 60 ySalto) scrittaHaiPerso.draw(batch,"HAI PERSO!",orthographicCamera.position.x 50,500) menu.draw(batch,"MENU",orthographicCamera.position.x,300) batch.end() stage.draw() fineGioco true batch.begin() batch.draw(spriteTuboVerde,list.get(i).xTubo, 30,120,list.get(i).altezza) batch.end() if(xPersonaggio gt list.get(i).xTubo 50) tubiSaltati In this cycle I draw a lot of views, as you can see at the bottom. At the top I have my very rudimental collision system. When a collision happens, an imagebutton appears on the screen and I have to draw it with a stage. So I have to begin and ends a lot of times the batch and this doesn't go well at all. How can I write less batches? NOTE The order of drawing has to be this
15
Hand cards auto arrangement I'm making a card game with libgdx scene2d and what I'm trying to achieve is auto arrange the cards in a way the all fit the screen. This is what it looks now when the hand is full I have done that using a horizontalGroup and puting a 1 3 cardWidth space between the cards. I want the cards to spread evenly when some are removed. I think I have to change the space between the cards whenever a card is removed or added but I don't know how much. This is my code CardActor cards new CardActor 14 HorizontalGroup hand new HorizontalGroup() int width Gdx.graphics.getWidth() 10 int height width 2 hand.setBounds(width 2, height 4, stage.getWidth() width, height) hand.space(width 3f) hand.align(Align.bottom Align.center) for (int i 0 i lt cards.length i ) cards i new CardActor(new Card(MathUtils.random(3), MathUtils.random(3, 10))) hand.addActor(cards i ) stage.addActor(hand) And this is the CardActor public class CardActor extends ImageButton public CardActor(Card card) super(new TextureRegionDrawable(CardTextures .getTexture(card.getType(), card.getRank()))) int width Gdx.graphics.getWidth() 10 int height width 2 getImageCell().prefSize(width, height) setBounds(getX(), getY(), getWidth(), getHeight()) addListener(new ChangeListener() Override public void changed(ChangeEvent event, Actor actor) onSelected() )
15
testPoint not working libgdx I'm making a game like angry birds with LibGDX and box2d in which I want to drag a ball (instead of the bird) back before releasing it. I deploy with testPoint function when I touch down the screen, I check if the point is within the body of the ball or not but testPoint function never works exactly. Here's what I'm trying thanks so much public boolean touchDown(int screenX, int screenY, int pointer, int button) for(Fixture fixture bird.getBody().getFixtureList()) if(fixture.testPoint(screenX 100, (mapHeight screenY) 100)) 100 is scaled parameter draggedBird true return true return false
15
How to fix the character flip when using an orthographic camera in libGDX I used an orthographic camera to follow the character (player), but the problem is that my character is flipped. There are no tutorials on how to fix this. Please help as fast as possible. Here is my create method public void create () batch new SpriteBatch() float width Gdx.graphics.getWidth() float height Gdx.graphics.getHeight() camera new OrthographicCamera() camera.setToOrtho(false,width,height) camera.update() tiledMap new TmxMapLoader().load("assets untitled.tmx") tiledMapRenderer new OrthogonalTiledMapRenderer(tiledMap) player new Player(new Vector2(0,0)) sr new ShapeRenderer() Here is my render method public void render () Gdx.gl.glClearColor(0, 0, 0.2f, 1f) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) Gdx.gl.glBlendFunc(GL20.GL SRC ALPHA,GL20.GL ONE MINUS SRC ALPHA) player.update() camera.position.set(player.getPosition().x,player.getPosition().y,0) camera.update() tiledMapRenderer.setView(camera) tiledMapRenderer.render() sr.begin(ShapeRenderer.ShapeType.Line) sr.setColor(Color.BLUE) sr.rect(player.getPosition().x,player.getPosition().y,player.getCurrentFrame().getRegionWidth(),player.getCurrentFrame().getRegionHeight()) sr.end() batch.begin() batch.draw(player.getCurrentFrame(),player.getPosition().x, player.getPosition().y) batch.setProjectionMatrix(camera.combined) batch.end()
15
How can I load assets dynamically on user's input in LibGDX HTML? I am working with LibGDX and GWT and I am trying to publish my app as a HTML webapp, it has many assets with around hundred of folders, now I want to load them dynamically (user input is sent to JSNI, and security issues set aside), I want to be able to add more assets later without having to recompile the entire thing or creating new assets.txt file. Here is how the app works. A user select a foldername from an HTML dropdown, this will trigger an javascript function created by JSNI load(foldername). The app then load the files inside foldername and use it by accessing FileHandle file provided by Gdx.files.internal(file) My goal is to be able to add more assets later on without recompiling touching the java source code, and to eliminate load time so as not to preload hundreds of assets I was unable to find similar problem anywhere on the Internet and I am fairly new to this field. Workaround can be accepted too. I am using LibGDX 1.9.12 and GWT 2.8.2
15
How do I use Libgdx viewport for UI? I am using LibGDX to make a game for Android and I am using 2 Viewports. One for UI and one for the actual game content. My problem is I can't find a good way to scale my UI using a Viewport. This is a picture of my UI using a FitViewport As you can see it adds space on the top and bottom to fit the screen, but I want my pause button to stay on the top of the screen. I tried using a StretchViewport and that worked well for the pause button, but then the joysticks were no longer circle because they were distorted. Is there a way to make a StretchViewport that only stretches the middle? (since nothing will be in the middle I don't care about that. Should I make a custom Viewport? And if so, how would I go about that? Thank you for any help!
15
Libgdx FPS drop drawing alot of text i'm drawing text above monster head and it's fine. But when there is to many monsters and their name gets render every second cause fps go down. When i disable the font drawing, then the fps is fine. Any id a how to tackle this perfomence issue? Thanks.
15
How can I find all connected objects of the same type recursively? In my game, when a user selects an object of some type, I'd like to search for all other objects of the same type that are connected to that first one. For example, if the user selects a object of type 2, I want to check the object next to that one to see if it is also of type 2 and so on in all directions (up, down, left and right, et cetera) until there are no more objects of that type connected. Does anyone know how I could do something like this? You can assume I have access to the set of connections from any given object.
15
Play videos via 3rd party library or as animation in libGDX? I want to add an animated splash screen to my desktop game, which I develop using libGDX. Now I see there is no native support for videos in libGDX, so I guess I have two options Include a 3rd party framework for video playback (like the Java media framework) or Save the video as a series of PNG images and play them as a libGDX animation. Since the splash screen video is not very long, maybe 5 seconds or so, I tend to the libGDX animation option. However, the video would be full screen, so rather large images, and I am not sure whether an animation would really be the best option in that case. Does anyone of you guys have some experience with (full screen) video playback under libGDX on the desktop?
15
How do I add the "tween engine api" to my libGDX game? I finished now my first game at LibGDX (I am using Eclipse). I run the game in the desktop launcher and it works. I now want to run my game on Android and iOS. From some guides I have read, I understand that for running the game on devices I must have the tween engine library in my project. I tried but couldn't add it to my project. Can someone help me? (I already tried to do that at "add jars", but it only shows me my project and not the tween engine library)
15
Draw a sprite when a key is pressed in LibGDX I'm working with LibGDX. How can I draw a sprite when a key is pressed? I have tried with the following, but it doesn't seem to work. if (Gdx.input.isKeyPressed(Input.Keys.X)) batch.begin() sprite.draw(batch) batch.end()
15
Changing Box2D Body from Kinematic to Dynamic after contact What is the correct way to change a Kinematic body into a dynamic body? context I have a dynamic body as a projectile which has to be fired at a kinematic body (it is kinematic because i am tweening it around the world in random movements). when the projectile makes contact with the kinematic body I would like it to become a dynamic body and be affected by gravity and I will apply a force to the contact point. At the moment I am simply changing the type with in a menthod called by the contactListener body.setType(BodyType.DynamicBody) my biggest issue is that gravity is not acting on the body once it is changed to dynamic, so I'm pretty certain I'm going about this the wrong way.
15
LibGdx input data REQUIRED I am using the code below to ask users for their username. MyTextInputListener listenerz new MyTextInputListener() Gdx.input.getTextInput(listenerz, "Create Username", "") I have knowledge in PHP but beginner in Java LibGdx. I know that in HTML there is a REQUIRED lt input name 'username' required gt That's why I wanted to know the equivalent coding in LibGdx for the REQUIRED input.
15
Artefacts when drawing textures I am working on a level based android game. The level is constructed of many blocks, all drawn with the same texture. Until now I didn't have any problems with drawing the different textures next to each other. However, when I draw a translucent rectangle over the level (in order to show a pause screen on top of it for example), I get artefacts on the places where the textures overlap. To be more clear I included a screenshot that clearly shows my issue the regions where the textures of the different level blocks overlap do not have the same transparency as the rest of the rectangle. As you can see, only when drawing the translucent rectangle on top of the level, the overlap is visible.
15
libgdx input handling issue Not sure how to describe the issue I'm facing here Rectangles are grouped and attached to a "layer" extending Stage. Each layer is added to a multiplexer in a Screen extension. There are 2 layers Top has the 1 big rectangle amp group members (smaller colored rectangles) Bottom has the 2 big rectangles amp their members The 3 big rectangles are all the same size amp color (turns yellow if it detects the mouse is over it, for debugging purposes) When you click on it, it brings its group to the front of its layer. The problem is that both the top layer and bottom layer are processing the input, grouping and drawing stuff works fine. In the screenshot, only the top most big rectangle should be yellow at the cursor's position
15
Why do we put deltaTime as an argument in render() LibGDX? I know that deltaTime is the time the last frame took to be rendered. However, I have no idea why we have to put it inside the parameter of the render method. I also don't know how the render method takes use of the deltaTime.
15
Which is the best method implementing a background scrolling for game in libgdx? My question is very simple I am new to libgdx development, which is the best approach implementing a background that is to make the background move in y direction 1)My First approach is drawing the background image 10 times towards positive y direction using camera.translate(x,y) function to move camera from bottom to top 2)second approach is to make the camera still while making the background scroll ie drawing the background frame by frame updating the position each time Can you please suggest which is the best approach?
15
Howto apply alpha value (Color) to a sprite in libgdx Howto apply alpha to a sprite so it will work. With the following code, the sprite still is completely visible. Can someone help me ? batch.enableBlending() if (sprite ! null) Color c sprite.getColor() c.a 0 sprite.setColor(c) batch.draw(sprite, x, y) sprite.setAlpha(0f)
15
libgdx custom shape overlap detecting I'm writing my game on libgdx w o any of those extensions like box2d and whatsoever. But right now I'm forcing problem with overlapping detection. I need to detect if bullet (which is always in different degree) overlapped my rocket. At first I was using Rectangle, but it sometimes is giving me false overlap. I have visualized it. How it is now My goal as you see I also want to make bullets rectangle rotated so it was more accurate. And as I said earlier I need to detect collision overlapping between these polygons. Do I need to use that box2d extension??? Because right now I've written working prototype entirely w o it.
15
Does destroying body also destroys the sprite? Suppose a sprite is attached to a box2d body. And world.destroyBody(b) is getting called then the sprite also get destroyed or it stays there in memory. In my situation lots of box2d bodies are getting created and destroyed and after a delay of few seconds the sprite disappears. Here's the snippet of where body is getting destroyed Override public void act(float delta) super.act(delta) camera.update() world.step(1 60f, 6, 3) if (enemy destroy) Array lt Body gt bodies new Array lt Body gt () world.getBodies(bodies) for(int i 0 i lt bodies.size i ) Body b bodies.get(i) if (b.getUserData() instanceof Boolean) world.destroyBody(b) b.setActive(false)
15
Gdx.input.setInputProcessor(stage) doesn't work I have an image and I want to make clickable this image. I have already done this a lot of times, but this time doesn't work. Probably because the image is from a class which extends Image public class BitmapFontGenerale extends Image BitmapFont bitmapFont String scritta private float x private float y public BitmapFontGenerale(BitmapFont bitmapFont1, String string, float scale) bitmapFont bitmapFont1 bitmapFont.setColor(Color.BLACK) bitmapFont.getData().setScale(scale) scritta string Override public void draw(Batch batch, float parentAlpha) bitmapFont.draw(batch,scritta,x,y) public void setX(float x) this.x x public void setY(float y) this.y y public float getX() return x public float getY() return y This is the code which I used to set the input image.addListener(new ClickListener() Override public void clicked (InputEvent event, float x, float y) Gdx.app.log("CLICKED ", "CLICKED") ) stage.add(image) Gdx.input.setInputProcessor(stage) This code works if image is from Image class and not if it's from a class which extends Image. Note I need to extend Image class. What's the problem?
15
Libgdx 2d floor Animation I'm building Runner Game. Ground Class. public class Ground extends Actor private Texture texture private ArrayList lt Vector2 gt groundLocations private float speed private float cameraLeft, cameraRight private int textureWidth public Ground() this.cameraRight Const.GAME WIDTH Const.GAME MARGIN this.cameraLeft 0 Const.GAME MARGIN texture new Texture(Gdx.files.internal("ui ground.png")) groundLocations new ArrayList lt Vector2 gt () init() public void setSpeed(float speed) this.speed speed private void init() textureWidth texture.getWidth() float currentPosition cameraLeft while (currentPosition lt cameraRight) Vector2 newLocation new Vector2(currentPosition, 0) groundLocations.add(newLocation) currentPosition textureWidth public int getFloorHeight() return texture.getHeight() Override public void act(float delta) super.act(delta) int size groundLocations.size() for (int i 0 i lt size i ) Vector2 location groundLocations.get(i) location.x delta speed if (location.x lt cameraLeft) location.x findMax().x textureWidth private Vector2 findMax() return Collections.max(groundLocations, new Vector2Comparator()) Override public void draw(Batch batch, float parentAlpha) super.draw(batch, parentAlpha) for (Vector2 location groundLocations) batch.draw(texture, location.x, location.y) public void dispose() if (texture ! null) texture.dispose() Ground Texture is 128x128 GAME WIDTH 1024f GAME MARGIN 250f speed changes. While the ground is moving according to Speed and FPS. (Speed delta) Problem is There are always Gaps between ground Textures. after certain Movement function findMax finds the texture with the biggest X any help would be Appreciated. Solution for (int i 0 i lt size i ) Vector2 location groundLocations.get(i) if (location.x lt cameraLeft) location.x findMax().x textureWidth location.x delta speed
15
How do I derive an appropriate acceleration value for my game? I am creating a Flappy Bird clone from this tutorial. I have a question about acceleration in libgdx. The author assigned the bird a constant acceleration vector in the constructor of the bird acceleration new Vector2(0, 460) and later updated the velocity vector from the accleration vector with velocity.add(acceleration.cpy().scl(delta)) I understand generally why acceleration is constant like the author mentioned, acceleration due to gravity is 9.81m s 2, meaning that the speed of an object falling will increase by 9.81m s every second. It seems the author somehow got from 9.81 real world value to 460 in the actual code. How does one go about deriving this value? Is this a standard derivation or something the author just made up?
15
Registering InputListener in libGDX I'm just getting started with libGDX and have run into a snag registering an InputListener for a button. I've gone through many examples and this code appears correct to me but the associated callback never triggers ("touched" is not printed to console). I'm just posting the code with the abstract game screen and the implementing screen. The application starts successfully with a label of "Exit" in the bottom left hand corner, but clicking the button label does nothing. I'm guessing the fix is something simple. What am I overlooking? public abstract class GameScreen lt T gt implements Screen protected final T game protected final SpriteBatch batch protected final Stage stage public GameScreen(T game) this.game game this.batch new SpriteBatch() this.stage new Stage(0, 0, true) Override public final void render(float delta) update(delta) Clear the screen with the given RGB color (black) Gdx.gl.glClearColor(0f, 0f, 0f, 1f) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) stage.act(delta) stage.draw() public abstract void update(float delta) Override public void resize(int width, int height) stage.setViewport(width, height, true) Override public void show() Gdx.input.setInputProcessor(stage) hide, pause, resume, dipose public class ExampleScreen extends GameScreen lt MyGame gt private TextButton exitButton public ExampleScreen(MyGame game) super(game) Override public void show() super.show() TextButton.TextButtonStyle buttonStyle new TextButton.TextButtonStyle() buttonStyle.font Font.getFont("Origicide", 32) buttonStyle.fontColor Color.WHITE exitButton new TextButton("Exit", buttonStyle) exitButton.addListener(new InputListener() Override public void touchUp (InputEvent event, float x, float y, int pointer, int button) System.out.println("touched") ) stage.addActor(exitButton) Override public void update(float delta)
15
LibGdx sprite rotation vs Box2D physics rotation problem LibGdx sprite rotation vs Box2D physics rotation problem Tearing my hair out on this one. I am an experienced software developer, but very new to LibGdx and Box2D development. I am writing a game where the game board is the size of the screen. The game board does not pan it just fills the screen. For the descriptions below presume that the device is being held vertically, so that vertical is the longest length. Also, for the description below, presume that on a device with a 'normal' aspect ratio, circles will be rendered perfectly circular, but a device that is narrower than expected, the circles will be squashed so that they are taller than wide. I have a number of circle shapes that are rendered to the screen. Because different devices will have different width height aspect ratios, I am happy for the circle shapes to be squashed on a device that is narrower on the horizontal than expected (I am trying to avoid maintaining identical aspect ratios and forcing black borders at the edges of the game board). My problem is this when Box2D debug renders the screen, showing the physics objects, the circle shapes maintain their width and height, even when rotated. To describe further, if a sphere is displayed with 0 degree rotation on a narrow device, it takes an oval shape that is taller than it is wide, as would be expected on a narrower than expected device. If you rotate the circle shape by 90 degrees, the Box2d debug renderer shows the rotation (there is a line that sticks out of the centre of the object at an angle that shows the angle of rotation) but the object maintains its taller than wide oval shape. This is correct, as a sphere on a horizontally narrower aspect ratioed device will always be displayed taller than wide. When I attempt to overlay a LibGDX sprite on top of the Box2D physics simulation (the sprite, in its unaltered form, is circular, and is then scaled to the devices aspect ratio), with a zero degree angle, it appears nicely mapped to the Box2D representation taller than it is wide. However, when I rotate the LibGDX sprite by 90 degrees, it appears rotated the way a billboard image would be rotated, so it is now wider than it is tall (imagine drawing a taller than wide oval on a piece of paper and turning the piece of paper by 90 degrees). It appears to me that Box2D applies rotation before it applies the camera scaling so the circular object is rotated first (maintaining its circular shape under the hood), and then sqaushed to form an ellipse that is taller than wide on the screen. Whereas, the LibGDX engine applies the transforms in reverse. The object is squashed to taller than wide, then rotated, so it becomes wider than tall on the screen. I have pasted the relevant code below screen size in box2D metres private static float screenHeight 100.0f private static float screenWidth 70.0f set up the camera in the show() method cam new OrthographicCamera(screenWidth, screenHeight) cam.position.set(screenWidth 2, screenHeight 2, 0) render method batch.begin() for (int i 0 i lt ballList.length i ) ballList i .render(batch) batch.end() ball class render method public void render(SpriteBatch batch) ballHappyImage.setOrigin(64.0f, 64.0f) ballHappyImage.setPosition(body.getPosition().x 64.0f, body.getPosition().y 64.0f) float scaleWidth Gdx.graphics.getWidth() 1400.0f hardcoded to make things fit correctly float scaleHeight Gdx.graphics.getHeight() 2000.0f hardcoded to make things fit correctly ballHappyImage.setRotation(body.getAngle() MathUtils.radiansToDegrees) ballHappyImage.setScale(scaleWidth, scaleHeight) ballHappyImage.draw(batch) The images below show the Box2D debug rendered line drawings overlayed on the libgdx sprites.
15
Handling bad network clients using socket.io Currently I'm working on a MMO game which players can join and exit game whenever they want. I have a connection manager server (CMS) written in golang using socket io library. World connects to CMS and clients connect to CMS and talk to world and world update clients with snapshots of game state. For testing I wrote a client that connects to CMS and act as a player for testing how many clients can my CMS handle. I reach around 80 clients per one core vcpu and 1 gig ram and that's acceptable for my game and resources. I released the game but in real life when there is around 5 or 6 real players and one player with bad network connection joins game it massively take effect the another players game experience. Packets don't receive to another clients or delayed heavily! I believe it's because socket io uses tcp and when a bad network client joins it should send messages many times for client received it completely. How should I overcome this? I know I should used udp for my game but it's too late and I released my game in play store and it got around 700 installs. Is there anyway I can put a time to live like attribute to messages that if client don't received them at a certain time dropped them? Any idea whould be helpful.
15
LibGDX Content appears stretched although I'm using a ScreenViewport I just fixed another issue regarding the scaling inside a ScreenViewport. And yet another problem arises If I'm understanding the wiki correctly, a ScreenViewport does not scale or stretch the content in any way. In my case it somehow does When the game is started, it looks like this And after resizing the window (e.g. making it wider) it looks like this (obviously stretched...) (The code is mostly still the same as in the linked question). Since I couldn't find a example of using a ScreenViewport with unitScale yet, I have no idea how to make this work... Thanks in advance )
15
How do I save my game with highscores and player positioning in LibGDX? So I have a game that needs to save high scores for the number of waves, what guns the player has, positioning of the player and the zombies, and so on. I saw something about SharedPreferences but have no clue how to use them. Can someone point me to the right direction or willing to tell me how to use them correctly?
15
share assets beetween platforms What is the good way to share assets between platforms (android, desktop, etc) ? by default there is an assets folder in each platform folder.
15
Subdivided Icosahedron Hex Pent grid efficient rendering? How to performantly display a hex pent grid on a subdivided icosahedron? I have a subdivided icosahedron planet used as the "board" for a strategy game. It usually has anywhere between a few thousand and a hundred thousand tiles depending on the size the user inputs to the map generator. Basically, I cannot brute force this and do a simple bounds and depth check, because of the sheer numbers of tiles. I am storing the grid in a 2D array for simplicity. I understand that, on a 2D map, you simply do something like the following to draw a hex map for(int x cameraX x lt viewportWidth x ) for(int y cameraY y lt viewportHeight y ) if(x 2 0) For the 2D array to work properly we have to offset every other row by 1 world coordinate (assuming each tile is 1 1 world coordinates) grid x y .render(x tile width, y) else grid x y .render(x, y) And that to draw a wrap around world you would check the absolute distance from the camera's position. Eg This sets up the variable that tells the game what hex tiles to draw. if(camera.x viewportWidth lt 0) camera rX camera.x viewportWidth cameraX grid.length camera rX We will add this to the cameraX value because the result should be a negative value if the prerequisite if statement is met. The "cameraX" variable is used for viewing calculations, while the "camera.x" variable is used for camera positioning. Err... I think this makes sense.
15
libgdx images go out of proportion on some devices I'm trying to develop a simple game using libgdx. The game works perfectly on emulator ( Nexus 5x API 26 x86 ). But when I generated its apk and tested on my phone(Samsung J7), the images somehow seem to go out of proportion. I dont know if the problem is libgdx specific or something else is causing the problem. I suspect that the issue is about the different screen sizes or resolution. This is how I want it to be. This is how it appears. The images appear to be enlarged. The app seems to work as expected on larger mobile screens but the images do not scale well to smaller screens. Does libGdx or the android not automatically resize images according to the hardware being run on ? Any help would be highly appreciated. Edit boy new Texture("boyfinal.png") batch.draw(boy, Gdx.graphics.getWidth() 4 boy.getWidth() 2, boyY )
15
LibGdx ImageButton in table not clicking i'm having a problem adding ImageButtons to a Table in libGDX. The buttons seem to work fine when i add them directly to the stage, i can click on them, and they change textures and do whatever they are suppossed to. However, when i add them to a table, and then add the table to the stage, i can't click on them for some reason. This is how i'm creating a button (aButton is an ImageButton which i declared preivously) public void configAButton(Texture pressedTexture,Texture notPressedTexture) Skin skin new Skin() skin.add("button down", pressedTexture) skin.add("button up", notPressedTexture) ImageButton.ImageButtonStyle buttonStyle new ImageButton.ImageButtonStyle() buttonStyle.imageUp skin.getDrawable("button up") buttonStyle.imageDown skin.getDrawable("button down") aButton new ImageButton(buttonStyle) i use that method in "show()", and once i've done that i create my table like userInterfaceTable new Table() userInterfaceTable.setWidth(stage.getWidth()) userInterfaceTable.align(Align.bottomRight) i just add the button to the table userInterfaceTable.add(aButton).size(60,60).padRight(30) And add the table to the stage stage.addActor(userInterfaceTable) what am i missing? thanks in advance, i'm quite new to this.
15
LibGDX Its there any way to calculate the speed of a repeated scrolling background? I'm trying to calculate the scrolling speed of an background, I'm doing something like this on the background class private Texture texture new Texture(Gdx.files.internal("backgound.png")) private Sprite sprite private float scrollTimer 0.0f private static float scrollFactor 0.2f public Background() texture.setWrap(TextureWrap.Repeat, TextureWrap.Repeat) int width texture.getWidth() int height texture.getHeight() sprite new Sprite(texture, 0, 0, width, height) sprite.setSize(1280, 320) Override public void act(float delta) updateScrollFactor() scrollTimer delta scrollFactor if (scrollTimer gt 1.0f) scrollTimer 0.0f sprite.setU(scrollTimer) sprite.setU2(scrollTimer 2) Override public void draw(Batch batch, float alpha) sprite.draw(batch, alpha) private void updateScrollFactor() Increase scroll factor when the game score being higher. public static float getScrollFactor() return scrollFactor And in another class I'm trying to calculate the speed of this background above because I need the same speed to apply in the entity of mentioned class, that is described below private Texture texture private Sprite sprite public Item(String textureName) texture new Texture(Gdx.files.internal(textureName)) int width texture.getWidth() int height texture.getHeight() sprite new Sprite(texture, 0, 0, width, height) sprite.setSize(30f, 50f) Sets initial position, the entity will be scrolled from the screen width to zero sprite.setPosition(Gdx.app.getWidth() 10, 10) Override public void act(float delta) scrollTimer delta Background.getScrollFactor() if (scrollTimer gt 1.0f) scrollTimer 0.0f float x sprite.getX() if (x sprite.getWidth() gt 0) sprite.setX(x Gdx.graphics.getWidth() scrollTimer) else sets to initial position when the entity vanish thru the window left side. sprite.setX(Gdx.graphics.getWidth() 10) Override public void draw(Batch batch, float alpha) sprite.draw(batch, alpha) The case is the entity don't run sync with background but i need this separated from the background because it is a clickable entity. Thoughts?
15
Infinite Jumper Snow Effect I wish to achieve a snowing effect on my game. The game is made in LibGDX and im using ParticleEmitter. I created a snow effect in ParticleEditor which consists in a line which spawns snow flakes. The problem is First, and the most important, since the game movement is vertical (its a jumper), if i just place the line above the screen, the jumping makes it look unnatural since when im jumping up, and the camera follows me, the particle emitter also has to move up, and the snow flakes are spawned with a bigger vertical distance And when Im going down from the jump, a section of closer snowflakes is spawned due to that occurence. That makes the snow visually inconsistent. Second, i wanted the snow to show up filling the screen from the start, instead of it starting to follow when the emitter is started. To try to fix the first problem, i made the snow screen static, but it looks horrible, i really want the feeling that the snow is falling and my character is going up against it. Any ideas how to achieve such an effect?
15
Sprites on scrolling tmx map (LibGDX) I have .tmx map loaded, and a camera to see it. The map is bigger than the camera viewport, so I need to move that viewport scrolling the camera. Now I want to draw a sprite on the map. To do that, at the beginning I used the batch.draw() method, trying to calculate the position relative to the camera, but it didn't worked. After that I found that I could add this line batch.setProjectionMatrix(camera.combined) using an Sprite class to draw my object. Howevert, it won't draw on screen I don't know why. Here's my code MOVING CAMERA private void controlCamera() if (Gdx.input.isKeyPressed(Keys.RIGHT) amp amp camera.position.x lt mapPixelWidth camera.viewportWidth 2) camera.position.x mapSpeed else if (Gdx.input.isKeyPressed(Keys.LEFT) amp amp camera.position.x gt camera.viewportWidth 2) camera.position.x mapSpeed else if (Gdx.input.isKeyPressed(Keys.UP) amp amp camera.position.y lt mapPixelHeight camera.viewportHeight) camera.position.y mapSpeed else if (Gdx.input.isKeyPressed(Keys.DOWN) amp amp camera.position.y gt camera.viewportHeight 2) camera.position.y mapSpeed Note that I'm moving the camera between viewport 2 and viewport 2 map size, since the left down corner is situated at (viewportWidth 2, viewportHeight 2). That's the default position where my .tmx map is drawn. SPRITE RENDER METHOD public void render(SpriteBatch batch, float stateTime) currentFrame anim.getKeyFrame(stateTime, true) sprite.setPosition(getDrawCoords().x, getDrawCoords().y) sprite.setSize(currentFrame.getTexture().getWidth() 2, currentFrame.getTexture().getHeight()) sprite.setRegion(currentFrame) sprite.draw(batch) GETDRAWCOORDS METHOD public Vector2 getDrawCoords() int x (int) (map.camera.viewportWidth 2 map.tilePixelWidth xMap) int y (int) (map.camera.viewportHeight 2 map.tilePixelHeight yMap) return new Vector2(x,y) I really don't know if I wrote the sprite.setPosition correctly. I tried with lots of things but it never get drawn. MAIN CLASS RENDER METHOD public void render() Gdx.gl.glClearColor(1, 1, 1, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) map.update() Include camera mov stateTime Gdx.graphics.getDeltaTime() map.render() draw the map. Include camera.update() batch.setProjectionMatrix(camera.combined) batch.begin() units.get(0).render(batch, stateTime) render my unit batch.end() Using a batch.draw() with the texture draw well the sprite in the initial position, but when I try to move the camera it goes crazy. I tried to write the vector position in terms of the other vector, but it doesn't work, and I'm pretty sure of my vector calculus. I'm trying with the sprite and using the projection matrix because I read it give a position relative to camera, but now I can't get my sprite drawn. Any help is appreciated. Thank you!
15
Timer.schedule(task, 0, 100) never fires I added some code using java.util.Timer to execute my spawnMonster function every 100ms. It worked, until I tried instantiating images in it since it doesn't run on the libGDX core thread, there's no OpenGL context, so it can't do stuff with images. I figured using the libGDX Timer class, which the javadocs say runs on the core thread, would solve this problem but unfortunately, the timer code just doesn't execute. I tried new Timer().scheduleTask(task, 0, 100) new Timer().scheduleTask(task, 0, 100, 99999) Timer.schedule(task, 0, 100) Timer.schedule(task, 0, 999999) Timer.start() t new Timer() t.scheduleTask(...) t.start() task appears to execute once, and only once it never executes again. (It prints a date time diff from a target time, so I can tell it's not running.)
15
Using libraries in libgdx This is the first time I'm using libgdx and I've got one problem. I am confused by the web of dependencies and the number of projects and I'm not sure how and mostly where to add a third party library I want to use. It should work both for desktop and android. How is this done?
15
Curiosity on any Smartphones that Run on Android 2.3.3 with Different Screen Reoslution I have a question regarding about any smartphones that run only in Android 2.3.3. Is the size of screen or the screen resolution is always HVGA or does it have capable of running this OS (Android 2.3.3) on big screen size (4" to 5") at about 720x1280? I'm thinking of the game's compatibility depending on the version of the Android OS and the screen resolution, which affects the change of coordinates especially for assigning touch buttons and drag n drop at exact location, before I'm gonna decide to make one. My program works on the Android 4 ICS and Jellybean, however, will that work on Android 2.3.3 in spite of precise touch coordinate or just dependent on the screen resolution (regardless how large it is) as the X and Y coordinate? And take note, I'm using Eclipse IDE for Java developers.
15
What is the easiest way to make an online high scores table? I made an 2d Android game with using Libgdx library. This game like Flappy Bird. And every user have a highscore. I want to store this highscores respectively to an online database and return the rank of the user in the world ranking. How to do this? In backend ,which architecture should I use? Is there a tutorial for this?
15
How to implement in app Billing in libgdx? I'm trying to implement in app Billing in libgdx game. Does someone have a working example? There is some explanation on developer.android but it's not helpful for libgdx.
15
Smooth camera movement between followed objects I have 2d game where my camera follows the player. Simplified, it copies the player position as its own. Now I have some other object in the game, that I want to camera to follow. This is easy enough by not setting the camera's position with the player's, but with the position of the other object. The problem is that this camera movement is instant. I'd like to have a more smooth transition (e.g. panning over the level to the given object). How can I achieve this?
15
Is using Game in libGDX for more than just switching screens a bad practice? I'm the process of refactoring the prototype of my game to use multiple screens using the Game Screens model. I found some information (I think in more than one place) that the Game class should be used only to switch screens. I've checked some libGDX demos and they indeed follow that pattern. Initially I wanted to do it the same way, but then I found more and more problems with this approach. AssetManager is the best example I think. Since there is only one instance of it and I would like to use it in more than on screen why not use the Game object to store it? Same thing with Viewport for example or Camera, if I'm happy with just one. What about single instances of my own classes, that I need throughout the whole game, why not to use Game for that? I know that there are different ways to achieve what I wrote above. I can use static methods like here or create my own class to store all the needed objects and pass its instance between screens, but since I'm already passing instance of Game, what's the point? To summarize is using Game to anything else than to switch screens a bad practice? If so, why?
15
LibGDX How to do more things asynchronously Most documentation only mentions how to load assets asynchronously, eg with code similar to private void render(float delta) if (assetManager.update()) HERE game.setScreen(new MainGameScreen(game)) else progress assetManager.getProgress() draw progress bar or whatever but what if, as part of game initialization, I have to do other things before switching to the main game screen (marked with HERE in the above code)? Sure, the user is still seeing the splash screen, but what if I wanted to do these things in background as well, and give some sign of progress (another progress bar, or whatever). I haven't found examples of similar things (or perhaps I haven't looked hard enough).
15
Nullpointer exception with Scrollpane in LIBGDX I get a strange Nullpointer exception and I don't understand why. Can someone help me ? Exception Exception in thread "LWJGL Application" java.lang.NullPointerException at com.badlogic.gdx.scenes.scene2d.ui.ScrollPane.draw(ScrollPane.java 583) at com.badlogic.gdx.scenes.scene2d.Group.drawChildren(Group.java 123) at com.badlogic.gdx.scenes.scene2d.Group.draw(Group.java 57) at com.badlogic.gdx.scenes.scene2d.ui.WidgetGroup.draw(WidgetGroup.java 163) at com.badlogic.gdx.scenes.scene2d.ui.Table.draw(Table.java 119) at com.solvapps.tests.NewStoryBook.draw(NewStoryBook.java 40) My Code ACTOR public class NewStoryBook extends Actor Table table ScrollPane pane Table tableScroller public NewStoryBook(Skin skin) int w Gdx.graphics.getWidth() int h Gdx.graphics.getHeight() table new Table() table.setPosition(400, 400) table.setSize(w 3, h 0.8f) tableScroller new Table() tableScroller.add(new Label("bla bla",skin)) pane new ScrollPane(tableScroller) table.add(pane) Override public void draw(Batch batch, float parentAlpha) super.draw(batch, parentAlpha) table.draw(batch, parentAlpha) My Code App public class StoryBoxTest4 extends ApplicationAdapter private Stage stage NewStoryBook newstoryBook public void create() stage new Stage(new ScreenViewport()) Skin skin new Skin(Gdx.files.internal(SkinManager.getSkin())) newstoryBook new NewStoryBook(skin) stage.addActor(newstoryBook) Gdx.input.setInputProcessor(stage)
15
libgdx 2nd var of myClass()'s values saving to overriding 1st var of myClass() I'm using libgdx with Eclipse. PROBLEM In the class inputHandler I have a list of buttons, menuButtons, composed of 2 buttons playButton and retryButton. They both belong to the class simpleButton public static simpleButton playButton, retryButton I declared them as retryButton new simpleButton(100, 100, 40, 10, retryRegion, retryRegion) playButton new simpleButton(80, 80, 20, 20, assetLoader.playButtonUp, assetLoader.playButtonDown) (see note at end of question) But when I run the game only the 2nd button runs (in the above case, playButton). So I went to the class gameRenderer and used shapeRenderer to clearly see what was going on. shapeRenderer.rect(inputHandler.retryButton.bounds.x, inputHandler.retryButton.bounds.y, inputHandler.retryButton.bounds.width, inputHandler.retryButton.bounds.height) shapeRenderer.rect(inputHandler.playButton.bounds.x, inputHandler.playButton.bounds.y, inputHandler.playButton.bounds.width, inputHandler.playButton.bounds.height) Although only the 2nd button was displaying, the 2nd button now adopted the code for both the buttons. i.e. the 2nd button was now both the play and retry (replay) buttons and worked perfectly. note from before These aren't their actual sizes (the actual sizes are equal to the sizes of the texture regions of their art graphics) but for the sake of simplicity and legibility I changed them to simpler values. Pictures playButton on bottom (playButton working) retryButton on bottom (retryButton working) The simpleButton class public class simpleButton private float x, y, width, height private TextureRegion buttonUp private TextureRegion buttonDown public static Rectangle bounds public static boolean isPressed public simpleButton(float x, float y, float width, float height, TextureRegion buttonUp, TextureRegion buttonDown) this.x x this.y y this.width width this.height height this.buttonUp buttonUp this.buttonDown buttonDown bounds new Rectangle(x, y, width, height)
15
libgdx Player movment dungeon crawler The player go's throe walls and stops when theres no wall. Code package input import com.badlogic.gdx.Gdx import com.badlogic.gdx.Input.Keys import com.badlogic.gdx.math.GridPoint2 import com.badlogic.gdx.math.Vector2 import dungeon.Dungeon import player.PlayerCharacter import player.Player state public class PlayerInputProcessor private PlayerCharacter player private Dungeon dungeon private final int NORTH 0, SOUTH 1, WEST 2, EAST 3 public PlayerInputProcessor(PlayerCharacter player, Dungeon dungeon) this.player player this.dungeon dungeon public void HandleInput() Vector2 pos player.getVectorPos() if(Gdx.input.isKeyPressed(Keys.UP)) if(canmovethere(new GridPoint2( (int) player.getVectorPosX() player.getWidth(), (int) (player.getVectorPosY() 3) player.getHight()), NORTH)) player.setVectorPosY(player.getVectorPosY() 3) if(Gdx.input.isKeyPressed(Keys.DOWN)) if(canmovethere(new GridPoint2( (int) player.getVectorPosX() player.getWidth(), (int) (player.getVectorPosY() 3) player.getHight()), SOUTH)) player.setVectorPosY(player.getVectorPosY() 3) player.setState(Player state.WALKING FORWORD) if(Gdx.input.isKeyPressed(Keys.RIGHT)) if(canmovethere(new GridPoint2( (int) (player.getVectorPosX() 3) player.getWidth(), (int) player.getVectorPosY() player.getHight()), EAST)) player.setVectorPosX(player.getVectorPosX() 3) if(Gdx.input.isKeyPressed(Keys.LEFT)) if(canmovethere(new GridPoint2( (int) (player.getVectorPosX() 3) player.getWidth(), (int) player.getVectorPosY() player.getHight()), WEST)) player.setVectorPosX(player.getVectorPosX() 3) if(Gdx.input.isKeyJustPressed(Keys.E)) if(player.hasSword()) player.sword false else player.sword true player.setGridPos(new GridPoint2((int) player.getVectorPosX() player.getWidth(),(int) player.getVectorPosY() player.getHight())) private Boolean canmovethere(GridPoint2 newpos, int die) GridPoint2 nextpos new GridPoint2() GridPoint2 nextpos2 new GridPoint2() if(die NORTH) nextpos.x newpos.x nextpos.y newpos.y 1 nextpos2.x newpos.x nextpos2.y newpos.y 1 if(dungeon.getTile(nextpos).isPassable()) return true if(die SOUTH) nextpos.x newpos.x nextpos.y newpos.y nextpos2.x newpos.x 1 nextpos2.y newpos.y if(dungeon.getTile(nextpos).isPassable()) return true if(die EAST) nextpos.x newpos.x 1 nextpos.y newpos.y nextpos2.x newpos.x nextpos2.y newpos.y 1 if(dungeon.getTile(nextpos).isPassable() amp amp dungeon.getTile(nextpos2).isPassable()) return true if(die WEST) nextpos.x newpos.x nextpos.y newpos.y nextpos2.x newpos.x nextpos2.y newpos.y 1 if(dungeon.getTile(nextpos).isPassable()) return true player.setState(Player state.STANDING) return false
15
How can my entities avoid walking on certain tiles? In my tile map, created with 'Tiled', I placed some tiles that need to be avoided by my mobiles. Tiles like water or obstacles. The entities "wander" in the map, choosing random directions, and their position are in world coordinates (float), not grid or tile positions (int). To create a more natural effect, the random directions are similar in a period of time, so no abrupt change of direction occurs. Is there a way to make entities avoid some tile types, or 'Tiled' tile properties, without losing the "wander" behaviour? I mean, choose random directions that do not reach these type of tiles?
15
set sprite to current animation texture In my game I have some box2d bodies where I add sprites using the following code in my render() method. for (Body body worldBodies) if (body.getUserData() instanceof Sprite) Sprite sprite (Sprite) body.getUserData() Vector2 position body.getPosition() sprite.setPosition(position.x sprite.getWidth() 2 , position.y sprite.getHeight() 2) sprite.setRotation(body.getAngle() MathUtils.radiansToDegrees) sprite.draw(batch) One of the bodies has to be animated. birdAnimation new Animation(1, birdAtlas.getRegions()) birdAnimation.setPlayMode(Animation.PlayMode.LOOP PINGPONG) This is the animation and now I tried to set the body's sprite obstacle6 to the current textureRegion from the Animation unsing this code obstacle6.setRegion(birdAnimation.getKeyFrame(delta)) Somehow it just shows the first texture of the atlas. How can I get it to change? Or is there an other way to animate a box2d body? If you need any other information just comment.
15
Clearing a libGDX pixmap Is there a way to clear a libGDX Pixmap? Or is the only way to dispose it and create a brand new Pixmap?
15
set sprite to current animation texture In my game I have some box2d bodies where I add sprites using the following code in my render() method. for (Body body worldBodies) if (body.getUserData() instanceof Sprite) Sprite sprite (Sprite) body.getUserData() Vector2 position body.getPosition() sprite.setPosition(position.x sprite.getWidth() 2 , position.y sprite.getHeight() 2) sprite.setRotation(body.getAngle() MathUtils.radiansToDegrees) sprite.draw(batch) One of the bodies has to be animated. birdAnimation new Animation(1, birdAtlas.getRegions()) birdAnimation.setPlayMode(Animation.PlayMode.LOOP PINGPONG) This is the animation and now I tried to set the body's sprite obstacle6 to the current textureRegion from the Animation unsing this code obstacle6.setRegion(birdAnimation.getKeyFrame(delta)) Somehow it just shows the first texture of the atlas. How can I get it to change? Or is there an other way to animate a box2d body? If you need any other information just comment.
15
LibGDX, Box2D , Destroy body into parts I am developing a game using libGDX game engine and box2d physics engine. There are asteroids in my game, I want to destroy their bodies randomly and fill with texture. How can I do it?
15
How do I manually make a .pack file like TexturePacker (without using TexturePacker)? I am using libGDX and apparently the only way I see for creating a UI is with texture packs. I would say that since a texture pack is nothing more than JSON or XML file and a large png I could manually code a texture pack. How?
15
libgdx intersection problem between rectangle and circle My collision detection in libgdx is somehow buggy. player.png is 20 80px and ball.png 25 25px. Code Override public void create() ... batch new SpriteBatch() playerTex new Texture(Gdx.files.internal("data player.png")) ballTex new Texture(Gdx.files.internal("data ball.png")) player new Rectangle() player.width 20 player.height 80 player.x Gdx.graphics.getWidth() player.width 10 player.y 300 ball new Circle() ball.x Gdx.graphics.getWidth() 2 ball.y Gdx.graphics.getHeight() 2 ball.radius ballTex.getWidth() 2 Override public void render() Gdx.gl.glClearColor(1, 1, 1, 1) Gdx.gl.glClear(GL10.GL COLOR BUFFER BIT) camera.update() draw player, ball batch.setProjectionMatrix(camera.combined) batch.begin() batch.draw(ballTex, ball.x, ball.y) batch.draw(playerTex, player.x, player.y) batch.end() update player position if(Gdx.input.isKeyPressed(Keys.DOWN)) player.y 250 Gdx.graphics.getDeltaTime() if(Gdx.input.isKeyPressed(Keys.UP)) player.y 250 Gdx.graphics.getDeltaTime() if(Gdx.input.isKeyPressed(Keys.LEFT)) player.x 250 Gdx.graphics.getDeltaTime() if(Gdx.input.isKeyPressed(Keys.RIGHT)) player.x 250 Gdx.graphics.getDeltaTime() don't let the player leave the field if(player.y lt 0) player.y 0 if(player.y gt 600 80) player.y 600 80 check collision if (Intersector.overlaps(ball, player)) Gdx.app.log("overlaps", "yes")
15
Libgdx fbx converter doesn't write meshes to g3dj file LibGDX FBX converter doesn't write meshes nor materials to g3dj file. This happens with blender 2.8 when exporting model to FBX then converting it to g3dj. meshes will result in an empty block. 2.8 blender settings and when converting... g3dj file.. "version" 0, 1 , "id" "", "meshes" , "materials" , "nodes" "id" "Cube", "rotation" 0.707107, 0.000000, 0.000000, 0.707107 , "scale" 10.000000, 10.000000, 10.000000 , "animations" I tried to convert a fbx written with blender 2.76 with these settings... and meshes and materials are written in g3dj file successfully. I'm thinking this has to do with FBX version, but it seems you can't change FBX version in blender 2.8
15
Libgdx scrolling background for preview screen Good day, I have been coding for quite a while now and I'm at a certain point where I am having difficulties on solving something. I've been creating a preview screen which contains the following reads .txt file and stores them in an array which will be displayed on the screen. the text will have an animation which will be moving upwards like a Star Wars type of intro. the background of the screen will also move upwards. The problems that I have encountered are the following my text did not fit on the screen, but I did try to change the font and the font size and also did change the spacing in the .txt file. the text always starts in the middle of the screen which it should start at the bottom of the screen. the background is buggy, tried to debug it but still can find a solution for a parallaxbackground(scrolling background) and here is the code. public class PreviewScreen implements Screen private static DugManMainClass game private SpriteBatch batch private OrthographicCamera camera private Texture tx1 Assets.bgmenu private BitmapFont font Assets.menufont2 private final static List lt String gt lines new ArrayList lt String gt () private static int time 0 private float temp 0 private Sprite s public PreviewScreen(DugManMainClass game) this.game game reads .txt file and stores them in an array try BufferedReader br new BufferedReader(new InputStreamReader(Gdx.files.internal("previewtext.txt").read())) String line "" while ((line br.readLine()) ! null) lines.add(line) br.close() catch(Exception e) e.printStackTrace() Override public void render(float delta) float w s.getHeight() Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) temp is a timer which will do the animation effect for the text and background temp Gdx.graphics.getDeltaTime() while(temp gt 1.0f 60.0f) PreviewScreen.tick() temp 1.0f 60.0f here is my problem for the background s.setU(temp 1f) s.setU2(temp 1f) batch.setProjectionMatrix(camera.combined) batch.begin() s.draw(batch) i commented this out because i waited to draw my sprite which is the background text(parallaxbackground) batch.draw(s, 0, (temp 10 w)) batch.draw(s, 0, (temp 10 w) w) int yo time 4 this is where the the text problem is for (int y 0 y lt 420 12 y ) int yl yo 12 420 12 y if (yl gt 0 amp amp yl lt lines.size()) font.draw(batch,lines.get(yl), (800 30 12) 2, y 12 yo 12) batch.end() Override public void resize(int width, int height) Override public void show() batch new SpriteBatch() float w 800 float h 420 camera new OrthographicCamera() camera.setToOrtho(false, w, h) tx1.setWrap(TextureWrap.Repeat, TextureWrap.Repeat) s new Sprite(tx1) s.setPosition(0, 0) Assets.bgsound3.play(1f) Override public void dispose() Assets.dispose() public static void tick() time if (Gdx.input.isKeyPressed(Keys.ENTER) Gdx.input.isTouched()) game.setScreen(new MainMenuScreen(game)) Assets.bgsound3.stop() if (time 4 gt lines.size() 10 250) game.setScreen(new MainMenuScreen(game)) Assets.bgsound3.stop()
15
LibGDX Overlay Game with Stage I have been working on a 2d game that is similar to billiards pool. I've got the basic game down and now I'm working on some visual effects. One of the things I would like to do is have have numbers pop up on the screen where a scoring event occurs and then have that number "swoosh up" to the main score at the top of the screen. To accomplish this I have been trying to overlay a Stage onto my main game area so that I can add score text and then let the LibGDX Scene2d take over. I am adding the text as an actor to the stage and then assigning some actions to it to achieve the desired effect. The problem I'm having is that when I add the object I need to convert from world to stage coordinates. This is because I want to place the score popup where two balls touch, which is in world coordinates. I have tried to use the "project" method of the stage's viewport (it is a FitViewport) but the coordinates never translate correctly. Now that I've explained what I'm trying to do, I was hoping that someone would know how I could pull this off. I'm sure it isn't difficult and that I'm missing some small detail. Here is the relevant code This is the class that will be used to overlay a stage onto the main game screen. import com.badlogic.gdx.Gdx import com.badlogic.gdx.graphics.Camera import com.badlogic.gdx.math.Interpolation import com.badlogic.gdx.math.Vector2 import com.badlogic.gdx.scenes.scene2d.Stage import com.badlogic.gdx.scenes.scene2d.actions.Actions import com.badlogic.gdx.scenes.scene2d.ui.Label import com.badlogic.gdx.scenes.scene2d.ui.Skin import com.badlogic.gdx.utils.viewport.Viewport public class UIOverlay private Skin skin new Skin( Gdx.files.internal("skins gamePlaySkin.json")) private Stage stage new Stage() public void init (Viewport viewport) stage.setViewport(viewport) stage.getViewport().update(GameWorld.WIDTH, GameWorld.HEIGHT, true) public void render () stage.act() stage.draw() public Stage getStage () return this.stage public void addScorePopup (int score, Vector2 worldPos) Viewport vp stage.getViewport() Vector2 screenPos new Vector2(worldPos.x, worldPos.y) vp.project(screenPos) Some sample vectors after projection worldPos.x 0.88585174, worldPos.y 1.6051532 screenPos.x 0.885849, screenPos.y 1022.39484 Another Set worldPos.x 0.63776636, worldPos.y 0.8991218 screenPos.x 0.63777924, screenPos.y 1023.1009 Label popLabel new Label(String.valueOf(score), skin, "popupScore") stage.addActor(popLabel) popLabel.setPosition(screenPos.x, screenPos.y) float time 0.5f popLabel.addAction(Actions.delay(1000, Actions.sequence(Actions.moveTo(0.0f, 0.0f, time, Interpolation.sineIn), Actions.alpha(0, 0.1f)))) This is where I set up the main game viewport public static void init() GameWorld.WIDTH and HEIGHT are 1280 and 1024 m camera new OrthographicCamera() m camera.setToOrtho(true, GameWorld.WIDTH, GameWorld.HEIGHT) m viewport new FitViewport(GameWorld.WIDTH, GameWorld.HEIGHT, m camera) When creating the UIOverlay I pass the game's m viewport into UIOverlay.init(). I have also tried creating a new FitViewport in UIOverlay with the same dimensions as the game's viewport, but have the same behavior.
15
How to split a screen in half using LibGDX without scaling? I am currently working on a racing game with libGDX and I need to split the screen in half for a two players mode. (Player 1 in first half and Player 2 in second half). I already have Camera1 that will follow Player 1's car, and Camera2 that will follow Player 2's car. Basically, I want the first half to show Player 1's car and the second half to show Player 2's car. I have been searching for a while online for a way to split screens with LibGDX and found how to split the screen in two with this code Left Half Gdx.gl.glViewport( 0,0,Gdx.graphics.getWidth() 2,Gdx.graphics.getHeight() ) Right Half Gdx.gl.glViewport(Gdx.graphics.getWidth() 2,0,Gdx.graphics.getWidth() 2,Gdx.graphics.getHeight() ) However, it squeezes the screen into the right half, which is not what I want. Is there a way to split the screen without squeezing it?
15
How to extract a point in LibGdx from Tiled map? Tiled has a feature to insert a point in to an Object layer. But there doesn't seem to be a "PointMapObject" implementation in Libgdx on the doc. currently i am being forced to use a PolylineMap Object with two vertices but all i want is only the x or y of the first vertex.
15
How to detect collision only in non transparent texture? I am developing a game using libGDX. I am trying to detect the collision between bee and tube. I am using the following code to detect the collision. if(player.getBounds().overlaps(boundsBot)) player is a bee and boundsBot is Rectangle of tube. Since there is some transparency in bee image, this returns true even if it doesn't seem to collide. I understand the reason why this is returning true. I read this solutions. I understood the theoretical concept to the solve the problem but I couldn't achieve it using libGDX. Here is what I tried, if(Intersector.intersectRectangles(player.getBounds(), boundsBot, rectangle)) Gets the intersected rectangle System.out.println("Rectangle Bottom " rectangle) Converting texture to pixmap Texture texture player.getTexture().getTexture() if (!texture.getTextureData().isPrepared()) texture.getTextureData().prepare() Pixmap pixmap texture.getTextureData().consumePixmap() Trying to find transparency..... System.out.println("Format " pixmap.getGLFormat()) How can I solve this issue? Thank You!
15
Different Sprite sizes for animation I have a character which has a size of 32x64 when walking or standing. Using the libgdx animation class I can easily animate him with a texture atlas. When I want to make him attack however, the Sprite appears squished because the frames for the attack animation are 64x64 to accommodate the sword. My question is as the artist and programmer, would it make more sense to have each Sprite frame for every animation be 64x64? Or in code, resize the Sprite origin and bounds before the attack animation and set them back to 32x64 when the attack is done?
15
Different Sprite sizes for animation I have a character which has a size of 32x64 when walking or standing. Using the libgdx animation class I can easily animate him with a texture atlas. When I want to make him attack however, the Sprite appears squished because the frames for the attack animation are 64x64 to accommodate the sword. My question is as the artist and programmer, would it make more sense to have each Sprite frame for every animation be 64x64? Or in code, resize the Sprite origin and bounds before the attack animation and set them back to 32x64 when the attack is done?
15
Libgdx OrthogonalTiledMapRenderer not rendering map properly I'm using a little hack to change the coordinate system to the one i'm accustomed to (left and up is negative and right and down is positive) but this causes the tiled map renderer to render the map incorrectly, as shown below Whereas it looks like this in the Tiled map editor This is the "hack" I'm using to change the coordinate system float w Gdx.graphics.getWidth() float h Gdx.graphics.getHeight() Camera new OrthographicCamera(w, h) Camera.setToOrtho(true, w, h) My render code renderer.setView(Camera) renderer.render() So is there a workaround to this? Or perhaps a better way to change the coordinate system that doesn't screw up everything? Edit The rendered tiles are correct now but the map and everything rendering is still flipped along the y axis. If I was drawing sprite and stuff, I could always draw them flipped but I don't know how to do it with the tiled map renderer.
15
Scene2d scrollbar not showing even though it exists in uiskin.json atlas Using uiskin.json, uiskin.png, uiskin.atlas, default.fnt from libgdx tests I'm trying to make a console window, however the scroll bar is not shown. uiskin atlas contains a two relevat fragments default scroll rotate false xy 78, 29 size 20, 20 split 2, 2, 2, 2 orig 20, 20 offset 0, 0 index 1 default round large rotate false xy 57, 29 size 20, 20 split 5, 5, 5, 4 orig 20, 20 offset 0, 0 index 1 Which are referenced in uiskin.json com.badlogic.gdx.scenes.scene2d.ui.ScrollPane ScrollPaneStyle default vScroll default scroll, hScrollKnob default round large, background default rect, hScroll default scroll, vScrollKnob default round large And this is my console window Skin is above mentioned uiskin.json, png, atlas Window window new Window("CONSOLE", skin) window.padTop(20f) window.setWidth(500f) window.setHeight(250f) window.setMovable(true) window.setModal(true) window.setResizable(true) window.defaults().expand().fill() Label consoleLog new Label("TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT" "TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT" "TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT" "TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT" "TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT" "TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT" "TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT" "TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT" "TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT" "TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT", skin) consoleLog.setWrap(true) ScrollPane scrollPane new ScrollPane(consoleLog) window.add(scrollPane) window.row() window.add(new TextField("", skin)) When I run this, I get a window with a label and a textfield, and I can scroll the label using mouse scroll or by dragging the text, but the scrollbar is not visible. what am I doing wrong?
15
In Scene2D, does Actor.hasActions() no longer exist? Eclipse does not allow me to do while (actor.hasActions()) saying it's undefined for type actor, but the libgdx API still has it as one of an Actor object functions.
15
questions about position and size I am new to game development and I wanted to ask a question. I am reading the simple game example from here. 1) I want to ask why we define bucket.x 800 2 48 2 ? How is that? Why not just set bucket.x 400 ( at the middle position). ... camera.setToOrtho(false, 800, 480) ... bucket new Rectangle() bucket.x 800 2 48 2 bucket.y 20 bucket.width 48 bucket.height 48 2) The bucket width and height are seet 1 10 of our screen size.Ok. But what about the real dimensions of bucket object?I mean , the bucket what size must be?32x32 pix?48X48 pix?How we handle that? 3) Also, I am a bit confused about x and y dimensions. x refers to width and y to height as we see the cell phone in portrait mode? So , if we are in landscape mode , y is "x"? Thanks!
15
How would you create a single object effect with ecs like a shadow moving straight and a bouncing ball? I have a bullet that has projectile motion, this bullet is also an effect. Also the bullet has a shadow, that fade on specific time relatively to bullet. So I'm thinking of using the libgdx particle system (I am using an Entity Component based System approach) so I created a particle component, or would you rather recommend to create another component for that specific effect? like a projectile component and linear component or a motion component in general. Creating shadow, bullet, and other single object effect entity. Notice that I doesn't use any Box2d Physics yet. Entity shadow engine.createEntity() ... add texture, transform, movement or with gravity components engine.addEntity(shadow) To move the shadow entity Shadow Vector2 linear ... movement.velocity.set(linear) To move the bullet entity Bullet gravity.vertical 9.8f set earth gravity Vector2 projectile ... movement.velocity.set(projectile) Also I need to calculate the time to reach its destination to add in lifespan To create and move a ball entity Entity ball ... assume that the world has zero horizontal and 9.8 vertical Vector2 gravity set the physics body and set restitution to have bounce physics.body createCircleBody(...) add(texture) add(transform) add(physics) Every single object has lifespan so I added some lifespan component LifespanComponent lifespan ... lifespan.duration 0.5f let say half a second Then the lifespan system will handle if the time reached the duration, then remove entity. The problem is, Because Particle System has many moving objects, I don't know if I could use libgdx Particle System to create a single moving object that has a lifespan, like shadow, ball, bullet.
15
When input listener set in resize(), input doubles I created a button and assigned an input listener in the resize() method of the screen. For simplicity's sake, whenever I press the button, 1000 adds to a total amount. The weird part is, it adds 2000 when I press the button. Then I moved the button's input listener addition to the constructor now it works perfectly adding 1000. For some odd reason, if I set the input handler in the resize method it somehow does everything it is supposed to twice. The game works when I transfer that piece of code to the constructor, but why on earth did it do the assigned thing twice? This is the code I use for attaching the input listener button.addListener(new InputListener() public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) return true public void touchUp (InputEvent event, float x, float y, int pointer, int button) count increment countLabel.setText(String.valueOf(count)) )
15
How do I delete all saved preferences in my libgdx project? I want to delete the preferences that saved my last highscore. How can I do this? Here's how I am saving preferences at the moment prefs Gdx.app.getPreferences("ZombieBird") if (!prefs.contains("highScore")) prefs.putInteger("highScore", 0) public static void setHighScore(int val) prefs.putInteger("highScore", val) prefs.flush()
15
libGDX HTML5 game sounds doesn't work on iPhone I have a libGDX HTML5 project that works well on desktop browsers, but on mobile browsers it has problems. I can have some sounds on Android browsers (not perfect) but on iPhone browsers it doesn't work at all. I don't know exactly which part of the project to put in here. There is an mp3 file to be played at menu screen, "music.mp3". I use import com.badlogic.gdx.audio.Music ... public class MyGame extends ApplicationAdapter ... private Music music ... Override public void create () ... music Gdx.audio.newMusic(Gdx.files.internal("music.mp3")) music.setLooping(true) music.setVolume(0.1f) music.play() ... I would appreciate any help.
15
box2dlights confuses ScreenUtils for screenshots in libGDX I take screenshots as usual in libGDX via ScreenUtils.getFrameBufferPixmap(), which works fine. Hoever, when I call RayHandler.updateAndRender() during rendering, then the screenshot only contains those assets rendered after this call. All other pixels in the screenshot are transparent. What is the best way to deal with this issue?
15
TiledMap blocks makes Animation invisible Got it fixed. Thanks to anyone who tried to help me. New Code mapManager.render() spriteBatchForeground.setProjectionMatrix(Main.getGraphicsManager().getAdvCamera().getCamera().combined) spriteBatchForeground.begin() worldManager.render(delta, spriteBatchForeground) animationManager.render(spriteBatchForeground) particleEffectManager.render(delta, spriteBatchForeground) spriteBatchForeground.end() I just implemented my animations but now I discovered a problem with my TiledMap. Here some Screenshots Code for 1 spriteBatchForeground.begin() mapManager.render() spriteBatchForeground.setProjectionMatrix( Main.getGraphicsManager().getAdvCamera().getCamera().combined ) worldManager.render(delta, spriteBatchForeground) animationManager.render(spriteBatchForeground) particleEffectManager.render(delta, spriteBatchForeground) spriteBatchForeground.end() Code for 2 spriteBatchForeground.begin() mapManager.render() spriteBatchForeground.setProjectionMatrix( Main.getGraphicsManager().getAdvCamera().getCamera().combined ) worldManager.render(delta, spriteBatchForeground) animationManager.render(spriteBatchForeground) particleEffectManager.render(delta, spriteBatchForeground) spriteBatchForeground.end() Issue The animation isn't drawing when I enable the drawing for the tiledmap. I have no idea why this happens...
15
libgdx automove Actor does not work I am trying to make my sprite start moving from the moment it is created and do its animation. It draws on the screen right and animates but doesn't move. It should start moving towards the direction it is facin this means right and if collision detected to stop the animation do whatever and continue the animation. Here is my code public class grt extends ApplicationAdapter Misheva mshv Override public void create () mshv new Misheva() mshv.init() Override public void render () mshv.drawIt() mshv.act(Gdx.graphics.getDeltaTime()) Override public void dispose() mshv.disposer() Misheva.java public class Misheva extends Actor int state TextureAtlas atl TextureRegion walk SpriteBatch batch Animation anim float stateTime float elapsed 0 int horizontalspeed 10 public void reset () state 0 stateTime 0 Override public void act(float delta) super.act(delta) stateTime delta switch(state) case 0 setX(getX() horizontalspeed delta) public void drawIt() Gdx.gl.glClearColor(1, 1, 1, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) batch.begin() elapsed Gdx.graphics.getDeltaTime() batch.draw(anim.getKeyFrame(elapsed,true), 0, 0) batch.end() public void init () atl new TextureAtlas(Gdx.files.internal("data tomaton.atlas")) batch new SpriteBatch() walk new TextureRegion 3 walk 0 atl.findRegion("tomato") walk 1 atl.findRegion("t walk2") walk 2 atl.findRegion("t walk1") anim new Animation(1 10f,walk) protected void disposer() batch.dispose() atl.dispose()
15
How to correctly set window size in Libgdx scene2d.ui dialog In my libGDX application I am using the scene2d.ui classes to render my game's GUI. One of the things I render via these classes is a dialog window with a background image set. I have created the uiskin.json file accordingly, and the dialog is shown correctly with the background image. There is one catch however The size of the dialog window is exactly set to fit the text elements, but not more. If not much text is shown on the dialog, then the background image is rendered much smaller than it really is. I can override or hard code the window size by overriding getPrefWidth() and getPrefHeight() in my custom Dialog class. But that does not feel right. My question What is the correct way to set a scene2d.ui dialog with a background image to be as large as that background image, regardless of how much text is being shown?
15
How do I show a minimap in a 3D world? Got a really typical use case here. I have large map made up of hexagons and at any given time only a small section of the map is visible. To provide an overview of the complete map, I want to show a small 2D representation of the map in a corner of the screen. What is the recommended approach for this in libgdx? Keep in mind the minimap must be updated when the currently visible section changes and when the map is updated. I've found SpriteBatch(info here), but the warning label on it made me think twice A SpriteBatch is a pretty heavy object so you should only ever have one in your program. I'm not sure I'm supposed to use the one SpriteBatch that I can have on the minimap, and I'm also not sure how to interpret "heavy" in this context. Another thing to possibly keep in mind is that the minimap will probably be part of a larger UI, is there any way to integrate these two?
15
LibGDX full screen display mode and camera resize I'm creating a simple 2D platformer and I have problem with my camera y position when I enter full screen mode. But first here's my code screenY Gdx.graphics.getHeight() public void updateCamera() camera.position.x (player1.getHitBox().x camera.position.x) if(screenY lt player1.getHitBox().getY() amp amp player1.getHitBox().getY() gt (screenY Gdx.graphics.getHeight())) screenChanger else if(player1.getHitBox().getY() lt (screenY Gdx.graphics.getHeight())) screenChanger screenY Gdx.graphics.getHeight() screenChanger camera.position.y (screenY screenY 2) camera.update() System.out.println(Gdx.graphics.getHeight() " " screenY) So here's my results 1) When I start the game all works fine 2) But when I enter to fullscreen here what I get 3) here how it looks when I zoom out my camera
15
How to properly calculate y position when drawing from .fnt bitmap font? I want to render text to bitmap to use it later as a decal texture. I've read through libGDX fonts drawing code and came up with this private void writeTextToPixmap(Pixmap destPixmap, Pixmap fontPixmap, BitmapFont.BitmapFontData fontData, int startX, int startY, String text) int cursor startX char chars text.toCharArray() for(int i 0 i lt chars.length i ) BitmapFont.Glyph glyph fontData.getGlyph(chars i ) destPixmap.drawPixmap(fontPixmap, glyph.srcX, glyph.srcY, glyph.width, glyph.height, cursor glyph.xoffset, startY glyph.yoffset, glyph.width, glyph.height) cursor glyph.xadvance The font was generated with Hiero using default settings. But the result does not look as expected http i.imgur.com T7Isg2R.png Usage Pixmap pixmap new Pixmap(1024, 1024, Pixmap.Format.RGBA8888) BitmapFont.BitmapFontData fontData new BitmapFont.BitmapFontData(Gdx.files.internal("data couriernew.fnt"), false) Pixmap fontPixmap new Pixmap(Gdx.files.internal("data couriernew.png")) writeTextToPixmap(pixmap, fontPixmap, fontData, 300, 400, "ga")
15
LibGDX transparent textures look weird for a brief moment during skeleton animation So I have a stage with some characters (Spine2D Skeletons). Each character has a health bar stamina bar texture above them. The textures are simple PNGs with some gradient on them and transparency too. Sometimes, when I set an animation on one of the skeletons in the stage, some of the health stamina bars textures look like they're color burned or the transparency doesn't work on them while the animation lasts. I tried setting PremultiplyAlpha to true and to false on the skeleton renderer but it didn't help. Do you have any idea why this could be? Edit Sample before and after images
15
Libgdx Particle Editor Blank UI elements How can I get Libgdx Particle Editor to run properly on my 32 bit Windows 7 machine? When I run it, the UI elements are blank like this
15
LibGDX Show a minimap I've started to develop a small roguelike game in LibGDX. I've also made a minimap class, which creates and updates the minimap as the player explores the dungeon, by using a Pixmap. The minimap class has an OrthographicCamera (currently unused), which will be used for centering the minimap on the player. The minimap is currently rendered with it's own SpriteBatch. Now I'd like to put the minimap on the upper right corner, and clip it, because it is so big, that it'd obscure the half of the screen. I'm not really sure how to do this clipping part. I assume I should use the ScissorStack class, but the LibGDX wiki is a bit uninformative for me.
15
How do I save my game with highscores and player positioning in LibGDX? So I have a game that needs to save high scores for the number of waves, what guns the player has, positioning of the player and the zombies, and so on. I saw something about SharedPreferences but have no clue how to use them. Can someone point me to the right direction or willing to tell me how to use them correctly?
15
LibGdx How to check if VSync is enabled I am just about finished my options screen, the only thing I need is some way of detecting if Vsync is enabled or not. I'm using LibGdx 1.5. I have tried to find an access to wglSwapIntervals, but haven't found one. Libgdxs API only allows a setVsync options that accepts a Boolean. If anyone could shed some light on this, it would be greatly appreciated!
15
Libgdx drawing a circle with large radius causes exception When drawing a circle using the ShapeRenderer and using a really big radius (in millions, planet sun size, given in metres) libgdx throws an exception Exception in thread "LWJGL Application" java.lang.ArrayIndexOutOfBoundsException 20003 at com.badlogic.gdx.graphics.glutils.ImmediateModeRenderer20.color(ImmediateModeRenderer20.java 116) at com.badlogic.gdx.graphics.glutils.ShapeRenderer.circle(ShapeRenderer.java 880) at com.badlogic.gdx.graphics.glutils.ShapeRenderer.circle(ShapeRenderer.java 844) at com.kacpr.solar.system.Planet.draw(Planet.java 74) at com.kacpr.solar.system.SolarSystem.render(SolarSystem.java 66) at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java 223) at com.badlogic.gdx.backends.lwjgl.LwjglApplication 1.run(LwjglApplication.java 124) This didn't happen when I used smaller values. The question I have is whether I'm doing something wrong using such high numbers for a radius and should scale this down before drawing (I use this radius for some other calculations) or is this a bug?
15
how to set volume of sound depending on the impulse a body receives in Libgdx Box2d? I am trying to set the volume of a bouncing sound of a ball depending on how hard the ball hits something. so the harder the ball hits a wall or a ground the more loud the bounce sound. I couldn't find anyway to get the impulse of a body other than the postSolve(Contact contact, ContactImpulse impulse) method inContactListner class. But i then realized that unlike the beginContact(Contact contact) method, postSolve(Contact contact, ContactImpulse impulse) gets called repeatedly until the contact ends. so it repeatedly plays the bouncing sound making it sound stalked and buggy. I cant use the beginContact(Contact contact) method because there is no way to get the impulse that the ball is receiving from this method. I tried to to use the velocity of the ball instead of impulse inside beginContact(Contact contact)but that didnt yield good results and found it very complicated as i had to consider both horizontal and vertical speeds. so my question is how can I make the sound play only once if i am using the postSolve(Contact contact, ContactImpulse impulse) method or is there any other solution to achieve what i am trying to do here?
15
testPoint not working libgdx I'm making a game like angry birds with LibGDX and box2d in which I want to drag a ball (instead of the bird) back before releasing it. I deploy with testPoint function when I touch down the screen, I check if the point is within the body of the ball or not but testPoint function never works exactly. Here's what I'm trying thanks so much public boolean touchDown(int screenX, int screenY, int pointer, int button) for(Fixture fixture bird.getBody().getFixtureList()) if(fixture.testPoint(screenX 100, (mapHeight screenY) 100)) 100 is scaled parameter draggedBird true return true return false
15
Libgdx OrthographicCamera culling problem with zooming When I set zoom on an orthographic camera to anything above 1 I get a strange black border on the bottom of the screen. I suspect that this might be some sort of culling problem. I use a viewport to control the game resolution, and no matter the size the borders are there. The camera is set on a direction ( 1, 1, 1) basicaly isometric. Also it is positioned well above to origin at (1113,1113, 1113). Far plane at 7777 near at 0.00001f. The ground plane is at 0,0,0 laying in the xz axis, with an other plane on top of it sligtly off to the left and with a 45 degrees on its axis to face the camera. Here is an image of the problem Posting code wont really help here since I only use defaults almost everywhere, but if you need it just tell.
15
Is it reasonable to use FreeType Won't it slow my game if I use FreeType lib and convert 2 fonts from .ttf instead of using preloaded BitmapFont .png? Or may be FreeType so fast, that I can use fonts both ways? All I need is to change color and size of my text. P.S. I use 3 fonts in my project
15
spriteBatch.draw is not getting overloaded I am following this tutorial from gamefromscratch.com tutorial 11. I am using libGdx framework in Android studio . public class OrthogonalTiledMapRendererWithSprites extends OrthogonalTiledMapRenderer public OrthogonalTiledMapRendererWithSprites(TiledMap map) super(map) Override public void renderObject(MapObject object) if(object instanceof TextureMapObject) TextureMapObject textureObj (TextureMapObject) object spriteBatch.draw(textureObj.getTextureRegion(), textureObj.getX(), textureObj.getY()) getting error in this line I am getting an unresolved error in the following line spriteBatch.draw(textureObj.getTextureRegion(), textureObj.getX(), textureObj.getY()) The code in render() method is public void render () Gdx.gl.glClearColor(1, 0, 0, 1) Gdx.gl.glBlendFunc(GL20.GL SRC ALPHA, GL20.GL ONE MINUS SRC ALPHA) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) camera.update() tiledMapRenderer.setView(camera) tiledMapRenderer.render() I am new in game development please help me solve this error. Thanks in advance
15
Solid outline around block I'm creating a minecraft clone (for practice), and I'm trying to implement a feature in which the block that the player is looking at has a block outline. The way I do this is just by creating a GL LINES mesh that covers the edges of the block, and then translating it to the block position. I'm using the LibGDX framework to do this the outline ends up producing a ModelInstance. It partially works, but this is what it looks like As you can see, some of the pixels are getting rendered, but some aren't. My theory is that this is because of the depth buffer because the line is intersecting with the face, some of the pixels don't get rendered. So my question is, how can I ensure that the outline gets rendered solidly?
15
LibGDX How can I draw a line at a specific angle I'm working on a 2D platformer, shooter game and I'm attempting to draw a line to serve as a guide to indicate where the player is shooting. The line should be drawn from the player's sprite to the mouse's position. I need to draw a line between the player and the mouse, at the angle from the player to the mouse, how can I do something like this? Here is a concept picture to explain what I'm talking about
15
What causes undefined geometry to be drawn? I am currently using the polygonSpriteBatch of libgdx to draw triangles, rectangles and a concave polygon as border. After adding the concave polygon for the colored borders everything seems to break and random geometry appears (sometimes even with a gradient). Some Examples Here you can see on the left everything looks good and after drawing the additional rectangle with its border and removing the other borders you can still see some weird red regions. This is even more extreme. On the left part of the concave polygon is drawn with a different color, and after it despawns (on the right) there is still part of it left and other triangles not created by me are drawn. I am quite confident that all convex polygons are defined in counter clockwise ordering. In the past I had trouble with providing the correct TextureRegion and it still doesn't feel like my current implementation is how it should be, but it worked for simple rectangles and triangles. Currently I have a (3px) (3px) Region and all polygon vertices are between (0f,0f) and (3f,3f). Because I define all triangles of the polygons myself the short array given to the PolygonRegion for a rectangle looks like this (0, 1, 2, 3, 4, 5) and the corresponding Vector2 polygon array like this ((0.0, 3.0), (0.0, 0.0), (3.0, 0.0), (0.0, 3.0), (3.0, 0.0), (3.0, 3.0)) I experienced even more artifacts when executing this on android and for some reason drawing a small rectangle for each vertice (for debugging) fixed some of the artifacts above. This is quite a complex problem but I hope somebody knows what could cause such a behaviour.