LibGDX limit the PerspectiveCamera for a FPS view I'm using LibGDX and I'm trying to implement a FPS camera into my game. I'm not using the FirstPersonCameraController for multiple reasons I don't want to touch to roll (only yaw and pitch), with this camera when looking on sides the horizon goes up and down like waves (meaning that the roll is changing) I don't want dragging, I want the camera to always move with the mouse. I want movements to stay consistent whatever the player is looking at. I don't want it to go slower even if he looks at the ground. So I've come up with this which does pretty much what I want Override public boolean mouseMoved(int screenX, int screenY) float deltaX (mousePos.x screenX) sensitivity float deltaY (mousePos.y screenY) sensitivity Vector3 tmpAxis game.getGame().getPool().obtain(Vector3.class) game.getCamera().rotate(Vector3.Y, deltaX) tmpAxis.set(game.getCamera().direction.z, 0, game.getCamera().direction.x) game.getCamera().rotate(tmpAxis, deltaY) if(game.getCamera().up.y lt 0) game.getCamera().up.y 0 mousePos.set(screenX, screenY, 0) game.getGame().getPool().free(tmpAxis) return true However, I have an issue described by the commented lines. When the camera goes to low or too high (when the y value of the up vector become negative), the rotation is reversed and the rotation starts to make it come back. In pratice, it just flickers a lot and when I try to go back, I have 1 2 chance of going back normally, and 1 2 chance of looking backward with my camera reversed (if the up vector is negative). So naturally, what I want is to lock the movement so It can never look pass his feets or pass the sky. Locking the up vector is easy, I just have to prevent it from going negative but I need to replace the direction vector also. However, I don't know how to "replace" the direction vector. I search on google for how to set the camera rotation or just how to get it and didn't found anything convincing. I've just tried also adding game.getCamera().direction.y 1f to my commented if to make it look down when getting past the point I don't want it to get past. However, I found out the direction vector isn't normalized and that's really confusing.


Tiled object layer draw sprites I added some tiles to some object layers in my tiled map and now I want to draw them in game. I tried to render everything with mapRender.render() but the tiles doesn't show up. Then I tried to render just one object layer and all of its objects with mapRenderer.renderObjects(tiledMap.getLayers().get(0)) but it wasn't working. Ingame Tiled Could someone please tell me how to make the tiles show up? Thank you very much!


Translating ChainShape to world coordinates according to touch drag input I'm trying to draw a ChainShape according to touch screen coordinates, however the coordinates are slightly off from my touch coordinates. I translate the chain drawn on the screen to world coordinates but don't think I've done it correctly. I tried setting the shape's position to the first vertex but it positions it even further from the original touch coordinates. Can someone please help me understand where I'm going wrong? public class Play implements Screen private static final float TIMESTEP 1 60f private static final int VELOCITYITERATIONS 8, POSITIONITERATIONS 3 private Box2DDebugRenderer debugRenderer private OrthographicCamera camera private PolygonSpriteBatch batch private World world private List lt Float gt chain verts new ArrayList lt Float gt () private float chain Override public void show() world new World(new Vector2(0f, 9.81f), true) debugRenderer new Box2DDebugRenderer() camera new OrthographicCamera() batch new PolygonSpriteBatch() InputProcessor input 0 new GestureDetector(new Gesture() ) Override public boolean touchUp(float x, float y, int pointer, int button) if (chain verts.size() ! 0) chain new float chain verts.size() for (int i 0 i lt chain verts.size() i ) chain i chain verts.get(i) System.out.print(chain i " ") ChainShape chainShape new ChainShape() chainShape.createChain(chain) Vector3 mouse new Vector3() camera.unproject(mouse.set(Gdx.input.getX(), Gdx.input.getY(), 0)) BodyDef bodyDef new BodyDef() bodyDef.type BodyType.StaticBody bodyDef.position.set(mouse.x , mouse.y) FixtureDef fixtureDef new FixtureDef() fixtureDef.shape chainShape world.createBody(bodyDef).createFixture(fixtureDef) chain verts.clear() chainShape.dispose() return super.touchUp(x, y, pointer, button) Override public boolean touchDragged(float x, float y, int pointer) chain verts.add(x) chain verts.add(Gdx.graphics.getHeight() y) return super.touchDragged(x, y, pointer) Gdx.input.setInputProcessor(input 0) Override public void render(float delta) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) world.step(TIMESTEP, VELOCITYITERATIONS, POSITIONITERATIONS) camera.position.set(0, 20, 0) camera.update() batch.setProjectionMatrix(camera.combined) debugRenderer.render(world, camera.combined) Override public void resize(int width, int height) camera.viewportWidth 1200 camera.viewportHeight 800 Override public void pause() Override public void resume() Override public void hide() dispose() Override public void dispose() batch.dispose() world.dispose() debugRenderer.dispose()


Fading in and fading out animations This is how I'm creating my player. Is there any way to start fading in and fading out for an amount of time when I get hit? private Texture tex Game.res.getTexture("player") public Player(Body body) TextureRegion sprites new TextureRegion 1 sprites 0 new TextureRegion(tex, 0, 0, 70, 96) sprites 1 new TextureRegion(tex, 69, 193, 68, 93) animation.setFrames(sprites, 1 6f)


Convert transform from world to local space I have a hierarchical node system. Given a world space transform, I need to obtain the transform for a specific node in local space. My Node class has the following method. public void worldToLocal(Matrix4 world, Matrix4 local) if (dirty) update() local.set(worldInverse).mul(world) worldInverse is the inverse of the node's world transformation matrix. I'm using LibGDX, so this is equivalent to doing LOCAL T 1 WORLD T 1 being the inverse of the node's world transform. However, this doesn't seem to be working correctly. Let's say we have a node at (2, 4, 0) rotated 180 degrees along its Z axis. Node node new Node() node.setPosition(2.0f, 4.0f, 0.0f) node.rotate(new Vector3(0.0f, 0.0f, 1.0f), 180.0f) Now, the point (1, 7, 0) should be (2, 1, 0) in local space for that node. Matrix4 local new Matrix4() Matrix4 world new Matrix4() Vector3 pos new Vector3() world.translate(1.0f, 7.0f, 0.0f) node.worldToLocal(world, local) local.getTranslation(pos) However, I get (1, 3, 0). I'm using this operation to translate from world space Bullet body transforms to local node transforms.


Rotating Sprite Around A Point Without Messing Its Drawing Point I am trying to draw and rotate an arrow sprite based on a point,around a static circle body without messing its drawing starting point. Arrow should be directed to the same direction with user touch point,static body center vector. Let me explain it with an example. This is how i calculate arrow drawing point fun powerIndicatorDownPointCalculator(playerPosition Vector2,touchPosition Vector2,distanceBetweenTouchPointAndPlayer Float) Vector2 player position is static body center,touch position is touch point. val playerPositionHolder playerPosition.cpy() val abVector playerPosition.sub(touchPosition) val normalizedAbVector Vector2(abVector.x distanceBetweenFingerAndPlayer,abVector.y distanceBetweenFingerAndPlayer) Gdx.app.log("normalized ab vector",normalizedAbVector.toString()) var pointToAddX 90 normalizedAbVector.x var pointToAddY 90 normalizedAbVector.y var newPointX playerPositionHolder.x pointToAddX var newPointY playerPositionHolder.y pointToAddY Gdx.app.log("NEW POINT", Vector2(newPointX,newPointY).toString()) return Vector2(newPointX,newPointY) Here is a simple gif showing it https i.ibb.co TvHBMh9 MNML November19 041320 AM.gif This is how i calculate C point to use later on rotation(?) fun calculateAimingPoint(playerPosition Vector2,touchPosition Vector2) Vector2 playerPosition is staticbody center val abVector playerPosition.sub(touchPosition) val secondPos blackBody.position.cpy() val cPointPosition secondPos.add(abVector) return cPointPosition This is what i wrote for rotation but for sure it is wrong since not working as i wanted var angle atan2(aimingPoint.y blackBody.position.y, aimingPoint.x blackBody.position.x ) 180 PI aiming point is C point, blackBody is static body if (angle gt 90) angle 450 angle else angle 90 angle powerIndicator.setOrigin(????) setOrigin is for rotation but i dont now what to write here. angle angle 1 powerIndicator.rotation angle.toFloat() What i actually wanna achieve is this https i.ibb.co gDM9H3L MNML November19 042729 AM 2.gif


Nullpointer exception with Scrollpane in LIBGDX I get a strange Nullpointer exception and I don't understand why. Can someone help me ? Exception Exception in thread "LWJGL Application" java.lang.NullPointerException at com.badlogic.gdx.scenes.scene2d.ui.ScrollPane.draw(ScrollPane.java 583) at com.badlogic.gdx.scenes.scene2d.Group.drawChildren(Group.java 123) at com.badlogic.gdx.scenes.scene2d.Group.draw(Group.java 57) at com.badlogic.gdx.scenes.scene2d.ui.WidgetGroup.draw(WidgetGroup.java 163) at com.badlogic.gdx.scenes.scene2d.ui.Table.draw(Table.java 119) at com.solvapps.tests.NewStoryBook.draw(NewStoryBook.java 40) My Code ACTOR public class NewStoryBook extends Actor Table table ScrollPane pane Table tableScroller public NewStoryBook(Skin skin) int w Gdx.graphics.getWidth() int h Gdx.graphics.getHeight() table new Table() table.setPosition(400, 400) table.setSize(w 3, h 0.8f) tableScroller new Table() tableScroller.add(new Label("bla bla",skin)) pane new ScrollPane(tableScroller) table.add(pane) Override public void draw(Batch batch, float parentAlpha) super.draw(batch, parentAlpha) table.draw(batch, parentAlpha) My Code App public class StoryBoxTest4 extends ApplicationAdapter private Stage stage NewStoryBook newstoryBook public void create() stage new Stage(new ScreenViewport()) Skin skin new Skin(Gdx.files.internal(SkinManager.getSkin())) newstoryBook new NewStoryBook(skin) stage.addActor(newstoryBook) Gdx.input.setInputProcessor(stage)


Implementing Scrolling Background in LibGDX game I am making a game in LibGDX. After working for whole a day..I could not come out with a solution on Scrolling background. My Screen width n height is 960 x 540. I have a png image of 1024 x 540. I want to scroll the background in such a way that it contuosly goes back with camera x as per camera I tried many alternatives... drawing the image twice ..did a lot of calculations and many others.... but finally end up with this dirty code if(bg x2 gt Assets.bg.getRegionWidth()) calculated it to position bg .. camera was initially at 15 bg x2 (16 4 camera.position.x) bg x1 bg x2 Assets.bg.getRegionWidth() else bg x1 (16 4 camera.position.x) 224 this 16 is not proper I think there can be other ways bg x2 bg x1 Assets.bg.getRegionWidth() drawing twice batch.draw(Assets.bg, bg x2, bg y) batch.draw(Assets.bg, bg x1, bg y) The Simple idea is SCROLLING BACKGROUND WITH SIZE SOMEWHAT MORE THAN SCREEN SIZE SO THAT IT LOOK SMOOTH. Even after a lot of search, i didn't find an online solution. Please help.


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!!


When setting Stage as inputProcessor, Shaperenderer shapes are drawn stretched I am working on making a falling sand simulation using libgdx. For drawing the individual elements I am using a ShapeRenderer and drawing rectangles. I have begun to implement a dropdown menu to allow selection of elements to place. The functionality of the dropdown menu is working. I am able to set the inputProcessor as the stage and upon selecting the element type set the inputProcessor back to CreatorInputProcessor and I am able to successfully place elements again. The functionality is all working as expected. However, when I set the stage with the dropdown as inputProcessor, the element rectangles become stretched. The resolution and pixel width of the window stays the same. It is not zooming in or anything. When the inputProcessor is set back to the CreatorInputProcessor the rectangles stay stretched. Here are the things I have tried to fix this issue Use every kind of ViewPort passing in both a new OrthographicCamera and also the same camera used for the game view Disposing of the stage after input processor is set back to CreatorInputProcessor Setting the projection matrix on the camera every frame just before drawing or after drawing. I found this stack exchange question which is similar to my issue but the marked answer does not solve my problem (setting the projection matrix every frame) LibGDX why are the shapes from my ShapeRenderer resizing with my viewport? I am looking for some advice on how I can resolve this issue. Thanks! Here is the relevant code snippet https github.com DavidMcLaughlin208 FallingSandJava blob master core src com gdx cellular InputManager.java L357 L399


Libgdx animation for HTML5 I'm working on my first html5 game with libgdx, it's a platform android game that I made a while back that I now want to host on my website. Everything has been going okay till I got to animating the character. The desktop and android versions of the game run just fine but with the html version the game doesn't run and I get the following error GwtApplication exception Couldn't find type for class 'com.badlogic.gdx.graphics.g2d.TextureAtlas AtlasRegion' When I comment out the code sections for the animation the game runs fine (with the character not animated). What's causing the error and how can I fix it?


LibGDX Scrollpane won't scroll to bottom after adding children to contained table To my game I want to add a gui element that displays text and textButtons whenever something is happening or it wants you to make a decission (an answer while talking to a person for example). To keep track of your actions you shall be able to scroll it. Similar to text adverntures or dialog boxes in rpgs. I use Scene2Dui for my GUI, so I put a scrollPane in my GUIs root table. I have methods for adding stuff to the contained table and tell the scrollPane to scroll to the bottom. In general the idea works, but the thing doesn't scroll to the bottom but only to the bottom of the element I added before the current one. I'm puzzled. Here's the code, leaving out the skins and styles part public class TextBox ScrollPane box Table table Label.LabelStyle lStyle Skin skin TextBox() table.setFillParent(false) box new ScrollPane(table, scrollStyle) box.setScrollingDisabled(true, false) box.setOverscroll(false, false) box.setFillParent(false) table.align(Align.topLeft) table.row() void writeDecissions(GameEvent events) Table tableD new Table() tableD.setFillParent(false) if (events ! null) for (int i 1 i lt events.length i ) if (events i ! null) String s Character.forDigit(i, 10) " " events i .getDecision() TextButton button new TextButton(s, style) button.getLabel().setWrap(true) button.getLabel().setAlignment(Align.left) tableD.add(button).width(box.getWidth() 40).spaceBottom(20).spaceTop(20) tableD.row() table.add(tableD).align(Align.left).pad(20) table.row() box.setScrollY(table.getHeight()) This is the way I test it public void render(float delta) Gdx.gl.glClearColor(0, 0, 0, 0) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) stage.act() stage.draw() if (Gdx.input.justTouched()) gui.textBox.writeDecissions(events) I tried box.setScrollY(box.getMaxY) as well as setting overscroll to true (don't really know what that is tough). With the same result. Finally a screenshot Help appreciated.


How can I draw things just in an area that can have a shape such as the shape of the letter B and not draw outside this form? I want to draw stuff on an image, for Example, if I have a letter, as an image and I want to draw on the letter it is necessary that this image is touchable. This is what I did Image.addListener (new clickListener () public boolean Touchdown (InputEvent event, float x, float y, int pointer, int button) posCurseurX x posCurseurY y Begin to draw on the screen touch true traitSprite new Sprite (rectangleTexture, 0.0, tailleTrait, tailleTrait) traitSprite.setPosition (x tailleTrait 2 (height) y tailleTrait 2) tabRectangelSprite.add (traitSprite) counter dessinerTrait (touch) dessinerCurseur () The index of the number of meter rectangle forming a line return true ) But I want to add another listener for mouse movements, but it does not work with MouseMove. and the other thing I would like, is to draw that if I'm on my image. If the cursor position is not between the coordinates of the image so I will not draw. that's what I tried if (posCurseurX gt image.getX posCurseurX amp amp lt image.getX image.getWidth) .. But the texture does not necessarily have that width, that's an example


Libgdx Using an AssetManager in every Screen or use a single AssetManager in Game class I have a HexGame class extending Game and various Screens that receive the game object in their constructor. I was thinking of having one AssetManager in the game class and using it to load the necessary assets in each screen's constructor and unload them in the screen's dispose method. The alternative would be to use a new AssetManager in every screen. What would be best practice?


object array positioning LibGdx In my game,if I touch a particular object,coin objects will come out of them at random speeds and occupy random positions. public void update(delta) if(isTouched() amp amp getY() lt Constants.WORLD HEIGHT 2) setY(getY() (randomSpeed delta)) setX(getX() (randomSpeed 4 delta)) Now I want to make this coins occupy positions in some patterns.Like if 3 coins come out,a triangle pattern or if 4 coins, rectangular pattern like that. I tried to make it work,but coins are coming out and moved,but overlapping each other.Not able to create any patterns. patterns like This is what I tried int a Math.abs(rndNo.nextInt() 3) 1 no of coins int no 0 float coinxPos player.getX() coins 0 .getWidth() 2 float coinyPos player.getY() int minCoinGap 20 switch (a) case 1 for (int i 0 i lt coins.length i ) if (!coins i .isCoinVisible() amp amp no lt a) coins i .setCoinVisible(true) coinxPos coinxPos rndNo.nextInt() 70 coinyPos coinyPos rndNo.nextInt() 70 coins i .setPosition(coinxPos, coinyPos) no break case 2 for (int i 0 i lt coins.length i ) if (!coins i .isCoinVisible() amp amp no lt a) coins i .setCoinVisible(true) coinxPos coinxPos minCoinGap rndNo.nextInt() 70 coinyPos coinyPos rndNo.nextInt() 150 coins i .setPosition(coinxPos, coinyPos) no break ...... ...... default break may be this is a simple logic to implement,but I wasted a lot of time on it and got confused of how to make it work. Any help would be appreciated.


LibGDX Scene2D ScrollPane I want to create a list of buttons with ScrollPane , but I cant create a ScrollPane . In the constructor method in the examples Skins are used (.atlas , .json files) but how to create these files? Skin skin new Skin(Gdx.files.internal("data uiskin.json")) Is there a program to generate this json ? As I noticed a lot of Scene2D elements need skins.


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?


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.


Why it takes some time to update the sprite draw order in libgdx SortedIteratingSystem? I have a rendering system that extends SortedIteratingSystem and created a comparator to sort the sprite draw order. But the problem is when I update the z index, it takes some time before it changes the order. public class RenderingSystem extends SortedIteratingSystem public RenderingSystem() super(Family.all(...components).get(), new ZComparator()) private static class ZComparator implements Comparator lt Entity gt Override public int compare(Entity e1, Entity e2) return (int)Math.signum(Mappers.index.get(e1).z Mappers.index.get(e2).z) IndexComponent implements Component public int z 0


Using Delta for a stopwatch, delta too fast than real time seconds I search for methods to create a stopwatch on libgdx and came across with this public void trigger(float delta) playTime delta playTimeRounded ((double)Math.round(playTime 100) 100) Gdx.app.log("deltaTime", delta "") But its not accurate and its much faster. How can i create an accurate stopwatch?


Drawing Sprites Depending On Mouse Position (LibGDX) I'm making a small game where you play as a turret in the middle of the screen trying to shoot the enemies coming after you. I am having difficulties, however, in trying to figure out how to make the turret change sprites depending on where my mouse cursor is pointing. I don't want to rotate the sprite, mind you, as I already have made different variations of the same sprite for the different directions it will face I have an idea of how to accomplish this, but I don't know how to make it happen The program generates 42 rays, (one for each turret sprite), that originate from the turret If the cursor falls between two of those rays, a specific sprite will be drawn How would I go about doing this? It doesn't have to be the method described above as long as it produces the same result. Thanks for your help in advance! Plug


How do I convert screen coordinates to isometric tile map coordinates in libGDX using matrices I know this has been asked many times but my question doesn't quite fit the others. I have an IsometricTiledMap and I need to get the tile under a set of screen X and Y coordinates. Here is a picture of my game I need to get the tile that the player is standing on. I need to convert screen coordinates to isometric tile coordinates and the way that seemed the easiest was by using a matrix as described here http www.alcove games.com advanced tutorials isometric tile picking comment 56390 Unfortunately I have no idea how to change that code to fit a 128x64 tile instead of a 1.0x.5 tile. Here is my code isoTransform new Matrix4() isoTransform.idt() isoTransform.translate(0.0f, 32f, 0.0f) isoTransform.scale((float) (Math.sqrt(2.0) 2.0), (float) (Math.sqrt(2.0) 4.0), 1.0f) isoTransform.rotate(0.0f, 0.0f, 1.0f, 45.0f) invIsotransform new Matrix4(isoTransform.inv()) touch vector touch new Vector3() Override public boolean touchDown(int screenX, int screenY, int pointer, int button) touch.set(screenX, screenY, 0) touch gameCamera.unproject(touch) touch.mul(invIsotransform) pickedTileX (int)touch.x 64 pickedTileY (int)touch.y 32 debug(touch.x " " touch.y) debug(pickedTileX " " pickedTileY) return false I think the problem is in this line isoTransform.scale((float) (Math.sqrt(2.0) 2.0), (float) (Math.sqrt(2.0) 4.0), 1.0f) but I'm not sure what to change.


libgdx UI coordinate consistency in a scaled window I'm having an issue that I'm sure boils down to something simple that I've missed The UI Graphics can't handle a window resize. Either the graphics get stretched, or the placement is incorrect. For now I'm working with just one UI element consisting of a Sprite, until i've gotten the project to render properly. Its position is defined in a Settings class when the asset is loaded touchpadBG new Sprite(assets.get("ui joystick background.png", Texture.class)) touchpadBG.setCenter(Settings.touchpadPositionX, Settings.touchpadPositionY) ... and drawn like so batch.setProjectionMatrix(gameCam.combined) batch.begin() Draw the gameworld. This is done without any issues. batch.setProjectionMatrix(uiCam.combined) touchpadBG.draw(batch) batch.end() uiCam is defined like this this.uiCam new OrthographicCamera(Settings.windowSize X, Settings.windowSize Y) uiCam.translate(Settings.windowSize X 2, Settings.windowSize Y 2, 0) uiCam.update() uiViewport new FitViewport(Settings.windowSize X, Settings.windowSize Y, uiCam) uiViewport.apply() I've experimented with different viewports (and no viewport), and while correct placement happens at first, resizing the window will result in the UI element being drawn in the wrong position, stretched, or both. I then suspected my resize update methods being off, but I can't find anything wrong public void resize(int w, int h) uiViewport.update(w, h) update() public void update() aspectRatio (float)Gdx.graphics.getHeight() (float)Gdx.graphics.getWidth() uiCam.update() gameCam.update() Any ideas where I'm going wrong with this? If my post is missing a relevant part of my code, leave a comment, and I'll edit it in.


how to set volume of sound depending on the impulse a body receives in Libgdx Box2d? I am trying to set the volume of a bouncing sound of a ball depending on how hard the ball hits something. so the harder the ball hits a wall or a ground the more loud the bounce sound. I couldn't find anyway to get the impulse of a body other than the postSolve(Contact contact, ContactImpulse impulse) method inContactListner class. But i then realized that unlike the beginContact(Contact contact) method, postSolve(Contact contact, ContactImpulse impulse) gets called repeatedly until the contact ends. so it repeatedly plays the bouncing sound making it sound stalked and buggy. I cant use the beginContact(Contact contact) method because there is no way to get the impulse that the ball is receiving from this method. I tried to to use the velocity of the ball instead of impulse inside beginContact(Contact contact)but that didnt yield good results and found it very complicated as i had to consider both horizontal and vertical speeds. so my question is how can I make the sound play only once if i am using the postSolve(Contact contact, ContactImpulse impulse) method or is there any other solution to achieve what i am trying to do here?


Unable to draw single particle effect at two places I am using Libgdx ParticleEffect to draw a fire particle effect . The issue I have is that when I try to render a ParticleEffect at two different locations within single game loop, only the last draw call has the effect drawn on screen. I update the Particle effect only once per game loop but set its position to two distinct locations and draw it. Is this a trivial problem with Libgdx ParticleEffect ParticleEffect effect new PartcleEffect() effect.load(gdx.files.internal("data effect.particle"),atlas,"") effect.start() In render effect.update(deltaTime) effect.setPosition(x1,y1) effect.draw(batch) effect.setPosition(x2,y2) effect.draw(batch) Can someone tell me why it isn't working?


LibGDX why are the shapes from my ShapeRenderer resizing with my viewport? I have created a class called Node which I would like to (currently) contain a single Actor (later I will be adding additional actors, but for now I'm sticking with just one). The actor is called "body" and is just a container for the position size of the "Node" actor. I have also created a Label which I am drawing with a custom font file. What I am having issues with is that when I RESIZE my app window (on desktop, I'm not currently using Android or any other targets), the LABEL works just fine (stays the same size on my screen), but the Node gets resized with the main window. That is, if I make the window twice as wide, the square stretches to be twice as wide as it was before. Why is this? The coordinates I am using work exactly as I expect UNTIL I resize the screen. Is there something else I have to do in the resize() method? App class public class App implements ApplicationListener private Stage stage private ShapeRenderer shapeRenderer Override public void pause() Override public void resume() Override public void create() stage new Stage(new ScreenViewport()) shapeRenderer new ShapeRenderer() FONT stuff https github.com libgdx libgdx wiki Gdx freetype FreeTypeFontGenerator generator new FreeTypeFontGenerator(Gdx.files.internal("fonts arial.ttf")) FreeTypeFontGenerator.FreeTypeFontParameter parameter new FreeTypeFontGenerator.FreeTypeFontParameter() parameter.color Color.ORANGE parameter.size 24 BitmapFont arialFont generator.generateFont(parameter) generator.dispose() Skin skin new Skin() Label.LabelStyle labelStyle new Label.LabelStyle() labelStyle.font arialFont skin.add("default", labelStyle) Label label new Label("DOOT", skin) label.setX(110.5f) label.setY(110.5f) stage.addActor(label) stage.addActor(new Node(shapeRenderer)) Override public void resize(int width, int height) See below for what true means. stage.getViewport().update(width, height, true) shapeRenderer.updateMatrices() System.out.println("" width "x" height) Override public void render() Gdx.gl.glClearColor(0.3f, 0.3f, 0.3f, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) stage.act(delta) stage.draw() Override public void dispose() stage.dispose() Node class public class Node extends Group private Actor body private ShapeRenderer shapeRenderer public Node(ShapeRenderer sr) body new Actor() body.setBounds(10.0f, 10.0f, 100.0f, 100.0f) shapeRenderer sr Override public void draw(Batch batch, float parentAlpha) super.draw(batch, parentAlpha) shapeRenderer.begin(ShapeRenderer.ShapeType.Line) shapeRenderer.box(body.getX(), body.getY(), 0.0f, body.getWidth(), body.getHeight(), 0.0f) shapeRenderer.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 resize animation in libgdx? I want to draw an animation, the size of each frame is 500x500px but when I try to resize, the animation seems to rotate... Here the code to load frames and create animation Texture fireSheet new Texture(Gdx.files.internal("fire sheet.png")) TextureRegion fireFrames new TextureRegion 4 fireFrames 0 new TextureRegion(fireSheet,0,0,500,500) fireFrames 1 new TextureRegion(fireSheet,700,0,1200,500) fireFrames 2 new TextureRegion(fireSheet,1450,0,1950,500) fireFrames 3 new TextureRegion(fireSheet,2250,0,2750,500) fireAnimation new Animation(0.5f, fireFrames) In draw method I resize the animation in this way public void draw(Batch batch, float parentAlpha) batch.enableBlending() stateTime Gdx.graphics.getDeltaTime() currentFrame Assets.fireAnimation.getKeyFrame(stateTime, true) batch.draw(currentFrame, getX(), getY(), 200, 200 ) So if I use batch.draw(currentFrame, getX(), getY() ) WORKS!!! But too Big for me 500x500px Instead if I use batch.draw(currentFrame, getX(), getY(), 200, 200 ) Animation doesn't work properly What Can I do? Thank you in advance


Translating ChainShape to world coordinates according to touch drag input I'm trying to draw a ChainShape according to touch screen coordinates, however the coordinates are slightly off from my touch coordinates. I translate the chain drawn on the screen to world coordinates but don't think I've done it correctly. I tried setting the shape's position to the first vertex but it positions it even further from the original touch coordinates. Can someone please help me understand where I'm going wrong? public class Play implements Screen private static final float TIMESTEP 1 60f private static final int VELOCITYITERATIONS 8, POSITIONITERATIONS 3 private Box2DDebugRenderer debugRenderer private OrthographicCamera camera private PolygonSpriteBatch batch private World world private List lt Float gt chain verts new ArrayList lt Float gt () private float chain Override public void show() world new World(new Vector2(0f, 9.81f), true) debugRenderer new Box2DDebugRenderer() camera new OrthographicCamera() batch new PolygonSpriteBatch() InputProcessor input 0 new GestureDetector(new Gesture() ) Override public boolean touchUp(float x, float y, int pointer, int button) if (chain verts.size() ! 0) chain new float chain verts.size() for (int i 0 i lt chain verts.size() i ) chain i chain verts.get(i) System.out.print(chain i " ") ChainShape chainShape new ChainShape() chainShape.createChain(chain) Vector3 mouse new Vector3() camera.unproject(mouse.set(Gdx.input.getX(), Gdx.input.getY(), 0)) BodyDef bodyDef new BodyDef() bodyDef.type BodyType.StaticBody bodyDef.position.set(mouse.x , mouse.y) FixtureDef fixtureDef new FixtureDef() fixtureDef.shape chainShape world.createBody(bodyDef).createFixture(fixtureDef) chain verts.clear() chainShape.dispose() return super.touchUp(x, y, pointer, button) Override public boolean touchDragged(float x, float y, int pointer) chain verts.add(x) chain verts.add(Gdx.graphics.getHeight() y) return super.touchDragged(x, y, pointer) Gdx.input.setInputProcessor(input 0) Override public void render(float delta) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) world.step(TIMESTEP, VELOCITYITERATIONS, POSITIONITERATIONS) camera.position.set(0, 20, 0) camera.update() batch.setProjectionMatrix(camera.combined) debugRenderer.render(world, camera.combined) Override public void resize(int width, int height) camera.viewportWidth 1200 camera.viewportHeight 800 Override public void pause() Override public void resume() Override public void hide() dispose() Override public void dispose() batch.dispose() world.dispose() debugRenderer.dispose()


Handling data logic on libgdx ai state machine or in ashley system? In this below example, I've combined libgdx ashley and AI state machine. Do you think it's a good idea to handle the logic in state machine or stick on handling the data logic on System? public enum TrollState implements State lt Entity gt MOVE AWAY() Override public void enter(Entity entity) Override public void update(Entity entity) PositionComponent position Mappers.position.get(entity) ... Override public void exit(Entity entity) Override public boolean onMessage(Entity entity, Telegram telegram) if (telegram.message 0) Gdx.app.log("Slime", "Waaaah, goo away, big daddy! yummmmmmy") return true return false


How do you handle entity parent child relationship in Ashley ECS? In the below code example, is a parent child relationship of an entities. Now every child should follow its parent position, and the child could be re positioned anywhere. Entity character character is a parent Entity weapon weapon is a child of character Entity gun gun is a parent Entity bullet bullet is a parent Entity bulletShadow shadow is a child of bullet My own solution is to have an OwnershipComponent which has a Entity owner attribute, but there's a doubt in my mind that the components should only have a data. An Entity is a collection of data, if I pass this data to components this could lead to over killing of iteration. So I've changed my mind to use its attribute int flags, this could now be use as an id to reference to child parent relationship. public class OwnershipComponent implements public int ownerId Entity Manager class public void create() Entity character createCharacter() createWeapon(0, 0, character.flags) public void createWeapon(float x, float y, int ownerId) Entity weapon engine.createEntity() weapon.flags generated unique ID from the weapon category OwnershipComponent ownership engine.createComponent(OwnershipComponent) ownership.ownerId ownerId weapon.add(ownership) public Entity getEntityById(int id) return ... I could access now the parent entity by id and transform its child position relatively. Ownership System public void processEntity(Entity entity, float deltaTime) OwnershipComponent ownership Mapper.ownership.get(entity) Entity parent EntityManager.getEntityById(ownership.ownerId)


LibGDX trying to create a matrix of circles I am trying to create a circular stage like so But I can only make a square


Libgdx draw a sprite in top of an isometric tile I have this isometric map and im using IsometricTiledMapRenderer to render the map I have a OrthographicCamera. I know where each tile is in the isometric map, but the isometric map is kinda rotated? So I was wondering how to convert Map Coordinates to Isometric and viceversa? Here I tried to draw a color cube in each tile coordinates.... Thanks in advance, I have been struggling with this for 2 days, and my lack english vocabulary isnt helping with the research, please some one point me to something


Using the same font with different sizes in libgdx I am using BitmapFonts, LabelStyles and Labels for my texts. I want to resize some labels, so i use this. fontType.scale( .6f) LabelStyle style new LabelStyle(fontType, Color.WHITE) titleLabel new Label("Points", style) titleLabel.setColor(Color.RED) titleLabel.x 260 titleLabel.y 310 but when i want to resize another label, all the labels containing that font resize (I create a new LabelStyle). So i resize the label instead of the font, but that doesnt solve the problem, because it doesnt resize the label, any idea?


How can I implement a scrolling text ticker? How can I implement a right to left scrolling text ticker in libGDX (like stock tickers)?


Transition the scale of a sprite I'm new to LibGDX but I am making a menu with some basic animation, I would like to start with a sprite scaled up and then it would transition to the normal size. Is it possible with LibGDX or do I have to use a third party library?


How to draw portion of a sprite in libGDX Let's say i have a sprite like this and i want to draw the lower portion of it, only the yellow color.. Initially the sprite has dimensions 10x10, i want it to be drawn 10x3 Do i have to redimension both the sprite and the texture region to mantain proportion between the two?


Libgdx Sprite is not drawn when generated inside another class I ve built a gameloop where I generate new items depending on the elapsed time and want to place them somewhere on the screen. I use some randomness for the color and coordinates. For better design I want the sprites of these items to be generated by classes that contain additional information on these items. But I figured out that when doing so my sprites won t be drawn. Sprites that are generated explictly inside my loop are perfectly drawn. This is my current gameloop public void loopGame(float delta) Gdx.gl.glClearColor(255, 255, 255, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) timer.addDelta(delta) Gdx.app.debug("Bubbles", "Time " String.valueOf(this.timer.getCurrentTime())) batch.begin() Sprite freeBubble new Sprite(new Texture(Gdx.files.internal("data img bubble black.png"))) freeBubble.setPosition(200, 200) freeBubble.draw(batch) Bubble newBubble this.bubbleFlask.createNewBubble(timer.getCurrentTime()) if (newBubble ! null) bubbles.add(newBubble) Gdx.app.debug("Bubbles", "Created new bubble!") Gdx.app.debug("Bubbles", "Attributes " newBubble) draw all bubbles for (Bubble bubble bubbles) Gdx.app.debug("Bubbles", "Drawing bubble") Sprite bubbleSprite bubble.buildSprite() bubbleSprite.draw(batch) batch.end() The freebubble is perfectly drawn. this.bubbleFlask generates bubbles the way it is supposed to but those bubbles are not drawn inside the for loop. Debugging messages show me that the loop works as it should. So you might guess that bubble.buildSprite() is broken. Here is this method public Sprite buildSprite() Sprite sprite new Sprite() sprite.setTexture(new Texture(Gdx.files.internal("data img bubble black.png"))) sprite.setPosition(300f, 300f) return sprite For the sake of demonstration I placed the same texture file here. What am I missing here?


Why is my sprite displayed offset from its Box2D body? I found out about this using a debug renderer. When the game starts, everything is in order. But when a collision happens, the sprite's rotation is way larger than its body. The sprite and body match when the body is completely horizontal. The sprite's rotation origin seems far distant from where it should be. Here's my code Sprite sprite data.sprite position body.getPosition() sprite.setPosition( position.x sprite.getWidth() 2, position.y sprite.getHeight() 2 ) sprite.setOrigin(position.x, position.y) sprite.setRotation(MathUtils.radiansToDegrees body.getAngle()) As you can see, I am even trying to set center of its rotation with setOrigin without success. How can I fix this?


ShapeRenderer efficiency on games I want to draw a rectangle box to use as a text background for a visual novel library I'm writing, I wanted some flexibility of color and transparency and the ShapeRenderer class seems to fit the need but the doc brings this disclaimer This class is not meant to be used for performance sensitive applications but more oriented towards debugging. If I use it as background the most action on screen would probably be the text scrolling over it. Can someone more experient on the engine tell me if it is viable to use it under those premises, or it is really for debug only?


Polygons and actionlisteners Libgdx I've been browsing these forums for a while now and I nearly always am able to find an answer without having to ask my own question! Such a great community! This is the first time I've been stumped so I hope that someone can help me, I'm just learning libgdx so any help is appreciated I know the code is rough but please be gentle as I'm learning everyday!!! ) I'm trying to create 6 shapes with inputlisteners which eventually will return the index of the shape which will correspond to an answer, but I can only seem to get the last input listener I create to actually fire... public Panel(final int count) this.count count img new Texture("badlogic.jpg") handlerShapeVertices new float 128,30,0,256,256,256 handlerShape new Polygon(handlerShapeVertices) triangle new PolygonRegion(new TextureRegion(img), handlerShapeVertices,new short 0, 1, 2 ) triangleSprite new PolygonSprite(triangle) triangleSprite.setOrigin(img.getWidth() 2,30) triangleSprite.setX(x) triangleSprite.setY(y) triangleSprite.setRotation(count 60) handlerShape.setOrigin(triangleSprite.getOriginX(), triangleSprite.getOriginY()) handlerShape.setPosition(x, y) handlerShape.rotate(count 60) setBounds(x,y, 256, 256) addListener(new InputListener() public boolean touchDown (InputEvent event, float xP, float yP, int pointer, int button) float temp handlerShape.getTransformedVertices() if(resourceManager.getInstance().interSector.isPointInPolygon(handlerShape.getVertices(),0,6,xP,yP)) System.out.println("CLICK INSIDE " count) return true ) I figured the polygon.getTransformedVertices() should work and to check they were correct I drew them in as you can see by the white lines surrounding the polygonsprites however it doesn't seem to and none of the listeners are actually fired when I use that... I'm completely stumped and hope someone has some insight or can point me in the right direction? I don't want someone to write my code for me but a pointer would be greatly appreciated!


Camera Coordinate To Screen Coordinate I want to convert the camera coordinate to screen coordinate. I have asked this question because my camera is 48m wide and 32m high but my screen is 480x320 pixels. So whatever collision point I get those are based on camera. Also I like to mention that my camera set at center of the screen. So I get (0,0) coordinate at middle of the screen. At collision time I put some particle effect but now that particle effect not at correct place in the screen. So someone from community please help.


How to correctly set window size in Libgdx scene2d.ui dialog In my libGDX application I am using the scene2d.ui classes to render my game's GUI. One of the things I render via these classes is a dialog window with a background image set. I have created the uiskin.json file accordingly, and the dialog is shown correctly with the background image. There is one catch however The size of the dialog window is exactly set to fit the text elements, but not more. If not much text is shown on the dialog, then the background image is rendered much smaller than it really is. I can override or hard code the window size by overriding getPrefWidth() and getPrefHeight() in my custom Dialog class. But that does not feel right. My question What is the correct way to set a scene2d.ui dialog with a background image to be as large as that background image, regardless of how much text is being shown?


Sprite wrong position on screen I want to render one sprite on top of another one. I create both sprites using same coordinates and while debuging I can see that they have same position but still one is being rendered beneath another and slightly to the left. Could somebody tell me what am I doing wrong? here is my code where I create sprites Sprite sprite1 new Sprite(new Texture("1.png")) sprite1.setScale(1 PPM) Sprite sprite2 new Sprite(new TextureRegion(...)) sprite2.setScale(1 PPM) sprite1.setPosition(x,y) sprite2.setPosition(x,y) Could it have something to do with scaling? Or maybe the fact that second sprite is created from TextureRegion?


How to create a polygon button in LibGDX? I need to make a button not a standard square shape, but a polygon shape.How to create a polygon button in LibGDX?


Libgdx fbx converter doesn't write meshes to g3dj file LibGDX FBX converter doesn't write meshes nor materials to g3dj file. This happens with blender 2.8 when exporting model to FBX then converting it to g3dj. meshes will result in an empty block. 2.8 blender settings and when converting... g3dj file.. "version" 0, 1 , "id" "", "meshes" , "materials" , "nodes" "id" "Cube", "rotation" 0.707107, 0.000000, 0.000000, 0.707107 , "scale" 10.000000, 10.000000, 10.000000 , "animations" I tried to convert a fbx written with blender 2.76 with these settings... and meshes and materials are written in g3dj file successfully. I'm thinking this has to do with FBX version, but it seems you can't change FBX version in blender 2.8


How do you make a ShapeRenderer always full screen on resize? I have shapeRenderer.setProjectionMatrix(stage.getViewport().getCamera().combined) And I tried to do the following in render() shapeRenderer.rect(0, 0, stage.getViewport().getScreenWidth(), stage.getViewport.getScreenHeight()) Which full screens the ShapeRenderer when I first run my project, but as soon as I resize the window, the rectangle starts to change size and go off screen. I'm using a FitViewport on my Stage, is there any way to make the ShapeRenderer always be full screen?


LibGDX particle emitter rotation I have a libGDX game, in which I'd like to make some ice breath like effect using particles. So far we made a cone like effect. I can obtain and render it on the screen with this. ParticleEffectPool.PooledEffect effect breathPool.obtain() effect.setPosition(x,y) ps.add(effect) But I don't really see any way to rotate the entire particle system in a given direction. Is there any way to achieve this?


render() can't seem to reference my sprite properly This is driving me a little crazy. We use libGDX, working on making a simple side scroller for fun. I've got it switching from screens alright, loading from my main menu into my level one class, which implements screen. public class levelOne implements Screen Don't know if that effects this. When I try to initialize my sprite, my editor (AIDE) highlights it. Gives me an error saying that there is no access to the variable, as it does when you declare something but don't use it. Texture faceTexture new Texture(Gdx.files.internal("faceSprite.png")) faceGuy new TextureRegion(faceTexture, 50, 50, 95, 95) Sprite player new Sprite(faceGuy) I do actually call up the sprite in render() though, batch.begin() Background batch.draw(backGround,0,0,2900,800) Player player.draw(batch) Enemies batch.draw(faceGuy, baddieOnePosition.x, baddieOnePosition.y, 150, 150) batch.end() It doesn't generate an error there, but trying to run it generates a crash. I can do a batch.draw of the texture, but every attempt at doing it as a sprite fails. I have it being initialized in show(), thought maybe making a new method to do so would help, but had the same result. The only way I've managed to make it work was to initialize it in render(), but that not only resets the sprites position multiple times a second, but I expect is also a memory hog. Help!


How can I draw things just in an area that can have a shape such as the shape of the letter B and not draw outside this form? I want to draw stuff on an image, for Example, if I have a letter, as an image and I want to draw on the letter it is necessary that this image is touchable. This is what I did Image.addListener (new clickListener () public boolean Touchdown (InputEvent event, float x, float y, int pointer, int button) posCurseurX x posCurseurY y Begin to draw on the screen touch true traitSprite new Sprite (rectangleTexture, 0.0, tailleTrait, tailleTrait) traitSprite.setPosition (x tailleTrait 2 (height) y tailleTrait 2) tabRectangelSprite.add (traitSprite) counter dessinerTrait (touch) dessinerCurseur () The index of the number of meter rectangle forming a line return true ) But I want to add another listener for mouse movements, but it does not work with MouseMove. and the other thing I would like, is to draw that if I'm on my image. If the cursor position is not between the coordinates of the image so I will not draw. that's what I tried if (posCurseurX gt image.getX posCurseurX amp amp lt image.getX image.getWidth) .. But the texture does not necessarily have that width, that's an example


LibGDX multiple enemies animations Hello everyone i have a question about animating multiple enemies on the screen at the same time. Basically, i figured out how to use the Pool for creating enemies and dispose them after use etc.. All enemies are equal to each other, and all enemies have 3 different animations for creating, moving, destroying. Everything is working fine, but when i have multiple enemies on screen, they are all animating at the same times, even if they were (obviously) created in different times. For example, i create 3 enemies, make them moving on the screen and they all have the same frame.. the animation must be the same for all, but i expected that the time when they change frame should be different. The animations are instantiated inside the Enemy class, so i guess every instance of Enemy must have its own animation. This is how i draw them in the Renderer class private void drawEnemies(float runTime) enemyArrayLen catta.activeEnemies.size for (int i enemyArrayLen i gt 0 ) currentEnemyAnimation catta.activeEnemies.get(i).getCurrentAnimation() batcher.draw( currentEnemyAnimation.getKeyFrame(runTime), catta.activeEnemies.get(i).getX(), catta.activeEnemies.get(i).getY(), catta.activeEnemies.get(i).getWidth() 2.0f, catta.activeEnemies.get(i).getHeight() 2.0f, catta.activeEnemies.get(i).getWidth(), catta.activeEnemies.get(i).getHeight(), 1, 1, 0 ) Enemies are stored in the catta.activeEnemies array. currentEnemyAnimation is a "support" variable in which i put the Enemy in every cicle of the for cicle. This is how i initialize an Enemy public void init(float posX, float posY, int width, int height) this.position.set(posX, posY) this.width width this.height height this.alive true this.enemyRunTime 0 this.creationTime 0.8f this.destructionTime 0.8f this.crea Animation AssetLoader.enemy creaAnimation this.crea Animation.setFrameDuration(this.creationTime 4) this.mo Animation AssetLoader.enemy moAnimation this.des Animation AssetLoader.enemy desAnimation this.des Animation.setFrameDuration(this.destructionTime 4) this.enemyState EnemyState.CREATING ... Maybe it's all a runTime and delta matter?


Lighting shadow casting sprites with box2Dlights I currently have something like this using box2Dlights Ideally, I would like objects casting shadows to be lit, so the object is lit but there is still a shadow cast around it. Right now the object is covered by shadow. I am aware of the soft and softnesslength settings in box2dlights but this is not really what I'm looking for. Softness seems to light up a certain radius from the player rather than just lighting objects. It ends up kind of weird looking So for example in the above picture, I would want the entire grey box to be lit, and none of the area to the left right behind it to be lit. Any thoughts would be appreciated. Thanks


How can I detect touch intensity or pressure via libGDX? How can I detect the intensity of touch pressure in libGDX? For example, low pressure, medium, medium high, high and so on. There are some questions about it but there aren't answers for libGDX.


How can I make my button do something when clicked? I'm trying to create a game with libGDX in Android Studio, and I am struggling with my code to add a command to the program to do something when I press the button. I have added an ImageButton, but now I struggle to get it to do something when I click on it. Here's my code bplay.addListener( new ClickListener() public void clicked(InputEvent event, float x, float y) batch.begin() batch.draw( splash, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ) batch.end() )


How do I switch between the game screen and score screen without redrawing everything? I'm working on a multiplayer game in Libgdx and want to display the scores of say, the top 10 players on the map. The player should be able to checking the scores at any point during the game and return to the game screen (with themselves in the same location they were at earlier), much like pressing Tab during a game of Counter Strike displays the scores. Changing the screen to the score screen is simple enough using setscreen, but how can I return to the previous view without calling a setscreen on the game screen and rendering everything all over again?


GUI scaling Viewport based scaling or individual logic I want to use scene2d for creating a GUI for a libGDX game. In scene2d all sizes are provided in pixel units (instead of percentages). So I wonder what is the best approach to deal with different screen resolutions? Two solutions came into my mind and I wonder how to proceed Use a fixed resolution for the GUI (e.g. 1920x1080), optimize all widgets for this size and let the viewport do the rest (so there will be super or subsampling) or write a resizing logic for the gui to properly adapt the widget sizes and positions to the screen's resolution Is there any known best practice how to deal with this problem?


Box2d RopeJoint bug fix or alternative solution? What I am trying to do is to create rope game. Below you can find a movie how it looks like now. https youtu.be QTULCGNF70I I am using RopeJoint and I am reducing maxLength each frame to be able to accelerate. Everything seems fine, but the problem appears for bubble kind of ball. I realized that shortening rope does not increase balls velocity. For example if I throw the rope fully vertical and the only "force" is from shortening the rope, the velocity is 0,0. Seems like, body movement is not simulated? After I let the rope go the momentum is lost. The bubble can fly, but the factor from rope shortening is ignored. I don't know if you understand what I mean. The movie should clarify it better. Workarounds I tried Good idea was to use prismaticJoint, but the rotation is fixed, so it doesn't work. I couldn't swing Another idea was to use wheelJoint and make use of it's frequency parameter. However here there's a problem that rope becomes rubber. Swing feeling is bad, when it can extend more than initial length, it should always only shorten. Solutions I see, but they are not available RopeJoint which keeps body momentum from rope shortening PrismaticJoint without fixed rotation WheelJoint with possibility to set max length or create the rope with it's max length, not the rest position.


What is the delta value passed to the Screen's render method? The delta value given to the render method in the Screen class is a non constant number. What is it? Where does it come from? Does it differ by screen size?


Storing player data for multiple players in libGDX I'm working on a game (in libGDX) that would allow multiple player accounts. I need to store some simple user data (several key value pairs). I think JSON is the best for my needs, but I'm wondering how this data should be organised. I'm thinking about two possibilities single file for each player seems better design wise, but I'm not sure if real time file creation won't lead to issues one big file with player id as key and organised array of values safer, but would require loading data for all players on initial read and each update (although there shouldn't be that many accounts on a single game instance). Also harder to maintain due to necessity of keeping values in proper order, etc. Perhaps there are better ways to do it, that I didn't think about.


Does libGDX support the Xbox One controller? I just bought a Xbox one controller and i'd like to test my game with it. I use the Controllers extension from libGDX and it works fine, at least with my PS3 controller. I get some weird results when i'm polling the axis of the controller with libGDX. The values are ok for Y axies but not for X ones. I mean, for X axis, values are really weird, sometimes, when the stick is fully pushed to the left, the value is not even negative, same goes for the right, sometimes value is negative. I don't know why but values seems inconsistent for X axies, Y axies work fine. Concerning buttons, they are all detected except for the dpad. I am using the drivers available here. I tested the controller with several games, it works fine so i think it's related to libGDX. Do you think the Xbox One controller is not supported yet? Can it be a driver issue? Should I use another way to poll controller states? If yes, is there a good and up to date library to do so? Thanks.


how to set volume of sound depending on the impulse a body receives in Libgdx Box2d? I am trying to set the volume of a bouncing sound of a ball depending on how hard the ball hits something. so the harder the ball hits a wall or a ground the more loud the bounce sound. I couldn't find anyway to get the impulse of a body other than the postSolve(Contact contact, ContactImpulse impulse) method inContactListner class. But i then realized that unlike the beginContact(Contact contact) method, postSolve(Contact contact, ContactImpulse impulse) gets called repeatedly until the contact ends. so it repeatedly plays the bouncing sound making it sound stalked and buggy. I cant use the beginContact(Contact contact) method because there is no way to get the impulse that the ball is receiving from this method. I tried to to use the velocity of the ball instead of impulse inside beginContact(Contact contact)but that didnt yield good results and found it very complicated as i had to consider both horizontal and vertical speeds. so my question is how can I make the sound play only once if i am using the postSolve(Contact contact, ContactImpulse impulse) method or is there any other solution to achieve what i am trying to do here?


How to access entites from scripts in an entity framework? I'm developing on a simple libGDX based Game and im using the entity component system ashley. For non generic but custom behaviour (e.g. the Player Movement), I'm using "scripts" instead of reuseable and generic Entity Systems. Therefore I've got an ScriptComponent and a ScriptSystem which runs init() and update() on all scripts related to an entity. At some point I want to generate a map, counting game related properties etc. that brings me to the point where I'm confused about how to access those porperties from any script. In other Engines Enviroments like Unity3D the GameObjects (the entities) brings functionality to find other entities like FindGameObjectsWithTag(...). But how can I realise that in ashley? Also should it be possible in an Entity Framework to access specific entities in general? Edit Additional information Here comes a simple example usecase. This is very notional example I've just created for that post. I just wanted to demonstrate, that I thing there is a need of an "main Game Object" in a game which also uses a entity component framework like ashley. So I thought a correct way is, to let this main game object be an entitiy too which holds the main script. But I'm not sure, if this is a good approach. Here I demonstrate this with having a PlayerScript which just sets the lives for the player accordingly to the difficulty level of the game (maybe set by the player on the main menu screen). This PlayerScript is attached to the ScriptComponent of the player entity. public class PlayerScript extends Script int playerLives public void init() GameEntity entity getTheEntityByName("game") this method doesn't exist GameScriptComponent gsc scriptComponentMapper.get(entity) GameScript mainGameScript gsc.getScriptByName("game") if(mainGameScript.getDifficulty "easy") playerLives 999


Independent Column sizes in Scene2D Table in LibGDX For my game's (mostly GUI based) UI i am using table from Scene2D in libGDX. I want independent column sizes in my table but first cell width is the width for all other rows in column. Is it possible to have a table in Scene2D with independent cell width in each row? For example, first cell in first row should have 10 width and first cell in second row should have 15 width. I tried using Horizontal Groups, Containers but they make my code too shabby and cluttered.


Libgdx overlapping stages textbutton unclickable I've created a few TextButtons for a menu that render on top of another stage area, however the textbuttons that i've created for menu aren't clickable or don't provide any events. The MenuComponent class I created is being instantiated rendered in another class. The buttons show up, just unable to click anything or get any events from the buttons. Can someone take a look at the code I provided and maybe show me mistakes or something I forgot to implement to make them work? MenuComponent Class Override public void create() batch new SpriteBatch() this.stage new Stage() setRenderer(new ShapeRenderer()) Gdx.input.setInputProcessor(stage) menuUp new Texture( quot assets ui disengage.png quot ) menuDown new Texture( quot assets ui disengagePressed.png quot ) Table menuWindow new Table() this.menuWindow menuWindow menuWindow.setPosition(675,160) Button View SpriteDrawable upFormat new SpriteDrawable(new Sprite(createRoundPixMap(Color.BLACK,100, 30,10))) SpriteDrawable downFormat new SpriteDrawable(new Sprite(createRoundPixMap(Color.RED,100, 30,10))) SpriteDrawable checkedFormat new SpriteDrawable(new Sprite(createRoundPixMap(Color.BLACK,100, 30,10))) TextButtonStyle buttonStyle new TextButtonStyle(upFormat, downFormat, checkedFormat, new BitmapFont()) Individual Buttons lobbyButton new TextButton( quot Back to Lobby quot ,buttonStyle) mapsButton new TextButton( quot List Maps quot ,buttonStyle) menuWindow.add(lobbyButton).pad(3,0,3,0).row() menuWindow.add(mapsButton).pad(3,0,3,0).row() menuWindow.setVisible(false) stage.addActor(menuWindow) stage.getRoot().setPosition(65,150) Override public void update() Override public void render() batch.begin() batch.draw((menuButtonIsDown)?menuDown menuUp, MENU buttonX, MENU buttonY) batch.end() stage.act() stage.draw() Part of the class its being rendered created in Override public void create() generator new FreeTypeFontGenerator(Gdx.files.internal( quot assets font Roboto Regular.ttf quot )) FreeTypeFontGenerator.FreeTypeFontParameter parameter new FreeTypeFontGenerator.FreeTypeFontParameter() parameter.size 10 parameter.spaceX 0 parameter.shadowColor new Color(0, 0, 0, 0.5f) parameter.borderColor Color.BLACK parameter.borderWidth 1 parameter.borderStraight true parameter.shadowOffsetY 1 parameter.shadowOffsetX 1 font generator.generateFont(parameter) renderer new ShapeRenderer() this.batch new SpriteBatch() sea context.getManager().get(context.getAssetObject().sea,Texture.class) sea.setWrap(Texture.TextureWrap.Repeat, Texture.TextureWrap.Repeat) camera new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight() 200) this.mainmenu new MenuComponent(context, this) mainmenu.create() Override public void render() batch.setProjectionMatrix(camera.combined) batch.begin() Gdx.gl.glViewport(0,200, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() 200) mainmenu.render()


How To generate spiky terrain in 2D? I am learning game design, and wanted to know how one can automatically generate spiky terrain (something like this Cavernaut, notice, the terrain at the sides?). I have heard about midpoint displacement algorithm. But How can I apply that to my problem, given that I would also like to increase decrease the randomness of the terrain. Also, Is there any helpful library for this in libgdx?


Libgdx change the image inside table dynamically I am trying to draw a HUD that shows the score and time and image like loading but I want to update and change the image when the score get higher but I tried to do that but it is not working. I thought maybe I can define new table in the update method and put different image each time but I don't want to define new table each time. is there anyway to update the image only inside the table this is the code public class Hud implements Disposable public Stage stage private Viewport viewport private static Integer worldTimer private float timecount private static Integer score Label countdownLabel private static Label scorelabel private Label timelabel private Label levellabel private Label worldlabel private Label mariolabel private Image loading private Table table public Hud(SpriteBatch sb) worldTimer 40 timecount 0 score 0 viewport new FitViewport(Fruits.V WIDTH,Fruits.V HIEGT,new OrthographicCamera()) 2 stage new Stage(viewport,sb) stage is as box and try to put widget and organize things inside that table table new Table() table.top() table at top of our stage table.setFillParent(true) table is now fill all the stage countdownLabel new Label(String.format(" 02d",worldTimer),new Label.LabelStyle(new BitmapFont(), Color.BLACK)) label for gdx scorelabel new Label(String.format(" 02d",score),new Label.LabelStyle(new BitmapFont(), Color.BLACK)) label for gdx timelabel new Label("TIME",new Label.LabelStyle(new BitmapFont(), Color.BLACK)) label for gdx levellabel new Label("1 1",new Label.LabelStyle(new BitmapFont(), Color.BLACK)) label for gdx worldlabel new Label("WORLD",new Label.LabelStyle(new BitmapFont(), Color.BLACK)) label for gdx mariolabel new Label("Score" ,new Label.LabelStyle(new BitmapFont(), Color.BLACK)) label for gdx loading new Image(new Texture("10 .png")) loading.setSize(40, 10) table.add(mariolabel).expandX().padTop(10) table.add(timelabel).expandX().padTop(10) table.add(worldlabel).expandX().padTop(10) table.row() table.add(scorelabel).expandX() table.add(countdownLabel).expandX() table.add(loading).width(50).height(10) stage.addActor(table) public void update(float dt) timecount dt if (timecount gt 1) worldTimer if(worldTimer gt 0) countdownLabel.setText(String.format(" 02d", worldTimer)) loading new Image(new Texture("90.png")) timecount 0 public static int getTime() return worldTimer public static void addScore(int value) score value scorelabel.setText(String.format(" 02d",score)) public static int getScore() return score Override public void dispose() stage.dispose()


Move Animation in LibGdx I'm trying move animation within screen, here's the code Animation lt TextureRegion gt animation run GifDecoder.loadGIFAnimation(Animation.PlayMode.LOOP, Gdx.files.internal("run.gif").read()) float elapsedTime (Gdx.graphics.getDeltaTime()) 2 float playablePosition (Gdx.graphics.getWidth()) 2 200 float currentPosition 0 for (int i 0 currentPosition lt playablePosition i ) currentPosition i batch.begin() batch.draw(animation run.getKeyFrame(elapsedTime), currentPosition, 0, 200, 300) batch.end() but I got not exactly what I want Does anybody know how fix my code to make movement from left edge to the center properly?


How can I improve the display of my png files? I develop a mini Android game available from my github (also the release apk file). The game is for kids and you are supposed to catch falling object and get points for that. Now I just created png files for the sprites and added alpha channel in gimp. It looks better, before alpha channel After But I'm not 100 satisfied with the rough edges of the sprites. Am I correct that if I do the alpha channel more exact then the sprites will look even better (without the edges) or is there some other mistake that I make with the sprites? Edit With new background image, it looks like this. Edit 2 I used jamie the monkey now of BSD license which renders better. It seems to be more exact work in GIMP that is needed. Edit 3. Now I am satisfied. Thanks.


libGDX application does not support 800x480 resolution I have an application written with libGDX that does not run with a resolution of 800x480, whereas on devices with other resolutions (e.g. 480x320) it works perfectly. It also works perfectly as a desktop application with a resolution of 800x480. In onCreate() method I only have this code Override protected void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState) initialize(new BreakTheBall(), false) So what do I have to do to have it work in a resolution of 800x480? I have to ask this question because my samsung galaxy sx2 display only blank screen at the time of game execution but emulator work perfectly. I also want to said that all the given demo application by libGDX could not run on the same device resolution. Also I like to mention the base class of my project which specify about stage, camera and viewport declaration protected BreakTheBall game protected Stage stage protected World world protected OrthographicCamera camera protected Preferences preferences protected ArrayList lt Obstacles gt boxArrayList protected ArrayList lt BlastBall gt blastBallArrayList private static final int VIRTUAL WIDTH 480 private static final int VIRTUAL HEIGHT 320 private static final float ASPECT RATIO (float) VIRTUAL WIDTH (float) VIRTUAL HEIGHT private Rectangle viewport protected Box2DDebugRenderer renderer public AbstractScreen(BreakTheBall game) this.game game Texture.setEnforcePotImages(false) stage new Stage(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false) Constant.setStageRatio(stage.width(), stage.height()) world new World(new Vector2(0.0f, 0.0f), false) camera new OrthographicCamera(Gdx.graphics.getWidth() 10.0f, Gdx.graphics.getHeight() 10.0f) camera new OrthographicCamera((float) VIRTUAL WIDTH 10.0f, (float) VIRTUAL HEIGHT 10.0f) camera.position.scale(0.0f, 0.0f, 0.0f) renderer new Box2DDebugRenderer(true, false, false) Gdx.input.setInputProcessor(stage) preferences new Preferences() Override public void render(float deltaTime) GL10 gl Gdx.graphics.getGL10() camera.update() camera.apply(gl) gl.glClearColor(0f, 0f, 0f, 1f) gl.glClear(GL10.GL COLOR BUFFER BIT) gl.glViewport(0, 0, (int) viewport.width, (int) viewport.height) world.step(1 60f, 3, 3) world.clearForces() stage.act(deltaTime) stage.setCamera(camera) Override public void resize(int width, int height) float aspectRatio (float) width (float) height float scale 1f Vector2 crop new Vector2(0f, 0f) if (aspectRatio gt ASPECT RATIO) scale (float) height (float) VIRTUAL HEIGHT crop.x (width VIRTUAL WIDTH scale) 2f else if (aspectRatio lt ASPECT RATIO) scale (float) width (float) VIRTUAL WIDTH crop.y (height VIRTUAL HEIGHT scale) 2f else scale (float) width (float) VIRTUAL WIDTH float w (float) VIRTUAL WIDTH scale float h (float) VIRTUAL HEIGHT scale viewport new Rectangle(crop.x, crop.y, w, h) I think above specified code provide more guidance to community members so please help me to come out of this problem.


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 Rectangle Collision and Response I've been using LibGDX for the past few weeks and I have some problems that I need help on. What I need help on is understanding how to use LibGDX Rectangle class for a platformer. I found this project on github that seems to be useful. https github.com obviam star assault reboot I was able to wrap my mind around how this game worked for the most part. The only thing I can't understand, which is the most essential part of the game, is how the collision detection and response works. In the project, the BobController class holds the everything that's used to detect collision. https github.com obviam star assault reboot blob master core src net obviam starassault controller BobController.java I tried going to the website linked in the github project for answers, but it seems to be empty. Maybe I'm just dumb, but I can't wrap my mind how this works. Even with the comments provided in the project, I still don't understand. Can someone explain in greater detail how this class handles collision detection and response using the LibGDX Rectangle class. EDIT This is the specific function that I don't understand Collision checking private void checkCollisionWithBlocks(float delta) scale velocity to frame units bob.getVelocity().scl(delta) Obtain the rectangle from the pool instead of instantiating it Rectangle bobRect rectPool.obtain() set the rectangle to bob's bounding box bobRect.set(bob.getBounds().x, bob.getBounds().y, bob.getBounds().width, bob.getBounds().height) we first check the movement on the horizontal X axis int startX, endX int startY (int) bob.getBounds().y int endY (int) (bob.getBounds().y bob.getBounds().height) if Bob is heading left then we check if he collides with the block on his left we check the block on his right otherwise if (bob.getVelocity().x lt 0) startX endX (int) Math.floor(bob.getBounds().x bob.getVelocity().x) else startX endX (int) Math.floor(bob.getBounds().x bob.getBounds().width bob.getVelocity().x) get the block(s) bob can collide with populateCollidableBlocks(startX, startY, endX, endY) simulate bob's movement on the X bobRect.x bob.getVelocity().x clear collision boxes in world world.getCollisionRects().clear() if bob collides, make his horizontal velocity 0 for (Block block collidable) if (block null) continue if (bobRect.overlaps(block.getBounds())) bob.getVelocity().x 0 world.getCollisionRects().add(block.getBounds()) break reset the x position of the collision box bobRect.x bob.getPosition().x the same thing but on the vertical Y axis startX (int) bob.getBounds().x endX (int) (bob.getBounds().x bob.getBounds().width) if (bob.getVelocity().y lt 0) startY endY (int) Math.floor(bob.getBounds().y bob.getVelocity().y) else startY endY (int) Math.floor(bob.getBounds().y bob.getBounds().height bob.getVelocity().y) populateCollidableBlocks(startX, startY, endX, endY) bobRect.y bob.getVelocity().y for (Block block collidable) if (block null) continue if (bobRect.overlaps(block.getBounds())) if (bob.getVelocity().y lt 0) grounded true bob.getVelocity().y 0 world.getCollisionRects().add(block.getBounds()) break reset the collision box's position on Y bobRect.y bob.getPosition().y update Bob's position bob.getPosition().add(bob.getVelocity()) bob.getBounds().x bob.getPosition().x bob.getBounds().y bob.getPosition().y un scale velocity (not in frame time) bob.getVelocity().scl(1 delta)


LibGDX camera position shifted on movement I'm programming a game with LibGDX and Box2D and I want my camera to follow my player. But as I zoom in (because Box2Ds metric system, using camera.zoom x) the camera is shifted when the player moves (the camera follows the player) Shifted View Normal View That only happens when the player moves, so there can't be a problem with the coordinates. My Question is how to remove this shifting as the player moves. Here's some of my code Render Loop (excerpt) Override public void render(float delta) set the camera position to player's position cam.position.set(player body.getWorldCenter().x, player body.getWorldCenter().y, 0) cam.update() world.step(Gdx.graphics.getDeltaTime(), 6, 2) world.clearForces() handleInput() Gdx.gl.glClearColor(.05f, .05f, .05f, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) batch.setProjectionMatrix(cam.combined) debugRenderer.render(world, cam.combined) Make the player move if (Gdx.input.isKeyPressed(Keys.W)) player body.setLinearVelocity(transX, transY) player.setMoving(true)


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


Rotating towards a point in Box2D I'm using Box2d as my physics engine and I'm trying to solve what would normally be a simple problem but what has become a nightmare for me and preventing me from finishing my app. (6 months work) I've tried implementing this (Example of implementation below) http box2d.org forum viewtopic.php?f 18 amp t 7306 but it's got three problems. 1 When reaching the top angle it stops and goes the other way. (Example in logs) 2 Limited speed, some objects need turn fast. 3 Large objects with moving joints spaz out rocking all over the place. I have a desired angle and I want my body to rotate at different speeds (depending on turn speed setting as I want large slow turn objects). Problems with current code. 1 Large object with a moving joint either spin very fast or rock constantly. 2 The rock effect exists on everything. Edit This is within a game loop, so have access to delta. Code 1 Box2D attempt Testing speed. float tempSpeed MathUtils.PI float currentAngle getBody().getAngle() MathUtils.PI2 float nextAngle getBody().getAngle() (getBody().getAngularVelocity() update) float totalRotation getDesiredAngle() nextAngle Assuming this tries to prevent the switch angle problem but limits the speed?? while ( totalRotation lt MathUtils.PI tempSpeed ) totalRotation MathUtils.PI2 tempSpeed while ( totalRotation gt MathUtils.PI tempSpeed ) totalRotation MathUtils.PI2 tempSpeed float desiredAngularVelocity totalRotation float change 1f tempSpeed allow 1 degree rotation per time step desiredAngularVelocity Math.min(change, Math.max( change, desiredAngularVelocity)) float impulse getBody().getInertia() desiredAngularVelocity getBody().applyAngularImpulse(impulse, true) Below shows an example of the top angle being switched. if(getFocus()) Functions.log("currentAngle " getBody().getAngle() " nextAngle " nextAngle " totalRotation " totalRotation " desiredAngularVelocity " desiredAngularVelocity) Log nextAngle 0.1850999 totalRotation 6.400846 desiredAngularVelocity 3.1415927 Log nextAngle 0.02812685 totalRotation 6.2195992 desiredAngularVelocity 3.1415927 Example of top angle being reached and switching back. Log nextAngle 0.21522963 totalRotation 5.948592 desiredAngularVelocity 3.1415927 Log nextAngle 0.45278195 totalRotation 5.6859627 desiredAngularVelocity 3.1415927 Code 2 My warped attempt Keep the angle within range. float currentAngle getBody().getAngle() 6.283185f Get the next angle. Use angle in next time step float nextAngle currentAngle (getBody().getAngularVelocity() update) float totalRotationAngle getDesiredAngle() nextAngle Keep the total rotation within range, so we don't spin all the way around when reaching the other side. while (totalRotationAngle lt MathUtils.PI) totalRotationAngle (MathUtils.PI2) while (totalRotationAngle gt MathUtils.PI) totalRotationAngle (MathUtils.PI2) Do some other stuff. float desiredAngularVelocity totalRotationAngle getRotationSpeed() Inertia is the amount of force required to rotate the object, without it it rotates really fast. If we introduce it, we get more realistic results but the horrible rock. float torque (getBody().getInertia() (desiredAngularVelocity this.turnSpeed)) update Need inertia otherwise it can spins things right out the way. float turnSpeed (this.turnSpeed (4f (getDesiredAngle()))) float torque (desiredAngularVelocity (this.turnSpeed)) torque (getBody().getInertia()) torque update Apply torque. getBody().applyTorque(torque, false)


Checking if Body is surrounded by other Bodies I'm trying to make a game like Rampart as practice. I have gotten to the point where I want to check if the castle is surrounded by walls and decide whether to fill in the area and continue the game, but I have no idea how to do this. I have thought about ray casting from the castle but it wouldn't work if there was a bend in the walls. So any help or suggestions would be great!


share assets beetween platforms What is the good way to share assets between platforms (android, desktop, etc) ? by default there is an assets folder in each platform folder.


Which is the best method implementing a background scrolling for game in libgdx? My question is very simple I am new to libgdx development, which is the best approach implementing a background that is to make the background move in y direction 1)My First approach is drawing the background image 10 times towards positive y direction using camera.translate(x,y) function to move camera from bottom to top 2)second approach is to make the camera still while making the background scroll ie drawing the background frame by frame updating the position each time Can you please suggest which is the best approach?


LibGDX, vertical group not displaying I'm having trouble showing a simple custom VerticalGroup. Here's my SideBar class public class SideBar extends VerticalGroup final GameManager gameManager GameManager.instance final Image nextBackground final Image nextImage final Image powerImage final Image powerUp1Background final Image powerUp2Background final Image powerUp3Background public SideBar() super() nextBackground new Image(gameManager.getTexture("bar.next.png")) addActor(nextBackground) nextImage new Image(gameManager.getTexture("label.next.png")) addActor(nextImage) powerImage new Image(gameManager.getTexture("label.power.png")) addActor(powerImage) powerUp1Background new Image(gameManager.getTexture("powerup.bg.png")) addActor(powerUp1Background) powerUp2Background new Image(gameManager.getTexture("powerup.bg.png")) addActor(powerUp2Background) powerUp3Background new Image(gameManager.getTexture("powerup.bg.png")) addActor(powerUp3Background) And here's where I add it to my main Stage TopBar topBar new TopBar() topBar.setY(DonutsGame.WORLD HEIGHT topBar.getHeight()) stage.addActor(topBar) SideBar sideBar new SideBar() Gdx.app.log(TAG, "side bar x,y " sideBar.getX() "," sideBar.getY() ", w,h " sideBar.getWidth() "," sideBar.getHeight()) stage.addActor(sideBar) My TopBar class extends Group and is displaying correctly, so I'm not sure what I'm doing wrong with SideBar that's causing it to not show. The log output shows that the position, and width height are all 0, which seems incorrect to me according to the vertical group's documentation. Which states that the width height should be based on the pref. width height of the children (height based on sum). I've tried calling validate and layout with no success.


Why is the sprite so offset from the physics body? I'm trying to make a sprite object that has physics, but once the game runs the physics body is drawn at an unknown offset from the sprite, which varies based on the size of the sprites texture. Physics Sprite class public class PhysicsSprite extends Sprite World world public Body body public PhysicsSprite(Texture texture, World PhysicsWorld, float x, float y) super(texture) this.world PhysicsWorld setPosition(x,y) setOrigin(getX(),getY()) InitializeBody() private void InitializeBody() BodyDef bd new BodyDef() bd.position.set((getX()) GameMain.PPM,(getX()) GameMain.PPM) bd.type BodyDef.BodyType.DynamicBody body world.createBody(bd) PolygonShape shape new PolygonShape() shape.setAsBox(getWidth() 2f GameMain.PPM,getHeight() 2f GameMain.PPM) FixtureDef fd new FixtureDef() fd.density 1 fd.shape shape Fixture fixture body.createFixture(fd) System.out.println(body) private void updateSprite() setPosition(body.getPosition().x GameMain.PPM,body.getPosition().y GameMain.PPM) setRotation((float)Math.toDegrees((double) body.getAngle())) Override public void draw(Batch batch) updateSprite() super.draw(batch) physics world rendering scene class public class TestLevel implements Screen World world new World(new Vector2(0f,0f),true) OrthographicCamera camera new OrthographicCamera(GameMain.WIDTH GameMain.PPM, GameMain.HEIGHT GameMain.PPM) Box2DDebugRenderer debugR new Box2DDebugRenderer() PhysicsSprite s GameMain game SpriteBatch batch public TestLevel(GameMain g) game g batch g.batch s new PhysicsSprite(new Texture("badlogic.jpg"),world,300,500) Override public void show() Override public void render(float delta) Gdx.gl.glClearColor(.4f,0.4f,.4f,1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) batch.begin() s.draw(batch) batch.end() debugR.render(world,camera.combined) world.step(Gdx.graphics.getDeltaTime(),6,2) Override public void resize(int width, int height) Override public void pause() Override public void resume() Override public void hide() Override public void dispose() I've followed this tutorial and he mentions the sprite being offset but nothing occurs to him like whats happening here. I've tried to find someone with a similar issue but failed. Can someone help me out?


How do I dynamically set a WheelJoint's anchor points? I've created a car in RUBE and imported it into my game. The game has a tuning menu, allowing the ride height of the car to be adjusted with a slider. I can't work out how to change the position of the WheelJoint relative to the car body. The result I'm looking for is as if I had changed the anchorA Y value in RUBE. I thought this would be equivalent, but it isn't car.rearWheelJoint.getAnchorA().set(xvalue,yvalue) I've tried instead creating a whole new jointdef WheelJointDef d new WheelJointDef() d.initialize(car.rearWheelJoint.getBodyA(), car.rearWheelJoint.getBodyB(), car.rearWheelJoint.getAnchorA().add(0,(val 100) 0.01f), car.rearWheelJoint.getAnchorB()) car.rearWheelJoint (WheelJoint) game.world.createJoint(d) ...but I think this is messing up the pointer to the wheel joint. How can I do this?


Libgdx How to overlay two images on Table I'm trying to set the player image inside the circle of the bars. I've tried to use stack, to position it topLeft but it does not work. Stack stack new Stack() healthbar new Image(new Texture(Gdx.files.internal("data ui healthbar.png"))) playerLook new Image(player.getFrame()) stack.add(healthbar) stack.add(playerLook) Table table new Table() table.top() table.setFillParent(true) table.add(healthbar).expandX().pad(10).left() table.add(playerLook).expandX().pad(10).left() stack.add(table) stage.addActor(stack)


ClickListener getTapCount() returns 0 I want to detect the double tap on a Container. If it is detected, then i have to remove the Actor associated with it. This is my first attempt addListener(new ClickListener() if(getTapCount() 2) System.out.println("double click detected") return true ) It does not work. The method getTapCount() returns always 0.


Box2d Fixed Timestep and Interpolation I am using libGDX and I have problems implementing the box2d fixed timestep with interpolation. This is my code private void updateWorld() accumulator Gdx.graphics.getDeltaTime() while (accumulator gt step) The step is 1 10 copyCurrentPosition() world.step(step, 8, 3) accumulator step interpolate(accumulator step) private void copyCurrentPosition() prevPosition new Vector2(player.body.getPosition().x, player.body.getPosition().y) private void interpolate(float alpha) player.body.setTransform(player.body.getPosition().x alpha prevPosition.x (1.0f alpha), player.body.getPosition().y alpha prevPosition.y (1.0f alpha), 0)


LibGDX FileHandle does not delete file I'm using this line of code to delete a file if(Gdx.files.local(" files ids.json").exists()) Gdx.files.local(" files ids.json").delete() The same code works for all previous levels except the last one. The file does exist, but the delete() method returns false. Any help would be greatly appreciated as it has exhausted me. I've seen similar topics in Java but nothing has worked for me. It's really weird that the same code works in some cases. Edit Also, in case this provides any information, when I step through the program with the debugger, the delete() returns true.


Rendering Tilemap Tile Layer Side by Side for Infinite Endless Runner Game I was strugeling this for days how to implement tilemap into libgdx and box2d with infinite endless scheme. I can load a single map and display everything on screen. But placing 2 or more tilemap side by side got me headache. I know currently not possible to offset add x value position of tilemap. What I do right now is use setview for camera of it's render method. This is my map helper and currently I works with 3 renderer for 3 tilemap as a test... public class MapHelper private Array lt OrthogonalTiledMapRenderer gt renderer new Array lt OrthogonalTiledMapRenderer gt () private int number private float oldDistance, currentDistance private String layer "world" public MapHelper(Callback callback) this.callback callback number 0 item new ItemMap 3 public void render(CamHandler cam) for(int r 0 r lt renderer.size r ) if(item r ! null) renderer.get(r).setView(cam.getCam().combined, item r .distance, 0, item r .getWidth(), item r .getHeight()) renderer.get(r).render() public void updateMap(CamHandler cam) if(mapOut(cam)) number if(number gt 2) number 0 loadMap(number) Check if camera reach the current distance, then build new map param cam return private boolean mapOut(CamHandler cam) float x cam.getCam().position.x cam.getCam().viewportWidth 2 Utils.log("pos cam x " x " current distance " currentDistance) return x gt currentDistance private void loadMap(int map) AssetsManager.loadMap(map) if(item map ! null) renderer.set(map, new OrthogonalTiledMapRenderer(AssetsManager.map)) item map .set(TileHelper.getMapWidth(AssetsManager.map, layer), TileHelper.getMapHeight(AssetsManager.map, layer), currentDistance) else renderer.add(new OrthogonalTiledMapRenderer(AssetsManager.map)) item map new ItemMap(TileHelper.getMapWidth(AssetsManager.map, layer), TileHelper.getMapHeight(AssetsManager.map, layer), currentDistance) oldDistance currentDistance currentDistance TileHelper.getMapWidth(AssetsManager.map, layer) callback.onLoad() Utils.log("load new map " map " distance " currentDistance) public Array lt OrthogonalTiledMapRenderer gt getRenderer() return renderer public Array lt Body gt getBodies(World world) return new MapBodyBuilder().buildShapes(AssetsManager.map, world, oldDistance) private ItemMap item private class ItemMap private float distance, mapWidth, mapHeight ItemMap(float w, float h, float distance) mapWidth w mapHeight h this.distance distance private void set(float mapWidth, float mapHeight, float distance) this.mapWidth mapWidth this.mapHeight mapHeight this.distance distance private float getWidth() return mapWidth Constants.WORLD TO SCREEN private float getHeight() return mapHeight Constants.WORLD TO SCREEN private Callback callback public interface Callback void onLoad() public void startOver() clear() currentDistance number 0 loadMap(number) private void clear() for (OrthogonalTiledMapRenderer render renderer) render.dispose() With above class, I can display and load new map on screen when camera reaching the map end. But the tile layer texture keeps wrong position. Please give me an advice.


Libgdx get texture from Texture Atlas with findRegion I have this code textureAtlas TextureAtlas("atlas.atlas") val box textureAtlas.findRegion("box") I want to create a texture with "box". Is it possible? box.texture return the original texture, not the regioned. Oh and I don't want to use Sprite and SpriteBatch. I need this in 3D, not 2D. Thanks


How to force a garbage collector swep on libgdx? I found that you can control your memory usage on libgdx with int javaHeap Gdx.app.getJavaHeap() int nativeHeap Gdx.app.getNativeHeap() But, How can I force a garbage collector cleanup? I want to force in special moments, like screen change on a game.


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?


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?


How To generate spiky terrain in 2D? I am learning game design, and wanted to know how one can automatically generate spiky terrain (something like this Cavernaut, notice, the terrain at the sides?). I have heard about midpoint displacement algorithm. But How can I apply that to my problem, given that I would also like to increase decrease the randomness of the terrain. Also, Is there any helpful library for this in libgdx?