- Home /
Make 3D Player look exactly at mouse with ScreenToWorldPoint? (maths Question)
//Debug.Log ("ray for mouse pick >> 1");
float cameraDif = _camera.transform.position.y - transform.position.y;
Vector2 mousePos = new Vector2 (Input.mousePosition.x, Input.mousePosition.y);
Vector3 worldpos = _cameraComponent.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y * multipliery, cameraDif));
Vector3 lookDir = new Vector3 (worldpos.x,transform.position.y, worldpos.z);
transform.LookAt (lookDir);
Debug.Log("Screen h/w : " + (float) Screen.height / (float) Screen.width + " Screen w/h : " + (float) Screen.width / (float) Screen.height);
Hello all, I wanted to upgrade my character to look at the mouse without using a resource intensive procedure with a raycast. The above is a script that is attached to a player which is always in the center of the screen. If you run it it will make the player rotate on the y axis, and performance friendly looks at the mouse. However, the rotation is not that accurate and drifts out as you rotate around the character. Here is a small 10 sec Video showing it : https://youtu.be/pMbyUy2jtnM . I have found out, if you set a multiplier ( in this case multipliery variable) to somewhere around 1.2f , the outcome is more accurate, but if you want to cover all angles one would need to change it depending on whatever angle the character is looking. I have no idea how to solve this mathematically.
Answer by FallingRocketGames · May 29, 2018 at 07:06 PM
You could try this solutions
https://answers.unity.com/questions/10615/rotate-objectweapon-towards-mouse-cursor-2d.html https://stackoverflow.com/questions/36615476/unity-gameobject-look-at-mouse
Or check Transform.LookAt it might work https://docs.unity3d.com/ScriptReference/Transform.LookAt.html
Good luck buddy!
Answer by Slastraf · May 30, 2018 at 11:28 AM
I did some Diagnostics and it came up that this code :
Ray ray = _cameraComponent.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
//Debug.Log ("ray for mouse pick >> 1");
if (Physics.Raycast (ray, out hit, 2000)) {
Vector3 relativePos = hit.point - transform.position;
relativePos.y = relativePos.y + 1;
var desiredRot = Quaternion.LookRotation (relativePos);
transform.rotation = Quaternion.Lerp (transform.rotation, desiredRot, Time.deltaTime * 20f);
}
takes about as long to calculate as the other methods.