I am using the animation class to make a simple animation, with only 2 frames.
With animation, i can get the index, or texture region at the current time.
if (!animation.isAnimationFinished(time))
time += Gdx.graphics.getDeltaTime();
else
time = 0;
But the problem is, that I can't load any texture, its width and height must be a power of 2, so i got a big 1024x1024 texture, that has the 2 images.
With sprite.setTexture() i can only put a Texture, but animation.getframe returns a texture region.
Is there a way to change the sprite texture with an animation?
Also
sprite.setTexture(animation.getKeyFrame(time).getTexture());
Does not work.
This works
sprite = new Sprite(animation.getKeyFrame(time));
But I don't think is the best idea... I think is slow can can make bugs.
You usually use TextureRegion for sprites. The method that you are looking for is TextureRegion#setRegion (Sprite extends TextureRegion).
Like this:
sprite.setRegion(animation.getKeyFrame(time));
Related
I am currently working on a game in which i need pixel perfect collision with objects. The only obstacle i had gotten to however, is with actually getting a mask of the object. I thought about rendering a sprite of an object (which is properly scaled and transformed) to FrameBuffer, which then i'd convert to a pixmap, but i had no luck doing it (tried many methods, including this)
So, my question is: Is there a way of rendering a single sprite to a pixmap in LibGDX?
Sounds like putting the horse behind the cart. A Sprite is a region of a Texture, which in turn is an image loaded from file aka Pixmap. If you just want to load the image from file then you can do: new Pixmap(Gdx.files.internal("yourfile.png"));. You can also scale and transform your coordinates without rendering to a FBO first.
That said; getting the Pixmap of a FrameBuffer is as "simple" as taking a screenshot while the FBO is bound, because it is exactly that.
fbo.begin();
Gdx.gl.glClear(...);
... //render to the FBO
Pixmap pixmap = ScreenUtils.getFrameBufferPixmap(0, 0, fbo.getWidth(), fbo.getHeight());
fbo.end();
Note that this will look like it is up-side-down.
But you are probably only interested in the pixel data, so you might as well skip the Pixmap step in that case and use the ScreenUtils.getFrameBufferPixels method.
However, that said; using the pixel data for collision detection is most likely not the best solution for whatever it is you are trying to achieve. Instead I'd advise to look into other options, for example have a look at this tool which can be used to convert your images into a collision shape.
Hopefully the title isn't too confusing, but I am new to LibGDX and after hours of searching on Google I finally got the camera and viewport to work, it now properly scales to the screen. There's still one problem, while the Y coordinate at 0 is correct, the X coordinate at 0 seems to be 1/a few pixels off, I am bad at describing, so here's a picture: Link to image
Like I said, I'm new to LibGDX and I am guessing it's a pretty obvious mistake, but here's the code I'm using:
I use these variables:
public static final int WORLD_WIDTH = 480;
public static final int WORLD_HEIGHT = 800;
OrthographicCamera cam;
Viewport viewport;
SpriteBatch batch;
Texture img;
I have this in the create():
cam = new OrthographicCamera(WORLD_WIDTH, WORLD_HEIGHT);
cam.setToOrtho(false, WORLD_WIDTH, WORLD_HEIGHT);
viewport = new FitViewport(WORLD_WIDTH, WORLD_HEIGHT);
img = new Texture("badlogic.jpg");
I have this in the render():
batch.setProjectionMatrix(cam.combined); //Important
And further down in render() I have this code:
batch.begin();
batch.draw(img, 0, 0);
batch.end();
And I have this in resize():
viewport.update(width, height);
Which gives the result from the picture.
Is there a solution to this problem, do I need to alter a part of the code, add some new lines or is there a smarter way to do a camera/viewport?
I'm looking forward to your answers, thanks in advance.
Cheers!
What you are experiencing is the way it is supposed to be. You are working with a FitViewport and a "virtual" resolution. A FitViewport keeps the aspect ratio of the given viewport size, while scaling it up or down to fill your game window. If your window does not have the same aspect ratio like the virtual resolution, FitViewport will lead to parts of your window being "empty" (that means having only the glClear-color).
Have a look at the Viewports wiki page, where you can see this behaviour in a more extreme way.
If you don't want this, you can try it with the "opposite" FillViewport (no empty areas, but some parts may be cut off because they are "outside" of your window), a ScreenViewport (good for UI), or an ExtendViewport.
About a year ago I developed a full LibGDX game tutorial and provided code that was reusable for any game you'd want to create. I included a dynamic Camera which handled the aspect ratio and resolution perfectly. You can take a look at the code for the camera here and determine how it is similar to yours and if there are any things you can do to improve your camera.
is there a way to combine a number of textures into one texture with libgdx API?
For example, consider having these 3 textures:
Texture texture1 = new Texture("texture1.png");
Texture texture2 = new Texture("texture2.png");
Texture texture3 = new Texture("texture3.png");
The goal is to combine them into one usable texture, is there a way to do it?
I wanted to get the same result, but I did not find the previous instructions given to be of any help. Neither I was able to find any other clear solution for this issue, so here's what I managed to get working after I read a bit of api-docs and did some testing of my own.
Texture splashTexture = new Texture("texture1.png"); // Remember to dispose
splashTexture.getTextureData().prepare(); // The api-doc says this is needed
Pixmap splashpixmap = splashTexture.getTextureData().consumePixmap(); // Strange name, but gives the pixmap of the texture. Remember to dispose this also
Pixmap pixmap = new Pixmap(splashTexture.getWidth(), splashTexture.getHeight(), Format.RGBA8888); // Remember to dispose
// We want the center point coordinates of the image region as the circle origo is at the center and drawn by the radius
int x = (int) (splashTexture.getWidth() / 2f);
int y = (int) (splashTexture.getHeight() / 2f);
int radius = (int) (splashTexture.getWidth() / 2f - 5); // -5 just to leave a small margin in my picture
pixmap.setColor(Color.ORANGE);
pixmap.fillCircle(x, y, radius);
// Draws the texture on the background shape (orange circle)
pixmap.drawPixmap(splashpixmap, 0, 0);
// TADA! New combined texture
this.splashImage = new Texture(pixmap); // Not sure if needed, but may be needed to get disposed as well when it's no longer needed
// These are not needed anymore
pixmap.dispose();
splashpixmap.dispose();
splashTexture.dispose();
Then use the splashImage (which is a class variable of type Texture in my case) to render the combined image where you want it. The resulting image has the given background and the foreground is a png image which has transparent parts to be filled by the background color.
#Ville Myrskyneva's answer works, but it doesn't entirely show how to combine 2 or more textures. I made a Utility method that takes 2 textures as input and returns a combined texture. Note that the second texture will always be drawn on top of the first one.
public static Texture combineTextures(Texture texture1, Texture texture2) {
texture1.getTextureData().prepare();
Pixmap pixmap1 = texture1.getTextureData().consumePixmap();
texture2.getTextureData().prepare();
Pixmap pixmap2 = texture2.getTextureData().consumePixmap();
pixmap1.drawPixmap(pixmap2, 0, 0);
Texture textureResult = new Texture(pixmap1);
pixmap1.dispose();
pixmap2.dispose();
return textureResult;
}
You should use the TexturePacker for creating one big Texture from lots of small one. https://github.com/libgdx/libgdx/wiki/Texture-packer .
And here is GUI version (jar) whcih will help you to pack all your textures in one before putting them to your project: https://code.google.com/p/libgdx-texturepacker-gui/.
You should also remember that maximum size of one texture for most Android and IOS devices is: 2048x2048.
In case you want to use combined texture as atlas for performance benefits, you better use #Alon Zilberman answer.
But I think that your question is about another problem. If you want to get some custom texture from these three textures (e.g. merge them by drawing one at one), then your best solution is to draw to FrameBuffer. Here you can find nice example of how to do it https://stackoverflow.com/a/7632680/3802890
I am currently experiencing issues when drawing and scaling sprites.
I am loading my assets from a texture-atlas, which I packed no problem with the LibGDX texture packer gui tool. My texture atlas image currently looks like this.
These images are supposed to be buttons, but as you can see, the image is very small, so when the sprites are loaded, they load a sprite of say, 34x16 pixels. When I render these buttons, on a canvas of 1920x1080, they are much too small. I use sprite.scale(int scale) to scale the sprites, but when I scale them, they appear blurry. What I would like to happen, is when they are scaled, each pixel is scaled proportionally, keeping the pixelated effect on the button, rather than a blurry resized image from a really small texture. I currently render the sprites using sprite.render(SpriteBatch batch). Is this the proper way of rendering a sprite, after they are loaded using atlas.createSprite(String name)? I am new to using sprites, and loading textures from a texture-atlas, so i am wondering if this is the correct way of doing things.
Also, when I initialize my game, I load numerous different Sprite objects from a TextureAtlas. Each sprite holds a texture that will represent a game object, however it is my understanding that you render a sprite using sprite.render(SpriteBatch batch), so therefore I could only use a sprite, loaded from the TextureAtlas for one game object, because I would also have to set the scale, and position of the sprite, as it represents the game object. I am used to loading a Texture, then rendering this texture using batch.render(), at a given position, but I don't see how this is possible if I am using a sprite. Even if I use batch.render(Sprite, x, y), I am unable to scale the sprite properly, because as I mentioned before, I would like to scale the sprite while maintaining a pixelated effect, and even so, using the Sprite.scale() method, this would scale the Sprite object as a whole, making it impossible to use the Sprite's texture multiple times for numerous game objects.
Any suggestions would be greatly appreciated.
The code I am currently using to render/load the sprites is as follows:
Loading from TextureAtlas:
public static TextureAtlas atlas = new TextureAtlas(Gdx.files.internal("data/texture/pack/output/pack.pack"));
public static Sprite sprite = atlas.createSprite("buttonUp");
sprite.setScale(10);
Rendering Sprite: GdxGame.WIDTH/HEIGHT are 1920x1080. Though the Desktop window is scaled down from that size. Thus, everything is rendered as if the screen were 1920x1080.
batch = new SpriteBatch();
camera = new OrthographicCamera(GdxGame.WIDTH, GdxGame.HEIGHT);
camera.position.set(GdxGame.WIDTH/2, GdxGame.HEIGHT/2, 0);
camera.setToOrtho(false, GdxGame.WIDTH, GdxGame.HEIGHT);
public void render(float delta){
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined);
batch.begin();
camera.update();
sprite.draw(batch);
batch.end();
}
After further investigation, I have discovered that I can use Sprite.set(Sprite sprite) to make Sprite x a copy of Sprite y, and therefore render each sprite multiple times. However, this does not solve the issue of scaling the sprite. I must emphasize further that when rendering a scaled sprite, the scaling is not done by pixel, meaning that it is blurry. But, when rendering a TextureRegion, like: batch.draw(TextureRegion, x, y, width, height) if the width and height are greater than that of the original texture, it will scale each pixel, rather than blur the whole thing to try and make it look better. The following is an image of the blurriness I am talking about:
Notice how this sprite is scaled to be blurry, even though the original image is small, and pixelated.
What TextureFilter settings are you using in your code or in the texturepacker? Try the "Nearest" filter. If you have set it to "Linear" or alike, it will always take 4 texture pixels (texels) and interpolate them to get the color of the pixel to be drawn.
That might help against the blur, but I am not sure if it will produce exactly that 8-bit look you are aiming for...
SpriteBatch.SetProjectionMatrix(cam.combined) makes Spritebatch not draw blocks and my character but camera movement works, but if I don't use this line of code everything is drawn but camera is not working? Does anyone know the solution, because if simply can't see it.
EDIT: sorry for the messy first post
Here is the piece of code that is troublesome:
public void render()
{
cam.update();
spriteBatch.setProjectionMatrix(cam.combined);
spriteBatch.begin();
drawBlocks();
drawBob();
spriteBatch.end();
cam.position.x = world.bob.GetPosition().x;
cam.update();
drawCollisionBlocks();
if(debug)
drawDebug();
}
I found the solution but for anyone who may have this kind of problem in the future, the problem was in drawing methods where i was drawing
textures like this:
CODE:
spriteBatch.draw(bobFrame, bob.GetPosition().x * PPuX, bob.GetPosition().y*PPuY ,Bob.SIZE*PPuX , Bob.SIZE*PPuY );
PPuX,PPuY were of type int and were used for different screen sizes and that was messing spriteBatch up when i was setting the projection matrix
The spriteBatch.setProjectionMatrix(cam.combined) lets spriteBatch use the coordinate system that specified by cam instead of the default ones. This is because the both's coordinate system are different and the cam.combined will do the maths for you.
I believe you actually ARE drawing the sprites, however you are not seeing them because your camera viewports are not set(ie. you are looking at the wrong coordinate area).
Adding
cam.setToOrtho(false); //true to invert y axis
"Sets this camera to an orthographic projection using a viewport fitting the screen resolution, centered at (Gdx.graphics.getWidth()/2, Gdx.graphics.getHeight()/2), with the y-axis pointing up or down."
Link to JavaDOC here