_id
int64
0
49
text
stringlengths
71
4.19k
15
libgdx scene2d DelayAction and SequenceAction I'm trying to get the delay action in scene2d working correctly. I have multiple image objects which I store in an array and I have managed to get them all displaying, scaling and moving correctly. I can't however seem to get them moving independently using the delay action. I have tried using the sequence action and that isn t working either I m trying to create transition effects using little squares that move off the screen. I have included a sample of the code im using below for (i 0 i lt scaleActions.length i ) ScaleByAction scaleAction new ScaleByAction() scaleAction.setAmount( 0.1f) scaleAction.setDuration(0.5f) scaleActions i scaleAction float increase 0 for (i 0 i lt delayActions.length i ) DelayAction delayAction new DelayAction() delayAction.setDuration(0.05f increase) increase 0.1 delayActions i delayAction for (i 0 i lt boxArray.length i ) SequenceAction sequence new SequenceAction(scaleActions i ,moveActions i ,delayActions i ) boxArray i .setOrigin(boxW 2, boxH 2) boxArray i .addAction(sequence) boxArray i .addAction(sequenceActions i ) boxArray i .addAction(scaleActions i ) boxArray i .addAction(moveActions i ) boxArray i .addAction(delayActions i ) public void addToStage() for (i 0 i lt boxArray.length i ) stage.addActor(boxArray i ) Everything seems to be moving and scaling at the same time, the delay doesn t look like it is even working. Hope you guys can help point out what I'm doing wrong.
15
How To generate spiky terrain in 2D? I am learning game design, and wanted to know how one can automatically generate spiky terrain (something like this Cavernaut, notice, the terrain at the sides?). I have heard about midpoint displacement algorithm. But How can I apply that to my problem, given that I would also like to increase decrease the randomness of the terrain. Also, Is there any helpful library for this in libgdx?
15
Call touchUp() programattically for sprite in LibGDX I'm trying to call touchUp() for a sprite i've created in my app. i'm getting success but the co ordinates do not match while i call it manually. final int x (int)mySprite.getX() 10 final int y (int)(Gdx.graphics.getHeight() (mySprite.getY() 5)) touchDown(x, y, 0, 0) this code calls method perfectly but positions do not match. x and y values that i get in touchUp() method is different. it call touch up event of another sprite.
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
Smooth camera movement between followed objects I have 2d game where my camera follows the player. Simplified, it copies the player position as its own. Now I have some other object in the game, that I want to camera to follow. This is easy enough by not setting the camera's position with the player's, but with the position of the other object. The problem is that this camera movement is instant. I'd like to have a more smooth transition (e.g. panning over the level to the given object). How can I achieve this?
15
Texture Packer Any way to make it combine intelligently I am making a Pokemon Clone, using libgdx. I have the different types of sprites e.g. Back, front, back shiny, and front shiny. The current way the Texture Packer combines the textures seems to be semi randomly. I would like to be able to tell it to put the sprites together based on number, because my sprites go 003 003b 003bs 003s Where the 003 is the pokedex number, and the b is for back, and s for shiny. Two questions here Is there a way to get it to sort the textures in some way? Is there a benefit to this sorting?
15
Libgdx AtlasTmxMapLoader with multiple tilsets I am working on a Libgdx game which loads Tiled maps. The current map I am working on makes use of two tilesets, one for shadow light and another for terrain and buildings. The general process I do, that has been working fine, is that I receive the sprite sheet from the artist, design the maps, then take the spritesheet file and split it using ImageMagick. From there I take the split images and create an optimized png and atlas file with TexturePacker. However, this is the first map I have made that makes use of multiple tilesets. The issue I am having is when loading the map with AtlasTmxMapLoader it relies on a single atlas file property in the map. I tried to merge my 2 images into a single atlas texture (keeping the same names indexes) but it only seems to render by first tileset tiles. Perhaps I am missing something simple. What is the correct way to handle multiple tilesets (how exactly should my atlas file be setup)?
15
SelectBox in LibGDX doesn't display and freezes the program after a click I am currently trying to apply an overlay with LibGDX over my 3D ModelBatch. Everything works fine except for the SelectBox. Once instanciated, it shows up on my screen I can click on it once but then it freezes. The drop down list is not displayed and the clicks are no longer registered by my application. However, if my second click is under the standard position of the list, that is where it should be drawn when it drops down, an item is selected but then any third click will just return the list to the original selected item and no click is registered by my application anymore. I am running the application on Desktop. Using break points in the SelectBox.class I was able to notice that the third and other next clicks are registered by the SelectBox.class as part of the list in the Listener responsible for selecting an item. selectBox new SelectBox lt Object gt (skin) selectBox.setItems(array) selectBox.setSelected("Custom") stage.addActor(selectBox) array in this case is an instance of Object containing only Strings. This is the only part of code I have related to the selectBox. I have tried using an array of String at first but then switched to Object as suggested on a LibGDX forum. I am currently using the latest Nightly Build of 2014 04 11 as I also need TextArea which is not yet in the stable release. However, I have tried the stable release 0.9.9 and it doesn't work either. Am I using the right code to declare my SelectBox, or what could I do to make the SelectBox behave properly that is display its list when clicked and return to a normal state after an item is selected?
15
Label does not maintain correct position within a Table I'm hoping the fix is quite simple, but this has become increasingly frustrating. I've built a minimally reproducable example. This is how the table is rendered And this is the corresponding code private Table testTable() Table table new Table() Skin skin new Skin(Gdx.files.internal("skin uiskin.json")) Label label1 new Label("String", skin) Label label2 new Label("Hello", skin) Label label3 new Label("World", skin) table.add(label1) table.row() table.add(label2).width(100).height(100) table.add(label3).width(200).height(200) table.setFillParent(true) table.debugAll() return table As you can see, the "Hello" and "World" labels are not centered within their logical tables. Further, even if I try .width(100).height(100).center(), or even .bottom().right(), for example, the two labels' positions are always fixed to the left, center of their logical table. The only way I could 'fix' the problem is by excluding the .width().height(), but I need them for my UI. Any thoughts?
15
create ipa without RoboVM in a project libgdx I am creating an application with libgdx , and I wish I could produce an IPA without using RoboVM , because since version 1.9 became a fee . I saw on the original documentation that you can do with the gradlew. https github.com libgdx libgdx wiki Gradle on the Commandline packaging the project command gradlew ios createIPA but I saw that still requires robovm . you can create an IPA without robovm ? or if there is a plugin that makes the IPA. I use Android studio (IntelliJ) Thank you
15
Box2d bodies that are really close together, are getting stuck I'm using a tiled tmx map, and I created a class that adds bodies to each tile within a certain layer. This has been working great so far except for when a character or an enemy moves around on the screen, its body gets stuck on an edge between two tiles. This seems to happen "sometimes" and in certain spots. Jumping makes you unstuck but it's annoying when it happens, and I tried increasing the position iterations, but the problem keeps reoccurring. Here's what my game looks like
15
Libgdx actor bounds are wrong The Actor's boundaries are not centered at the ButtonText but I used the setBounds() method. The higher the Y position is, the less centered is the boundary. The weird thing is that i only created and added to the Stage one button but the screen shows two. When i click the top button, the bottom one is the one highlighted. How can i fix that? import com.badlogic.gdx.Game import com.badlogic.gdx.Gdx import com.badlogic.gdx.files.FileHandle import com.badlogic.gdx.scenes.scene2d.Stage import com.badlogic.gdx.scenes.scene2d.ui.Skin import com.badlogic.gdx.scenes.scene2d.ui.TextButton public class MyGame extends Game Stage stage Override public void create() stage new Stage() FileHandle skinFile new FileHandle("data resources uiskin uiskin.json") Skin skin new Skin(skinFile) TextButton sas new TextButton("dd",skin) sas.setBounds(0, 500, 100, 100) stage.addActor(sas) Gdx.input.setInputProcessor(stage) Override public void dispose() super.dispose() Override public void render() super.render() stage.act(Gdx.graphics.getDeltaTime()) stage.draw() Override public void resize(int width, int height) super.resize(width, height) Override public void pause() super.pause() Override public void resume() super.resume()
15
LibGDX ShapeRenderer as principal game entity renderer I am trying to make a 2D game that is just a bunch of default figures like circles, arcs and quadrilaterals with no textures (similar to Super Hexagon), and for that I was using C and XNA long time ago, but recently I move my code to Java and LibGDX mostly using the ShapeRenderer library. The problem appears when, reading in internet, I found that render this figures is a more computational cost task than just draw a texture or sprite. But by the nature of this project I just can't use sprites or similar, mostly because I will drastically scale this entities in the game, and when I scale an image the result is just not nice, blurry and or pixelated. What I asking for is if is a bad idea to render pure shapes for a game (no images, except maybe the background and text)? is ShapeRenderer a good approach? Do I should try with another way to manage this "not affected by scale" entities? I have read some answer from here (like this or this) but they are focused on sprites, not just pure shapes. For now, I got acceptable results and the game run smootly even when I create a lot of shapes, but in the future I plan to use effects and so, and I don't know if render shapes is the best answer or if this will affect the performance of my game (the game is focus for PC platform). I'm not limited only to Java, and if exist another language framework that manage this with better result, I'm opened to learn it. Thanks!.
15
How to rotate a pixmap (LIBGDX) In my game I have a world with randomly generated islands. My islands are based on the pixel information of the LibGDX Pixmap class. Now I need to rotate the islands. For this I need to rotate the Pixmaps. Not for drawing, but for reading the pixel data of the rotated Pixmap afterwards. My problem is, that I don't know how to rotate the Pixmap, so I can read the pixel data of the rotated Pixmap. Drawing a rotated Pixmap works well, but I need the rotated data persisted, so I can read it. My code I started with, which doesn't work public Pixmap rotatePixmap(Pixmap pixmap, int angle) Sprite sprite new Sprite(new Texture(pixmap)) sprite.setRotation(angle) return sprite.getTexture().getTextureData().consumePixmap() How can I rotate the Pixmap, so the pixels are altered to the desired rotation?
15
Different Sprite sizes for animation I have a character which has a size of 32x64 when walking or standing. Using the libgdx animation class I can easily animate him with a texture atlas. When I want to make him attack however, the Sprite appears squished because the frames for the attack animation are 64x64 to accommodate the sword. My question is as the artist and programmer, would it make more sense to have each Sprite frame for every animation be 64x64? Or in code, resize the Sprite origin and bounds before the attack animation and set them back to 32x64 when the attack is done?
15
LibGDX Shader works fine on desktop but does not work at all on Android device I made a very basic shader that works perfectly fine on Desktop, but when I try it with an AVD the sprite affected by the shader is not drawn. I have tried with WQVGA API 16 and Nexus S API 23. I have also tried putting this in my shaders but then it doesn't work on Desktop nor android ifdef GL ES " version 300" precision mediump float else " version 130" endif My vertex shader is simply a "passthrough" version 130 attribute vec4 a color attribute vec3 a position attribute vec2 a texCoord0 uniform mat4 u projTrans varying vec4 v color varying vec2 v texCoord0 void main() v color a color v texCoord0 a texCoord0 gl Position u projTrans vec4(a position, 1.0) My Fragment Shader version 130 precision mediump float varying vec4 v color varying vec2 v texCoord0 uniform sampler2D u sampler2D uniform vec4 color1 uniform vec4 color2 void main() vec4 actualColor v color texture2D( u sampler2D, v texCoord0 ) if(actualColor.g gt actualColor.r) actualColor color1 else if(actualColor.r gt actualColor.g) actualColor color2 gl FragColor actualColor Edit I changed gl FragColor vec4(1.0, 0.0, 0.0, 1.0) in my fragment shader in order to test if a red rectangle would appear, but it failed. The red rectangle being the desktop version and on top being Android. If it helps I also get this error in my Android console libpng warning iCCP known incorrect sRGB profile libpng warning iCCP known incorrect sRGB profile libpng warning iCCP known incorrect sRGB profile libpng warning iCCP known incorrect sRGB profile libpng warning iCCP known incorrect sRGB profile emulator Listening for console connections on port 5554 emulator Serial number of this emulator (for ADB) emulator 5554 emulator emulator window was out of view and was recentered distrib android emugl host libs Translator GLES V2 GLESv2Imp.cpp glGetUniformLocation 1628 error 0x501 distrib android emugl host libs Translator GLES V2 GLESv2Imp.cpp glGetUniformLocation 1628 error 0x501 distrib android emugl host libs Translator GLES V2 GLESv2Imp.cpp glGetUniformLocation 1628 error 0x501 distrib android emugl host libs Translator GLES V2 GLESv2Imp.cpp glGetUniformLocation 1628 error 0x501 distrib android emugl host libs Translator GLES V2 GLESv2Imp.cpp glGetAttribLocation 988 error 0x501 distrib android emugl host libs Translator GLES V2 GLESv2Imp.cpp glGetAttribLocation 988 error 0x501 distrib android emugl host libs Translator GLES V2 GLESv2Imp.cpp glGetAttribLocation 988 error 0x501
15
Act on Right Mouse Button click on Button I want to be able to listen for a right mouse click onto a TextButton. Is this possible without removing the default ClickListener of the TextButton? If yes, how? Or should I use a different listener?
15
LibGDX collision with rectangle and circle I have 2 objects, A and B, both are classes with only values, so positions and dimensions are only values (float posX,posY). I have a render class which render A and B with shapeRenderer A is rendered as a rectangle and B as a circle, how could check if there is a collision ? edit I have a rectangle coming from up, when it hits the circle I have to stop the game
15
Creating metadata pack files for an existing sprite sheet I've just bought Oryx's Roguelike Tileset pack and I use LibGDX (flixel gdx to be precise). My question is, given this pre made sprite sheet format, what's the best way to integrate the sprites into the game I'm making? LibGDX uses TexturePacker, but that needs a special .pack file with metadata like where the sprites are located. I can't see a way to generate these from an existing spritesheet. Is there any other recommended technique?
15
Change the alpha blending color of scaled textures It looks like semitransparent pixels are blended with while color when textures are drawn scaled. It is very noticeable and looks ugly when textures are drawn on dark background. public class SomeScreen implements Screen private TextureRegion textureRegion Override public void show() Loading texture Texture texture new Texture(Gdx.files.internal("texture.png"), true) Setting filter to "linear" texture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear) Getting the region textureRegion new TextureRegion(texture, 0, 0, 64, 64) Override public void render(float delta) Clearing screen Gdx.gl.glClearColor(0.09f, 0.09f, 0.09f, 1f) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) Drawing textureRegion Game.instance.batch.begin() Game.instance.batch.draw(textureRegion, 100f, 100f, 256f, 256f) Actual texture region size is 64x64px Game.instance.batch.end() I need to get rid of that white noise around the shape, bud don't know how. Source image Draw results
15
How can I efficiently resize sprites every frame? I want to animate UI elements, like HP bars, by moving and resizing them. How can I efficiently resize sprites every frame? I am using the LibGDX framework.
15
libGDX without android dependancies I want to create a game that due to some assumptions doesn't make sense as a tablet game. I already created some frame (controllers, autowiring, build scripts, etc.) that would help me later on, but since Slick2D, that I currently basing it on, is no longer really supported I am considering switching to libGDX while it still not time expensive. My question is is it possible to easily get rid of all of Android dependencies? GUI scaffold generator doesn't allow to do that and I would like to know is it just generator's issue or is the library itself tied to Android dependencies? It's my main concern that would help me decide whether or not switch from Slick. EDIT Basically when I use GUI generator to scaffold project it creates at least 3 Eclipse projects core project, Android project depending on core, desktop project depending on Android. While it shouldn't a be problem to merge them into 1 bigger project and remove virtually dead code, I want to know if there would be left some Android dependencies that I couldn't remove to make it still runnable on desktop.
15
Making a pixel perfect viewport in LibGDX My game that uses LibGDX as the graphics library, should be playable with every display. Here's the problem It have to be pixel perfect. That means, the scale factor must be an integer value, so that my pixels do not stretch over two physical pixels resulting in flickering pixels which I obviously do not want. The player should see a constant amount Y of vertical space. The width is calculated by the screen resolution. My game field is designed for 4 3. Therefore a player with 16 9 or even 21 9 should see more in the horizontal space. Best example An usual Pong field. The field is 4 3. A player with 16 9 should see the same field size, but with more "empty" space on the sides. I've tried various approaches to achieve this. The first was the ScreenViewport, provided by LibGDX. Problem Adjusting the unitsPerPixel would result in a smaller playfield. Or even mirroring it. I could provide a high res playfield and scale it down with unitsPerPixels, but it is not very future proof (Think of providing a 4k field for a future 512k monitor). My second approach was a custom viewport. (No worries! It is written in Kotlin) worldWidth (screenHeight worldHeight).toInt() worldHeight (screenHeight worldHeight).toInt() setScreenBounds( screenWidth 2 worldWidth.toInt() 2, screenHeight 2 worldHeight.toInt() 2, worldWidth.toInt(), worldHeight.toInt() ) It tries to scale up the field by a integer number (making it pixel perfect). Problem The unscaled zones (that would be normally covered by the non integer scaling) are black. Black bars. Instead, I want to show the game world. Any ideas how to achieve this? Thanks!
15
How can I rumble vibrate my controller with libGDX? The com.badlogic.gdx.controllers.Controllers API only supports getting the input data (which works fine). Is there a way to make my controller rumble vibrate, possibly using some other classes? I tried using the org.lwjgl.input.Controllers class, which supports this, but the controllers don't get indexed there and I can not access them.
15
How can I draw Polyline and detect its collision with other objects? The idea is to draw trace of moving Actor and if some other Actor intersect it, some function would be called. I've been searching for solution to this problem in Intersector class, but it seems to me that the only way to do what I want is to implement my polyline as a Polygon and find intersections, but its totally inelegant. I'm sure there should be some smart way to do this.
15
Animation reset in libgdx i have an issue that i hope it's easy to resolve. I'm playing various animations in my libgdx created game. For a particular animation, i need that to play in loop mode but only if a particular condition is true. Simple this far. What i need is to "reset" the animation (i mean restart from sprite n 1) when the condition become true again after the animation stopped. I know that i can simply dispose the actual animation and create another one every time the condition is true, but this seems a complicated way to resolve this.. How do i change the value of the index used by that animation? Is it possible? Do i have to create a class that extends the Animation class from libgdx library?
15
how to fill alpha with color? model changes color completely G3dModelLoader modelLoader new G3dModelLoader(new JsonReader()) Model model modelLoader.loadModel(Gdx.files.getFileHandle("g3dj model.g3dj", Files.FileType.Internal)) ModelInstance modelInstance new ModelInstance(model) modelInstance.materials.get(0).set(ColorAttribute.createDiffuse(0, 0, 1, 1)) I want to replace only the alpha channel with blue color (one model, many colors)
15
Special character's with LibGDX's I18NBundle such as " " or " " are marked as unknown I am loading my I18NBundle like this assetManager.load("i18n language", I18NBundle.class) assetManager.finishLoading() i18NBundle assetManager.get("i18n language", I18NBundle.class) When I get(String key) the values of the german localization I get these symbols for the and characters. This is what it looks like when I use the debugger to see the mapped values In game, it will display Huser instead of H user. The french localization works fine with and . So I'm quite confused as why only the german localization fails.
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
How to detect collision only in non transparent texture? I am developing a game using libGDX. I am trying to detect the collision between bee and tube. I am using the following code to detect the collision. if(player.getBounds().overlaps(boundsBot)) player is a bee and boundsBot is Rectangle of tube. Since there is some transparency in bee image, this returns true even if it doesn't seem to collide. I understand the reason why this is returning true. I read this solutions. I understood the theoretical concept to the solve the problem but I couldn't achieve it using libGDX. Here is what I tried, if(Intersector.intersectRectangles(player.getBounds(), boundsBot, rectangle)) Gets the intersected rectangle System.out.println("Rectangle Bottom " rectangle) Converting texture to pixmap Texture texture player.getTexture().getTexture() if (!texture.getTextureData().isPrepared()) texture.getTextureData().prepare() Pixmap pixmap texture.getTextureData().consumePixmap() Trying to find transparency..... System.out.println("Format " pixmap.getGLFormat()) How can I solve this issue? Thank You!
15
LibGDX Scene2D ScrollPane I want to create a list of buttons with ScrollPane , but I cant create a ScrollPane . In the constructor method in the examples Skins are used (.atlas , .json files) but how to create these files? Skin skin new Skin(Gdx.files.internal("data uiskin.json")) Is there a program to generate this json ? As I noticed a lot of Scene2D elements need skins.
15
How to create groups in libGdx? Can any of you please demonstrate a simple example on how to use groups in libGdx ? so if i move the parent, then all the children will move with it and same goes for rotation and scaling. I looked for tutorials and example online but it seems that the latest version of libGdx did some changes to the Stage class. Thank you
15
Framerate independent game loops and discrete tasks When writing good framerate independent game code, you take some sort of deltaTime parameter in your main render() function and then scale your calculations based on that this is essential for things like physics engines. However, in my game there are often discrete tasks the AI system might add components representing a "task" to the agents that should be removed (finished) after x seconds have passed. To make a contrived example, if a task component takes 60ms to process, and the game is running at 60fps (16.6ms frame), then the first three frames will run, bringing the "work done" on that task to 50ms, and then one last frame will do 10ms of work, but then the remaining 6.6ms will be "lost", because the AI system won't run and schedule new work until the next frame. Ideally, I'd like to not lose the "loose change" of ms that occurs at the end of tasks. How do people normally deal with this? I can think of a few options Ignore it the shortest tasks will probably never be less than 100ms anyway, generally more in the 1 5 second range. It's not multiplayer, and provided the game can maintain 60 fps (which it probably can), the experience should be the same for all players. "Carry" the remainder over to the next frame. In the example above, give the agents 23.2ms of time to "spend" in the next frame. Amp up the framerate. At 60fps, the most time you can possibly waste is 16.6ms, but at 200fps you can lose at most 5ms. (Currently my logic loop and render loop are coupled and capped at 60fps, but I can easily change that.)
15
neon effect to textures libgdx I am working on a live wallpaper with Libgdx . I am wondering if I can give neon glow to my textures , at runtime . Is this possible? If yes can anybody give me any pointers?
15
Libgdx and Box2D TiledMap render is not smooth I'm building simple side scroller game. My player (square) move fast and it interacts with other world objects. Problem is when my player is moving it seems that all world is rendering somehow strange (for example box2d objects are not rendering smooth). When player is not moving everything is ok. Here pic when player is moving and here when my player stands still Here I add my code private OrthogonalTiledMapRenderer renderer mapLoader new TmxMapLoader() map mapLoader.load("level1.tmx") renderer new OrthogonalTiledMapRenderer(map, DIV) gamecam.position.set((gamePort.getWorldWidth() 2), (gamePort.getWorldHeight() 2), 0) public void update(float dt) world.step(1 60f, 6, 2) if(playerAndGroundTest) player.update(dt) float x gamecam.position.x gamecam.viewportWidth gamecam.zoom DIV float y gamecam.position.y gamecam.viewportHeight gamecam.zoom DIV float width gamecam.viewportWidth gamecam.zoom 2 DIV float height gamecam.viewportHeight gamecam.zoom 2 DIV renderer.setView(gamecam.combined, x, y, width, height) gamecam.position.set(new Vector2(player.getBody().getPosition().x, (gamePort.getWorldHeight() 2)), 0) gamecam.update() Override public void render(float delta) update(delta) Gdx.gl.glClearColor(0.4f, 0.4f, 0.4f, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) renderer.render() b2dr.render(world, gamecam.combined) here's Player update function public void update(float dt) body.setLinearVelocity(200 dt, body.getLinearVelocity().y)
15
ScreenSize vs. WorldSize While programming a game with LibGDX, I came across a problem. My OrthographicCamera wasn't centering in the right place. I was trying to center the camera by using the line of code gameCam.position.set(gamePort.getScreenWidth() 2, gamePort.getScreenHeight() 2, 0) But that centered the camera at (0, 0) so that you could see all four quadrants of the coordinate table. Here is the image NOTE I am using a FitViewport that was initialized like gamePort new FitViewport(MarioBros.V WIDTH, MarioBros.V HEIGHT, gameCam) Also public static final int V WIDTH 400 public static final int V HEIGHT 208 (in the MarioBros class) But after some fiddling with the code, I changed the line of code to this gameCam.position.set(gamePort.getWorldWidth() 2, gamePort.getWorldHeight() 2, 0) I changed it from ScreenSize to WorldSize and got this result I'm still unsure of what using WorldSize changed. What's the difference between the two?. Also, why did one work while the other didn't?
15
LibGDX How do you load huge spritesheets? As we know, there is a GL MAX TEXTURE SIZE on each mobile phone which makes things really hard. I write an app for all mobile devices and I need to load some huge spritesheets combined with 64 frames when each of them has 512x1024 dimensions. As I tested and read, I should load spritesheets lt 1024 so it will work on all mobile devices including IPhone3 and some old Androids. If I have a spritesheet 512x1024 with 64 frames, it's dimensions are really, really large for ex. if the spritesheet has 64 columns, it's with is 61000 px. Of course, I can cut it, but it gives me 64 images and I have no idea if this if efiicient of not. How do you handle things like this? Scaling the graphics down is not an option it lowers the quality and my game IS QUALITY. If someone has any experience I would be grateful!
15
Libgdx create rectangle Scence 2D I want to draw a empty rectangle around my gamescreen, to show "borders" around. I've tried pixmap. Works perfectly fine, but i could not find the option of change stroke width of the rectangle. I thougt about using texture, but i do not feel it's the best way. Due to there is no artwork into this border. It's just a thick line around the screen. Remember i want to create the border once and not recreate it everytime i render. Any suggestions?
15
GLSL Only draw arond point flashlight effect I'm currently trying to achieve a sort of flashlight effect in GLSL. I only want to draw textures within a certain distance of a specified point (the mouse position, for example). Here's a quick example drawing of the effect I wish to achieve I've successfully created a shader that checks the position from a certain point to the position of the fragment, and then discards the fragment if the distance is larger than the specified light radius. The frag shader looks like this version 400 ifdef GL ES precision mediump float endif in vec4 v color in vec2 v texCoords in vec2 v position out vec4 outColor uniform sampler2D u texture uniform vec2 u mousePos uniform float u lightRadius void main() float distance distance((v position 1.0) 2.0, u mousePosition) if(distance gt u lightRadius) discard outColor v color texture2D(u texture, v texCoords) The problem with this shader is that the visible area isn't a circle, it's an elipse. This is obviously because the screen aspect ratio is not 1 1. I've tried multiplying the Y values of all of the position variables with a resolution uniform, but it still remains an elipse. My other problem is that I wish to have smooth edges on my visible area. I've read up some on the subject and I see that you can use mix and or smoothstep to achieve this, but I'm unsure on how to implement it. Anyone got any suggestions?
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
Call touchUp() programattically for sprite in LibGDX I'm trying to call touchUp() for a sprite i've created in my app. i'm getting success but the co ordinates do not match while i call it manually. final int x (int)mySprite.getX() 10 final int y (int)(Gdx.graphics.getHeight() (mySprite.getY() 5)) touchDown(x, y, 0, 0) this code calls method perfectly but positions do not match. x and y values that i get in touchUp() method is different. it call touch up event of another sprite.
15
Can I use JBox2D on server with Box2D on libGDX on client? I want to use Box2D for my turn based game, made with libGDX. The client is supposed to do some prediction of physics after his input and I want to correct these calculations with server side calculations afterwards. As I do not want to run an entire libGDX project on my server (because there will be parallel games and a single game per GameRoom is not necessary), I thought about running JBox2D on the server and send the final calculations for correction purposes to my two clients. Can I e.g. step 10 seconds ahead at once with my server side physics and send the results to my client right away? I don't need small steps, because the server won't render them anyways Will these results mostly match with the client results of the built in libgdx box2d version? I will here use smaller steps, so the client can render the changes easily. Thanks in advance!
15
How to load background image in sprite class in libgdx? How can I insert a background image in sprite class? here is my code..Thank's and advance import com.badlogic.gdx.ApplicationListener import com.badlogic.gdx.Gdx import com.badlogic.gdx.graphics.GL20 import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.graphics.g2d.Animation import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.graphics.g2d.TextureRegion public class Sprite implements ApplicationListener Constant rows and columns of the sprite sheet private static final int FRAME COLS 5, FRAME ROWS 1 Objects used Animation lt TextureRegion gt walkAnimation Must declare frame type (TextureRegion) Texture walkSheet SpriteBatch spriteBatch A variable for tracking elapsed time for the animation float stateTime Override public void create() Load the sprite sheet as a walkSheet new Texture(Gdx.files.internal("cat2.png")) Use the split utility method to create a 2D array of TextureRegions. This is possible because this sprite sheet contains frames of equal size and they are all aligned. TextureRegion tmp TextureRegion.split(walkSheet, walkSheet.getWidth() FRAME COLS, walkSheet.getHeight() FRAME ROWS) Place the regions into a 1D array in the correct order, starting from the top left, going across first. The Animation constructor requires a 1D array. TextureRegion walkFrames new TextureRegion FRAME COLS FRAME ROWS int index 0 for (int i 0 i lt FRAME ROWS i ) for (int j 0 j lt FRAME COLS j ) walkFrames index tmp i j Initialize the Animation with the frame interval and array of frames walkAnimation new Animation lt TextureRegion gt (0.075f, walkFrames) Instantiate a SpriteBatch for drawing and reset the elapsed animation time to 0 spriteBatch new SpriteBatch() stateTime 0f Override public void resize(int width, int height) Override public void render() Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) Clear screen stateTime Gdx.graphics.getDeltaTime() Accumulate elapsed animation time Get current frame of animation for the current stateTime TextureRegion currentFrame walkAnimation.getKeyFrame(stateTime, true) spriteBatch.begin() spriteBatch.draw(currentFrame, 50, 50) Draw current frame at (50, 50) spriteBatch.end() Override public void pause() Override public void resume() Override public void dispose() SpriteBatches and Textures must always be disposed spriteBatch.dispose() walkSheet.dispose()
15
libgdx 2nd var of myClass()'s values saving to overriding 1st var of myClass() I'm using libgdx with Eclipse. PROBLEM In the class inputHandler I have a list of buttons, menuButtons, composed of 2 buttons playButton and retryButton. They both belong to the class simpleButton public static simpleButton playButton, retryButton I declared them as retryButton new simpleButton(100, 100, 40, 10, retryRegion, retryRegion) playButton new simpleButton(80, 80, 20, 20, assetLoader.playButtonUp, assetLoader.playButtonDown) (see note at end of question) But when I run the game only the 2nd button runs (in the above case, playButton). So I went to the class gameRenderer and used shapeRenderer to clearly see what was going on. shapeRenderer.rect(inputHandler.retryButton.bounds.x, inputHandler.retryButton.bounds.y, inputHandler.retryButton.bounds.width, inputHandler.retryButton.bounds.height) shapeRenderer.rect(inputHandler.playButton.bounds.x, inputHandler.playButton.bounds.y, inputHandler.playButton.bounds.width, inputHandler.playButton.bounds.height) Although only the 2nd button was displaying, the 2nd button now adopted the code for both the buttons. i.e. the 2nd button was now both the play and retry (replay) buttons and worked perfectly. note from before These aren't their actual sizes (the actual sizes are equal to the sizes of the texture regions of their art graphics) but for the sake of simplicity and legibility I changed them to simpler values. Pictures playButton on bottom (playButton working) retryButton on bottom (retryButton working) The simpleButton class public class simpleButton private float x, y, width, height private TextureRegion buttonUp private TextureRegion buttonDown public static Rectangle bounds public static boolean isPressed public simpleButton(float x, float y, float width, float height, TextureRegion buttonUp, TextureRegion buttonDown) this.x x this.y y this.width width this.height height this.buttonUp buttonUp this.buttonDown buttonDown bounds new Rectangle(x, y, width, height)
15
Libgdx How to overlay two images on Table I'm trying to set the player image inside the circle of the bars. I've tried to use stack, to position it topLeft but it does not work. Stack stack new Stack() healthbar new Image(new Texture(Gdx.files.internal("data ui healthbar.png"))) playerLook new Image(player.getFrame()) stack.add(healthbar) stack.add(playerLook) Table table new Table() table.top() table.setFillParent(true) table.add(healthbar).expandX().pad(10).left() table.add(playerLook).expandX().pad(10).left() stack.add(table) stage.addActor(stack)
15
Why does adding LIBGDX "fadeIn" action to a table in a group make the whole stage fade in? I'm trying to "fadeIn" a store "screen" which is really just an invisible group. I set the group to visible true, set the alpha to 0 and then do a "fadeIn" on the group. The problem is that the whole stage goes black (my clear screen color) and then fades back in. storeGroup.addAction(Actions.sequence(Actions.alpha(0), Actions.fadeIn(1))) I even went as far as to make the Table within my StoreGroup accessible and adding the action to that, but the result is the same. storeGroup.getTable().addAction(Actions.sequence(Actions.alpha(0), Actions.fadeIn(1))) Essentially I just want my store group to fade in over whatever is currently displaying, but the fade in seems to apply to every other actor in my Stage, not JUST the one I'm adding it to. Any help would be greatly appreciated, I've been working on this all morning and can't figure out why the "fadeIn" is applying to everything.
15
Setting Higher Z Index for Sprite For my game, I have to set highest z index for my sprite. At present, I wrote following code but didn't work for me. Sprite houseSprite new Sprite(pX, pY, textureManager.houseBgRegion.deepCopy(), mVertexBufferObjectManager) attachChild(houseSprite) houseSprite.setZIndex(500) sortChildren() My requirement did not satisfied with setting sprite in the HUD. So any how I have to apply highest z index. Also in my game sprites are dynamically generated as per game play. So members please share your thoughts.
15
libgdx get the value of a key I'm trying to do collision detection (which I have working well) but now I want to use it for a little more. I want to check special circumstances for the collision. Right now I'm checking for containsKey like so someCell. ... .getTile().getProperties().containsKey("collision") This works fine. But now I want to use the VALUE of that key to determine what the character hit and continue accordingly. If the value is null, just a normal hit. But if the value is a sign, and the user chooses, it can be read. Or if the value is a chest, if the user chooses to do so they can open it (but check that locked is indeed false first, or the user can unlock it). The thing is, I've looked everywhere and can't find a way to check the value of the key. And yes, I can just create a lot of keys but it would be easier to have one key that can carry many values and check and alter them based on user input or game circumstances. I tried theKey someCell. ... .getTile().getProperties().containsKey("collision") .value("someValue") theKey.value("someValue") but neither worked. So, my question to you is this how can I access and later edit the value of a custom key created in tiled map editor (should have mentioned that earlier, huh)? Any help would be appreciated.
15
How to create a Pixmap from an OrthographicCamera in LibGDX I am trying to create a picture based on what one of my OrthographicCamera can see. LibGDX has a ScreenUtils class that has a getFrameBufferPixels method, but it does not what I want as I want to get only what one camera sees, not the whole screen.
15
Remove background from sprite sheet after splitting I am using libgdx to implement a Parallax background. Now I need to show some animated object over the background. I downloaded a sprite sheet(with images of objects on white background), and split it using TextureRegion.split() method. But when I draw the objects to screen, white background is shown along with the object as in this image I tried using batch.enableBlending() but it didn't work. Is there any way to resolve this issue? Or should I code only using individual sprites with transparent background? Here is a brief code snippet public class Animator extends Actor int FRAME COLS 3, FRAME ROWS 3 Animation lt TextureRegion gt eagleAnimation Texture eagleSheet float stateTime Animator(Texture sheet) eagleSheet sheet TextureRegion tmp TextureRegion.split(eagleSheet, eagleSheet.getWidth() FRAME COLS, eagleSheet.getHeight() FRAME ROWS) TextureRegion eagleFrames new TextureRegion FRAME COLS FRAME ROWS int index 0 for(int i 0 i lt FRAME ROWS i ) for(int j 0 j lt FRAME COLS j ) eagleFrames index tmp i j eagleAnimation new Animation lt TextureRegion gt (0.09f, eagleFrames) stateTime 0f Override public void draw(Batch batch, float parentAlpha) stateTime Gdx.graphics.getDeltaTime() TextureRegion currentFrame eagleAnimation.getKeyFrame(stateTime, true) batch.enableBlending() doesn't work batch.draw(currentFrame, 250, 250, 264, 264) This is where I call above class from public class GameScreen implements Screen MyGdxGame game Texture eagleSheet OrthographicCamera camera Array lt Texture gt layers Stage stage public GameScreen(MyGdxGame game) this.game game stage new Stage(new ScreenViewport()) camera (OrthographicCamera) stage.getViewport().getCamera() layers new Array lt Texture gt () for(int i 1 i lt 6 i ) layers.add(new Texture(Gdx.files.internal("parallax img" i ".png"))) ParallaxBackground parallaxBackground new ParallaxBackground(layers) parallaxBackground.setSpeed(1) parallaxBackground.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()) stage.addActor(parallaxBackground) eagleSheet new Texture(Gdx.files.internal("eagle.png")) Animator animator new Animator(eagleSheet) animator.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()) stage.addActor(animator) Override public void render (float delta) Gdx.gl.glClearColor(1, 0, 0, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) stage.act() stage.draw() Override public void dispose () stage.dispose() Override public void show() Override public void hide() Override public void resume() Override public void resize(int x, int y) Override public void pause()
15
How to keep track of camera's rotation while it's being rotated? I'm building a 2D game where the sole interaction of the player is rotating what they can see (this is currently the camera, though it could be the world) by plus or minus 60 degrees. My current approach has their input rotating the camera. The issue I'm having is that I'm finding it impossible to keep track of how many degrees they've rotated it, since the camera is rotating and losing its initial position. (I'm using libgdx, however, I think this problem is framework independent.) Edit To help with the understanding, let me provide an example. Picture yourself in a school playground. You want to turn 90 degrees. To help you keep track, you mark the ground with the chalk in your hand. Turning 90 degrees is now easy since you have a reference point. Now imagine you're in space and trying to do the same thing. Instead of chalking the ground, you chalk yourself. It's now nigh impossible to know how much you turn by when you do.
15
Getting screen coordinates of actor I'm trying to tell if an actor exists at a screen position so I can do something if the actor is clicked on. To do this, I first need to get the screen coordinates of the actor so I can compare it to the coordinates where I click, however, I am having some difficulty. I am currently trying to do this Actor actor ... The position where I clicked obtained from touchDown() in my InputAdapter Vector2 screenPos ... Vector2 actorStagePos actor.localToStageCoordinates(new Vector2(0,0)) Vector2 actorScreenPos actor.getStage().stageToScreenCoordinates(actorStageCoordinates) Rectangle actorScreenBounds new Rectangle(actorScreenPos.x, actorScreenPos.y, actor.getWidth(), actor.getHeight()) if (actorScreenBounds.contains(screenPos)) System.out.println("An actor is there") However, the coordinates don't seem to be converting correctly. They end up slightly below and to the right of where they should be. At first, I thought this was caused because I'm scaling some of the Image actors, but it also did not work when nothing was scaled up.
15
Texture gets blurry when moving Box2D body I'm having this issue that is very annoying. Somehow the texture of the player body is getting blurry and leaving a slight trail with its colors when moving it. The interesting fact is, this only happens when the player is moving in the air. I set linear velocity to move the player on the ground and I'm applying force to center to move the player when he's jumping. I also tried using just a simple sprite. I played with Texture Filters and it didn't change anything. I even tried different textures. I'm calling Gdx.gl.glClear, which should have solved this issue. Here's the render method of my Screen class Override public void render(float delta) Gdx.gl.glClearColor( 1, 0, 0, 1 ) Gdx.gl.glClear( GL20.GL COLOR BUFFER BIT GL20.GL DEPTH BUFFER BIT ) camera.update() game.batch.setProjectionMatrix(camera.combined) world.step(Gdx.graphics.getDeltaTime(), 6, 2) debugMatrix game.batch.getProjectionMatrix().cpy().scale(pixelsToMeters, pixelsToMeters, 0) game.batch.setProjectionMatrix(camera.combined) tiledMapRenderer.setView(camera) tiledMapRenderer.render() game.batch.begin() player.update() player.render(game.batch) game.batch.end() debugRenderer.render(world, debugMatrix) Here's the part in the player's update method where I move him if he's jumping. This is the only movement in the game that causes the texture to get blurry. Same thing for the left side except the " " sign when applying force to center if (Gdx.input.isKeyPressed(Input.Keys.RIGHT) amp amp !rightCollision) playerDir Direction.right if (playerState State.jumping) playerBody.applyForceToCenter(250f, 0f, true) else playerState State.walking playerBody.setLinearVelocity(1.2f, 0f) And here's the part that makes the player jump if (Gdx.input.isKeyJustPressed(Input.Keys.UP) amp amp playerState ! State.jumping) playerBody.applyLinearImpulse(new Vector2(0, 500f), playerBody.getWorldCenter(), true) playerState State.jumping
15
How to prevent overlapping of gunshot sounds when using fast firing weapons So I am now trying to find sounds for my guns but when I grab a gun sound effect and play it in my game a lot of the sounds are either terrible sounding or have this horrible echoing effect because as a gun shoots sometimes the previous sound is playing still. public void shoot(float x, float y, float direction) if(empty) PlayHUD.message "No more bullets!" return if(reloading) return if(System.currentTimeMillis() lastShot lt fireRate) AssetsLoader.lmgSound.stop() return float dx (float) ( 13 Math.cos(direction) 75 Math.sin(direction)) float dy (float) ( 14 Math.sin(direction) 75 Math.cos(direction)) float dx1 (float) ( 13 Math.cos(direction) 75 Math.sin(direction)) float dy1 (float) ( 14 Math.sin(direction) 75 Math.cos(direction)) PlayState.effects.add(new MuzzleFlashEffect(x dx1, y dy1, (float) Math.toDegrees( direction))) PlayState.projectiles.add(new Bullet(this, x dx, y dy, (float) (direction (Math.toRadians(MathUtils.random( accuracy, accuracy)))))) if(OptionState.soundOn) AssetsLoader.lmgSound.play(OptionState.volume) bulletsInClip lastShot System.currentTimeMillis() Here is the code for where the sound plays. Every time this method is called the sound is called but it happens so often in this case that there is this terrible echoing. Any idea on how to fix this?
15
How to make a smooth circuit path in Universal tween engine? I tried to make a circuit by starting at point A, with waypoints B and C and final target at A again, and infinite repeats. What happens is that the path from A to B, B to C is smoothed, but path C to A ends with a "sharp" edge Is there any way to make it totally smooth?
15
How do I manually make a .pack file like TexturePacker (without using TexturePacker)? I am using libGDX and apparently the only way I see for creating a UI is with texture packs. I would say that since a texture pack is nothing more than JSON or XML file and a large png I could manually code a texture pack. How?
15
How do I manually make a .pack file like TexturePacker (without using TexturePacker)? I am using libGDX and apparently the only way I see for creating a UI is with texture packs. I would say that since a texture pack is nothing more than JSON or XML file and a large png I could manually code a texture pack. How?
15
Checking if Body is surrounded by other Bodies I'm trying to make a game like Rampart as practice. I have gotten to the point where I want to check if the castle is surrounded by walls and decide whether to fill in the area and continue the game, but I have no idea how to do this. I have thought about ray casting from the castle but it wouldn't work if there was a bend in the walls. So any help or suggestions would be great!
15
Rotating, moving and scaling a mask in a shader I want to rotate, move or scale a mask in a shader. But I have no clue to how perform these actions. My code Override public void create() batch new SpriteBatch() background new Texture(Gdx.files.internal("images background.png")) spritebackgournd new Sprite(background,Gdx.graphics.getWidth(),Gdx.graphics.getHeight()) foreground new Texture(Gdx.files.internal("images foreground.png")) mask new Texture(Gdx.files.internal("images mask.png")) spriteforegournd new Sprite(foreground,Gdx.graphics.getWidth(),Gdx.graphics.getHeight()) shader new ShaderProgram(Gdx.files.internal("shaders shader1.vert"), Gdx.files.internal("shaders shader1.frag")) Override public void render() batch.begin() spritebackgournd.draw(batch) batch.setShader(shader) Gdx.graphics.getGL20().glActiveTexture(GL20.GL TEXTURE0) spriteforegournd.getTexture().bind(0) texture.bind(0) shader.setUniformi("u texture", 0) Gdx.graphics.getGL20().glActiveTexture(GL20.GL TEXTURE1) spritemask.getTexture().bind(1) mask.bind(1) shader.setUniformi("u mask", 1) Gdx.graphics.getGL20().glActiveTexture(GL20.GL TEXTURE0) spriteforegournd.draw(batch) batch.end() batch.setShader(null) The vertex shader attribute vec4 a position attribute vec4 a color attribute vec2 a texCoord0 uniform mat4 u projTrans varying vec2 v texCoords void main() v texCoords a texCoord0 gl Position u projTrans a position The fragment shader varying vec2 v texCoords uniform sampler2D u texture uniform sampler2D u mask uniform mat4 u projTrans void main() vec4 texColor texture2D(u texture, v texCoords) vec4 maskColor texture2D(u mask, v texCoords) gl FragColor texColor maskColor.a What I would like to be able to is to scale, rotate and move the mask in the shader. How can I do this?
15
LibGDX EXCEPTION ACCESS VIOLATION error when recreating previously disposed Box2DLights light I just installed the Box2DLights dependency for LibGDX and I added a cave with 2 ConeLights inside. The first time I render the cave, everything works as expected. Then when I exit the cave, I make sure to dispose() all the lights. Then if I enter the cave again and try to create the same 2 ConeLights, it gives me this exception with a big error log (PasteBin added at the bottom of this post). If I don't dispose() the lights when exiting the cave, it won't crash the second time, but it will keep adding lights and it will get brighter and brighter and it's bad for performance. It doesn't matter if I use a PointLight or a ConeLight, the same exception will occur. Everytime a map change occurs, destroyLighting() and then loadLighting() for the new map is called. The error happens when a ConeLight is created, the second time when you enter the cave (4th line in the loadLighting() method) loadLighting() for(MapObject o lightingObjects) EllipseMapObject circleMapObject (EllipseMapObject) o Ellipse ellipse circleMapObject.getEllipse() Light light new ConeLight(rayHandler, 60, new Color(255,225,166,1), 100, ellipse.x, ellipse.y, 90, 90) light.setSoftnessLength(0) lights.add(light) destroyLighting() for(Light light lights) light.dispose() lights.clear() The error log https pastebin.com 1v36aNPg
15
Saving and Loading the Game (Automatically or Manually) via Internal Storage Only (Tablet PC Issues) Here is my question. When making a game app for Android, I considered first the device. It's no problem to save progress everything (from levels to records) on a smartphone because it has an SD Card slot. Exception to this, the tablet PC, it can really nothing but on internal only storage. For example, I'm using this tutorial for audio spectrum (see http www.youtube.com watch?v 5cN1VzZXcdo) that involves copying from internal to external in order to detect frequency. It works on the desktop but not on the Android device (Tablets only i.e. Google Nexus Tablet ). Is there a way to optimize save load game problems due to internal external device issues? Plus, additionally, what's the reason why my device won't work on tablets, except the desktop, while testing the audio spectrum code and why? Also, is it the same with saving loading game?
15
Libgdx problem while converting TextureRegion to Pixmap I'm developping a Tile base game where I have to generate transition tiles. To do so, I have a method that generate those tiles from 2 existing one and 1 "filter tile". I use this method to make a pixMap from the region I retrieved from my TextureAtlas. public Pixmap getPixMapFromRegion(TextureRegion region) Texture texture region.getTexture() TextureData data texture.getTextureData() if (!data.isPrepared()) data.prepare() Pixmap pixmap data.consumePixmap() int width region.getRegionWidth() int height region.getRegionHeight() Pixmap px new Pixmap(width, height, Format.RGBA4444) for (int x 0 x lt width x ) for (int y 0 y lt height y ) int colorInt pixmap.getPixel(region.getRegionX() x, region.getRegionY() y) return px Them I apply this method public Pixmap generateMixedTile(TiledMapTileSet tileset, AssetManager assMan,String template, TextureRegion region1, TextureRegion region2) TextureAtlas atlas assMan.get(".. core assets tuiles MergeFilter.atlas") AtlasRegion region atlas.findRegion(template) Pixmap templ getPixMapFromRegion(region) Pixmap img1 getPixMapFromRegion(region1) Pixmap img2 getPixMapFromRegion(region2) Pixmap res newPixmap(region.getRegionWidth(),region.getRegionHeight(),Format.RGBA4444) for (int y 0 y lt templ.getHeight() y ) for (int x 0 x lt templ.getWidth() x ) if(0xFF000000 templ.getPixel(x, y)) res.drawPixel(x, y, img1.getPixel(x, y)) else res.drawPixel(x, y, img2.getPixel(x, y)) return res It seems that after asking again and again for the same texture in the AssetManager, I get a Couldn't load file .. core assets tuiles Water3.png Exception. But this happen after the system success a lot of time to access that same file. So I don't know how I could handle that because I thought that using assetManager and Atlas was the bests practices Any Idea of how to fix that or to do it in another way?
15
"Pixel perfect" camera positioning in 2d game I am writing a 2d game using LibGDX. The view to the game world is top down. The game shows a grid of lines, which looks nice when the camera is at its initial position (0,0). The problem is now that when I move (shift) the camera left right up down this grid sometimes becomes a bit blurry, so the lines do not look perfectly sharp any more. I assume this is because in these cases the grid lines are not exactly on screen pixels, but somewhere in between. Is this correct? In any case Are there any "best practices" how to address this problem (not necessarily LibGDX specific)?
15
Libgdx converting between two camera coordinates I had a similar issue to the question here Why is my text is too large even when scaled to .05f in libGDX? So I created a second camera for my text elements. I'm rendering the text above some other elements, and under others, so I was trying to map between the two camera's coordinates when rendering. That seems to be working OK, but I need to invert the y coordinate during the transformation. I'm wondering why that's the case? Here's the code Setup camera OrthographicCamera camera new OrthographicCamera(VIEWPORT UNITS, VIEWPORT UNITS (height width)) camera.position.set(camera.viewportWidth 2f, camera.viewportHeight 2f, 0) Setup text camera FitViewport fitViewport new FitViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()) fitViewport.apply(true) gameContext.setHudViewport(fitViewport) OrthographicCamera textCamera fitViewport.getCamera() ... later, during render(), convert between coordinates Vector3 textPosition new Vector3(fontX, fontY, 0) camera.project(textPosition) textPosition.y Gdx.graphics.getHeight() textPosition.y why? textCamera.unproject(textPosition) font.draw(spriteBatch, text, textPosition.x, textPosition.y)
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
Is there a difference in these two ways of rendering sprites? I use an OrthogonalTiledMapRenderer renderer new OrthogonalTiledMapRenderer(world.getMap()) and I wonder if there is a differnce between this call renderer.getSpriteBatch().draw(sprite, sprite.getX(), sprite.getY()) and this sprite.draw(renderer.getSpriteBatch()) If there is a difference, what is it?
15
Rotating, moving and scaling a mask in a shader I want to rotate, move or scale a mask in a shader. But I have no clue to how perform these actions. My code Override public void create() batch new SpriteBatch() background new Texture(Gdx.files.internal("images background.png")) spritebackgournd new Sprite(background,Gdx.graphics.getWidth(),Gdx.graphics.getHeight()) foreground new Texture(Gdx.files.internal("images foreground.png")) mask new Texture(Gdx.files.internal("images mask.png")) spriteforegournd new Sprite(foreground,Gdx.graphics.getWidth(),Gdx.graphics.getHeight()) shader new ShaderProgram(Gdx.files.internal("shaders shader1.vert"), Gdx.files.internal("shaders shader1.frag")) Override public void render() batch.begin() spritebackgournd.draw(batch) batch.setShader(shader) Gdx.graphics.getGL20().glActiveTexture(GL20.GL TEXTURE0) spriteforegournd.getTexture().bind(0) texture.bind(0) shader.setUniformi("u texture", 0) Gdx.graphics.getGL20().glActiveTexture(GL20.GL TEXTURE1) spritemask.getTexture().bind(1) mask.bind(1) shader.setUniformi("u mask", 1) Gdx.graphics.getGL20().glActiveTexture(GL20.GL TEXTURE0) spriteforegournd.draw(batch) batch.end() batch.setShader(null) The vertex shader attribute vec4 a position attribute vec4 a color attribute vec2 a texCoord0 uniform mat4 u projTrans varying vec2 v texCoords void main() v texCoords a texCoord0 gl Position u projTrans a position The fragment shader varying vec2 v texCoords uniform sampler2D u texture uniform sampler2D u mask uniform mat4 u projTrans void main() vec4 texColor texture2D(u texture, v texCoords) vec4 maskColor texture2D(u mask, v texCoords) gl FragColor texColor maskColor.a What I would like to be able to is to scale, rotate and move the mask in the shader. How can I do this?
15
Change the alpha blending color of scaled textures It looks like semitransparent pixels are blended with while color when textures are drawn scaled. It is very noticeable and looks ugly when textures are drawn on dark background. public class SomeScreen implements Screen private TextureRegion textureRegion Override public void show() Loading texture Texture texture new Texture(Gdx.files.internal("texture.png"), true) Setting filter to "linear" texture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear) Getting the region textureRegion new TextureRegion(texture, 0, 0, 64, 64) Override public void render(float delta) Clearing screen Gdx.gl.glClearColor(0.09f, 0.09f, 0.09f, 1f) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) Drawing textureRegion Game.instance.batch.begin() Game.instance.batch.draw(textureRegion, 100f, 100f, 256f, 256f) Actual texture region size is 64x64px Game.instance.batch.end() I need to get rid of that white noise around the shape, bud don't know how. Source image Draw results
15
share assets beetween platforms What is the good way to share assets between platforms (android, desktop, etc) ? by default there is an assets folder in each platform folder.
15
Create apk from libgdx project What is the basic procedure to create the signed apk for my libGDX project? I am new to libGDX so provide some guidance. I am talking about deploying apk to the Android market. I have to ask this question because my Galaxy SX2 display only blank screen.
15
what makes render() and update() change frame 60 times every second in LibGDX Whenever we declare the render(float deltatime) or update(float deltatime), in any class, it automatically become a method that is repeated 60 times per second. But what makes this method repeat itself 60 fps? What makes the method do that? In some classes, I am not implementing any other interface or expending any abstract class but that still makes the render(float deltatim) and update(float deltatime) work. Also, even though I do expend a interface like Game, how does the render(float deltatime) work? I mean, there is no special code within the render() in the Game interface class as well.
15
Implementing Scrolling Background in LibGDX game I am making a game in LibGDX. After working for whole a day..I could not come out with a solution on Scrolling background. My Screen width n height is 960 x 540. I have a png image of 1024 x 540. I want to scroll the background in such a way that it contuosly goes back with camera x as per camera I tried many alternatives... drawing the image twice ..did a lot of calculations and many others.... but finally end up with this dirty code if(bg x2 gt Assets.bg.getRegionWidth()) calculated it to position bg .. camera was initially at 15 bg x2 (16 4 camera.position.x) bg x1 bg x2 Assets.bg.getRegionWidth() else bg x1 (16 4 camera.position.x) 224 this 16 is not proper I think there can be other ways bg x2 bg x1 Assets.bg.getRegionWidth() drawing twice batch.draw(Assets.bg, bg x2, bg y) batch.draw(Assets.bg, bg x1, bg y) The Simple idea is SCROLLING BACKGROUND WITH SIZE SOMEWHAT MORE THAN SCREEN SIZE SO THAT IT LOOK SMOOTH. Even after a lot of search, i didn't find an online solution. Please help.
15
Make camera move constantly upwards in box2d world Im using libGdx to develop a 2d game, which has the following The world moves in an upward direction by having a camera follow the player's y position. The user only controls player's x movement, the y is a constant speed. What i want to do now is let the user control the players x and y movement and let the camera move constantly up without following the player. What is the best way to do this? This is what i tried in Render() player.body.setTransform(fingerPosition.x, fingerPosition.y, player.body.getAngle()) box2dCamera.position.y box2dCamera.position.y cameraSpeed box2dCamera.update() box2dSpriteBatch.setProjectionMatrix(box2dCamera.combined) This worked but all my collisions stopped working with other box2d bodies. Do i need to update each body in my game with the recalculated camera some how? How would I do this?
15
Box2D Lights Simulate water I have a libGDX project, in which I have a Box2D world, which is currently filled with some boxes as a terrain. I also added a DirectionalLight to the scene for simulating the Sun. I almost have the effect I'd like to achieve, but is there any way to let the light shine through the water more deeply than it does on the surface?
15
Scene2D set table cell size in percentage of tables s size Is it somehow possible to set Scene2D table cell s size in percentage of the table? I would like to have orientation independent menu, with buttons filling let s say 75 percent of the screen, and also to respond on window resizing (desktop version). I have tried several methods, for example using Value table.add(button).width(Value.percentWidth(.75F)) but when value.get(actor) is called inside cell, it is supplied with inner button actor not its container (table). I have also tried to set it in fixed fashion table.add(button).width(Value.percentWidth(.75F).get(table)) This works fine, but since I set pixel value insted of Value object it is not recalculated upon resizing. Is there any way to achieve this?
15
Incrementally processing large number of entitites in an entity component system LibGDX Ashley has a class IntervalIteratingSystem that allows you to process all entities in a particular family every X milliseconds. But if you have a lot of entities to process, it might be a bad idea to do all that at once. For example, if you want to process 10,000 entities once every 10 seconds, you might not actually want to wait 10 seconds, and then process all the entities you'd want to "spread it out" over many frames. Perhaps every 100ms you process 100 entities, cycling through them all. To rephrase I'd like to process a large number of entities but spread out across multiple frames, preferably providing a reasonable guarantee that all entities will processed at least once every X seconds, enabling you to keep track of how much time has passed since that entity was last processed, with a random entity order, all entities are processed an equal number of times. Here are my ideas so far...(some bad, some good) Every time an entity is added to the Engine, add a Group1, Group2, or GroupN component (either randomly or sequentially), and then in my EntitySystem I cycle through the various families based on their Group . Every 10 seconds, add all 10,000 entities to a list, and then every 100ms, drain and process 100 from that list. (Memory intensive, and might fall behind) Every 100ms, iterate over all 10,000 entities, but skip 99 of them randomly (either using a PRNG or by checking their hashcode mod prime). Maintain a list (a copy, really) of all relevant entities inside an EntitySystem using Engine addEntityListener() and then process 1 of the list every 100ms by sequentially stepping through it, and wrapping around when reaching the end. (Uses LibGDX's unordered Array so removals are cheap). Same as 4., but rely on Engine getEntitiesFor and just let Ashley handle ordering and tracking entities instead of keeping a separate list. At the moment, 1 and 5 seem most promising. 1 seems to meet all my requirements, but is a bit pervasive (creating and adding a bunch of components), 5 is less pervasive, but doesn't meet the requirements quite as well ( 2 and 3 mostly). Thoughts? Is there something better than these?
15
Libgdx loading images I can't find a sulotions that solves my problem, I've tried pretty much every tip I can find, but with no luck. Error Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException Couldn't load file assets enemy.png From code enemyImg new Texture(Gdx.files.internal("assets enemy.png")) I've linked the asset file from android to desktop as I am supposed to. But still, no luck, the asset file in my desktop project doesn't even update when I add my image to my android projects asset file. Please help so I can get started ) EDIT Managed to load png now, but I have to manually put the picture in the desktop projects asset folder, so would still appriciate an answer on how to do it automaticly
15
Vertically mirroring the screen in LibGDX I'm developing a game in which the screen layout is different for right and lefty players, so i'll put a button in it to mirror the screen vertically. For displaying textures and fonts, i use a single scene2D stage with actors and labels. The stage's viewport type is FitViewport. How can i swap between the right and left layouts? Is there something already done to do it on the viewport side? Is it only a matter of switching coordinates from bottom left to bottom right? I can do that on the viewport camera, but what about all the textures? How can i change an actor's coordinate system? Thank you all
15
Entity Component System Unique Behaviour So, I decided to see what the Entity Component system of game development was all about. I really liked it. So, I decided to implement my current game with it. My problem Unique Behaviour with the system. From what I have seen, the way to implement Unique Behaviour for a entity is to Create a unique Component, and a Unique System that only accepts Entities with that Component. This seems to be a lot of code, for what could be a very small feature. My Solution Have entities with "hooks" in them, so that they can define their own unique behaviour in them. They would still have the major things done for them by systems, such as Health, Rendering, and Movement. e.g. public abstract class EntityLiving extends Entity Called when a entity is spawned in param map public void onSpawn(Map map) this.map map Called when an entity is killed param map public void onDeath(Map map) My Question Is this bad programming practice? Could this be done in a 'better' way? I realize that this question is extremely subjective, but I would like some professional opinions. EDIT By better I mean, in order of priority Less Code for this scenario Code Reusability Code Efficency
15
ParticleEffectPool.obtain() not resetting particles I want to use ParticleEffectPools in libGDX but I'm running into an odd issue where the effects don't seem to be reset when obtained by the pool. The code below looks for an existing ParticleEffectPool for the named effect, creates one if necessary, and then obtains a particle effect for the newly created Actor. The particle effect should be reset in the obtain function (if you look at the source it does so). What happens is the first effect works as expected but every subsequent one flashes very briefly on the screen as if its run out of duration. public class ParticleEffectActor extends Actor private static final Map lt String, ParticleEffectPool gt ParticlePools new HashMap lt gt () private final PooledEffect effect public ParticleEffectActor(String effectName, float rotation) if(!ParticlePools.containsKey(effectName)) ParticleEffect particleEffect new ParticleEffect() particleEffect.load(Gdx.files.internal("resources particles " effectName ".p"), Images.Atlas) ParticlePools.put(effectName, new ParticleEffectPool(particleEffect, 10, 50)) this.effect ParticlePools.get(effectName).obtain() rotation 90f for(ParticleEmitter emitter effect.getEmitters()) emitter.reset() ParticleEmitter.ScaledNumericValue angle emitter.getAngle() angle.setLow(rotation 35, rotation 35) angle.setHigh(rotation 35, rotation 35) Override public void draw (SpriteBatch batch, float parentAlpha) effect.draw(batch) Override public void act (float delta) super.act(delta) effect.setPosition(getX(), getY()) effect.update(delta) Override public boolean remove() effect.free() return super.remove()
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
object array positioning LibGdx In my game,if I touch a particular object,coin objects will come out of them at random speeds and occupy random positions. public void update(delta) if(isTouched() amp amp getY() lt Constants.WORLD HEIGHT 2) setY(getY() (randomSpeed delta)) setX(getX() (randomSpeed 4 delta)) Now I want to make this coins occupy positions in some patterns.Like if 3 coins come out,a triangle pattern or if 4 coins, rectangular pattern like that. I tried to make it work,but coins are coming out and moved,but overlapping each other.Not able to create any patterns. patterns like This is what I tried int a Math.abs(rndNo.nextInt() 3) 1 no of coins int no 0 float coinxPos player.getX() coins 0 .getWidth() 2 float coinyPos player.getY() int minCoinGap 20 switch (a) case 1 for (int i 0 i lt coins.length i ) if (!coins i .isCoinVisible() amp amp no lt a) coins i .setCoinVisible(true) coinxPos coinxPos rndNo.nextInt() 70 coinyPos coinyPos rndNo.nextInt() 70 coins i .setPosition(coinxPos, coinyPos) no break case 2 for (int i 0 i lt coins.length i ) if (!coins i .isCoinVisible() amp amp no lt a) coins i .setCoinVisible(true) coinxPos coinxPos minCoinGap rndNo.nextInt() 70 coinyPos coinyPos rndNo.nextInt() 150 coins i .setPosition(coinxPos, coinyPos) no break ...... ...... default break may be this is a simple logic to implement,but I wasted a lot of time on it and got confused of how to make it work. Any help would be appreciated.
15
Communication between Box2D and libGDX Stage (Scene2D) running in separate threads I'm making a physics based 2D game using libGDX and Box2D. I want to move the execution of the simulation out of render thread. I use immutable messages and the BlockingQueue to pass the information about player actions. The Box2D applies forces and runs a frame of simulation. In the next step I would like to sync back the changes and update Scene2D Actors accordingly. Making an immutable copy of the state of the game world and sending it back using Gdx.app.postRunnable() is one option but it seems inefficient. Is there any other option?
15
Libgdx handle screen resolutions I know there are some questions to this topic, but i didnt find a satisfying answer for my problem yet. I'm learning to use libgdx right now, and I'm not sure about handling different screen resolutions. I can use Viewports and a Camera of course, to fit the content to the screen. But how do i achieve, that my game doesnt appear kind of stretched if a device has a different resolution? For example Do you know the game Clash Royale? It feels like this game looks the same on all devices with every different resolution and screen size. How do they do this? Thank you.
15
Combining pathfinding with global AI objectives I'm making a turn based strategy game using Java and LibGDX. Now I want to code the AI. I haven't written the AI code yet. I've simply designed it. The AI will have two components, one focused in tactics and resource management (create troops, determine who have strategical advantage, detect important objectives, etc) and a individual component, focused in assign the work to each unit, examine its possibilites and move the unit. Now I'm facing an important problem. The map where the action take place is a grid based map. Each terrain has different movement cost. I read about pathfinding and I think A is a very good option to determine a good route between two points. However, imagine I have an unit with movement 5 (i.e, it can move 5 tiles of movement cost 1). My tactical AI has found an objective at a distance d 20 tiles (Manhattan distance) from my unit. My problem is the following the unit won't be able to reach the objective in one turn. So the AI will have to store a list of position and execute them in various turns. I don't know how to solve this. PS. In my unit code, I have a list called selectionMarks which stores all the possible places where the unit can go in this turn. This places are calculated recursively using a getSelectionMarks function.
15
Wavy effect shader in LibGDX HaxeFlixel has a nifty built in shader called FlxWaveEffect. Video Demo (Flash required) if you start the game and steer the player into an enemy. Usage (search for FlxWaveEffect) How does one go about creating a similar effect in LibGDX?
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
Making a border around a translucent shape in LibGdx The recommended method for making a border around a shape using LibGdx is to draw a larger version of the shape to serve as the border, then draw the shape over the larger image. shapeRenderer.setColor(borderColor) shapeRenderer.circle(x, y, radius borderWidth) shapeRenderer.setColor(shapeColor) shapeRenderer.circle(x, y, radius) This works well most of the time, but if you want shapeColor to have any opacity less than 1, it fails. The problem is that you can see the borderColor through the shape, and the colors are blended. Is there anyway to fix this issue?
15
LibGDX , Scale button with animation when it is pressed I am developing game using LibGDX . I want to create beautiful menu and to scale buttons when they are pressed but not in this way , when it is pressed scale it 1.5f , I want to scale it with animation . I am using imagebuttons .
15
LibGDX Wait for action to complete With Scene2D, in the act() method of a Group, under certain circumstances I add actions to some children (eg a moveTo, or a fadeOut), which last a few tenths of seconds. Now I need ALL these action to complete before I start running the code in act() again. Right now I'm using a kludge with a timer, I set a variable actionRunTime before attaching the actions to children, set to the value of how long all actions should take to complete, then in act() I do public void act(float delta) super.act(delta) to have the actions run on children actionRunTime delta if (actionRunTime gt 0) return ... code to run when no action is running This looks terrible to me. Is there some cleaner way?
15
Smoothly fitting texture tiles using alpha gradient on edges I'm trying to draw a background texture with tiles that I'll rotate and mirror to create a maze. Here is a sample tile As you can see, I use an alpha gradient on the borders. If I'd use a sharp border instead, you'd notice the border between a tile and another because these shadows and glows are not perfectly symmetrical. So far it works OK, but I've noticed there is a slightly darker spot where two tiles connect I used Photoshop to create these gradients, and was very careful to make sure these gradients are linear and start exactly where the next gradient ends, so that the total alpha of every pixel add up to exactly one. I'm using a SpriteBatch to draw these textures and use the default blending mode (I don't set any blend function at all). Apparently I'd need some blending function whose output will be the sum of both image's alphas and the average of their colors. Is this the default mode (if so, I guess my picture's alpha gradients are not perfectly linear)? And if not, what should I set my SpriteBatch's blend function to? Edit So I tried batch.setBlendFunction(GL20.GL SRC ALPHA, GL20.GL DST ALPHA) and it fixed the dark spot, but now the textures I draw on top look messed up, even if I revert it back to the old blending mode right after drawing my tiles.
15
LibGDX camera position shifted on movement I'm programming a game with LibGDX and Box2D and I want my camera to follow my player. But as I zoom in (because Box2Ds metric system, using camera.zoom x) the camera is shifted when the player moves (the camera follows the player) Shifted View Normal View That only happens when the player moves, so there can't be a problem with the coordinates. My Question is how to remove this shifting as the player moves. Here's some of my code Render Loop (excerpt) Override public void render(float delta) set the camera position to player's position cam.position.set(player body.getWorldCenter().x, player body.getWorldCenter().y, 0) cam.update() world.step(Gdx.graphics.getDeltaTime(), 6, 2) world.clearForces() handleInput() Gdx.gl.glClearColor(.05f, .05f, .05f, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) batch.setProjectionMatrix(cam.combined) debugRenderer.render(world, cam.combined) Make the player move if (Gdx.input.isKeyPressed(Keys.W)) player body.setLinearVelocity(transX, transY) player.setMoving(true)
15
Statemachine to behaviour tree? Background I was able to convert simple statemachines like this... Into a BT looking like this (Notation describtion)... root sequence After another playAnimation name idle sequence walks? Breaks current sequence if false playAnimation name walk sequence runs? playAnimation name run Goal But how do we convert more complex multi layered animation states into a behaviour tree ? How would such a BT look like ? The difficult parts here are transistions between the different states, something i couldnt solve in an BT. Question Is it possible to convert every statemachine into a behaviour tree ? What does the theory says and how does it look like in practice ?
15
ParticleEffectPool.obtain() not resetting particles I want to use ParticleEffectPools in libGDX but I'm running into an odd issue where the effects don't seem to be reset when obtained by the pool. The code below looks for an existing ParticleEffectPool for the named effect, creates one if necessary, and then obtains a particle effect for the newly created Actor. The particle effect should be reset in the obtain function (if you look at the source it does so). What happens is the first effect works as expected but every subsequent one flashes very briefly on the screen as if its run out of duration. public class ParticleEffectActor extends Actor private static final Map lt String, ParticleEffectPool gt ParticlePools new HashMap lt gt () private final PooledEffect effect public ParticleEffectActor(String effectName, float rotation) if(!ParticlePools.containsKey(effectName)) ParticleEffect particleEffect new ParticleEffect() particleEffect.load(Gdx.files.internal("resources particles " effectName ".p"), Images.Atlas) ParticlePools.put(effectName, new ParticleEffectPool(particleEffect, 10, 50)) this.effect ParticlePools.get(effectName).obtain() rotation 90f for(ParticleEmitter emitter effect.getEmitters()) emitter.reset() ParticleEmitter.ScaledNumericValue angle emitter.getAngle() angle.setLow(rotation 35, rotation 35) angle.setHigh(rotation 35, rotation 35) Override public void draw (SpriteBatch batch, float parentAlpha) effect.draw(batch) Override public void act (float delta) super.act(delta) effect.setPosition(getX(), getY()) effect.update(delta) Override public boolean remove() effect.free() return super.remove()
15
How do I draw a circular portion of a texture within LibGDX using an OpenGL ES shader? What is the simplest way to implement a shader to draw a circular portion of a full screen texture where the circle is dynamically resized as part of an animation using LibGDX? Is a shader even the best place to do this kind of thing? I'm sure you could do this in software using a Pixmap but that would be slow. In the end I managed to get something working using the OpenGL depth buffer, a ShapeRenderer to draw a circular mask and a SpriteBatch to draw the texture but it feels messy and awkward.
15
LibGDX multiple enemies animations Hello everyone i have a question about animating multiple enemies on the screen at the same time. Basically, i figured out how to use the Pool for creating enemies and dispose them after use etc.. All enemies are equal to each other, and all enemies have 3 different animations for creating, moving, destroying. Everything is working fine, but when i have multiple enemies on screen, they are all animating at the same times, even if they were (obviously) created in different times. For example, i create 3 enemies, make them moving on the screen and they all have the same frame.. the animation must be the same for all, but i expected that the time when they change frame should be different. The animations are instantiated inside the Enemy class, so i guess every instance of Enemy must have its own animation. This is how i draw them in the Renderer class private void drawEnemies(float runTime) enemyArrayLen catta.activeEnemies.size for (int i enemyArrayLen i gt 0 ) currentEnemyAnimation catta.activeEnemies.get(i).getCurrentAnimation() batcher.draw( currentEnemyAnimation.getKeyFrame(runTime), catta.activeEnemies.get(i).getX(), catta.activeEnemies.get(i).getY(), catta.activeEnemies.get(i).getWidth() 2.0f, catta.activeEnemies.get(i).getHeight() 2.0f, catta.activeEnemies.get(i).getWidth(), catta.activeEnemies.get(i).getHeight(), 1, 1, 0 ) Enemies are stored in the catta.activeEnemies array. currentEnemyAnimation is a "support" variable in which i put the Enemy in every cicle of the for cicle. This is how i initialize an Enemy public void init(float posX, float posY, int width, int height) this.position.set(posX, posY) this.width width this.height height this.alive true this.enemyRunTime 0 this.creationTime 0.8f this.destructionTime 0.8f this.crea Animation AssetLoader.enemy creaAnimation this.crea Animation.setFrameDuration(this.creationTime 4) this.mo Animation AssetLoader.enemy moAnimation this.des Animation AssetLoader.enemy desAnimation this.des Animation.setFrameDuration(this.destructionTime 4) this.enemyState EnemyState.CREATING ... Maybe it's all a runTime and delta matter?
15
Aspect ratio in LibGdx I'm learning LibGdx and I need some help with the camera. Let's see, I'm making a Chu Chu Rocket! clon to start. I've loaded a TiledMap (10x10), and I've created an OrthographicCamera to show the map. This is my camera code, written in the Map class constructor, which is invoked in the create() method map new TmxMapLoader().load("data maps " filename) renderer new OrthogonalTiledMapRenderer(map, 1.0f 24.0f) camera new OrthographicCamera() camera.setToOrtho(false, 10, 10) And this is the result, when I compile The problem is that the tiles I used in Tiled were squares. When I load, as you can see, they're rectangles. That's a problem for me. I've read some things about resizing, changing aspect ratio, etc, but everithing was about doing it to fit various devices resolutions screen sizes. So, my questions are How to define correctly the aspect ratio for a tiled map using a ortographic camera? When I do that, the ratio will be correct for every device? The elements which aren't the map (like the mice) would need to be also adjusted? How? Thanks for your answers.
15
How do I draw a name above monsters head? My player HUD works perfect, but when I move, the monster name moves with me instead of getting attached to the monster. Player has a HUD and I'm using Scene2D.ui to pull it off and works great. I use unit scale, that's why I got 2 camera. One for UI stuff and other for game. public void update(float deltaTime) update creatures world.getPlayer().onThink(deltaTime) for (Monster monster world.getMonsters()) monster.onThink(deltaTime) update camera to the player camera.position.set(world.getPlayer().getPosition(), 0) camera.update() Override public void render(float deltaTime) clear screen Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) seprate update logic update(deltaTime) set camera to what we see worldRenderer.renderer.setView(camera) worldRenderer.renderer.render() draw world game.spriteBatch.setProjectionMatrix(camera.combined) worldRenderer.render() monster UI game.spriteBatch.setProjectionMatrix(uiCam.combined) for (Monster monster world.getMonsters()) uiCam.project(uiPosition.set(monster.getPosition().x, monster.getPosition().y, 0)) game.spriteBatch.begin() Assets.font.draw(game.spriteBatch, quot Firefox quot , uiPosition.x 2, uiPosition.y 2) game.spriteBatch.end() Player Hud game.spriteBatch.setProjectionMatrix(hud.stage.getCamera().combined) hud.stage.draw() I'll appricate all kind of suggestions! If i could use Scene2D.ui for monsters aswell, would be great. Cheers.
15
Checking if Body is surrounded by other Bodies I'm trying to make a game like Rampart as practice. I have gotten to the point where I want to check if the castle is surrounded by walls and decide whether to fill in the area and continue the game, but I have no idea how to do this. I have thought about ray casting from the castle but it wouldn't work if there was a bend in the walls. So any help or suggestions would be great!
15
libgdx tilemap rendering problem I don't really know how to describe my tilemap rendering problem with words, so I think the best way is to show the pictures. This is how my map looks like when it rendered correctly but when I move the player little bit (the camera follows the player) I get this weird result Notice how the tiles which generating the floor got this strange shape, like they are not align correctly. I do have a padding in my tileset, so I'm not sure this is the problem. I also tried to round the camera position to integers, but it's result was always rendered like the second picture (the unwanted way), instead of sometimes correctly and sometimes not. What else can be the issue? EDIT I noticed now that this problem happened only when the camera reach to the edges points of the tilemap, and also right at the beginning of the program running (when the player is at his first position, before any movement was made).