Sprites appear as white boxes - android

I have a simple LibGdx application with two sprites. One is a simple texture which is repeated to fill the background. This one works. The other is a texture which is alpha blended so the corners look darker than the center. It is stretched to cover the entire screen. For some reason, this one appears in the wrong location and is just a big white box.
Here is my code:
public class TestGame extends ApplicationAdapter {
SpriteBatch batch;
boolean showingMenu;
Texture background;
Sprite edgeBlur;
Texture edgeBlurTex;
#Override
public void create() {
showingMenu = true;
batch = new SpriteBatch();
background = new Texture(Gdx.files.internal("blue1.png"));
edgeBlurTex = new Texture(Gdx.files.internal("edge_blur.png"));
edgeBlur = new Sprite(edgeBlurTex);
edgeBlur.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
}
#Override
public void resize(int width, int height) {
super.resize(width, height);
edgeBlur.setSize(width, height);
}
#Override
public void dispose() {
background.dispose();
edgeBlurTex.dispose();
super.dispose();
}
#Override
public void render() {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
drawBackground();
batch.end();
}
private void drawBackground() {
for (float x = 0; x < Gdx.graphics.getWidth(); x += background.getWidth()) {
for (float y = 0; y < Gdx.graphics.getHeight(); y += background.getHeight()) {
batch.draw(background, x, y);
}
}
edgeBlur.draw(batch);
}
}
Edit:
I fixed it by changing the draw command to:
batch.draw(edgeBlurTex, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
However the if I attempt to do any drawing after drawing these textures, such as:
ShapeRenderer shapeRenderer = new ShapeRenderer();
shapeRenderer.begin(ShapeRenderer.ShapeType.Line);
shapeRenderer.setColor(0, 0, 0, 1);
float unitHeight = Gdx.graphics.getHeight() / 9;
float indent = Gdx.graphics.getWidth() / 20;
shapeRenderer.rect(indent, unitHeight, Gdx.graphics.getWidth() - indent * 2, unitHeight);
shapeRenderer.rect(indent, unitHeight * 3, Gdx.graphics.getWidth() - indent * 2, unitHeight);
shapeRenderer.rect(indent, unitHeight * 5, Gdx.graphics.getWidth() - indent * 2, unitHeight);
shapeRenderer.rect(indent, unitHeight * 7, Gdx.graphics.getWidth() - indent * 2, unitHeight);
shapeRenderer.end();
It just stops working and goes back to drawing a white box. It seems very random, like something is seriously misconfigured with libgdx. Is there any way to debug this thing to work out what is wrong?

you should add enableBlending before your blended texture draw
batch.enableBlending();
edgeBlur.draw(batch);
batch.disableBlending();
you can also try to set the batch blending func by using setBlendFunction method after batch is created
update due to edit:
the SpriteBatch should be ended when starting Shaperenderer

Related

LibGdx tilting an image

I'm trying to create a children's game using the LibGdx framework. What I want to accomplish is to tilt an image of a balloon that will be used to collect points. So far I have added code to move the balloon up/down. I'm unable to figure out how to tilt it to the right or left. Here is the code I have so far. Can someone please help
public class balloongame extends ApplicationAdapter {
SpriteBatch batch;
Texture background;
Texture balloon;
private float renderX;
#Override
public void create () {
batch = new SpriteBatch();
background = new Texture("bg.png");
balloon = new Texture("final.png");
renderX = 100;
}
#Override
public void render () {
renderX += Gdx.input.getAccelerometerX();
if(renderX < 0) renderX = 0;
if(renderX > Gdx.graphics.getWidth() - 200) renderX = Gdx.graphics.getWidth() - 200;
batch.begin();
batch.draw(background, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.draw(balloon,renderX, Gdx.graphics.getWidth());
batch.end();
}
#Override
public void dispose () {
batch.dispose();
}
}
I know two easy ways to do it.
Affine2 class have shear method in it.And similar transformation methods.
Affine2.shear()
After you set affine matrix you can draw it with
draw(TextureRegion region, float width, float height, Affine2 transform)
I prefer changing vertices attributes in draw method.
draw(Texture texture,
float[] spriteVertices,
int offset,
int count)
There must be 4 vertices, each made up of 5 elements in this order: x, y, color, u, v
batch.draw(textures[0], new float[]{
0, 0 ,Color.RED.toFloatBits(), 0f, 1f,
textures[0].getWidth(),50, Color.BLUE.toFloatBits(), 1f, 1f,
textures[0].getWidth(), 50+textures[1].getHeight(), Color.GREEN.toFloatBits(), 1f, 0f,
0 ,textures[0].getHeight(), Color.GOLD.toFloatBits(), 0f, 0f},0,20);
You can set individial colors for each vertice or simply can set color to white.
You can change it however you want.

Opengl ES 2.0 Depth test doesn't work properly

I'm trying to learn OpenGL ES 2.0 and I went to load 3d models on Android. I can now load properly with the model texture, but I have a problem on the display depth. When I place my model in perspective, and part of the model is hidden by another part of it, it happens to me that a triangle or two before another draw and this is what I see through some parts .
I try setEGLConfigChooser (8, 8, 8, 8, 16, 0); and (8, 8, 8, 8, 24, 0), but my problem remains the same, except that when I put (8, 8, 8, 8, 24, 0) and display a little better defined, but when the 3d object moves, the colors make a strobe effect that is disturbing to me.
I also try glDepthFunc function (GL_LEQUAL); with glEnable (GL_DEPTH_TEST), but this does not rule over my problem.
Here's the pictures of the probleme:
The probleme : Link is broken
The good : Link is broken
Sorry for my link picture, I do not have more than 10 reputation to post picture in the question.
Here my code
My GLSurfaceView
public MyGLSurfaceView(Context context) {
super(context);
this.context = context;
setEGLContextClientVersion(2);
setEGLConfigChooser(true);
//setZOrderOnTop(true);
//setEGLConfigChooser(8, 8, 8, 8, 16, 0);
//setEGLConfigChooser(8, 8, 8, 8, 24, 0);
//getHolder().setFormat(PixelFormat.RGBA_8888);
mRenderer = new Renderer(context);
setRenderer(mRenderer);
}
My renderer
#Override
public void onSurfaceCreated(GL10 glUnused, EGLConfig config) {
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glFrontFace(GL_CCW);
glEnable(GL_DEPTH_TEST);
mushroom = new Mushroom();
textureProgram = new TextureShaderProgram(context);
texture = TextureHelper.loadTexture(context, R.drawable.mushroom);
}
#Override
public void onSurfaceChanged(GL10 glUnused, int width, int height) {
glViewport(0, 0, width, height);
MatrixHelper.perspectiveM(projectionMatrix, 45, (float) width
/ (float) height, 0f, 10f);
setLookAtM(viewMatrix, 0, 0f, 1.2f, -10.2f, 0f, 0f, 0f, 0f, 1f, 0f);
}
#Override
public void onDrawFrame(GL10 glUnused) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
multiplyMM(viewProjectionMatrix, 0, projectionMatrix, 0, viewMatrix, 0);
glDepthFunc(GL_LEQUAL);
//glDepthMask(true);
positionMushroomInScene();
textureProgram.useProgram();
textureProgram.setUniforms(modelViewProjectionMatrix, texture);
mushroom.bindData(textureProgram);
mushroom.draw();
//glDepthFunc(GL_LESS);
}
private void positionMushroomInScene() {
setIdentityM(modelMatrix, 0);
translateM(modelMatrix, 0, 0f, 0f, 5f);
rotateM(modelMatrix, 0, -yRotation, 1f, 0f, 0f);
rotateM(modelMatrix, 0, xRotation, 0f, 1f, 0f);
multiplyMM(modelViewProjectionMatrix, 0, viewProjectionMatrix,
0, modelMatrix, 0);
}
My matrix Helper
public static void perspectiveM(float[] m, float yFovInDegrees, float aspect, float n, float f) {
final float angleInRadians = (float) (yFovInDegrees * Math.PI / 180.0);
final float a = (float) (1.0 / Math.tan(angleInRadians / 2.0));
m[0] = a / aspect;
m[1] = 0f;
m[2] = 0f;
m[3] = 0f;
m[4] = 0f;
m[5] = a;
m[6] = 0f;
m[7] = 0f;
m[8] = 0f;
m[9] = 0f;
m[10] = -((f + n) / (f - n));
m[11] = -1f;
m[12] = 0f;
m[13] = 0f;
m[14] = -((2f * f * n) / (f - n));
m[15] = 0f;
}
The problem is most likely with the way you set up your projection matrix:
MatrixHelper.perspectiveM(projectionMatrix, 45, (float) width
/ (float) height, 0f, 10f);
The 4th argument in your definition of this function is the near plane. This value should never be 0.0. It should typically be a reasonable fraction of the far distance. Choosing the ideal value can be somewhat of a tradeoff. The larger far / near is, the less depth precision you get. On the other hand, if you set the near value too large, you risk clipping off close geometry that you actually wanted to see.
A ratio of maybe 100 or 1000 for far / near should normally give you reasonable depth precision, without undesirable front clipping. You'll need to be a little more conservative with the ratio if you use a 16-bit depth buffer than if you have a 24-bit depth buffer.
For your purpose, try changing near to 0.1, and see how that works for you:
MatrixHelper.perspectiveM(projectionMatrix, 45, (float) width
/ (float) height, 0.1f, 10f);

Needs advice on Libgdx Scaling

This might be a simple question being addressed somewhere, but I can’t find it. I do hope someone can lead me to the right path. The design resolution for my application is 800x480. To maintain the correct aspect ratio on devices with higher resolution, I followed this post and managed to get the “black bar” (I used blue for testing) on both side on a bigger screen (nexus 7). However, it seems that the stage is not scaled to cover the screen. Please see screen shot bellow, blue colour are the Gdx.gl.glClearColor(0.5f, 1, 1, 1); black rectangular (800x480) is the actual Sprite.
Link to image
I am not sure where I went wrong. Any help is much appreciated. Code below:
private SpriteBatch batch;
private Texture splashTexture;
private Sprite splashSp;
TextureRegion splashTr;
Stage stage;
#Override
public void create() {
stage = new Stage();
batch = new SpriteBatch();
splashTexture = new Texture(Gdx.files.internal("img/splashTexture.png"));
splashTexture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
TextureRegion splashTr = new TextureRegion(splashTexture, 0, 0, 800, 480);
splashSp = new Sprite(splashTr);
Gdx.app.log("myapp", "Creating game");
}
#Override
public void render() {
Gdx.gl.glClearColor(0.5f, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
stage.draw();
batch.begin();
batch.draw(splashSp, 0, 0);
batch.end();
}
#Override
public void resize(int width, int height) {
Gdx.app.log("myapp", "width:" + width + " height:" + height);
Vector2 size = Scaling.fit.apply(800, 480, width, height);
int viewportX = (int)(width - size.x) / 2;
int viewportY = (int)(height - size.y) / 2;
int viewportWidth = (int)size.x;
int viewportHeight = (int)size.y;
Gdx.app.log("myapp", "viewportWidth:" + viewportWidth + " viewportHeight:" + viewportHeight);
Gdx.app.log("myapp", "viewportX:" + viewportX + " viewportY:" + viewportY);
Gdx.gl.glViewport(viewportX, viewportY, viewportWidth, viewportHeight);
stage.setViewport(800, 480, true);
Gdx.app.log("myapp", "Resizing game");
}
You need to set the camera and stage.
first declare a variable of camera like this
OrthographicCamera camera;
then in create method do this
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
camera.update();
mystage = new Stage(800, 480, false);
and in render method update the camera
camera.update();
worked fine for mee..

Galaxy Nexus slow with animations

I've edited this code to move the Rect instantiations out of the onDraw method. I've tested it on several devices.
public class BallBouncesActivity extends Activity {
BallBounces ball;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ball = new BallBounces(this);
setContentView(ball);
}
}
class BallBounces extends SurfaceView implements SurfaceHolder.Callback {
GameThread thread;
int screenW; //Device's screen width.
int screenH; //Devices's screen height.
int ballX; //Ball x position.
int ballY; //Ball y position.
int initialY ;
float dY; //Ball vertical speed.
int ballW;
int ballH;
int bgrW;
int bgrH;
int angle;
int bgrScroll;
int dBgrY; //Background scroll speed.
float acc;
Bitmap ball, bgr, bgrReverse;
boolean reverseBackroundFirst;
boolean ballFingerMove;
Rect toRect1, fromRect1;
Rect toRect2, fromRect2;
//Measure frames per second.
long now;
int framesCount=0;
int framesCountAvg=0;
long framesTimer=0;
Paint fpsPaint=new Paint();
//Frame speed
long timeNow;
long timePrev = 0;
long timePrevFrame = 0;
long timeDelta;
public BallBounces(Context context) {
super(context);
ball = BitmapFactory.decodeResource(getResources(), R.drawable.rocket); //Load a ball image.
bgr = BitmapFactory.decodeResource(getResources(), R.drawable.sky_bgr); //Load a background.
ballW = ball.getWidth();
ballH = ball.getHeight();
toRect1 = new Rect(0, 0, bgr.getWidth(), bgr.getHeight());
fromRect1 = new Rect(0, 0, bgr.getWidth(), bgr.getHeight());
toRect2 = new Rect(0, 0, bgr.getWidth(), bgr.getHeight());
fromRect2 = new Rect(0, 0, bgr.getWidth(), bgr.getHeight());
//Create a flag for the onDraw method to alternate background with its mirror image.
reverseBackroundFirst = false;
//Initialise animation variables.
acc = 0.2f; //Acceleration
dY = 0; //vertical speed
initialY = 100; //Initial vertical position
angle = 0; //Start value for the rotation angle
bgrScroll = 0; //Background scroll position
dBgrY = 1; //Scrolling background speed
fpsPaint.setTextSize(30);
//Set thread
getHolder().addCallback(this);
setFocusable(true);
}
#Override
public void onSizeChanged (int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
//This event-method provides the real dimensions of this custom view.
screenW = w;
screenH = h;
bgr = Bitmap.createScaledBitmap(bgr, w, h, true); //Scale background to fit the screen.
bgrW = bgr.getWidth();
bgrH = bgr.getHeight();
//Create a mirror image of the background (horizontal flip) - for a more circular background.
Matrix matrix = new Matrix(); //Like a frame or mould for an image.
matrix.setScale(-1, 1); //Horizontal mirror effect.
bgrReverse = Bitmap.createBitmap(bgr, 0, 0, bgrW, bgrH, matrix, true); //Create a new mirrored bitmap by applying the matrix.
ballX = (int) (screenW /2) - (ballW / 2) ; //Centre ball X into the centre of the screen.
ballY = -50; //Centre ball height above the screen.
}
//***************************************
//************* TOUCH *****************
//***************************************
#Override
public synchronized boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN: {
ballX = (int) ev.getX() - ballW/2;
ballY = (int) ev.getY() - ballH/2;
ballFingerMove = true;
break;
}
case MotionEvent.ACTION_MOVE: {
ballX = (int) ev.getX() - ballW/2;
ballY = (int) ev.getY() - ballH/2;
break;
}
case MotionEvent.ACTION_UP:
ballFingerMove = false;
dY = 0;
break;
}
return true;
}
#Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
//Draw scrolling background.
fromRect1.set(0, 0, bgrW - bgrScroll, bgrH);
toRect1.set(bgrScroll, 0, bgrW, bgrH);
fromRect2.set(bgrW - bgrScroll, 0, bgrW, bgrH);
toRect2.set(0, 0, bgrScroll, bgrH);
// Rect fromRect1 = new Rect(0, 0, bgrW - bgrScroll, bgrH);
// Rect toRect1 = new Rect(bgrScroll, 0, bgrW, bgrH);
//
// Rect fromRect2 = new Rect(bgrW - bgrScroll, 0, bgrW, bgrH);
// Rect toRect2 = new Rect(0, 0, bgrScroll, bgrH);
if (!reverseBackroundFirst) {
canvas.drawBitmap(bgr, fromRect1, toRect1, null);
canvas.drawBitmap(bgrReverse, fromRect2, toRect2, null);
}
else{
canvas.drawBitmap(bgr, fromRect2, toRect2, null);
canvas.drawBitmap(bgrReverse, fromRect1, toRect1, null);
}
//Next value for the background's position.
if ( (bgrScroll += dBgrY) >= bgrW) {
bgrScroll = 0;
reverseBackroundFirst = !reverseBackroundFirst;
}
//Compute roughly the ball's speed and location.
if (!ballFingerMove) {
ballY += (int) dY; //Increase or decrease vertical position.
if (ballY > (screenH - ballH)) {
dY=(-1)*dY; //Reverse speed when bottom hit.
}
dY+= acc; //Increase or decrease speed.
}
//Increase rotating angle
if (angle++ >360)
angle =0;
//DRAW BALL
//Rotate method one
/*
Matrix matrix = new Matrix();
matrix.postRotate(angle, (ballW / 2), (ballH / 2)); //Rotate it.
matrix.postTranslate(ballX, ballY); //Move it into x, y position.
canvas.drawBitmap(ball, matrix, null); //Draw the ball with applied matrix.
*/// Rotate method two
canvas.save(); //Save the position of the canvas matrix.
canvas.rotate(angle, ballX + (ballW / 2), ballY + (ballH / 2)); //Rotate the canvas matrix.
canvas.drawBitmap(ball, ballX, ballY, null); //Draw the ball by applying the canvas rotated matrix.
canvas.restore(); //Rotate the canvas matrix back to its saved position - only the ball bitmap was rotated not all canvas.
//*/
//Measure frame rate (unit: frames per second).
now=System.currentTimeMillis();
canvas.drawText(framesCountAvg+" fps", 40, 70, fpsPaint);
framesCount++;
if(now-framesTimer>1000) {
framesTimer=now;
framesCountAvg=framesCount;
framesCount=0;
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
thread = new GameThread(getHolder(), this);
thread.setRunning(true);
thread.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
thread.setRunning(false);
while (retry) {
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
class GameThread extends Thread {
private SurfaceHolder surfaceHolder;
private BallBounces gameView;
private boolean run = false;
public GameThread(SurfaceHolder surfaceHolder, BallBounces gameView) {
this.surfaceHolder = surfaceHolder;
this.gameView = gameView;
}
public void setRunning(boolean run) {
this.run = run;
}
public SurfaceHolder getSurfaceHolder() {
return surfaceHolder;
}
#Override
public void run() {
Canvas c;
while (run) {
c = null;
//limit frame rate to max 60fps
timeNow = System.currentTimeMillis();
timeDelta = timeNow - timePrevFrame;
if ( timeDelta < 16) {
try {
Thread.sleep(16 - timeDelta);
}
catch(InterruptedException e) {
}
}
timePrevFrame = System.currentTimeMillis();
try {
c = surfaceHolder.lockCanvas(null);
synchronized (surfaceHolder) {
//call methods to draw and process next fame
gameView.onDraw(c);
}
} finally {
if (c != null) {
surfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
}
}
If you notice, there's code to measure the frame rate:
now=System.currentTimeMillis();
canvas.drawText(framesCountAvg+" fps", 40, 70, fpsPaint);
framesCount++;
if(now-framesTimer>1000) {
framesTimer=now;
framesCountAvg=framesCount;
framesCount=0;
}
I'm seeing that on both of my Galaxy Nexus devices, running Android 4.0 and 4.2, it's around 22-24fps. On my HTC Desire, running Android 2.2, it's more like 60fps.
You'll also notice that I'm not allocating anything in the onDraw method. I'm not creating new Paint objects either. I really don't see how this is running so, so, so much slower on the my Galaxy Nexus devices. There's a lot of stuttering and the ball moves very slowly.
Does anyone know whether there is a setting I can undo or a known issue with re-drawing on the Galaxy Nexus? This is happening to my Galaxy Nexus that's running 4.0 and the one that's running 4.2, so I'm not sure it's OS-specific. I have turned off the window and transition animations in Developer Options. It doesn't make a difference whether I force 2D acceleration.
Have you tested android:hardwareAccelerated="true|false" flag in application?
Android Dev Doc: http://developer.android.com/guide/topics/graphics/hardware-accel.html
You can add before setContentView:
if (android.os.Build.VERSION.SDK_INT >= 11) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
}
I've been thinking about this, as I'm still having performance issues on my Nexus 10 with surfaceview, like I said previously, I increased my performance a lot my removing the use of paint objects, it's a long shot as you are only using one, but you could try to remove the text drawing section from your onDraw() just to see if it makes any difference to your drawing speed.
Other than that, I think it's really a case of trying to pin down the problem.
I've noticed that even if I remove my onDraw and Logic updating methods completely from the equation, it's still taking sometimes up to 25ms just to lock and unlock/post the canvas! So it might be that the problem actually doesn't lie in onDraw method - give it a go, comment onDraw() out from your Run() method and see what speeds you get (Use logging to Logcat to see the figures, remember that ironically, displaying a frame / time count on the screen could affect the very thing you're measuring). :-)
What's your targetSdk set to?
If targetSdk is set to 8 (2.2), but you're running it on a 4.x device (15+), the 4.x device will run in compatibility mode, meaning that it will virtualize all the calls so that they return exactly the same as if they're running on a version 8 device.
This virtualization might explain some of the slowness. Try changing targetSdk to 17 (for your 4.2 device) and see if it makes a difference.
I has experienced the same thing on Kindle Fire, Sony Xperia Z and Samsung S4 (all with android 4.2).
The fix is: at App Manifest file remove "android:supportsRtl="true"".
Hope it will save your time. I spend 4 hours on tests and merging before i got it.

How do I create an orthographic camera that correctly scales my sprites/textures with libgdx?

I'm creating a game with libgdx that I want to run at a higher resolution on the desktop, but I want it to scale everything down correctly when I run it on android at smaller resolutions. I've read that the best way to do this is to not use a pixel perfect camera, and instead to use world coordinates, but I'm not sure how to correctly do that.
This is the code I have right now:
#Override
public void create() {
characterTexture = new Texture(Gdx.files.internal("character.png"));
characterTextureRegion = new TextureRegion(characterTexture, 0, 0, 100, 150);
batch = new SpriteBatch();
Gdx.gl10.glClearColor(0.4f, 0.6f, 0.9f, 1);
float aspectRatio = (float)Gdx.graphics.getWidth() / (float)Gdx.graphics.getHeight();
camera= new OrthographicCamera(aspectRatio, 1.0f);
}
#Override
public void render() {
GL10 gl = Gdx.graphics.getGL10();
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
camera.update();
camera.apply(gl);
batch.setProjectionMatrix(camera.combined);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
draw();
}
private void draw() {
//batch.getProjectionMatrix().set(camera.combined);
batch.begin();
batch.draw(characterTextureRegion, 0, 0, // the bottom left corner of the box, unrotated
1f, 1f, // the rotation center relative to the bottom left corner of the box
0.390625f, 0.5859375f, // the width and height of the box
1, 1, // the scale on the x- and y-axis
0); // the rotation angle
batch.end();
}
The texture I'm use is 256x256 with the actual image in it being 100x150.
This is the result I get when I run the game: http://i.imgur.com/HV9Bi.png
The sprite that gets rendered is massive, considering this is the original image: http://i.imgur.com/q1cZT.png
What's the best way to go about making it so that the sprites get rendered at their original size while still keeping the ability to have the game scale correctly when played in different resolutions?
I've only found two solutions, both of which I don't like.
The image showed up how it was supposed to if I used pixel coordinates for the camera, but then that didn't scale at all when I put it on my phone with a different resolution.
I can scale the texture region down when I draw it, but it seems like there is a better way because it is extremely tedious trying to figure out the correct number to scale it by.
Have you ever used the Libgdx setup tool? When you create a project with it, it has a sample image that is displayed. It seems to keep it's ratio correct no matter what size you change the screen to.
public class RotationTest implements ApplicationListener {
private OrthographicCamera camera;
private SpriteBatch batch;
private Texture texture;
private Sprite sprite;
Stage stage;
public boolean leonAiming = true;
#Override
public void create() {
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
camera = new OrthographicCamera(1, h/w);
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); }....
#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();
sprite.draw(batch);
batch.end();
First of all you need to fix boundaries to the world (I mean to your game ). In that world only you actors(game characters) should play. If you are crossing boundaries, manage it with camera like showing up, down, left and right.

Categories

Resources