0

I am currently working on a 2d game and I want the player to be able to move around the world freely and always "face/look at" the mouse. To implement this I made a Camera which translates everything in relation to the player:

x = (player.getX()+(player.getWidth()/2)) - game.getWidth()/2;
y = (player.getY()+(player.getHeight()/2)) - game.getHeight()/2;

g2d.translate(-camX, -camY);
//render everything(including player)
g2d.translate(camX, camY);

then when rendering the player i calculate the rotation:

g2d.rotate(Math.atan2(playerCenterY - mouseY, playerCenterX - mouseX) - Math.PI / 2 , playerCenterX , playerCenterY );
//draw player
g2d.rotate(-Math.atan2(playerCenterY - mouseY, playerCenterX - mouseX) - Math.PI / 2 , playerCenterX , playerCenterY );

This works perfectly but once the player has moved (causing the camera to move) it no longer works and I have no idea why. Any thoughts would be greatly appreciated.

  • I would guess, you probably need to "translate" the mouseX/Y in accordance to the direction of the camera – MadProgrammer May 16 '18 at 22:12
  • @MadProgrammer that is what I thought too, but when I checked the cords in the console and it is unchanged by the translation –  May 16 '18 at 22:17
  • The translation shouldn't affect the "coordinates" until it goes about applying to the `Graphics` state - so you could, for example, translate the context and then draw something offset by a given amount. The offset won't change, but it will be "translated" by the context - clear as mud :P – MadProgrammer May 16 '18 at 23:10
  • @MadProgrammer is there an easier way to get around this? like ending the translation and then re translating it back? if not would I just have to add the camera's x cord to the mouse's X cord and same for y cord? –  May 16 '18 at 23:21
  • Off the top of my head, I don't know. Either you need to manually "translate" the mouseX/Y coordinates to reverse the translations done to the `Graphics` context OR rotate the character independently of the translations – MadProgrammer May 16 '18 at 23:32
  • @MadProgrammer can you give me an example of rotating it independently? –  May 16 '18 at 23:43
  • [This example](https://stackoverflow.com/questions/20275424/rotating-image-with-affinetransform/20280225#20280225) rotates a image independently, the image can then be painted as normal. The resulting image's size will change to ensure that the whole image will fit correctly when rotated - not sure if this will help, but it's an idea :P – MadProgrammer May 16 '18 at 23:52

0 Answers0