I'm making a tank game in unity and I want to rotate tank's turret with mouse. The main Camera is a child of the turret.
I've tried this:
Ray dir = MainCamera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(dir, out hit)){}
Turret.transform.LookAt(hit.point);
But the turret starts to rotate infinitely. I think it's because of MainCamera is a child of Turret. So I don't know how to do this.
Can you help me?
CodePudding user response:
Calculate the angle between mouse and turret and rotate it with quaternion.lookat
CodePudding user response:
You can try something like this.
using UnityEngine;
public class Rotator : MonoBehaviour
{
[SerializeField]
private Camera _camera;
[SerializeField] private float _rotationFactor = 0.01f;
private Transform _cameraTransform;
void Start()
{
_cameraTransform = _camera.transform;
}
void Update()
{
var screenCenter = new Vector3(Screen.width / 2.0f, Screen.height / 2.0f);
// This prevents camera rotation when mouse is in 100 pixels circle in screen center.
if (!(Input.mousePosition - screenCenter).magnitude < 100f)
return;
var mouseWorldPos = _camera.ScreenToWorldPoint(Input.mousePosition Vector3.forward);
Debug.Log(mouseWorldPos);
_camera.transform.rotation = Quaternion.Slerp(
_camera.transform.rotation,
Quaternion.LookRotation(mouseWorldPos - _cameraTransform.position),
_rotationFactor);
}
}