Hi!
I’m working on a prototype of an action RPG. It’s sort of 3D-lite with a locked isometric camera—meaning that the player can go up and down stairs to different vertical levels, fall between areas, etc., but entities’ actions are basically limited to the current horizontal plane they’re on. So an entity with a gun can’t shoot upwards or downwards, they can only shoot along the plane they’re currently on.
I’d like the player character to rotate to face the current mouse position, but I’m having a little trouble. Specifically, I’ve been trying to cast the mouse position into world space as if the mouse is on the same horizontal plane as the player. The way I’ve been trying this so far has been to have the following in a script on the player entity:
Vector2 relativeMousePosition = Input.mousePosition - mainCamera.WorldToScreenPoint(transform.position);
if (relativeMousePosition != Vector2.zero)
{
Vector3 newPosition = Quaternion.Euler(0f, cameraRotation, 0f) * new Vector3(mousePosition.x, transform.position.y, mousePosition.y);
transform.LookAt(newPosition);
}
This sort of works—according to Debug.DrawLine, the player looks in the right place when the mouse position is directly to the right, to the left, above, or below the player on the screen. At any other angle, though, there’s a slight gap between the DrawLine and the mouse position.
I’ve also poked around with using a Plane set to the player’s position, raycasting off the mouse position, and taking the point where the plane and the ray intersect. This hasn’t worked so well, and it also seems like it’d be unnecessarily expensive, as it requires translating the plane around with the player.
What’s the preferred way of handling this?
Thank you!
Edit: Right after posting this I found a way to get an accurate position from Plane using the following:
playerPlane = new Plane(Vector3.up, transform.position);
Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
float distance;
Vector3 relativeMousePosition;
if (playerPlane.Raycast(ray, out distance))
{
relativeMousePosition = ray.GetPoint(distance);
}
This works, but making a new Plane every Update seems expensive—is it?