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()
}
Related
My app provides two buttons in a table row. Each image has a width of 300 pixel (source). The app shows all parts of both buttons if I provide an initial window width which is greater than 600. Even resizing the window to a smaller size works smoothly. Both buttons are shown fully and they get scaled down if needed when resizing the window. The buttons are cut off once I provide an initial window size which is smaller than 600 pixel. How can I show the whole buttons on small screens by default?
Screenshots:
My code looks like this:
public class LevelChooserState extends GameState {
private Stage stage;
private Texture bgTexture;
private Pixmap bgPixmap;
private Viewport viewportStage;
private Container<Table> container;
private Table table;
public LevelChooserState(final GameStateController gsc) {
super(gsc);
Gdx.app.log(TAG, "Setup Level Chooser State.");
// Setup Background Color
bgPixmap = new Pixmap(1, 1, Pixmap.Format.RGB565);
bgPixmap.setColor(Color.WHITE);
bgPixmap.fill();
bgTexture = new Texture(bgPixmap);
TextureRegionDrawable textureRegionDrawableBg = new TextureRegionDrawable(new TextureRegion(bgTexture));
// Setup viewports
viewportStage = new ExtendViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
viewportStage.setScreenBounds(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
// Setup stage
stage = new Stage(viewportStage);
Gdx.input.setInputProcessor(stage);
// Setup font
int Help_Guides = 12;
int row_height = Gdx.graphics.getWidth() / 12;
FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("fonts/PatrickHand-Regular.ttf"));
FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
parameter.size = 30;
parameter.borderWidth = 1;
parameter.color = Color.BLACK;
BitmapFont myFont = generator.generateFont(parameter);
generator.dispose();
// Setup background pictures
TextureAtlas textureAtlas = new TextureAtlas("atlas/onoff.atlas");
TextureRegion backgroundTR1 = textureAtlas.findRegion("onoff_off");
TextureRegion backgroundTR2 = textureAtlas.findRegion("onoff_on");
// Setup TextButtons
TextureRegionDrawable up1= new TextureRegionDrawable(backgroundTR1);
TextureRegionDrawable down1= new TextureRegionDrawable(backgroundTR2);
TextureRegionDrawable checked1= new TextureRegionDrawable(backgroundTR2);
String text1 = "Deceptive dance in the poultry house.";
ClickListener clickListner1 = new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
Gdx.app.log(Constants.TAG, "Button click received.");
gsc.setState(GameStateController.State.PLAY);
}
};
TextButton textButton1 = createTextButton(myFont, text1, up1, down1, checked1, clickListner1);
// ... created some more buttons at this point
// Setup Layout
container = new Container<Table>();
container.setBounds(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
container.setBackground(textureRegionDrawableBg);
container.align(Align.bottomLeft);
table = new Table();
table.setBounds(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
table.setTouchable(Touchable.enabled);
table.setDebug(true);
table.debugAll();
table.setBackground(textureRegionDrawableBg);
table.setFillParent(true);
table.align(Align.top);
// TODO take care of scaling too when setting padding
float padding = 10;
table.row();
table.add(textButton1).expandX().pad(padding);
table.add(textButton2).expandX().pad(padding);
table.row();
table.add(textButton3).expandX().pad(padding);
table.add(textButton4).expandX().pad(padding);
table.row();
container.setActor(table);
stage.addActor(container);
}
private TextButton createTextButton(BitmapFont font, String text, TextureRegionDrawable up, TextureRegionDrawable down, TextureRegionDrawable checked, ClickListener clickListener) {
Label.LabelStyle labelStyle = new Label.LabelStyle();
labelStyle.font = font;
Label label = new Label(text,labelStyle);
label.setWrap(true);
TextButton.TextButtonStyle style = new TextButton.TextButtonStyle();
style.up = up;
style.down = down;
style.checked = checked;
style.font = font;
TextButton button = new TextButton(label.toString(), style);
//button.setSize(50,100);
button.setLabel(label);
button.getLabelCell().pad(20f);
button.getLabel().setAlignment(Align.topLeft);
button.setPosition(0,0);
button.addListener(clickListener);
return button;
}
#Override
public void update(float delta) {
}
#Override
public void render() {
Gdx.gl.glClearColor(1f,1f,1f,1f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined);
batch.begin();
stage.getViewport().apply();
stage.draw();
stage.act();
batch.end();
}
#Override
public void dispose() {
Gdx.app.log(TAG, "dispose(); Level Chooser");
stage.dispose();
bgPixmap.dispose();
bgTexture.dispose();
}
#Override
public void resize(int w, int h) {
Gdx.app.log(TAG, "resize() LevelChooserState;");
stage.getViewport().update(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), true);
container.setFillParent(true); // makes sure the container will expand on resize
}
}
LibGDX uses real-pixel-to-screen-pixel mapping.
You're using an ExtendViewport to initialize the game, which takes its minimum height and width from the actual window size in Gdx.graphics.getWidth(), Gdx.graphics.getHeight().
This means that the 'fake screen' you have, which you can then resize as much as you want, is actually determined by the size of the window.
I would advise you start with a fixed size for the ExtendViewport - say, 600 width, 400 height - and later you can change this to suit different sizes if necessary.
ExtendViewport with fixed sizes works fantastically well, even when displaying on extremely large screens.
It works smoothly once I calculate and set the desired button manually. Width and height are calculated depending on screen size.
I changed this:
table.add(textButton1).expandX().pad(padding);
to this:
float buttonWidth = Gdx.graphics.getWidth()/2 * 0.9f;
float buttonHeight = buttonWidth * 1.3f;
table.add(textButton1).width(buttonWidth).height(buttonHeight).expandX().pad(padding);
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.
As you can see in my code below, I create a camera using the width and height of the device target. Then I create stage with the size of the camera viewport and add a Window to it (everything works fine till here in any device).
However, when add a TextButton to the Windows is not re-sized accordingly to the Stage size.
So, how can I re-size a TextButton to looks good in any device?
#Override
public void create() {
.
.
.
// Define camera our view port in meters because of Box2D
camera = new OrthographicCamera(20,
20 * (Gdx.graphics.getHeight() / (float) Gdx.graphics.getWidth()));
// create stage with the size of the viewport
stage = new Stage(new StretchViewport(camera.viewportWidth,camera.viewportHeight));
// create restart button
atlas = new TextureAtlas("data/ui/atlas.pack");
skin = new Skin(Gdx.files.internal("data/ui/menu_skin.json"), atlas);
TextButton restartButton = Util.createTextButton("Restart", skin, "red",
new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
timer=timeMax;
}
});
// create a window and add the restart to it
skin.add("texture", new Texture("data/texture.png"));
WindowStyle windowStyle = new WindowStyle(new BitmapFont(), Color.WHITE, skin.newDrawable("texture"));
windowTryAgain = new Window("", windowStyle);
windowTryAgain.setMovable(false);
//windowTryAgain.padTop(20);
//stage.addActor(window);
windowTryAgain.setPosition(0, 0);
windowTryAgain.setSize(2,2);
windowTryAgain.row().fill().expandX();
windowTryAgain.add(restartButton).fill(0f, 0f);
windowTryAgain.center();
windowTryAgain.setVisible(false);
stage.addActor(windowTryAgain);
.
.
.
}
public class Util {
public static TextButton createTextButton(String text, Skin skin,
String styleName, EventListener listener) {
TextButton textButton = new TextButton(text, skin, styleName);
textButton.pad(10);
//Set height does not work in my case
//textButton.setHeight(0.1f);
textButton.addListener(listener);
return textButton;
}
}
You can make a secondary camera and attach it to your stage. To scale the table just scale the viewport size of the secondary camera
An example would be:
//Heres where you set the scale of your buttons and your table
Camera secondaryCamera = new Camera(Gdx.graphics.getWidth() * scale,
Gdx.graphics.getHeight() * scale);
Stage stage = new Stage();
Table table = new Table();
ImageButton button = new ImageButton(drawableUp, drawableDown, drawableChecked);
table.setFillParent(true);
stage.getViewport().setCamera(secondaryCamera);
table.add(ImageButton);
stage.addActor(table);
This works great when your using it for touch controls. You can use a table for the entire UI and scale it to your liking independent of your other game items;
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.
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)