I ve got some problem with mouse position in game world in LibGDX.
There is some difference between my mouse position in world and real position.
To get my mouse position Im using:
Vector3 mousePos = gamecam.unproject(new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0));
speechBaloon.setPosition(mousePos.x, mousePos.y); //texture that follows cursor
where:
public static final int WIDTH = 1920;
public static final int HEIGHT = 1080;
gamecam = new OrthographicCamera();
gamePort = new FitViewport(MyGame.WIDTH, MyGame.HEIGHT, gamecam);
gamecam.setToOrtho(false, MyGame.WIDTH, MyGame.HEIGHT);
Here some photos(added mouse coursor by myself, cuz my screens program doesnt have options to capture photo with cursor, but scale between distance is preserved):
img1
img2 - full resolution
As u can see in img2 there is a difference between X position, and in img1 between Y. I cannot post more than 2 photos, but when I drag cursor to the center of Y axis in situation from img1, my texture and cursor are covering themselves.
I have resize function (my class implements Screen).
#Override
public void resize(int width, int height)
{
gamePort.update(width, height);
hudPort.update(width, height);
}
Thanks in advance for help!
Like Tenfour04 noticed as long as Viewport (gamePort) is used we need to call .unproject() on Viewport instance.
From documentation of LibGDX Camera:
Function to translate a point given in screen coordinates to world
space. ...
The viewport is assumed to span the whole screen and is fetched from
Graphics.getWidth() and Graphics.getHeight().
Final outcome:
Vector3 mousePos = gamePort.unproject(new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0));
speechBaloon.setPosition(mousePos.x, mousePos.y); //texture that follows cursor
Related
#Override
public void create()
{
batch = new SpriteBatch();
shape = new ShapeRenderer();
velocity = new Vector2(100, 0);
position = new Rectangle(0, 5, 100, 100);
font = new BitmapFont();
font.setColor(Color.BLACK);
font.getData().scale(3f);
camera = new OrthographicCamera();
confCamera();
}
#Override
public void render()
{
if(Gdx.input.isTouched())
position.x = Gdx.input.getX() - position.width/2;
position.y = (Gdx.input.getY() - position.height/2);
shape.begin(ShapeRenderer.ShapeType.Filled);
shape.setColor(Color.BLACK);
shape.rect(position.x, position.y, position.width, position.height);
shape.end();
}
It's a simple code, but I'm not undestanding Y axis, my shape moves like a mirror. If I touch on top, my shape goes to bottom. If I touch on bottom, my shape goes to top. How to fix it?
LibGDX (by default) for rendering uses coordinate system where 0 is at bottom of the screen and the more you go up Y coordinate grows.
Also, when you read input coordinates (touches, moves...) you get screen coordinates, but when you render your graphics you are using "world" coordinates. They are in 2 different coordinate system so to convert from screen to world you have to use camera.unproject() call. Should be like:
Vector3 touchPos = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(touchPos);
and then use touchPos.x and touchPos.y.
The similar question is asked here so you can find more answers there:
Using unProject correctly in Java Libgdx
I'm having problems setting my orthographic camera to the bottom left part of my screen (0,0)
public GameScreen(Main game) {
this.game = game;
Width = 200;
Height = 300;
view = new ExtendViewport(Width,Height);
camera = new OrthographicCamera(Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
camera.setToOrtho(false,Width/2,Height/2);
camera.position.set(Width,Height,0);
camera.update();
play.Player1();
staple = new Stage();
staple.addActor(play);
staple.addActor(pile);
Gdx.input.setInputProcessor(staple);
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
Gdx.graphics.getDeltaTime();
game.getBatch().begin();
game.getBatch().setProjectionMatrix(camera.combined);
game.getBatch().end();
staple.act();
staple.draw();
}
#Override
public void resize(int width, int height) {
view.update(width,height);
view.setScreenPosition(width,height);
}
I've set my viewport as extended viewport using my width and height values I have assigned but I'm struggling to move the camera to the bottom left
part of my screen (0,0) where it can focus on my images on my android device.
Here are a little example how to use camera and viewport:
First we must define how big is our world the camera shows:
private static final int WORLD_WIDTH = 300;
private static final int WORLD_HEIGHT = 250;
Our world is now 300 x 250 units (not Pixel!) big.
It's importent to think in units not in pixels!!
Now we need a OrthographicCamera, a Viewport and a SpriteBatch
OrthographicCamera camera;
Viewport viewport;
SpriteBatch batch;
#Override
public void create () {
camera = new OrthographicCamera(); // we create a OrthographicCamera
viewport = new ExtendViewport(WORLD_WIDTH, WORLD_HEIGHT, camera); // we create a new Viewport with our camera and we will display our world 300 x 250 units
batch = new SpriteBatch(); // we create a new SpriteBatch for draw our textures
}
In our render method we say the batch only to draw what we can see in our Viewport with the method setProjectionMatrix()
#Override
public void render (float delta) {
camera.update(); //update our camera every frame
batch.setProjectionMatrix(camera.combined); //say the batch to only draw what we see in our camera
batch.begin();
batch.draw(texture, 0,0); //draw our texture on point 0,0 bottom left corner
batch.end();
}
And in the resize method:
public void resize(int width, int height){
viewport.update(width, height); //update the viewport to recalculate
}
To understand why you have this issue:
In your code you never set the camera to the viewport: view = new ExtendViewport(Width,Height);
So your viewport never apply to the batch.
To render the correct way without Viewport you must know that the position of OrhographicCamera is in the center.
So when you set a Camera to position 0,0 and size 50,50 you see the world from -25 to 25 in each direction;
To use OrthographicCamera without Viewport:
public void create () {
camera = new OrthographicCamera(WORLD_WIDTH, WORLD_HEIGHT); // we create a OrthographicCamera and we will display our world 300 x 250 units
camera.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2, 0); //we set position of camera, our world point 0,0 is now the bottom left corner in the camera
batch = new SpriteBatch(); // we create a new SpriteBatch for draw our textures
texture = new Texture("badlogic.jpg");
}
public void render () {
camera.update();
batch.setProjectionMatrix(camera.combined);
batch.begin();
batch.draw(texture, 0,0);
batch.end();
}
The important point is in the resize method:
public void resize(int width, int height){
camera.viewportWidth = WORLD_WIDTH;
camera.viewportHeight = WORLD_HEIGHT * height / width;
camera.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2, 0);
}
With this calculation you always see a World of 300 width and 250 * ratio of width, and height.
And exactly this calculation does the viewport for you. Depending on which Vieport (FitViewport, ScreenViewport, ExtendViewport) you use this calculation will be different, try it out.
I hope this helps you to understand how camera, viewport and Spritebatch works together.
Here are useful links to the libgdx wiki which descript the Viewport and Camera:
https://github.com/libgdx/libgdx/wiki/Viewports
https://github.com/libgdx/libgdx/wiki/Orthographic-camera
Use camera.position.set(Width, Height, 1); instead of 0
First you set the Camara width and height equal to the amount of pixels of the window.
camera = new OrthographicCamera(Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
Then you center it at 100, 150. And move it again to 200, 300
camera.setToOrtho(false,Width/2,Height/2);
camera.position.set(Width,Height,0);
You are also using a Viewport but never make use of it.
I would recommend just using a Viewport of choice. A Viewport can take a camera so if you insist using your own camera you can create it but then also pass it to the Viewport when you construct it.
EDIT
Following is a tested minimal example.
public class TestScreen extends ScreenAdapter {
private Viewport viewport;
private ShapeRenderer sr;
public TestScreen() {
// Note that extend viewport extends it's camera so you end up with smaller or larger view of your world depending on the aspect ratio of the physical screen.
viewport = new ExtendViewport(200, 300);
viewport.apply();
System.out.println(viewport.getWorldWidth());
// Just for testing in the resize method.
viewport.getCamera().translate(0, 0, 0);
viewport.getCamera().update();
// ShapeRenderer for testing
sr = new ShapeRenderer();
sr.setAutoShapeType(true);
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(.04f, .06f, .1f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// Draw circle at 0.0 in the world
sr.setProjectionMatrix(viewport.getCamera().combined);
sr.begin(ShapeRenderer.ShapeType.Line);
sr.circle(0, 0, 100);
sr.end();
}
#Override
public void resize(int width, int height) {
// Will center the camera in the world at half it's width and half it's height so left bottom is 0.0 as long as the camera did.
// By using true here you cannot move the camera since you order it to center on the screen and thus the circle we are drawing
// remains in the bottom left.
//viewport.update(width, height, true);
// This will just update the viewport, we moved the camera slightly to the left so the circle appears slight right from the middle.
viewport.update(width, height, false);
// So you want to start your camera centered on something but still want to move it you need to specify that center in the camera
// by either changing it's position or translating it like I did in the constructor. Unfortunately you only get to know the size
// of the world that is being displayed once this resize method did it's job so certain parts might get cut off or your world does
// not fill the screen.
}
}
i try to rotate a 3D instance when I move the mouse. i use Orthographic Camera, and i have a tiled isomap in background.
[EDIT] I use this code :
public boolean mouseMoved (int x, int y) {
Vector3 direction = new Vector3();
Vector3 worldCoordinate = cam.unproject(new Vector3(x, y, 0));
direction = (worldCoordinate).sub(position).nor();
direction.set(-direction.x, -direction.y, -direction.z);
Matrix4 instanceRotation = instance.transform.cpy().mul(instance.transform);
instanceRotation.setToLookAt(direction, new Vector3(0,-1,0));
instanceRotation.rotate(0, 0, 1, 180);
quat = new Quaternion();
instanceRotation.getRotation(quat);
instance.transform.set(position, quat);
return false;
}
Now, the instance follows the cursor, but in all axes. I just want to turn on the Y axis. I can change quat.x = 0 and quat.z = 0 to lock the rotation. After that, the rotation only works on the Y axis. But, the model should turn over if my cursor is at the top of the screen, but it remains facing, no matter where my cursor is.
I don't know how to convert the coordinates to tell my rotation that it needs to turn over. And to modify the quat in this way is not very elegant
Edit : Some image for illustrate what i want
Here, with cursor in the bottom of the screen, the model turn to look in good direction :
Here, the model dont turn over, like the cursor is in bottom of the screen :
I'm just trying to get libgdx to create a picture wherever I touch the screen.
here's what i have that isn't doing anything
SpriteBatch batch;
Texture img;
#Override
public void create () {
batch = new SpriteBatch();
img = new Texture("badlogic.jpg");
}
#Override
public void render () {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}
public class MyInputProcessor implements InputProcessor {
public boolean touchDown (int x, int y, int pointer, int button) {
batch.begin();
batch.draw(img,Gdx.input.getX(),Gdx.input.getY());
batch.end();
return true;
}
... (the rest of the input methods)
if you can't tell, I don't really know what I'm doing yet, I think it has to do with the batch.draw() being in the touchDown method instead of the render area but I can't figure out from research how to do it a different way either
or maybe this is all wrong too, point is I'm doing this to learn so hopefully the correct answer will help me understand some important things about java in general
LibGDX, like basically all game engines, re-renders the entire scene every time render() is called. render() is called repeatedly at the frame rate of the game (typically 60fps if you don't have a complex and unoptimized game). The first drawing-related thing you usually do in the render() method is to clear the screen, which you have already done with Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);. Then you re-draw the whole scene with whatever changes there might be since the last frame.
You are trying to draw something with the batch outside of the render method. In this case, you are doing it when there is a touch down. But since you are doing this only when there is a touch down, the object will appear and disappear on the next call to render(), so it will only be on screen for 1/60th of a second. If you want to do this with an input processor, you need to set some variable to true to indicate the render method should draw it, and other variables to indicate where to draw it. Then in the render() method, you draw the stuff if the variable is true.
Secondly, the x and y that an input processor gets do not necessarily (and usually don't) correspond with the x and y in OpenGL. This is because OpenGL has it's own coordinate system that is not necessarily sized exactly the same as the screen's coordinate system. The screen has (0,0) in the top left with the Y axis going down, and the width and height of the screen matching the number of actual pixels on the screen. OpenGL has (0,0) in the center of the screen with the Y axis going up, and the width and height of the screen being 2 regardless of the actual screen pixels.
But the OpenGL coordinate system is modified with projection matrices. The LibGDX camera classes make this simpler. For 2D drawing, you need an OrthographicCamera. You set the width and size of the OpenGL world using the camera, and can also position the camera. Then you pass the camera's calculated matrices to the SpriteBatch for it to position the scene in OpenGL space.
So to get an input coordinate into your scene's coordinates, you need to use that camera to convert the coordinates.
Finally, LibGDX cannot magically know that it should pass input commands to any old input processor you have created. You have to tell it which InputProcessor it should use with a call to Gdx.input.setInputProcessor().
So to fix up your class:
SpriteBatch batch;
Texture img;
boolean isTouchDown;
final Vector3 touchPosition = new Vector3();
OrthographicCamera camera;
#Override
public void create () {
batch = new SpriteBatch();
img = new Texture("badlogic.jpg");
camera = new OrthographicCamera();
Gdx.input.setInputProcessor(new MyInputProcessor()); // Tell LibGDX what to pass input to
}
#Override
void resize (int width, int height) {
// Set the camera's size in relation to screen or window size
// In a real game you would do something more sophisticated or
// use a Viewport class to manage the camera's size to make your
// game resolution-independent.
camera.viewportWidth = width;
camera.viewportHeight = height;
camera.update(); // re-calculate the camera's matrices
}
#Override
public void render () {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined); // pass camera's matrices to batch
batch.begin();
if (isTouchDown) { // Only draw this while the screen is touched.
batch.draw(img, touchPosition.x, touchPosition.y);
}
batch.end();
}
public class MyInputProcessor implements InputProcessor {
public boolean touchDown (int x, int y, int pointer, int button) {
isTouchDown = true;
touchPosition.set(x, y, 0); // Put screen touch coordinates into vector
camera.unproject(touchPosition); // Convert the screen coordinates to world coordinates
return true;
}
public boolean touchUp (int screenX, int screenY, int pointer, int button){
isTouchDown = false;
return true;
}
//... (the rest of the input methods)
}
I'm very new to programming and am currently trying to make a simple game for android. The problem I'm having is the way the view is scrolling. By my logic, I believe the sprite should stay in the center of the screen, but it doesn't. The view does follow the sprite, but not at the same speed if that makes sense. As in the view kind of lags behind. It's not jumpy so I know it's not running slowly. What surprises me though is I'm setting my scrolling rectangle equal to player x location - display width, and then same for the y axis. So What I'm hoping you guys can help me out with is figure out why the sprite isn't staying in the center of the view. Any help will be greatly appreciated.
Thanks.
private static Rect displayRect = null; //rect we display to
private Rect scrollRect = null; //rect we scroll over our bitmap with
Display display = getWindowManager().getDefaultDisplay();
displayWidth = display.getWidth();
displayHeight = display.getHeight();
displayRect = new Rect(0, 0, displayWidth, displayHeight);
scrollRect = new Rect(0, 0, displayWidth, displayHeight);
//Setting the new upper left corner of the scrolling rectangle
newScrollRectX = ((int)player.getXLocation() - (displayWidth/2));
newScrollRectY = ((int)player.getYLocation() - (displayHeight/2));
//This is in my onDraw method, so it updates right before the player is drawn
scrollRect.set(newScrollRectX, newScrollRectY,
newScrollRectX + displayWidth, newScrollRectY + displayHeight);
//bmLargeImage is a 1440X1440 background
canvas.drawBitmap(bmLargeImage, scrollRect, displayRect, paint);
canvas.drawBitmap(player.getBitmap(),(float)player.getX(player.getSpeedX()), (float)player.getY(player.getSpeedY()), null);
My first guess would be you are using integer calculations and should use floating point calculations instead.
int test = 10 / 3; // == 3
float test2 = 10 / 3.0; // == 3.33333...
This would explain the 'jumping'.
Beware, I am not certain whether all android phones have FPUs. You might have to use fixed point calculations instead to guarantee proper performance.