_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
15 | LibGDX Box2D Realistic Light and Layers I'm having some problems with my current game. Short description It's a 2D game where you have to avoid the lights or you lose HP. My problem is the following one Here is the rendering process The background is drawn The Moon image is drawn The point light is applied The collision layer and the images attached to it are drawn Player is drawn The foreground image (on the top left and bottom middle) My problem is that the rendering does not look realistic. I need some help on how I could make the light coming from "behind" the collisions and applying it everywhere. Thanks for your help. |
15 | libgdx iterator() cannot be used nested I'm getting this error when I try to check if any of the targets overlap each other iterTargets targets.iterator() while (iterTargets.hasNext()) Target target iterTargets.next() for (Target otherTarget targets) if (target.rectangle.overlaps(otherTarget.rectangle)) do something So I can't do that? How am I supposed to check each member of an array to see if it overlaps any other member? |
15 | 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? |
15 | LibGDX Shader does not work with FBO texture I have a shader and I want to run the shader on the whole rendered image at the end instead of each individual sprite that I render on screen. For this purpose I created an FBO, I render the all my images to the FBO and then I render to colorBufferTexture generated by the FBO. There is just one problem, the shader does not work when I render the FBO texture. The withoutFbo() method render the image with the shader working just fine, but the withFbo() method only renders the image without the shader. Also I know that the shader in withFbo() is working because if I try to render something other then the colorBufferTexture from the FBO the shader will work. So why isn't the shader working with the texture generated by the FBO? public class Application3 extends ApplicationAdapter float time Sprite sprite FrameBuffer fbo SpriteBatch batch Texture noiseTexture TextureRegion fboTexture ShaderProgram shaderProgram Override public void create() ShaderProgram.pedantic false batch new SpriteBatch() sprite new Sprite(new Texture("game.png")) sprite.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()) shaderProgram new ShaderProgram(Gdx.files.internal(Shader.GLITCH2.getVertex()), Gdx.files.internal(Shader.GLITCH2.getFragment())) noiseTexture new Texture(Gdx.files.internal(Shader.GLITCH2.getPath() "noise.png")) noiseTexture.bind(0) fbo new FrameBuffer(Pixmap.Format.RGBA8888, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false) fboTexture new TextureRegion(fbo.getColorBufferTexture()) fboTexture.flip(false, true) Override public void render() withFbo() withoutFbo() void withoutFbo() Gdx.gl.glClearColor(0, 0, 0, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) time Gdx.graphics.getDeltaTime() shaderProgram.setUniformi("u noise", 0) shaderProgram.setUniformf("u time", time) batch.setShader(shaderProgram) batch.begin() batch.draw(sprite, sprite.getX(), sprite.getY(), sprite.getWidth(), sprite.getHeight()) batch.setShader(null) batch.end() void withFbo() Gdx.gl.glClearColor(0, 0, 0, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) time Gdx.graphics.getDeltaTime() fbo.begin() batch.begin() batch.draw(sprite, sprite.getX(), sprite.getY(), sprite.getWidth(), sprite.getHeight()) batch.end() fbo.end() shaderProgram.setUniformi("u noise", 0) shaderProgram.setUniformf("u time", time) batch.setShader(shaderProgram) batch.begin() batch.draw(fboTexture, sprite.getX(), sprite.getY(), sprite.getWidth(), sprite.getHeight()) batch.setShader(null) batch.end() |
15 | Libgdx change velocity of moveTo action I am trying to create physics for a ball in Libgdx. The ball starts moving after a pan and everytime the ball collides with a wall, a moveTo action is added to it. But my ball moves with a constant velocity (action time distance velocity). I want my ball movement to get slower smoothly. Here is my method for calculating velocity private float velocity(float panDistance) float coefficent 0.3f return panDistance coefficent in act method of the Ball I decrement velocity Override public void act(float delta) super.act(delta) if (velocity lt 100 amp amp velocity gt 0) ballImage.clearActions() velocity 3f delta When gesture detector detects a pan the method below is called. public void moveTheBall(float tanX, float tanY) if (ballImage.getActions().size 0) motionVector (int) (tanX Math.abs(tanX)) motionAngleTan tanY tanX panDistance (float) Math.sqrt((tanX tanX) (tanY tanY)) velocity velocity(panDistance) recursivelyAddActions(motionVector) in recursivelyAddActions() method private void recursivelyAddActions(int vectorDirection) AFTER SOME CALCULATIONS distance (float) Math.sqrt(((predictionX ballStartingPosX) (predictionX ballStartingPosX)) ((predictionY ballStartingPosY) (predictionY ballStartingPosY))) moveToAction Actions.moveTo(predictionX, predictionY, distance velocity) ballImage.addAction(moveToAction) this is not smooth and this does not work good. I need an advice to make this work better. Thank you. |
15 | Setting uniform value of a vertex shader for different sprites in a SpriteBatch I'm using libGDX and currently have a simple shader that does a passthrough, except for randomly shifting the vertex positions. This shift is a vec2 uniform that I set within my code's render() loop. It's declared in my vertex shader as uniform vec2 u random. I have two different kind of Sprites let's called them SpriteA and SpriteB. Both are drawn within the same SpriteBatch's begin() end() calls. Prior to drawing each sprite in my scene, I check the type of the sprite. If sprite instance of SpriteA I set the uniform u random value to Vector2.Zero, meaning that I don't want any vertex changes for it. If sprite instance of SpriteB, I set the uniform u random to Vector2(MathUtils.random(), MathUtils.random(). The expected behavior was that all the SpriteA objects in my scene won't experience any jittering, while all SpriteB objects would be jittering about their positions. However, what I'm experiencing is that both SpriteA and SpriteB are jittering, leading me to believe that the u random uniform is not actually being set per Sprite, and being applied to all sprites. What is the reason for this? And how can I fix this such that the vertex shader correctly accepts the uniform value set to affect each sprite individually? passthrough.vsh attribute vec4 a color attribute vec3 a position attribute vec2 a texCoord0 uniform mat4 u projTrans uniform vec2 u random varying vec4 v color varying vec2 v texCoord void main() v color a color v texCoord a texCoord0 vec3 temp position vec3( a position.x u random.x, a position.y u random.y, a position.z) gl Position u projTrans vec4(temp position, 1.0) Java Code this.batch.begin() this.batch.setShader(shader) for (Sprite sprite sprites) Vector2 v Vector2.Zero if (sprite instanceof SpriteB) v.x MathUtils.random( 1, 1) v.y MathUtils.random( 1, 1) shader.setUniformf("u random", v) sprite.draw(this.batch) this.batch.end() |
15 | ECS should everything be a system? I've just recently started working with LibGDX and Ashley, and I find it to be really useful and I like working with the whole entity component system workflow. But I've been starting to layout the GUI and other aspects of the interface that dont exactly, to me, seem like they should be entities. When using an ECS should EVERYTHING in your game be an entity with components a system to control them? |
15 | 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? |
15 | box2d not centered in sprite I am trying to create a bounding box for my sprite using box2d, but the box is being created at the wrong spot. I followed a tutorial on the wiki using this code BodyDef bodyDef1 new BodyDef() bodyDef1.type BodyDef.BodyType.DynamicBody bodyDef1.position.set(player.getX(), player.getY()) playerBody world.createBody(bodyDef1) PolygonShape square new PolygonShape() square.setAsBox(player.getWidth() 2, player.getHeight() 2) FixtureDef fixtureDef1 new FixtureDef() fixtureDef1.shape square fixtureDef1.density 0.1f Player is a just the sprite that I am trying to create the box around. |
15 | libGDX Scene2d Actions or Frame Animation, which is better for performance? I only use Scene2d for the UI layer of my libGDX game. But I need some animations like fading or rotating on my players. Which is better for performance Scene2d fade action or having multiple frames with different opacity and using them in the Animation class? Also scene2d rotate action or having multiple frames with different angle? Thanks! |
15 | Libgdx, Gradle, android package naming problem I'm upgrading my libgdx project to make use of all the new Gradle stuff. However I changed the package namespace from the default generated by gdx setup but that hasn't worked when I debug to my phone Gradle is still trying to launch the default activity using the old namespace, hence it fails. But I can't figure out where Gradle is getting this from I've searched the entire folder tree for the offending old namespace string and can't find it anywhere. Details So gdx setup generated the android project with namespace "com.wibble.mygame.android" To match the namespace of my already published game, I edited that to "com.wibble.mygame a". I did this in the Android.manifest and the source code. Also noticed that the android build.gradle file has a line that generates the am start command so corrected that as well. But when I debug with my connected Android device, it tries to launch the app with a command like am start n "com.wibble.mygame.android com.wibble.mygame a.AndroidLauncher" a android.intent.action.MAIN c android.intent.category.LAUNCHER the old namespace is still there but I can't figure out where its getting it from because I can't find any mention of 'mygame.android' anywhere in the whole project tree. Is there some cache of stuff hidden somewhere that I need to delete? |
15 | Box2D collision between dynamic body I'm implementing Box2D for my 2d top down LIBGDX game and i have some struggle with two dynamic body. Currently, my two bodies are created that way BodyDef bodyDef new BodyDef() bodyDef.type BodyType.DynamicBody bodyDef.position.set(this.x, this.y) this.body world.createBody(bodyDef) PolygonShape collider new PolygonShape() collider.setAsBox(16, 16) FixtureDef fDef new FixtureDef() fDef.density 0f fDef.friction 0f fDef.restitution 0f fDef.shape collider body.createFixture(fDef) body.setUserData(this) collider.dispose() So basicly, no rotation, no friction and no restitution. Also, my world have a gravity of 0 (since it's a 2d top down game, i don't that want them to fall). When player 1 collide with player 2, player 2 is moved backward like it was push but i don't want that. I want it to stay where he is, blocking the path to player 1 but he can also move. Is there a way to do that ? I have looked for some tips like catching collision with the contact listener but i don't know what to do in the preSolve method. I'd like some help, thanks ! |
15 | Stopping Actor tap click event from propagating I've been struggling with this for hours now and have read posts, docs and libgdx sources to better understand what's happening, but I still can't make any sense of this. I want to accomplish something very simple stopping a tap on an Actor from propagating through the stage. The setup is as follows GameStage defines a gesture listener (for map panning and propagating taps in the map to the Player actor so it can move around) Player has a child actor which can receive clicks It is on that last child actor that I want to detect clicks, but then not have them propagate to any other actors or be handled by the stage. I define the click handler as follows in child actor addListener(new ClickListener() void clicked(...) ) Nothing surprising here. The problem is since the actor is physically located outside the Player parent actor, any clicks on it get picked up by the stage's map gesture handler which then propagates these taps back to the player which makes it move around. I don't want that this click listener is supposed to handle and swallow the event. However, none of the following calls I make inside clicked actually cancel the event event.handle() event.stop() event.cancel() The only way I could make the event stop from propagating is to use Stage cancelTouchFocus. However, this has the side effect of dispatching a touchUp event on the stage (why?), which ends up in my gesture listener and gets interpreted as a longPress! Probably because it is paired up with the wrong touchDown... What am I missing? It can't be that complicated to stop an event from propagating given all the supposed options? UPDATE I believe the problem lies in Stage https github.com libgdx libgdx blob 2bd1557bc293cb8c2348374771aad832befbe26f gdx src com badlogic gdx scenes scene2d Stage.java L348 It walks over all the listeners that have touch focus, and let's them handle the event. However, it does not break out of the loop as soon as a listener has handled it, thus propagating it further. Is that just a bug? |
15 | 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. |
15 | Conditionally use java or android classes I'm using bezier curves in my libgdx project. I was testing the desktop version using java.awt.geom with GeneralPath but when I went to test on android, it raised an error saying that I can't import java.awt. Android have corresponding classes for GeneralPath, Point2D etc so my question is how can I use those classes in their respectives environments? |
15 | LibGdx 2d Free Form Terrain I have a query about how to create a 2d landscape level using libgdx box2d (Or possibly with Unity) for Android and iOs. Let me describe the goal and then the specific points I need help with. What I'm trying to create is something like quot Hill Climb Racing quot where the player has to drive across a finite 2d free form landscape, like the one shown here. Different areas may have different properties (friction, texture, restitution, etc) as shown. The player will be able to pinch and zoom out to see all or most of the map and pinch to zoom in to see details.. The level width will vary from game to game but at most it will be about 800 box2d meters wide. Now if I use 32px m that requires an image 25,600 pixels across and this is where the issues start.. I can't tile it because that might preclude me from making free formed curves which I need to be able to do. So what I need to know is How can I create a box2d body for the terrain? What pixel meter ratio should I use? How many pixels wide should the image be? Should I split the image up into sections and how should I chunk the images together? What strategies have people used before to achieve this effect? Hope I have been specific enough and thanks for all the help.. |
15 | libGdx Window .pack() not working I'm trying to make a window, then use the pack method to get the right size, but the window maximizes instead. Here's my code private Table buildOptionsWindowLayer() winOptions new Window("Options", skinLibgdx) (...) building some widgets Gdx.app.log(TAG, "pref width is " winOptions.getPrefWidth()) displays "pref width is 247.0" winOptions.pack() move the window winOptions.setPosition(Constants.VIEWPORT GUI HEIGHT winOptions.getWidth() 50, 50) return winOptions The window ends up with a width of 800.0f. Why? What it is supposed to render What it does render |
15 | How to only detect Actor and not background I'm making a game where I have buttons on a stage, but the background also acts as a "button". But when I press on one of the existing actors on the stage, it also registers a click in the background in addition to the click on the button. How can I fix this? Inside constructor button new ImageButton(getDrawable(new Texture("PlayUp.jpg"))) only using one image atm button.setSize(150, 134) button.setPosition(camera.position.x, camera.position.y) stage new Stage(viewport) Gdx.input.setInputProcessor(stage) stage.addListener(new ClickListener() Override public void clicked(InputEvent event, float x, float y) System.out.println("Background touched") ) button.addListener(new InputListener() Override public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) return true Override public void touchUp(InputEvent event, float x, float y, int pointer, int button) System.out.println("Button touched") ) stage.addActor(button) part of render() method Override public void render(float delta) Gdx.gl.glClearColor(1, 0, 0, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) tapCatch.batch.setProjectionMatrix(camera.combined) tapCatch.batch.begin() stage.act(delta) stage.draw() tapCatch.batch.end() |
15 | How to make an application architecture a global strategy game? I am doing a global libgdx strategy, how can I properly design the architecture? So far, I'm in some kind of chaos, because there are different events that need to be shown to the player in the form of widgets. For example, one problem is that I need to understand how the Province class will display a message that there is a hunger problem. Should it immediately inside itself display a message? send event data to the main class of the game, which processes the data and, depending on the event, display the message or take some other action? do something else entirely? I had the idea to make a separate class of events and so that all game objects create this object and pass it to the main class of the game, which handles them and decides what to do with it, and if necessary, pass it to the players. And I read about the fact that there is a class java.util.EventObject. Is it worth implementing it with the help of it, or should it be implemented like that yourself? Or maybe it should be done in a completely different way? The game is turn based. There are separate provinces and the units move from one province to the neighboring one in 1 turn. At the beginning of each turn, a series of windows appear in turn, notifying of certain events, for example, famine in a province or enemy troops attacked a province, etc. There are classes of the province, the player, various UI windows, which display information about events. |
15 | Help on TileMapRenderer In my project, I'm trying to render a map using TileMapRenderer. But it doesn't show anything when I render it. But when I use some other files from a tutorial they are rendered correctly. When debugging my TileAtlas instance shows the size as 0. I have used Texture Packer UI for packing the images. Comparing with the tutorial's files, I can see that the index starts from 1 in my file and 0 in the tutorial. But changing it to 0 wouldn't work also. map.png format RGBA8888 filter Nearest,Nearest repeat none Map rotate false xy 0, 0 size 32, 32 orig 32, 32 offset 0, 0 index 1 Map rotate false xy 32, 0 size 32, 32 orig 32, 32 offset 0, 0 index 2 Map rotate false xy 64, 0 size 32, 32 orig 32, 32 offset 0, 0 index 3 Map rotate false xy 96, 0 size 32, 32 orig 32, 32 offset 0, 0 index 4 Map rotate false xy 128, 0 size 32, 32 orig 32, 32 offset 0, 0 index 5 Here is the begining of the tmx file. lt ?xml version "1.0" encoding "UTF 8"? gt lt map version "1.0" orientation "orthogonal" width "20" height "20" tilewidth "32" tileheight "32" gt lt tileset firstgid "1" name "a" tilewidth "32" tileheight "32" gt lt image source "map.png" width "256" height "32" gt lt tileset gt lt layer name "Tile Layer 1" width "20" height "20" gt lt data gt lt tile gid "2" gt lt tile gid "2" gt Apart from that the tutorial files and my files seems to be similar. Can anyone help me here. |
15 | LibGDX Shader does not work with FBO texture I have a shader and I want to run the shader on the whole rendered image at the end instead of each individual sprite that I render on screen. For this purpose I created an FBO, I render the all my images to the FBO and then I render to colorBufferTexture generated by the FBO. There is just one problem, the shader does not work when I render the FBO texture. The withoutFbo() method render the image with the shader working just fine, but the withFbo() method only renders the image without the shader. Also I know that the shader in withFbo() is working because if I try to render something other then the colorBufferTexture from the FBO the shader will work. So why isn't the shader working with the texture generated by the FBO? public class Application3 extends ApplicationAdapter float time Sprite sprite FrameBuffer fbo SpriteBatch batch Texture noiseTexture TextureRegion fboTexture ShaderProgram shaderProgram Override public void create() ShaderProgram.pedantic false batch new SpriteBatch() sprite new Sprite(new Texture("game.png")) sprite.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()) shaderProgram new ShaderProgram(Gdx.files.internal(Shader.GLITCH2.getVertex()), Gdx.files.internal(Shader.GLITCH2.getFragment())) noiseTexture new Texture(Gdx.files.internal(Shader.GLITCH2.getPath() "noise.png")) noiseTexture.bind(0) fbo new FrameBuffer(Pixmap.Format.RGBA8888, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false) fboTexture new TextureRegion(fbo.getColorBufferTexture()) fboTexture.flip(false, true) Override public void render() withFbo() withoutFbo() void withoutFbo() Gdx.gl.glClearColor(0, 0, 0, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) time Gdx.graphics.getDeltaTime() shaderProgram.setUniformi("u noise", 0) shaderProgram.setUniformf("u time", time) batch.setShader(shaderProgram) batch.begin() batch.draw(sprite, sprite.getX(), sprite.getY(), sprite.getWidth(), sprite.getHeight()) batch.setShader(null) batch.end() void withFbo() Gdx.gl.glClearColor(0, 0, 0, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) time Gdx.graphics.getDeltaTime() fbo.begin() batch.begin() batch.draw(sprite, sprite.getX(), sprite.getY(), sprite.getWidth(), sprite.getHeight()) batch.end() fbo.end() shaderProgram.setUniformi("u noise", 0) shaderProgram.setUniformf("u time", time) batch.setShader(shaderProgram) batch.begin() batch.draw(fboTexture, sprite.getX(), sprite.getY(), sprite.getWidth(), sprite.getHeight()) batch.setShader(null) batch.end() |
15 | box2dlights confuses ScreenUtils for screenshots in libGDX I take screenshots as usual in libGDX via ScreenUtils.getFrameBufferPixmap(), which works fine. Hoever, when I call RayHandler.updateAndRender() during rendering, then the screenshot only contains those assets rendered after this call. All other pixels in the screenshot are transparent. What is the best way to deal with this issue? |
15 | How to use moveTo Actor? How to use moveTo? I do so actor.addAction(Actions.moveTo(500, 500, 10)) but he does not move Thanks you UPDATE does not move my code public class MyActions extends ApplicationAdapter private Stage stage private Actor actor Override public void create () stage new Stage() actor new Actor() setSize(100, 100) Sprite actorSprite new Sprite(new Texture(Gdx.files.internal("badlogic.jpg")), 57, 10, (int)getWidth(), (int)getHeight()) Override public void draw(Batch batch, float parentAlpha) actorSprite.draw(batch, parentAlpha) stage.addActor(actor) actor.addAction(Actions.moveTo(500, 500, 1)) Override public void render () Gdx.gl.glClearColor(1, 1, 0, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) actor.act(Gdx.graphics.getDeltaTime()) stage.act() stage.draw() what's wrong? |
15 | LibGdx input data REQUIRED I am using the code below to ask users for their username. MyTextInputListener listenerz new MyTextInputListener() Gdx.input.getTextInput(listenerz, "Create Username", "") I have knowledge in PHP but beginner in Java LibGdx. I know that in HTML there is a REQUIRED lt input name 'username' required gt That's why I wanted to know the equivalent coding in LibGdx for the REQUIRED input. |
15 | Image Button coordinates are busted I have an image button and I set its position in create in this way imageButton.setPosition(orthographicCamera.position.x 150,150) The problem is that the position always changes, despite I set it in create. Also if I change device, I notice that the coordinates are busted, wrong, instead other views are right. If I write setPositionin render, the image button is faster than the camera, it gets away from the screen, but for other views, this doesn't happen because they follow the camera. Why? |
15 | Sounds overlapping when playing too many at the same time I am pretty novice when it comes to game sound management, so excuse my ignorance. I am having an issue when playing too many sounds at the same time where some sounds stop playing, or doesn't play at all, almost like some sounds overlap others. I've read some about the sounds using individual buffers and that there should be no problem playing these at the same time at runtime. When I only had a small ammount of sounds in the game, it all worked flawlessly. My SoundManager had no problem playing multiple sounds at the same time ( I loaded the sound to memory when I was going to play it and disposed it when it was done playing, approx. 5 seconds). My SoundManager Class I've recorded a video to better illustrate what this sound problem is. As you can hear in the video below, the attacking sounds can only be heard at some points, as for some enemy sounds. The idling sounds of the enemies (breathing and bat sounds) seem to work without issues, though. Video Thank you for helping, because I have no clue how to fix this issue. Is there something that I've left out in my SoundManager? |
15 | libGDX upload z axis of sprite to graphics card Background I want to obtain each fragments position via vertex interpolation to then calculate the light vector for phong shading (L Fragment pos light source pos ). Problem At the moment I am using libGDX's com.badlogic.gdx.graphics.g2d.Sprites to upload my 2d sprites via the batch to the graphics card. However they only transport the x and y information for each vertex ( I think in the shader z is 0). I also want to upload the z axis of the sprite for use with normal map based pixel shading (calculate the vector of the incoming light). Should I use a com.badlogic.gdx.graphics.Mesh for that or can I extend the Sprite class and somehow put the z axis in the vertices float array? If I should do that, how do I do this? |
15 | 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) |
15 | Box2D fixed timestep updating is twitchy on constant FPS I'm messing around with libgdx and box2d and I'm trying to implement sidescroller movement with fixed timestep logic according to the famous Fix Your Timestep! tutorial guide. However, logic updating seems to be twitchy and I'm not exactly sure why. Here's the render method where the issue lies public void render() handleCameraInput() handleTestBodyInputImpulse() handleTestBodyInputVelocity() accumulator Math.min(Gdx.graphics.getDeltaTime(), STEP) int logicStepCount 0 while (accumulator gt STEP) world.step(STEP, VELOCITY ITERATIONS, POSITION ITERATIONS) accumulator STEP logicStepCount Gdx.graphics.setTitle("FPS " Gdx.graphics.getFramesPerSecond() ", Logic steps " logicStepCount ", Test body vel " testBody.getLinearVelocity()) cam.update() update box2d world camera Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) renderer.render(world, cam.combined) renders box2d bodies From what I've noticed the logic while loop responsible for updating the physics sometimes doesn't execute (counter goes from 1 to 0 for one frame) and that seems to be causing the twitching. This is weird to me since delta time added to the accumulator is clamped and since the FPS is constant 60 on my machine I'd assume that the loop should always execute once. Am I doing something wrong? Is this behavior normal and is it something I am supposed to solve during rendering with interpolation? Complete minimal example can be found here on Gist and can be run on any LibGdx project with Box2d dependency. |
15 | AI pathfinding in mostly free space I'm working in an action strategy proyect. Consider it a RTS game. The game is in 2D (with LibGDX), and I have a lot of soldiers moving along. Now I have to implement the AI. Let me say some things about my current design The map has been constructed with tiles. However, I want to allow the soldiers to move in every direction so using the tiles as graph for A is not a good idea. The obstacles are given by collision rectangles. Maps will have a lot of free space, and collision rectangles don't fit the tiles that makes even worse the election of A with tiles. Waypoints, for the same reason, are not a good idea. I would need a very big net and soldiers would move in strange ways, as pointed out here http www.ai blog.net archives 000152.html I've taken a look to the LibGDX AI library. I would like to make soldiers follow the captain or use some kind of formation. Looks like this library is a good choice to make that. Some things I know I also have read about potential vector fields and navigation mesh. The fields look interesting, but I'm not sure of how to implement them for my case. They could be good for pahtfinding, but some soldier have to follow the captain and move in formation. I think nav meshes won't solve my problem. As I've said, I have a lot of free space, and soldiers can move whatever they want, so the question "how to move the soldier inside the mesh?" remains. QUESTIONS How to make a free space AI pathfinding which avoid my collision rectangles? How to make this compatible with formations like following the player across the map? Is there any way to use LibGDX AI to do this? |
15 | Box2D fixed timestep updating is twitchy on constant FPS I'm messing around with libgdx and box2d and I'm trying to implement sidescroller movement with fixed timestep logic according to the famous Fix Your Timestep! tutorial guide. However, logic updating seems to be twitchy and I'm not exactly sure why. Here's the render method where the issue lies public void render() handleCameraInput() handleTestBodyInputImpulse() handleTestBodyInputVelocity() accumulator Math.min(Gdx.graphics.getDeltaTime(), STEP) int logicStepCount 0 while (accumulator gt STEP) world.step(STEP, VELOCITY ITERATIONS, POSITION ITERATIONS) accumulator STEP logicStepCount Gdx.graphics.setTitle("FPS " Gdx.graphics.getFramesPerSecond() ", Logic steps " logicStepCount ", Test body vel " testBody.getLinearVelocity()) cam.update() update box2d world camera Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) renderer.render(world, cam.combined) renders box2d bodies From what I've noticed the logic while loop responsible for updating the physics sometimes doesn't execute (counter goes from 1 to 0 for one frame) and that seems to be causing the twitching. This is weird to me since delta time added to the accumulator is clamped and since the FPS is constant 60 on my machine I'd assume that the loop should always execute once. Am I doing something wrong? Is this behavior normal and is it something I am supposed to solve during rendering with interpolation? Complete minimal example can be found here on Gist and can be run on any LibGdx project with Box2d dependency. |
15 | LibGDX How can I draw a line at a specific angle I'm working on a 2D platformer, shooter game and I'm attempting to draw a line to serve as a guide to indicate where the player is shooting. The line should be drawn from the player's sprite to the mouse's position. I need to draw a line between the player and the mouse, at the angle from the player to the mouse, how can I do something like this? Here is a concept picture to explain what I'm talking about |
15 | Handling character with world object collision in libgdx and bullet I am using libgdx and bullet for my 3d mmo project. I have been able to detect collisions using a collision world with collision objects. This was working fine for things like detecting players hitting each other but I was having problems handling players hitting walls or other world objects. After some searching I came across rigid bodies and the dynamics world. This seemed like it would solve my issue but once I got my objects converted over to rigid bodies my collision handler is no longer detecting collisions and the player is still going through walls. I would like to not have to handle the low level details of players not going through walls but I would still like to be able to manually handle collisions of collision objects for things like spells or weapons. What is the best way to go about this? I am also seeing different bullet objects like static, kinematic, dynamic, but I am not sure which is best for my situation. I also am thinking that part of my problem may be that I am translating my character every update instead of updating its velocity. What is the best setup for accomplishing this? |
15 | How to achieve sprite reflection effect in libgdx I am currently working on an open world game similar to Pokemon using libgdx. I am currently stuck on this effect that I really want to be done before moving to other features of my game. How can I achieve the following water reflection effect? I also want it to shimmer like in this video "Pok mon Sapphire Reflections in the water Episode 4" 3 38 |
15 | libgdx android White screen after re create() but not resume() I have this weird issue only on android where if I push the home button, when I get back into the game it passes through resume() and it display by background texture correctly. But if I push the back button it destroy and when I get back it the game it calls create(), but it draws the background as a white texture instead. I searched a bit on the subject and what I know so far Android static variables are not reinitialized on activity recreation, so you must make sure that create() will initialize those variables. OpenGL will free the textures when the application loses focus, so this is why they must be reloaded when the application resume. Unfortunately, even having this information in mind while programming did not fix the issue. I'll just show important portion of the code below The asset manager is created statically, but not initialized private static AssetManager manager Then during the create() and resume() method, the manager is initialized and all the textures will be loaded afterwards. manager new AssetManager() When the app is destroyed, dispose() is called and the manager is nullified manager.dispose() manager null So given the code above, if the application is destroyed or resumed, they will both pass into the same initialization method that creates the assets manager and load textures. So why it only works on resume() and not on create() when the same code is actually called. A quick fix that worked was something I found on this forum which consisted in killing the application on disposal with the following code in the android project SOURCE https gamedev.stackexchange.com questions 102079 screen not rendering after restarting game Override protected void onDestroy() android.os.Process.killProcess(android.os.Process.myPid()) this line will kill process super.onDestroy() But I am not sure it is the right way to do things. |
15 | Game graphics taking too much memory of 0.5 GB I am developing a simple 2D game. I have multiple sprites. Each sprite has around 80 png frames of 265 256. I used LibGdx's Texture packer to package the atlas. Am enabling mimap using following code to pac TexturePacker.Settings settings new TexturePacker.Settings() settings.combineSubdirectories true settings.filterMin Texture.TextureFilter.MipMapNearestLinear settings.filterMag Texture.TextureFilter.Linear TexturePacker.process(settings, f.getPath(), outputFolderName, atlasFileName) Questions Are 80 images frames for single sprite too much? Is 0.5 GB memory usage too much for a simple game like Fruit ninja? How can i reduce my memory usage? Any other things i should try? |
15 | Why does rotating a polygon also translates it in libGDX? I'm using polygons for collision detection. Here is the code poly new Polygon(verticies) poly.setOrigin(100,100) poly.setRotation(45) renderer.setColor(Color.GREEN) renderer.begin(ShapeType.Line) renderer.identity() renderer.translate(poly.getOriginX(), poly.getOriginY(), 0) renderer.polygon(poly.getTransformedVertices()) renderer.translate( poly.getOriginX(), poly.getOriginY(), 0) renderer.end() Result, polygon is rotated, but it moves to the right. Here is the picture for 0, 30, 45, 60 , 90 degrees (from left to right). What am I doing wrong? |
15 | Libgdx sprite rotation (image quality) This one is probably really simple but I didn't find a solution. I'm trying to create a widget (speedometer) with libgdx. For the arrows I'm using the setRotation() function. But when the image is rotated, the quality drops. The result looks like this How can I improve the quality of the arrows? |
15 | Libgdx inputlistener scrolled is not working I am currently using libgdx. Below codes are added to a stage. this.addListener(new InputListener() public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) System.out.println("down") return true public void touchUp (InputEvent event, float x, float y, int pointer, int button) System.out.println("up") public void touchDragged(InputEvent event, float x, float y , int pointer) System.out.println("dragged") zoom(0.01f) public boolean scrolled(InputEvent event, float x, float y, int amount) System.out.println("scrolled") zoom(0.01f) return true everything is working just fine (touchUp touchDragged Touchdown) except scrolled. Can someone tell me what is the reason? edited for reply comment and answer On screen class outside stage, I think I already added like screen.set input processor(stage). So touch dragged is working properly and print message 'dragged' and zoom is working. But when I scroll, message 'scrolled' is not printed and zoom function is not called I think. Thank you for comment and answer |
15 | 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? |
15 | How to flip a box2d body when it can't move forward? LibGDX I'm attempting to create a simple enemy for a platformer. It should move forward constantly until it hits something like a wall, and then it should flip and move forward the other direction. How might I accomplish this? |
15 | Setting time for a particular action to be happened LibGdx In my LibGdx game,enemies are coming in to the screen one by one. I want to make enemeies appear at a particular time after the game starts. How can I do it efficiently? |
15 | LibGDX TiledMap Unit Scale I'm working on a 2D rpg style game and I'm currently rewriting my game to get a more clean and structured code. Some thing that has been bugging me is that I have no idea how unit scales work with the OrthogonalTiledMapRenderer, it's kind of like a "Hey it works, I don't know how, but it works" solution. Basically to scale my map up, since it's a pixel game I use renderer new OrthogonalTiledMapRenderer(map, 4) which seems completely wrong since I've seen other examples using things such as 1 32f. However using that makes me unable to even find my map in game when moving the camera. I've looked up on unit scales but I have a hard time grasping why and how I should use them and if they are really necessary. And by using the code above, which I'm guessing I use the wrong way, does that bring any problems? Thanks in advance! |
15 | Why can't I read .ttf file when running Android configuration? When running or debugging my game on Android device, I get this error in the logcat com.badlogic.gdx.utils.GdxRuntimeException Error reading file data fonts myFont.ttf (Internal) Which is created by this code line FreeTypeFontGenerator generator new FreeTypeFontGenerator(fontFile) where fontFile is defined like this FileHandle fontFile Gdx.files.internal("data fonts myFont.ttf") This doesn't happen when I run the desktop configuration. I know that for desktop configuration you have to define the working directory of your project, but I don't see such option in android configuration and it also makes no sense, so I don't think it's a "working directory" related problem. Obviously, the file is in the correct path. Also note that everything worked fine in my previous project. I created this new project by creating a new blank prj using libgdx setup and then copying all the classes and packages from the older project. So maybe it's a problem related to some Gradle file? |
15 | How to access coordinates of objects in bullet physics (libGDX)? I need to access the x, y and z coordinates of a bullet physics object. I'm assuming this is done via the transform matrix, but I have no idea which values mean what. There doesn't seem to be any information about it on the internet. How is this done? Is there a better was of doing it that I'm not aware of? |
15 | Libgdx touchup fired even when figure not on texture I've implemented a touchup listener for an actor in stage. Now what happens is that when user touch downs the sprite and releases finger, its all good. The problem is when user touch downs the finger, and drag it somewhere else (possibly to cancel the touch) and releases, it still fires the touch up event as if nothing ever happened. How do I stop that? Here's my code voiceToggle.addListener(new InputListener() Override public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) System.out.println("touched") return true Override public void touchUp(InputEvent event, float x, float y, int pointer, int button) System.out.println(event) still fires even if not on original touchdown element ) |
15 | Running and Jumping using Box2d and libgdx .this is my first trial on making a 2d game and currently struglling how to run and jump smoothly. My problem is when the player keep pressing on left or right botton then jump. the player won't jump, also when keep on holding left or right. the speed gets faster if (KeyInput.isPressed(KeyInput.Button.JUMP)) body.applyForceToCenter(0, playerJumpForce, true) if (KeyInput.isDown(KeyInput.Button.LEFT)) body.setLinearVelocity(new Vector2((body.getLinearVelocity().x (playerSpeed delta)), 0)) if (KeyInput.isDown(KeyInput.Button.RIGHT)) body.setLinearVelocity(new Vector2((body.getLinearVelocity().x (playerSpeed delta)), 0)) |
15 | LibGDX On the "slowness" of loading assets Many tutorials I've seen put the loading of assets via AssetManager in a dedicated screen which displays some progress bar or image while the loading happens in background. Each "real" screen then gets the resources it needs from the asset manager, typically in the constructor, eg public class GameScreen extends ScreenAdapter private MyGame game private Texture t1 private Sound s1 public GameScreen(MyGame game) this.game game AssetManager am game.getAssetManager() t1 am.get("....", Texture.class) s1 am.get("....", Sound.class) use t1 and s1 Now another source I've seen takes this concept a bit further and also does the actual get()s in the asset loading class, so screens don't have to do them themselves, eg in the Loader class public AssetManager am new AssetManager() public Texture t1 public Sound s1 ... am.load(...) am.load(...) am.load(...) finishLoading() or update().... ... t1 am.get(...) s1 am.get(...) ... in the screen class t1 game.am.t1 s1 game.am.s1 ... use t1 and s1 Now my question is is this good practice? What's the expensive part of loading assets, the AssetManager's .load()s or also the .get()s? (I thought it was only the .load()s.) Is removing the get()s from the screens really a performance gain? |
15 | Actor in Stage Does Not Update the MoveTo XY Location I am creating a game wherein an apple is being shot with an arrow. The apple's location is the XY location of the user input and the arrow actor has to move to that location using the code actor.moveto. The problem is the arrow only moves only once to the user input's direction. I know that the moveTo action of the actor is updated many times per second when I called stageArrow.act in the update method so I am wondering why the arrow only moves once. Here's my code appleclass.java public class AppleClass implements Screen Arrow arrow private final MainApp app public Image ShotImage public AppleClass(final MainApp app) this.app app this.stageApple new Stage(new StretchViewport(app.screenWidth,app.screenHeight , app.camera)) this.stageArrow new Stage(new StretchViewport(app.screenWidth,app.screenHeight , app.camera)) arrow new ArrowClass(app) Override public void show() InputMultiplexer inputMultiplexer new InputMultiplexer() inputMultiplexer.addProcessor(stageApple) inputMultiplexer.addProcessor(stageArrow) Gdx.input.setInputProcessor(inputMultiplexer) arrow() public void arrow() arrow.isTouchable() stageArrow.addActor(arrow) arrow.addAction((moveTo(Gdx.input.getX(),Gdx.input.getY(),0.3f))) gt only executes once. arrow.addListener(new InputListener() public void enter(InputEvent event, float x, float y, int pointer, Actor fromActor) if (Gdx.input.isTouched()) ShotImage.setVisible(true) ) Override public void render(float delta) Gdx.gl.glClearColor(0, 0, 0, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) update(delta) public void update(float deltaTime) stageApple.draw() stageArrow.draw() stageApple.act(deltaTime) stageArrow.act(deltaTime) ArrowClass.java public class ArrowClass extends Actor MainApp app AppleClass appleClass public Texture arrowTexture public ArrowClass(final MainApp app) this.app app arrowTexture new Texture("medievalarrow.png") this.setSize(arrowWidth, arrowHeight) this.setTouchable(Touchable.enabled) this.setBounds(app.screenWidth 0.45f,0,arrowWidth,arrowHeight) this.setOrigin(0,0) Override public void draw(Batch batch, float parentAlpha) super.draw(batch, parentAlpha) final float delta Gdx.graphics.getDeltaTime() this.act(delta) app.batch.begin() app.batch.draw(arrowTexture, getX(),getY(),getWidth(),getHeight()) app.batch.end() Any help will be highly appreciated. Thanks. |
15 | How to move Vector2 along angle? These are my Vector2's that I am using for this function. public Vector2 position new Vector2() public Vector2 velocity new Vector2() public Vector2 movement new Vector2() public Vector2 direction new Vector2() Here is the function that I use to move the position vector along an angle. setLocation() just sets the new location of the image. public void move(float delta, float degrees) position.set(image.getX() image.getWidth() 2, image.getY() image.getHeight() 2) direction.set((float) Math.cos(degrees), (float) Math.sin(degrees)).nor() velocity.set(direction).scl(speed) movement.set(velocity).scl(delta) position.add(movement) setLocation(position.x, position.y) Sets location of image I get a lot of different angles with this, just not the correct angles. How should I change this function to move a Vector2 along an angle using the Vector2 class from com.badlogic.gdx.math.Vector2 within the LibGDX library? I found this answer, but not sure how to implement it. Update I figured out part of the issue. Should convert degrees to radians. However, the angle of 0 degrees is towards the right. Is there any way to fix this? As I shouldn't have to add 90 to degrees in order to have correct heading. New code is below public void move(float delta, float degrees) degrees 90 Set degrees to correct heading, shouldn't have to do this position.set(image.getX() image.getWidth() 2, image.getY() image.getHeight() 2) direction.set(MathUtils.cos(degrees MathUtils.degreesToRadians), MathUtils.sin(degrees MathUtils.degreesToRadians)).nor() velocity.set(direction).scl(speed) movement.set(velocity).scl(delta) position.add(movement) setLocation(position.x, position.y) |
15 | Is there a Box2d b2World ShiftOrigin function in Libgdx? Is there an equivalent Box2d b2World ShiftOrigin function in Libgdx? I can't seem to find it. |
15 | How to mirror a texture in libGDX Is it possible to rotate my sprite in LibGDX? public class Flame private static final int FRAME COLS 6 private static final int FRAME ROWS 1 private Animation flameAnimation private Texture flameSheet private TextureRegion flameFrames private SpriteBatch spriteBatch private TextureRegion currentFrame private float stateTime private int xFlame private int yFlame private float rotation Some code here public void draw() stateTime Gdx.graphics.getDeltaTime() currentFrame flameAnimation.getKeyFrame(stateTime, true) I also try currentFrame.flip(true, false) but this doesn't work spriteBatch.begin() spriteBatch.draw(currentFrame, xFlame, yFlame) spriteBatch.end() |
15 | Libgdx SpriteBatch won't position correctly on Screen I have been trying to position my spritebatch correctly regardless of screen size but it simply wont scale..This is what I want to achieve on every screen size..I want my Sprite Object to be positioned at the center of the x axis on every screen size and on the first half of the screen (above dotted line) and have it scale as well..I have also noticed that spritebatch doesn't respect my gameheight and gamewidth instead opting for screenwidth and screenheight. The dimensions for my sprite anim are 900 by 700 and I am hoping it can scale for lower resolutions Code batch.draw(animation.getKeyFrame(elapsedTime, true), 20, app.midPointY 350, app.screenWidth, 465) |
15 | 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? |
15 | Sprite draw order in libgdx From other frameworks I know methods for easy ordering sprites within a spritebatch (to determine if a sprite has to be drawn in front or behind another sprite). For example in MonoGame XNA this is called Sprite.depth or Pyglet has its OrderedGroups. But I cannot find anything like that in libgdx. I've read that libgdx' scene2d has something like that but I don't want to use that as I use a entity system (ashley) and want to keep rendering separeted from the other logic. What is the appropriate way to set the draw order of libgdx sprites? |
15 | LibBDX create a tail when the object is moved I am looking for a way to implement in my game a kind of shadow tail which will be displayed after the object is moved. Should I use animation? If yes how? Here an example |
15 | Box2D collision between dynamic body I'm implementing Box2D for my 2d top down LIBGDX game and i have some struggle with two dynamic body. Currently, my two bodies are created that way BodyDef bodyDef new BodyDef() bodyDef.type BodyType.DynamicBody bodyDef.position.set(this.x, this.y) this.body world.createBody(bodyDef) PolygonShape collider new PolygonShape() collider.setAsBox(16, 16) FixtureDef fDef new FixtureDef() fDef.density 0f fDef.friction 0f fDef.restitution 0f fDef.shape collider body.createFixture(fDef) body.setUserData(this) collider.dispose() So basicly, no rotation, no friction and no restitution. Also, my world have a gravity of 0 (since it's a 2d top down game, i don't that want them to fall). When player 1 collide with player 2, player 2 is moved backward like it was push but i don't want that. I want it to stay where he is, blocking the path to player 1 but he can also move. Is there a way to do that ? I have looked for some tips like catching collision with the contact listener but i don't know what to do in the preSolve method. I'd like some help, thanks ! |
15 | LibGDX destroy object when not used I am developing a game where objects move in the screen. My object is instantiated in Y 0 and I want to destroy this object when it goes under the screen Height. So if (positionY ScreenHeight) I have to destroy this object to clean my game and prevent "lag". How to do this? I have a dispose method (this.dispose) but it cause the dispose of the app and I want destroy only the object. Thanks in advance |
15 | Why is alpha channel ignored in Texture I am binding a texture to draw over some geometry (using the ImmediateModeRenderer20) but the alpha channel of the texture turns into colour black when drawn. Why is that happening? My draw call loop looks sort of like this immediateModeRenderer20.begin(renderer.getUiCamera().combined, GL20.GL TRIANGLE STRIP) immediateModeRenderer20.color(new Color(1, 1, 1, 1)) immediateModeRenderer20.texCoord(distance, tc.y) immediateModeRenderer20.vertex(point.x, point.y, 0f) immediateModeRenderer20.end() |
15 | Networking Board Game Design Pattern I am currently working on a board game in Java with libgdx. It is supposed to be a multiplayer game, that you can play across multiple computers and for the sake of simplicity, I use kryonet. Even though I assume my friends are no cheaters, I want all the game logic to happen on the server. This is for learning purposes, so I get to know a clean approach of anti cheating. However, I have been looking for design approaches for days now and really can't get my head around how I am supposed to handle actions, their verifications and distributions. You can think of the game as turn based and similar to Monopoly, it especially has some sort of randomness (drawing event cards). At first, I came across FSM and thought it would be a perfect approach, because I could easily let a state process the input and send a corresponding package to the server, who does the validation and broadcasts it to the other clients, who then.. Yeah, what do they do with it? Simply updating the model (as of "Player 1 is not at tile 8) doesn't make too much sense, because I would then not have any actions, such as walking, state transitions, etc. (the game is running in an update method, with a delta parameter, so you usually step your game forwards here). The second approach I came across was an "action" approach, that strongly discouraged the use of a FSM, because they would easily get too big and too complicated to understand later on. Every Action would have an "isvalid()" function, so the server could check the model for the action to be legal and then broadcast it to the clients to "take action" (pun intended). Here again, I feel the need of a FSM on the server side, so I can validate, whether an action would be legal or not. Do you think it is fine to mix two approaches? Is there an major point in my understanding of the approaches, that is entirely wrong and leads me to some misconception? Thanks in advance and have a good weekend! |
15 | AI pathfinding in mostly free space I'm working in an action strategy proyect. Consider it a RTS game. The game is in 2D (with LibGDX), and I have a lot of soldiers moving along. Now I have to implement the AI. Let me say some things about my current design The map has been constructed with tiles. However, I want to allow the soldiers to move in every direction so using the tiles as graph for A is not a good idea. The obstacles are given by collision rectangles. Maps will have a lot of free space, and collision rectangles don't fit the tiles that makes even worse the election of A with tiles. Waypoints, for the same reason, are not a good idea. I would need a very big net and soldiers would move in strange ways, as pointed out here http www.ai blog.net archives 000152.html I've taken a look to the LibGDX AI library. I would like to make soldiers follow the captain or use some kind of formation. Looks like this library is a good choice to make that. Some things I know I also have read about potential vector fields and navigation mesh. The fields look interesting, but I'm not sure of how to implement them for my case. They could be good for pahtfinding, but some soldier have to follow the captain and move in formation. I think nav meshes won't solve my problem. As I've said, I have a lot of free space, and soldiers can move whatever they want, so the question "how to move the soldier inside the mesh?" remains. QUESTIONS How to make a free space AI pathfinding which avoid my collision rectangles? How to make this compatible with formations like following the player across the map? Is there any way to use LibGDX AI to do this? |
15 | LibGDX On the "slowness" of loading assets Many tutorials I've seen put the loading of assets via AssetManager in a dedicated screen which displays some progress bar or image while the loading happens in background. Each "real" screen then gets the resources it needs from the asset manager, typically in the constructor, eg public class GameScreen extends ScreenAdapter private MyGame game private Texture t1 private Sound s1 public GameScreen(MyGame game) this.game game AssetManager am game.getAssetManager() t1 am.get("....", Texture.class) s1 am.get("....", Sound.class) use t1 and s1 Now another source I've seen takes this concept a bit further and also does the actual get()s in the asset loading class, so screens don't have to do them themselves, eg in the Loader class public AssetManager am new AssetManager() public Texture t1 public Sound s1 ... am.load(...) am.load(...) am.load(...) finishLoading() or update().... ... t1 am.get(...) s1 am.get(...) ... in the screen class t1 game.am.t1 s1 game.am.s1 ... use t1 and s1 Now my question is is this good practice? What's the expensive part of loading assets, the AssetManager's .load()s or also the .get()s? (I thought it was only the .load()s.) Is removing the get()s from the screens really a performance gain? |
15 | Libgdx notification popup (something like Toast) on both Desktop and Android I'm trying to implement a notification system with LibGDX. As we know, Android has it's Toast which is great, but I can't use it in Desktop mode. I tried extending Dialog etc, adding as an actor and it all worked, but there's one problem it still needs to be within the 'stage' object range, cause I have to add the 'notification actor' to the stage. Do you have any ideas how to implement it in a static way, that the notification dialog label window would be 'callable' from the whole app? Here's my code public class Notification extends Dialog public enum NotificationType SUCCESS, FAIL, INFO static Skin skin new Skin(Gdx.files.internal("data notificationskin.json")) Label label public Notification(String text, NotificationType type) super("", skin) setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight() 10) setPosition(0, Gdx.graphics.getHeight() getHeight()) label new Label(text, skin) add(label).center() label.setColor(Color.BLUE) setKeepWithinStage(false) show() public void show() MoveToAction moveTo new MoveToAction() moveTo.setPosition(getX(), Gdx.graphics.getHeight() getHeight()) moveTo.setDuration(2f) MoveToAction moveBack new MoveToAction() moveBack.setPosition(getX(), Gdx.graphics.getHeight() getHeight()) moveBack.setDuration(2f) SequenceAction action new SequenceAction(moveTo, Actions.delay(1.0f), moveBack, Actions.removeActor()) addAction(action) To show the toast I need to call Notification not new Notification("You're now connected", SUCCESS) stage.addActor(not) which is bad it should be static. |
15 | LibGDX Headless System.in I started developing a little multiplayer game with LibGDX and Kryonet. I'm also using the headless backend for the server. So far everything went well, but now I'd like to create a command line parser for the server. I found out that I should make that in a separate thread, so I made a class for that. But the BufferedReader's readLine() method always returns with null (but it doesn't raise any exceptions). Here is the code I'm using public class ServerScreen implements Screen boolean headless Server server CLIParser cliParser null public ServerScreen(boolean headless) this.headless headless server new Server() server.start() if(headless) cliParser new CLIParser() cliParser.start() System.out.println("SERVER STARTED") Screen overrides omitted... public static class CLIParser implements Runnable public boolean started false public synchronized void start() if(!started) started true new Thread(this).start() public synchronized void stop() started false Override public void run() BufferedReader br new BufferedReader(new InputStreamReader(System.in)) System.out.println("cliParser run started") while(started) String line null try line br.readLine() catch (Exception e) System.out.println(e) if(line ! null) System.out.println("READ LINE " line) The cliParser starts up successfully, but the readLine() always returns null, and doesn't even blocks the code from running. I don't get any exceptions. I tried the CLIParser in a dummy project, and it works fine, so I assume this could be an issue with the headless backend. Here is the sample code I used import java.io.BufferedReader import java.io.InputStreamReader public class CliParserTester public CliParserTester() CLIParser cp new CLIParser() cp.start() public static void main(String args) new CliParserTester() public class CLIParser implements Runnable public boolean started false public synchronized void start() if(!started) started true new Thread(this).start() public synchronized void stop() started false Override public void run() BufferedReader br new BufferedReader(new InputStreamReader(System.in)) System.out.println(System.in) System.out.println("cliParser run started") while(started) String line null try line br.readLine() System.out.println(line) catch (Exception e) System.out.println(e) if(line ! null) System.out.println("READ LINE " line) |
15 | 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? |
15 | 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? |
15 | How can I get the instantaneous volume level of a sound at a particular playback point? How can I go about getting the current volume output of an audio file in libGDX? By that I mean of the actual file at its current play position. Essentially I want to write my own version of a plugin I was using in Unity for basic lip syncing. Depending how loud the audio is, a different mouth shape sprite will be shown. So for example if there was a sound with a sentance "what is that?" you would expect the "that" to be a different shape than the "what is," as it's louder. Is there a way to do this, to get the volume at a certain point? |
15 | LibGDX Is there a maximum amount of vertices for a PolygonShape? When you use PolygonShape.set(Vector2 vertices), is there a limit of vertices of the array which is passed to the method? |
15 | Using libGdx and Box2d for game and getting this error "incorrect checksum for freed object" I am new in game development and I am using libGdx with box2d in my game, whenever I try to switch screen (both screens has box2d bodies with Tiled map), I encounter the following error. java(610,0x70000297a000) malloc error for object 0x7f8d642fd600 incorrect checksum for freed object object was probably modified after being freed. set a breakpoint in malloc error break to debug The code which I use to switch screen is in render method if((mapPixelWidth 200) lt frog.body.getPosition().x PPM) game.gm.setPrefLevel(0) Gdx.app.postRunnable(new Runnable() Override public void run () Array lt Body gt bodies new Array lt Body gt () world.getBodies(bodies) for (Body b bodies) world.destroyBody(b) ) game.manager.unload("maps World1Level3.tmx") game.setScreen(game.levelLoading) Apart from this error, I want to ask that the way I am using Asset Manager and Box2d bodies are correct or not? |
15 | 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? |
15 | how to set volume of sound depending on the impulse a body receives in Libgdx Box2d? I am trying to set the volume of a bouncing sound of a ball depending on how hard the ball hits something. so the harder the ball hits a wall or a ground the more loud the bounce sound. I couldn't find anyway to get the impulse of a body other than the postSolve(Contact contact, ContactImpulse impulse) method inContactListner class. But i then realized that unlike the beginContact(Contact contact) method, postSolve(Contact contact, ContactImpulse impulse) gets called repeatedly until the contact ends. so it repeatedly plays the bouncing sound making it sound stalked and buggy. I cant use the beginContact(Contact contact) method because there is no way to get the impulse that the ball is receiving from this method. I tried to to use the velocity of the ball instead of impulse inside beginContact(Contact contact)but that didnt yield good results and found it very complicated as i had to consider both horizontal and vertical speeds. so my question is how can I make the sound play only once if i am using the postSolve(Contact contact, ContactImpulse impulse) method or is there any other solution to achieve what i am trying to do here? |
15 | How to run a method after a scene2d being rendered in libGDX I want to make a screenshot with ScreenUtils.getFrameBufferPixmap(x, y, w, h) I call this function in Actions.run(new Runnable ... ) in scene2d.ui, and the problem is that actions are called at very beginning of a new frame, so nothing is rendered yet. How to call this method properly, e.g. Scene.inTheEnd(run(ScreenUtils.getFrameBufferPixmap(x, y, w, h) )) ? |
15 | Scene2d cyrillic font I'm trying to use cyrillic(Russian) letters in libgdx Scene2d. I drop default.fnt and default 0.png (generated with BMfont) into folder assets of my Android project (other files such as uiskin.atlas,uiskin.json,uiskin.png are taken from libgdx examples). main code skin new Skin(Gdx.files.internal("uiskin.json")) Label label1 new Label("QWERTYqwerty ",skin) uiskin.json com.badlogic.gdx.graphics.g2d.BitmapFont default font file default.fnt , com.badlogic.gdx.graphics.Color green a 1, b 0, g 1, r 0 , white a 1, b 1, g 1, r 1 , red a 1, b 0, g 0, r 1 , black a 1, b 0, g 0, r 0 , , com.badlogic.gdx.scenes.scene2d.ui.Skin TintedDrawable dialogDim name white, color r 0, g 0, b 0, a 0.45 , , com.badlogic.gdx.scenes.scene2d.ui.Button ButtonStyle default down default round down, up default round , toggle down default round down, checked default round down, up default round , com.badlogic.gdx.scenes.scene2d.ui.TextButton TextButtonStyle default down default round down, up default round, font default font, fontColor white , toggle down default round down, up default round, checked default round down, font default font, fontColor white, downFontColor red , com.badlogic.gdx.scenes.scene2d.ui.ScrollPane ScrollPaneStyle default vScroll default scroll, hScrollKnob default round large, background default rect, hScroll default scroll, vScrollKnob default round large , com.badlogic.gdx.scenes.scene2d.ui.SelectBox SelectBoxStyle default font default font, fontColor white, background default select, scrollStyle default, listStyle font default font, selection default select selection , com.badlogic.gdx.scenes.scene2d.ui.SplitPane SplitPaneStyle default vertical handle default splitpane vertical , default horizontal handle default splitpane , com.badlogic.gdx.scenes.scene2d.ui.Window WindowStyle default titleFont default font, background default window, titleFontColor white , dialog titleFont default font, background default window, titleFontColor white, stageBackground dialogDim , com.badlogic.gdx.scenes.scene2d.ui.ProgressBar ProgressBarStyle default horizontal background default slider, knob default slider knob , default vertical background default slider, knob default round large , com.badlogic.gdx.scenes.scene2d.ui.Slider SliderStyle default horizontal background default slider, knob default slider knob , default vertical background default slider, knob default round large , com.badlogic.gdx.scenes.scene2d.ui.Label LabelStyle default font default font, fontColor white , com.badlogic.gdx.scenes.scene2d.ui.TextField TextFieldStyle default selection selection, background textfield, font default font, fontColor white, cursor cursor , com.badlogic.gdx.scenes.scene2d.ui.CheckBox CheckBoxStyle default checkboxOn check on, checkboxOff check off, font default font, fontColor white , com.badlogic.gdx.scenes.scene2d.ui.List ListStyle default fontColorUnselected white, selection selection, fontColorSelected white, font default font , com.badlogic.gdx.scenes.scene2d.ui.Touchpad TouchpadStyle default background default pane, knob default round large , com.badlogic.gdx.scenes.scene2d.ui.Tree TreeStyle default minus tree minus, plus tree plus, selection default select selection , com.badlogic.gdx.scenes.scene2d.ui.TextTooltip TextTooltipStyle default label font default font, fontColor white , background default pane , and get such result Where can be the problem? |
15 | Do I need to dispose Pixmap in Actor? I create Pixmap in Actor and don't know how to dispose it. Is it necessary in my case? class MyActor(x Float 0f, y Float 0f) Actor() var pixmap Pixmap(1, 1, Pixmap.Format.RGBA8888) var texture Texture(pixmap) var sprite Sprite(texture) init setPosition(x, y) sprite.setSize(32f, 32f) sprite.setPosition(this.x sprite.width 2, this.y sprite.height 2) override fun act(delta Float) sprite.setPosition(x sprite.width 2, y sprite.height 2) override fun draw(batch Batch?, parentAlpha Float) sprite.draw(batch) |
15 | swipe effect problem using only mesh and array libgdx I tried to combine matdesl's and libgdx's draw lines algo ang code. but i can only create a line. problem is i want to make a fruit ninja swipe effect but only knows this... problem is i want to make a fruit ninja swipe effect but only knows this... anyone try to help me on improving just a line to have a swipe effect like fruit ninja? public class GameTouch private static final int MAX LINES 1000 private OrthographicCamera camera private Mesh lineMesh private Vector3 unprojectedVertex new Vector3() private FixedList lt Vector2 gt list public GameTouch() this.camera new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()) lineMesh new Mesh(false, MAX LINES , 0, new VertexAttribute(Usage.Position, 2, "a pos")) list new FixedList lt Vector2 gt () public void update(float delta) camera.update() camera.apply(Gdx.gl10) if(Gdx.input.isTouched()) unprojectedVertex.set(Gdx.input.getX(), Gdx.input.getY(), 0) camera.unproject(unprojectedVertex) Vector2 input new Vector2() input.x unprojectedVertex.x input.y unprojectedVertex.y if(list.size gt 0) Vector2 temp new Vector2() float sqlen temp.set(input).sub(list.get(0)).len2() Array lt Vector2 gt tempA new FixedList lt Vector2 gt () if(sqlen gt 3) list.insert(input) lineMesh.setVertices(getVertices(list), 0, list.size 2) else list.insert(input) else if(list.size gt 0) list.removeIndex(list.size 1) if(list.size gt 2) lineMesh lineMesh.render(GL10.GL TRIANGLE STRIP) Gdx.gl10.glColor4f(0f, 0f, 1, 0.5f) private float getVertices(Array lt Vector2 gt list) float vertices new float list.size 2 int counter 0 for(Vector2 vertex list) vertices counter vertex.x vertices counter vertex.y return vertices private class FixedList lt T gt extends Array lt T gt public FixedList() super(Vector2.class) public FixedList(int capacity , Class lt T gt type) super(false, capacity , type) public void insert(T t) T items this.items size Math.min(size 1 , items.length) for(int i size 1 i gt 0 i ) items i items i 1 items 0 t |
15 | Static spawning locations for players, creatures, items in Tiled map editor I am using Tiled map editor. I am trying to add static spawning locations (x,y) for various entities (lets say 15) in my game. The best idea I had so far is something like this I am using a polygon collider named Player to declare the spawn location of the player. The width and height of this box is irrelevant. I have placed all "spawning colliders" in the same layer. I am using the Name tag to identify the type of the object. This works fine, however, inside the editor, I would like to be able to see the type of entity (Player, monster, item, etc.) without having to select the polygon collider and look at the Name tag each time. If I continue doing this I am going to end up with 100 grey boxes one next to the other. Is there any way of adding an indication on the collider that would represent its type (Player, monster, item, etc.) ? |
15 | LibGDX full screen display mode and camera resize I'm creating a simple 2D platformer and I have problem with my camera y position when I enter full screen mode. But first here's my code screenY Gdx.graphics.getHeight() public void updateCamera() camera.position.x (player1.getHitBox().x camera.position.x) if(screenY lt player1.getHitBox().getY() amp amp player1.getHitBox().getY() gt (screenY Gdx.graphics.getHeight())) screenChanger else if(player1.getHitBox().getY() lt (screenY Gdx.graphics.getHeight())) screenChanger screenY Gdx.graphics.getHeight() screenChanger camera.position.y (screenY screenY 2) camera.update() System.out.println(Gdx.graphics.getHeight() " " screenY) So here's my results 1) When I start the game all works fine 2) But when I enter to fullscreen here what I get 3) here how it looks when I zoom out my camera |
15 | Eclipse LibGDXgame doesn't load textures Our LibGDX project doesn't load textures after building on PC Android but when it's built from Eclipse using Ctrl F11 (Run Debug) everything is fine. What could be causing that? |
15 | Is there a Box2d b2World ShiftOrigin function in Libgdx? Is there an equivalent Box2d b2World ShiftOrigin function in Libgdx? I can't seem to find it. |
15 | How does the stateTimer parameter is initialized in this method getKeyFrame(stateTimer)? I have been following the tutorial https www.youtube.com watch?v 1fJrhgc0RRw amp list PLZm85UZQLd2SXQzsF a0 pPF6IWDDdrXt amp index 11 I an not able to understand what is stateTimer in getframe method and how is that initialized? |
15 | LibGDX how to remove PointLight that is attached a destroyed Body I have this code Override public void beginContact(Contact contact) fa contact.getFixtureA() fb contact.getFixtureB() if (fa null fb null) return if (fa.getUserData() null fb.getUserData() null) return final Body toRemove contact.getFixtureA().getBody().getType() BodyDef.BodyType.StaticBody ? contact.getFixtureA().getBody() contact.getFixtureB().getBody() Gdx.app.postRunnable(new Runnable() Override public void run () world.destroyBody(toRemove) ) It removes the FA body, but this body have a pointlight attached. I want to remove this PointLight attached. I have no idea how to do this . |
15 | How do I set the gravity of a plane world As you can see in the image, the character is set to move on a ground plane, however that causes an issue with Box2d's gravitational pull. The player can go sideways, upwards and downwards on the plane. Is there any way I can use gravity in this case? |
15 | Is using camera and viewport in Libgdx always necessary? I understand that camera and viewport are important to keep virtual measurement units and handle different aspect ratios and resolutions when building games with worlds bigger than the screen (e.g. side scrollers map based games). I am not sure whether it is the proper way to go for a simple game that fits on the screen entirely like a puzzle or card game for example. Is it still better to use camera and viewport in this case, or is it more simple, effective (and hence better) to use directly screen absolute coordinates for these types of games? Or to put it in other way what are the advantages to use camera and viewport for games that fit on the screen entirely? |
15 | LibGDX. How to fill background with shader? I want to make background of my game like lava via perlin noise. I've read some tutorials but they were too old and some api calls aren't exist already. If I understand right in libgdx I need to create a runtime generated texture (FrameBuffer) on x 0 and y 0 with width Screen width and height Screen height and apply shader to it. I tried to do class A extends ApplicationAdapter FrameBuffer background ShaderProgram shaderProgram public void create() background new FrameBuffer( Pixmap.Format.RGBA8888, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false ) shaderProgram stuff to pickup .vert and .frag Override public void render () Gdx.gl.glClearColor(0f, 0f, 0f, 0f) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) background.begin() batch.setProjectionMatrix( new Matrix4().setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()) ) batch.begin() batch.setShader(shaderProgram) batch.end() background.end() My shaders are simple red fill programs Vertex attribute vec4 a position uniform mat4 u projTrans varying vec2 v Pos void main() gl Position u projTrans a position v Pos gl Position Fragment ifdef GL ES precision mediump float endif uniform mat4 u projTrans varying vec2 v Pos void main() gl FragColor vec4(1.0, 0.0, 0.0, 1.0) Nothing has been drawn. I expect that all my viewport become red Function that picks up shaders is working, i tested at sprites |
15 | 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() ) |
15 | Switching lanes in an endless runner Some of you probably know the (once) popular mobile games Temple Run, Minion Rush or Subway Surfers. They all have the similarity of a lane system, which allows you to switch your position with a simple swipe to the left right. I am creating a game that also consists of three lanes. The only difference is your general movement going from left to right, thus making the lanes on top of each other. As LibGDX is my preferred 2D games framework, I want to accomplish this task with mostly built in functionality. Currently, I have two approaches, which both have flaws and resolving any of them would be a major help to me. 1) Using Actions. I could add an moveTo(upperLane.x, upperLane.y, 0.5f) if the player is in the middle, same goes for the lowerLane. But what, if he double swipes down, while being at the top? I would need so build a sequence, after the first actions started, or cancel the current action and start a new, but how to calculate the appropriate time for that large movement, while still "hanging between" two lines? 2) Implement impulses, that are able to add up in positive (up) and negative (down) directions. This would make it possible to move two steps at once, while having an appropriate time and also to move back up, while being in between two lanes, on your way down. Everything about impulses is plain speculation, as I have no further knowledge and don't want to use Box2D only for this purpose. 3) Feel free to give better suggestions! Special thanks to whom can point out the mechanic of one of the above mentioned games, which implement this feature flawlessly! |
15 | Libgdx change velocity of moveTo action I am trying to create physics for a ball in Libgdx. The ball starts moving after a pan and everytime the ball collides with a wall, a moveTo action is added to it. But my ball moves with a constant velocity (action time distance velocity). I want my ball movement to get slower smoothly. Here is my method for calculating velocity private float velocity(float panDistance) float coefficent 0.3f return panDistance coefficent in act method of the Ball I decrement velocity Override public void act(float delta) super.act(delta) if (velocity lt 100 amp amp velocity gt 0) ballImage.clearActions() velocity 3f delta When gesture detector detects a pan the method below is called. public void moveTheBall(float tanX, float tanY) if (ballImage.getActions().size 0) motionVector (int) (tanX Math.abs(tanX)) motionAngleTan tanY tanX panDistance (float) Math.sqrt((tanX tanX) (tanY tanY)) velocity velocity(panDistance) recursivelyAddActions(motionVector) in recursivelyAddActions() method private void recursivelyAddActions(int vectorDirection) AFTER SOME CALCULATIONS distance (float) Math.sqrt(((predictionX ballStartingPosX) (predictionX ballStartingPosX)) ((predictionY ballStartingPosY) (predictionY ballStartingPosY))) moveToAction Actions.moveTo(predictionX, predictionY, distance velocity) ballImage.addAction(moveToAction) this is not smooth and this does not work good. I need an advice to make this work better. Thank you. |
15 | 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) |
15 | How can I avoid assets reload if an Android activity is re created? I've put my libGDX view inside a bigger Android layout. When the user rotates the screen, a new layout specific for the orientation is drawn, for this reason, the activity is rebuilt from scratch forcing the libGDX view to reload all assets. I tried to store these assets in a static variable, but on the second time I create the libGDX view, they are not rendered correctly (it looks like textures are not loaded and everything is transparent). How can I avoid reloading heavy assets (models and textures)? |
15 | LibGDX, BitmapFont strange position behavior I'm using a Stage of LibGDX to draw a text, in my case the FPS. But after resizing, the position of the text does not behave properly. As you can see in the attached gif The resizing function does work correctly. Also here is my code of the UI renderer GameScreen screen BitmapFont font FreeTypeFontGenerator generator FreeTypeFontGenerator.FreeTypeFontParameter parameter private Texture map public UIStage(GameScreen screen) this.screen screen generator new FreeTypeFontGenerator(Gdx.files.internal("font acknowtt.ttf")) parameter new FreeTypeFontGenerator.FreeTypeFontParameter() parameter.size 24 parameter.borderWidth 2 parameter.borderColor new Color(0, 0, 0, 1F) parameter.borderStraight true font generator.generateFont(parameter) this.map new Texture(Gdx.files.internal("levels map " screen.map.getLevel().getName() ".png")) generator.dispose() Override public void draw() this.getBatch().setColor(1F, 1F, 1F, 1F) this.getBatch().begin() this.font.draw( this.getBatch(), "FPS " GameScreen.fpsLogger.getFPS(), 10, this.getViewport().getScreenHeight() 44) this.getBatch().end() How can I make my text behave properly? |
15 | what's wrong with my lookAt and move forward code? so am still in the process of getting familiar with libGdx and one of the fun things i love to do is to make basics method for reusability on future projects, and for now am stacked on getting a Sprite rotate toward target (vector2) and then move forward based on that rotation the code am using is this set angle public void lookAt(Vector2 target) float angle (float) Math.atan2(target.y this.position.y, target.x this.position.x) angle (float) (angle (180 Math.PI)) setAngle(angle) move forward public void moveForward() this.position.x Math.cos(getAngle()) this.speed this.position.y Math.sin(getAngle()) this.speed and this is my render method Override public void render(float delta) TODO Auto generated method stub Gdx.gl.glClearColor(0, 0, 0.0f, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) groupUpdate() Vector3 mousePos new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0) camera.unproject(mousePos) ball.lookAt(new Vector2(mousePos.x, mousePos.y)) if (Gdx.input.isTouched()) ball.moveForward() batch.begin() batch.draw(ball.getSprite(), ball.getPos().x, ball.getPos().y, ball .getSprite().getOriginX(), ball.getSprite().getOriginY(), ball .getSprite().getWidth(), ball.getSprite().getHeight(), .5f, .5f, ball.getAngle()) batch.end() the goal is to make the ball always look at the mouse cursor, and then move forward when i click, am also using this camera create the camera and the SpriteBatch camera new OrthographicCamera() camera.setToOrtho(false, 800, 480) aaaand the result was so creepy lol Thank you |
15 | How to monitor the collisions between multiple bodies I'm making a 2D platformer with Box2D and LibGDX, shooter, and I'm implementing the logic for a snail in the game. The basic idea is that it walks across the ground leaving a sort of, slime trail, and when the snail is not colliding with slime, it should create more. I've set it up to where it will move across the ground creating slime objects, but I'm looking for a way to detect if the snail is colliding with any slime. I have this in my World contact listener begin contact case Finals.SLITHERIKTER BIT Finals.SLIME BIT ((Slitherikter) ((fixtureA.getFilterData().categoryBits Finals.SLITHERIKTER BIT) ? fixtureA.getUserData() fixtureB.getUserData())).isColidingWithSlime true end contact case Finals.SLITHERIKTER BIT Finals.SLIME BIT ((Slitherikter) ((fixtureA.getFilterData().categoryBits Finals.SLITHERIKTER BIT) ? fixtureA.getUserData() fixtureB.getUserData())).isColidingWithSlime false Depending on that variable if(!isColidingWithSlime amp amp body.getLinearVelocity().y 0) slime.add(new Slime(body.getPosition().add(0, primaryFixture.getShape().getRadius()), color)) I understand why it doesn't work, but don't know what to do, Please help. EDIT For clarification, I should specify, that if the snail is colliding with slime, I don't' want it to make more because this works pretty well, but I"m attempting to severely limit slime production to increase performance. I only want to create new slime if there's no collision at all. |
15 | LibGDX buttons bounds are wrong I am making a simple gui in libgdx and run into this problem when you click on the button it's bounds (?) are wrong since if I click under it, the game registers it as a click. On the other end, if I click it at the top it won't get the click. It seems like the bounds are a bit under the button. I tried to set manually but nothing. Also i tried changing sizes. Looked here too this is almost the same but no answer.. tabl new Table() stage new Stage() tabl.setSize(stage.getWidth() 2, stage.getHeight() 2) tabl.defaults().size(500, 40) g game Gdx.input.setInputProcessor(stage) skin new Skin() TextureAtlas te new TextureAtlas(Gdx.files.internal("uiskin.atlas")) skin.addRegions(te) skin.add("default font", new BitmapFont()) skin.load(Gdx.files.internal("uiskin.json")) Pixmap r new Pixmap(100,100,Format.RGBA8888) r.setColor(0xff0000ff) r.fillRectangle(1, 1, 13, 13) Texture s new Texture(r) SpriteDrawable s1 new SpriteDrawable(new Sprite(s)) TextButton gam new TextButton("new games",skin) gam.addListener(new InputListener() Override public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) TODO Auto generated method stub g.setScreen(null) new Logger("e").setLevel(10) return true ) super.getS LabelStyle tt new LabelStyle(new BitmapFont(), Color.BLUE) Label l new Label("d",tt) tabl.add(gam) tabl.setDebug(true) stage.addActor(tabl) |
15 | Create a filled pixmap for box2d fixture I'm trying to make a pixmap that fills in a Box2D fixture. It would be kind of like a fill bucket. I've done this before, but I want it to work on rectangles and other polygons. Is there an algorithm to do is, or will I need to write on myself? Thanks. |
15 | How Can I Monetize With Startapp A Libgdx Game Made With Aide I have created a libGDX game with the AIDE IDE Android app. The game is working fine so I will be uploading it to the Play Store to make money. I'd like to use Startapp ads, how would I integrate it? I Will Using Aide Premium |
15 | Isometric Architecture Map Game Data I'm not sure this kind of question has been answered yet, if so i'm sorry to duplicate it. My question is rather simple I'm creating a simple Isometric game with libgdx, i'm using Tiled but only to design the map and render it with OrthographicMapRenderer. The map is a static map of 6864 6880 pixels, one tile is 59 43 pixels I wanted to do some pathfinding to my game, so I decided to store my map data into a simple 2D array like this int cells i j which would contains 0 if the tile is walkable or 1 if it's not, it is as simple as that ! Currently I've simply using basic formula to convert world cartesian coordinate to Isometric coord, and formula to get tile pos based on iso pos, (eg you input a iso coord, the function return a vector like lt 2,5 which is the 2nd x tile and 5th y tile. It perfecttly work as execepted, I also make it that iso tile coord is always positive ( lt 0,0 is at the top left corner of my world ) But here is my Question or doubt How to handle correctly the game data tile ? Does a 2D array is sufficient, if yes, how to, for exemple write a function that get if a tile is walkable or no based on tile coord ? ( example I click on my map, the coordinate is translated to tile coord ( lt 4,5 for example,) how to check if this tile is walkable ?, i dont get on how to do it i'm really lost. EDIT Ive successfully implemented the isometric logic I can convert world coordinate to tile coorinate ( eg (5075 4851) (203 28)) and the reverse but i'm confused on how to fill the 2d Array, use it for A algorithm and make the bridge between these coordinate and the 2D array Thank you for you help, Regard |
15 | How can I have margins or padding around a texture in libgdx? I am building a game using libgdx a 2048 like game and I draw the tiles of the board using textures (each texture represents a tile with the number 2 or 4 etc.) I would like tohave a small space around the square textures. How can I do this ? Thanks. |
15 | Missing texture after add new actors I want to add two types of characters multiple times but when I add a new actor to stage texture in "old" actors stops render. I can add multiple KnightActor (without RatActor) or multiple RatActor (without KnightActor). When I try to add multiple KnightActor and RatActor on one stage only textures from newest actors are rendered (one RatActor and one KnightActor) GameScreen.kt override fun render(delta Float) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) actorManager.addNewActors(stage) viewPort.camera.update() stage.act(delta) stage.draw() world.step(delta, 8, 3) debugger.render(world, viewPort.camera.combined) ActorManager.kt fun markToAdd(actor BaseActor lt gt ) toAdd.add(actor) fun addNewActors(stage Stage) toAdd.forEach actor BaseActor lt gt gt stage.addActor(actor) actor.addToWorld(worldService.getWorld()) Gdx.app.log("afterAdd", ( charactersOnStage).toString()) toAdd.clear() KnightActor.kt override fun draw(batch Batch, parentAlpha Float) super.draw(batch, parentAlpha) if (isMoving) frameStateTime Gdx.graphics.deltaTime DRAW TEXTURE val frame animationManager.getFrameAndChangeSpeed(AnimationType.KNIGHT WALK RIGHT, frameStateTime, getSpeed()) val frameX Float position.x (size.width 2) val frameY Float position.y (size.height 2) batch.draw(frame, frameX, frameY, size.width, size.height) END DRAW RatActor.kt override fun draw(batch Batch, parentAlpha Float) super.draw(batch, parentAlpha) if (isMoving) frameStateTime Gdx.graphics.deltaTime DRAW TEXTURE val frame animationManager.getFrameAndChangeSpeed(AnimationType.RAT WALK LEFT, frameStateTime, getSpeed()) val frameX Float position.x (size.width 2) val frameY Float position.y (size.height 2) batch.draw(frame, frameX, frameY, size.width, size.height) END DRAW AnimationManager.kt fun getAnimation(animationType AnimationType) Animation lt TextureRegion gt return AssetsManager.loadSprite(animationType.spriteFile, animationType.alias).getAnimationForSprite(animationType.alias, animationType.width, animationType.height) fun getFrameAndChangeSpeed(animationType AnimationType, stateTime Float, speed Float, looping Boolean true) TextureRegion val animation getAnimation(animationType) animation.frameDuration 1 speed return animation.getKeyFrame(stateTime, looping) |
15 | How do i initialize and use a Texture Array? LibGDX First of all, I am new to Java and LibGDX.. What I am trying to do is Load my texture images into an array so that I can reference them in my drawing code by number, rather than by name. I am drawing a tile map. Instead of this tile1 new Texture(Gdx.files.internal("grass.png")) tile2 new Texture(Gdx.files.internal("dirttile.png")) tile3 new Texture(Gdx.files.internal("watertile.png")) I would like it to be more like tile 1 new Texture(Gdx.files.internal("grass.png")) tile 2 new Texture(Gdx.files.internal("dirttile.png")) tile 3 new Texture(Gdx.files.internal("watertile.png")) ..so that later I can draw them by which tile I need..such as tileType worldMap i j will be an int number batch.draw(tile tileType , tileX, tileY) I can't figure out how to initialize array and load textures into it though in order to do this, without getting errors. Basically I need to draw my map based on numbers I have in a tile map like this int worldMap 1,1,1,1,1,1,1,1,1,1 , 1,1,1,1,1,1,1,1,1,1 , 1,1,1,1,1,1,1,1,1,1 , 1,1,1,3,3,3,1,1,1,1 , 1,1,1,3,3,3,1,1,1,1 , 1,1,1,3,3,3,1,1,1,1 , 1,1,1,1,1,1,1,1,1,1 , 1,1,1,1,1,1,1,1,1,1 , 1,1,1,1,1,1,1,1,1,1 , 1,1,1,1,1,1,1,1,1,1 , I need to draw the map tile based on the numbers in that map... 1 grass 2 dirt 3 water etc.... Still no luck getting the array working. |
15 | LibGDX keep camera within bounds of TiledMap I have a simple TiledMap which I can render fine. I have a player hopping (with Box2D) around and my camera follows the player around cam.position.set( player.position().x Game.PPM Game.V WIDTH 4, player.position().y Game.PPM, 0 ) cam.update() However, the camera will move "off" the TiledMap. How could I keep my camera on the TiledMap, so when I near the edges of my map, the camera stops scrolling and the player moves towards the edge of the camera? |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.