Help Understanding libgdx create animations example game I am trying to understand the example game, cuboc. GitHub is https github.com libgdx libgdx demo cuboc. I have generated my texture atlas but I do not understand the code that uses this texture atlas. Here's the code (you can see on github too here package com.badlogic.cubocy import com.badlogic.gdx.Gdx import com.badlogic.gdx.graphics.FPSLogger import com.badlogic.gdx.graphics.GL20 import com.badlogic.gdx.graphics.OrthographicCamera import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.graphics.g2d.Animation import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.graphics.g2d.SpriteCache import com.badlogic.gdx.graphics.g2d.TextureRegion import com.badlogic.gdx.graphics.glutils.ImmediateModeRenderer20 import com.badlogic.gdx.math.Vector3 public class MapRenderer ... private void createAnimations () this.tile new TextureRegion(new Texture(Gdx.files.internal("data tile.png")), 0, 0, 20, 20) Texture bobTexture new Texture(Gdx.files.internal("data bob.png")) TextureRegion split new TextureRegion(bobTexture).split(20, 20) 0 TextureRegion mirror new TextureRegion(bobTexture).split(20, 20) 0 for (TextureRegion region mirror) region.flip(true, false) spikes split 5 bobRight new Animation(0.1f, split 0 , split 1 ) bobLeft new Animation(0.1f, mirror 0 , mirror 1 ) bobJumpRight new Animation(0.1f, split 2 , split 3 ) bobJumpLeft new Animation(0.1f, mirror 2 , mirror 3 ) bobIdleRight new Animation(0.5f, split 0 , split 4 ) bobIdleLeft new Animation(0.5f, mirror 0 , mirror 4 ) bobDead new Animation(0.2f, split 0 ) split new TextureRegion(bobTexture).split(20, 20) 1 cube split 0 cubeFixed new Animation(1, split 1 , split 2 , split 3 , split 4 , split 5 ) split new TextureRegion(bobTexture).split(20, 20) 2 cubeControlled split 0 spawn new Animation(0.1f, split 4 , split 3 , split 2 , split 1 ) dying new Animation(0.1f, split 1 , split 2 , split 3 , split 4 ) dispenser split 5 split new TextureRegion(bobTexture).split(20, 20) 3 rocket new Animation(0.1f, split 0 , split 1 , split 2 , split 3 ) rocketPad split 4 split new TextureRegion(bobTexture).split(20, 20) 4 rocketExplosion new Animation(0.1f, split 0 , split 1 , split 2 , split 3 , split 4 , split 4 ) split new TextureRegion(bobTexture).split(20, 20) 5 endDoor split 2 movingSpikes split 0 laser split 1 What I do not understand is what is split used for? Like, what is going on here split new TextureRegion(bobTexture).split(20, 20) 1 And sometimes it looks like split is a method that takes two int's, 20 and 20? Why 20? Othertimes split is used as an Array like in ... rocketExplosion new Animation(0.1f, split 0 , split 1 , split 2 , split 3 , split 4 , split 4 ) ... and I just can't follow what's going on here. Thanks!


How to make an application architecture a global strategy game? I am doing a global libgdx strategy, how can I properly design the architecture? So far, I'm in some kind of chaos, because there are different events that need to be shown to the player in the form of widgets. For example, one problem is that I need to understand how the Province class will display a message that there is a hunger problem. Should it immediately inside itself display a message? send event data to the main class of the game, which processes the data and, depending on the event, display the message or take some other action? do something else entirely? I had the idea to make a separate class of events and so that all game objects create this object and pass it to the main class of the game, which handles them and decides what to do with it, and if necessary, pass it to the players. And I read about the fact that there is a class java.util.EventObject. Is it worth implementing it with the help of it, or should it be implemented like that yourself? Or maybe it should be done in a completely different way? The game is turn based. There are separate provinces and the units move from one province to the neighboring one in 1 turn. At the beginning of each turn, a series of windows appear in turn, notifying of certain events, for example, famine in a province or enemy troops attacked a province, etc. There are classes of the province, the player, various UI windows, which display information about events.


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()


LibGDX Problems with Button Listener in a Dialog I'm developing a game where the player has an inventory, and you can find chests in the map with items which you can collect, so I created a class that extends from Dialog to show both item lists, player's inventory and chest's inventory, just like this private class InventoryDialog extends Dialog public InventoryDialog(boolean isPlayerInventory, Inventory inventory) super(isPlayerInventory? "Inventory" "Chest", mySkin) final List inventoryList new List(mySkin) inventoryList.setItems(inventory.getItems()) ScrollPane pane new ScrollPane(inventoryList,mySkin) getContentTable().add(pane).size(myDimensions) button("Back") if(isPlayerInventory) button("Use").addListener(new ClickListener() Override public void clicked(InputEvent event, float x, float y) super.clicked(event, x, y) player.getInventory().useItemAt(inventoryList.getSelectedIndex()) ) else button("Get").addListener(new ClickListener() Override public void clicked(InputEvent event, float x, float y) super.clicked(event, x, y) player.getInventory().add(inventory.remove(inventoryList.getSelectedIndex())) ) So they will use or get the item only if they click that button. My problem is that the get use listener is always invoked even if the clicked button is the "Back" button, what am I doing wrong?


How to convert and handle (controlling) OOP game objects via ECS? I'm having hard time converting OOP game objects to Ashley ECS framework. I have a character, gun amp a bullet class. The character uses the gun as weapon, the gun class has a fire method that handles the creation of bullet. In the below code, is my current WeaponSystem that serves as a generic system for any weapon like Gun class. public interface Weapon void use() public class WeaponComponent implements Component Weapon weapon public class WeaponSystem extends IteratingSystem ... Constructor ... Process Entity public void use(Entity weapon) WeaponComponent weaponComponent Components.getWeapon(weapon) weaponComponent.use() ... The character system.. public class CharacterSystem extends IteratingSytem ... Constuctor ... Process Entity public void attack(Entity character) getEngine().getSystem(WeaponSystem.class).use(character) also can be use like this CharacterComponent characterComponent ... it seems that, it was redundant characterComponent.weapon.use() And the user controlled system ... public class UserControlledSystem extends IteratingSystem ... public void move(Entity character) ... Set character directions InputComponent input ... input.key arrow key, etc... getEngine().getSystem(CharacterSystem.class).move(character, direction) public void attack(Entity character) getEngine().getSystem(CharacterSystem.class).attack(character) Based on this article, they are using event dispatcher. But do I really need to use dispatcher? Is that possible to not to use dispatcher, just purely ECS? Anyways let's back to the main question(How to convert and handle (controlling) OOP game objects via ECS?). Currently, the Ashley ECS Entity has an access to engine and systems. Like in the above code example, do you think it is the proper way of handling the system?


libGDX map transition via try catch exeption I have a simple question. Some explination first, however I am using libGDX and making a Legend of Zelda type top down game and I'm having an issue with map transitions. When I made the tilemap and added the (currently crappy) collision detection to it, I noticed that the IDE threw an error when the character walks off the map (where there are no tiles to test the collision possibility against). I thought, cool, I can use that. Knowing that the program would throw an exception when the player left the screen, I caught that exception and used it to decide to which map the player was trying to transition and switch accordingly. I played a little transition from the scene2d actions and to the next map we went. BUT, I got to thinking that while catching that exception is a great thing, I probably shouldn't rely on it for map transitions. I'm betting you all will agree handle the exception just in case, but don't rely on it. SO, this means that I need to handle a transition before the user gets off the map. I tried using transition tiles from within the collision detection If the tile had the transition property, figure out where the user is attempting to transfer and then play the transition effect and on to the next map. The only problem with this system is that it doesn't look right. The user transitions just as collision is made while there is still room left in the tile to transverse. My question to you all, then, is this Is there a middle ground between the two? Is there a way to tell end of map or last tile, allow the user to transverse the tile just prior to transitioning? Or are my two ways the only ones?


LibGdx table with label children at fixed positions I'm trying to make a table containing three labels in each row. Something like this Label1 Label2 Label3 Text1 Text2 LongerText LongTextLoremIpsum LongTextLoremIpsum LongTextLoremIpsum Is there a way to fix the position of the labels so that they will be at the same position horizontally regardless of the length of the text in the label? So far I'm using a table as the root container, and then HorizontalGroup for each row.


Vertically mirroring the screen in LibGDX I'm developing a game in which the screen layout is different for right and lefty players, so i'll put a button in it to mirror the screen vertically. For displaying textures and fonts, i use a single scene2D stage with actors and labels. The stage's viewport type is FitViewport. How can i swap between the right and left layouts? Is there something already done to do it on the viewport side? Is it only a matter of switching coordinates from bottom left to bottom right? I can do that on the viewport camera, but what about all the textures? How can i change an actor's coordinate system? Thank you all


Is there an existing Quadtree implementation in libGDX? I've seen a lot of sites that recommends to use Quadtree for splitting the array by levels and nodes for a better performance for example in CollisionSystem there's a lot of collisions needs to be handle. I need to ask this question because I'm planning to create my own Quadtree class, if there it didn't exist.


Deleting Cleaning Screen Objects with all child objects in libGDX For my game, Im using libGDX Ashley (ECS) Box2D Ive got a lot of screens but for simplification MainMenuScreen and InGameScreen. In InGameScreen Im init the ECS (Ashley) and create a lot of entities. Some have PhysicsComponent. The PhysicsSystem will catch them and call Box2D to spawn some objects based on the parameters within the PhysicsComponents. So far so good. Now, when the player dyes, I run setScreen(new MainMenuScreen()) from my "Main" Class (MyGame.java). the game starts and MyGame loading at first the MainMenuScreen than the InGameScreen will get loaded (when player presses a key) than the player dyes MyGame recognized it and loading again (throu calling setScreen(...)) the MainMenuScreen When Player press key MyGame loading another round (setScreen(new InGameScreen)) I guess I have to do something like a complete clean up between switching screens. But how should I implement this? Just "deleting" the old InGameScreen Object shouldent be enought, right? Do I have to use the dispose() Method? Is it enough to instantiate everything new (in the init from InGameScreen) since it will instantiate all child object new for its own like Box2DWorld world new World()


Scene2D set table cell size in percentage of tables s size Is it somehow possible to set Scene2D table cell s size in percentage of the table? I would like to have orientation independent menu, with buttons filling let s say 75 percent of the screen, and also to respond on window resizing (desktop version). I have tried several methods, for example using Value table.add(button).width(Value.percentWidth(.75F)) but when value.get(actor) is called inside cell, it is supplied with inner button actor not its container (table). I have also tried to set it in fixed fashion table.add(button).width(Value.percentWidth(.75F).get(table)) This works fine, but since I set pixel value insted of Value object it is not recalculated upon resizing. Is there any way to achieve this?


Box2D Proper way to simulate player's body and feet I'm new to LibGDX and Box2D, and I'm trying to create my player's body but got some issues. I've created the ground as a ChainShape, and my player as a Rectangle. I want to attach a fixture for its feet, so I tried adding an EdgeShape but correct me if I'm wrong it seems that an EdgeShape cannot collide with a ChainShape. Is there a proper way to create the player's feet? Should I change my ground from ChainShape to Rectangles or should I use some other shape for the feet? Edit Following DMGregory's advice, I've made some progress. Since my print statements won't be of much help, I'll post this link with a very detailed explanation https stackoverflow.com questions 7459208 distinguish between collision surface orientations in box2d And some background reading here https www.iforce2d.net b2dtut collision anatomy


LibGDX Easy way to draw partial sprites I am surely overlooking something, but is there an easy to draw for example only half a sprite in LibGDX? I originally thought I could do this with setBounds() but this distorts the sprite.


Scaling a single scalar using OrthographicCamera I'm trying to convert a length (well, a radius) from world coordinates to screen coordinates using an OrthographicCamera. However, the only method I've figured out so far is to do a projection, with some basic vector math before after, but this seems...expensive. Here's what I have so far (apologies, written in Kotlin) val cam OrthographicCamera ... val behavior SteeringBehavior lt Vector2 gt ... calculating the center of the circle val coords Vector3() val wander behavior as Wander lt Vector2 gt defined elsewhere above coords.set(wander.wanderCenter, 0F) cam.project(coords) coords now has wanderCenter in screen coordinates now, the part I'm interested in, calculating the radius val radiusCoords Vector3(wander.wanderCenter, 0F).add(wander.wanderRadius, 0F, 0F) cam.project(radiusCoords) radiusCoords.sub(coords) val radius radiusCoords.x this is the value I want The first half of the code snippet is fine, and provided for context. But the second half...I'm basically taking a scalar and plugging it through a Vector3 and a series of Complicated Matrix Math to convert it to another larger scalar. Is there an easier way to do what I'm doing? I've looked around a bit like at OrthographicCamera's combined.getScaleX() field, but it doesn't seem to have the value I need.


Use libgdx box2d for dynamically generated top down map So, I've already found some information on how to use box2d and tiledmap together. Since I want to generate my top down map (100 by 100 tiles), I thought about only using box2d. The tiles would be fixed and only the player (and maybe some other movable parts like chests, etc) would be dynamic. I'd also like to use box2dlights later, so using box2d seems convenient. My only concern on this is the performance. I haven't used box2d much, so I don't know how it handles such a big amount of boxes (though not all 10000 tiles would be visible at the same time). Does anyone know how the performance would be influenced or advice on how to achieve this easier? Thanks in advance


Render BitmapFont with size 1 in Libgdx My ingame camera has units that 25 times less than screen units so when I render BitmapFont generated for camera which used in non game screens (settings, level choose etc.) it's even doesn't fit in camera. I came up with some solutions Generate font with right size, but No cap character found in font exception caught. Scale font with font.getData().setScale(float scaleXY) but got this Increase camera units but I'll need to rewrite a lot of code depending on camera combined matrix. Is there any easier way to do this?


how to get width and height of TiledMap in the latest Version of Libgdx I am making a tiled based game, I want not to let the camera show places, where there is no map... this is a obvious solution I got from a tutorial if(camera.position.x lt 400) camera.position.x 400 else if(camera.position.x gt map.width map.tileWidth 400) camera.position.x map.width map.tileWidth 400 if(camera.position.y lt 240) camera.position.y 240 else if(camera.position.y gt map.height map.tileHeight 240) camera.position.y map.height map.tileHeight 240 camera.update() but I don't know how to get width amp height of the tiledMap in the latest version of libgdx https github.com libgdx libgdx blob master gdx src com badlogic gdx maps tiled TiledMap.java Seems strange... I even tried the Super classes but couldn't find. Please help.


Libgdx converting between two camera coordinates I had a similar issue to the question here Why is my text is too large even when scaled to .05f in libGDX? So I created a second camera for my text elements. I'm rendering the text above some other elements, and under others, so I was trying to map between the two camera's coordinates when rendering. That seems to be working OK, but I need to invert the y coordinate during the transformation. I'm wondering why that's the case? Here's the code Setup camera OrthographicCamera camera new OrthographicCamera(VIEWPORT UNITS, VIEWPORT UNITS (height width)) camera.position.set(camera.viewportWidth 2f, camera.viewportHeight 2f, 0) Setup text camera FitViewport fitViewport new FitViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()) fitViewport.apply(true) gameContext.setHudViewport(fitViewport) OrthographicCamera textCamera fitViewport.getCamera() ... later, during render(), convert between coordinates Vector3 textPosition new Vector3(fontX, fontY, 0) camera.project(textPosition) textPosition.y Gdx.graphics.getHeight() textPosition.y why? textCamera.unproject(textPosition) font.draw(spriteBatch, text, textPosition.x, textPosition.y)


Screenshot always returning as a white image on iOS using robovm and libgdx I am trying to take a screenshot for sharing on social media. This code works on my Desktop project, but when I use it on iOS it always shows up as a white image, I am using the standard libgdx code for the screenshot factory, any suggestions? public class ScreenShotFactory public static void SaveScreenshot() try Gdx.files.local("shot.png").delete() FileHandle fh do fh new FileHandle(Gdx.files.getLocalStoragePath() "shot.png") while (fh.exists()) Pixmap pixmap getScreenshot(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), true) PixmapIO.writePNG(fh, pixmap) pixmap.dispose() catch (Exception e) private static Pixmap getScreenshot(int x, int y, int w, int h, boolean yDown) final Pixmap pixmap ScreenUtils.getFrameBufferPixmap(x, y, w, h) if (yDown) Flip the pixmap upside downx ByteBuffer pixels pixmap.getPixels() int numBytes w h 4 byte lines new byte numBytes int numBytesPerLine w 4 for (int i 0 i lt h i ) pixels.position((h i 1) numBytesPerLine) pixels.get(lines, i numBytesPerLine, numBytesPerLine) pixels.clear() pixels.put(lines) pixels.clear() Logger.Log("ScreenShot Taken!") return pixmap


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.


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?


Create a filled pixmap for box2d fixture I'm trying to make a pixmap that fills in a Box2D fixture. It would be kind of like a fill bucket. I've done this before, but I want it to work on rectangles and other polygons. Is there an algorithm to do is, or will I need to write on myself? Thanks.


Can I sell games made with LibGdx on Steam my question is pretty self explanatory, there is any technical or legal issue in selling libgdx games on steam? EDIT It is possible to show some kind of evidence, maybe a exemple of a game that is made with libgdx and already is on steam?


How to implement a simple bullet trajectory I searched and searched and although it's a fair simple question, I don't find the proper answer but general ideas (which I already have). I have a top down game and I want to implement a gun which shoots bullets that follow a simple path (no physics nor change of trajectory, just go from A to B thing). a vector of the position of the gun player. b vector of the mouse position (cross hair). w the vector of the bullet's trajectory. So, w b a. And the position of the bullet x x0 speedtimenormalized w.x , y y0 speed time normalized w.y . I have the constructor public Shot(int shipX, int shipY, int mouseX, int mouseY) I get mouse with Gdx.input.getX() getY() ... this.shotTime TimeUtils.millis() this.posX shipX this.posY shipY I used aVector aVector.nor() here before but for some reason didn't work float tmp (float) (Math.pow(mouseX shipX, 2) Math.pow(mouseY shipY, 2)) tmp (float) Math.sqrt(Math.abs(tmp)) this.vecX (mouseX shipX) tmp this.vecY (mouseY shipY) tmp And here I update the position and draw the shot public void drawShot(SpriteBatch batch) this.lifeTime TimeUtils.millis() this.shotTime position positionBefore v t this.posX this.posX this.vecX this.lifeTime speed Gdx.graphics.getDeltaTime() this.posY this.posY this.vecY this.lifeTime speed Gdx.graphics.getDeltaTime() ... Now, the behavior of the bullet seems very awkward, not going exactly where my mouse is (it's like the mouse is 30px off) and with a random speed. I know I probably need to open the old algebra book from college but I'd like somebody says if I'm in the right direction (or points me to it) if it's a calculation problem, a code problem or both. Also, is it possible that Gdx.input.getX() gives me non precise position? Because when I draw the cross hair it also draws off the cursor position. Sorry for the long post and sorry if it's a very basic question. Thanks!


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?


Move Sprite in constant speed on squircle I'm creating a game and i need to move a sprite on squircle path. https en.wikipedia.org wiki Squircle i created the path using the equation angle Gdx.graphics.getDeltaTime() speed float x (float) (R Math.pow(Math.abs(MathUtils.cos(angle)),1 10f) sgn(MathUtils.cos(angle))) a float y (float) (R Math.pow(Math.abs(MathUtils.sin(angle)),1 10f) sgn(MathUtils.sin(angle))) b sprite.setPosition(x,y) the result is My question is how to make the sprite move in a constant speed Edit i used the formula found on Wikipedia


Libgdx SpriteBatch won't position correctly on Screen I have been trying to position my spritebatch correctly regardless of screen size but it simply wont scale..This is what I want to achieve on every screen size..I want my Sprite Object to be positioned at the center of the x axis on every screen size and on the first half of the screen (above dotted line) and have it scale as well..I have also noticed that spritebatch doesn't respect my gameheight and gamewidth instead opting for screenwidth and screenheight. The dimensions for my sprite anim are 900 by 700 and I am hoping it can scale for lower resolutions Code batch.draw(animation.getKeyFrame(elapsedTime, true), 20, app.midPointY 350, app.screenWidth, 465)


making an object follow a path libgdx I am making a game that has objects that shoot other objects. I need the enemies to follow a path. The easiest way I can think of doing this is by having an array of coordinates and they move between them. But when I make a curve in the path, I don't want to have to put in 100 coordinates. There must be a better way.


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


Error in projecting coordinates from FitViewport to screen in LibGDX i'm using a FitViewport to render my "game world". Viewport virtual dimensions are fixed 400x240. I use viewport.unproject method to scale input touches from screen coordinates to world coordinates, and the values are good. The problem begins when i use the opposite (viewport.project method). I have to use it for drawing a sprite that is scaled for screen dimensions but i have X and Y positions in "game" coordinates. Vector2 screenCoords new Vector2() screenCoords (viewport.project(new Vector2(gameX, gameY))) When i use viewport.project i only have the result i expect if the screen aspect ratio matches my game aspect ratio (so the viewport fits the whole screen). I noticed that if screen height is higher (so my viewport is fitted horizontally and black bars appear below and above it) the X coordinate is fine, but Y coordinate varies slightly depending if the "game" Y coordinate is near upper or lower side. Based on my knowledge and on javadoc comments i've red, the method must automatically recognize if the viewport is not full screen or if it is not, and add an offset based on how tall the black bars are. Am i doing something wrong???


How to setup engine properly in ktx ashley? I'm trying to setup simplest Ashley project with only 2 entities and get this error Exception in thread "LWJGL Application" java.lang.IllegalStateException createComponent(T class.java).apply(configure) must not be null Here is the code class AshleyScreen(game Main) KtxScreen private val engine Engine() override fun show() engine.add entity with lt DrawableComponent gt sprite Sprite(Texture("image1.png")) with lt TransformComponent gt position.set(0f, 400f) entity with lt DrawableComponent gt sprite Sprite(Texture("image2.png")) with lt TransformComponent gt position.set(500f, 50f) val renderSystem RenderSystem() engine.addSystem(renderSystem) override fun render(delta Float) engine.update(delta) Components class DrawableComponent(var sprite Sprite) Component class TransformComponent(val position Vector2 Vector2()) Component Systems class RenderSystem IteratingSystem(allOf(DrawableComponent class).get()) val batch SpriteBatch() val tm ComponentMapper.getFor(TransformComponent class.java) val dm ComponentMapper.getFor(DrawableComponent class.java) override fun processEntity(entity Entity, deltaTime Float) val t tm entity val d dm entity d.sprite.setPosition(t.position.x, t.position.y) clearScreen(0.8f, 0.8f, 0.8f) batch.begin() d.sprite.draw(batch) batch.end() Compiler complains on engine.add line.


LibGDX Sending event to a button behaves differently from actually clicking it I have a button on screen, and I want the user to be able to dismiss it by either clicking on it, or hitting space. The button is constructed as follows button new TextButton("RESUME", skin) button.setVisible(false) button.addListener(new InputListener() Override public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) return true Override public void touchUp(InputEvent event, float x, float y, int pointer, int button) button.addAction( Actions.sequence( send out of the screen Actions.moveTo(WORLD WIDTH 2 button.getWidth() 2, button.getHeight(), 0.2f), Actions.hide(), Actions.run( () gt resumeGame() ), Actions.removeActor() ) ) ) ... table.add(button) stage.AddActor(table) ... So if I make the button appear and click on it, everything is fine. I can repeat the sequence "button appear click" at will, and each time the button will move offscreen to the bottom and will be removed from the table. I want the button to do exactly the same when the user hits space, so I did private void clickButton(TextButton button) InputEvent inputEvent new InputEvent() inputEvent.setRelatedActor(button) inputEvent.setType(InputEvent.Type.touchDown) button.fire(inputEvent) inputEvent.setType(InputEvent.Type.touchUp) button.fire(inputEvent) then stage.addListener(new InputListener() Override public boolean keyDown(InputEvent event, int keycode) if (keycode Input.Keys.SPACE) clickButton(button) return true Now when the button is shown and I hit space, it looks like it works, but if I make the button appear again, it's shown briefly then it disappears (it's removed from the table). It's like the final Actions.removeActor() in the button listener is not executed when the button is "clicked" using space, and it's then executed the next time when the button appears again, making it disappear immediately. EDIT this is indeed the case. I put a debug print statement right before the Actions.removeActor() action, and upon mouse click the text is printed, but using clickButton() it's not (and it's printed instead when the button is shown again and readded to the table). Am I doing something wrong here? What's the "correct" way to click a button programmatically (yes, I've already seen https stackoverflow.com questions 25870645 programatically perform click on actor libgdx)


ParticleEffectPool.obtain() not resetting particles I want to use ParticleEffectPools in libGDX but I'm running into an odd issue where the effects don't seem to be reset when obtained by the pool. The code below looks for an existing ParticleEffectPool for the named effect, creates one if necessary, and then obtains a particle effect for the newly created Actor. The particle effect should be reset in the obtain function (if you look at the source it does so). What happens is the first effect works as expected but every subsequent one flashes very briefly on the screen as if its run out of duration. public class ParticleEffectActor extends Actor private static final Map lt String, ParticleEffectPool gt ParticlePools new HashMap lt gt () private final PooledEffect effect public ParticleEffectActor(String effectName, float rotation) if(!ParticlePools.containsKey(effectName)) ParticleEffect particleEffect new ParticleEffect() particleEffect.load(Gdx.files.internal("resources particles " effectName ".p"), Images.Atlas) ParticlePools.put(effectName, new ParticleEffectPool(particleEffect, 10, 50)) this.effect ParticlePools.get(effectName).obtain() rotation 90f for(ParticleEmitter emitter effect.getEmitters()) emitter.reset() ParticleEmitter.ScaledNumericValue angle emitter.getAngle() angle.setLow(rotation 35, rotation 35) angle.setHigh(rotation 35, rotation 35) Override public void draw (SpriteBatch batch, float parentAlpha) effect.draw(batch) Override public void act (float delta) super.act(delta) effect.setPosition(getX(), getY()) effect.update(delta) Override public boolean remove() effect.free() return super.remove()


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


The most popular Resolutions and Aspect Ratios in Android OS 2019 I develop the game with Libgdx framework. When I tried to deal with support multiple screen resolutions it turns out that Libgdx is not following Android approach how to deal with Screen sizes and densities (mdpi, hdpi, xhdpi, etc folders). I found only one way to handle assets ResolutionFileResolver. I have to create folders with different resolutions and the Libgdx choose more appropriate texture for me automatically for each device. Android platform has a huge amount of Phones and Tables with different screen resolutions. I have to find a good strategy on how to handle it. For example let's take a look at the case where I have 2 folders in my game "800x480" and "1440x2560". The device on which I run the game has "1280x720". In this case, "800x480" resolution will be chosen as more appropriate. It leads to bad quality of the Textures because of stretching. At the same time, I can't leave only one asset with high quality. It leads to cut all older devices with a small amount of RAM. The idea is to create 3 most popular resolutions for 3 categories low, middle and high resolutions. Where can I find some statistic about the resolutions popularity of Android Devices? I know about the Android Developer Dashboard but it doesn't show Screen Resolutions. Does anyone use Libgdx in 2019? How to deal with Multiple Screen Support in this framework? Any real statistic about the most popular Aspect Ratio? Which aspect ratio you choose as "basic" in your games? I would love to see any "best practice" how to cover as many devices as possible with the good quality of the view.


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.


Loading TextureRegion with filter diff from that of texture it came from I am using libgdx . While packing my texture atlas I have set the filter for mag and min to Nearest . But for just one region I wish to draw it with linear filter . Is it possible to have different filters for texture region than that of texture atlas it came from.


Why am I unable to move a player that extends image? I wanted to create a simple game where I will be able to move a player image horizontally. I am using Screens (at least trying to do so) and created the below public class GameScreen implements Screen private JumpingKitten jumpingKitten private Stage stage private OrthographicCamera camera private SpriteBatch spriteBatch private Player player public GameScreen(JumpingKitten jumpingKitten) this.jumpingKitten jumpingKitten this.createCamera() this.stage new Stage(new StretchViewport(1026.0f, 768.0f, this.camera)) this.spriteBatch new SpriteBatch() Gdx.input.setInputProcessor(this.stage) init() private void init() initPlayer() private void initPlayer() player new Player() stage.addActor(player) stage.act() private void createCamera() this.camera new OrthographicCamera() this.camera.setToOrtho(false, 1026.0f, 768.0f) this.camera.update() Override public void render(float delta) this.clearScreen() handleInput() this.camera.update() this.spriteBatch.setProjectionMatrix(this.camera.combined) spriteBatch.begin() stage.draw() spriteBatch.end() private void clearScreen() Gdx.gl.glClearColor(0.15F, 0.15F, 0.3F, 1.0F) Gdx.gl.glClear(16384) private void handleInput() if(Gdx.input.isKeyPressed(Input.Keys.A)) player.STARTING X 50 Gdx.graphics.getDeltaTime() STARTING X incorrect System.out.println("A is pressed") shown in console if(Gdx.input.isKeyPressed(Input.Keys.D)) player.STARTING X 50 Gdx.graphics.getDeltaTime() And below is the player class public class Player extends Image private static final int PLAYER WIDTH 119 private static final int PLAYER HEIGHT 136 public static int STARTING X 100 public static final int STARTING Y 100 public Player() super(new Texture("Cat Idle 1.png")) this.setOrigin(100, 100) this.setSize(PLAYER WIDTH, PLAYER HEIGHT) this.setPosition(STARTING X, STARTING Y) Even though I have completed some simple tutorials, I am unable to retrieve the x coordinate of the player object. This is stopping me from translating the player object along the x axis. Can someone explain what I am doing wrong, here? I honestly think that I jumped into something I shouldn't have.


How to combine Actor.setPosition and Actor.hit? Why after using Actor.setPosition, input coordinates in Actor.hit come with a shift in the values specified in setPosition? Create scene public class MyActor extends Actor ... int width 70 int height 70 public MyActor(Texture img, int x, int y, int realX, int realY) ... sprite new Sprite(img, x, y, width, height) this.setPosition(realX, realY) Standard search Actor public class GameScreen implements Screen, InputProcessor Override public boolean touchDown(int screenX, int screenY, int pointer, int button) Vector2 coord stage.screenToStageCoordinates(new Vector2((float)screenX,(float)screenY)) Gdx.app.log("touchDown", "" coord.x "," coord.y) selectedActor (MyActor)stage.hit(coord.x,coord.y,false) ... public class MyActor extends Actor Override public Actor hit(float x, float y, boolean touchable) if(!touchable) Gdx.app.log("Actor.hit ", "" x " " y) return x lt getX() x gt getX() width y lt getY() y gt getY() height ? null this But come the distorted values. Coordinates Click touchDown 26.25,81.250015. MyActor in the values obtained from the offset, the multiple of 70 Actor.hit 43.75 11.250015 Actor.hit 43.75 81.250015 Actor.hit 26.25 11.250015 Actor.hit 26.25 81.250015 Why? How to fix? UPDATE public class MyStage extends Stage ... Override public Actor hit(float x, float y, boolean touchable) return super.hit(x,y,touchable)


Libgdx, tiled map how to reload layer? In the simple platform game I'm making, when player collects coin, its cell is set to null. Is it possible to recover all cells from layer "coins" after player dies? I have tried multiple things but none of them worked Here is part of code responsible for collecting coins for (Rectangle coins coins) TiledMapTileLayer layer coins (TiledMapTileLayer)map.getLayers().get("coins") if(dotRect.overlaps(coins)) layer coins.setCell((int)coins.x, (int)coins.y, null) coinsN Sounds.playCoin() But when player dies and re spawns, there are no coins if he collected them before. I tried reloading the map it works fine, but loading after every death is unacceptable it takes a lot of time. EDIT Now I have another problem, with loading TiledMapTile to put into cell... TiledMapTile coinTile public void show() TextureRegion mapTexture1Region new TextureRegion(mapTexture1, 32, 0, 16, 16) coinTile.setTextureRegion(mapTexture1Region) It gives me NullPointerException, and I have no idea why


LibGDX Stage and Viewport management for Actors? So I've done research about how to use Stage, Actor and Viewports etc. To optimize the game for most devices running Android. I'm pretty sure that the viewport is configured or the background image is just being drawn over the screen without actually using the viewport. That is fine though. So I'm basically telling the viewport to draw an image over the whole screen and it seems that that applies to actors also. So I guess the viewport is trying to draw the actor over the whole screen. When testing the app on emulators with different screen sizes the actor is not resized (probably because of the viewport setting), but how can I get the actor to resize so that the actor fits in the world? The world will be the whole screen of the device. Do I need to use two viewports where one is for UI (background so far) and another for the game? If I need to do that wouldn't the UI viewport need to be the screen size and the Game viewport holding the world size would have size constants? If so, then I don't have the whole screen size as the world, but drawing the Game viewport using the screen width and height would probably result in drawing the actor over the whole screen again, right? And I've seen in some tutorials that they often set a constant unit of the world width and world height. Wouldn't that fail to fit all devices since they have a specific constant for width and height? I want all of my Actors to be resized so that they fit inside the world (screen size). UPDATE TO CLARIFY MY QUESTION As you see the background is scaled up and down due to being drawn as the width and height of the screen, I guess, but I need the actors to also be scaled up or down. The actors can't remain the same size for all screens. MyGdxGame public class MyGdxGame extends ApplicationAdapter private OrthographicCamera camera private Stage stage private Viewport viewport private Texture textureBackground Override public void create () camera new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()) camera.position.set(Gdx.graphics.getWidth() 2, Gdx.graphics.getHeight() 2, 0) final float GAME WORLD WIDTH Gdx.graphics.getWidth() final float GAME WORLD HEIGHT Gdx.graphics.getHeight() viewport new FitViewport(GAME WORLD WIDTH, GAME WORLD HEIGHT, camera) stage new Stage(viewport) MyActor actor new MyActor(new Texture("badlogic.jpg")) actor.setPosition(0, 0) stage.addActor(actor) stage.getViewport().apply() Gdx.input.setInputProcessor(stage) textureBackground new Texture("TheWorld.png") Override public void resize(int width, int height) stage.getViewport().update(width, height) stage.getCamera().position.set(Gdx.graphics.getWidth() 2, Gdx.graphics.getHeight() 2, 0) Override public void render () Gdx.gl.glClearColor(1, 0, 0, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) stage.getBatch().setProjectionMatrix(stage.getCamera().combined) stage.getCamera().update() stage.getBatch().begin() stage.getBatch().draw(textureBackground, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()) stage.getBatch().end() stage.act(Gdx.graphics.getDeltaTime()) stage.draw() MyActor package com.mygdx.game import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.graphics.g2d.Batch import com.badlogic.gdx.scenes.scene2d.Actor public class MyActor extends Actor private Texture texture public MyActor(Texture texture) this.texture texture Override public void draw(Batch batch, float parentAlpha) batch.draw(texture, getX(), getY()) Images Research links Using two viewports for UI and Game Viewports and World units LibGDX Viewport Tutorial


Tween animation with Universal Tween Engine LIbGDX Let me preface by saying that I'm new to libgdx... I have an animation that I'm currently drawing to the screen using game.batch.draw(flyAnimation2.getKeyFrame(elapsedTime, true), 200,200,0, 0, 124, 90, 1.0f, 1.0f, 90) Where flyAnimation2 is Animation flyAnimation2 This works correctly. I now want to use UniversalTweenEngine to tween it from one side of the screen to the other. I can't find any decent documentation on how to achieve this affect using an Animation. Any help would be appreciated!!


How do I implement efficient collision avoidance in 100 enemies I am developing a libgdx game. It is a top down shooter and I am trying to make a good AI. I have tried to implement A from the AI library from libgdx and it works fine but when i have a lot of enemies it starts to slow down the game. Have tried implementing a Pathfinding manager to manage threads and path requests but I have trouble implementing it and still slows down. Also I know A is a bit overkill for my game, which is a big open zone mostly (see pic of my map) So I tried to implement this collision avoidance Steering Behaviors Collision Avoidance but it doesn't go well when the player is inside houses. My question is, does exists some type of algorithm that fits perfectly for what I am asking? There are a lot of games with hundreds of enemies going to kill you so I bet there is a way, just I cant find out pd Any doubt ask and I will provide more information if necessary


html5 libgdx project war to be deployed in a servlet container or only part of the contents to a web server I am new to compiling games with libgdx to be played on the web and I have some doubts perhaps someone can point me in the right direction Using the new gradle setup I wrote a simple game to learn how to deploy a game to be played on the web, but I am not sure what files have to be uploaded to my server. 1) Where is the compiled code I should deploy? In some places I found that the "war" directory has the files I need to deploy. In other places I found that the "build dist" (generated running gradle's dist task) has the files. 2) What files should I deploy The war directory gives me the hint I should deploy everything into a servlet container like Tomcat because, besides of the name, I have a war directory structure (it has a WEB INF sub dir). But in the badlogic info I found it says I only need to deploy Assets, html, and the index.html file to a WEBSERVER. Note Both ways work, so perhaps the deployment of the full war is to be done under certain conditions. So which would these conditions be? 3) I've read about the SuperDev mode to debug the app. When I run the application I get a SuperDev blue button in the browser. When I compile using GWT (I understand this generates production mode) I stilll get the blue SuperDev button. Do I have to remove it manually, or am I doing something wrong? Please, can someone put a bit of light on this?


Since Table.drawDebug is deprecated in libGDX, what should I use instead? I am following the "Learning LibGDX Game Development" book to make a simple game. I am in the menu creation section where we create a stage and render it with debug borders. The book says to use Table.drawDebug(stage) but this static method seems to have been removed from the frameworks Table class entirely. I am importing com.badlogic.gdx.scenes.scene2d.ui.Table below is my code Override public void render(float deltaTime) Gdx.gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) if (debugEnabled) debugRebuildStage deltaTime if (debugRebuildStage lt 0) debugRebuildStage DEBUG REBUILD INTERVAL rebuildStage() stage.act(deltaTime) stage.draw() Table.drawDebug(stage) The last line, Table.drawDebug(stage) has the compilation error "The method drawDebug(ShapeRenderer) in the type Table is not applicable for the arguments (Stage)" Is there a new way to draw the stage in debug mode?


Draw a line curve for the path an object has taken Hello I am making a game in libgdx. I want to draw a line curve of the path a object have taken. First a thought I could save all positions of the objects each iteration and draw line between them using the Shaperenderer. This is however inefficient because the number of saved positions for a object becomes really large, and I have alot of objects. My second thought was to draw a line between only the previous position and the current position on to a pixmap, and then draw the pixmap to the screen. This way I only need to save the old position because I don't clear the pixmap. The problem is that the world is infinitely big, and the pixmap cant cover the entire world (and it is bad to make a really big pixmap?). Also when I zoom out of the world the lines becomes really small and I cant see them. When I use the shaperenderer, the lines are always one pixel wide independent of the zoom. So is there a smart way where I can draw the path my objects have taken without saving all previous positions, and where the line stays constant width?


Implementing a scrolling UI in Libgdx I am using the LibGDX framework. I'm not using Scene2D but I want to implement my own "scrolling UI". This is only what I could think of (see image below) I will make the 2nd camera look at very far coordinates (and draw the UI stuff there) and have it (within the blue box) receive its own input. But I think this is not possible with LibGDX, since if you set the size of the camera you are like setting how big it views the world and not how big the viewport is. I mean you can't set the size of the camera of something like 50px width and height and have it place on the center. If you setPosition, you are setting it to where it looks at and not where it is placed in the 2D space. I'm trying to explain it clearly and I hope it is clear.


How to add slowmotion effect in libgdx I want to add slow motion effect with a collision as a trigger. So I want to have an effective way to trigger a slowmotion effect on bodies as well as sprites that can be caled in the update method. Can anyone please help me with this or provide a link as to where I can find the answer?


libgdx universal tween engine how to control the tweening speed? How can i control the speed of a tweening sprite? Here is the code in create () try tween w Gdx.graphics.getWidth() h Gdx.graphics.getHeight() texture new Texture("nube png by diieguiitoh d4vhyzb.png") texture.setFilter(TextureFilter.Linear, TextureFilter.Linear) sprite1 new Sprite(texture) sprite1.setPosition(50,0.25f h) Tween.registerAccessor(Sprite.class, new SpriteAccessor()) manager1 new TweenManager() Tween.to(sprite1,SpriteAccessor.POSITION X,1000f) tween POSITION X for a duration .target(w 100) final POSITION X .ease(TweenEquations.easeInOutQuad) easing equation .repeat(10,1000f) ten more times .start(manager1) start it startTime TimeUtils.millis() try tween In render() batch.begin() delta (TimeUtils.millis() startTime) 1000 get time delta manager1.update(delta) update sprite1 sprite1.draw(batch) batch.end()


Eliminate an Actor dragged outside SlotTarget As the title suggests, i would like to eliminate an Actor from the Stage when the player moves it outside my SourceTarget. The default behavior of DragAndDrop class doesn't allow to drag an Actor on a place that isn't a valid SourceTarget, but i need to implement the elimination of an Actor in this way. So, can i implement one or both the following solutions? 1) When the Actor is dragged outside SourceTarget, remove it 2) Use a special TargetActor over which the dragged Actor gets removed (like a trash can) In this latter case i should create a second special TargetActor, but seems that Libgdx doesn't allow it. I can have only one TargetActor. In my particular case SourceActor and TargetActor are the same. dragAndDrop.addSource(new SourceActor(slotActor)) dragAndDrop.addTarget(new TargetActor(slotActor)) Thank you


How to rotate actors around the actor like a satellite around the earth? I'm not a pro in LibGDX and physics but I know basics, vectors, actor's actions and so. I'm trying to achieve a movement like on the gif below For now, let's say that I have a stage and a central actor that the moon and comet will rotate around. The problem is here that I have no idea if this is achievable with 2D. Should I implement some sort of 3D in LibGDX? Also, is there a way so these objects move in a 'random' path, not the straight line like the comet below? (Moon is a little bit randomized) I know that this question is too broad, but I really didn't know where to ask about this. I'm here to learn cause I always wanted to build a thing like this. I personally think that this is achievable with LibGDX's actions cause I saw something similiar somewhere. If someone could point me the way I would be grateful ) Thanks!


Getting screen coordinates of actor I'm trying to tell if an actor exists at a screen position so I can do something if the actor is clicked on. To do this, I first need to get the screen coordinates of the actor so I can compare it to the coordinates where I click, however, I am having some difficulty. I am currently trying to do this Actor actor ... The position where I clicked obtained from touchDown() in my InputAdapter Vector2 screenPos ... Vector2 actorStagePos actor.localToStageCoordinates(new Vector2(0,0)) Vector2 actorScreenPos actor.getStage().stageToScreenCoordinates(actorStageCoordinates) Rectangle actorScreenBounds new Rectangle(actorScreenPos.x, actorScreenPos.y, actor.getWidth(), actor.getHeight()) if (actorScreenBounds.contains(screenPos)) System.out.println("An actor is there") However, the coordinates don't seem to be converting correctly. They end up slightly below and to the right of where they should be. At first, I thought this was caused because I'm scaling some of the Image actors, but it also did not work when nothing was scaled up.


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() )


How to only detect Actor and not background I'm making a game where I have buttons on a stage, but the background also acts as a "button". But when I press on one of the existing actors on the stage, it also registers a click in the background in addition to the click on the button. How can I fix this? Inside constructor button new ImageButton(getDrawable(new Texture("PlayUp.jpg"))) only using one image atm button.setSize(150, 134) button.setPosition(camera.position.x, camera.position.y) stage new Stage(viewport) Gdx.input.setInputProcessor(stage) stage.addListener(new ClickListener() Override public void clicked(InputEvent event, float x, float y) System.out.println("Background touched") ) button.addListener(new InputListener() Override public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) return true Override public void touchUp(InputEvent event, float x, float y, int pointer, int button) System.out.println("Button touched") ) stage.addActor(button) part of render() method Override public void render(float delta) Gdx.gl.glClearColor(1, 0, 0, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) tapCatch.batch.setProjectionMatrix(camera.combined) tapCatch.batch.begin() stage.act(delta) stage.draw() tapCatch.batch.end()


Units, Layers, and Isometric Ordering I'm currently using LibGDX and Tiled map editor to render isometric maps. I'm having a two related difficulties. The first issue is, when do I render units that will end up changing position often and to which layer? At first I thought that I would render units with a wall layer so that walls behind of and in front of the unit are drawn correctly. However, the problem with this is that if a unit (i.e. a character) steps in front of say an object in some sort of top level decoration layer, part of that object will be drawn on top of the unit. The second issue is how to deal with layers that have static objects that units will often be stepping in front of or behind. Let's say you have a decoration layer where you will place trees. The problem with this layer is that depending on where some objects are placed in the layer, they will overlap inconsistently. For example, the following I know this is related to painter's algorithm, but I'm using LibGDX's tile map renderer so the extent to which I have control over drawing the map is rendering different layers at a time and switching out cells tiles in a layer.


Libgdx particle editor absorb effect I am trying to achieve a certain kind of absorb effect within libgdx via the particle editor. To be more descriptive I want particles to spawn in a circle and then move towards the center point of that circle (and then disappear there). I can of course spawn the particles in a circle, but then I cannot seem to find a way to make sure they all move toward a center point. So my questions can be divided into two parts Is their any way I could use the particle editor to achieve this absorb effect I described? If not, then what would the best way to achieve it in libgdx? Is their some way I could hack into the particle effect behavior itself and make this work?


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.


How to create a color aura around actors in libGDX? Is there an easy mechanism to create a color aura around an actor in libGDX? Thanks for all tips!


LibGDX Getting Tile Map Layers Problem While following a tutorial with LibGDX, I am working with tile maps. This is the method that I'm using tilemap.getLayers().get("Collision Layer") or tilemap.getLayers().get(1) 1 is the second layer, the collision layer The problem is, is that when I try to get a certain layer from the tile map, it return a null pointer error like so Exception in thread "LWJGL Application" java.lang.NullPointerException at com.mytut.game.Player.Init(Player.java 25) at com.mytut.game.MyTutGame.create(MyTutGame.java 70) at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java 147) at com.badlogic.gdx.backends.lwjgl.LwjglApplication 1.run(LwjglApplication.java 124) I have tried various ways of getting the layer but none of them seem to work. Here's an image of my tile map in the Tiled map editor


Unproject considering parallax depth How can I take screen coordinates (or alternatively world coordinates on the 'primary' parallax plane) and find out what world coordinates they translate into when taking parallax depth into account? I want to be able to tell if a rectangle is under the mouse cursor. I'm using libGDX and the ParallaxCamera class from the tests module. This means depth is modelled in two dimensions, where 1 primary plane, 0 pinned to the screen, 0,5 scrolls at half the rate of the primary plane. This is trivial in the primary parallax plane, as libGDX's camera has a handy unproject method. However, I can't find any examples that use the 'parallax matrix', as this is typically passed into a SpriteBatch setProjectionMatrix rather than being used in internal camera calculations. I don't understand the mathematics enough to figure this out. If anyone reading this can link to any very basic explanations of the mathematics behind projecting things with parallax depth into screen space and vice versa, I'd be really grateful to read it.


Detecting key press only once in Libgdx Have a question on keyboard inputs. Currently I am using this method to read my input, Gdx.input.isKeyPressed(Input.Keys.A), it is working fine. But I do realized at times there are multiple instances of A being pressed when I only press once. And I understand that the method had to be placed in the render() method for it to work. Is the problem due to the refreshing? My question is, how can I only detect 1 instance of "A", when A is pressed for once.


Sprites with same position rendered in different places on screen In LibGDX I have few sprites that all have set position (0,0). So in theory they all should render in one place on top of each other but what ends up happening is that all the sprites are being rendered in different spot on screen. For all sprites objects all I do is Sprite sprite new Sprite(new Texture("texture.png")) sprite.setOriginCenter() sprite.setScale(1 PPM) And then when rendering it batch.begin() sprite.draw(batch) ... batch.end() And here is what I get rocket sprite is in completely different place than fire sprite and some other sprites I couldn't even find. I marked "real" 0,0 point with yellow circle. So why are does sprites in different spots? I've heard that it could be because of scaling but since I am setting sprite's origin to center it shouldn't be a problem, right?


I was expecting a circle to trace a path of parabola . why isnt that the case? Why isn't the rendered shape a parabola? Override public void render () Gdx.gl.glClearColor(1, 0, 0, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) renderer.begin(ShapeRenderer.ShapeType.Filled) position.x 1 position.y position.x position.x renderer.circle(position.x,position.y,radius) renderer.end()


LibGDX Making an object move correctly based on real time Below is an image of my gameworld. As we can see, the player starts at position 0. each cell represents 1 game world unit. My goal is to get the player to move 1 unit (the red cell) in 1 second in 'real world' time using the LIBGDX framework. LibGDX uses something called 'continuous rendering' by default, which means its 'main loop' runs as fast as the underlying OS is able to. The range could be anywhere from 0 80 frames per second. I am capping the FPS to 60 with the below 'main' loop (In LIbGDX the main loop is called render) Override public void render(float deltaTime) Get the time it took to render the last frame and make sure our delta time is never larger than 0.0166666666666667 (60 FPS). This will ensure that on fast OS the game at only 60 FPS. float dt Math.min(Gdx.graphics.getDeltaTime(), 1 60f) UPDATE player.update(dt) RENDER clear the screen and set it to cornflower blue Gdx.gl.glClearColor(0x64 255.0f, 0x95 255.0f, 0xed 255.0f, 0xff 255.0f) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) worldRenderer.render() Below is the code for my player object's update method. As we can see it is operating solely on the delta time for now. In a perfect world of 60 FPS, this would work perfectly but unfortunatly FPS dips will always happen (especially on mobile platforms). How can I add a calculation on top of the delta time to move the player 1 unit in real time regardless of framerate? Override public void update(float deltaTime) handle user input always should come first if (Gdx.input.isKeyPressed(Keys.SPACE)) position.x deltaTime Below shows what is happening with my current code, if we had a perfect 60 FPS the position should 1, but as we can see it does not because the FPS varies slightly from frame to frame.


Get device rotation in Y axis So using LibGDX accelerometer methods, I'm able to get the rotation of the device in the X and Z axes in degrees with this code Override public void render(float delta) float accX Gdx.input.getAccelerometerX(), accY Gdx.input.getAccelerometerY(), accZ Gdx.input.getAccelerometerZ() float moduleValue (float) Math.sqrt(accX accX accY accY accZ accZ) Here I do the gravity compensation accX moduleValue accY moduleValue accZ moduleValue float xRotation (float) Math.atan2(accY, accZ) MathUtils.radiansToDegrees, zRotation (float) Math.atan2(accY, accX) MathUtils.radiansToDegrees However, get the rotation in the Y axis is not that easy to obtain, and if I try to get it by this way, it returns erroneus values.


Draw a line curve for the path an object has taken Hello I am making a game in libgdx. I want to draw a line curve of the path a object have taken. First a thought I could save all positions of the objects each iteration and draw line between them using the Shaperenderer. This is however inefficient because the number of saved positions for a object becomes really large, and I have alot of objects. My second thought was to draw a line between only the previous position and the current position on to a pixmap, and then draw the pixmap to the screen. This way I only need to save the old position because I don't clear the pixmap. The problem is that the world is infinitely big, and the pixmap cant cover the entire world (and it is bad to make a really big pixmap?). Also when I zoom out of the world the lines becomes really small and I cant see them. When I use the shaperenderer, the lines are always one pixel wide independent of the zoom. So is there a smart way where I can draw the path my objects have taken without saving all previous positions, and where the line stays constant width?


creating a simple cartoon like light effect I could like to create a really simple light engine that does not eat to much CPU and will produce this effect I am using libgdx for my game with box 2D light (which is too heavy for my needs). I have no idea of what is the best solution to create this effect (shapeRenderer? pure shader?). For the moment I don't need any shadow casting, but I would like to be able to maintain multiple light sources and to add color to the light.


What is the formula or algorithm used in libgdx delta time? I'm studying time stepping algorithm and I need to know how delta time works in libgdx, because I think delta time uses some kind of time stepping algorithm.


LibGDX player movement on X axis is very limited I'm making a side scroller game using LibGDX, where player can move only on X axis. The problem is that the player can only move on positive X value, so he can't go to negative X. This is not that big of a problem, but the main problem is that where ever I choose his initial position, he will never move right, so he basically can't extend his initial X value. I'm making movement with Gdx.graphics.getDeltaTime(), but when I don't use it, strangely everything works right. Other things work alright, the animation change works, test outputs worked, the problem always occurs only in the part of adding delta time to the x axis. Player's initial position private Actor hiro hiro new Hiro("Hiro", 106, 4, 32, 32) (I'm not using LibGDX's Actor class, I made my own which uses animations) Player's constructor public Hiro(String name, int x, int y, int width, int height) super(name, x, y, width, height) this.x x this.y y this.width width this.height height standingRightTexture new Texture("hiro standing right.png") standingLeftTexture new Texture("hiro standing left.png") walkingRightTexture new Texture("hiro walking right.png") walkingLeftTexture new Texture("hiro walking left.png") standingRight new Animation(standingRightTexture, 1, 10f, true) standingLeft new Animation(standingLeftTexture, 1, 10f, true) walkingRight new Animation(walkingRightTexture, 8, 0.6f, true) walkingLeft new Animation(walkingLeftTexture, 8, 0.6f, true) setAnimation(standingRight) state State.STANDING RIGHT facingRight true Player's movement if(Gdx.input.isKeyPressed(Input.Keys.D)) x Gdx.graphics.getDeltaTime() 6f facingRight true state State.WALKING RIGHT System.out.println(x) if(Gdx.input.isKeyPressed(Input.Keys.A)) x Gdx.graphics.getDeltaTime() 6f facingRight false state State.WALKING LEFT System.out.println(x) Playing Screen's render method Override public void render(SpriteBatch spriteBatch) cam.update() spriteBatch.setProjectionMatrix(cam.combined) spriteBatch.begin() hiro.getAnimation().update(Gdx.graphics.getDeltaTime()) spriteBatch.draw(hiro.getAnimation().getFrame(), hiro.getX(), hiro.getY()) moveCamera() spriteBatch.end() If you want other segments of code, I'll provide it. I greatly thank everyone whiling to help. Edit SOLVED! All I had to do was to use float axis instead of integer. Silly me!


Focus scene2d UI actors programmatically in libGDX I am trying to implement keyboard movement in game main menu which is libGDX Stage with UI Actors. I'm also trying to code this feature myself since I can't neither find anything relevant to it in the docs nor find libraries for the feature. I have a bunch of Buttons in the VerticalGroup. Using keyboard UP and DOWN keys, I want to somehow focus, highlight or hover buttons like the way that mouse hovering do. Hovewer, firing FocusEvent on children of the VerticalGroup do not change Button appearance. So how do I focus these buttons or any other UI element (because there are other menus with more complex UI architecture) ? Here is the code for the menu (Kotlin, using ktx scene2d builders and ktx actors event methods) class MainMenuUi Stage() val root verticalGroup center() setFillParent(true) expand(true) space(spacing) fill(0.5f) wrap(false) textButton("Start") textButton("Settings") textButton("Exit") onKeyUp key gt when(key) Input.Keys.UP gt ??? Input.Keys.DOWN gt ??? .also addActor(it) keyboardFocus it


What is the intended usage of the Sprite class in LibGDX I am making a small game in LibGDX and it all works, sprites are moving etc. The drawing is mainly done in the render() method of a Screen, using Batch.draw(TextureRegion). So far so good. But now I would like my sprites to rotate. There are Batch draw methods for rotation (I think), but I noticed a bunch of useful methods in tne Sprite class. Problem is I do not know how to use them without making the rest of the program ugly. I could have a Sprite as a member of each "game object", but that makes direct dependency of the game model on drawing mechanism, specifically LibGDX. Besides I can see problems with serialization and duplicate parameters (Sprite x,y vs model x,y etc) and unnecessary overhead. Or I could subclass Sprite, which would probably be orders of magnitude messier. Is there a common way of clearly separating the model part and rendering part of a small game? And how is Sprite typically used?


How to make a smooth circuit path in Universal tween engine? I tried to make a circuit by starting at point A, with waypoints B and C and final target at A again, and infinite repeats. What happens is that the path from A to B, B to C is smoothed, but path C to A ends with a "sharp" edge Is there any way to make it totally smooth?


Using deltaTime and Frame Rate Independence I'm working on one of my first games and I've read that linking your game logic to FPS is bad because it will run differently at different FPS (obviously). I have already made some of the basic game dependent on frame rate and now that I know this, I would like to unlink the logic and render. I've learned that LibGdx has deltaTime in its render method for this, however I believe I'm misunderstanding how I am to use it. For example, my movement currently looks something like this if (rightKeyisPressed) setVelocityX(movementSpeeD) playerPos.add(getVelocity) In my case, I would like the player to move 6 units per second. Since I built this on 60 fps, that means that movementSpeed is 0.1. Now the way I have seen deltaTime used is by scaling the movementSpeed based on the time like this setVelocityX(movementSpeed deltaTime) However, now I move very slow because delteTime is a very small number. How can I make movement still the same speed without depending on the fps? Sorry if I'm missing something obvious, I just can't seem to wrap my head around this.


How to use Actors Groups with ShapeRenderer instead of Batch? I am intersted in using Actors and Groups on a Stage so that I can make components and subcomponents which draw relative to their parents, but I intend to do my drawing with a ShapeRenderer instead of a Batch. From what I understand of an Actor, the batch which is passed in to the draw() method has all of its matrices set up properly so that I can just use a coordinate system WITHIN THE PARENT to lay out the subcomponents. But it seems that this coordinate system is focused on Batches, and I want to draw using a ShapeRenderer. What do I have to do to get the child Actors to draw themselves RELATIVE TO THEIR PARENT (rather than in global coordinates) when drawing them with ShapeRenderers? Also, one other question How should I be managing begining ending the ShapeRenderer? I am currently passing in a reference to a global ShapeRenderer when I construct my parent object, and this parent object passes in references to each of its children. Should I be calling begin() end() separately in the draw method of each parent child actor? Or should I call it in my main app's draw() method, so I'm only calling it once each frame?


How to start an animation just once on an event in libGDX I am trying to show an explosion animation which i created using a few textureregions and created Animation missileblastAnimation from those textureregion like this TextureRegion explosion explodemissile1, explodemissile2, explodemissile3, explodemissile4, explodemissile5, explodemissile6, explodemissile7,explodemissile8, explodemissile9, explodemissile10, explodemissile11, explodemissile12, explodemissile13, explodemissile14,explodemissile15, explodemissile16, explodemissile17, explodemissile18 missileblastAnimation new Animation(0.1f, explosion) missileblastAnimation.setPlayMode(Animation.NORMAL) I have this following code in the render method Note explosionstarted is set to true when missile hits the ground if(explosionstarted) check if the missile hits the ground to start explosion animation batcher.draw(AssetLoader.missileblastAnimation.getKeyFrame(runTime), 100, 300 102, 50, 102) if(AssetLoader.missileblastAnimation.isAnimationFinished(runTime)) i found that isAnimationFinished tells if animation is finished or not but i still cant understand the passing runTime thing explosionstarted false reset the boolean to make the animation stop drawing Problem is the animation is not playing as it should i.e sometimes it plays too much fast . sometimes it skips first few frames and jumps to ending frames. What is the right way to do this? Is there any other way i can check if the animation is completed ?


Pause Tiled animation during game in LibGDX I m using Tiled with LibGDX and I have some animated tiles. When the game is paused I would like their animation to be paused as well. Is this possible? The map is drawn with mapRenderer.render() and if I'm not mistake, this is the class responsible for getting the corresponding animation. There doesn't seem to be a way to freeze time. Any help appreciated, I've been searching for a couple of hours and cannot find anything.


Is there a Box2d b2World ShiftOrigin function in Libgdx? Is there an equivalent Box2d b2World ShiftOrigin function in Libgdx? I can't seem to find it.


Correct way of texture mapping a 2D mesh in libgdx this is a question regarding the libGDX framework. I have managed to UV map a texture to vertices (in 2D) but have come across a few problems that I think might be caused by incorrect order of vertices. In the first two pictures, you can see a rendering produced by the code bits below (without blending enabled). It seems fine at first, but you can clearly notice that the lower triangle seems to have a rough transition. Is there an easy way to prevent this (without writing too much low level stuff) or is this an expected limitation of this approach? The second problem occurs with the same code but with blending turned on. In the fragment shader, you can see that I adjust the alpha level of each pixel in the region, but with this mesh, it produces a rather weird and distorted image in the right triangle area. Here's the code Shaders Vertex shader attribute vec4 a position attribute vec4 a color attribute vec2 a texCoord0 uniform mat4 u projTrans varying vec4 v color varying vec2 v texCoords void main() v color vec4(1, 1, 1, 1) v texCoords a texCoord0 gl Position u projTrans a position Fragment shader ifdef GL ES precision mediump float endif varying vec4 v color varying vec2 v texCoords uniform sampler2D u texture void main() gl FragColor v color texture2D(u texture, v texCoords) vec4(0, 0, 0, 0.50) Mesh Mesh m new Mesh(true, 5, 0, new VertexAttribute(Usage.Position, 2, "a position"), x,y new VertexAttribute(Usage.TextureCoordinates,2,"a texCoord" 0)) u,v m.setVertices(new float 20f, 360f, 0f,0f, upper left 60f, 20f, 0f, 1f, lower left 180f,20f,1f,1f, lower right 220f, 360f, 1f, 0f, upper right 20f, 360f, 0f, 0f ) upper left (closure) Render Gdx.gl.glEnable(GL20.GL BLEND) Gdx.gl.glBlendFunc(GL20.GL SRC ALPHA, GL20.GL ONE MINUS SRC ALPHA) shaderProgram mesh.begin() shaderProgram mesh.setUniformMatrix("u projTrans", camera.combined) texture.bind() m.render(shaderProgram mesh, GL20.GL TRIANGLE STRIP, 0, 5) shaderProgram mesh.end()


Write error log on crash in libGDX? I've been having problems building my game. I've built it successfully before, until I added the LuaJava.dll and LuaJava.jar files (so I can use Lua in my game). Now, it just briefly opens with black screen and immediately closes. Even though it works just fine in Eclipse. What I used to do before, was set my jar file in my assets and it would just work fine. But now, it refuses to work, and I have no idea what the error is. Is there a function I can call to output the error into a log file?


Render a sphere when the user clicks on the screen with libgdx I m really new to Libgdx, and decided to try out some codes to familiarise myself with it. I m trying to write a program such that a sphere is rendered at the position of the user s click. Here s my code package com.mygdx.game import com.badlogic.gdx.ApplicationListener import com.badlogic.gdx.Gdx import com.badlogic.gdx.graphics.GL20 import com.badlogic.gdx.graphics.PerspectiveCamera import com.badlogic.gdx.graphics.VertexAttributes.Usage import com.badlogic.gdx.graphics.g3d.Environment import com.badlogic.gdx.graphics.g3d.Model import com.badlogic.gdx.graphics.g3d.ModelBatch import com.badlogic.gdx.graphics.g3d.ModelInstance import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight import com.badlogic.gdx.graphics.g3d.Material import com.badlogic.gdx.graphics.g3d.utils.CameraInputController import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder import com.badlogic.gdx.InputAdapter import com.badlogic.gdx.graphics.FPSLogger public class Render implements ApplicationListener public Environment environment public PerspectiveCamera cam public CameraInputController camController public ModelBatch modelBatch private FPSLogger fps public Model model Override public void create() Gdx.graphics.setContinuousRendering(false) environment new Environment() environment.set(new ColorAttribute(ColorAttribute.Specular, 0.4f, 0.4f, 0.4f, 0.6f)) environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, 0f, 0f, 1f)) modelBatch new ModelBatch() cam new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()) cam.position.set(0f, 0f, 10f) cam.lookAt(0,0,0) cam.near 1f cam.far 300f cam.update() ModelBuilder modelBuilder new ModelBuilder() model modelBuilder.createSphere(1f, 1f, 1f, 30, 30, new Material(), Usage.Position Usage.Normal) camController new CameraInputController(cam) Gdx.input.setInputProcessor(camController) fps new FPSLogger() Override public void render() if (Gdx.input.justTouched()) ModelInstance Instance new ModelInstance (model) Instance.transform.setToTranslation(Gdx.input.getX(),Gdx.input.getY(), 0) DataBase.array.add(Instance) Gdx.graphics.requestRendering() camController.update() Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT GL20.GL DEPTH BUFFER BIT) modelBatch.begin(cam) for (ModelInstance instance DataBase.array) modelBatch.render(instance, environment) modelBatch.end() fps.log() Override public void dispose() modelBatch.dispose() model.dispose() Override public void resize(int width, int height) Override public void pause() Override public void resume() The DataBase.array is simply an ArrayList. What am I doing wrong? Any help would be really appreciated thanks!


Is Table the only layout that I can use in libgdx? I'm looking for the common way to handle the layout in libgdx. I searched google and found only table layout. Meanwhile I don't use any layout and just insert coordination into each visual object but I think that this is not the proper way to do it... Is their any other layout that I can use? p.s The game layout should split into two parts, left is smaller that the right and contains things like score time and info about stuff in the game. The right part will display the game play itself


ECS should everything be a system? I've just recently started working with LibGDX and Ashley, and I find it to be really useful and I like working with the whole entity component system workflow. But I've been starting to layout the GUI and other aspects of the interface that dont exactly, to me, seem like they should be entities. When using an ECS should EVERYTHING in your game be an entity with components a system to control them?


Libgdx change velocity of moveTo action I am trying to create physics for a ball in Libgdx. The ball starts moving after a pan and everytime the ball collides with a wall, a moveTo action is added to it. But my ball moves with a constant velocity (action time distance velocity). I want my ball movement to get slower smoothly. Here is my method for calculating velocity private float velocity(float panDistance) float coefficent 0.3f return panDistance coefficent in act method of the Ball I decrement velocity Override public void act(float delta) super.act(delta) if (velocity lt 100 amp amp velocity gt 0) ballImage.clearActions() velocity 3f delta When gesture detector detects a pan the method below is called. public void moveTheBall(float tanX, float tanY) if (ballImage.getActions().size 0) motionVector (int) (tanX Math.abs(tanX)) motionAngleTan tanY tanX panDistance (float) Math.sqrt((tanX tanX) (tanY tanY)) velocity velocity(panDistance) recursivelyAddActions(motionVector) in recursivelyAddActions() method private void recursivelyAddActions(int vectorDirection) AFTER SOME CALCULATIONS distance (float) Math.sqrt(((predictionX ballStartingPosX) (predictionX ballStartingPosX)) ((predictionY ballStartingPosY) (predictionY ballStartingPosY))) moveToAction Actions.moveTo(predictionX, predictionY, distance velocity) ballImage.addAction(moveToAction) this is not smooth and this does not work good. I need an advice to make this work better. Thank you.


LIBGDX fadeout, hide and remove action not triggered I try to execute an sequence of actions, but fadeout and following are not working for me. I can see the actor moving to the desired point, but after that it just stays there. My code. personActor is an Actor of a list in my mainactor SequenceAction sequence new SequenceAction() sequence.addAction(Actions.moveTo(0, 300)) sequence.addAction(Actions.moveTo(1000, 300,3f)) sequence.addAction(Actions.fadeOut(0.5f)) sequence.addAction(Actions.hide()) sequence.addAction(Actions.removeActor()) personActor.addAction(sequence) The main actor loops through the list of childactors Override public void draw(Batch batch, float parentAlpha) super.draw(batch, parentAlpha) for(PersonActor personActor personenActors) personActor.draw(batch,parentAlpha) Do someone see, whats wrong here ?


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.


Setting resizable to false in LibGDX I have a small working game prototype. I want to do something like LwjglApplicationConfiguration cfg new LwjglApplicationConfiguration() cfg.resizable false But I get "LwjglApplicationConfiguration cannot be resolved to a type" What can I do? Or is there a different method? Thanks.


Is there a way to use the facebook sdk with libgdx? I have tried to use the facebook sdk in libgdx with callbacks, but it never enters the authetication listeners, so the user never is logged in, it permits the authorization for the facebook app but it never implements the authentication interfaces ( Is there a way to use it? public MyFbClass() facebook new Facebook(APPID) mAsyncRunner new AsyncFacebookRunner(facebook) SessionStore.restore(facebook, this) FB.init(this, 0, facebook, this.permissions) Method for init the permissions and my listener for authetication public void init(final Activity activity, final Facebook fb,final String permissions) mActivity activity this.fb fb mPermissions permissions mHandler new Handler() async new AsyncFacebookRunner(mFb) params new Bundle() SessionEvents.addAuthListener(auth) I call the authetication process, I call it with a callback from libgdx public void facebookAction() TODO Auto generated method stub fb.authenticate() It only allow the app permission, it doesnt register the events public void authenticate() if (mFb.isSessionValid()) SessionEvents.onLogoutBegin() AsyncFacebookRunner asyncRunner new AsyncFacebookRunner(mFb) asyncRunner.logout(getContext(), new LogoutRequestListener()) SessionStore.save(this.mFb, getContext()) else mFb.authorize(mActivity, mPermissions,0 , new DialogListener()) public class SessionListener implements AuthListener, LogoutListener Override public void onAuthSucceed() SessionStore.save(mFb, getContext()) Override public void onAuthFail(String error) Override public void onLogoutBegin() Override public void onLogoutFinish() SessionStore.clear(getContext()) DialogListener() Override public void onComplete(Bundle values) SessionEvents.onLoginSuccess() Override public void onFacebookError(FacebookError error) SessionEvents.onLoginError(error.getMessage()) Override public void onError(DialogError error) SessionEvents.onLoginError(error.getMessage()) Override public void onCancel() SessionEvents.onLoginError("Action Canceled")


score displaying system without using bitmap how to make a score displaying system without using bitmap in libgdx. I making a fluppy bird remake somone can explaim me in details?


How do I scale and rotate around different points in Libgdx? I'm using a SpriteBatcher to rotate and scale a TextureRegion in libGDX. I'd like to rotate the texture around an origin outside of the region, but have the texture scaled around the region's center. As far as I'm aware, this has to be performed in one action in the SpriteBatcher.draw() method. The region is scaled to the correct size, but scaled away from the origin. I could compensate by adjusting the origin location, but is there a better method?


If filled polygon cannot be drawn via libgdx ShapeRenderer , then what is the work around? I know most of you would suggest me to draw a filled polygon by using combination of triangles and rectangles , but that is not possible for complex shapes . I want to basically draw a generic shape on screen , here it is The above shape needs to be drawn in generic form , i.e the width of each trapezium's upper edge is fixed . the lower edge of the overall compound shape is a constant unit greater than upper edge. this whole compound shape can have arbitrary length and thus number of individual trapeziums that compose the compound shape is not fixed. I wish to draw each colored trapezium as a filled polygon . Is there any way of achieving this


Label does not maintain correct position within a Table I'm hoping the fix is quite simple, but this has become increasingly frustrating. I've built a minimally reproducable example. This is how the table is rendered And this is the corresponding code private Table testTable() Table table new Table() Skin skin new Skin(Gdx.files.internal("skin uiskin.json")) Label label1 new Label("String", skin) Label label2 new Label("Hello", skin) Label label3 new Label("World", skin) table.add(label1) table.row() table.add(label2).width(100).height(100) table.add(label3).width(200).height(200) table.setFillParent(true) table.debugAll() return table As you can see, the "Hello" and "World" labels are not centered within their logical tables. Further, even if I try .width(100).height(100).center(), or even .bottom().right(), for example, the two labels' positions are always fixed to the left, center of their logical table. The only way I could 'fix' the problem is by excluding the .width().height(), but I need them for my UI. Any thoughts?


Implementing an Asset Lifecycle I'm currently developing a game using Kotlin and LibGDX. But this Question should be Framework Engine agnostic. Given I have a Screen class like this class MyScreen Screen private val assetManager AssetManager() private var anyTexture Texture? null override fun show() assetManager.load(" ... anyTexture.png", Texture.class) anyTexture assetManager.get(" ... anyTexture.png", Texture.class) override fun render(delta Float) do rendering override fun dispose() assetManager.unload(" ... anyTexture.png", Texture.class) anyTexture null Every Screen I have manages it's own assets. How would I achieve the same Lifecyle of my assets without using the nullable Type for every asset in the Screen? My Goal is just load all assets when the screen is loaded and then unload them when the game switches to another Screen. Has anybody got an idea for implementing this?


Algorithm for 2d AI aiming to compensate for gravity In a 2d side view scenario I have two riflemen aiming at each other. By normalizing the x and y difference they know the direct path to the enemy. However, gravity will pull the projectiles downwards, so aiming straight for the enemy is obviously useless. Any interesting ideas for AI logic when it comes to adding a correction based on world.gravity (which is a "force" in y pixels per physics tick) and enemy.path (libgdx Vector2 with the X and Y difference to the enemy. Weapon.muzzleVelocity could also be factored in (double, speed in pixels after the shot is fired. I've been thinking of two things Option 1 Magic numbers The X distance is multiplied by a magic number (such as gravity) to produce a reasonable close result to an aiming offset. Possibly also factoring in Y distance, but in most cases, the Y distance should be close to 0. Pros Simple, easy to implement, quick, low calculation overhead Cons Boring, A bit too arcade for my taste with a very static result, Been done before countless times including by me in previous projects Option 2 Firing table AI trial and error, basically. Each time the unit fires, the X (and Y?) distance of that shot is recorded with the offset used, and the result (hit vs too low vs too high) is registered. Each time the unit fires it'll look up for the closest match to the x distance to get a rough estimate on aiming offset. Pros Units become more valuable as they learn, it's a lot more modern, and it makes sense to me. Cons Unit types with low rate of fire will not have much use of their firing table. It's also somewhat complex to implement and will cause a much larger memory footprint as the firing table grows. For the record, I'm writing this in java libgdx, mainly targetting the android and HTML5 platforms, but if it turns out to be decent, ports are expected. I'd love to hear other ideas for how a unit can come up with an aiming offset, as well as pros cons. I have to pick something, and I'm not entirely convinced either of my own algorithms are right for the task.


Dynamic length increment of of an object LibGdx I want to implement something in my LibGdx game, where a small stick is positioned vertically.On tap,I have to increase the length of the stick with tap frequency.Later I want to rotate,perform collision and do all those things that a sprite can do.It is an advanced form of fly Swatter game. I am wondering how can I do it.I found some ways.But I am not sure it will work nicely. 1.Creating an array of small sticks and adding it to the base stick to increase the length.(Rotating array of object at a time is difficult,I know.) 2.Scale the image to increase the size of the stick. Important thing is that this stick and rotation is an super important event in my game. I only have experience of a simple running in LibGdx. It would be very helpful if experienced persons give some ideas to implement this game in LibGdx.


How to add slowmotion effect in libgdx I want to add slow motion effect with a collision as a trigger. So I want to have an effective way to trigger a slowmotion effect on bodies as well as sprites that can be caled in the update method. Can anyone please help me with this or provide a link as to where I can find the answer?


How to create a Pixmap from an OrthographicCamera in LibGDX I am trying to create a picture based on what one of my OrthographicCamera can see. LibGDX has a ScreenUtils class that has a getFrameBufferPixels method, but it does not what I want as I want to get only what one camera sees, not the whole screen.


Switching Screens without initializing them every time I have a UI with four Screens (all extending a "main Screen") that users switch between very frequently, at the moment I am switching Screens using g.setScreen(new screen) , but this leads to the problem that I have to reload and initialize everything inside the Screen every single time, which is causing memory leaks. Is there some way I can save the Screens in memory and just load them without having to re initialize everything inside them? Or is this bad? Because my current approach is not going to cut it. I was thinking something like initializing all Screens on startup and saving them in an array, then just loading the Screen I need from that array when I need it, ie g.setScreen(screenArray.get(nextScreen)) . Is this a viable approach? Please any advice you can give will help, really need help with this.


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)


LibGDX how to make sizeToAction relative to other corner than bottom left? I'm trying to resize a widget inside a Table. It's a fullscreen widget and when Android Keyboard comes out, the widget is resized so it fits half of the screen from the top. SizeByAction works from the left bottom corner so it resizes the widget down, and I have to resize it up. For now I use a hack with a parallel action and I change it's size and POSITION in the same time so it looks like a want (like it was staying in the left top corner all the time). I know there's a originX and originY but they're used to rotation, not resizing elements. If someone did something like this before without a hack like mine, I would be grateful for a tip! ) How does the widget look like? It's a fullscreen widget How does it look after resize? How I want it to look like? I want it to rezise relative to it's left up corner