简体   繁体   中英

Java Slick2d - How to translate mouse coordinates to world coordinates

I am translating in my main class' render. How do I get the mouse position based on the translation?

public void render(GameContainer gc, Graphics g) 
        throws SlickException 
{
    float centerX = 800/2;
    float centerY = 600/2;
    g.translate(centerX, centerY);
    g.translate(-player.playerX, -player.playerY);
    gen.render(g);
    player.render(g);
}

playerX = 800 /2 - sprite.getWidth();
playerY = 600 /2 - sprite.getHeight();

I update the player position on keydown by.2f * delta

Picture to help with explanation

i92.photobucket.com/albums/l22/occ31191/Untitled-4.png

World coordinates = camera position + mouse position

Camera position is calculated/explained in my answer to this question: Slick2D and JBox2D. How to draw

You're making a tile-based game, where each tile seems to have the same size. For this case, you don't need a generalized unprojection.

Imagine the complete map. The viewport shows only a portion of it; somewhere you need to store the (x,y) offets of the viewport into the complete map. Since the mouse coordinates are relative to the viewport, you need to add this offset to the mouse coordinates. Now, you can easily get the tile coordinates by using modulo operations on the shifted mouse coordinates with the tile's width and height.

Effectively, this is a coordinate transformation of window coordinates to tile coordinates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM