Libgdx , When to use camera.position.set? - libgdx

I am really confused with two examples related to viewport and orthagraphic. Although i understand that Viewport is the size of the dimensions we set to view on the screen and camera projects that. I am learning libgdx and cannot finish through orthographic camera and viewport examples which have left me completely confused. the code runs fine for both examples and with proper result on screen.
here's one example in which camera.position.set is used to position the camera.
public class AnimatedSpriteSample extends GdxSample {
private static final float WORLD_TO_SCREEN = 1.0f / 100.0f;
private static final float SCENE_WIDTH = 12.80f;
private static final float SCENE_HEIGHT = 7.20f;
private static final float FRAME_DURATION = 1.0f / 30.0f;
private OrthographicCamera camera;
private Viewport viewport;
private SpriteBatch batch;
private TextureAtlas cavemanAtlas;
private TextureAtlas dinosaurAtlas;
private Texture background;
private Animation dinosaurWalk;
private Animation cavemanWalk;
private float animationTime;
#Override
public void create() {
camera = new OrthographicCamera();
viewport = new FitViewport(SCENE_WIDTH, SCENE_HEIGHT, camera);
batch = new SpriteBatch();
animationTime = 0.0f;
...
...
..
camera.position.set(SCENE_WIDTH * 0.5f, SCENE_HEIGHT * 0.5f, 0.0f);
Here's another example which does not use camera.position.set and still the result is the same.
#Override
public void create() {
camera = new OrthographicCamera();
viewport = new FitViewport(SCENE_WIDTH, SCENE_HEIGHT, camera);
batch = new SpriteBatch();
oldColor = new Color();
cavemanTexture = new Texture(Gdx.files.internal("data/caveman.png"));
cavemanTexture.setFilter(TextureFilter.Nearest, TextureFilter.Nearest);
}
#Override
public void dispose() {
batch.dispose();
cavemanTexture.dispose();
}
#Override
public void render() {
Gdx.gl.glClearColor(BACKGROUND_COLOR.r,
BACKGROUND_COLOR.g,
BACKGROUND_COLOR.b,
BACKGROUND_COLOR.a);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined);
batch.begin();
int width = cavemanTexture.getWidth();
int height = cavemanTexture.getHeight();
float originX = width * 0.5f;
float originY = height * 0.5f;
// flipX, flipY
// Render caveman centered on the screen
batch.draw(cavemanTexture, // Texture itselft
-originX, -originY, // pass in the world space coordinates where we to draw, Considering the camera is centered at (0,0). by default we need to position
// out cavement at -originX, -originY.
originX, originY, // coordinates in pixels of our texture that we consider to be the origin starting from the bottom-left corner.
// in our case, we want the origin to be the center of the texture. then we pass the dimensions of the texture and the scale
// and the scale along both axes (x and Y).
width, height, // width, height
WORLD_TO_SCREEN, WORLD_TO_SCREEN, // scaleX, scaleY
0.0f, // rotation
0, 0, // srcX, srcY
width, height, // srcWidth, srcHeight
false, false); // flipX, flipY
What is really confusing me is why does it not use camera.position.set on the second example to adjust the camera's view and why is it important to use this on the first example.
I really hope this question is legit and makes sense. I have searched the forum here and couldnt find any clues. Hope someone can guide in the right direction.
Many Thanks.

In the first example a 2 dimensional vector has been initialized for the position of the camera the x direction and the y direction. This for the specifically the camera.
camera = new OrthographicCamera();
So, this code creates a camera object from the OrthographicCamera class created by libgdx creators. Check out the documentation for the class here from that class you can see when that it is constructed it accepts both the viewport_height and viewport_width. (in your example you've left it blank, so these are 0 for the time being.)
viewport = new FitViewport(SCENE_WIDTH, SCENE_HEIGHT, camera);
This line of code defines the width, height and which camera should be used for the viewport. check out the documentation for FitViewport class here
So when camera.position.set is called, it sets for the x and y direction based on the viewport's width and height. This whole example defines the viewport dimensions for the overall viewport.
The difference between this and the second example is that the camera is set around the texture that has been loaded onto the screen. So the viewport's x and y direction has been positioned and the width, height, originX, originY of the texture/camera has been defined also:
int width = cavemanTexture.getWidth();
int height = cavemanTexture.getHeight();
float originX = width * 0.5f;
float originY = height * 0.5f;
Libgdx then allows you to draw the texture using the spritebatch class to draw both the texture and the viewport surrounding that texture.
Summary
Example one allows you to define a viewport on it's own, without any textures being drawn. This will allow you to draw multiple textures with the same viewport being set (a normal process of game creation)
But in Example two if you wanted the viewport to say, follow the main character around on the screen. you can define the viewport surrounding the texture to thus follow that texture.
Personally, i'd always pursue the first example as you can define a viewport for any game width or height and then i'd create a second viewport ontop to follow any textures i've drawn on the screen. They both work, just for different reasons.
Hope this helps you clear things up.
Happy coding,
Bradley.

Related

body falls slowly in any gravity

I've created a World with earth gravity and I place an entity in the scene (contains a sprite and a Body) and it falls down slowly like a balloon.
Here's how I set the World:
world = new World(new Vector2(0, -GRAVITY_EARTH), true);
and here's the relevant Box2D code for the Body etc:
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(positionX, positionY);
// Create our body in the world
body = world.createBody(bodyDef);
// Grab the first idle sprite to use as initial
Sprite sprite = idleSprites.get(0);
// Create a box shape to represent our hit box
PolygonShape box = new PolygonShape();
box.setAsBox(sprite.getWidth() / 2f, sprite.getHeight() / 2f);
// Create a fixture definition to apply our shape
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = box;
fixtureDef.density = 1f; // Give it full density
fixtureDef.friction = 0f; // Give it no friction
fixtureDef.restitution = 0f; // Make it not bouncy
// Create our fixture and attach it to the body
fixture = body.createFixture(fixtureDef);
// Remember to dispose of any shapes after you're done with them!
// BodyDef and FixtureDef don't need disposing, but shapes do.
box.dispose();
and how I draw the sprite:
TextureRegion keyFrame = idleAnimation.getKeyFrame(stateTimeSeconds, true);
Vector2 position = body.getPosition();
batch.draw(keyFrame, position.x - keyFrame.getRegionWidth() / 2f, position.y - keyFrame.getRegionHeight() / 2f);
and the relevant code in the render() method:
#Override
public void render () {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
final float deltaTime = Gdx.graphics.getDeltaTime();
camera.update();
spriteBatch.setProjectionMatrix(camera.combined);
spriteBatch.begin();
spriteBatch.draw(sky, 0, 0);
tim.animate(spriteBatch, deltaTime);
spriteBatch.draw(floor, 0, 0);
spriteBatch.end();
// Render physics for debug
debugRenderer.render(world, camera.combined);
// Run physics
doPhysicsStep(deltaTime);
}
private void doPhysicsStep(float deltaTime) {
// fixed time step
// max frame time to avoid spiral of death (on slow devices)
float frameTime = Math.min(deltaTime, 0.25f);
accumulator += frameTime;
while (accumulator >= TIME_STEP) {
world.step(TIME_STEP, VELOCITY_ITERATIONS, POSITION_ITERATIONS);
accumulator -= TIME_STEP;
}
}
I've tried changing the density of the fixture, and I've tried changing the gravity value, and I've tried changing the TIME_STEP and nothing is having an effect. The body just falls down slowly like a balloon.
It looks to me like you're using pixels as your units, box2d treats every unit as a meter and so you're hitting the internal limit of 2.0 units per time step, see http://www.iforce2d.net/b2dtut/gotchas. You can get around this by setting up your camera in world units instead of pixels, you have to scale all your sprites and positions to fit into world units instead of pixels though.
Something like this may do:
float w = (float) Gdx.graphics.getWidth();
float h = (float) Gdx.graphics.getHeight();
camera = new OrthographicCamera(30, 30 * (h / w));
the way the camera is set up here allows the height of the viewport to be variable based on the screens' aspect ratio.
Then to setup the sprite change it by a set factor
sprite.setSize(sprite.getWidth / PIX2M, sprite.getHeight / PIX2M);
where PIX2M is a static field defining how many pixels are a meter in box2d
Alternatively you can set the dimensions of the sprite explicitly to a value which makes physical sense and with the aspect ratio of the original image(my personal preference) . So an image of a person which is 100 x 500 for example could be set like this.
sprite.setSize(.4f, 2f);
meaning the person is 2 meters high and .4 meters wide. Also with this method you don't need a PIX2M conversion factor and you will always know the exact size of your body. Since you set the camera to a specific number of world units, 30 in this case, the sprite will take up the same amount of room on the screen no matter the resolution of the display.

Table elements of a stage using a viewport in libgdx is shown at top right screen per default instead of center

I'm using a Screen.
When I use the Table class in my Stage I want to show my Table at the top left of the screen but per default it is shown at the top right of my screen.
Calling tableLeft.left() moves my table to the top-center of the screen. Using tableLeft.top() moves the tabe out of the screen complettly.
If I'm not using any viewports it works perfectly fine but then I'm running into other issues.
Also note that I'm reading about cameras and viewpoints for about two weeks now and I'm still confused as hell as how it works even after reading like all of the official libgdx tutorials on the wiki and reading everythign else about it I could google. For example I have no clue why I can remove everything from the resize() method and the output does not change at all.
My code looks like that:
#Override
public void show() {
....
camera = new OrthographicCamera(1920, 1080);
viewport = new FitViewport(1920, 1080, camera);
viewport.apply();
....
batch = new SpriteBatch();
....
stage = new Stage(viewport, batch);
Table tableLeft = new Table();
tableLeft.add(new Label("Dummy Label", skin, "default"));
stage.addActor(tableLeft);
.....
}
#Override
public void resize(int width, int height) {
viewport.update(width, height, true);
stage.getViewport().update(width, height, true);
camera.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2, 0);
}
I guess that you don't need to update viewport nor center camera manualy:
viewport.update(width, height, true);
camera.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2, 0);
because
stage.getViewport().update(width, height, true);
already does it in your case:
/** Configures this viewport's screen bounds using the specified screen size and calls {#link #apply(boolean)}. Typically called
* from {#link ApplicationListener#resize(int, int)} or {#link Screen#resize(int, int)}.
* <p>
* The default implementation only calls {#link #apply(boolean)}. */
public void update (int screenWidth, int screenHeight, boolean centerCamera) {
apply(centerCamera);
}
/** Applies the viewport to the camera and sets the glViewport.
* #param centerCamera If true, the camera position is set to the center of the world. */
public void apply (boolean centerCamera) {
Gdx.gl.glViewport(screenX, screenY, screenWidth, screenHeight);
camera.viewportWidth = worldWidth;
camera.viewportHeight = worldHeight;
if (centerCamera) camera.position.set(worldWidth / 2, worldHeight / 2, 0);
camera.update();
}

How to make the camera follow the player?

I'm making a game in libgdx which includes the player being able to move vertically beyond the set screen size.
As for my question, if I have the screen size set at a certain width and height, what is required to make the actual game world larger for the camera to follow the player?
This is of course my targeted screen size in the Main game class:
public static final int WIDTH = 480, HEIGHT = 800;
Below that I currently have :
public static final int GameHeight = 3200;
GameHeight is the value I test for whether the player is going out of bounds.
Here is the problem. With this code, the player is centered on the screen, and moves horizontally, rebounding off the screen bounds (As it would without the camera, but neglecting the change in y-position)
public GameScreen(){
cam = new OrthographicCamera();
cam.setToOrtho(false, 480, 800);
}
#Override
public void render(float delta) {
// TODO Auto-generated method stub
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
cam.position.y = player.getPosition().y;
cam.update();
batch.setProjectionMatrix(cam.combined);
player.update();
player.draw(batch);
}
If I remove:
cam.position.y = player.getPosition().y;
The camera is placed at the bottom of the virtual world and the ball starts at the top (y = 3200) and travels downward. When it reaches y = 800, it shows up as it should.
I've found a lot of examples that indicate in writing that setting the cameras position to the players y position should force the camera to follow the player, whether it's moving up or down, but it either freezes y movement or sets the camera at the bottom the virtual world.
Any help is appreciated, thanks!
I would try doing cam.position.set(player.getPosition().x, player.getPosition().y). This will make the camera follow your player and it should not cause any "freezing."
private val worldTransform = Matrix4()
private val cameraPosition = Vector3()
private val objPosition = Vector3()
private var rot = Quaternion()
private var carTranslation = Vector3(0f, 0f, 0f)
fun focus(obj: BulletObject) {
// worldTransform
obj.entity?.motionState?.getWorldTransform(worldTransform)
// objPosition
worldTransform.getTranslation(objPosition)
obj.entity?.modelInstance?.transform?.getTranslation(carTranslation)
// get rotation
worldTransform.getRotation(rot)
println("rot.angle: ${rot.getAngleAround(Vector3.Y)}")
val rad = Math.toRadians(rot.getAngleAround(Vector3.Y).toDouble())
// pointFromCar
val pointFromCar = Vector2(-3f * sin(rad.toFloat()), -3f * cos(rad.toFloat()));
cameraPosition.set(Vector3(objPosition.x + pointFromCar.x, objPosition.y + 1f, objPosition.z + pointFromCar.y))
// camera set position
camera.position.set(cameraPosition)
camera.lookAt(objPosition)
camera.up.set(Vector3.Y)
camera.update()
}

How do I extend the ViewPort and use it to paint a "window" of 3D graphics on the screen

I need to create a 3D perspective camera viewport of 480x480 and display it on the bottom right corner of the screen. The rest of the screen is filled with 2D graphics.
I tried extending Viewport and using viewportX, and viewportY as well as viewportHeight and viewportWidth, but the test 3D object does not draw.
I followed this tutorial to get the basic prototype going.
https://code.google.com/p/libgdx-users/wiki/Decals
How do I properly extend the ViewPort and use it to paint a "window" of 3D graphics on the screen ?
The following could be used to have a Viewport with a fixed size of 480x480 which is placed on the bottom left corner. If you supply a PerspectiveCamera to it, everything will be rendered in this area.
public class CustomViewport extends Viewport {
public CustomViewport (Camera camera) {
this.camera = camera;
}
#Override
public void update (int screenWidth, int screenHeight, boolean centerCamera) {
viewportX = 0;
viewportY = 0;
viewportWidth = 480;
viewportHeight = 480;
worldWidth = 480;
worldHeight = 480;
super.update(screenWidth, screenHeight, false);
}
}
If you want to render somewhere else after that, you have to "reset" the glViewport() via Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Now you are free to render whereever you want, for example in the top and right areas which were left blank.
This test shows another example of how to render in those areas.

Libgdx: screen resize and ClickListener (libgdx)

I develope a 2D game and use OrthographicCamera and Viewport to resize virtaul board to real display size. I add images to stage and use ClickListener to detect clicks. It works fine, but when I change resolution it works incorrent(can't detect correct actor, I think the problem with new and original x and y). Is there any way to fix this?
You will need to translate the screen coordinates to world coordinates.
Your camera can do that. You can do both ways, cam.project(...) and cam.unproject(...)
Or if you are already using Actors, don't initialize a camera yourself, but use a Stage. Create a Stage and add the actors to it. The Stage will then do coordinate translation for you.
Once me too suffered from this problem but at end i got the working solution, for drawing anything using SpriteBatch or Stage in libgdx. Using orthogrphic camera we can do this.
first choose one constant resolution which is best for game. Here i have taken 1280*720(landscape).
class ScreenTest implements Screen{
final float appWidth = 1280, screenWidth = Gdx.graphics.getWidth();
final float appHeight = 720, screenHeight = Gdx.graphics.getHeight();
OrthographicCamera camera;
SpriteBatch batch;
Stage stage;
Texture img1;
Image img2;
public ScreenTest(){
camera = new OrthographicCamera();
camera.setToOrtho(false, appWidth, appHeight);
batch = new SpriteBatch();
batch.setProjectionMatrix(camera.combined);
img1 = new Texture("your_image1.png");
img2 = new Image(new Texture("your_image2.png"));
img2.setPosition(0, 0); // drawing from (0,0)
stage = new Stage(new StretchViewport(appWidth, appHeight, camera));
stage.addActor(img2);
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(img, 0, 0);
batch.end();
stage.act();
stage.act(delta);
stage.draw();
// Also You can get touch input according to your Screen.
if (Gdx.input.isTouched()) {
System.out.println(" X " + Gdx.input.getX() * (appWidth / screenWidth));
System.out.println(" Y " + Gdx.input.getY() * (appHeight / screenHeight));
}
}
//
:
:
//
}
run this code in Any type of resolution it will going to adjust in that resolution without any disturbance.
I just think Stage is easy to use.
If there are some wrong,i consider you should check your code:
public Actor hit(float x, float y)