LibGdx How to Scroll using OrthographicCamera? - java

I have been looking for 10 hours (literally) and I'm done, I need to ask. Thing is I'm learning How use LibGdx to program Java games. I'm doing a Horizontal Space Ship Game. So, my worst problem here is that I do not know how do scroll (I think draw will explain better). I want to draw a huge background (Space) and make my OrthographicCamera move right like with my SpaceShip, so it will create a Scroll effect with the Space Background. No enemies and nothing but the ship on the screen.
I'm trying this:
public void moveCamera(float x,float y){
cam.position.set(x, y, 0);
}
Then I use that method in my WorldRender render() method:
public void render(float delta){
ship.Move(delta);
moveCamera(ship.getPosition().x,ship.getPosition().y);
cam.update();
System.out.println(""+cam.position);
spriteBatch.begin();
drawBackground();
drawShip();
spriteBatch.end();
}
I actually move the camera position (I can see that thanks to the println), but It isn't moving in the game, so SpaceShip just disappears by the edge of the window.
I also tried this before spriteBatch.end()
spriteBatch.setProjectionMatrix(camera.combined);
but when I do that windows only shows a black screen, no ship, no nothing.
As I said, I'm desperate, I see lot of examples (scroll with mouse, paralexscrolling etc) but all are to advanced or just nothing to do with my code.
This is how I draw stuff. Background and ship are textures inside WorldRender. I draw background image very wide, so my intention is do some scrolling over as I said. That's the code
private void loadTextures(){
shipTexture=new Texture(Gdx.files.internal("nave.png"));
background=new Texture(Gdx.files.internal("fondo.jpg"));
}
public void drawShip(){
spriteBatch.draw(shipTexture,ship.getPosition().x*ppuX,ship.getPosition().y*ppuY, ship.WIDTH*ppuX,ship.HEIGHT*ppuY);
}
public void drawBackground(){
spriteBatch.draw(background, -10*ppuX,0*ppuY, Gdx.graphics.getWidth()*10,Gdx.graphics.getHeight());
}
Here you can download the code if someone want to help in hardcore mode
My code (not working)
I FINALLY SOLVED IT!
That's the code I used in a class name WorldRenderer, which have methods that are called within GameScreen for render, resize etc
public WorldRenderer(World world) {
// TODO Auto-generated constructor stub
this.world=world;
this.ship=world.getShip();
this.cam = new OrthographicCamera(CAMERA_WIDTH,CAMERA_HEIGHT);
this.cam.setToOrtho(false,CAMERA_WIDTH,CAMERA_HEIGHT);
this.cam.position.set(ship.getPosition().x,CAMERA_HEIGHT/2,0);
this.cam.update();//actualizamos la camara
spriteBatch=new SpriteBatch();
loadTextures();
}
private void loadTextures(){
shipTexture=new Texture(Gdx.files.internal("nave.png"));
background=new Texture(Gdx.files.internal("fondo.jpg"));
}
public void drawShip(){
spriteBatch.draw(shipTexture,ship.getPosition().x,ship.getPosition().y,10,10);
}
public void drawBackground(){
spriteBatch.draw(background, 0,0, 500,50);
}
public void render(float delta){
ship.Move(delta);
moveCamera(ship.getPosition().x);
spriteBatch.setProjectionMatrix(cam.combined);
spriteBatch.begin();
drawBackground();
drawShip();
spriteBatch.end();
}
public void moveCemara(float x){
cam.position.set(x+20,cam.position.y, 0);
cam.update();
}
Inside the Ship I have this method which I call within render in WorldRenderer to move It
public void Move(float delta){
if(Gdx.input.isKeyPressed(Keys.LEFT)) this.position.x -=velocity *delta;
if(Gdx.input.isKeyPressed(Keys.RIGHT)) this.position.x +=velocity *delta;
if(Gdx.input.isKeyPressed(Keys.UP)) this.position.y +=velocity *delta;
if(Gdx.input.isKeyPressed(Keys.DOWN)) this.position.y -=velocity *delta;
}
Also I want to thanks very much to the people who helped me. I'm marking first answer as the good one, but, mix both was what gave me the real solution.
I leave here some tutorials I followed which are pretty good for noobs
That's a good everything-from-scratching-tutorial
LiGdxForNoobs
A simple platform game
platformGame
A very simple game
bucketGame

I can't tell if this is your only mistake, but this is ONE mistake. If this is what you say you were doing:
spriteBatch.begin();
drawBackground();
drawShip();
spriteBatch.setProjectionMatrix(camera.combined);
spriteBatch.end();
You wont see anything. When setProjectionMatrix is called inside a begin()/end() block. the current batch is flushed to the gpu. So, you are actually not drawing anything with the camera matrix. You should do this instead:
spriteBatch.setProjectionMatrix(camera.combined);
spriteBatch.begin();
drawBackground();
drawShip();
spriteBatch.end();
EDIT:
If you don't call that line, spriteBatch uses its own default camera (which wont notice your camera.update() modifications, so that's not what you want).
You should now pay more attention to the coordinates you are using. I'm not quite sure you really need the ppu conversion thing. To begin with, define everything in imaginary world coordinates, note that you'll see some stretching in your world.
public void drawShip(){
spriteBatch.draw(shipTexture,ship.getPosition().x,ship.getPosition().y, 10, 10);
}//your ship is 10 units wide and tall!
public void drawBackground(){
spriteBatch.draw(background, -10,0, 500, 100);
} //your background is 500 units wide, and 100 units tall
//camera setup
camera = new OrthographicCamera(50, 50);
//your camera will print to screen 50 units of your world
If you get to see a stretched world, try to understand how it's working (if you can't see anything, there is something wrong somewhere).
EDIT 2
I took a look at your code. First remove ppu's, as it obscures your code. You were setting your cam position to the ship.postion, while drawing at ship.position * ppu. Also your background was way too big (that's why you see it pixelated). You should see something reasonable with this. (someday you'll have to initialize your camera in another way to deal with stretching, but forget it until you understand how all works).
this.cam = new OrthographicCamera(CAMERA_WIDTH,CAMERA_HEIGHT);
public void drawShip(){
spriteBatch.draw(shipTexture, ship.getPosition().x ,ship.getPosition().y, 10, 10);
}
public void drawBackground(){
spriteBatch.draw(background, -CAMERA_WIDTH/2, -CAMERA_HEIGHT/2, 100, 100); //let bg begin where camera starts. (0,0)
}
public void render(float delta){
ship.Move(delta);
moverCamara(ship.getPosition().x, ship.getPosition().y);
spriteBatch.setProjectionMatrix(cam.combined);
spriteBatch.begin();
drawBackground();
drawShip();
spriteBatch.end();
}

Its not clear how your drawing? I'm not sure if your doing this approach correctly.. Can you provide details of your background and ship? Can you provide details on you background image, is it a huge image that your scrolling around or is it a repeated image you want to repeat as you scroll?
--EDIT--
ok i think i have an idea what might be up. I would normally apply the camera to the current context.
Place the following in your resize
public void resize(int width, int height) {
cam = new OrthographicCamera(width, height);
cam.translate(width / 2, height / 2, 0);
}
Place the following in the start of your render()
cam.position.set(posX,posY,0);
cam.update();
cam.apply(Gdx.gl10);
Gdx.gl.glClearColor(0,0,0,1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); // #14
This will make you have a clear screen with the origin set at the bottom left of the window. You should then draw your background first
spriteBatch.setProjectionMatrix(cam.combined);
spriteBatch.begin();
spriteBatch.draw(background,0,0,sizeX,sizeY);
spriteBatch.end()
see how that looks as you move your camera position posX and posY. Then add your ship to the mix
-- MORE EDITS ---
you can then calculate the posX and posY as
posX = defaultOffsetX+shipX
and so on..
Anyhow hope this helps
I'm still only learning myself so this might not be the best method.. but it seems to work.

I've edited your code. Have a look at the following:
public class WorldRenderer {
private World world;
private Ship ship;
private Texture shipTexture,background;
private SpriteBatch spriteBatch;
private OrthographicCamera cam;
float screenSizeX = 100;
float screenSizeY = 100;
float shipSizeX = 10;
float shipSizeY = 10;
public void setSize (int w, int h) {
cam = new OrthographicCamera(screenSizeX,screenSizeY);
}
public WorldRenderer(World world) {
this.world=world;
this.ship=world.getShip();
spriteBatch=new SpriteBatch();
loadTextures();
}
private void loadTextures(){
shipTexture=new Texture(Gdx.files.internal("nave.png"));
background=new Texture(Gdx.files.internal("fondo2.jpg"));
}
public void drawShip(){
spriteBatch.draw(shipTexture, ship.getPosition().x,ship.getPosition().y, shipSizeX,shipSizeY);
}
public void drawBackground(){
spriteBatch.draw(background, 0,0);
}
public void render(float delta){
ship.Move(delta);
moverCamara(ship.getPosition().x,ship.getPosition().y);
spriteBatch.setProjectionMatrix(cam.combined);
spriteBatch.begin();
drawBackground();
drawShip();
spriteBatch.end();
}
public void moverCamara(float x,float y){
cam.position.set(x, y, 0);
cam.update();
}
}
This way, your ship is always in the middle of the screen and the background moves. Hope this helps.

Related

Libgdx texture sizes, developing for bigger resolution than my laptop's

I'm currently working on a libgdx game and before I give it final touches I wanted to actually hear something from experienced users, that has been bothering me for a few days already.
If I want to support as many as possible devices, essentially I will be designing graphics for the biggest possible res ,which is then going to be scaled if needed, for smaller screens, right? How do I go about developing for a resolution that is even bigger than my laptop's(the 2015/16 gen phones). My laptop has a resolution of 1920x1080px and the S7 Samsung has 2k+ width.
Thank you!
I think what you are looking for is Viewports. You have to decide which strategy fits best your needs. For example a FitViewport always keeps the aspect ratio you define, which might lead to black bars on some devices.
When I personally develop with libgdx I place and size all objects relative to the screen width and height. This includes images, fonts, buttons, etc. This gives me a pretty consistent result across all devices because most devices today have a ratio 16:9 or something close to it. For developing an image larger than your screen size what's wrong with just using photoshop to create the image of the specified size?
Better you choose the screen with as 1280 and screen height as 800 and also use the fill viewPort . So you will be able to render your game in almost all the screens without the issue of stretching.
Viewport is the method which provided by the libgdx to solve this multi screen compatible issue . here i will post some sample code which you can use for the reference.
public class myGame extends ApplicationAdapter {
public OrthographicCamera camera;
public Viewport viewPort;
private SpriteBatch batch;
private BitmapFont myScoreFont;
private Texture texture;
public myGAme() {
}
#Override
public void create() {
myScoreFont = new BitmapFont(Gdx.files.internal(Constants.PATH_TO_MY_SCORE_FONT), true);
batch = new SpriteBatch();
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
texture = new Texture(Gdx.files.internal(Constants.PATH_TO_LEFT_BAR));
camera = new OrthographicCamera();
camera.position.set(0, 0, 0);
camera.update();
camera.setToOrtho(false, Constants.APP_WIDTH, Constants.APP_HEIGHT);
// Here is the viewport is setting up with the camera and the screen size
viewPort = new FillViewport(1280, 800, camera);
}
#Override
public void dispose() {
batch.dispose();
}
#Override
public void render() {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);
float deltaTime = Gdx.graphics.getDeltaTime();
batch.setProjectionMatrix(camera.combined);
batch.begin();
batch.draw(myScorefont,"Score",0,0);
batch.end();
}
#Override
public void resize(int width, int height) {
// the game area will be resized as per the screen size of the device
viewPort.update(width, height);
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}

Java/libGDX - issues with Actions.fadeIn() and Actions.fadeOut()

it's my first time posting and I'm self taught so be please gentle!
I've been building a bomberman replica game in libGDX using Game and Screen classes:
public class Main extends Game {
...
#Override
public void create() {
levelScreen = new LevelScreen(playerCount, new int[playerCount]);
levelScreen.level.addAction(Actions.sequence(Actions.alpha(0), Actions.fadeIn(2f)));
this.setScreen(levelScreen);
}
However when the game launches there is no fade effect.
public class LevelScreen implements Screen {
...
#Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 0.1f, 0.5f, 0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
level.act();
level.draw();
batch.end();
}
I want this levelScreen to fade in from black but it just doesn't!
When the round is over I want to fadeOut of this levelScreen to black, then fadeIn to a trophyScreen from black:
(From Main Class)
#Override
public void render() {
super.render();
if (endRoundTimer <= 0) {
trophyScreen = new TrophyScreen(playerCount, levelScreen.getScore());
levelScreen.level.addAction(Actions.sequence(Actions.fadeOut(1), Actions.run(new Runnable() {
#Override
public void run() {
setScreen(trophyScreen);
}
})));
}
}
And I've tried using the show() method in the TrophyScreen:
public class TrophyScreen implements Screen {
...
#Override
public void show() {
stage.addAction(Actions.sequence(Actions.alpha(0), Actions.fadeIn(1)));
}
I've done loads of searching and tried various things but no joy. I'm sure I'm missing something somewhere in a draw() or render() method that is preventing the fade Action from taking place.
UPDATE1
#Override public void draw() {
super.draw();
if (roundOver) {
this.getBatch().begin(); String s = String.format("%s", message);
font_text.draw(this.getBatch(), s, (90 + (2 * 30)), (this.getHeight() / 2));
this.getBatch().end();
}
For fading to work on actors, they must properly apply their own color's alpha in the draw method. And for an entire hierarchy of objects to fade at once, they must all also apply the parentAlpha parameter from the draw method signature.
So your draw method in any custom Actor subclass should look like this:
public void draw (Batch batch, float parentAlpha) {
Color color = getColor();
batch.setColor(color.r, color.g, color.b, color.a * parentAlpha);
//..do drawing
}
If you are using a Sprite in your Actor instead of a TextureRegion (which I don't recommend due to redundancies) you must apply the color to the Sprite instead of Batch.
Note that this method of fading the whole game is not a "clean" fade. Any actors that are overlapping other actors will show through each other when the parent alpha is less than 1 during the fade. An alternative that would provide a clean-looking fade would be to draw a copy of your background (or black) over your entire scene and fade that instead.
I assume that level is an object of class that extends Stage and you are creating a control inside the stage, which is weird. You are not appling color to your font_text which I assume it is a BitmapFont
Solution, the weird way
If you want to do it in this way you will need something like that:
#Override public void draw() {
super.draw();
if (roundOver) {
getBatch().begin();
String s = String.format("%s", message);
font_text.setColor(getRoot().getColor())
font_text.draw(this.getBatch(), s, (90 + (2 * 30)), (this.getHeight() / 2));
getBatch().end();
}
}
getRoot() gets Group from Stage, we do it, because every action applied to Stage is actually applied to this Group root element. We get color (which has alpha channel) and we copy the color to the bitmapFont.
This solution is weird, because you are actually creating an Label inside Stage. It is pointless, actors plays on stage, not inside.
Solution, the good way
You want to draw text, right? So just use Label which is an actor, who shows a text. Actors do jobs for you:
stage = new Stage();
Label.LabelStyle labelStyle = new Label.LabelStyle(bitmapFont, Color.WHITE);
Label label = new Label("Hi, I am a label!", labelStyle);
stage.addActor(label);
Then you can apply actions and they will work fine (and every actor can have own actions applied).
stage.addAction(Actions.sequence(Actions.alpha(0), Actions.fadeIn(5)));
label.addAction(Actions.moveBy(0, 300, 15));
There is a lot of different actors like TextButton, Image, ScrollPane. They are customizable, easy to manage and they can be integrated in groups and tables.
Output:
A better way would be to just start by drawing a black image over everything, so you don't have to mess with every scene object's alpha. Use layering to do that. This post may be helpful.
Then you can control it's alpha channel, change it's rendering to 0 right before unpausing the game action to get it's drawing cycles back. Reactivate it on stage ending for your fade out effect.
Thank you cray, it's way better like this.

libgdx - moving an object

So, I'm farely new to programming this is my first game, and I have been working on it for a while, for one of my classes and I'm creating a pong game just changed it up a bit and I'm having trouble moving my paddle from the left to the center everytime I change the the percentage of the width of the screen to move it for some reason it elevates the paddle by all almost the same. Also everything is controlled by the width for some bizarre reason its almost like the field.height has no effect on moving it? I'm stuck right here and I'm so close to finishing it I'm trying to lower the paddle to the bottom center? any help would really be appreciated and hopefully this makes sense.
here is the field
#Override
public void create () {
field.set(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
fieldLeft = field.x;
fieldRight = field.x + field.width;
fieldBottom = field.y;
fieldTop = field.y + field.height;
and here is the paddle movement
private void resetRectangle(){
paddle1.move(field.x + (field.width * .5f, 0);
paddle2.move(0,0);
}
and the class
public class Paddle extends GameShare{
private ShapeRenderer paddleRenderer;
protected Paddle() {
super(100, 32);
}
public void paddleCreate(){
paddleRenderer = new ShapeRenderer();
}
public void paddleRender(float dt){
paddleRenderer.begin(ShapeType.Filled);
drawPaddle(dt);
paddleRenderer.end();
}
private void drawPaddle(float dt) {
paddleRenderer.rect(this.getX(), this.getX(), this.getWidth(), this.getHeight());
paddleRenderer.rect(this.getX(), this.getX(), this.getWidth(), this.getHeight());
}

ActiveRendering - Drawing on Buffer not working

I am creating a pong game. I have fininshed the ball and paddle classes, the animator and everything else related. However when I open my created program only 1 paddle shows, while the other paddle and the ball do not show. If I change the way I draw things, the ball will show and the other 2 paddles don't. So it only draws 1 thing, whatever comes first. Here is the code for part which paints to the buffer.
public void renderlojen(){ // render game function
if(pamja==null){
pamja=createImage(GJERESIA,LARTESIA); // Image - serves as buffer
}
g =(Graphics2D) pamja.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, GJERESIA, LARTESIA);
doreza1.vizatodorezen(g); // paddle1
doreza2.vizatodorezen(g); // paddle2
topi1.vizatotopin(g); // ball
g.dispose();
}
public void updatolojen(){ // update game function
topi1.leviztopin();
doreza1.levizdorezen();
doreza2.levizdorezen();
}
public void pikturolojen(){ // draw from buffer to screen
if (pamja!=null){
g=(Graphics2D)this.getGraphics();
g.drawImage(pamja, 0, 0, null);
Toolkit.getDefaultToolkit().sync();
g.dispose();
System.out.println(doreza1.merrX());
System.out.println(doreza2.merrX());
}
else
System.out.println("Ska pamje");
}
public void vizatotopin(Graphics2D g2d){ // draw the ball code
topiforma =new Ellipse2D.Float(pozicioniX,pozicioniY,2*rrezja,2*rrezja);
g2d.setColor(Color.CYAN);
g2d.fill(topiforma);
g2d.dispose();
}
public void vizatodorezen (Graphics2D g2d){ // draw paddle code
drejtkendeshforma = new Rectangle2D.Float(pozicioniX,pozicioniY,GJERESIA,LARTESIA);
g2d.setColor(ngjyra);
g2d.fill(drejtkendeshforma);
g2d.dispose();
}
The problem is calling Graphics.dispose() in the rendering methods of the game objects. Drawing to the Graphics is not valid after that, so only the first object gets drawn.
In general, call Graphics.dispose() only in the same method where you created it. Not in methods that receive one as a parameter.

libGdx - image background

I have problem with background in libGdx.
I try solve mine problem with this:
"In your create() method, create a new Texture referencing your image.png, and then use your existing SpriteBatch to render it in the render() loop. Immediately after your GL.clear() call, go your batch.draw(backgroundTexture, 0. 0) and make sure you're in OrthographicProjection mode for your camera."
I do this:
public void render() {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
camera.update();
batch.setProjectionMatrix(camera.combined);
batch.begin();
batch.draw(image, 250, 200);
batch.draw(backGroundImage, 0, 0);
batch.end();
"image" is mine normal Texture (it's simple image), "backGround" is ofc. mine background.
I have "backGround" apply in mine create() method. Mine camer is on camera = new OrthographicCamera();.
Here is what I see:
... I need 10 points of reputation to add image :<... Image is to short and cut on lef and right...
What I doing wrong. On this solution a link! And a reference-style link to [a panda][1] Shinzul said something about loop in in render(), maybe this is mine problem but I dont know how to fix this.
Please help.
I think you should draw your backgroung image first.
Besides I think you should look at some tutorials, e.g. https://github.com/libgdx/libgdx/wiki/Spritebatch%2C-Textureregions%2C-and-Sprites. It explains same basic concepts of libgdx.
public static Texture backgroundTexture;
public static Sprite backgroundSprite;
private SpriteBatch spriteBatch;
private void loadTextures() {
backgroundTexture = new Texture("images/background.png");
backgroundSprite =new Sprite(backgroundTexture);
.
.
}
public void renderBackground() {
backgroundSprite.draw(spriteBatch);
}
public void render() {
spriteBatch.begin();
renderBackground(); //In first place!!!!
drawStuff();
drawMoreStuff();
drawMoreMoreStuff();
spriteBatch.end();
}
I found this online resource and helped me get started in the world of libgdx.
I hope I've been helpful.
Simply you can set device hight and width using Gdx, its help me
batch.draw(mTextureBg, 0 , 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
I don't know if this is the best way to do it but it worked for me.
sprite.scale(2);
sprite.setCenter(Gdx.graphics.getWidth()/2, Gdx.graphics.getHeight()/2);
You can change the scale in (int) until it covers the whole screen.

Categories