Shooting at mouse position with a slight camera rotation
I'm having a small problem where the bullets I shoot at my mouse position are slightly misaligned due to my camera having a small rotation instead of being directly on top of the player. If I position the camera directly on top of my character, the bullets will fire exactly where the mouse position is as you'd expect.
Here's my current coding for rotations:
Ray ray = _camera.ScreenPointToRay(_lookPosition);
Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
if (groundPlane.Raycast(ray, out float rayLength))
{
Vector3 pointToLookAt = ray.GetPoint(rayLength);
Debug.DrawLine(ray.origin, pointToLookAt, Color.red);
transform.rotation = Quaternion.LookRotation(pointToLookAt - transform.position);
}
How could I factor in the camera rotation to accurately get the position of my mouse?
Subtracting from the y-axis of Input.mousePosition, seems to have done the trick, but I'm not sure why.
Ray ray = _camera.ScreenPointToRay(new Vector2(Input.mousePosition.x, Input.mousePosition.y - 22));
22 seems to be the magic number that works perfectly in my case. The camera's position is "0, 17.5, -10) with a rotation of 55 on the x-axis. Perhaps someone can help me understand what's happening here?
Your answer
Follow this Question
Related Questions
LayerMask Not working when raycasting to Specific layer. 0 Answers
RayCast not accurate on non-colliders (3D) 1 Answer
Raycast Weapon not cause damage 1 Answer
Shotguns with raycasts 0 Answers