So i am creating a game where i will draw a background but this background doesen't cover the whole screen, even when i lower the window size it doesen't cover the whole window. Here is the code for drawing the background:
Gdx.gl20.glClearColor(0.2F, 0.6F, 1F, 1F);
Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT);
cam.update();
sb.setProjectionMatrix(cam.combined);
sb.begin();
sb.draw(Assets.splash_spr_background, 0, 0);
sb.end();
And here is the code for initializing the sprite:
public static Texture splash_tex_background;
public static Sprite splash_spr_background;
public static void init()
{
splash_tex_background = new Texture(Gdx.files.internal("Splash Screen/background.png"));
splash_tex_background.setFilter(TextureFilter.Linear, TextureFilter.Linear);
splash_spr_background = new Sprite(splash_tex_background);
}
And finally here is the code for initializing the camera & spritebatch stuff:
cam = new OrthographicCamera();
cam.setToOrtho(false, 1920, 1080);
sb = new SpriteBatch();
Now here is my question: Why does this not work? What have i done wrong?
Thanks for any help! :)
You don't need 1920x1080 resolution for the game. That's clearly an overkill. Imagine that someone with a lower spec device will play it.
So you can just set the screen to match the background:
cam.setToOrtho(false, 1280, 720);
If you really need the resolution, you can stretch the background like this:
background.setWrap(Texture.TextureWrap.ClampToEdge, Texture.TextureWrap.ClampToEdge);
Related
I have a 540x720 background image.
I need to show it in full screen regardless of screen size and resolution (My game will run on desktop and on Android) and regardless of portrait/landscape mode.
I want to keep the aspect ratio of the image, if necessary by cropping the image.
I have already tried ScreenViewport and ExtendViewport but when resizing the window, the background is no longer full screen (for example if the window becomes horizontal) and letter-boxing occurs (showing white side bars).
public class MainMenuScreen implements Screen, InputProcessor {
final MyGame game;
TextureRegionDrawable textureRegionDrawableBackground = new TextureRegionDrawable(new TextureRegion(new Texture(game.backgroundFileName)));
Stage stageBackground = new Stage(new ScreenViewport());
// Stage stageBackground = new Stage(new ExtendViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight())));
Image image = new Image(textureRegionDrawableBackground);
image.setPosition(0, 0);
image.setHeight(Gdx.graphics.getHeight());
// makes the background as tall as the screen while maintaining its aspect ratio
image.setWidth(Gdx.graphics.getHeight() * textureRegionDrawableBackground.getRegion().getRegionWidth() / textureRegionDrawableBackground.getRegion().getRegionHeight());
stageBackground.addActor(image);
}
public void render(float delta) {
stageBackground.getViewport().apply();
stageBackground.draw();
}
public void resize(int width, int height) {
stageBackground.getViewport().update(width, height, true);
}
How to achieve that?
Thanks
Use FillViewport which will maintain aspect ratio and be full screen by cropping part of the image.
See here
https://gamefromscratch.com/libgdx-tutorial-part-17-viewports/
Ok, I'm making a monopoly-like game where in the game-loop activity I have a fragment with a LibGDX inside, which represents the 3D board with pieces. I've been struggling in the last few days figuring out how can I create additional ModelInstances after the activity has loaded and the create() method in the LibGDX class has ended. Here is the Demo3D.java holding the board and pieces:
#Override
public void create() {
pieces = new ArrayList<ModelInstance>();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 1f, 1f, 1f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
camera = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
camera.position.set(0f, 1.6f, -4f);
camera.lookAt(0f, 0f, 0f);
camera.near = 0.01f;
camera.far = 12f;
mapTexture = new Texture("monopoly_board.jpg");
mapSprite = new Sprite(mapTexture, 1024, 1024);
modelBatch = new ModelBatch();
modelBuilder= new ModelBuilder();
board = new Board3D(mapSprite, mapSprite);
board.worldTransform.rotate(Vector3.X, 270);
board.worldTransform.rotate(Vector3.Z, 180);
board.worldTransform.translate(0, 0, 0);
createPiece("blue");
createPiece("green");
Gdx.input.setInputProcessor(this);
}
#Override
public void render() {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
camera.update();
modelBatch.begin(camera);
modelBatch.render(board);
for (ModelInstance piece: pieces) {
modelBatch.render(piece, environment);
}
modelBatch.end();
}
// Some other methods...
public void createPiece(String pieceColor){
// Some logic...
ModelInstance mi = new ModelInstance(modelBuilder.createCone(0.2f, 0.4f, 0.2f, 20,
pieceMat,
VertexAttributes.Usage.Position|VertexAttributes.Usage.Normal), -1.95f, 0.1f, -2.2f);
pieces.add(mi);
render();
}
So I basically need to be able to call a method from the activity/model which would result in invoking
createPiece(String color) in the Demo3D class, resulting in a new piece shown on the board.
I tested calling the createPiece() from the outside and it creates a new piece and shows it but the board disappears. I tried calling render() at the end of createPiece() and in this case the board doesn't disappear but the newly created piece is not present... Couldn't dig anything up so I'd be glad if someone helps..
Cheers
So I decided to make a button "Start" which when pressed gets all the players and creates pieces for every player. This is the Listener:
((Button) findViewById(R.id.populate)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boardFragment.populatePieces(currentGame.getPlayers());
rollDice.setVisibility(View.VISIBLE);
v.setVisibility(View.INVISIBLE);
}
});
Where the boardFragment.populatePieces(Arrl<Players>) is:
for (Player p: players){
instance.createPiece(p.getTokenColor());
}
The odd thing is that yesterday I decided to test this out without any changes and in Genymotion it runs perfectly, adding and removing pieces with no problems at all /Running HTC One X in Geny/. But just few hours ago I decided to test it out on my physical device and there it is the problem again... My device is Huawei Mate 7 with Lolipop 5.1
Update: It turns out the app doesn't work properly on Lollipop devices haven't tested it out on physical devices with Android 4/6, but in Genymotion everything is smooth with 4/6 devices..
I believe you need to make sure that in your drawScene() method, you iterate over the pieces collection and draw/render each component.
I'm trying to create a game with LibGDX. My problem comes when I put the background in the screen that I have. I created a Base Screen (abstract) in order to make easier. In Desktop, the screen fits good, but in Android, trying different devices, the screen doesn't scale to full screen. I solved this situation using the next easy code:
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(texture, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.end();
}
That was enough to see my game in full screen on android devices. Now, I want to use Scene2D(which I don't know so much...) So I create a Stage, I'm dealing with the background like an actor. Here's my code.
public class MenuScreen extends BaseScreen {
private FitViewport viewport;
private Stage stage;
private Image imageFondo, imagePrueba;
//private float escala;
public MenuScreen(MissingWords missingwords) {
super(missingwords);
}
#Override
public void show() {
//viewport = new StretchViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
viewport = new FitViewport(800, 480);
stage = new Stage(viewport, missingwords.getSB());
//Gdx.input.setInputProcessor(stage);
/* Crear fondo */
imageFondo = new Image(missingwords.getAM().get("fondo.png", Texture.class));
stage.addActor(imageFondo);
imagePrueba = new Image(missingwords.getAM().get("prueba.png", Texture.class));
imagePrueba.setPosition(50, 50);
stage.addActor(imagePrueba);
}
#Override
public void render(float delta) {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act();
stage.draw();
}
#Override
public void resize(int width, int height) {
stage.getViewport().update(width, height, true);
}
However, it doesn't work and I don't know if I'm using the Viewports in the correct way. How can I write this line in order to be compatible with Scene 2D and support android devices?
batch.draw(texture, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Thanks in advance.
Finally I "solved" it using a ScalingViewport. Like this:
viewport = new ScalingViewport(Scaling.stretch, 800, 480);
Scaling.stretch as javadoc says: the world is scaled to take the whole screen. So, it doesn't keep the aspect ratio but for me is good. Maybe it looks wrong using large screens, but I'm still learning and I don't know if this is the best solution. So, I hope this helps someone.
I'm trying to load a simple background texture for the menu of a game I'm creating, but the texture isn't displayed properly.
For example, if I use this texture: http://s15.postimage.org/mqvuhq463/Super_Mario_Galazy_Background.png the entire background is blue and if I use this texture: http://www.highresolutiontextures.com/wp-content/uploads/2010/11/food-textures-01-bowtie-pasta-texture.jpg the entire background is a shade of orange.
This is the code I've written:
public class Menu extends Painter
{
public Menu(GLCanvas canvas, Animator animator, GameWindow window)
{
super(canvas, animator, window);
}
#Override
public void display(GLAutoDrawable drawable)
{
GL gl = drawable.getGL();
drawBackground(gl);
gl.glFlush();
}
private void drawBackground(GL gl)
{
Texture background = textureLoader.getTexture("background");
background.enable();
background.bind();
gl.glBegin(GL.GL_QUADS);
gl.glVertex2f(0f, 0f);
gl.glVertex2f(0f, window.getHeight());
gl.glVertex2f(window.getWidth(), window.getHeight());
gl.glVertex2f(window.getWidth(), 0);
gl.glEnd();
background.disable();
}
#Override
public void init(GLAutoDrawable drawable)
{
GL gl = drawable.getGL();
textureLoader = new TextureLoader("menu textures/", gl);
gl.glMatrixMode(GL.GL_PROJECTION);
gl.glLoadIdentity();
// set ortho to the size of the background
gl.glOrtho(0, 800, 800, 0, -1, 1);
gl.glMatrixMode(GL.GL_MODELVIEW_MATRIX);
gl.glClearColor(0f, 0f, 0f, 0f);
gl.glClear(GL.GL_COLOR_BUFFER_BIT);
}
}
I haven't got the slightest clue how this is even possible, so any help would be greatly appreciated.
You don't supply texture coordinates. Without texture coordinates all vertices receive the default texture coordinate, which is (0,0,0,0), which is the bottom left corner. If you look at your texture images the colors you see, are the colors of the bottom left pixel of each picture.
Solution: Supply texture coordinates. Texture coordinates are in the range [0; 1].
I'm seriously betting that I did something effing stupid and just can't seem to notice it.
package com.me.mygdxgame;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
public class Locked implements ApplicationListener
{
private OrthographicCamera camera;
private SpriteBatch batch;
private Texture texture;
private Sprite sprite;
private BitmapFont font;
private CharSequence str = "Hello World!";
private float width;
private float height;
#Override
public void create()
{
width = Gdx.graphics.getWidth();
height = Gdx.graphics.getHeight();
camera = new OrthographicCamera(1, height / width);
batch = new SpriteBatch();
texture = new Texture(Gdx.files.internal("data/libgdx.png"));
texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
TextureRegion region = new TextureRegion(texture, 0, 0, 512, 275);
sprite = new Sprite(region);
sprite.setSize(0.9f, 0.9f * sprite.getHeight() / sprite.getWidth());
sprite.setOrigin(sprite.getWidth() / 2, sprite.getHeight() / 2);
sprite.setPosition(-sprite.getWidth() / 2, -sprite.getHeight() / 2);
font = new BitmapFont(Gdx.files.internal("data/digib.fnt"),
Gdx.files.internal("data/digib.png"), false);
}
#Override
public void dispose()
{
batch.dispose();
texture.dispose();
}
#Override
public void render()
{
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined);
batch.begin();
font.setColor(0.0f, 0.0f, 0.0f, 1.0f);
//sprite.draw(batch);
font.draw(batch, str, width*0.5f, height*0.5f);
batch.end();
}
#Override
public void resize(int width, int height)
{
}
#Override
public void pause()
{
}
#Override
public void resume()
{
}
}
The project was generated with the template tool they provide gdx-setup-ui.jar
As you can see in the code, I didn't bother to get rid of the default codes (Just some simple draw codes to render the LibGDX logo).
So, with the cleanly generated project, I followed this guide here
http://code.google.com/p/libgdx-users/wiki/addingText2D
and finally arriving with the provided code above.
The problem is, why won't the !##$ing text show!? I changed the position so many times and still no luck :\
Did I miss something?
FYI: The fonts are fine, I dropped them into another game and it works.
Try to change projection matrix like this:
Matrix4 normalProjection = new Matrix4().setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.setProjectionMatrix(normalProjection);
All I do is
spriteBatch = new SpriteBatch();
font = new BitmapFont(Gdx.files.internal("data/nameOfFont.fnt"),
Gdx.files.internal("data/nameOfFont.png"), false);
and in render method
spriteBatch.begin();
font.setColor(1.0f, 1.0f, 1.0f, 1.0f);
font.draw(spriteBatch, "some string", 25, 160);
spriteBatch.end();
You can read something more about it on my blog: http://algorhymes.wordpress.com/2012/11/17/javalibgdx-fonts/
Personally I'm not a big fan of converting all the fonts to .fnt format. If you need different sizes for a certain font you have to spend a lot of time (and app space) to make all the conversions.
You can just use the FreeType Extension and load straight from a .ttf
FreeTypeFontGenerator generator = new FreeTypeFontGenerator(fontFile);
BitmapFont font15 = generator.generateFont(15);
BitmapFont font22 = generator.generateFont(22);
generator.dispose();
More info here
Rendering is done in the same way as explained by watis.
create a .fnt file using hiero which is provided by libgdx website
set the size of font 150 ,it will create a .fnt file and a png file
copy both of file in your assests folder
now declare the font
BitmapFont font;
nw in create method
font = new BitmapFont(Gdx.files.internal("data/100.fnt"), false);//100 is the font name you can give your font any name
in render
font.setscale(.2f);
font.draw(batch, "whatever you want to write", x,y);
this will work smoothly
The main problem with your code is that you have created camera with
viewportWidth = 1 &
viewportHeight = width/height
and you are drawing font at width*0.5f & height*0.5f which is out of scope from camera
Either change the camera initialization to
camera = new OrthographicCamera(width, height);
....
or change the draw font statement to
font.setScale(1,height/width);
font.draw(batch, str, 0.5f, height/width*0.5f);
Did you try giving position manually like this. I hope this will work
batch.setProjectionMatrix(camera.combined);
batch.enableBlending();
batch.begin();
font.draw(batch, yourString, 100,100);
batch.end();