Difficulties using ScreenToWorldPoint to aim
Hi, I'm making a 2D scrolling shooter (but in 3D) and I'm having a hard time making the aiming work. Here's the code sitting on the gun :
Vector3 mouseWorldPosition = cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, cam.farClipPlane));
mouseWorldPosition.z = 0;
transform.LookAt(mouseWorldPosition, Vector3.forward);
I managed to make it behave by fiddling with several nested empty objects to handle the rotation, but it's neither clean or precise.
The problems :
- I don't understand precisely the inner workings of ScreenToWorldPoint, especially how it relates to a perspective camera (I'm working in 3D even though it's a 2D scrolling shooter)
nor did I manage to apply the rotation in a predictable way (only the z rotation must change). Maybe it's just a problem due to how I've organize my objects in the scene (with pivots points and parenting ?)
The cinemachine camera and its damping messes with the aiming direction (because the player is not centered anymore ?)
Questions :
Shoud I use transform.lookAt() or something like Quaternion.LookRotation()
What is the proper way ?
Do the axis work the same in a 3D project as in a 2D one ?
I found the following way to do it in 2D tutorials but it doesn't seem to translate to 3D coordinates
Vector3 difference = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10f)) - transform.position; difference.Normalize(); float rotz = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg; transform.rotation = Quaternion.Euler(0f, 0f, rotz);
Thank you for your time and sorry if I'm unclear : I'm a beginner still and my english is rusty ;) !
Your answer
Follow this Question
Related Questions
Turret rotation based on its own local rotation. 3 Answers
How do I aim a tank turret at a point? 0 Answers
using RayCast to aim at different planes 0 Answers
ScreenToWorldPoint not working 1 Answer
Object point of rotation unknown 1 Answer