_id
int64
0
49
text
stringlengths
71
4.19k
15
How can I increase text using scale and keep the text smooth in libgdx? I found that I can use DistanceFieldShader from here and found an example but I couldn't make it work. First my whole screen becomes white, all the other actors that I have on screen disappears. second, the text that supposed to be smooth becomes to be black squares. whats wrong with my code? Or maybe someone can give me an example that suits my needs. This class represents score in the game. (Maybe this should be actor and needs to be Label) public class Score extends Actor private int scoreInt private BitmapFont scoreBitmapFont private int x, y private DistanceFieldShader distanceFieldShader private Texture distanceFieldTexture private BitmapFont distanceFieldFont float scale 1.5f float smoothing public Score(int x, int y) this.x x this.y y scoreInt 0 scoreBitmapFont new BitmapFont() scoreBitmapFont.setColor(Color.BLACK) scoreBitmapFont.scale(scale) distanceFieldTexture new Texture(Gdx.files.internal("default.png"), true) distanceFieldFont new BitmapFont(Gdx.files.internal("default.fnt"), new TextureRegion( distanceFieldTexture), true) distanceFieldFont.setColor(Color.BLACK) distanceFieldShader new DistanceFieldShader() set filters for each page Texture.TextureFilter minFilter Texture.TextureFilter.MipMapLinearNearest Texture.TextureFilter magFilter Texture.TextureFilter.Linear scoreBitmapFont.getRegion().getTexture().setFilter(Texture.TextureFilter.MipMapLinearNearest, Texture.TextureFilter.Linear) public void inc(int inc) scoreInt scoreInt inc if (scoreInt lt 0) scoreInt 0 Override public void draw(Batch batch, float alpha) String scoreStr String.format("Score d", scoreInt) smoothing scoreBitmapFont.getBounds(scoreStr).width batch.setShader(distanceFieldShader) scoreBitmapFont.draw(batch, scoreStr, x, y scale getBaselineShift(scoreBitmapFont) ) distanceFieldShader.setSmoothing(smoothing scale) y scoreBitmapFont.getLineHeight() public int getScoreValue() return scoreInt private float getBaselineShift(BitmapFont font) if (font distanceFieldFont) We set 8 paddingAdvanceY in Hiero to compensate for 4 padding on each side. Unfortunately the padding affects the baseline inside the font description. return 8 else return 0
15
How do I implement efficient collision avoidance in 100 enemies I am developing a libgdx game. It is a top down shooter and I am trying to make a good AI. I have tried to implement A from the AI library from libgdx and it works fine but when i have a lot of enemies it starts to slow down the game. Have tried implementing a Pathfinding manager to manage threads and path requests but I have trouble implementing it and still slows down. Also I know A is a bit overkill for my game, which is a big open zone mostly (see pic of my map) So I tried to implement this collision avoidance Steering Behaviors Collision Avoidance but it doesn't go well when the player is inside houses. My question is, does exists some type of algorithm that fits perfectly for what I am asking? There are a lot of games with hundreds of enemies going to kill you so I bet there is a way, just I cant find out pd Any doubt ask and I will provide more information if necessary
15
Box2dMapObjectParser isometric map bodies have wrong position and size I'm using Box2dMapObjectParser to load Tiled objects layer onto my IsometricTiledMapRenderer'ed TiledMap. It works OK with a UnitScale of 1 but the position is wrong and some shapes have weird rotation and size. Map in Tiled Map in game I've found another similar question but the answer is unfortunately far from being clear, at least to me. Relevant code mParser.load(mWorld, mMap) mRenderer new IsometricTiledMapRenderer(mMap, mParser.getUnitScale()) Notice the 'Ellipse' is not drawn at all, the Rectangle is way off and Polygons Polylines are just not positioned right. Did anyone experience the same issue and or have any idea how to fix this?
15
How to rotate an image on touch using RotateToAction in libGDX? I want to rotate my image on touch but it never applies action, I'm using RotateToAction to achieve this. class actorCark extends Actor Texture texture Sprite sprite Global g GetActorByName a public actorCark() ses new sesler() g new Global() a new GetActorByName() sr new soruSor() texture new Texture(Gdx.files.internal("images carkifelek.png")) sprite new Sprite(texture) setBounds(Global.screen width 2 Global.screen height 0.9F sprite.getTexture().getWidth() sprite.getTexture().getHeight() 2, Global.screen height 2 Global.screen height 0.9F 2, Global.screen height 0.9F sprite.getTexture().getWidth() sprite.getTexture().getHeight(), Global.screen height 0.9F) setTouchable(Touchable.enabled) addListener(new InputListener() public boolean touchDown(InputEvent event, float x, float y, int pointer, int buttons) clearActions() RotateToAction rotateToAction new RotateToAction() rotateToAction.setRotation(360) rotateToAction.setDuration(2) addAction(rotateToAction) dondur() sesler.donmeS.play() return true ) Override public void act(float delta) super.act(delta) public void draw(Batch batch, float alpha) sprite.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear) sprite.setBounds(Global.screen width 2 Global.screen height 0.9F sprite.getTexture().getWidth() sprite.getTexture().getHeight() 2, Global.screen height 2 Global.screen height 0.9F 2, Global.screen height 0.9F sprite.getTexture().getWidth() sprite.getTexture().getHeight(), Global.screen height 0.9F) sprite.setOrigin(sprite.getWidth() 2, sprite.getHeight() 2) sprite.draw(batch)
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
Use libgdx box2d for dynamically generated top down map So, I've already found some information on how to use box2d and tiledmap together. Since I want to generate my top down map (100 by 100 tiles), I thought about only using box2d. The tiles would be fixed and only the player (and maybe some other movable parts like chests, etc) would be dynamic. I'd also like to use box2dlights later, so using box2d seems convenient. My only concern on this is the performance. I haven't used box2d much, so I don't know how it handles such a big amount of boxes (though not all 10000 tiles would be visible at the same time). Does anyone know how the performance would be influenced or advice on how to achieve this easier? Thanks in advance
15
Render BitmapFont with size 1 in Libgdx My ingame camera has units that 25 times less than screen units so when I render BitmapFont generated for camera which used in non game screens (settings, level choose etc.) it's even doesn't fit in camera. I came up with some solutions Generate font with right size, but No cap character found in font exception caught. Scale font with font.getData().setScale(float scaleXY) but got this Increase camera units but I'll need to rewrite a lot of code depending on camera combined matrix. Is there any easier way to do this?
15
Game freezing when i create a body Box2D Libgdx I'm implementing a Worms game using libGDX and Box2D and I'm having a problem I didn't have until recently. When a player shoots, it creates a bullet body and applies a force to it. I have a step system to see what the player should be doing( move, select weapon, select angle and charge force). The methods involved with shooting in player are public void nextStep() if ( turnStep 0) startingPosition player.getPosition().x turnStep if(turnStep gt 5) turnStep 0 chargeBar.dispose() movementBar.dispose() arrow.dispose() if(turnStep 1) movementBar new MovementBar(getX(),getY(),world) if(turnStep 3) arrow new Arrow(getX() tex.getWidth() 2, getY() tex.getHeight() 2, world) if(turnStep 4) chargeBar new ChargeBar(getX(),getY(),world) if(turnStep 5) shooting true public void shoot() actualWeapon.shoot( arrow.getTip(), chargeBar.getCharge() , arrow.getAngle()) shooting false In my main game class, I have an update method where I do the world step and update other things, and I perform the shooting here world.step( 1 60f, 6, 2) if (playerWhoseTurnItIs.isShooting()) playerWhoseTurnItIs.shoot() Which ends up calling public void shoot(Vector2 pos, float force, float angle) isFlaggedForDeletion false body BodyCreators.createBox( pos.x PPM, pos.y PPM, projectileTex.getWidth(), projectileTex.getHeight(), false, false, world, (short) BIT PROJECTILE, (short) (BIT PLAYER BIT WALL), (short) 0 , this) Vector2 f new Vector2( force MathUtils.cos(angle MathUtils.degreesToRadians), force MathUtils.sin(angle MathUtils.degreesToRadians) ) body.applyForceToCenter( f , true) Everything used to work fine, and I didn't touch any of this while working, but now every couple of turns the bullet just appears and then freezes there, on the tip of the arrow, freezing my whole game. Also, when I started having this problem I implemented the check after the world step, it just used to shoot when i called nextStep() and the turn was five, but since applying the check didn't actually solve the problem (I thought it was like when destroying bodies you can only do it after the step) I might revert the change. If you need more information please ask, thank you
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
How do I move a sprite by clicking other sprites in the stage? I am new to the LibGDX environment how do I move a sprite by clicking other sprites in the stage? As you can see, I have an object I wish to move by clicking on arrow keys. Here are my current scripts public class MyGdxGame extends ApplicationAdapter Stage stage Override public void create () ScreenViewport viewport new ScreenViewport() stage new Stage(viewport) Gdx.input.setInputProcessor(stage) Myactor actor new Myactor() stage.addActor(actor) Override public void render () Gdx.gl.glClearColor(0.33f,0.66f,0.99f,1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) stage.act(Gdx.graphics.getDeltaTime()) stage.draw() Override public void dispose () public class Myactor extends Actor Texture texture new Texture(Gdx.files.internal("ball.png")) Sprite sprite new Sprite(texture) Texture Tsol new Texture(Gdx.files.internal("left.png")) Sprite Ssol new Sprite(Tsol) Texture Tsag new Texture(Gdx.files.internal("right.png")) Sprite Ssag new Sprite(Tsag) Override public void draw(Batch batch, float parentAlpha) sprite.setPosition(Gdx.graphics.getWidth() sprite.getWidth() 50, Gdx.graphics.getHeight() 2) sprite.draw(batch) Ssol.setPosition(Gdx.graphics.getWidth() sprite.getWidth(), 0) Ssol.setRotation(90f) Ssol.draw(batch) Ssag.setPosition(Gdx.graphics.getWidth() sprite.getWidth(), Gdx.graphics.getHeight() sprite.getHeight()) Ssag.setRotation(90f) Ssag.draw(batch)
15
Using LibGDX, is it necessary to clip what I'm rendering for efficiency? So I am working on a game, and I've noticed that everything in the world is sent to be rendered. Of course with the camera, only some of the world is rendered. Does this mean there is there any expense for when I send all those extra vertices to OpenGL that don't show up on screen? Will OpenGL LibGDX do it automatically? If I should clip it, is ScissorStack the way to go?
15
How to implement dynamic background music? Assumption 1 As a game's story progresses, dynamic background music is often used to enhance the player's immersion. Assumption 2 Background music is probably always streamed due to memory limitation and performance. What do I need to consider when I'm checking the feasibility of having dynamic(ally changing, adapting) background music? For example when a boss enemy appears the game should not just replace the "wandering music" to "boss combat", it should rather somehow cross fade the two music scores as it starts playing the new music. Is it usually possible to stream multiple sounds in parallel? I'm using LibGDX, where as far as I'm aware only a single streaming music instance can be played at a time, so how can I have such music with this framework? Do I suspect correctly if I also need to separate a dynamic music into parts like "intro", "loopable part", "loopable part near the climax", "outro", etc., and when a part ends have a music manager code decide which part should be (re)started? I'm more interested in understanding the theory instead of the actual implementation of the code.
15
How to start an animation just once on an event in libGDX I am trying to show an explosion animation which i created using a few textureregions and created Animation missileblastAnimation from those textureregion like this TextureRegion explosion explodemissile1, explodemissile2, explodemissile3, explodemissile4, explodemissile5, explodemissile6, explodemissile7,explodemissile8, explodemissile9, explodemissile10, explodemissile11, explodemissile12, explodemissile13, explodemissile14,explodemissile15, explodemissile16, explodemissile17, explodemissile18 missileblastAnimation new Animation(0.1f, explosion) missileblastAnimation.setPlayMode(Animation.NORMAL) I have this following code in the render method Note explosionstarted is set to true when missile hits the ground if(explosionstarted) check if the missile hits the ground to start explosion animation batcher.draw(AssetLoader.missileblastAnimation.getKeyFrame(runTime), 100, 300 102, 50, 102) if(AssetLoader.missileblastAnimation.isAnimationFinished(runTime)) i found that isAnimationFinished tells if animation is finished or not but i still cant understand the passing runTime thing explosionstarted false reset the boolean to make the animation stop drawing Problem is the animation is not playing as it should i.e sometimes it plays too much fast . sometimes it skips first few frames and jumps to ending frames. What is the right way to do this? Is there any other way i can check if the animation is completed ?
15
LibGDX button change image on hover over time As we all know, LibGDX has a TextButtonclass which has a TextButtonStyle and ButtonStyle. The style has some parameters up an image which is shown normally as a button background down shown when the button is being 'pressed' over on hover My question is Is there any way to implement the 'hovering' changing the background image IN TIME? So for example it takes 2 seconds and it's smooth? I tried with actions and tween engine, but honestly, I really have no idea how I should implement this. Maybe some alpha operations? If you have any ideas, I would be grateful )
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
testPoint not working libgdx I'm making a game like angry birds with LibGDX and box2d in which I want to drag a ball (instead of the bird) back before releasing it. I deploy with testPoint function when I touch down the screen, I check if the point is within the body of the ball or not but testPoint function never works exactly. Here's what I'm trying thanks so much public boolean touchDown(int screenX, int screenY, int pointer, int button) for(Fixture fixture bird.getBody().getFixtureList()) if(fixture.testPoint(screenX 100, (mapHeight screenY) 100)) 100 is scaled parameter draggedBird true return true return false
15
Isometric Architecture Map Game Data I'm not sure this kind of question has been answered yet, if so i'm sorry to duplicate it. My question is rather simple I'm creating a simple Isometric game with libgdx, i'm using Tiled but only to design the map and render it with OrthographicMapRenderer. The map is a static map of 6864 6880 pixels, one tile is 59 43 pixels I wanted to do some pathfinding to my game, so I decided to store my map data into a simple 2D array like this int cells i j which would contains 0 if the tile is walkable or 1 if it's not, it is as simple as that ! Currently I've simply using basic formula to convert world cartesian coordinate to Isometric coord, and formula to get tile pos based on iso pos, (eg you input a iso coord, the function return a vector like lt 2,5 which is the 2nd x tile and 5th y tile. It perfecttly work as execepted, I also make it that iso tile coord is always positive ( lt 0,0 is at the top left corner of my world ) But here is my Question or doubt How to handle correctly the game data tile ? Does a 2D array is sufficient, if yes, how to, for exemple write a function that get if a tile is walkable or no based on tile coord ? ( example I click on my map, the coordinate is translated to tile coord ( lt 4,5 for example,) how to check if this tile is walkable ?, i dont get on how to do it i'm really lost. EDIT Ive successfully implemented the isometric logic I can convert world coordinate to tile coorinate ( eg (5075 4851) (203 28)) and the reverse but i'm confused on how to fill the 2d Array, use it for A algorithm and make the bridge between these coordinate and the 2D array Thank you for you help, Regard
15
Libgdx and ParticleEffect with scene2d not showing the same way as in the Particle Editor I am developing a new game with libgdx and trying to implement ParticleEffect in scene2d (using actor). I am creating a ParticleEffect with Particle Editor in which I would like to add to a stage. From some reason, the effect appears horizontally only (objects appear from left to right but not up and down) and is not appearing the same as in the Particle Editor (X and Y axis). Does anyone have an idea what could be the reason for that? Snapshot of the horizontal effects (desktop run) Particle Editor effect
15
How to properly change resolution I'm trying to understand how LibGDX handles screen size resolution, etc. Coming from XNA this seems very confusing to me. Basically I want to support 480x800 for my game. If the screen size is different it should scale the resolution and use letterboxing. To do this I use a FitViewport. And that's the code public static final int VIRTUAL WIDTH 480 public static final int VIRTUAL HEIGHT 800 Viewport viewport SpriteBatch spriteBatch ShapeRenderer shapeBatch Texture img Override public void create() viewport new FitViewport(VIRTUAL WIDTH, VIRTUAL HEIGHT) spriteBatch new SpriteBatch() shapeBatch new ShapeRenderer() img new Texture("test.jpg") Override public void resize(int width, int height) viewport.update(width, height) Override public void render() Gdx.gl.glClearColor(0, 0, 0, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) shapeBatch.begin(ShapeType.Filled) shapeBatch.setColor(Color.GRAY) shapeBatch.rect(0, 0, viewport.getWorldWidth(), viewport.getWorldHeight()) shapeBatch.end() spriteBatch.begin() spriteBatch.draw(img, 0, 0) spriteBatch.end() Now if I set the game resolution to be 480x800 right at the beginning, it basically works except that if I change the window size, the resolution keeps to be 480x800. So it stretches the image but keeps the aspect ratio And if I run the game with any other resolution like for example 700x500 I get this What is going on behind the scenes? (And sorry if my english is bad)
15
How to handle mixed input I'm aiming for the following design in my app, and I am having a difficulty figuring how this could be achieved. The purple part will be the main part of the game, which I have actually already written, implementing InputProcessor. It uses touch controls for dragging (mainly) and touching down or up with the finger. I didn't think of creating a HUD beforehand and now decided that a Stage would work perfectly for that, but it definitely wouldn't work with the above input method. Is there a way to split the screen into areas like in the diagram, and depending on touch location pass the touch events to either main game InputProcessor or to the Stage?
15
SpriteBatch being drawn outside of Stage? Currently working on my first game, though running into some problems with libgx and screen aspect ratio. What I have is a Stage which contains things like menu buttons etc, and the rest of the game is pretty much sprites being drawn with via SpriteBatch. To avoid having multiple SpriteBatches and cameras, I have re used the ones that are created when Stage is created. stage new Stage(WIDTH, HEIGHT, true) keep aspect ratio batch stage.getSpriteBatch() camera (OrthographicCamera) stage.getCamera() move camera so 'active' screen is centred stage.getCamera().translate( stage.getGutterWidth(), stage.getGutterHeight(), 0) Anything that is Stage Actor related is drawn fine all goes within the aspect ratio adjusted boundaries. The problem I'm having is anything that drawn via SpriteBatch, seems to ignore this viewport that is defined by Stage and can be visible outside of the Stage area. batch.begin() ... sirWuffles.draw(batch) ... batch.end() For example, in the above, if Sir Wuffles is generated outside of the defined WIDTH HEIGHT it might still appear in the "gutters" of the screen. Tried to explain it in the below screenshot. It's an exaggerated screen ratio to make the gutters large. I've also covered most of the gutter area in the blue cyan rectangle so they are very obvious. Does anyone know what is happening? and how to fix it? Currently, my "fix" is to use ShapeRenderer to draw rectangles that correspond to the gutters on top of the sprites...
15
Create a filled pixmap for box2d fixture I'm trying to make a pixmap that fills in a Box2D fixture. It would be kind of like a fill bucket. I've done this before, but I want it to work on rectangles and other polygons. Is there an algorithm to do is, or will I need to write on myself? Thanks.
15
How to access entites from scripts in an entity framework? I'm developing on a simple libGDX based Game and im using the entity component system ashley. For non generic but custom behaviour (e.g. the Player Movement), I'm using "scripts" instead of reuseable and generic Entity Systems. Therefore I've got an ScriptComponent and a ScriptSystem which runs init() and update() on all scripts related to an entity. At some point I want to generate a map, counting game related properties etc. that brings me to the point where I'm confused about how to access those porperties from any script. In other Engines Enviroments like Unity3D the GameObjects (the entities) brings functionality to find other entities like FindGameObjectsWithTag(...). But how can I realise that in ashley? Also should it be possible in an Entity Framework to access specific entities in general? Edit Additional information Here comes a simple example usecase. This is very notional example I've just created for that post. I just wanted to demonstrate, that I thing there is a need of an "main Game Object" in a game which also uses a entity component framework like ashley. So I thought a correct way is, to let this main game object be an entitiy too which holds the main script. But I'm not sure, if this is a good approach. Here I demonstrate this with having a PlayerScript which just sets the lives for the player accordingly to the difficulty level of the game (maybe set by the player on the main menu screen). This PlayerScript is attached to the ScriptComponent of the player entity. public class PlayerScript extends Script int playerLives public void init() GameEntity entity getTheEntityByName("game") this method doesn't exist GameScriptComponent gsc scriptComponentMapper.get(entity) GameScript mainGameScript gsc.getScriptByName("game") if(mainGameScript.getDifficulty "easy") playerLives 999
15
2D Collision Response I am trying to implement collision response in my libgdx game. I'm using Rectangle objects as my bounbing boxes. This makes collision detection very easy, however I can't quite get the response working correctly. At the moment I have this float overlapX getOverlap1D(dynamicBounds.x, dynamicBounds.x dynamicBounds.width, blockBounds.x, blockBounds.x blockBounds.width) float overlapY getOverlap1D(dynamicBounds.y, dynamicBounds.y dynamicBounds.height, blockBounds.y, blockBounds.y blockBounds.height) if (overlapX lt overlapY) if (dynamic.getVelocity().x lt 0) dynamic.getPos().add(overlapX, 0) else dynamic.getPos().sub(overlapX, 0) dynamic.setVelocityX(0) else if (dynamic.getVelocity().y lt 0) dynamic.getPos().add(0, overlapY) else dynamic.getPos().sub(0, overlapY) dynamic.setVelocityY(0) private float getOverlap1D(float min1, float max1, float min2, float max2) return Math.max(0, Math.min(max1, max2) Math.max(min1, min2)) Using this, corners are handled in a very unpleasant way, resulting in less than extraoridnary results like this. Where am I going wrong that allows this to happen?
15
Libgdx touchup fired even when figure not on texture I've implemented a touchup listener for an actor in stage. Now what happens is that when user touch downs the sprite and releases finger, its all good. The problem is when user touch downs the finger, and drag it somewhere else (possibly to cancel the touch) and releases, it still fires the touch up event as if nothing ever happened. How do I stop that? Here's my code voiceToggle.addListener(new InputListener() Override public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) System.out.println("touched") return true Override public void touchUp(InputEvent event, float x, float y, int pointer, int button) System.out.println(event) still fires even if not on original touchdown element )
15
Box2D body rotation with setTransform I' having a problem rotating a body with setTransform(), The body has multiple sensors that should rotate with the player. The rotation works but it rotates around the bodys local 0,0 position instead of the center. Note that the game is in a top down perspective and the player can go in four different directions, thus I need to rotate him immediately (in one tick) in 90 degrees steps. Up Down I can't find a way to set the rotation center. Here's the code I use to rotate it float angle direction 90 MathUtils.degRad direction is an int value from 0 to 3 body.setTransform(body.getPosition(), angle) I also tried body.getLocalCenter().set() and body.getMassData().center.set() but it didn't seem to have any effect. How can I rotate the body around its center? EDIT (added code to create fixtures) This is the method to create a fixture private Fixture createFixture(FixtureDef fixtureDef, Body body) PolygonShape ps createPolygon() creates a polygon shape from XML config fixtureDef.shape ps Fixture fixture body.createFixture(fixtureDef) if (fc.filter ! null) fixture.setFilterData(fc.filter) This is the simplified code to create the fixtures (they are really loaded with xml config but these are the values I set) FixtureDef sensorDef1 new FixtureDef() sensorDef1.friction 0 sensorDef1.restitution 0 sensorDef1.isSensor true sensorDef1.center new Vector2(0.8f, 1.6f) and some filters FixtureDef sensorDef2 new FixtureDef() sensorDef2.isSensor true sensorDef2.center new Vector2(0.8f, 1.6f) and some filters FixtureDef sensorDef3 new FixtureDef() sensorDef3.isSensor true and some filters createFixture(sensorDef1, body) createFixture(sensorDef2, body) createFixture(sensorDef3, body)
15
Error suddenly when compiling Desktop on Android Studio all projects nothing changed LibGDX I have just gone into Android Studio to open a project. It will run in Android but not my Desktop configuration. Nothing of the code has been changed and I have now tried 3 projects, also a brand new project straight from the LibGDX Project Generator .jar file. The error I get in Studio is Exception in thread "LWJGL Application" java.lang.NullPointerException at com.badlogic.gdx.backends.lwjgl.LwjglGraphics.createDisplayPixelFormat(LwjglGraphics.java 322) at com.badlogic.gdx.backends.lwjgl.LwjglGraphics.setupDisplay(LwjglGraphics.java 216) at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java 142) at com.badlogic.gdx.backends.lwjgl.LwjglApplication 1.run(LwjglApplication.java 124) Process finished with exit code 0 Please can anybody help me here? thanks
15
LibGDX moving game window with mouse drag TL DR How can I move window with mouse without tide effect. Long Version So when I tried to move my game window via InputListener(just to test if it would work). I got some strange result. The window goes back and forth between last two locations when mouse drags and while button is held. Game Part Gdx.input.setInputProcessor(new InputAdapter() int b Override public boolean touchDown(int screenX, int screenY, int pointer, int button) b button TODO Auto generated method stub Rectangle.tmp.set(0, 0, 100, 100) if (Rectangle.tmp.contains(screenX, screenY)) lastx screenX lasty screenY System.err.println("Touch ( " screenX " , " screenY " )") return true Override public boolean touchDragged(int screenX, int screenY, int pointer) if (lastx ! null amp amp tr ! null) tr.translate(screenX lastx, screenY lasty) System.err.println("Drag ( " lastx " " screenX " , " lasty " " screenY " )") lastx screenX lasty screenY return true Override public boolean touchUp(int screenX, int screenY, int pointer, int button) lastx null lasty null System.err.println("Up ( " lastx " , " lasty " )") return true ) DesktopLauncher Part Game.tr new Translator() Override public boolean translate(int x, int y) Display.setLocation(Display.getX() x, Display.getY() y) return true PS What I try amp tried to make may look stupid. Edit Actually I noticed that window moves less than actual mouse movement. Edit2 When I move the movement code to touchUp I get exact result as movement.
15
2D LibGDX Collision Avoidance I would like to know what is the best way to implement collision avoidance and eventually pathfinding in a LibGDX 2D top view game. Think of "Binding of Isaac". I use a sort of tilemap to place the obstacles (squares), taken from an ASCII map, but I'd prefer to keep the movements free from it. (Enemies shouldn't move from tile to tile but freely) Since the target is mobile I can't use heavy algorithms. I'm not particularly concearned about enemies getting stuck on weird shapes (such as 'U') since it kind of makes sense (they are white globules, not particularly smart P) but I still want them to be a challenge. I've taken into consideration Steering Behaviors and the LibGDX AI framework but I can't find good documentation, I can aswell code it by myself in case. ANOTHER QUESTION Just to know, which kind of algorithm is used in the Binding of Isaac? It perfectly suits my needs
15
Stopping Actor tap click event from propagating I've been struggling with this for hours now and have read posts, docs and libgdx sources to better understand what's happening, but I still can't make any sense of this. I want to accomplish something very simple stopping a tap on an Actor from propagating through the stage. The setup is as follows GameStage defines a gesture listener (for map panning and propagating taps in the map to the Player actor so it can move around) Player has a child actor which can receive clicks It is on that last child actor that I want to detect clicks, but then not have them propagate to any other actors or be handled by the stage. I define the click handler as follows in child actor addListener(new ClickListener() void clicked(...) ) Nothing surprising here. The problem is since the actor is physically located outside the Player parent actor, any clicks on it get picked up by the stage's map gesture handler which then propagates these taps back to the player which makes it move around. I don't want that this click listener is supposed to handle and swallow the event. However, none of the following calls I make inside clicked actually cancel the event event.handle() event.stop() event.cancel() The only way I could make the event stop from propagating is to use Stage cancelTouchFocus. However, this has the side effect of dispatching a touchUp event on the stage (why?), which ends up in my gesture listener and gets interpreted as a longPress! Probably because it is paired up with the wrong touchDown... What am I missing? It can't be that complicated to stop an event from propagating given all the supposed options? UPDATE I believe the problem lies in Stage https github.com libgdx libgdx blob 2bd1557bc293cb8c2348374771aad832befbe26f gdx src com badlogic gdx scenes scene2d Stage.java L348 It walks over all the listeners that have touch focus, and let's them handle the event. However, it does not break out of the loop as soon as a listener has handled it, thus propagating it further. Is that just a bug?
15
How to set indent spacing of a tree in libGDX scene2d? I've been trying to create a customized UI using scene2d library in libGDX. However I am having troubles as I'm trying to set a custom indent spacing on my Tree object. I have tried to search for the answer but haven't actually found any discussions about this on the internet. This is the current situation which I am having. This is how I would prefer it to look like. All I want is that I could be able to change the size of the margin which is caused by nodes being on different levels. How can I achieve this?
15
libGDX upload z axis of sprite to graphics card Background I want to obtain each fragments position via vertex interpolation to then calculate the light vector for phong shading (L Fragment pos light source pos ). Problem At the moment I am using libGDX's com.badlogic.gdx.graphics.g2d.Sprites to upload my 2d sprites via the batch to the graphics card. However they only transport the x and y information for each vertex ( I think in the shader z is 0). I also want to upload the z axis of the sprite for use with normal map based pixel shading (calculate the vector of the incoming light). Should I use a com.badlogic.gdx.graphics.Mesh for that or can I extend the Sprite class and somehow put the z axis in the vertices float array? If I should do that, how do I do this?
15
2d libgdx runtime level generation I have encountered a problem during my first game development I thought of a Array lt Ground gt groundArray that does groundArray.add when a new ground will appear on the screen, and removes oldest ground when it will no longer be seen, if player only moves to the right, like in flappy bird. The perfect structure would be a queue for such a mechanic, but libgdx doesnt have one. Using libgdx's Array is not intuitive too i have to reverse the order of elements. It has a method pop() that removes the last element, but no such method to use on the first element. What are my options here? extend Array class and add something? writing my own queue like class? UPDATE 18 8 2014 i actually found a way to do it with the default Array private void checkGround() for (Ground ground groundArray) if (ground.x 500 lt camera.position.x) groundArray.removeValue(ground, true) if (groundArray.peek().x lt camera.position.x 500) groundArray.add(new Ground(groundX, 150)) groundX 50 my ground texture is 50 pixels wide Only question left now will it affect performance when there will be 10000 empty elements before the 10 actual ground elements? In my render method i use for (Ground ground groundArray) batch.draw(ground.getTextureRegion(), ground.x, ground.y) If yes i will have to make a re sort method that shifts all the grounds to the beginning of the array. Will doing so improve this? for (Ground ground groundArray) if (ground ! null) batch.draw(ground.getTextureRegion(), ground.x, ground.y) After checking apparently the array size doesnt boost , it size is always equals the number of actual ground objects in it, but i thought that it will count also the null values that were ground objects before. But then surely there would be nullpointers when i tried to draw those null's, so the problem looks fully resolved.
15
how to make different sprite when moving and aiming I want to create top down game where you are Russian soldier in libGDX. The player controls the soldier with W A S D and aims with the mouse. That way the soldier can run sideways and shoot towards enemy. What is best way to make his legs walk into the right direction but aim the weapon towards the mouse pointer? My idea is to make two sprites, for both torso weapon and legs and let them lay over each other but I don't know if that is best way to do it.
15
How to combine Actor.setPosition and Actor.hit? Why after using Actor.setPosition, input coordinates in Actor.hit come with a shift in the values specified in setPosition? Create scene public class MyActor extends Actor ... int width 70 int height 70 public MyActor(Texture img, int x, int y, int realX, int realY) ... sprite new Sprite(img, x, y, width, height) this.setPosition(realX, realY) Standard search Actor public class GameScreen implements Screen, InputProcessor Override public boolean touchDown(int screenX, int screenY, int pointer, int button) Vector2 coord stage.screenToStageCoordinates(new Vector2((float)screenX,(float)screenY)) Gdx.app.log("touchDown", "" coord.x "," coord.y) selectedActor (MyActor)stage.hit(coord.x,coord.y,false) ... public class MyActor extends Actor Override public Actor hit(float x, float y, boolean touchable) if(!touchable) Gdx.app.log("Actor.hit ", "" x " " y) return x lt getX() x gt getX() width y lt getY() y gt getY() height ? null this But come the distorted values. Coordinates Click touchDown 26.25,81.250015. MyActor in the values obtained from the offset, the multiple of 70 Actor.hit 43.75 11.250015 Actor.hit 43.75 81.250015 Actor.hit 26.25 11.250015 Actor.hit 26.25 81.250015 Why? How to fix? UPDATE public class MyStage extends Stage ... Override public Actor hit(float x, float y, boolean touchable) return super.hit(x,y,touchable)
15
Rendering Tilemap Tile Layer Side by Side for Infinite Endless Runner Game I was strugeling this for days how to implement tilemap into libgdx and box2d with infinite endless scheme. I can load a single map and display everything on screen. But placing 2 or more tilemap side by side got me headache. I know currently not possible to offset add x value position of tilemap. What I do right now is use setview for camera of it's render method. This is my map helper and currently I works with 3 renderer for 3 tilemap as a test... public class MapHelper private Array lt OrthogonalTiledMapRenderer gt renderer new Array lt OrthogonalTiledMapRenderer gt () private int number private float oldDistance, currentDistance private String layer "world" public MapHelper(Callback callback) this.callback callback number 0 item new ItemMap 3 public void render(CamHandler cam) for(int r 0 r lt renderer.size r ) if(item r ! null) renderer.get(r).setView(cam.getCam().combined, item r .distance, 0, item r .getWidth(), item r .getHeight()) renderer.get(r).render() public void updateMap(CamHandler cam) if(mapOut(cam)) number if(number gt 2) number 0 loadMap(number) Check if camera reach the current distance, then build new map param cam return private boolean mapOut(CamHandler cam) float x cam.getCam().position.x cam.getCam().viewportWidth 2 Utils.log("pos cam x " x " current distance " currentDistance) return x gt currentDistance private void loadMap(int map) AssetsManager.loadMap(map) if(item map ! null) renderer.set(map, new OrthogonalTiledMapRenderer(AssetsManager.map)) item map .set(TileHelper.getMapWidth(AssetsManager.map, layer), TileHelper.getMapHeight(AssetsManager.map, layer), currentDistance) else renderer.add(new OrthogonalTiledMapRenderer(AssetsManager.map)) item map new ItemMap(TileHelper.getMapWidth(AssetsManager.map, layer), TileHelper.getMapHeight(AssetsManager.map, layer), currentDistance) oldDistance currentDistance currentDistance TileHelper.getMapWidth(AssetsManager.map, layer) callback.onLoad() Utils.log("load new map " map " distance " currentDistance) public Array lt OrthogonalTiledMapRenderer gt getRenderer() return renderer public Array lt Body gt getBodies(World world) return new MapBodyBuilder().buildShapes(AssetsManager.map, world, oldDistance) private ItemMap item private class ItemMap private float distance, mapWidth, mapHeight ItemMap(float w, float h, float distance) mapWidth w mapHeight h this.distance distance private void set(float mapWidth, float mapHeight, float distance) this.mapWidth mapWidth this.mapHeight mapHeight this.distance distance private float getWidth() return mapWidth Constants.WORLD TO SCREEN private float getHeight() return mapHeight Constants.WORLD TO SCREEN private Callback callback public interface Callback void onLoad() public void startOver() clear() currentDistance number 0 loadMap(number) private void clear() for (OrthogonalTiledMapRenderer render renderer) render.dispose() With above class, I can display and load new map on screen when camera reaching the map end. But the tile layer texture keeps wrong position. Please give me an advice.
15
How to make the bullet stop accurately when destination is reached? In the below code, is the method I use to move a bullet to its destination and stop when bullet is near to destination. But the problem is the bullet is stopping not accurately, sometimes there's a small offset or span or sometimes is accurate depends on the angle. public Vector2 getVelocity(Vector2 currentPosition, Vector2 targetPosition) Vector2 targetDirection targetPosition.cpy().sub(currentPosition) return targetDirection .nor() final float SPEED 6 float pos bulletPosition.len() float des bullet.destination.len() float tol Constants.TIME STEP SPEED if(MathUtils.isEqual(pos,des, tol)) body.setLinearVelocity(0,0) else body.setLinearVelocity(getVelocity(bulletPosition, destination).scl(SPEED)) SOLVED if(MathUtils.isEqual(pos, des, tol)) quick amp dirty way body.setTransform(destination, angle) better way ...
15
Ball bouncing with box2d in libgdx I just started using Box2d and libgdx. I followed this tutorial, https github.com libgdx libgdx wiki Box2d And a ball would bounce if I run the following code I took from the tutorial. ...omit the rest of code World world new World(new Vector2(0, 10), true) BodyDef bodyDef new BodyDef() bodyDef.type BodyType.DynamicBody bodyDef.position.set(100, 300) Body body world.createBody(bodyDef) CircleShape circle new CircleShape() circle.setRadius(6f) FixtureDef fixtureDef new FixtureDef() fixtureDef.shape circle fixtureDef.density 0.5f fixtureDef.friction 0.4f fixtureDef.restitution 0.6f Make it bounce a little bit Fixture fixture body.createFixture(fixtureDef) circle.dispose() ...omit the rest of code I'm wondering how I can make the ball bounce like a basketball or volleyball? It's like the ball movement is in a space, move so slowly. I changed some properties such as density or friction, but it seems box2d doesn't care of air friction, so nothing changed at all. Could you tell me how I can make the ball movement to be a basketball or such stuff?
15
How to split a screen in half using LibGDX without scaling? I am currently working on a racing game with libGDX and I need to split the screen in half for a two players mode. (Player 1 in first half and Player 2 in second half). I already have Camera1 that will follow Player 1's car, and Camera2 that will follow Player 2's car. Basically, I want the first half to show Player 1's car and the second half to show Player 2's car. I have been searching for a while online for a way to split screens with LibGDX and found how to split the screen in two with this code Left Half Gdx.gl.glViewport( 0,0,Gdx.graphics.getWidth() 2,Gdx.graphics.getHeight() ) Right Half Gdx.gl.glViewport(Gdx.graphics.getWidth() 2,0,Gdx.graphics.getWidth() 2,Gdx.graphics.getHeight() ) However, it squeezes the screen into the right half, which is not what I want. Is there a way to split the screen without squeezing it?
15
Libgdx, actor touchlistener not working public class Main extends ApplicationAdapter SpriteBatch batch OrthographicCamera camera Stage stage Image greyback Image circle private float width private float height Override public void create () batch new SpriteBatch() camera new OrthographicCamera() stage new Stage() Gdx.input.setInputProcessor(stage) greyback new Image(new Texture("greyback.png")) circle new Image(new Texture("circle.png")) width Gdx.graphics.getWidth() height Gdx.graphics.getHeight() greyback.setWidth(width) greyback.setHeight(height) circle.setPosition(200,200) circle.setBounds(200, 200, circle.getWidth(), circle.getHeight()) circle.setTouchable(Touchable.enabled) circle.addListener(new InputListener() public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) System.out.println("CLICKED") return true public void touchUp(InputEvent event, float x, float y, int pointer, int button) System.out.println("REMOVED") ) stage.addActor(greyback) stage.addActor(circle) Override public void render () stage.draw() But, when I click on the circle the touchlistener doesnt fire, why?
15
LibGDX Button and Table Layout I want to change the position of the Buttons inside a table, I tried setting their X and Y, or get their position when adding the Buttons on the Table, but it didn't work. It always aligns the button on the center. Code TextureAtlas ta new TextureAtlas("Comecar.txt") final TextureAtlas.AtlasRegion as ta.findRegion("comeca") final TextureAtlas.AtlasRegion as2 ta.findRegion("comecaversao2") myTexRegionDrawable2 new TextureRegionDrawable(as2) myTexRegionDrawable new TextureRegionDrawable(as) myTexRegionDrawable.setMinHeight(300) myTexRegionDrawable.setMinWidth(260) myTexRegionDrawable2.setMinHeight(300) myTexRegionDrawable2.setMinWidth(260) b new ImageButton(myTexRegionDrawable) op new ImageButton(myTexRegionDrawable2) op.addListener(new ClickListener() Override public void clicked(InputEvent event, float x, float y) ) b.addListener(new ClickListener() Override public void clicked(InputEvent event, float x, float y) gdxGame.setScreen(new Janela2(gdxGame)) ) t new Table() t.add(b) I tried setting the position here t.add(op) t.setFillParent(true) stage.addActor(t) Gdx.input.setInputProcessor(stage)
15
Is using camera and viewport in Libgdx always necessary? I understand that camera and viewport are important to keep virtual measurement units and handle different aspect ratios and resolutions when building games with worlds bigger than the screen (e.g. side scrollers map based games). I am not sure whether it is the proper way to go for a simple game that fits on the screen entirely like a puzzle or card game for example. Is it still better to use camera and viewport in this case, or is it more simple, effective (and hence better) to use directly screen absolute coordinates for these types of games? Or to put it in other way what are the advantages to use camera and viewport for games that fit on the screen entirely?
15
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 map transition via try catch exeption I have a simple question. Some explination first, however I am using libGDX and making a Legend of Zelda type top down game and I'm having an issue with map transitions. When I made the tilemap and added the (currently crappy) collision detection to it, I noticed that the IDE threw an error when the character walks off the map (where there are no tiles to test the collision possibility against). I thought, cool, I can use that. Knowing that the program would throw an exception when the player left the screen, I caught that exception and used it to decide to which map the player was trying to transition and switch accordingly. I played a little transition from the scene2d actions and to the next map we went. BUT, I got to thinking that while catching that exception is a great thing, I probably shouldn't rely on it for map transitions. I'm betting you all will agree handle the exception just in case, but don't rely on it. SO, this means that I need to handle a transition before the user gets off the map. I tried using transition tiles from within the collision detection If the tile had the transition property, figure out where the user is attempting to transfer and then play the transition effect and on to the next map. The only problem with this system is that it doesn't look right. The user transitions just as collision is made while there is still room left in the tile to transverse. My question to you all, then, is this Is there a middle ground between the two? Is there a way to tell end of map or last tile, allow the user to transverse the tile just prior to transitioning? Or are my two ways the only ones?
15
Gesture Detector not firing So I'm trying to create a input class that implements a InputHandler amp GestureListener in order to support both Android amp Desktop. The problem is that not all the methods are being called properly. Here is the input class definition amp a couple of the methods public class InputHandler implements GestureListener, InputProcessor ... public InputHandler(OrthographicCamera camera, Map m, Player play, Vector2 maxPos) ... Override public boolean zoom(float originalDistance, float currentDistance) this.zoom true this.zoomRatio originalDistance currentDistance cam.zoom cam.zoom zoomRatio Gdx.app.log("GestureDetector", "Zoom ratio " zoomRatio) return true Override public boolean touchDown(int x, int y, int pointerNum, int button) booleanConditions TOUCH EVENT true this.inputButton button this.inputFingerNum pointerNum this.lastTouchEventLoc.set(x,y) this.currentCursorPos.set(x,y) if(pointerNum 1) this.fingerOne true this.fOnePosition.set(x, y) else if(pointerNum 2) this.fingerTwo true this.fTwoPosition.set(x,y) Gdx.app.log("GestureDetector", "touch down at " x ", " y ", pointer " pointerNum) return true The touchDown event always occurs but I can never trigger Zoom (or pan among others...). The following is where I register and create the input handler in the "Game Screen". public class GameScreen implements Screen ... this.inputHandler new InputHandler(this.cam, this.map, this.player, this.map.maxCamPos) Gdx.input.setInputProcessor(this.inputHandler) Anyone have any ideas why zoom, pan, etc... are not triggering? Thanks!
15
swipe effect problem using only mesh and array libgdx I tried to combine matdesl's and libgdx's draw lines algo ang code. but i can only create a line. problem is i want to make a fruit ninja swipe effect but only knows this... problem is i want to make a fruit ninja swipe effect but only knows this... anyone try to help me on improving just a line to have a swipe effect like fruit ninja? public class GameTouch private static final int MAX LINES 1000 private OrthographicCamera camera private Mesh lineMesh private Vector3 unprojectedVertex new Vector3() private FixedList lt Vector2 gt list public GameTouch() this.camera new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()) lineMesh new Mesh(false, MAX LINES , 0, new VertexAttribute(Usage.Position, 2, "a pos")) list new FixedList lt Vector2 gt () public void update(float delta) camera.update() camera.apply(Gdx.gl10) if(Gdx.input.isTouched()) unprojectedVertex.set(Gdx.input.getX(), Gdx.input.getY(), 0) camera.unproject(unprojectedVertex) Vector2 input new Vector2() input.x unprojectedVertex.x input.y unprojectedVertex.y if(list.size gt 0) Vector2 temp new Vector2() float sqlen temp.set(input).sub(list.get(0)).len2() Array lt Vector2 gt tempA new FixedList lt Vector2 gt () if(sqlen gt 3) list.insert(input) lineMesh.setVertices(getVertices(list), 0, list.size 2) else list.insert(input) else if(list.size gt 0) list.removeIndex(list.size 1) if(list.size gt 2) lineMesh lineMesh.render(GL10.GL TRIANGLE STRIP) Gdx.gl10.glColor4f(0f, 0f, 1, 0.5f) private float getVertices(Array lt Vector2 gt list) float vertices new float list.size 2 int counter 0 for(Vector2 vertex list) vertices counter vertex.x vertices counter vertex.y return vertices private class FixedList lt T gt extends Array lt T gt public FixedList() super(Vector2.class) public FixedList(int capacity , Class lt T gt type) super(false, capacity , type) public void insert(T t) T items this.items size Math.min(size 1 , items.length) for(int i size 1 i gt 0 i ) items i items i 1 items 0 t
15
Box2D body rotation problem When my player jumps, I start a rotation and I want to finish it when he gets back on the ground. My Player is jumping off the ground and landing back on in 1 second. My physics are updating at 10 FPS (10 times per second). So I want to complete a 180 degree rotation for exactly 1 second. I add 18 degree to my player at every world update. I convert the degrees to radians, but the result is this I want him to jump with a 0 degree angle, rotate and land with 0 degree angle. Here is my code world.step(step, 8, 3) if(isJumping) angle (18 Math.PI) 180 conver degrees to radians player.body.setTransform(player.body.getPosition(), angle)
15
Unable to draw single particle effect at two places I am using Libgdx ParticleEffect to draw a fire particle effect . The issue I have is that when I try to render a ParticleEffect at two different locations within single game loop, only the last draw call has the effect drawn on screen. I update the Particle effect only once per game loop but set its position to two distinct locations and draw it. Is this a trivial problem with Libgdx ParticleEffect ParticleEffect effect new PartcleEffect() effect.load(gdx.files.internal("data effect.particle"),atlas,"") effect.start() In render effect.update(deltaTime) effect.setPosition(x1,y1) effect.draw(batch) effect.setPosition(x2,y2) effect.draw(batch) Can someone tell me why it isn't working?
15
How can I post scores to Facebook from a LibGDX Android game? I am using LibGDX to create an Android game. I am not making the HTML backend of the game. I just want it to be on the Android Google Play store. Is it possible to post the scores to Facebook? And if so, how can I do it? I searched and found the solutions only for web based games.
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
How to achieve the top down (oblique) projection of textures using an OrthographicCamera? This question is related to (How to calculate the initial velocity of projectile motion by a given distance and angle from point A to B) question. Details In the below image is the graphical projection of top down (oblique). And this is the pattern that I used to reference. Currently From the answer, the Coordinate systems describes how the oblique projection works. screenPos.x (worldPos.x cameraOffset.x) zoomFactor screenPos.y (worldPos.y worldPos.z cameraOffset.y) zoomFactor From the related question, currently the camera that I'm using is OrthographicCamera. Additional question In the above GIF animation, do I need to customize OrthographicCamera class to achieve the oblique projection? Or do I need to create a new ObliqueCamera class that extends Camera? (If yes, what pointers do I need to review to be able to do it, because I am new to graphical projection).
15
How to smooth scene2d ui default skin? I am usng uiskin.png, default.fnt, uiskin.atlas to create my game UI, but the images is blurred, How do I make it smooth?
15
Vertical alignment of a padded font generated by Hiero in libgdx I've generated bitmap fonts for libgdx using Hiero. I've got several distance field fonts that require a lot of padding, unfortunately they don't seem to align correctly. Below is a font with a bounding box drawn to the values returned from getBounds(). I've just changed to distance field fonts and all my logic that handles vertical positioning is broken because of this. If I use a font without any padding above or below then fonts are drawn aligned correctly. My padding is 10 on all sides. Playing with a couple of characters, if I increase the y by 10 and decrease the height by 10 in the .fnt file I get the image below instead, which looks far more accurate. If someone can tell me how I can resolve this issue, or a good way to work around it then that would be appreciated.
15
How to setup engine properly in ktx ashley? I'm trying to setup simplest Ashley project with only 2 entities and get this error Exception in thread "LWJGL Application" java.lang.IllegalStateException createComponent(T class.java).apply(configure) must not be null Here is the code class AshleyScreen(game Main) KtxScreen private val engine Engine() override fun show() engine.add entity with lt DrawableComponent gt sprite Sprite(Texture("image1.png")) with lt TransformComponent gt position.set(0f, 400f) entity with lt DrawableComponent gt sprite Sprite(Texture("image2.png")) with lt TransformComponent gt position.set(500f, 50f) val renderSystem RenderSystem() engine.addSystem(renderSystem) override fun render(delta Float) engine.update(delta) Components class DrawableComponent(var sprite Sprite) Component class TransformComponent(val position Vector2 Vector2()) Component Systems class RenderSystem IteratingSystem(allOf(DrawableComponent class).get()) val batch SpriteBatch() val tm ComponentMapper.getFor(TransformComponent class.java) val dm ComponentMapper.getFor(DrawableComponent class.java) override fun processEntity(entity Entity, deltaTime Float) val t tm entity val d dm entity d.sprite.setPosition(t.position.x, t.position.y) clearScreen(0.8f, 0.8f, 0.8f) batch.begin() d.sprite.draw(batch) batch.end() Compiler complains on engine.add line.
15
Multiple clicks required before listener is called I have a screen with multiple stages (pre game, game, pause) and on the game stage I have a pause button. This is implemented as public class PauseButton extends Actor private NumberzGame m game private TextureRegion m pauseButton private int m buttonSize public PauseButton(NumberzGame game, Stage stage, int size) super() m game game m buttonSize size m pauseButton createPauseButton() setWidth(m buttonSize) setHeight(m buttonSize) Override public void draw(Batch batch, float parentAlpha) Color color getColor() batch.setColor(color.r, color.g, color.b, color.a parentAlpha) batch.draw(m pauseButton, getX(), getY()) super.draw(batch, parentAlpha) private TextureRegion createPauseButton() Pixmap map new Pixmap(m buttonSize, m buttonSize, Format.RGBA8888) map.setColor(ColorUtils.colorFromHex(NumberzGame.COLOR BACKGROUND)) map.fill() int radius (m buttonSize 2) 4 map.setColor(ColorUtils.colorFromHex(NumberzGame.COLOR SOUND BUTTON BACKGROUND)) map.fillCircle(m buttonSize 2, m buttonSize 2, radius) map.setColor(ColorUtils.colorFromHex(NumberzGame.COLOR SOUND BUTTON)) int width 2 radius 10 int height width int xpos (m buttonSize width) 2 int ypos (m buttonSize height) 2 Pixmap pause m game.getAssets().get(NumberzGame.ID PAUSE PIXMAP, Pixmap.class) map.drawPixmap(pause, 0, 0, pause.getWidth(), pause.getHeight(), xpos, ypos, width, height) TextureRegion result new TextureRegion(new Texture(map)) map.dispose() return result In the screen class I have the following code to add the pause button to the game stage m pauseButton new PauseButton(getGame(), m gameStage, NumberzGame.PLAY BUTTON WIDTH) m pauseButton.setX(width NumberzGame.PLAY BUTTON WIDTH NumberzGame.MARGIN) m pauseButton.setY(height NumberzGame.PLAY BUTTON WIDTH NumberzGame.MARGIN) m pauseButton.addListener(new ClickListener() Override public void clicked(InputEvent event, float x, float y) m state GameState.PAUSED getGame().getWorld().pauseWorld(true) ) m gameStage.addActor(m pauseButton) When I run the application the first click on the pause button properly pauses the game and after I resume the game, I need to press the pause button twice to have it trigger. What am I missing here?
15
How do you add AdMob to LibGDX game? Im currently trying to implements AdMob into my libgdx game, but it seems that all tutorials are deprecated. For example in the offical libgdx wiki the google play services get imported into eclipse, but google split the google play services up. Also I need to implement Firebase to the game (u need to now), but it doesnt say anything about that either. I also looked at the offical tutorials for Android Studio, but doing it in LibGDX doesnt seem to work (Cant resolve AdView). All help is appreciated, thanks.
15
LibGDX HexagonalTiledMapRenderer wrong stagger index? Im using Tiled map editor, Hexagonal(staggered) map, libgdx version 1.9.9 If I set staggeredIndex even in tiled map editor, libgdx seems to render odd If I set it to odd in map editor, libgdx renders even Screen Shots Here's the code Override public void create () map new TmxMapLoader().load("mapa.tmx") cam new OrthographicCamera(Gdx.graphics.getWidth(),Gdx.graphics.getHeight()) mapRenderer new HexagonalTiledMapRenderer(map) Override public void render () Gdx.gl.glClearColor(0, 0, 0, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) cam.update() mapRenderer.setView(cam) mapRenderer.render()
15
How to start an animation just once on an event in libGDX I am trying to show an explosion animation which i created using a few textureregions and created Animation missileblastAnimation from those textureregion like this TextureRegion explosion explodemissile1, explodemissile2, explodemissile3, explodemissile4, explodemissile5, explodemissile6, explodemissile7,explodemissile8, explodemissile9, explodemissile10, explodemissile11, explodemissile12, explodemissile13, explodemissile14,explodemissile15, explodemissile16, explodemissile17, explodemissile18 missileblastAnimation new Animation(0.1f, explosion) missileblastAnimation.setPlayMode(Animation.NORMAL) I have this following code in the render method Note explosionstarted is set to true when missile hits the ground if(explosionstarted) check if the missile hits the ground to start explosion animation batcher.draw(AssetLoader.missileblastAnimation.getKeyFrame(runTime), 100, 300 102, 50, 102) if(AssetLoader.missileblastAnimation.isAnimationFinished(runTime)) i found that isAnimationFinished tells if animation is finished or not but i still cant understand the passing runTime thing explosionstarted false reset the boolean to make the animation stop drawing Problem is the animation is not playing as it should i.e sometimes it plays too much fast . sometimes it skips first few frames and jumps to ending frames. What is the right way to do this? Is there any other way i can check if the animation is completed ?
15
How can I detect touch intensity or pressure via libGDX? How can I detect the intensity of touch pressure in libGDX? For example, low pressure, medium, medium high, high and so on. There are some questions about it but there aren't answers for libGDX.
15
How to implement own UI widget in libGDX? I want to implement my own widget, here is an image what I want to get. Instead of numbers there will be some names, but I think it doesn't matter. I'm pretty new in libGDX, so could you please briefly describe me plan, how can I do something like this (if there will be some code, it would be awesome)? I tried to google it, but didn't find something relevant. Thanks in advance!
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
How can my entities avoid walking on certain tiles? In my tile map, created with 'Tiled', I placed some tiles that need to be avoided by my mobiles. Tiles like water or obstacles. The entities "wander" in the map, choosing random directions, and their position are in world coordinates (float), not grid or tile positions (int). To create a more natural effect, the random directions are similar in a period of time, so no abrupt change of direction occurs. Is there a way to make entities avoid some tile types, or 'Tiled' tile properties, without losing the "wander" behaviour? I mean, choose random directions that do not reach these type of tiles?
15
LibGDX changing actors parents is resulting in unwanted (x,y) translation I have a Rolodex of task item actors I want to drag to an agenda tablet. My drag and drop functionality is non native, but came from modifying a book's implementation. The problem seems to be when I change the parent of a task item, 'a', to the agenda's parent, 'other' other.getParent().addActor(a) When I do so the actor's coordinates shift. I want the actor to remain in the same spot I dropped it down. It worked as desired previously, possibly because the Rolodex's parent and the agenda's parent shared the same, whole screen dimensions. I've since moved away from layout to positioning actors and their groups on the screen with setBounds(). Tracking the (x,y) coordinates of my dragged item I'm getting negative values for x while it remains visible on screen, making me think actor.getX() and actor.getY() return values relative to the parent carousel container class I made, and not the screen stage nor the agenda's container. I found a set of methods off of Actor that looked promising, localToXXXX(Vector2), and experimented with a variety of them before settling on the following I think should work Vector2 snapShot a.localToActorCoordinates(other.getParent(), new Vector2( a.getX(), a.getY()) ) other.getParent().addActor(a) a.setBounds(snapShot.x, snapShot.y, a.getWidth(), a.getHeight()) ...but it doesn't. Converting it to stage or screen coordinates with the other method options shifts it even farther away from desired. What am I misunderstanding? How can I change an actor's parent without the x,y shifting?
15
LibGDX Overlay Game with Stage I have been working on a 2d game that is similar to billiards pool. I've got the basic game down and now I'm working on some visual effects. One of the things I would like to do is have have numbers pop up on the screen where a scoring event occurs and then have that number "swoosh up" to the main score at the top of the screen. To accomplish this I have been trying to overlay a Stage onto my main game area so that I can add score text and then let the LibGDX Scene2d take over. I am adding the text as an actor to the stage and then assigning some actions to it to achieve the desired effect. The problem I'm having is that when I add the object I need to convert from world to stage coordinates. This is because I want to place the score popup where two balls touch, which is in world coordinates. I have tried to use the "project" method of the stage's viewport (it is a FitViewport) but the coordinates never translate correctly. Now that I've explained what I'm trying to do, I was hoping that someone would know how I could pull this off. I'm sure it isn't difficult and that I'm missing some small detail. Here is the relevant code This is the class that will be used to overlay a stage onto the main game screen. import com.badlogic.gdx.Gdx import com.badlogic.gdx.graphics.Camera import com.badlogic.gdx.math.Interpolation import com.badlogic.gdx.math.Vector2 import com.badlogic.gdx.scenes.scene2d.Stage import com.badlogic.gdx.scenes.scene2d.actions.Actions import com.badlogic.gdx.scenes.scene2d.ui.Label import com.badlogic.gdx.scenes.scene2d.ui.Skin import com.badlogic.gdx.utils.viewport.Viewport public class UIOverlay private Skin skin new Skin( Gdx.files.internal("skins gamePlaySkin.json")) private Stage stage new Stage() public void init (Viewport viewport) stage.setViewport(viewport) stage.getViewport().update(GameWorld.WIDTH, GameWorld.HEIGHT, true) public void render () stage.act() stage.draw() public Stage getStage () return this.stage public void addScorePopup (int score, Vector2 worldPos) Viewport vp stage.getViewport() Vector2 screenPos new Vector2(worldPos.x, worldPos.y) vp.project(screenPos) Some sample vectors after projection worldPos.x 0.88585174, worldPos.y 1.6051532 screenPos.x 0.885849, screenPos.y 1022.39484 Another Set worldPos.x 0.63776636, worldPos.y 0.8991218 screenPos.x 0.63777924, screenPos.y 1023.1009 Label popLabel new Label(String.valueOf(score), skin, "popupScore") stage.addActor(popLabel) popLabel.setPosition(screenPos.x, screenPos.y) float time 0.5f popLabel.addAction(Actions.delay(1000, Actions.sequence(Actions.moveTo(0.0f, 0.0f, time, Interpolation.sineIn), Actions.alpha(0, 0.1f)))) This is where I set up the main game viewport public static void init() GameWorld.WIDTH and HEIGHT are 1280 and 1024 m camera new OrthographicCamera() m camera.setToOrtho(true, GameWorld.WIDTH, GameWorld.HEIGHT) m viewport new FitViewport(GameWorld.WIDTH, GameWorld.HEIGHT, m camera) When creating the UIOverlay I pass the game's m viewport into UIOverlay.init(). I have also tried creating a new FitViewport in UIOverlay with the same dimensions as the game's viewport, but have the same behavior.
15
Libgdx scrolling background for preview screen Good day, I have been coding for quite a while now and I'm at a certain point where I am having difficulties on solving something. I've been creating a preview screen which contains the following reads .txt file and stores them in an array which will be displayed on the screen. the text will have an animation which will be moving upwards like a Star Wars type of intro. the background of the screen will also move upwards. The problems that I have encountered are the following my text did not fit on the screen, but I did try to change the font and the font size and also did change the spacing in the .txt file. the text always starts in the middle of the screen which it should start at the bottom of the screen. the background is buggy, tried to debug it but still can find a solution for a parallaxbackground(scrolling background) and here is the code. public class PreviewScreen implements Screen private static DugManMainClass game private SpriteBatch batch private OrthographicCamera camera private Texture tx1 Assets.bgmenu private BitmapFont font Assets.menufont2 private final static List lt String gt lines new ArrayList lt String gt () private static int time 0 private float temp 0 private Sprite s public PreviewScreen(DugManMainClass game) this.game game reads .txt file and stores them in an array try BufferedReader br new BufferedReader(new InputStreamReader(Gdx.files.internal("previewtext.txt").read())) String line "" while ((line br.readLine()) ! null) lines.add(line) br.close() catch(Exception e) e.printStackTrace() Override public void render(float delta) float w s.getHeight() Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) temp is a timer which will do the animation effect for the text and background temp Gdx.graphics.getDeltaTime() while(temp gt 1.0f 60.0f) PreviewScreen.tick() temp 1.0f 60.0f here is my problem for the background s.setU(temp 1f) s.setU2(temp 1f) batch.setProjectionMatrix(camera.combined) batch.begin() s.draw(batch) i commented this out because i waited to draw my sprite which is the background text(parallaxbackground) batch.draw(s, 0, (temp 10 w)) batch.draw(s, 0, (temp 10 w) w) int yo time 4 this is where the the text problem is for (int y 0 y lt 420 12 y ) int yl yo 12 420 12 y if (yl gt 0 amp amp yl lt lines.size()) font.draw(batch,lines.get(yl), (800 30 12) 2, y 12 yo 12) batch.end() Override public void resize(int width, int height) Override public void show() batch new SpriteBatch() float w 800 float h 420 camera new OrthographicCamera() camera.setToOrtho(false, w, h) tx1.setWrap(TextureWrap.Repeat, TextureWrap.Repeat) s new Sprite(tx1) s.setPosition(0, 0) Assets.bgsound3.play(1f) Override public void dispose() Assets.dispose() public static void tick() time if (Gdx.input.isKeyPressed(Keys.ENTER) Gdx.input.isTouched()) game.setScreen(new MainMenuScreen(game)) Assets.bgsound3.stop() if (time 4 gt lines.size() 10 250) game.setScreen(new MainMenuScreen(game)) Assets.bgsound3.stop()
15
How do I work out what resolution my backgrounds should be? I'm working on a game that's 1200 x 800. The pixels per meter ratio is 1 20. When I add my background texture that is 400 x 225. It fits well in the zone however the lines on the image are pixelated. How can I work out what resolution my background should be in order for it to not look pixelated? Here's what I have so far Override public void show() ... b1 new Texture(Gdx.files.internal("backgrounds spr stars01.png"), true) b1.setFilter(TextureFilter.Linear, TextureFilter.Linear) ... Override public void render(float delta) (43, 55, 61) ... Gdx.gl.glClearColor(132 255f, 0 255f, 35 255f, 1f) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) world.step(TIMESTEP, VELOCITYITERATIONS, POSITIONITERATIONS) world.getBodies(bodies) camera.position.set(player.getPosition().x, player.getPosition().y, 0) camera.update() timer (delta 1.25f) batch.setProjectionMatrix(camera.combined) batch.begin() batch.draw(b1, player.getPosition().x 20, player.getPosition().y 20) batch.end() ... Override public void resize(int width, int height) camera.viewportWidth 1200 20 60m camera.viewportHeight 800 20 40m hud.getViewport().update(width, height) The result The original background edit my windows resolutions is 1200x800 edit2 Both answers have helped greatly in understanding background scaling. I have decided to create reusable polygon textures, much smaller than my original background, that I can scale with my box2d world. Thanks for the help!
15
2D Bounding box for collision detection alternate shapes I have objects in my game such as clouds and stars. I have given the bounds for them in rectangle format. The images are not rectangular, although the collision boxes are. How can I implement a collision box that is exactly the shape of my character? I'm suing overlap2D.
15
Libgdx how does dispose() work? My game uses a lot of images, for the over world, battle screens, chats, etc. I'm really meticulous when it comes to memory management, and I've noticed that even though I dispose every image when I load in a new one, the memory never goes down. Isn't this what Dispose() should do or is my understanding wrong?
15
Is Table the only layout that I can use in libgdx? I'm looking for the common way to handle the layout in libgdx. I searched google and found only table layout. Meanwhile I don't use any layout and just insert coordination into each visual object but I think that this is not the proper way to do it... Is their any other layout that I can use? p.s The game layout should split into two parts, left is smaller that the right and contains things like score time and info about stuff in the game. The right part will display the game play itself
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
How to store each rendered frame as image in libgdx for debugging I have a libgdx screen's render method where I am executing lots of for loops and drawing various shapes on screen in thoese loops. Also I am manupulating (x,y) of each shape at runtime to acheive a smooth animation.Everything was ok until, Issue Recently I had added few more shape's at some positions in my screen. Due to some mess up, I am getting flicker, and some shapes are getting drawn out of my game world. I tried to debug my code many times but there are too many loops and shapes so I am unable to pin point the exact loop or frame where shapes are getting drawn out of my game world. Need Input on following approach to debug So I was thinking to save each frame of my render method as an image locally. Is it possible? Please provide suggestions or sample code to acheive it. I will hook up some debug variables in my loops to calculate exact frame where things are getting messed up. That I will take care of. Please advice on above question. Thanks in advance.
15
Libgdx Box2D and Screen Viewport Scaling I am currently having problems getting an easy to manage system of scaling my units for use with box2D. Normally I would create virtual units to go along with me viewport and camera but since I am using a screen viewport this is not as easy as it seems. I have tried scaling my viewport by setting the units per pixel to 1 100 which will then scales my world by 100 times. Then I set set my sprite batch projection to be 1 100 as well as my tiles map renderer scale to be 1 100 this led to my box2D elements of size .64 to be 64 pixels large which leads to a good looking simulation as well as a good size. The only problem is then any sprite I use must also be scaled with a scale of 1 100. Also my scene 2d HUD must also be scaled. This works but it is confusing to manage and very time consuming to write out all the scaling etc. I am looking to see if there is a way to use world units where 1 world unit is 100 pixels to make my box2D elements and use screen coordinates for the rest of my drawing etc. Also if there is an easier way to do this that I am not thinking of please let me know. I will try to post code later tonight when I am back at my computer. EDIT I created a test project to work on just the scaling factor of my game and here is my test code. Override public void create () camera new OrthographicCamera() camera.translate(new Vector3(camera.viewportWidth 2, camera.viewportHeight 2, 0)) vp new ScreenViewport(camera) vp.setUnitsPerPixel(1 100f) batch new SpriteBatch() img new Texture("badlogic.jpg") sprite new Sprite(img) sprite.setScale(1 100f) world new World(new Vector2(0, (float) 9.8), true) BodyDef bdef new BodyDef() bdef.type BodyType.DynamicBody bdef.position.set(1, 1) body world.createBody(bdef) FixtureDef fdef new FixtureDef() PolygonShape shape new PolygonShape() shape.setAsBox(1, 1) fdef.shape shape body.createFixture(fdef) dr new Box2DDebugRenderer() map new TmxMapLoader().load("Levels bricksTest.tmx") mapRenderer new OrthogonalTiledMapRenderer(map, 1 100f) Override public void render () camera.update() sprite.setX(body.getPosition().x sprite.getWidth() 2) sprite.setY(body.getPosition().y sprite.getHeight() 2) Gdx.gl.glClearColor(0, 0, 0, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) mapRenderer.setView(camera) mapRenderer.render() batch.setProjectionMatrix(camera.combined) batch.begin() sprite.draw(batch) batch.end() world.step(Gdx.graphics.getDeltaTime(), 6, 2) dr.render(world, camera.combined) Override public void resize(int width, int height) vp.update(width, height, true) This code runs and produces the expected results, but I feel there has to be some easier way. Also ignore any of the size numbers horrible sloppiness of this code because this is only a test project and is not from my actual game. This is a picture of the final result. Note The box2D box is not the same size as the image because I wanted the box to be about the size of a character from my game for this test. I also moved the position of the box to x 5 and y 5 so it is easier to see.
15
LibGdx How to check if VSync is enabled I am just about finished my options screen, the only thing I need is some way of detecting if Vsync is enabled or not. I'm using LibGdx 1.5. I have tried to find an access to wglSwapIntervals, but haven't found one. Libgdxs API only allows a setVsync options that accepts a Boolean. If anyone could shed some light on this, it would be greatly appreciated!
15
LibGDX , 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
What is the exact unit in LibGDX if it says "private static final float WORLD SIZE 480"? In the code I see that the WORLD SIZE variable was initialized with 480 private static final float WORLD SIZE 480 What exactly the 480 means, are they pixels, cm or meters?
15
LibGDX touchDown event continues I'm using libGdx to create a simple platformer. I used a set of images as an onScreen controller for Android, and use this code to fire a shot Override public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) downPressed true return true return super.touchDown(event, x, y, pointer, button) Override public void touchUp(InputEvent event, float x, float y, int pointer, int button) downPressed false super.touchUp(event, x, y, pointer, button) But when I keep the button pressed, the player continues to shoot which I don't want, I want the player to tap to shoot. What am I doing wrong?
15
Lighting shadow casting sprites with box2Dlights I currently have something like this using box2Dlights Ideally, I would like objects casting shadows to be lit, so the object is lit but there is still a shadow cast around it. Right now the object is covered by shadow. I am aware of the soft and softnesslength settings in box2dlights but this is not really what I'm looking for. Softness seems to light up a certain radius from the player rather than just lighting objects. It ends up kind of weird looking So for example in the above picture, I would want the entire grey box to be lit, and none of the area to the left right behind it to be lit. Any thoughts would be appreciated. Thanks
15
LibGDX FrameBuffer no Transparency when drawing I try to draw severeal Sprites to a FrameBuffer. The Sprites are PNGs with transparency. When I draw them directly to the screen it's fine. But when I draw on the FrameBuffer and then draw the resulting texture on the screen the transparent parts are cut out and the glBackground shines through. Any idea how to solve this? Here is how I do it FrameBuffer fbo new FrameBuffer(Format.RGBA8888, width, height, false) Sprite fboTexture new Sprite(frameBufferObject.getColorBufferTexture()) fboTexture.flip(false, true) fbo.begin() batch.begin() Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) batch.draw(sprite1, 0,0) batch.draw(sprite2, 0,0) batch.draw(sprite3, 0,0) batch.end() fbo.end() batch.begin() batch.draw(fboTexture, 0,0) batch.end()
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
Box2d RopeJoint bug fix or alternative solution? What I am trying to do is to create rope game. Below you can find a movie how it looks like now. https youtu.be QTULCGNF70I I am using RopeJoint and I am reducing maxLength each frame to be able to accelerate. Everything seems fine, but the problem appears for bubble kind of ball. I realized that shortening rope does not increase balls velocity. For example if I throw the rope fully vertical and the only "force" is from shortening the rope, the velocity is 0,0. Seems like, body movement is not simulated? After I let the rope go the momentum is lost. The bubble can fly, but the factor from rope shortening is ignored. I don't know if you understand what I mean. The movie should clarify it better. Workarounds I tried Good idea was to use prismaticJoint, but the rotation is fixed, so it doesn't work. I couldn't swing Another idea was to use wheelJoint and make use of it's frequency parameter. However here there's a problem that rope becomes rubber. Swing feeling is bad, when it can extend more than initial length, it should always only shorten. Solutions I see, but they are not available RopeJoint which keeps body momentum from rope shortening PrismaticJoint without fixed rotation WheelJoint with possibility to set max length or create the rope with it's max length, not the rest position.
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
libGDX upload z axis of sprite to graphics card Background I want to obtain each fragments position via vertex interpolation to then calculate the light vector for phong shading (L Fragment pos light source pos ). Problem At the moment I am using libGDX's com.badlogic.gdx.graphics.g2d.Sprites to upload my 2d sprites via the batch to the graphics card. However they only transport the x and y information for each vertex ( I think in the shader z is 0). I also want to upload the z axis of the sprite for use with normal map based pixel shading (calculate the vector of the incoming light). Should I use a com.badlogic.gdx.graphics.Mesh for that or can I extend the Sprite class and somehow put the z axis in the vertices float array? If I should do that, how do I do this?
15
AnimatedActor class don t work Let me explain I m reading a book I got given that is called "Beginning Java Game Development with LibGDX", and get to the section where the book talks about animating actors, or animating "sprites". The example code they presented is as follows public class AnimatedActor extends BaseActor private float elapsedTime private Animation anim public AnimatedActor() super() elapsedTime 0 public void setAnimation(Animation a) Texture t a.getKeyFrame(0).getTexture() setTexture( t ) anim a public void act(float dt) super.act( dt ) elapsedTime dt if (velocityX ! 0 velocityY ! 0) setRotation( MathUtils.atan2( velocityY, velocityX ) MathUtils.radiansToDegrees ) public void draw(Batch batch, float parentAlpha) region.setRegion( anim.getKeyFrame(elapsedTime) ) super.draw(batch, parentAlpha) I'm running the examples, using android studio, and surprisingly I find the following situation the code that proposes the book marks an error ... and it is exactly in this line public void setAnimation(Animation a) Texture t a.getKeyFrame(0).getTexture() lt getTexture() is the error setTexture( t ) anim a The error I'm getting is cannot resolve method getTexture() I'm a bit surprised, since I'm not supposed to have any errors, since I'm reading from a book ... trying to implement something similar for my project, but ... I found this. Surely, it should be that the function should be removed in recent versions of LibGDX. The only thing I try to do is that the moment you click on an actor on the stage, the texture set, change to the animated sprite. How can you create an animation in LibGDX?
15
How do you handle entity parent child relationship in Ashley ECS? In the below code example, is a parent child relationship of an entities. Now every child should follow its parent position, and the child could be re positioned anywhere. Entity character character is a parent Entity weapon weapon is a child of character Entity gun gun is a parent Entity bullet bullet is a parent Entity bulletShadow shadow is a child of bullet My own solution is to have an OwnershipComponent which has a Entity owner attribute, but there's a doubt in my mind that the components should only have a data. An Entity is a collection of data, if I pass this data to components this could lead to over killing of iteration. So I've changed my mind to use its attribute int flags, this could now be use as an id to reference to child parent relationship. public class OwnershipComponent implements public int ownerId Entity Manager class public void create() Entity character createCharacter() createWeapon(0, 0, character.flags) public void createWeapon(float x, float y, int ownerId) Entity weapon engine.createEntity() weapon.flags generated unique ID from the weapon category OwnershipComponent ownership engine.createComponent(OwnershipComponent) ownership.ownerId ownerId weapon.add(ownership) public Entity getEntityById(int id) return ... I could access now the parent entity by id and transform its child position relatively. Ownership System public void processEntity(Entity entity, float deltaTime) OwnershipComponent ownership Mapper.ownership.get(entity) Entity parent EntityManager.getEntityById(ownership.ownerId)
15
How to initiate a TCP secure connection using LibGdx to a remote server? Can anyone point to a link or share with me a piece of code which does Base on LibGdx (Gdx.net package) Use a TCP secure connection to connect to a remote server Many thanks
15
LibGDX Scrollpane won't scroll to bottom after adding children to contained table To my game I want to add a gui element that displays text and textButtons whenever something is happening or it wants you to make a decission (an answer while talking to a person for example). To keep track of your actions you shall be able to scroll it. Similar to text adverntures or dialog boxes in rpgs. I use Scene2Dui for my GUI, so I put a scrollPane in my GUIs root table. I have methods for adding stuff to the contained table and tell the scrollPane to scroll to the bottom. In general the idea works, but the thing doesn't scroll to the bottom but only to the bottom of the element I added before the current one. I'm puzzled. Here's the code, leaving out the skins and styles part public class TextBox ScrollPane box Table table Label.LabelStyle lStyle Skin skin TextBox() table.setFillParent(false) box new ScrollPane(table, scrollStyle) box.setScrollingDisabled(true, false) box.setOverscroll(false, false) box.setFillParent(false) table.align(Align.topLeft) table.row() void writeDecissions(GameEvent events) Table tableD new Table() tableD.setFillParent(false) if (events ! null) for (int i 1 i lt events.length i ) if (events i ! null) String s Character.forDigit(i, 10) " " events i .getDecision() TextButton button new TextButton(s, style) button.getLabel().setWrap(true) button.getLabel().setAlignment(Align.left) tableD.add(button).width(box.getWidth() 40).spaceBottom(20).spaceTop(20) tableD.row() table.add(tableD).align(Align.left).pad(20) table.row() box.setScrollY(table.getHeight()) This is the way I test it public void render(float delta) Gdx.gl.glClearColor(0, 0, 0, 0) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) stage.act() stage.draw() if (Gdx.input.justTouched()) gui.textBox.writeDecissions(events) I tried box.setScrollY(box.getMaxY) as well as setting overscroll to true (don't really know what that is tough). With the same result. Finally a screenshot Help appreciated.
15
Why value 1 in OrthographicCamera viewPort width? So, I read that camera new OrthographicCamera(1, h w) creates a camera with an appropriate width and height for the field view.. However, I can't understand that value 1 for the viewport width, does a value 1 means full width?
15
Downscaling an asset, still pixellated? I created a rounded rectangle in photoshop, and I rasterized the rectangle before I saved it. Yet, when I try to use the rectangle in libGDX, it looks pixelated. How can I make it so that it's smooth? Here is how my rectangle looks now My original image is 2048x2048, and I'm using batch to rescale it depending on the screen size. For example, this is how I draw the rectangle batch.draw(img, Gdx.graphics.getWidth() 2 fitW 2, Gdx.graphics.getHeight() 2 fitH 2, fitW, fitH) Where fitW and fitH depend on the current screen width and height (arbitrarily set to 300 now). So I'm essentially downscaling the original 2048x2048 rectangle to one that's 300x300. Can this be why the image is not rasterized?
15
Polygons and actionlisteners Libgdx I've been browsing these forums for a while now and I nearly always am able to find an answer without having to ask my own question! Such a great community! This is the first time I've been stumped so I hope that someone can help me, I'm just learning libgdx so any help is appreciated I know the code is rough but please be gentle as I'm learning everyday!!! ) I'm trying to create 6 shapes with inputlisteners which eventually will return the index of the shape which will correspond to an answer, but I can only seem to get the last input listener I create to actually fire... public Panel(final int count) this.count count img new Texture("badlogic.jpg") handlerShapeVertices new float 128,30,0,256,256,256 handlerShape new Polygon(handlerShapeVertices) triangle new PolygonRegion(new TextureRegion(img), handlerShapeVertices,new short 0, 1, 2 ) triangleSprite new PolygonSprite(triangle) triangleSprite.setOrigin(img.getWidth() 2,30) triangleSprite.setX(x) triangleSprite.setY(y) triangleSprite.setRotation(count 60) handlerShape.setOrigin(triangleSprite.getOriginX(), triangleSprite.getOriginY()) handlerShape.setPosition(x, y) handlerShape.rotate(count 60) setBounds(x,y, 256, 256) addListener(new InputListener() public boolean touchDown (InputEvent event, float xP, float yP, int pointer, int button) float temp handlerShape.getTransformedVertices() if(resourceManager.getInstance().interSector.isPointInPolygon(handlerShape.getVertices(),0,6,xP,yP)) System.out.println("CLICK INSIDE " count) return true ) I figured the polygon.getTransformedVertices() should work and to check they were correct I drew them in as you can see by the white lines surrounding the polygonsprites however it doesn't seem to and none of the listeners are actually fired when I use that... I'm completely stumped and hope someone has some insight or can point me in the right direction? I don't want someone to write my code for me but a pointer would be greatly appreciated!
15
Using deltaTime and Frame Rate Independence I'm working on one of my first games and I've read that linking your game logic to FPS is bad because it will run differently at different FPS (obviously). I have already made some of the basic game dependent on frame rate and now that I know this, I would like to unlink the logic and render. I've learned that LibGdx has deltaTime in its render method for this, however I believe I'm misunderstanding how I am to use it. For example, my movement currently looks something like this if (rightKeyisPressed) setVelocityX(movementSpeeD) playerPos.add(getVelocity) In my case, I would like the player to move 6 units per second. Since I built this on 60 fps, that means that movementSpeed is 0.1. Now the way I have seen deltaTime used is by scaling the movementSpeed based on the time like this setVelocityX(movementSpeed deltaTime) However, now I move very slow because delteTime is a very small number. How can I make movement still the same speed without depending on the fps? Sorry if I'm missing something obvious, I just can't seem to wrap my head around this.
15
Drawing a partial sprite with batch LibGdx I have a sprite like this. I want to draw this sprite in such a way that sprite is growing from bottom to top, using sprite batch on tap.for that,I have written the following code if (MyInputProcessor.isTap) Sprite stickSprite new Sprite(stickTexture) stickSprite.setPosition(stick.getX(),stick.getY()) for(float n 0 n lt 100 n ) float i 0.01f n batch.draw( stickSprite.getTexture(), stick.getX(), stick.getY(), stickSprite.getWidth() 2, stickSprite.getHeight() 2, stickSprite.getWidth(), stickSprite.getHeight() i, multiplying with height stickSprite.getScaleX(), stickSprite.getScaleY(), 0 , stickSprite.getRegionX(), stickSprite.getRegionY(), stickSprite.getRegionWidth(), stickSprite.getRegionHeight(), false, false) MyInputProcessor.isTap false Here the i value increments but not taking effect in the code to scale. Whats wrong with the code? I tried this also private void drawStick() Sprite stickSprite new Sprite(stickTexture) if (MyInputProcessor.isTap) stickSprite.setPosition(stick.getX(),stick.getY()) for(float n 0 n lt 100 n ) float i 0.01f n stickSprite.setSize(stickSprite.getWidth(),stickSprite.getHeight() i) stickSprite.draw(batch) But rendering full sprite only.
15
how to use preferences in libgdx I am trying to save a username for game in preferences (first time user enters the game, registration screen shows up, and after that whenever user enters the game, username is automatically synchronized). i tried the following in create() method of game class userPreferences Gdx.app.getPreferences("userPrefs") then, in my registration stage enter.addListener(new ClickListener() Override public void clicked(InputEvent event, float x, float y) super.clicked(event, x, y) user.username usernameField.getText() PanBallGame.getGameInstance().userPreferences.putString("username", user.username) user.requestPath " addUser" new RequestObserver(user) ) but this doesn't save the username in preferences. Can anyone explain how to get this work ? Thank you .
15
ShapeRenderer efficiency on games I want to draw a rectangle box to use as a text background for a visual novel library I'm writing, I wanted some flexibility of color and transparency and the ShapeRenderer class seems to fit the need but the doc brings this disclaimer This class is not meant to be used for performance sensitive applications but more oriented towards debugging. If I use it as background the most action on screen would probably be the text scrolling over it. Can someone more experient on the engine tell me if it is viable to use it under those premises, or it is really for debug only?
15
Help on TileMapRenderer In my project, I'm trying to render a map using TileMapRenderer. But it doesn't show anything when I render it. But when I use some other files from a tutorial they are rendered correctly. When debugging my TileAtlas instance shows the size as 0. I have used Texture Packer UI for packing the images. Comparing with the tutorial's files, I can see that the index starts from 1 in my file and 0 in the tutorial. But changing it to 0 wouldn't work also. map.png format RGBA8888 filter Nearest,Nearest repeat none Map rotate false xy 0, 0 size 32, 32 orig 32, 32 offset 0, 0 index 1 Map rotate false xy 32, 0 size 32, 32 orig 32, 32 offset 0, 0 index 2 Map rotate false xy 64, 0 size 32, 32 orig 32, 32 offset 0, 0 index 3 Map rotate false xy 96, 0 size 32, 32 orig 32, 32 offset 0, 0 index 4 Map rotate false xy 128, 0 size 32, 32 orig 32, 32 offset 0, 0 index 5 Here is the begining of the tmx file. lt ?xml version "1.0" encoding "UTF 8"? gt lt map version "1.0" orientation "orthogonal" width "20" height "20" tilewidth "32" tileheight "32" gt lt tileset firstgid "1" name "a" tilewidth "32" tileheight "32" gt lt image source "map.png" width "256" height "32" gt lt tileset gt lt layer name "Tile Layer 1" width "20" height "20" gt lt data gt lt tile gid "2" gt lt tile gid "2" gt Apart from that the tutorial files and my files seems to be similar. Can anyone help me here.
15
Libgdx Application terminate in an unusual way I am developing simple multiplayer game using libgdx and box2D. And Im getting error below. This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information. AL lib (EE) alc cleanup 1 device not closed Assertion failed! Program C Program Files Java jre7 bin javaw.exe File var lib jenkins workspace libgdx gdx jni Box2D Dynamics b2Body.cpp, Line 419 Expression m world gt IsLocked() false I checked similar issue in SO which suggest that I may cause if we destroy Body before our World Stepping but its not case here. While trying to debug this error I found that following code is causing error public void updateScene(PlayerStatus playerStatus) Vector2 pos playerStatus.getPosition() Player coopPlayer coopPlayers.get(playerStatus.getId()) if (coopPlayer ! null) coopPlayer.b2body.setTransform(pos, 0) Main cause of error coopPlayer.setPosition(pos.x coopPlayer.getWidth() 2, pos.y coopPlayer.getHeight() 2) Any help is greatly appreciated.
15
What is the difference between Sprite and SpriteBatch, specifically in the context of libGDX? I'm using libGDX and I'm confused about the difference between the Sprite and SpriteBatch. Anybody can explain it to me in a simple way?
15
Help Understanding libgdx create animations example game I am trying to understand the example game, cuboc. GitHub is https github.com libgdx libgdx demo cuboc. I have generated my texture atlas but I do not understand the code that uses this texture atlas. Here's the code (you can see on github too here package com.badlogic.cubocy import com.badlogic.gdx.Gdx import com.badlogic.gdx.graphics.FPSLogger import com.badlogic.gdx.graphics.GL20 import com.badlogic.gdx.graphics.OrthographicCamera import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.graphics.g2d.Animation import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.graphics.g2d.SpriteCache import com.badlogic.gdx.graphics.g2d.TextureRegion import com.badlogic.gdx.graphics.glutils.ImmediateModeRenderer20 import com.badlogic.gdx.math.Vector3 public class MapRenderer ... private void createAnimations () this.tile new TextureRegion(new Texture(Gdx.files.internal("data tile.png")), 0, 0, 20, 20) Texture bobTexture new Texture(Gdx.files.internal("data bob.png")) TextureRegion split new TextureRegion(bobTexture).split(20, 20) 0 TextureRegion mirror new TextureRegion(bobTexture).split(20, 20) 0 for (TextureRegion region mirror) region.flip(true, false) spikes split 5 bobRight new Animation(0.1f, split 0 , split 1 ) bobLeft new Animation(0.1f, mirror 0 , mirror 1 ) bobJumpRight new Animation(0.1f, split 2 , split 3 ) bobJumpLeft new Animation(0.1f, mirror 2 , mirror 3 ) bobIdleRight new Animation(0.5f, split 0 , split 4 ) bobIdleLeft new Animation(0.5f, mirror 0 , mirror 4 ) bobDead new Animation(0.2f, split 0 ) split new TextureRegion(bobTexture).split(20, 20) 1 cube split 0 cubeFixed new Animation(1, split 1 , split 2 , split 3 , split 4 , split 5 ) split new TextureRegion(bobTexture).split(20, 20) 2 cubeControlled split 0 spawn new Animation(0.1f, split 4 , split 3 , split 2 , split 1 ) dying new Animation(0.1f, split 1 , split 2 , split 3 , split 4 ) dispenser split 5 split new TextureRegion(bobTexture).split(20, 20) 3 rocket new Animation(0.1f, split 0 , split 1 , split 2 , split 3 ) rocketPad split 4 split new TextureRegion(bobTexture).split(20, 20) 4 rocketExplosion new Animation(0.1f, split 0 , split 1 , split 2 , split 3 , split 4 , split 4 ) split new TextureRegion(bobTexture).split(20, 20) 5 endDoor split 2 movingSpikes split 0 laser split 1 What I do not understand is what is split used for? Like, what is going on here split new TextureRegion(bobTexture).split(20, 20) 1 And sometimes it looks like split is a method that takes two int's, 20 and 20? Why 20? Othertimes split is used as an Array like in ... rocketExplosion new Animation(0.1f, split 0 , split 1 , split 2 , split 3 , split 4 , split 4 ) ... and I just can't follow what's going on here. Thanks!
15
How to make an application architecture a global strategy game? I am doing a global libgdx strategy, how can I properly design the architecture? So far, I'm in some kind of chaos, because there are different events that need to be shown to the player in the form of widgets. For example, one problem is that I need to understand how the Province class will display a message that there is a hunger problem. Should it immediately inside itself display a message? send event data to the main class of the game, which processes the data and, depending on the event, display the message or take some other action? do something else entirely? I had the idea to make a separate class of events and so that all game objects create this object and pass it to the main class of the game, which handles them and decides what to do with it, and if necessary, pass it to the players. And I read about the fact that there is a class java.util.EventObject. Is it worth implementing it with the help of it, or should it be implemented like that yourself? Or maybe it should be done in a completely different way? The game is turn based. There are separate provinces and the units move from one province to the neighboring one in 1 turn. At the beginning of each turn, a series of windows appear in turn, notifying of certain events, for example, famine in a province or enemy troops attacked a province, etc. There are classes of the province, the player, various UI windows, which display information about events.
15
Draw a sprite when a key is pressed in LibGDX I'm working with LibGDX. How can I draw a sprite when a key is pressed? I have tried with the following, but it doesn't seem to work. if (Gdx.input.isKeyPressed(Input.Keys.X)) batch.begin() sprite.draw(batch) batch.end()
15
LibGDX Problems with Button Listener in a Dialog I'm developing a game where the player has an inventory, and you can find chests in the map with items which you can collect, so I created a class that extends from Dialog to show both item lists, player's inventory and chest's inventory, just like this private class InventoryDialog extends Dialog public InventoryDialog(boolean isPlayerInventory, Inventory inventory) super(isPlayerInventory? "Inventory" "Chest", mySkin) final List inventoryList new List(mySkin) inventoryList.setItems(inventory.getItems()) ScrollPane pane new ScrollPane(inventoryList,mySkin) getContentTable().add(pane).size(myDimensions) button("Back") if(isPlayerInventory) button("Use").addListener(new ClickListener() Override public void clicked(InputEvent event, float x, float y) super.clicked(event, x, y) player.getInventory().useItemAt(inventoryList.getSelectedIndex()) ) else button("Get").addListener(new ClickListener() Override public void clicked(InputEvent event, float x, float y) super.clicked(event, x, y) player.getInventory().add(inventory.remove(inventoryList.getSelectedIndex())) ) So they will use or get the item only if they click that button. My problem is that the get use listener is always invoked even if the clicked button is the "Back" button, what am I doing wrong?