libGDX - How to clip - libgdx

I have one SpriteBatch in my game, between whose batch.begin() and batch.end() I draw...
a large static background image
several game sprites
I want to clip the area in which the sprites are seen, which I've read is done using ScissorStack.
The problem is that ScissorStack appears to clip the entire SpriteBatch that's sent to the GPU. The result is that it clips my game sprites and the background image.
Question:
Must I have two separate batch.begin() and batch.end() cycles, one without clipping for the background, and another with clipping for the sprites? Or is there a way of clipping just the sprites without using ScissorStack?
If the former, then isn't it rather expensive flushing the SpriteBatch twice as many times simply in order to clip a few sprites, or is it really nothing to worry about in terms of performance?
Related question:
The calculateScissors() method in the latest source code has more parameters than I've seen documented anywhere...
calculateScissors(camera, viewportX, viewportY, viewportWidth, viewportHeight, batchTransform, area, scissor)
What is the purpose of the viewportX, viewportY, viewportWidth, viewportHeight when they appear to be duplicating the camera's viewport and area information, and are not mentioned in any docs?
Basically, I'm really confused... even after (or especially after!) testing the behaviour of different values for each of these parameters.
Any advice sought.

Instead of using a ScissorStack I resorted to using using glScissor to get the results I needed.
#Override
public void render(float delta) {
GameStage.INSTANCE.act(Gdx.graphics.getDeltaTime());
GameStage.INSTANCE.setViewport(GameGeometry.width, GameGeometry.height,
true);
GameStage.INSTANCE.getCamera().translate(
-GameStage.INSTANCE.getGutterWidth(),
-GameStage.INSTANCE.getGutterHeight(), 0);
Gdx.gl.glScissor(
(int) GameStage.INSTANCE.getGutterWidth() * 2,
(int) GameStage.INSTANCE.getGutterHeight(),
(int) Gdx.graphics.getWidth()
- (int) (GameStage.INSTANCE.getGutterWidth() * 4),
(int) Gdx.graphics.getHeight());
Gdx.gl.glDisable(GL10.GL_SCISSOR_TEST);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
Gdx.gl.glEnable(GL10.GL_SCISSOR_TEST);
GameStage.INSTANCE.draw();
}
Hope this helps.

Related

How to render properly Box2DDebugRenderer

I've some problem for render Box2D Debug with Box2DDebugRenderer.
I've 2 OrthographicCamera, one for render the world (named Cam) and one for the HUD (healthBar, Armor, ...) (named hudCam).
I've tried to render :
b2dr.render(world, cam.combined); -> I can't see the Box2D
b2dr.render(world, cam.projection);
b2dr.render(world, hudCam.combined);
b2dr.render(world, hudCam.projection);
b2dr.render(world, new OrthographicCamera().combined); and b2dr.render(world, new OrthographicCamera().projection)
I can't find a way to render the Box2D exactly like cam, to see the edge of all bodies.
If somebody understand my problem, please help me !
Thx.
Unfortunately some tutorial out there suggest to use a meter-to-pixel-conversion when using Box2D. This is not neccessary (at least with Libgdx), as this conversion can be done by using a camera.
The problem in your case is, that you are using a meter-to-pixel-conversion when rendering the Sprites, while the Box2DDebugRenderer renders everything 1:1.
To solve this problem you have to get rid of the meter-to-pixel conversion and use the camera or the viewport to "scale" the things.
THis way, the Box2DDebugRenderer and your SpriteBatch can (and should) use the same camera to render.
For the camera/viewport:
The constructor has the params width and height. Those params are often set as Gdx.graphics.getWidth() and Gdx.graphics.getHeight(), which in my optinion is not right, the game should be resolution-independent.
You should instead select those values depending on how big your player (or any other visible entity) is in real life and how big it should be on screen.
Let's say you have a little characte, like in your game. It is 1m tall in real live and should take 1/13 of the screen height (more or less like in your first picture, where the screen is about 13 times as high as the character).
So your cameras height should be 13, your characters height (also it's Box2Ds Body height) should be 1m. Next you need to define the width. For that i like to think about my desired aspect ratio. Lets assume the game should focus on 16/9 devices, the width is then (13/9)*16=23.
Now your camera should be created like this:
camera = new OrthographicCamera(23, 13);

LibGDX - Draw clipped sprite

I am surely overlooking something, but is there an easy to draw for example only half a sprite in LibGDX? I originally thought I could do this with setBounds() but this distorts the sprite and does not clip it.
do not know if this is what you want, or is the most efficient way but that's what I happened to read your question, I hope I understand and serve you this:
Variable class:
Texture testTexture = new Texture (Gdx.files.internal("badlogic.jpg"));
In render method for example:
//batch is a SpriteBatch.
batch.draw(testTexture, 50, 50,
0, 0,
testTexture.getWidth() /2,
testTexture.getHeight());
this is the method in SrpiteBatch.class:
public void draw (Texture texture, float x, float y, int srcX, int
srcY, int srcWidth, int srcHeight)
Now for example in you sprite (simple test):
batch.draw(yourSprite.getTexture(), 50, 50,
0, 0, yourSprite.getTexture().getWidth() /2,
yourSprite.getTexture().getHeight() );
Edit Note:
to re-look the answer, I thought it would be nice to say that this makes, show only one area of the texture as you say, but perhaps should be noted that the texture remains the same size, I say this because if you texture used to detect collisions, keep in mind, that although half display, texture remains as large than the original
There was also Scissors class:
http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/scenes/scene2d/utils/ScissorStack.html
I think I tried it once...but it worked well on desktop and not on android...so I didn't use it. Maybe it's fixed meanwhile.

I want to scale ParticleEffect - Libgdx

Basically my problem is simple - I have a ParticleEffect which looks nice on small screen but on my private phone (Samsung S4) it looks very small. My question is: How can I scale the effect?
I have already done something like this:
// Callback method
public void addEffect(Vector2 position, boolean special) {
// Callback Method for the particle effects
PooledEffect effect;
if (!special)
effect = (MathUtils.random(0, 1) == 0) ? yellow_star_pool.obtain()
: green_star_pool.obtain();
else
effect = special_star_pool.obtain();
effect.setPosition(position.x, position.y);
effect.scaleEffect(Values.Scalar_Width*1.3f);
effects.add(effect);
}
But the result is that the effect is scaling exponentially, something I don't want.
I just want the effect to be scaled so that it will look the same on all screens. How can I achieve that?
First, I want to explain why current approach doesn't work. Note that the method you use for scaling is named scaleEffect, not setScale. Every time you call it the effect will be scaled relative to its current state. When you use pooled particle effects you scale the effect as many times as the particle had been reused. That's why you see it scaling exponentially.
So, the solution is to scale only the particle effect that you use as a prototype for the pool. Something like:
prototypeEffect.scaleEffect(Values.Scalar_Width * 1.3f);
ParticleEffectPool yellow_star_pool = new ParticleEffectPool(prototypeEffect, 10, 100);
Then you didn't have to scale every particle effect you obtain.

Proper using of scene2d's Stage in a game with a huge world

If the whole "game world" is thousands of times wider than a viewport, and if I want to use scene2d to manage game objects as Actors, should I create Stage object as wide as the whole world, or should the Stage be some area around current viewport but not the whole world?
In other words, does a Stage with greater width and height consume more memory itself, even if I render objects only on a small viewport-sized part of it?
I think you misunderstood what exactly a Stage is. A Stage doesn't really have a size itself. You don't specify a width or height or the Stage, you only specify the width and height of the viewport. The viewport is like a window, which shows only a part of your world, aka scene. A Stage is a 2D scene graph and it "grows" with your Actors. The more Actors you have, the bigger (memory wise) your Stage is, but it doesn't depend on how far spreaded your Actors actually are. If they are very far spreaded and you only display a very small part of your whole Stage, it will be handled very efficient, because a scene graph sub-divides this huge space to be able to very quickly decide whether to ignore a certain Actor, or draw it on the Screen.
That means a Stage is actually exactly what you need for this kind of situation and you should probably not have any problems, FPS and memory wise. But of course if your Stage is 1000s of times the size of your viewport and you know yourself that certain Actors aren't displayed soon, then it might make sense to not add them to the Stage yet.
A stage is only a root node that will hold all the actors. It's role is to call methods for its children (like draw and act); thus only the number and complexity of actor have an impact on memory and frame rate.
For your situation a culling method is certainly required. The simplest one would be to check if an actor is in the viewport and if not skip drawing him. Create a custom actor and add this code: source
public void draw (SpriteBatch batch, float parentAlpha) {
// if this actor is not within the view of the camera we don't draw it.
if (isCulled()) return;
// otherwise we draw via the super class method
super.draw(batch, parentAlpha);
}
Rectangle actorRect = new Rectangle();
Rectangle camRect = new Rectangle();
boolean visible;
private boolean isCulled() {
// we start by setting the stage coordinates to this
// actors coordinates which are relative to its parent
// Group.
float stageX = getX();
float stageY = getY();
// now we go up the hierarchy and add all the parents'
// coordinates to this actors coordinates. Note that
// this assumes that neither this actor nor any of its
// parents are rotated or scaled!
Actor parent = this.getParent();
while (parent != null) {
stageX += parent.getX();
stageY += parent.getY();
parent = parent.getParent();
}
// now we check if the rectangle of this actor in screen
// coordinates is in the rectangle spanned by the camera's
// view. This assumes that the camera has no zoom and is
// not rotated!
actorRect.set(stageX, stageY, getWidth(), getHeight());
camRect.set(camera.position.x - camera.viewportWidth / 2.0f,
camera.position.y - camera.viewportHeight / 2.0f,
camera.viewportWidth, camera.viewportHeight);
visible = (camRect.overlaps(actorRect));
return !visible;
}
If you need to improve performance even further you can switch to manually deciding what is visible and what not (ex when moving the camera). This would be faster because all those culling calculations are executed at EVERY frame, for EVERY actor. So although it's a lot faster to do some math instead of drawing, a big number of actors would give a huge amount of unwanted calls.

Understand LibGDX Coordinate system and drawing sprites

So I am super stoked to start using LibGDX for my first android title for OUYA and PC, but I am running into some snags with LibGDX. (All of my questions can be answered by looking at source, but I am really trying to understand the design choices as well).
To start with, the coordinate system. I created a project using the Project Setup jar, and it creates an OrthographicCamera like so
camera = new OrthographicCamera(1, h/w);
From my reading, I understand that LibGdx uses bottom left corner for 0,0 and yUp. Fine.
I see that it is pretty easy to change to y down if I want to, but I am not understanding the next bit of code that was created.
For the default sprite that gets created the position is set like so.
logoSprite.setOrigin(logoSprite.getWidth()/2, logoSprite.getHeight()/2);
logoSprite.setPosition(-logoSprite.getWidth()/2, -logoSprite.getHeight()/2);
When I run this basic program, I see the logo image I have added is centered on the screen. What I am trying to understand is why the values are negative in set position, and why is it using the sprite width and height instead of the graphics w and h of the view port? If I change to the screen width and height, then the image is drawn in some odd position in the lower right hand side of the screen.
My next question is sprite.setSize vs sprite.setScale. Why is the difference between the two? (They appear to do the same thing, except setScale leaves getWidth and getHeight unchanged).
Since my game will be using a 2D camera heavily for panning, zooming and rotation, I am trying to understand as much as I can about the libgdx framework before I start writing any code.
As a side note, I have a game development and math background and I have made several 2D and 3D games using XNA. I am finding LibGdx a bit frustrating as it does not abstract away OpenGL as much as I was expecting it to, and so far the 2D drawing I have been experimenting with seems to be more confusing than it should be!
I also wanted to note that I am planning to use spine for my animations. Should that change my choice to use y-up or y-down?
If you want to draw a sprite in center of screen, do this in your create method
logosprite.setposition(scrw/2-logosprite.getwidth()/2,scrh/2-logosprite.getheight/2);
here scrw is your viewport's width,
and scrh is your viewport's height,
this way your sprite will be in center of screen
sprite.setsize is used for setting size of the sprite and sprite.setscale is used when we scale a large/small texture so that its quality remains good in all devices(hdpi.mdpi,xhdpi,ldpi)..
no need to worry if you are using spine it works smoothly in libgdx..
You can use just this code if possible
logoSprite.setPosition(Gdx.graphics.getWidth()/2 - image.getWidth()/2,
Gdx.graphics.getHeight()/2 - image.getHeight()/2);
To center the sprite into the middle of the screen Where "image" is the Texture you have loaded/declared initially.
As for why it is coming in a odd position is due to the fact that you are using a camera.
Which changes the view a lot just go through the documentations of libgdx about camera here
In my case, I needed to set position of camera and then call update() method.
Then never forget camera's (0,0) is its center. Everything is being placed that way. My camera code:
private void cameralariUpdateEt() {
cameraGame.position.set(cameraGame.viewportWidth * 0.5f,
cameraGame.viewportHeight * 0.5f, 0);
cameraGame.update();
cameraScore.position.set(cameraScore.viewportWidth * 0.5f,
cameraScore.viewportHeight * 0.5f, 0);
cameraScore.update();
}
Call this method from inside render();
Step 1: Set the sprite origin to the position you would like it to rotate around.
// camera center point is (c.x, c.y)
logoSprite.setOrigin(c.x, c.y);
Step 2: make sure to set your sprite center to origin
logoSprite.setOriginCenter();
Step 3: Rotate your sprite
logoSprite.setRotation(Angle);
Step 4: Set the sprite position, [subtract half the sprites width and height to center the sprite]
logoSprite.setPosition(c.x - logoSprite.getWidth() / 2, c.y - logoSprite.getHeight() / 2)