I'm trying to make an object appear where the person last touched. However when I try to do so it appears in the wrong place. I assume this is because of the fact the coordinates that the input returns is different to the display coordinates, my code is as follows:
public class Core implements ApplicationListener, InputProcessor
{ //Has to be here otherwise the code formatting becomes buggy
private Mesh squareMesh;
private PerspectiveCamera camera;
private Texture texture;
private SpriteBatch spriteBatch;
Sprite sprite;
float moveX = 0;
private final Matrix4 viewMatrix = new Matrix4();
private final Matrix4 transformMatrix = new Matrix4();
#Override
public void create()
{
Gdx.input.setInputProcessor(this);
texture = new Texture(Gdx.files.internal("door.png"));
spriteBatch = new SpriteBatch();
sprite = new Sprite(texture);
sprite.setPosition(0, 0);
viewMatrix.setToOrtho2D(0, 0, 480, 320);
float x = 0;
float y = 0;
}
#Override
public void dispose()
{
}
#Override
public void pause()
{
}
#Override
public void render()
{
viewMatrix.setToOrtho2D(0, 0, 480, 320);
spriteBatch.setProjectionMatrix(viewMatrix);
spriteBatch.setTransformMatrix(transformMatrix);
spriteBatch.begin();
spriteBatch.disableBlending();
spriteBatch.setColor(Color.WHITE);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
//spriteBatch.draw(texture, 0, 0, 1, 1, 0, 0, texture.getWidth(),
// texture.getHeight(), false, false);
sprite.draw(spriteBatch);
spriteBatch.end();
update();
}
#Override
public void resize(int width, int height)
{
float aspectRatio = (float) width / (float) height;
camera = new PerspectiveCamera(67, 2f * aspectRatio, 2f);
}
#Override
public void resume()
{
}
public void update()
{
float delta = Gdx.graphics.getDeltaTime();
if(Gdx.input.isTouched())
{
Vector3 worldCoordinates = new Vector3(sprite.getX(), sprite.getY(), 0);
camera.unproject(worldCoordinates);
sprite.setPosition(Gdx.input.getX(), Gdx.input.getY());
float moveX = 0;
float moveY = 0;
}
}
I cropped this code for sake of simplicty.
I also made a video demonstrating the bug:
http://www.youtube.com/watch?v=m89LpwMkneI
Camera.unproject converts screen coordinates to world coordinates.
Vector3 pos = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(pos);
sprite.setPosition(pos.x, pos.y);
Firstly, Gdx.input.getX() and Gdx.input.getY() return "screen coordinates". You want to transform these to your "camera coordinates". Screen coordinates typically have (0,0) in the top left corner of the window. I think your camera coordinates have (0,0) at the bottom left corner (either libgdx or opengl are doing that). Your video seems to suggest that this true. So you will need to multiply the Y value by -1. Secondly, I suspect the scale of the screen is different from the scale of the camera. I think you can fix the scale by multiplying by (world/screen).
Let's say your screen has width=800, height=600 and your world has width=480 height=320. Then your new X,Y for your sprite should be:
X = Gdx.input.getX()*(480/800)
Y = Gdx.input.getY()*(320/600)*-1
you should check your touch cordinates.
Gdx.app.log("", "hello x"+touchx);
Gdx.app.log("", "hello x"+touchy);
here touchx and touchy are your input x and input y variables
then do calculation where touch should work
like if u touched x=100,y=100
and touchx is coming 120
and touch y is coming 120
soo in your update method do this
sprite.setPosition(Gdx.input.getX()-20, Gdx.input.getY()-20);
i think this will help
I figured out the screen size/ game ratio and multiplied it to the current screen size:
rect.x=((((1024/Gdx.graphics.getWidth()))* Gdx.graphics.getWidth())
for a screen width of 1024 pixels
There must be an easier way however this works for me.
Related
i have created a test tiled map for a 2D game that i am programming. And everything is fine with!, but when i change the resolution the camera doesn´t fit the screen correctly.
I have a player sprite and the Tile map, and I use a resolution of 1366x768, as you can see the screen fit correctly:
but when i change the resolution, for example 640x480. The player doesn´t fit according to the new resolution as you can see in this picture:
The player seems bigger, but i want to fit the entire screen according to the new resolution, including all the sprites.
I think there is a problem with the cam rendering, but i don´t know what can i do to solve it. The camera is following the player movement and everything is ok with that, but i want to fit the screen game with the resolutions selected.
I'll put some parts of my code for you can see:
Here is the main code:
public class codeTiled implements ApplicationListener {
... //Variables.....
public void create() {
manager = new AssetManager();
manager.setLoader(TiledMap.class, new TmxMapLoader());
manager.load("C:/Users/HOME/Desktop/tilemap/TiledMap/data/maps/test.tmx", TiledMap.class);
manager.finishLoading();
map = manager.get("C:/Users/HOME/Desktop/tilemap/TiledMap/data/maps/test.tmx", TiledMap.class);
batch=new SpriteBatch();
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
camera = new OrthographicCamera(50, 50 * (h / w));
float unitScale = 1 / 8f;
renderer = new OrthogonalTiledMapRenderer(map, unitScale);
player=new playerEx(100, 100, camera);
}
public void render() {
handleInput();
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
camera.update();
renderer.setView(camera);
renderer.render();
batch.begin();
player.render(batch);
batch.end();
}
private void handleInput() {
if (Gdx.input.isKeyPressed(Input.Keys.ESCAPE)){
System.exit(0);
}
camera.zoom = MathUtils.clamp(camera.zoom, 0.1f, 100/camera.viewportWidth);
float effectiveViewportWidth = camera.viewportWidth * camera.zoom;
float effectiveViewportHeight = camera.viewportHeight * camera.zoom;
camera.position.x = MathUtils.clamp(camera.position.x, effectiveViewportWidth / 2f, 100 - effectiveViewportWidth / 2f);
camera.position.y = MathUtils.clamp(camera.position.y, effectiveViewportHeight / 2f, 100 - effectiveViewportHeight / 2f);
}
And this is some part of my player class:
public class playerEx {
...//Variables....
public playerEx(int x, int y, OrthographicCamera camera){
this.camera=camera;
recP= new Rectangle();
recP.height = 64;
recP.width = 64;
recP.x = x;
recP.y = y;
imagen=new Texture(Gdx.files.internal("C:/Users/HOME/Desktop/tilemap/TiledMap/data/sprites/player/minigunattack.png"));
imagen2=new Texture(Gdx.files.internal("C:/Users/HOME/Desktop/tilemap/TiledMap/data/sprites/player/minigunstand.png"));
TextureRegion[][] tmp=TextureRegion.split(imagen,
imagen.getWidth()/5,imagen.getHeight());
imagen1=new Texture(Gdx.files.internal("C:/Users/HOME/Desktop/tilemap/TiledMap/data/sprites/player/feet.png"));
TextureRegion[][] tmp1=TextureRegion.split(imagen1,
imagen1.getWidth()/5,imagen1.getHeight());
movPlayer=new TextureRegion[5];
movFeet=new TextureRegion[5];
for(int i=0;i<5;i++){
movFeet[i]=tmp1[0][i];
}for(int i=0;i<5;i++){
movPlayer[i]=tmp[0][i];
}animationAttack=new Animation(0.08f,movPlayer);
animationFeet=new Animation(0.10f,movFeet);
tiempo=0f;
}
Again, the camera is programmed to follow the player and it works fine. But when i want to change it to another resolution the sprite player doesn´t fit with the tiled map :(.
Hope somebody can help me with this...
Thank you!.
I recommend you to use a viewport and some Constants values for your world.
Firstly we define a default screen width and height in pixel. Doesn't matter how big the end screen will be.
In my example, I say the default screen size is: 512x256 pixel.
Secondly, I must decide how many pixels are one Meter. So if I say 256 pixels is one meter, my viewport shows 2x1 meter of my world. That's very small. If I want that my viewport shows for example 16 meter I can calculate: 512 / 16 = Pixel_Per_Meter. In this case 32.
Finally, we create a Constants class:
public class Constants {
public static final float PPM = 32; // PPM = Pixel per Meter
public static final float MPP = 1 / PPM; // MPP = Meter per Pixel
public static final int WORLD_PIXEL_WIDTH = 512;
public static final int WORLD_PIXEL_HEIGHT = 256;
public static final float WORLD_WIDTH = WORLD_PIXEL_WIDTH / PPM; //in meter
public static final float WORLD_HEIGHT = WORLD_PIXEL_HEIGHT / PPM; //in meter
}
Now when you see later in your game, the shown world is too small or too big, you can change the WORLD_PIXEL_WIDTH and WORLD_PIXEL_HEIGHT to show more or less
Now we create our OrthographicCamera, FitViewport and OrthogonalTiledMapRenderer
Viewport is a very important part of the game. If you will know more about Viewports read the viewport part of
calling render method from another class and Libgdx set ortho camera
So first create our OrthographicCamera 'camera' and our FitViewport 'viewport'
camera = new OrthographicCamera();
viewport = new FitViewport(Constants.WORLD_WIDTH, Constants.WORLD_HEIGHT, camera);
camera.position.set(viewport.getWorldWidth() / 2, viewport.getWorldHeight() / 2, 0); // Differ from your I eat ann Apple
Then our SpriteBatch 'batch' and TiledMap 'map'
batch = new SpriteBatch();
map = app.getAssets().loadSingleAsset("map/" + level + ".tmx", TiledMap.class);
And finally, our OrthogonalTiledMapRenderer 'mapRenderer'
mapRenderer = new OrthogonalTiledMapRenderer(map, Constants.MPP);
To render our world:
#Override
public void render(float delta) {
camera.update();
mapRenderer.setView(camera);
mapRenderer.render();
batch.setProjectionMatrix(camera.combined);
batch.begin();
player.draw(batch);
batch.end();
}
I am programming a 2d platformer with libgdx, I'm trying to make a menu screen where the player can click a button and it will load that level. I use gdx.input for the click coordinates and TextureRegion.getRegionX() for the button coordinates. They don't sync together and I read that camera.unproject should fix this problem. I duly used it but the coords still don't match. camera.unproject seems to set 0,0 for x and y as the centre of the screen, while batch.draw (which is the method which draws the TextureRegion to screen) seems to be using the bottom left hand corner as x and y's 0, 0.
Here is the code, I left out what I didn't think was relevant:
public class LevelScreen implements Screen {
private TextureRegion level_bg;
private SpriteBatch batch;
private Camera camera;
private TextureAtlas textureAtlas;
private TextureRegion lockselectbg[]=new TextureRegion[10];
public LevelScreen(){
}
#Override
public void show() {
batch=new SpriteBatch();
camera = new OrthographicCamera(500,700);
LevelStatus.put();
LevelStatus.get();
textureAtlas=new TextureAtlas(Gdx.files.internal("levelatlas.pack"));
Array<AtlasRegion> atlasArrays = new Array<AtlasRegion>(textureAtlas.getRegions());
level_bg = atlasArrays.get(0);
lockselectbg[0] = atlasArrays.get(21);
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(159/255.0f,220/255.0f,235/255.0f,0xff/255.0f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined);
batch.begin();
batch.draw(level_bg, -500/2,-348/2);
batch.draw(lockselectbg[0], -180,0);
batch.end();
if(Gdx.input.isTouched()){
Vector3 tmp = new Vector3(Gdx.input.getX(),Gdx.input.getY(), 0);
camera.unproject(tmp);
Rectangle textureBounds = new Rectangle(lockselectbg[0].getRegionX(), lockselectbg[0].getRegionY(), lockselectbg[0].getRegionWidth(), lockselectbg[0].getRegionHeight());
if(textureBounds.contains(tmp.x, tmp.y)) {
System.out.println("It worked");
}
}
}
#Override
public void dispose() {
textureAtlas.dispose();
batch.dispose();
}
Camera#unproject will convert touch coordinates to world coordinates. They have nothing to do with the location of the region on the texture, which is what TextureRegion is. You are practically comparing world (read: game logic) coordinates with asset coordinates. Those two are completely unrelated.
If you want to check whether your image on the screen is touched then compare the touch coordinate with the location and size of the image you used in the batch.draw call. For example:
float x = -180f;
float y = 0f;
float width = 200f;
float height = 150f;
...
batch.draw(region, x, y, width, height);
...
camera.unproject(tmp.set(Gdx.input.getX(),Gdx.input.getY(), 0));
boolean touched = tmp.x >= x && tmp.y >= y && tmp.x < (x + width) && tmp.y < (y + height);
if (touched)
System.out.println("It worked");
Btw, you might want to read this post: http://blog.xoppa.com/pixels as well, because you are coupling your logic with asset size.
I'm currently trying to make a game, and I'm still novice with using cameras, and I'm thinking that two OrthographicCameras may be necessary, but I'm not sure if that's the most efficient way, or even how to do so.
Basically, I want this to be the layout for it:
The Main Area is where the main stuff is, which is a Server Interface. The Game Level is where the actual game part is in. I am currently using a ScissorStack to cut the region, but with this demo, results make me question how to do this:
public class TestScissorStackAndCamera extends ApplicationAdapter {
private SpriteBatch batch;
private OrthographicCamera camera;
private Sprite sprite;
private int width, height;
#Override
public void create() {
Gdx.gl.glClearColor(0, 0, 0, 0);
width = Gdx.graphics.getWidth();
height = Gdx.graphics.getHeight();
batch = new SpriteBatch();
camera = new OrthographicCamera(width, height);
camera.position.set(width / 2, height / 2, 0);
camera.update();
createSprite();
}
private void createSprite() {
Pixmap map = new Pixmap(width, height, Format.RGBA8888);
map.setColor(Color.RED);
map.fillRectangle(0, 0, width, height);
map.setColor(Color.BLUE);
map.drawLine(width / 2, 0, width / 2, height);
map.drawLine(0, height / 2, width, height / 2);
Texture texture = new Texture(map);
sprite = new Sprite(texture);
}
#Override
public void render() {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined); // The Question!
batch.begin();
{
Rectangle scissors = new Rectangle();
Rectangle area = new Rectangle(10, 10, width - 20, height - 20);
ScissorStack.calculateScissors(camera, batch.getTransformMatrix(), area, scissors);
ScissorStack.pushScissors(scissors);
batch.draw(sprite, 0, 0);
batch.flush();
ScissorStack.popScissors();
}
batch.end();
}
public static void main(String[] args) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.title = "ScissorStack & Camera Test";
config.resizable = false;
new LwjglApplication(new TestScissorStackAndCamera(), config);
}
}
Questioning batch.setProjectionMatrix(camera.combined)
I marked a line in the code with a comment, The Question!, which is what is affecting the results. If I don't have it, using the camera.translate(...) method, the image is drawn at (0, 0) but what it does is it moves what part is viewed. If I do have that line, when I use the camera.translate(...) method, the image is drawn respectively to the position of the camera.
In respect to the game that I'm currently developing, it behaves awkwardly without the projectionMatrix not being set, but when I do set it, it messes up the positioning of the rest of the game. I even added some testing features, and it's not rendering inside of the correct ScissorStack
How could I go about setting up two cameras, or what could I do to set up what I'm trying to correctly and efficiently?
With my actual game (not the mock-up) this is what it is doing. It should be rendering inside of the red lines, but it's not:
If you'd like to see my current code for my GameLevel that is handling the ScissorStack and OrthographicCamera:
public GameLevel(int x, int y, int displayWidth, int displayHeight) {
this.x = x; // x = 10
this.y = y; // y = 10
this.displayWidth = displayWidth; // displayWidth = Gdx.graphics.getWidth() - x - 10
this.displayHeight = displayHeight; // displayHeight = Gdx.graphics.getHeight() - y - 120
camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
camera.position.set(displayWidth / 2, displayHeight / 2, 0);
// FBLAGame.batch.setProjectionMatrix(camera.combined);
camera.update();
init();
}
...
#Override
public void render() {
Rectangle area = new Rectangle(x, y, displayWidth, displayHeight);
Rectangle scissor = new Rectangle();
Matrix4 matrix = FBLAGame.batch.getTransformMatrix();
ScissorStack.calculateScissors(camera, matrix, area, scissor);
ScissorStack.pushScissors(scissor);
renderLevel();
FBLAGame.batch.flush();
ScissorStack.popScissors();
Pixmap map = new Pixmap(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), Format.RGBA8888);
map.setColor(Color.RED);
map.drawRectangle((int) area.x, (int) area.y, (int) area.width, (int) area.height);
Texture t = new Texture(map);
map.dispose();
FBLAGame.batch.draw(t, 0, 0);
}
it seems as though i cannot get the draw method to work???
it seems as though the bullet.draw(batcher)
does not work and i cannot understand why as the bullet is a sprite.
i have made a Sprite[] and added them as animation.
could that be it?
i tried
batcher.draw(AssetLoader.bulletAnimation.getKeyFrame(runTime), bullet.getX(), bullet.getY(), bullet.getOriginX() / 2, bullet.getOriginY() / 2, bullet.getWidth(), bullet.getHeight(), 1, 1, bullet.getRotation());
but that dont work, the only way it draws is this
batcher.draw(AssetLoader.bulletAnimation.getKeyFrame(runTime), bullet.getX(), bullet.getY());
below is the code.
// this is in a Asset Class
texture = new Texture(Gdx.files.internal("SpriteN1.png"));
texture.setFilter(TextureFilter.Nearest, TextureFilter.Nearest);
bullet1 = new Sprite(texture, 380, 350, 45, 20);
bullet1.flip(false, true);
bullet2 = new Sprite(texture, 425, 350, 45, 20);
bullet2.flip(false, true);
Sprite[] bullets = { bullet1, bullet2 };
bulletAnimation = new Animation(0.06f, bullets);
bulletAnimation.setPlayMode(Animation.PlayMode.LOOP);
// this is the GameRender class
public class GameRender() {
private Bullet bullet;
private Ball ball;
public GameRenderer(GameWorld world) {
myWorld = world;
cam = new OrthographicCamera();
cam.setToOrtho(true, 480, 320);
batcher = new SpriteBatch();
// Attach batcher to camera
batcher.setProjectionMatrix(cam.combined);
shapeRenderer = new ShapeRenderer();
shapeRenderer.setProjectionMatrix(cam.combined);
// Call helper methods to initialize instance variables
initGameObjects();
initAssets();
}
private void initGameObjects() {
ball = GameWorld.getBall();
bullet = myWorld.getBullet();
scroller = myWorld.getScroller();
}
private void initAssets() {
ballAnimation = AssetLoader.ballAnimation;
bulletAnimation = AssetLoader.bulletAnimation;
}
public void render(float runTime) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);
batcher.begin();
// Disable transparency
// This is good for performance when drawing images that do not require
// transparency.
batcher.disableBlending();
// The ball needs transparency, so we enable that again.
batcher.enableBlending();
batcher.draw(AssetLoader.ballAnimation.getKeyFrame(runTime), ball.getX(), ball.getY(), ball.getWidth(), ball.getHeight());
batcher.draw(AssetLoader.bulletAnimation.getKeyFrame(runTime), bullet.getX(), bullet.getY());
// End SpriteBatch
batcher.end();
}
}
// this is the gameworld class
public class GameWorld {
public static Ball ball;
private Bullet bullet;
private ScrollHandler scroller;
public GameWorld() {
ball = new Ball(480, 273, 32, 32);
bullet = new Bullet(10, 10);
scroller = new ScrollHandler(0);
}
public void update(float delta) {
ball.update(delta);
bullet.update(delta);
scroller.update(delta);
}
public static Ball getBall() {
return ball;
}
public ScrollHandler getScroller() {
return scroller;
}
public Bullet getBullet() {
return bullet;
}
}
is there anyway so make the sprite work?
i am adding the bullet class to see if there could be something wrong there.
public class Bullet extends Sprite {
public static final float BULLET_HOMING = 6000;
public static final float BULLET_SPEED = 300;
private Vector2 velocity;
private float lifetime;
public Bullet(float x, float y) {
velocity = new Vector2(0, 0);
setPosition(x, y);
}
public void update(float delta) {
float targetX = GameWorld.getBall().getX();
float targetY = GameWorld.getBall().getY();
float dx = targetX - getX();
float dy = targetY - getY();
float distToTarget = (float) Math.sqrt(dx * dx + dy * dy);
dx /= distToTarget;
dy /= distToTarget;
dx *= BULLET_HOMING;
dy *= BULLET_HOMING;
velocity.x += dx * delta;
velocity.y += dy * delta;
float vMag = (float) Math.sqrt(velocity.x * velocity.x + velocity.y * velocity.y);
velocity.x /= vMag;
velocity.y /= vMag;
velocity.x *= BULLET_SPEED;
velocity.y *= BULLET_SPEED;
Vector2 v = velocity.cpy().scl(delta);
setPosition(getX() + v.x, getY() + v.y);
setOriginCenter();
setRotation(velocity.angle());
lifetime += delta;
setRegion(AssetLoader.bulletAnimation.getKeyFrame(lifetime));
}
}
Your keyframes are kept in an array called bullets, but when you call the Animation constructor you pass something called 'aims' as the second argument. You should try instead passing 'bullets', as in:
bulletAnimation = new Animation(0.06f,bullets);
You shouldn't have a problem with using a Sprite[] as the Sprite class extends TextureRegion I think.
------ OP fixed the typo and still didn't work------
I think the problem will be with the origin arguments of the batcher.draw()call. The position of the Sprite is relative to the origin of the SpriteBatch's co-ordinate system, and the origin of the Sprite is relative to this position (i.e. the bottom-left corner of the Sprite rectangle). To get an origin in the center of the Sprite, i think originX should be width/2 and originY should be height/2. So try:
batcher.draw(AssetLoader.bulletAnimation.getKeyFrame(runTime),bullet.getX(),bullet.getY(), bullet.getWidth()/2,bullet.getHeight()/2,bullet.getWidth(),bullet.getHeight(),1,1,bullet.getRotation());
Because if your getOriginX/Y methods return origins relative to the SpriteBatcher's co-ordinate system(the screen co-ordinates), then your Sprites could be rotating and scaling around some ridiculous origin and end up being drawn off-screen.
I hope I'm right and it's problem solved.
----- OP posted further code, the 'bullet' class-----
When you call bullet.getWidth() and bullet.getHeight() in your draw method, these will return 0.0f because you haven't specified values for them. Remember the Sprites you are actually drawing are bullet1 and bullet2 from your AssetLoader class. Try setting bullet's width and height with:
setSize(AssetLoader.bullet1.getWidth(), AssetLoader.bullet1.getHeight());
in your bullet constructor.
I don't think you need to use setRegion() in your bullet class either, again, because the Sprites you're actually drawing are bullet1 and 2.
fingers crossed.
try and change the update method to this
Vector2 target = new Vector2(GameWorld.getBall().getX(), GameWorld.getBall().getY());
target.sub(getX(), getY());
target.nor().scl(BULLET_HOMING);
velocity.add(target.scl(delta));
velocity.nor().scl(BULLET_SPEED);
Vector2 v = velocity.cpy().scl(delta);
translate(v.x, v.y);
setOriginCenter();
setRotation(velocity.angle());
that should clean your code a little
I would like the camera to be positioned correctly but I am getting the result below:
It seems like when I resize the window, the map does not get rendered properly. Why does that happen?
Code:
public void render(float delta){
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
mapRenderer.setView(camera);
mapRenderer.render(background);
mapRenderer.render(foreground);
shapeRenderer.setProjectionMatrix(camera.combined);
//draw rectangles around walls
for(MapObject object : tiledMap.getLayers().get("walls").getObjects()){
if(object instanceof RectangleMapObject) {
RectangleMapObject rectObject = (RectangleMapObject) object;
Rectangle rect = rectObject.getRectangle();
shapeRenderer.begin(ShapeType.Line);
shapeRenderer.rect(rect.x, rect.y, rect.width, rect.height);
shapeRenderer.end();
}
}
//done drawing rectangles
}
#Override
public void resize(int width, int height) {
camera.viewportWidth = width;
camera.viewportHeight = height;
}
#Override
public void show(){
//call the tile map here
//I believe this is called first before render() is called
tiledMap = new TmxMapLoader().load("data/mapComplete.tmx");
mapRenderer = new OrthogonalTiledMapRenderer(tiledMap, 1f);
//initiate shapeRenderer. Can remove later
shapeRenderer = new ShapeRenderer();
shapeRenderer.setColor(Color.RED);
camera = new OrthographicCamera();
camera.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
}
This should center the camera at the viewport of the game.
#Override
public void resize(int width, int height) {
camera.viewportWidth = width;
camera.viewportHeight = height;
camera.position.set(width/2f, height/2f, 0); //by default camera position on (0,0,0)
}
You do not set the position of the camera anywhere. Thus it is looking at (0, 0) by default (which means (0, 0) will be in the center of your screen). The TiledMapRenderer renders the bottom left corner of the map at (0, 0) which means that it will fill the top right quadrant of your screen. That's what you see in your screenshot.
To set it to the center of the map, you could do something like the following:
TiledMapTileLayer layer0 = (TiledMapTileLayer) map.getLayers().get(0);
Vector3 center = new Vector3(layer0.getWidth() * layer0.getTileWidth() / 2, layer0.getHeight() * layer0.getTileHeight() / 2, 0);
camera.position.set(center);