Rotation on One Axis Using lookAt

Helo thar,



I’m using JME to render a primarily 2D game, where each sprite is a textured quad. The player is supposed to be facing the mouse cursor at all times, so I use the mouse position relative to the center of the screen, and then use lookAt with that position in the 3D environment. Unfortunately, the player quad flips upside down whenever the mouse’s x-pos is greater than the player’s x-pos. The code is as follows:



[java]

Vector2f mousePos = inputManager.getCursorPosition();

Vector2f screenCenter = new Vector2f(app.settings.getWidth()/2, app.settings.getHeight()/2);

Vector2f relativePos = new Vector2f(mousePos.x - screenCenter.x, mousePos.y - screenCenter.y);

Vector3f playerPos = playerNode.getLocalTranslation();

playerNode.lookAt(new Vector3f(playerPos.x + relativePos.x, playerPos.y + relativePos.y, 0), new Vector3f(0,1,0));

[/java]



It seems that because the point I’m looking at eventually moves under the player, the quad flips. I’d like to rotate on the Z axis only, but I don’t have sufficient knowledge to isolate that aspect of the lookAt() method. Any help would be appreciated! :slight_smile:

Why don’t you do a look-at at the camera position?

@zarch said:
Why don't you do a look-at at the camera position?

The player is supposed to face the mouse, not the camera. Perhaps I misunderstand?

The mouse doesn’t exist in the 3d world though. Or are you casting a ray out from the mouse and looking at where that intersects?



Either way it looks like you need to do some trig or similar to work out the desired angle and then set the rotation accordingly.

try to use:

camera.getScreenCoordinates(player);

camera.getCursorPosition(); // not sure how this method is named possibly getMousePosition()…



So you have 2 points with Vector2f. This is my tip. :slight_smile:



Edited:

and if you make VectorA - VectorB so you will get the view direction.

Everyone doing graphics should have at least a basic knowledge of trig or they will struggle. If you have the time, it would be worth learning.



This presumes that the player is in the center of the screen: (and just off the top of my head)

[java]

Vector2f mousePos = inputManager.getCursorPosition();

Vector2f screenCenter = new Vector2f(app.settings.getWidth()/2, app.settings.getHeight()/2);

Vector2f relativePos = new Vector2f(mousePos.x - screenCenter.x, mousePos.y - screenCenter.y);

float angleRads = FastMath.atan2(relativePos.y, relativePos.x);

Quaternion playerRotation = new Quaternion().fromAngles( 0, angleRads, 0 );

playerNode.setRotation(playerRotation);

[/java]

1 Like