_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
15 | Google Play Services Message Handling with Libgdx I'm looking for some idea of how to handle Reliable Messages in Google Play Services with libGDX. So far I've been using it like this I was waiting for message with OnRealTimeMessageReceivedListener, setting an outside byte array to the message received, changing a flag that suggests that new message arrived to true, getting that message in my libGDX class using methods from interface, setting newMessage flag again to false, handling message, and so again waiting for new one private OnRealTimeMessageReceivedListener mMessageRecievedHandler new OnRealTimeMessageReceivedListener() Override public void onRealTimeMessageReceived( NonNull RealTimeMessage realTimeMessage) Handle received message here byte message realTimeMessage.getMessageData() byte tbye message ByteBuffer bb ByteBuffer.wrap(tbye) if(bb.getFloat() 1884) Log.d("MESSAGETEST", "Message received in anL " debugIntL) debugIntL byteArray message newMessageFlag true Override public boolean getNewMessageFlag() return newMessageFlag Override public byte getMessage() newMessageFlag false return byteArray Libgdx class Override public void render (float delta) ... checkForNewMessage() ... private void checkForNewMessage() if(game.customHandler.getNewMessageFlag()) handleMessage() handling message here private void handleMessage() byte message game.customHandler.getMessage() ByteBuffer bb ByteBuffer.wrap(message) float typeOfMessage bb.getFloat() if(typeOfMessage NEW UNIT MESSAGE) Gdx.app.log("MESSAGETEST", "Message received in gdx " debugInt) debugInt ... But the result is, when uncommenting the code in OnRealTimeMessageReceivedListener and adding similar log to my handleMessage() that some messages are skipped between receiving it in listener and checking for new in my libGDX class, I don't know why, maybe because some render calls take longer to do everything inside and it skips through one check call when there's significant number of those in small amount of time On the image you can see that first log is from OnRealTimeMessageReceivedListener, which receives every message, but the second one is from handleMessage, and at 251 there it wasn't called, so handleMessage just skipped this message and went to the next one. So here's my question, what's good way to handle those messages so that I won't skip any? |
15 | What is the intended usage of the Sprite class in LibGDX I am making a small game in LibGDX and it all works, sprites are moving etc. The drawing is mainly done in the render() method of a Screen, using Batch.draw(TextureRegion). So far so good. But now I would like my sprites to rotate. There are Batch draw methods for rotation (I think), but I noticed a bunch of useful methods in tne Sprite class. Problem is I do not know how to use them without making the rest of the program ugly. I could have a Sprite as a member of each "game object", but that makes direct dependency of the game model on drawing mechanism, specifically LibGDX. Besides I can see problems with serialization and duplicate parameters (Sprite x,y vs model x,y etc) and unnecessary overhead. Or I could subclass Sprite, which would probably be orders of magnitude messier. Is there a common way of clearly separating the model part and rendering part of a small game? And how is Sprite typically used? |
15 | Intersecting Triangle and BoundingBox in 3D environment I am trying to check if a triangle is intersecting a BoundingBox in a 3D space with libgdx, but I am unable to find anything that can help me with that. I tried using a Plane but it is not precise enough and I would like to avoid using Bullet. Is there any existing code that I can use to deal with this ? |
15 | Networking problems when sending textures from the server When a client connects to my game server, the server sends textures and then the world information. The problem is that the texture information may come after the world information and so the client errors out because it has no texture to give the models. How would I combat this? |
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 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 | Why do we have to resize the screen in LibGDX In a lot of the libgdx tutorials that I have took until now, I am told to resize the screen of the game using the SetToOrtho() of the orthographic camera. However, I don't get this part. Why do I have to resize the screen and make the sprites look bigger when I can just make the sprites themselves big at the first place? |
15 | Using Box2d to model rotating turret I would like to model a rotating "turret" on top of a tank like object in 2D from the side view like pictured here tank with turret http uofitorn.net static images tankwithbox2dturret.png Notice the faint outline of a gun protruding to the upper left courtesy of libgdx's debug renderer (the actual gun sprite is not being rendered). How do I best implement this using Box2d? Should I use two bodies? If so, how? Or one body with two fixtures? I tried using two bodies connected by a Revolute Joint, but the turret "gun" does not maintain a constant angle but instead rotates down until it is vertical and then just hangs there. Or should I not model the turret aspect of the tank in box2d at all? |
15 | LibGDX Show a minimap I've started to develop a small roguelike game in LibGDX. I've also made a minimap class, which creates and updates the minimap as the player explores the dungeon, by using a Pixmap. The minimap class has an OrthographicCamera (currently unused), which will be used for centering the minimap on the player. The minimap is currently rendered with it's own SpriteBatch. Now I'd like to put the minimap on the upper right corner, and clip it, because it is so big, that it'd obscure the half of the screen. I'm not really sure how to do this clipping part. I assume I should use the ScissorStack class, but the LibGDX wiki is a bit uninformative for me. |
15 | libgdx using more than one class Hi i am very new to programming and in this community,so im recently studying on how to develop games with libgdx and all the tutorials only have one class and do all the things in that class,but is it possible to use more than one class?(ex individual class for player, mobs , etc) thanks! |
15 | libgdx tiledmap rendering optimazation I'm new to game development can anyone show me how to render tiles which were only seen by the camera I cant seem to find straight answer in google. The game is in 2D and im using tiled |
15 | Input events not working simultaneously on android devices in libgdx I am making a simple platform game in Libgdx... in which I have made the player to move left, move right and jump. The code works fine on Desktop but on Android devices, Jump is not fired when the player moves left or right. It looks strange. Here is my code... private void updatePlayerForUserInput(float deltaTime) check input and apply to velocity amp state if ((Gdx.input.isKeyPressed(Keys.SPACE) isTouched(0.87f, 1,0,1f)) amp amp world.player.grounded) world.player.velocity.y world.player.JUMP VELOCITY world.player.state 2 world.player.grounded false if (Gdx.input.isKeyPressed(Keys.LEFT) Gdx.input.isKeyPressed(Keys.A) isTouched(0, 0.1f,0,1f)) world.player.velocity.x world.player.MAX VELOCITY if (world.player.grounded) world.player.state 1 world.player.facesRight false if (Gdx.input.isKeyPressed(Keys.RIGHT) Gdx.input.isKeyPressed(Keys.D) isTouched(0.2f, 0.3f,0,1f)) world.player.velocity.x world.player.MAX VELOCITY if (world.player.grounded) world.player.state 1 world.player.facesRight true private boolean isTouched(float startX, float endX , float startY, float endY) check if any finge is touch the area between startX and endX startX endX are given between 0 (left edge of the screen) and 1 (right edge of the screen) for (int i 0 i lt 2 i ) float x Gdx.input.getX() (float) Gdx.graphics.getWidth() float y Gdx.input.getY() (float) Gdx.graphics.getHeight() if (Gdx.input.isTouched(i) amp amp (x gt startX amp amp x lt endX) amp amp (y gt startY amp amp y lt endY)) return true return false I took the idea from the demo platform game SuperKoalio by mzencher at https github.com libgdx libgdx blob master tests gdx tests src com badlogic gdx tests superkoalio SuperKoalio.java Please suggest |
15 | Box2d bodies that are really close together, are getting stuck I'm using a tiled tmx map, and I created a class that adds bodies to each tile within a certain layer. This has been working great so far except for when a character or an enemy moves around on the screen, its body gets stuck on an edge between two tiles. This seems to happen "sometimes" and in certain spots. Jumping makes you unstuck but it's annoying when it happens, and I tried increasing the position iterations, but the problem keeps reoccurring. Here's what my game looks like |
15 | LibGDX MainMenu with ScrollPane Select Level and press Play In my level Menu, I am using tables that have images and text to identify each game level. Those tables are in a table that is inside a ScrollPane so the player can browse the levels available. Here is how i've written the code top of my show() method stage new Stage() Gdx.input.setInputProcessor((com.badlogic.gdx.InputProcessor) stage) atlas new TextureAtlas("levelsmenu levelmenu.pack") skin new Skin(Gdx.files.internal("levelsmenu liststyle.json"), atlas) example of the tables with image and text identifying each level tableLevel1 new Table() tableLevel1.add(new Image(skin, "rhlevelone")) tableLevel1.add(new Label("THE HOOD", skin)) table with the levels available Table levelList new Table(skin) levelList.add(tableLevel1) levelList.row() levelList.add(tableLevel2) levelList.row() etc. ScrollPane scrollPane new ScrollPane(levelList, skin) table3.add(scrollPane).padLeft(220).expandY() stage.addActor(table3) On the stage I have a button to go back to the Main Menu and a button to play the level selected. I would like to request help to figure out how to set the right listeners so a level can be selected in the ScrollPane and then played cliking the Play Button. Should I use FocusListener or ClickListener? Here is an illustration of what I want do do Thanks in advance for any help that may come!!! Rich Days |
15 | Collision detection for an arc of a circle So how do I implement the collision detection for an arc of a circle? Will I have to use the Box 2D collision or can I do it some other way using Rectangle or stuff like that? BTW I hate box2d because I don't understand most of the things in it, so if there is a solution that excludes the box2d, it will be very much appreciated. The yellow arc keeps on rotating over the black circle. How do I implement collision detection in here? |
15 | ECS should everything be a system? I've just recently started working with LibGDX and Ashley, and I find it to be really useful and I like working with the whole entity component system workflow. But I've been starting to layout the GUI and other aspects of the interface that dont exactly, to me, seem like they should be entities. When using an ECS should EVERYTHING in your game be an entity with components a system to control them? |
15 | Map Positions in LibGDX I am developing an RPG game where there is a main world map, locations such as towns or ruins on that map and buildings in those locations where players can interact to go into. For example, I have a map and my character goes to a local town where there is a inn that I can freely enter and interact in. Once I wish to leave the building, I leave and I'll be at the same position that I had once entered the building from, albeit facing the opposite direction. The one problem that I have with imagining a map system that could be complex like this are the coordinates. Is there a way of accomplishing this with the use of universal coordinates, such as only one x and y position throughout all 3 stages of this map system, or would I need to have 3 coordinates, a Map coordinate system for the world map, a Local coordinate system for the town or ruin and a Temporary coordinate system for when I am in a building? Also, is there something in libGDX that could help out with this? |
15 | Correct way of texture mapping a 2D mesh in libgdx this is a question regarding the libGDX framework. I have managed to UV map a texture to vertices (in 2D) but have come across a few problems that I think might be caused by incorrect order of vertices. In the first two pictures, you can see a rendering produced by the code bits below (without blending enabled). It seems fine at first, but you can clearly notice that the lower triangle seems to have a rough transition. Is there an easy way to prevent this (without writing too much low level stuff) or is this an expected limitation of this approach? The second problem occurs with the same code but with blending turned on. In the fragment shader, you can see that I adjust the alpha level of each pixel in the region, but with this mesh, it produces a rather weird and distorted image in the right triangle area. Here's the code Shaders Vertex shader attribute vec4 a position attribute vec4 a color attribute vec2 a texCoord0 uniform mat4 u projTrans varying vec4 v color varying vec2 v texCoords void main() v color vec4(1, 1, 1, 1) v texCoords a texCoord0 gl Position u projTrans a position Fragment shader ifdef GL ES precision mediump float endif varying vec4 v color varying vec2 v texCoords uniform sampler2D u texture void main() gl FragColor v color texture2D(u texture, v texCoords) vec4(0, 0, 0, 0.50) Mesh Mesh m new Mesh(true, 5, 0, new VertexAttribute(Usage.Position, 2, "a position"), x,y new VertexAttribute(Usage.TextureCoordinates,2,"a texCoord" 0)) u,v m.setVertices(new float 20f, 360f, 0f,0f, upper left 60f, 20f, 0f, 1f, lower left 180f,20f,1f,1f, lower right 220f, 360f, 1f, 0f, upper right 20f, 360f, 0f, 0f ) upper left (closure) Render Gdx.gl.glEnable(GL20.GL BLEND) Gdx.gl.glBlendFunc(GL20.GL SRC ALPHA, GL20.GL ONE MINUS SRC ALPHA) shaderProgram mesh.begin() shaderProgram mesh.setUniformMatrix("u projTrans", camera.combined) texture.bind() m.render(shaderProgram mesh, GL20.GL TRIANGLE STRIP, 0, 5) shaderProgram mesh.end() |
15 | Why do I get glitchy graphics when drawing scene with scene2D? I'm trying to display a simple text for a menu UI using scene2D, but for some reason nothing is being displayed here. The screen displays pure black. public class ScreenMenu implements Screen MyGame myGame SpriteBatch batch Stage stage Label labelNewGame, labelContinue, labelCredits public ScreenMenu(MyGame myGame) this.myGame myGame Override public void show() init() BitmapFont font initFont() initLabels(font) initStage() private void init() batch new SpriteBatch() private BitmapFont initFont() return new FontLoader().getMichroma() private void initLabels(BitmapFont font) Label.LabelStyle labelStyle new Label.LabelStyle(font, Color.WHITE) labelNewGame new Label("New Game", labelStyle) labelContinue new Label("Continue", labelStyle) labelCredits new Label("Credits", labelStyle) private void initStage() stage new Stage(new ScreenViewport()) Gdx.input.setInputProcessor(stage) stage.addActor(labelNewGame) Override public void render(float delta) GlHelper.clearScreen() stage.act(delta) stage.draw() Override public void resize(int width, int height) stage.getViewport().update(width, height, true) Override public void pause() Override public void resume() Override public void hide() dispose() Override public void dispose() myGame.dispose() batch.dispose() stage.dispose() The following class contains the clearScreen function. If I don't run it, the entire screen becomes super glitchy, but I can see the New Game text. public class GlHelper public static void clearScreen() Gdx.gl.glClearColor(0, 0, 0, 0) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) public static void clearScreen(float red, float green, float blue, float alpha) Gdx.gl.glClearColor(red, green, blue, alpha) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) |
15 | Why won't my sprite move with this code? When I ran the android application, The sprite image will not move when I press the input keys. I followed a tutorial based on input keys and wish to know what's wrong. Can anyone see what's wrong? Not sure if its my android emulator. EDIT website where the tutorial is located http www.gamefromscratch.com post 2013 10 15 LibGDX Tutorial 4 Handling the mouse and keyboard.aspx import com.badlogic.gdx.ApplicationListener import com.badlogic.gdx.Gdx import com.badlogic.gdx.Input import com.badlogic.gdx.graphics.GL20 import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.graphics.g2d.Animation import com.badlogic.gdx.graphics.g2d.Sprite import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.graphics.g2d.TextureAtlas public class otherSide implements ApplicationListener private SpriteBatch batch private TextureAtlas textureAtlas private Texture texture private Sprite sprite private Animation animation private float elapsedTime 0 Override public void create() float h Gdx.graphics.getHeight() float w Gdx.graphics.getWidth() batch new SpriteBatch() texture new Texture(Gdx.files.internal("image.png")) sprite new Sprite(texture) sprite.setPosition(w 2 sprite.getWidth() 2, h 2 sprite.getHeight() 2) textureAtlas new TextureAtlas(Gdx.files.internal("spritesheet.atlas")) animation new Animation(1 15f, textureAtlas.getRegions()) Override public void resize(int width, int height) Override public void render() Gdx.gl.glClearColor(1, 1, 1, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) if(Gdx.input.isKeyPressed(Input.Keys.LEFT)) if(Gdx.input.isKeyPressed(Input.Keys.CONTROL LEFT)) sprite.translateX( 1f) else sprite.translateX( 10.0f) if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)) if(Gdx.input.isKeyPressed(Input.Keys.CONTROL RIGHT)) sprite.translateX(1f) else sprite.translateX(10.0f) batch.begin() elapsedTime Gdx.graphics.getDeltaTime() batch.draw(animation.getKeyFrame(elapsedTime, true), 0, 0) sprite.draw(batch) batch.end() Override public void pause() Override public void resume() Override public void dispose() batch.dispose() texture.dispose() |
15 | Get device rotation in Y axis So using LibGDX accelerometer methods, I'm able to get the rotation of the device in the X and Z axes in degrees with this code Override public void render(float delta) float accX Gdx.input.getAccelerometerX(), accY Gdx.input.getAccelerometerY(), accZ Gdx.input.getAccelerometerZ() float moduleValue (float) Math.sqrt(accX accX accY accY accZ accZ) Here I do the gravity compensation accX moduleValue accY moduleValue accZ moduleValue float xRotation (float) Math.atan2(accY, accZ) MathUtils.radiansToDegrees, zRotation (float) Math.atan2(accY, accX) MathUtils.radiansToDegrees However, get the rotation in the Y axis is not that easy to obtain, and if I try to get it by this way, it returns erroneus values. |
15 | Get next tile by given angle I am new to game development, and I have been building some game with LibGDX engine. The following function might make you feel bad The function I am going to show, is accepting the current rotation index of my player (player has 4 rotations, north, south, west, east). The function will return how much to jump in X to get the next tile according to his direction (angle) and the selected move (you can only select left, right or forward per turn) public int getIncrementXForRotation(int rotationIndex) switch(this) case MOVE FORWARD switch(rotationIndex) case Face.EAST return 1 case Face.SOUTH return 0 case Face.WEST return 1 case Face.NORTH return 0 case MOVE BACKWARD switch(rotationIndex) case Face.EAST return 1 case Face.SOUTH return 0 case Face.WEST return 1 case Face.NORTH return 0 case MOVE LEFT switch (rotationIndex) case Face.EAST return 0 case Face.SOUTH return 1 case Face.WEST return 0 case Face.NORTH return 1 case MOVE RIGHT switch (rotationIndex) case Face.EAST return 0 case Face.SOUTH return 1 case Face.WEST return 0 case Face.NORTH return 1 case TURN LEFT switch(rotationIndex) case Face.EAST case Face.SOUTH return 1 case Face.WEST case Face.NORTH return 1 case TURN RIGHT switch(rotationIndex) case Face.NORTH case Face.EAST return 1 case Face.WEST case Face.SOUTH return 1 return 0 Same function for Y. Now I looked at this, and i thought to myself.. north can be an 0, and east can be 90, and south can be 180 and west can be 270, am I right? So there is a way to mathematically do these coordinate increment according to the angle, isn't there? The reason I classified my player angles by enums is because each direction is an image. |
15 | Disposing objects when changing screens I'm making my first game with LibGDX and Box2D, and I've realized that the memory used increases when I change screens. It starts from 150MB and progressively reaches 850. How should I deal with this? It does not seem to be a memory leak, memory is constant throughout the level, and I'm using an AssetManager to dispose everything needed. The problem is when switching screens, since objects remain in memory. What is the best practice in this case? Should I have a method in each class that sets every object to null before the screen is disposed? Another problem might be that I have a static class for all my constants (this was the method proposed in the Udacity course), could this be an issue? Another idea described here is initializing all screens in the beginning and using them throughout the game. Though I'm not sure this could be done in my game now. Is this good practice? I tried profiling a bit although it's the first time, here are some results. The sudden 'hops' are when switching screens. |
15 | How can I create a button with an image in libGDX? I am new to LibGDX. I am trying to develop a game for Android (so it will support different screen sizes), but I don't know how to put a button with an image. I tried ImageButton but I can't resize it. I have put TextButtons in my app and it works and resizes fine too. Any suggestions ? |
15 | Google Play Services Message Handling with Libgdx I'm looking for some idea of how to handle Reliable Messages in Google Play Services with libGDX. So far I've been using it like this I was waiting for message with OnRealTimeMessageReceivedListener, setting an outside byte array to the message received, changing a flag that suggests that new message arrived to true, getting that message in my libGDX class using methods from interface, setting newMessage flag again to false, handling message, and so again waiting for new one private OnRealTimeMessageReceivedListener mMessageRecievedHandler new OnRealTimeMessageReceivedListener() Override public void onRealTimeMessageReceived( NonNull RealTimeMessage realTimeMessage) Handle received message here byte message realTimeMessage.getMessageData() byte tbye message ByteBuffer bb ByteBuffer.wrap(tbye) if(bb.getFloat() 1884) Log.d("MESSAGETEST", "Message received in anL " debugIntL) debugIntL byteArray message newMessageFlag true Override public boolean getNewMessageFlag() return newMessageFlag Override public byte getMessage() newMessageFlag false return byteArray Libgdx class Override public void render (float delta) ... checkForNewMessage() ... private void checkForNewMessage() if(game.customHandler.getNewMessageFlag()) handleMessage() handling message here private void handleMessage() byte message game.customHandler.getMessage() ByteBuffer bb ByteBuffer.wrap(message) float typeOfMessage bb.getFloat() if(typeOfMessage NEW UNIT MESSAGE) Gdx.app.log("MESSAGETEST", "Message received in gdx " debugInt) debugInt ... But the result is, when uncommenting the code in OnRealTimeMessageReceivedListener and adding similar log to my handleMessage() that some messages are skipped between receiving it in listener and checking for new in my libGDX class, I don't know why, maybe because some render calls take longer to do everything inside and it skips through one check call when there's significant number of those in small amount of time On the image you can see that first log is from OnRealTimeMessageReceivedListener, which receives every message, but the second one is from handleMessage, and at 251 there it wasn't called, so handleMessage just skipped this message and went to the next one. So here's my question, what's good way to handle those messages so that I won't skip any? |
15 | What is the difference between getWidth and getBackBufferWidth in LibGDX? In regards to gdx.graphics, what is the difference between using getWidth and getHeight, and using getBackBufferWidth and getBackBufferHeight? I am learning LibGDX and Java. I programmed formerly in pygame. To my knowledge, getBackBuffer means the width and height of the actual window. Is that true? |
15 | Confusion with Libgdx UI I've started with Libgdx and am currently stumbling about trying to understand how to set up the interface. I have generated the base projects in Eclipse ( lt proj name , lt proj name android, lt proj name desktop, lt proj name html), and can get the program to display a simple background, play a looping sound file, and draw a tank. I have been having some problems implementing the UI though. I want to make a collapsible interface bar at the bottom of the screen that would contain buttons for movement, and selecting weapons. I'm confused since there appears to be several ways of doing this and the documentation (or tutorials explaining it) tend to be obsolete. How would one go about this? Use a stage for the bar and actors for the widgets? I'm a little lost on this. |
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 | 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 Box2D TiledMap render is not smooth I'm building simple side scroller game. My player (square) move fast and it interacts with other world objects. Problem is when my player is moving it seems that all world is rendering somehow strange (for example box2d objects are not rendering smooth). When player is not moving everything is ok. Here pic when player is moving and here when my player stands still Here I add my code private OrthogonalTiledMapRenderer renderer mapLoader new TmxMapLoader() map mapLoader.load("level1.tmx") renderer new OrthogonalTiledMapRenderer(map, DIV) gamecam.position.set((gamePort.getWorldWidth() 2), (gamePort.getWorldHeight() 2), 0) public void update(float dt) world.step(1 60f, 6, 2) if(playerAndGroundTest) player.update(dt) float x gamecam.position.x gamecam.viewportWidth gamecam.zoom DIV float y gamecam.position.y gamecam.viewportHeight gamecam.zoom DIV float width gamecam.viewportWidth gamecam.zoom 2 DIV float height gamecam.viewportHeight gamecam.zoom 2 DIV renderer.setView(gamecam.combined, x, y, width, height) gamecam.position.set(new Vector2(player.getBody().getPosition().x, (gamePort.getWorldHeight() 2)), 0) gamecam.update() Override public void render(float delta) update(delta) Gdx.gl.glClearColor(0.4f, 0.4f, 0.4f, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) renderer.render() b2dr.render(world, gamecam.combined) here's Player update function public void update(float dt) body.setLinearVelocity(200 dt, body.getLinearVelocity().y) |
15 | libgdx scene2d DelayAction and SequenceAction I'm trying to get the delay action in scene2d working correctly. I have multiple image objects which I store in an array and I have managed to get them all displaying, scaling and moving correctly. I can't however seem to get them moving independently using the delay action. I have tried using the sequence action and that isn t working either I m trying to create transition effects using little squares that move off the screen. I have included a sample of the code im using below for (i 0 i lt scaleActions.length i ) ScaleByAction scaleAction new ScaleByAction() scaleAction.setAmount( 0.1f) scaleAction.setDuration(0.5f) scaleActions i scaleAction float increase 0 for (i 0 i lt delayActions.length i ) DelayAction delayAction new DelayAction() delayAction.setDuration(0.05f increase) increase 0.1 delayActions i delayAction for (i 0 i lt boxArray.length i ) SequenceAction sequence new SequenceAction(scaleActions i ,moveActions i ,delayActions i ) boxArray i .setOrigin(boxW 2, boxH 2) boxArray i .addAction(sequence) boxArray i .addAction(sequenceActions i ) boxArray i .addAction(scaleActions i ) boxArray i .addAction(moveActions i ) boxArray i .addAction(delayActions i ) public void addToStage() for (i 0 i lt boxArray.length i ) stage.addActor(boxArray i ) Everything seems to be moving and scaling at the same time, the delay doesn t look like it is even working. Hope you guys can help point out what I'm doing wrong. |
15 | libGdx Window .pack() not working I'm trying to make a window, then use the pack method to get the right size, but the window maximizes instead. Here's my code private Table buildOptionsWindowLayer() winOptions new Window("Options", skinLibgdx) (...) building some widgets Gdx.app.log(TAG, "pref width is " winOptions.getPrefWidth()) displays "pref width is 247.0" winOptions.pack() move the window winOptions.setPosition(Constants.VIEWPORT GUI HEIGHT winOptions.getWidth() 50, 50) return winOptions The window ends up with a width of 800.0f. Why? What it is supposed to render What it does render |
15 | How 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 | Virtual game dimensions how to implement? I'm creating a fighting game in LibGDX with a static board, camera moves only right lt left. There are 5 screen aspect ratios in Android and Apple so I have created 5 different background graphics 2560x1440 16 9 2560x1920 4 3 2700x1800 3 2 3000x1800 5 3 3200x2800 8 5 Each background width is multiplied by 1.5, cause I need to zoom out the game when players are too far away from each other, so for example 16 9 isn't 2560x1440 but 3840x1440. (I just realised that I should expand the height too LOL, gamedev is a fantastic place). When I load the background I check the screen size and scale the background to fit. The thing I need to implement is Virtual Coordinates which are the same for each device. Let's get the screen below I need to set virtual board dimensions to for example 2000x1000 units meters whatever. When the server sends a message Spawn a bomb on (1000,1000), left device spawns it at x 512, right device at x 960 (both on the half). I think working on pixels is a bad idea, cause I would need to calculate things with each move, jump etc. If someone could help me, how should I achieve this, I would be grateful for pointing me a way. Thanks! |
15 | how can I split the screen into two screens and make Gdx.input.setInputProcessor () accept two processors? I want to draw in the first screen portion, and manipulate the buttons in the second part. This is what I tried if (mouse.x lt 600) Gdx.input.setInputProcessor (new InputProcessor () Override public boolean touchup (int arg0, int arg1, int arg2, int arg3) return false . . . . . if (mouse.x gt 600) Gdx.input.setInputProcessor (stage) the problem is that I have the ability to go from the first part to the second but I'm not allowed to go from the second to the first, it blocks the mouse coordinates in x 600 This is what I tried |
15 | How do I find the shape of Tiled's circles or ellipses in libGDX? I created a level in the 'Tiled Map Editor' and loaded it into my libGDX game. I can easily transform almost all objects into Box2D objects (although this problem is not Box2D specific), but I have trouble with ellipses. Tiled seems to only create ellipse objects, without a special case for circles. I'd be happy with just circles if they existed in Tiled. However, even the EllipseMapObject I load in libGDX only has an x,y position. I don't see any information about area or vertices. Did I miss something? How can I create circle or ellipse objects in Tiled and load them into libGDX with right dimensions? Tiled version 0.10.1, libGDX version 1.4.1 |
15 | Movement for Box2D Bodies I'm having trouble wrapping my head around something that should be relatively simple. I'm making a breakout clone using LibGDX and Box2D. I'm also using the Ashley ECS. For movement with bodies, I have two components a BodyComponent (BC) which contains a reference to the Body that was created for the owning entity, and a PhysicsComponent (PC) which contains a velocity vector. What I'm currently doing is manipulating the PC's velocity vector when providing input, then setting the BC's body's linear velocity to the velocity vector in the PC. This allows my bodies to move how I want them to move but there are two issues Bodies have no maximum velocity If the pad bumps into a static body, it should bounce. However it quickly snaps back to its original position because the PC's velocity is unaffected when bodies collides. How can I manipulate bodies and make them move and interact with other bodies without the need to use another component for velocity? |
15 | LibGDX managing zoom Zooming an OrtographicCamera effectively changes the amount of world units that can be shown in the camera window. Should thus the camera viewport dimensions be correspondingly updated upon zoom? For example, ... camera.zoom 0.01 camera.viewportWidth camera.zoom camera.viewportHeight camera.zoom camera.update() ... EDIT Here's the full code private float CAMERA WIDTH 50 private float CAMERA HEIGHT 50 camera new OrthographicCamera(CAMERA WIDTH,CAMERA HEIGHT) camera.position.set(CAMERA WIDTH 2, CAMERA HEIGHT 2, 0) camera.update() prints 1.0, 50.0, 50.0 gt OK System.out.println(camera.zoom ", " camera.viewportWidth ", " camera.viewportHeight) ... camera.zoom 0.1 camera.update() prints 1.1, 50.0, 50.0 gt NOT Ok System.out.println(camera.zoom ", " camera.viewportWidth ", " camera.viewportHeight) ... Executive summary if you need the zoomed camera viewportWidth and viewportHeight, maintain them as separate variables. They must not be changed in the camera otherwise zoom calculation messes up (obviously, since the zoom is relative to the values the camera was created with, so the original values are always needed). If you absolutely want or need to reassign camera.viewportWidth and camera.viewportHeight, you have to reset camera.zoom to 1 immediately after. |
15 | LibGDX destroy object when not used I am developing a game where objects move in the screen. My object is instantiated in Y 0 and I want to destroy this object when it goes under the screen Height. So if (positionY ScreenHeight) I have to destroy this object to clean my game and prevent "lag". How to do this? I have a dispose method (this.dispose) but it cause the dispose of the app and I want destroy only the object. Thanks in advance |
15 | When should one use LibGDX's FrameBuffer and when SpriteCache? In my game I have some graphics that I want to draw once and only redraw whenever something is changed by the player. Now, I'm wondering, whether I should use the FrameBuffer or the SpriteCache class. I know that a framebuffer is much more general concept and also works for 3D, while a SpriteCache is only for 2D. However it seems to me that they would both make sense in my use case, so I'm wondering.. What are the differences, drawbacks and advantages of using one over the other? |
15 | Only render calculate the chunks in frustum! I have a 2D world in form of a Block Array that holds all the blocks of the world. Every block has it's own Box2D Body (I want a "minecraft" like 2D world for this project). Naturally I don't want to calculate all the box2D bodies at the same time and I don't want to render what's not on screen neither (SpriteBatch). So I divided my huge world into "Chunks". They are all of the same width and height. Now I'm a bit stunned though. Each chunk starts at (0,0) which is the lower left corner of the chunk. Now in my player class I do the following (if the player has moved) public void calculateChunksToRender() for(int x (int) this.getPosition().x Chunk.chunkWidth 2 (Chunk.chunkWidth 4) x gt 0 amp amp x lt game.getMap().getWidth() Chunk.chunkWidth amp amp x lt (int) this.getPosition().x Chunk.chunkWidth x ) if(x Chunk.chunkWidth 0) Vector2 chunkPosition new Vector2(x, 128) System.out.println(chunkPosition) chunksToRender.put(chunkPosition, game.getChunkMap().get(chunkPosition)) As the start point of the x coordinate in the chunk is on the left side, I go 1 3 4 chunks to left and render it, if still visible. Why 1 3 4? Because that way when I'm 3 4 to the right I don't see the left chunk anymore, so I don't need to render it. For the right chunk I do the same, but only with Chunkwidth... I guess it's pretty self explanatory though. Obviously this is just the X dimension and I'm not sure if there isn't a far better way to do this. Why? Because, well, right now I have 3 chunks to render, but basically I have a 8 neighbourhood around the one chunk the player is currently on in. I fear that I will have to render calculate (the physics for) far too many bodies the way I'm doing it right now. Currently I have 12k bodies in memory at any given time and around 45 60fps. But that's just 3 chunks! Each block has its sprite attached to it through the box2D body (userData), maybe I should separate them and separate rendering physics calculation as well? Not sure though, because if a player jumps to another chunk I want him to collide with the blocks there immediately not after a delay (so he is stuck in the middle). I also tried to calculate the nearest chunk (just go left on the x axis and down on the y axis until you find a chunk) and calculate the surrounding ones, but that's much more of a performance hit (logically) Any ideas optimizations? Kindest regards, Ohuro |
15 | Why not just create very high resolution graphics and use them on all screens? I'm creating a game with pretty basic graphics (numbers, blocks, words, and a few nice design elements for the logo and such). My question is can I create everything in a very high resolution say 2048x2048 and just let libGDX scale these depending on the screen size? The reason I ask is because I've seen questions that ask about creating a copy of the assets in various resolutions. What's wrong with just using one asset set that's a very high resolution on all devices? |
15 | Animation reset in libgdx i have an issue that i hope it's easy to resolve. I'm playing various animations in my libgdx created game. For a particular animation, i need that to play in loop mode but only if a particular condition is true. Simple this far. What i need is to "reset" the animation (i mean restart from sprite n 1) when the condition become true again after the animation stopped. I know that i can simply dispose the actual animation and create another one every time the condition is true, but this seems a complicated way to resolve this.. How do i change the value of the index used by that animation? Is it possible? Do i have to create a class that extends the Animation class from libgdx library? |
15 | 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 Resizing Textures for Different Platforms I'm using viewports to handle different screen resolutions to support multiple platforms (desktop, android, etc.) in my libgdx powered game. I made all image assets for Full HD resolution and thought it will be easy to scale down them for lower screen resolutions. The thing is when I resize them (scale up or down) they are pixelated very badly. I tried to use TextureFilter.Linear and TextureFilter.MipMapLinearLinear (enabled mipmaps). The result is still not satisfying. Then I came across this post made by an administrator on libgdx forums http badlogicgames.com forum viewtopic.php?p 107267 p107267 He says it scales the texture 60 times a second. 1 ) Does it really gets scaled 60 times a second? If so why isn't it scaled only one time at program start? How can i do this? 2 ) Since all games which support multiple platforms somehow need to achieve the rescaling, what is the best way to do it? My image editor program can resize it without pixelating so I think there should be a way. |
15 | Sprite draw order in libgdx From other frameworks I know methods for easy ordering sprites within a spritebatch (to determine if a sprite has to be drawn in front or behind another sprite). For example in MonoGame XNA this is called Sprite.depth or Pyglet has its OrderedGroups. But I cannot find anything like that in libgdx. I've read that libgdx' scene2d has something like that but I don't want to use that as I use a entity system (ashley) and want to keep rendering separeted from the other logic. What is the appropriate way to set the draw order of libgdx sprites? |
15 | Sprite wrong position on screen I want to render one sprite on top of another one. I create both sprites using same coordinates and while debuging I can see that they have same position but still one is being rendered beneath another and slightly to the left. Could somebody tell me what am I doing wrong? here is my code where I create sprites Sprite sprite1 new Sprite(new Texture("1.png")) sprite1.setScale(1 PPM) Sprite sprite2 new Sprite(new TextureRegion(...)) sprite2.setScale(1 PPM) sprite1.setPosition(x,y) sprite2.setPosition(x,y) Could it have something to do with scaling? Or maybe the fact that second sprite is created from TextureRegion? |
15 | LibGDX creating actor conformed by other actors I am making my custom actor class, made up by 3 actors(oneProgressBar, one Label and one TextButton), because I will be using this many times, so it's not a good idea to create 3 of that actors when I can create one that can contain them. So I am making my class public class MyActor extends Actor ProgressBar bar Label nameLabel TextButton button public MyActor(String name, Skin skin, float progress) nameLabel new Label(name, skin) button new TextButton("Buy", skin) bar new ProgressBar(0f,5f,progress,false,skin) Override public void act(float delta) super.act(delta) bar.setBounds(getX(), getTop() getHeight() 3f, getWidth(), getHeight() 3f) nameLabel.setBounds(getX(), getY() getHeight() 3f, getWidth(), getHeight() 3f) button.setBounds(getX(), getY(), getWidth(), getHeight() 3f) Override public void draw(Batch batch, float parentAlpha) super.draw(batch, parentAlpha) bar.draw(batch, parentAlpha) nameLabel.draw(batch, parentAlpha) button.draw(batch,parentAlpha) So in my game, I add my actor to the Stage using a table Table table new Table() table.debug() MyActor actor new MyActor("whatever",mySkin,1f) table.add(actor).size(myWidth,myHeight) The actor is drawn in the correct place(I know because of the debug lines), but the 3 actor are drawn in the 0,0 coordinates, what am I doing wrong? do I need to override another method? |
15 | LibGDX draw bullet physics bounding box I am very new to game development and I am trying to debug my 3d collision bounds. Could somebody give me an example on how to draw the collision bounds of an object in libGDX? I assume it has something to do with btIDebugDraw but I can't find any examples on how to draw them. |
15 | How to flip a box2d body when it can't move forward? LibGDX I'm attempting to create a simple enemy for a platformer. It should move forward constantly until it hits something like a wall, and then it should flip and move forward the other direction. How might I accomplish this? |
15 | Libgdx Am I abusing Vector2? Is there a better way to do my position updates and rendering? I'm simulating hair in a game. Currently I have a HairField object, which has a position defined by a Vector2. Each HairField has multiple Hair objects in a list, each with a position defined by a Vector2. Each hair has multiple HairParticle objects in a list, each with a Vector2 position. Like so HairField class Vector2 pos In world coords List lt Hair gt hairs Hair class HairField hairField Vector2 pos Relative to parent HairField List lt HairParticle gt hairParticles public Vector2 getWorldPos() return pos.cpy().add(hairField.getWorldPos()) HairParticle class Hair hair HairParticle parent Vector2 pos Relative to parent HairParticle public Vector2 getWorldPos() return pos.cpy().add(hair.getWorldPos()) My hair physics rendering loop looks like the following for each (Hair h hairField) HairParticle parent null for each (HairParticle p h) if (parent null) continue get position info from each HairParticle's getWorldPos() update p, constraining to certain distance from parent render line from parent gt p You can see that I'm calling a metric buttload of getWorldPos() methods on the particles, all so I can have information for updating rendering the particle. Each of these calls involves multiple Vector2.cpy() calls and some vector math. My question is, am I abusing Vector2's? They make for easy math, but I'm wondering if there's some more primitive (but faster) way I should be doing things. I've heard about transformation matrices, but don't know much about them yet (been reading). Does Libgdx expose some quicker way to be doing this math for updating rendering that I should be using instead? |
15 | Black screen when switching from fullscreen to windowed mode with libgdx I have just started working with libgdx, and have run into my first problem. I have a simple program that switches a desktop application from windowed mode to fullscreen and back again. If I start the program in windowed mode, it initially displays fine. When I toggle to full screen it is also OK. However, when I toggle back to windowed mode the screen goes completely black. The application remains responsive though, and if I toggle again it will go back to fullscreen and display correctly. I am using 64 bit Windows 7 with the IntelliJ IDEA IDE. Any help with working out why it is doing this would be greatly appreciated. A minimal example that displays the issue is shown below public class MyGdxGame extends ApplicationAdapter Override public void create () fullScreen false Override public void render () Gdx.gl.glClearColor(1, 0, 0, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) if (Gdx.input.isKeyPressed(Input.Keys.TAB)) fullScreen !fullScreen DisplayMode currentMode Gdx.graphics.getDesktopDisplayMode() Gdx.graphics.setDisplayMode(currentMode.width, currentMode.height, fullScreen) private boolean fullScreen |
15 | What is the delta value passed to the Screen's render method? The delta value given to the render method in the Screen class is a non constant number. What is it? Where does it come from? Does it differ by screen size? |
15 | Libgdx problem while converting TextureRegion to Pixmap I'm developping a Tile base game where I have to generate transition tiles. To do so, I have a method that generate those tiles from 2 existing one and 1 "filter tile". I use this method to make a pixMap from the region I retrieved from my TextureAtlas. public Pixmap getPixMapFromRegion(TextureRegion region) Texture texture region.getTexture() TextureData data texture.getTextureData() if (!data.isPrepared()) data.prepare() Pixmap pixmap data.consumePixmap() int width region.getRegionWidth() int height region.getRegionHeight() Pixmap px new Pixmap(width, height, Format.RGBA4444) for (int x 0 x lt width x ) for (int y 0 y lt height y ) int colorInt pixmap.getPixel(region.getRegionX() x, region.getRegionY() y) return px Them I apply this method public Pixmap generateMixedTile(TiledMapTileSet tileset, AssetManager assMan,String template, TextureRegion region1, TextureRegion region2) TextureAtlas atlas assMan.get(".. core assets tuiles MergeFilter.atlas") AtlasRegion region atlas.findRegion(template) Pixmap templ getPixMapFromRegion(region) Pixmap img1 getPixMapFromRegion(region1) Pixmap img2 getPixMapFromRegion(region2) Pixmap res newPixmap(region.getRegionWidth(),region.getRegionHeight(),Format.RGBA4444) for (int y 0 y lt templ.getHeight() y ) for (int x 0 x lt templ.getWidth() x ) if(0xFF000000 templ.getPixel(x, y)) res.drawPixel(x, y, img1.getPixel(x, y)) else res.drawPixel(x, y, img2.getPixel(x, y)) return res It seems that after asking again and again for the same texture in the AssetManager, I get a Couldn't load file .. core assets tuiles Water3.png Exception. But this happen after the system success a lot of time to access that same file. So I don't know how I could handle that because I thought that using assetManager and Atlas was the bests practices Any Idea of how to fix that or to do it in another way? |
15 | 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 to move Vector2 along angle? These are my Vector2's that I am using for this function. public Vector2 position new Vector2() public Vector2 velocity new Vector2() public Vector2 movement new Vector2() public Vector2 direction new Vector2() Here is the function that I use to move the position vector along an angle. setLocation() just sets the new location of the image. public void move(float delta, float degrees) position.set(image.getX() image.getWidth() 2, image.getY() image.getHeight() 2) direction.set((float) Math.cos(degrees), (float) Math.sin(degrees)).nor() velocity.set(direction).scl(speed) movement.set(velocity).scl(delta) position.add(movement) setLocation(position.x, position.y) Sets location of image I get a lot of different angles with this, just not the correct angles. How should I change this function to move a Vector2 along an angle using the Vector2 class from com.badlogic.gdx.math.Vector2 within the LibGDX library? I found this answer, but not sure how to implement it. Update I figured out part of the issue. Should convert degrees to radians. However, the angle of 0 degrees is towards the right. Is there any way to fix this? As I shouldn't have to add 90 to degrees in order to have correct heading. New code is below public void move(float delta, float degrees) degrees 90 Set degrees to correct heading, shouldn't have to do this position.set(image.getX() image.getWidth() 2, image.getY() image.getHeight() 2) direction.set(MathUtils.cos(degrees MathUtils.degreesToRadians), MathUtils.sin(degrees MathUtils.degreesToRadians)).nor() velocity.set(direction).scl(speed) movement.set(velocity).scl(delta) position.add(movement) setLocation(position.x, position.y) |
15 | LibGDX Json writes only part of class Hello I've been developing this game for awhile and now trying to implement save data via Json. I've gotten to where when the app is first launched it will write the Json file with the variables I would like the game to save, but it only writes part of the class that I am passing. Here is my implementation Override public void create() batch new SpriteBatch() file Gdx.files.external(" bin save.json") create.setFirstSpawn(true) create.setSpawnX( 7) create.setSpawnY(417) create.setTime(0) create.setMap("cabinMap") if(!file.exists()) Json json new Json() json.setOutputType(JsonWriter.OutputType.json) file.writeString(json.prettyPrint(create), false) if (file.exists()) JsonReader jread new JsonReader() JsonValue base jread.parse(file) SpawnX base.getFloat("SpawnX", 7) SpawnY base.getFloat("SpawnY", 417) map base.getString("map", "cabinMap") time base.getFloat("time", 0) firstSpawn base.getBoolean("firstSpawn", true) if(map "cabinMap") this.setScreen(new cabinMap(this)) if(map "tMap") this.setScreen(new tMap(this)) if(map "lowerTMap") this.setScreen(new lowerTMap(this)) if(map "rightTMap") this.setScreen(new rightTMap(this)) else this.setScreen(new cabinMap(this)) Here is the class that I am passing public class create boolean firstSpawn float SpawnX float SpawnY float time String map public void setFirstSpawn(boolean firstSpawn) this.firstSpawn firstSpawn public void setTime(float time) this.time time public float getTime() return time public void setMap(String map) this.map map public String getMap() return map public boolean isFirstSpawn() return firstSpawn public void setSpawnX(float spawnX) SpawnX spawnX public float getSpawnX() return SpawnX public void setSpawnY(float spawnY) SpawnY spawnY public float getSpawnY() return SpawnY And this is my result "map" "cabinMap", "SpawnX" 7, "SpawnY" 417 As you can see from the output file I am missing 2 values. float time and boolean firstSpawn are missing from the file. I've worked for hours trying to find out why. I have no clue why it omitted part of the code... If anyone knows why that would be very helpful to me. |
15 | libGDX game crashes on Android without any mention of crash in logs No mention of any issue in process logs, an application just turns off during loading assets ( 3 of all assets loaded). It works fine on desktop. Only thing that seems related in global logs is this 09 01 15 15 25.261 824 22928 ? W ActivityManager Force removing ActivityRecord 911979f u0 xxx.xxx.xxx .AndroidLauncher t664 app died, no saved state I suspect there might not be enough of memory, but why there is nothing in logs? I tried limiting JVM memory on PC to 512MB and it runs fine. But I am not entirely sure if this limit covers also native memory. Could that be the reason why it runs with limit set and yet crashes on a mobile device with 2GB memory? |
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 RotateToAction does not directly rotate between 179 and 179 It took me a bit of debugging to realize why I'm having trouble with my rotations and it seems that rather than just moving the 2 degrees between 179 and 179, it prefers to rotate all the way in the other direction, the full 358 degrees. Is there any way to make it go the short way in this case? Code I have so far public void rotateTo(float targetRotation) RotateToAction rotateToAction new RotateToAction() rotateToAction.setRotation(targetRotation) rotateToAction.setDuration(2f) if(Math.abs(this.getRotation() targetRotation) gt 180) failed attempt to force rotation SequenceAction sequenceAction new SequenceAction() RotateToAction rotateToAction2 new RotateToAction() rotateToAction2.setRotation(180) rotateToAction2.setDuration(1f) sequenceAction.addAction(rotateToAction2) sequenceAction.addAction(rotateToAction) this.addAction(sequenceAction) else this.addAction(rotateToAction) |
15 | Box2D rotate and set position to a static body with another origin I try to rotate a static body of a PolygonShape, from another origin, and set the position regarding this new origin. Why ? Because I create bodies from TiledMapEditor object. And origins of objects in this editor are in the left upper corner. Regarding the documentation, I can set origin using the setAsBox method. But then when I set the position, the body is not where it is supposed to be. (an offset is apply between the current position and the expected position) I assume that the origin is used for the rotation, but not the position. How can I set the position from another origin, and rotating from this same origin ? (the upper left corner and not the center of the shape) My attempt val rotation 45f rotation angle (in degree) val shape PolygonShape() shape.setAsBox(rectangle.width 0.5f, half width rectangle.height 0.5f, half height Vector2(0f, rectangle.height), new origin rotation MathUtils.degreesToRadians) angle to radians val bodyDef BodyDef() bodyDef.type BodyDef.BodyType.StaticBody bodyDef.position.set(rectangle.x, rectangle.y) set the position Regards |
15 | Changing the texture in a Sprite I'm a bit new to libGDX. My problem is ,in my code, only if I set the texture in the constructor of the Sprite instance, it will draw anything. My question is shouldn't it be working when I only call setTexture() when rendering? Or is there another way to render while changing the texture? Following code doesn't draw anything. public Sprite getSprite() if (this.sprite null) this.sprite new Sprite() return this.sprite public void render(final float deltaTime, final SpriteBatch batch) this.getSprite().setTexture(this.getCurrentTexture()) this.getSprite() .setPosition(this.getPosition().x, this.getPosition().y) this.getSprite().setRotation(this.getRotation()) this.getSprite().draw(batch) Following is the working code. public Sprite getSprite() if (this.sprite null) this.sprite new Sprite(this.getCurrentTexture()) return this.sprite public void render(final float deltaTime, final SpriteBatch batch) this.getSprite().setTexture(this.getCurrentTexture()) this.getSprite() .setPosition(this.getPosition().x, this.getPosition().y) this.getSprite().setRotation(this.getRotation()) this.getSprite().draw(batch) |
15 | How can I put multiple actors on a Button? I like to have an Button with a Text and some Pictures in it. Is there something out of the box to that ? I mean I would like to add a Table into a button, so I could add anything I need to the table. |
15 | Using 60 frames per second causes the screen to leave a drawn trail of textures, when there is movement I'm trying to implement a frame rate feature, and I have noticed that using 60 frames per second causes the screen to leave a drawn trail of textures, when there is movement. Here's the code I'm using to make the frame rate feature public void render(float deltaT) currentLevel.updateWorld(deltaT) if((fps deltaT) gt 1.0 60.0) fps 0 else return super.render(deltaT) Gdx.gl.glClearColor(103 255f, 69 255f, 117 255f, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT GL20.GL DEPTH BUFFER BIT) currentLevel.updateScreen(deltaT, gameCamera) The currentLevel.updateWorld updates the game's logic. The currentLevel.updateScreen method updates the camera's position, drawn to the screen. |
15 | How can I make a GameScreen? I want to make game level select screen. There are some stages which open, and some that are not. So if you clear a second stage and quit the game for a while, when you come back, you can start at stage 3, 2 or 1 whatever you can click, but not from stage 4 you can't play it without completing stage 3. I want to make something like this, but I have no idea how. What should I use to do it (boolean, database...)? Can you give me some simple code structure? |
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 | Collision detection for an arc of a circle So how do I implement the collision detection for an arc of a circle? Will I have to use the Box 2D collision or can I do it some other way using Rectangle or stuff like that? BTW I hate box2d because I don't understand most of the things in it, so if there is a solution that excludes the box2d, it will be very much appreciated. The yellow arc keeps on rotating over the black circle. How do I implement collision detection in here? |
15 | How can I improve the display of my png files? I develop a mini Android game available from my github (also the release apk file). The game is for kids and you are supposed to catch falling object and get points for that. Now I just created png files for the sprites and added alpha channel in gimp. It looks better, before alpha channel After But I'm not 100 satisfied with the rough edges of the sprites. Am I correct that if I do the alpha channel more exact then the sprites will look even better (without the edges) or is there some other mistake that I make with the sprites? Edit With new background image, it looks like this. Edit 2 I used jamie the monkey now of BSD license which renders better. It seems to be more exact work in GIMP that is needed. Edit 3. Now I am satisfied. Thanks. |
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 | Rendering multiple strings text using SpriteBatch from LibGDx library I am using the LibGDX library to render a 3D model in my Android application. Now, I am stuck, where I want to render multiple dynamic texts on to different 3D boxes located on different coordinates of the screen. I am able to render a single text using SpriteBatch, but I need to render different string values on different boxes. SpriteBatch spriteBatch new SpriteBatch() BitmapFont font new BitmapFont() spriteBatch.maxSpritesInBatch 5 spriteBatch.setProjectionMatrix(camera.combined.cpy().scale(camera.combined.cpy() .getScaleX() 25,camera.combined.cpy().getScaleY() 25, 0.8f)) spriteBatch.begin() font.setColor(1.0f, 0.0f, 0.0f, 1.0f) float xPos 90 int count 0 for (Widget widgets display.getWidgets()) float boxWidth widgets.getBounds().getWidth() float boxHeight widgets.getBounds().getHeight() float boxHeightCenter widgets.getBounds().getCenterY() if(count 0) font.draw(spriteBatch, "Hello" count, xPos, boxHeightCenter 25, boxWidth, 0, true) count else font.draw(spriteBatch, "Hello" count, xPos boxWidth, boxHeightCenter 25, boxWidth, 0, true) xPos xPos boxWidth count spriteBatch.end() The above code renders only one string value. While debugging, the "for" loop is getting traversed, but no positive result is obtained. How do I fix this? |
15 | How can I change the appearance of the mouse cursor in libGDX? How can I change the mouse a cursor to a picture using libGDX? |
15 | Change screen dimensions in libgdx in HTML Can i change the screen dimensions in libGDX in HTML? If I inspect the element (the game) in Chrome and I change canvas width or height it changes the screen dimensions, but I don't know how to do it in the HTML file. I have the default file generated by libGDX. The CSS path to the canvas containing the screen size is embed html table tbody tr td canvas The HTML is lt body gt lt a class "superdev" href "javascript 7B 20window. gwt bookmarklet params 20 3D 20 7B'server url' 3A'http 3A 2F 2Flocalhost 3A9876 2F' 7D 3B 20var 20s 20 3D 20document.createElement('script') 3B 20s.src 20 3D 20'http 3A 2F 2Flocalhost 3A9876 2Fdev mode on.js' 3B 20void(document.getElementsByTagName('head') 5B0 5D.appendChild(s)) 3B 7D" gt amp 8635 lt a gt lt div align "center" id "embed html" gt lt div gt lt script type "text javascript" src "html html.nocache.js" gt lt script gt lt body gt lt script gt function handleMouseDown(evt) evt.preventDefault() evt.stopPropagation() evt.target.style.cursor 'default' function handleMouseUp(evt) evt.preventDefault() evt.stopPropagation() evt.target.style.cursor '' document.getElementById('embed html').addEventListener('mousedown', handleMouseDown, false) document.getElementById('embed html').addEventListener('mouseup', handleMouseUp, false) lt script gt |
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 | LibGDX how to remove PointLight that is attached a destroyed Body I have this code Override public void beginContact(Contact contact) fa contact.getFixtureA() fb contact.getFixtureB() if (fa null fb null) return if (fa.getUserData() null fb.getUserData() null) return final Body toRemove contact.getFixtureA().getBody().getType() BodyDef.BodyType.StaticBody ? contact.getFixtureA().getBody() contact.getFixtureB().getBody() Gdx.app.postRunnable(new Runnable() Override public void run () world.destroyBody(toRemove) ) It removes the FA body, but this body have a pointlight attached. I want to remove this PointLight attached. I have no idea how to do this . |
15 | Vertical Text Bitmap Font Libgdx How can I achieve this kind of rotation or vertical text using Bitmap Font? I already used Matrix but didn't get the result same as above. |
15 | Custom Coloring of Tileset Characters Games like Dwarft Fortress and Dungeon Crawl Stone Soup are drawing their boards using tiles from a tileset image (I think?). I know you can do color keying and replace the background color with transparency or another color, but how are games like these drawing the text characters into different colors? Using the same method? I am trying to find the best way to use a tilesheet to draw ascii graphics and be able to choose what color the text is, and what color the background of the tile is separately. Something similar to what is pictured here. |
15 | How to properly calculate y position when drawing from .fnt bitmap font? I want to render text to bitmap to use it later as a decal texture. I've read through libGDX fonts drawing code and came up with this private void writeTextToPixmap(Pixmap destPixmap, Pixmap fontPixmap, BitmapFont.BitmapFontData fontData, int startX, int startY, String text) int cursor startX char chars text.toCharArray() for(int i 0 i lt chars.length i ) BitmapFont.Glyph glyph fontData.getGlyph(chars i ) destPixmap.drawPixmap(fontPixmap, glyph.srcX, glyph.srcY, glyph.width, glyph.height, cursor glyph.xoffset, startY glyph.yoffset, glyph.width, glyph.height) cursor glyph.xadvance The font was generated with Hiero using default settings. But the result does not look as expected http i.imgur.com T7Isg2R.png Usage Pixmap pixmap new Pixmap(1024, 1024, Pixmap.Format.RGBA8888) BitmapFont.BitmapFontData fontData new BitmapFont.BitmapFontData(Gdx.files.internal("data couriernew.fnt"), false) Pixmap fontPixmap new Pixmap(Gdx.files.internal("data couriernew.png")) writeTextToPixmap(pixmap, fontPixmap, fontData, 300, 400, "ga") |
15 | How to draw smooth circle in Libgdx I am trying to draw an circle to Libgdx which is created from Image not ShapeRenderer. But when I try to draw image to SpriteBatch it does not draw smoothly. I checked the image resolution and Image Dimension is 1673x1673 and Sprite Size is 80x80. This is my GameState code Override public void render(float delta) update(delta) SpriteBatch sb game.batch Color bg ThemeFactory.getInstance().getTheme().backgroundColor Gdx.gl.glClearColor(bg.r, bg.g, bg.b, bg.a) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) sb.setProjectionMatrix(camera.combined) sb.begin() for(int i 0 i lt elements.size() i ) if(!(elements.get(i) instanceof Arrow)) elements.get(i).render(sb) HERE IS DRAWING HAPPENING sb.end() barriers.render(sb) renderHud() My circle constructor and rendering code is below. public Circle(Texture texture, Size size, Vector3 position) mSprite new Sprite(texture) mSprite.setSize(size.width, size.height) 80x80 mSprite.setPosition(position.x, position.y) mSprite.setOriginCenter() Override public void render(SpriteBatch sb) mSprite.draw(sb) I tried TextureFilters Nearest Nearest and Linear Linear but nothing has changed. And also increased samples for desktop and android applications, nothing has changed too. |
15 | What causes undefined geometry to be drawn? I am currently using the polygonSpriteBatch of libgdx to draw triangles, rectangles and a concave polygon as border. After adding the concave polygon for the colored borders everything seems to break and random geometry appears (sometimes even with a gradient). Some Examples Here you can see on the left everything looks good and after drawing the additional rectangle with its border and removing the other borders you can still see some weird red regions. This is even more extreme. On the left part of the concave polygon is drawn with a different color, and after it despawns (on the right) there is still part of it left and other triangles not created by me are drawn. I am quite confident that all convex polygons are defined in counter clockwise ordering. In the past I had trouble with providing the correct TextureRegion and it still doesn't feel like my current implementation is how it should be, but it worked for simple rectangles and triangles. Currently I have a (3px) (3px) Region and all polygon vertices are between (0f,0f) and (3f,3f). Because I define all triangles of the polygons myself the short array given to the PolygonRegion for a rectangle looks like this (0, 1, 2, 3, 4, 5) and the corresponding Vector2 polygon array like this ((0.0, 3.0), (0.0, 0.0), (3.0, 0.0), (0.0, 3.0), (3.0, 0.0), (3.0, 3.0)) I experienced even more artifacts when executing this on android and for some reason drawing a small rectangle for each vertice (for debugging) fixed some of the artifacts above. This is quite a complex problem but I hope somebody knows what could cause such a behaviour. |
15 | Units, Layers, and Isometric Ordering I'm currently using LibGDX and Tiled map editor to render isometric maps. I'm having a two related difficulties. The first issue is, when do I render units that will end up changing position often and to which layer? At first I thought that I would render units with a wall layer so that walls behind of and in front of the unit are drawn correctly. However, the problem with this is that if a unit (i.e. a character) steps in front of say an object in some sort of top level decoration layer, part of that object will be drawn on top of the unit. The second issue is how to deal with layers that have static objects that units will often be stepping in front of or behind. Let's say you have a decoration layer where you will place trees. The problem with this layer is that depending on where some objects are placed in the layer, they will overlap inconsistently. For example, the following I know this is related to painter's algorithm, but I'm using LibGDX's tile map renderer so the extent to which I have control over drawing the map is rendering different layers at a time and switching out cells tiles in a layer. |
15 | How do I derive an appropriate acceleration value for my game? I am creating a Flappy Bird clone from this tutorial. I have a question about acceleration in libgdx. The author assigned the bird a constant acceleration vector in the constructor of the bird acceleration new Vector2(0, 460) and later updated the velocity vector from the accleration vector with velocity.add(acceleration.cpy().scl(delta)) I understand generally why acceleration is constant like the author mentioned, acceleration due to gravity is 9.81m s 2, meaning that the speed of an object falling will increase by 9.81m s every second. It seems the author somehow got from 9.81 real world value to 460 in the actual code. How does one go about deriving this value? Is this a standard derivation or something the author just made up? |
15 | Box2D meters and pixels I am confused about pixels and meters in Box2D. I know that Box2D work only in mters so I need SCALING FACTOR. How big I need it? For example I want that from my mouse coordinates position X and Y for example(1527, 30) throw an Box2D object how I need to do that? if my scaling factor is private final static float PPM 1 100f so my x 152,7, y 3meters Here is my code private void setBox2DFigures() world new World(new Vector2(0, 9.81f), true) rend new Box2DDebugRenderer() cam new OrthographicCamera() Camera body new BodyDef() bodyPhysics new FixtureDef() CircleShape c new CircleShape() body.type BodyType.DynamicBody c new CircleShape() c.setRadius(20 PPM) c.setPosition(new Vector2(Gdx.input.getX() PPM, Gdx.input.getY() PPM)) bodyPhysics.shape c world.createBody(body).createFixture(bodyPhysics) and here in a draw method I want to coin position set to my mouse position public void draw() c.setPosition(new Vector2(Gdx.input.getX() PPM, Gdx.input.getY() PPM)) mouse coordinates PPM rend.render(world, cam.combined) But I don't see anything in my screen. Whats wrong? How I need to choose My scaling factor(PPM)? here's my main public class DesktopLauncher public static void main (String arg) LwjglApplicationConfiguration cfg new LwjglApplicationConfiguration() cfg.title "Catch Me!" cfg.width 1800 1800 cfg.height 900 900 new LwjglApplication(new Game(), cfg) |
15 | For loop only checking the last object Hi I am using a for loop to check and see if my players character is colliding with a collision object in the game. But for some reason it only checks the last Rectangle of the list. private void collisionDetection() for(Rectangle rectangle colrect) Rectangle rect2 new Rectangle(posX, posY, 64, 64) if (rectangle.overlaps(rect2)) m.setTileCollision(true) else m.setTileCollision(false) Why and how is this happening? I gave up on looking for an answer so I'm here. I want to check all of the Rectangles in the list not the last... I even for looped text through Bitmap font to see the positions and set text at all Rectangles and that works properly, but this doesn't. Another solution perhaps is in order? |
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 | (Tiled) Background stops being rendered in libGDX I'm using Tiled and I created my background as an image in a Tile Layer. When I load the map in LibGDX, it shows fine. However when the camera moves, the whole background dissapears. The problem is solved if I add the background as an Image Layer. Any idea what's causing the problem in the Tile Layer? |
15 | Move Sprite in constant speed on squircle I'm creating a game and i need to move a sprite on squircle path. https en.wikipedia.org wiki Squircle i created the path using the equation angle Gdx.graphics.getDeltaTime() speed float x (float) (R Math.pow(Math.abs(MathUtils.cos(angle)),1 10f) sgn(MathUtils.cos(angle))) a float y (float) (R Math.pow(Math.abs(MathUtils.sin(angle)),1 10f) sgn(MathUtils.sin(angle))) b sprite.setPosition(x,y) the result is My question is how to make the sprite move in a constant speed Edit i used the formula found on Wikipedia |
15 | How do I dynamically set a WheelJoint's anchor points? I've created a car in RUBE and imported it into my game. The game has a tuning menu, allowing the ride height of the car to be adjusted with a slider. I can't work out how to change the position of the WheelJoint relative to the car body. The result I'm looking for is as if I had changed the anchorA Y value in RUBE. I thought this would be equivalent, but it isn't car.rearWheelJoint.getAnchorA().set(xvalue,yvalue) I've tried instead creating a whole new jointdef WheelJointDef d new WheelJointDef() d.initialize(car.rearWheelJoint.getBodyA(), car.rearWheelJoint.getBodyB(), car.rearWheelJoint.getAnchorA().add(0,(val 100) 0.01f), car.rearWheelJoint.getAnchorB()) car.rearWheelJoint (WheelJoint) game.world.createJoint(d) ...but I think this is messing up the pointer to the wheel joint. How can I do this? |
15 | Intersecting Triangle and BoundingBox in 3D environment I am trying to check if a triangle is intersecting a BoundingBox in a 3D space with libgdx, but I am unable to find anything that can help me with that. I tried using a Plane but it is not precise enough and I would like to avoid using Bullet. Is there any existing code that I can use to deal with this ? |
15 | Using a vector to measure an angle relative to the screen camera My game is supposed to have an object that changes it sprite depending on which way the mouse faces. programming this has become a challenge, because I want to calculate the angle relative to the center of the screen using the X axis. To explain what I mean, pretend that under a sprite in the center of a screen is a protractor. I want to measure the angle that's formed between the cursor and the center. If I use the X axis as a base, I should get an angle between 180 and 180 . How would I achieve this? I've tried vector.angle(reference vector), but that doesn't seem to give the desired result. |
15 | Clearing a libGDX pixmap Is there a way to clear a libGDX Pixmap? Or is the only way to dispose it and create a brand new Pixmap? |
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 | Gdx.input.setInputProcessor(stage) doesn't work I have an image and I want to make clickable this image. I have already done this a lot of times, but this time doesn't work. Probably because the image is from a class which extends Image public class BitmapFontGenerale extends Image BitmapFont bitmapFont String scritta private float x private float y public BitmapFontGenerale(BitmapFont bitmapFont1, String string, float scale) bitmapFont bitmapFont1 bitmapFont.setColor(Color.BLACK) bitmapFont.getData().setScale(scale) scritta string Override public void draw(Batch batch, float parentAlpha) bitmapFont.draw(batch,scritta,x,y) public void setX(float x) this.x x public void setY(float y) this.y y public float getX() return x public float getY() return y This is the code which I used to set the input image.addListener(new ClickListener() Override public void clicked (InputEvent event, float x, float y) Gdx.app.log("CLICKED ", "CLICKED") ) stage.add(image) Gdx.input.setInputProcessor(stage) This code works if image is from Image class and not if it's from a class which extends Image. Note I need to extend Image class. What's the problem? |
15 | How to move Stage in LibGDX? How to move Stage? I am looking for an example stage.draw(x,y) ??? Thanks you |
15 | How to smoothly display opponents in realtime multiplayer game I'm implementing a small scale multiplayer racing game. As of right now, the client sends updates to the opponents on a fixed interval (or as fast as possible), containing location on the map etc. Each client will then reposition that opponent on that location. Obviously, this will not run smoothly due to network lag. The vehicles will jump between each location. One solution for this would be to include the speed and direction with each update package, and then keep the vehicle running as that until next update, and then animate a movement to the new position. Repeat. This only works if the player drives predictably, e.g not reversing after update etc. It is not important that the sync is exact, but should be pretty close to the reality location wise. How to smoothly show opponents in a realtime multiplayer game? |
15 | libGDX Scene2d Actions or Frame Animation, which is better for performance? I only use Scene2d for the UI layer of my libGDX game. But I need some animations like fading or rotating on my players. Which is better for performance Scene2d fade action or having multiple frames with different opacity and using them in the Animation class? Also scene2d rotate action or having multiple frames with different angle? Thanks! |
15 | LibGDX limit the PerspectiveCamera for a FPS view I'm using LibGDX and I'm trying to implement a FPS camera into my game. I'm not using the FirstPersonCameraController for multiple reasons I don't want to touch to roll (only yaw and pitch), with this camera when looking on sides the horizon goes up and down like waves (meaning that the roll is changing) I don't want dragging, I want the camera to always move with the mouse. I want movements to stay consistent whatever the player is looking at. I don't want it to go slower even if he looks at the ground. So I've come up with this which does pretty much what I want Override public boolean mouseMoved(int screenX, int screenY) float deltaX (mousePos.x screenX) sensitivity float deltaY (mousePos.y screenY) sensitivity Vector3 tmpAxis game.getGame().getPool().obtain(Vector3.class) game.getCamera().rotate(Vector3.Y, deltaX) tmpAxis.set(game.getCamera().direction.z, 0, game.getCamera().direction.x) game.getCamera().rotate(tmpAxis, deltaY) if(game.getCamera().up.y lt 0) game.getCamera().up.y 0 mousePos.set(screenX, screenY, 0) game.getGame().getPool().free(tmpAxis) return true However, I have an issue described by the commented lines. When the camera goes to low or too high (when the y value of the up vector become negative), the rotation is reversed and the rotation starts to make it come back. In pratice, it just flickers a lot and when I try to go back, I have 1 2 chance of going back normally, and 1 2 chance of looking backward with my camera reversed (if the up vector is negative). So naturally, what I want is to lock the movement so It can never look pass his feets or pass the sky. Locking the up vector is easy, I just have to prevent it from going negative but I need to replace the direction vector also. However, I don't know how to "replace" the direction vector. I search on google for how to set the camera rotation or just how to get it and didn't found anything convincing. I've just tried also adding game.getCamera().direction.y 1f to my commented if to make it look down when getting past the point I don't want it to get past. However, I found out the direction vector isn't normalized and that's really confusing. |
15 | Tiled object layer draw sprites I added some tiles to some object layers in my tiled map and now I want to draw them in game. I tried to render everything with mapRender.render() but the tiles doesn't show up. Then I tried to render just one object layer and all of its objects with mapRenderer.renderObjects(tiledMap.getLayers().get(0)) but it wasn't working. Ingame Tiled Could someone please tell me how to make the tiles show up? Thank you very much! |
15 | Translating ChainShape to world coordinates according to touch drag input I'm trying to draw a ChainShape according to touch screen coordinates, however the coordinates are slightly off from my touch coordinates. I translate the chain drawn on the screen to world coordinates but don't think I've done it correctly. I tried setting the shape's position to the first vertex but it positions it even further from the original touch coordinates. Can someone please help me understand where I'm going wrong? public class Play implements Screen private static final float TIMESTEP 1 60f private static final int VELOCITYITERATIONS 8, POSITIONITERATIONS 3 private Box2DDebugRenderer debugRenderer private OrthographicCamera camera private PolygonSpriteBatch batch private World world private List lt Float gt chain verts new ArrayList lt Float gt () private float chain Override public void show() world new World(new Vector2(0f, 9.81f), true) debugRenderer new Box2DDebugRenderer() camera new OrthographicCamera() batch new PolygonSpriteBatch() InputProcessor input 0 new GestureDetector(new Gesture() ) Override public boolean touchUp(float x, float y, int pointer, int button) if (chain verts.size() ! 0) chain new float chain verts.size() for (int i 0 i lt chain verts.size() i ) chain i chain verts.get(i) System.out.print(chain i " ") ChainShape chainShape new ChainShape() chainShape.createChain(chain) Vector3 mouse new Vector3() camera.unproject(mouse.set(Gdx.input.getX(), Gdx.input.getY(), 0)) BodyDef bodyDef new BodyDef() bodyDef.type BodyType.StaticBody bodyDef.position.set(mouse.x , mouse.y) FixtureDef fixtureDef new FixtureDef() fixtureDef.shape chainShape world.createBody(bodyDef).createFixture(fixtureDef) chain verts.clear() chainShape.dispose() return super.touchUp(x, y, pointer, button) Override public boolean touchDragged(float x, float y, int pointer) chain verts.add(x) chain verts.add(Gdx.graphics.getHeight() y) return super.touchDragged(x, y, pointer) Gdx.input.setInputProcessor(input 0) Override public void render(float delta) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) world.step(TIMESTEP, VELOCITYITERATIONS, POSITIONITERATIONS) camera.position.set(0, 20, 0) camera.update() batch.setProjectionMatrix(camera.combined) debugRenderer.render(world, camera.combined) Override public void resize(int width, int height) camera.viewportWidth 1200 camera.viewportHeight 800 Override public void pause() Override public void resume() Override public void hide() dispose() Override public void dispose() batch.dispose() world.dispose() debugRenderer.dispose() |
15 | Fading in and fading out animations This is how I'm creating my player. Is there any way to start fading in and fading out for an amount of time when I get hit? private Texture tex Game.res.getTexture("player") public Player(Body body) TextureRegion sprites new TextureRegion 1 sprites 0 new TextureRegion(tex, 0, 0, 70, 96) sprites 1 new TextureRegion(tex, 69, 193, 68, 93) animation.setFrames(sprites, 1 6f) |
15 | Convert transform from world to local space I have a hierarchical node system. Given a world space transform, I need to obtain the transform for a specific node in local space. My Node class has the following method. public void worldToLocal(Matrix4 world, Matrix4 local) if (dirty) update() local.set(worldInverse).mul(world) worldInverse is the inverse of the node's world transformation matrix. I'm using LibGDX, so this is equivalent to doing LOCAL T 1 WORLD T 1 being the inverse of the node's world transform. However, this doesn't seem to be working correctly. Let's say we have a node at (2, 4, 0) rotated 180 degrees along its Z axis. Node node new Node() node.setPosition(2.0f, 4.0f, 0.0f) node.rotate(new Vector3(0.0f, 0.0f, 1.0f), 180.0f) Now, the point (1, 7, 0) should be (2, 1, 0) in local space for that node. Matrix4 local new Matrix4() Matrix4 world new Matrix4() Vector3 pos new Vector3() world.translate(1.0f, 7.0f, 0.0f) node.worldToLocal(world, local) local.getTranslation(pos) However, I get (1, 3, 0). I'm using this operation to translate from world space Bullet body transforms to local node transforms. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.