Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply pixel Coordinates to Screen Coordinates

Tags:

java

libgdx

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

like image 583
Derek Avatar asked Nov 12 '11 12:11

Derek


1 Answers

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);
like image 97
Teoh Han Hui Avatar answered Oct 05 '22 22:10

Teoh Han Hui