I know this is quite the newbie question, but I’m having trouble setting up mouse input in my game. The game world can scroll, and I’m trying to get the position of the mouse when it clicks. My game is a tiled game, so I take every mouse click and divide it by the tile size to try to get world coordinates. However, when I get the coordinates, they are crazy. The y is opposite of what I’m clicking (click at 0, 1 and I get 0, -1). I realize this is probably because my camera is set up with the origin to the bottom left, but when I try subtracting the window height, the y coordinate is still crazy. Its generally the same for the x coordinate, although I can’t really tell if its doing the same as y because the x seems so sporadic… I thought about it and I decided that since my world can scroll, maybe that was what was messing it up. So I used unproject, but that did nothing. Here’s my code:
if (Gdx.input.isTouched()) {
Vector3 touchPos = new Vector3();
touchPos.set(Gdx.input.getX() / 16, Gdx.input.getY() / 16, 0);
cam.getCamera().unproject(touchPos);
if (touchPos.x >= 0 && touchPos.y >= 0 && touchPos.x <= tileWidth && touchPos.y <= tileHeight) {
tiles[(int) touchPos.x][(int) touchPos.y] = Tile.base;
}
}
And my camera code:
package com.nishu.balancedEnergy.utilities;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.OrthographicCamera;
public class Camera {
private OrthographicCamera camera;
private float x, y;
private float moveSpeed = 1f;
private float zoom = 0.5f;
public Camera(){
camera = new OrthographicCamera();
camera.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
camera.zoom = zoom;
}
public void update(){
camera.update();
if(zoom <= 0){
zoom = 0.1f;
}
if(zoom > 1){
zoom = 1;
}
camera.zoom = zoom;
}
public void move(){
if(Gdx.input.isKeyPressed(Keys.W)){
y += moveSpeed;
}
if(Gdx.input.isKeyPressed(Keys.S)){
y -= moveSpeed;
}
if(Gdx.input.isKeyPressed(Keys.A)){
x -= moveSpeed;
}
if(Gdx.input.isKeyPressed(Keys.D)){
x += moveSpeed;
}
if(Gdx.input.isKeyPressed(Keys.NUM_1)){
zoom += 0.0625f;
}
if(Gdx.input.isKeyPressed(Keys.NUM_2)){
zoom -= 0.0625f;
}
translate(x, y);
x = 0;
y = 0;
}
public void translate(float x, float y){
camera.translate(x, y);
}
public OrthographicCamera getCamera() {
return camera;
}
public void setCamera(OrthographicCamera camera) {
this.camera = camera;
}
public float getX() {
return x;
}
public void setX(float x) {
this.x = x;
}
public float getY() {
return y;
}
public void setY(float y) {
this.y = y;
}
}
So what am I doing wrong here?