我正在做一个坦克游戏统一,我想旋转坦克的炮塔与鼠标。主照相机是炮塔的孩子。
我试过这个:
Ray dir = MainCamera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(dir, out hit)){}
Turret.transform.LookAt(hit.point);但炮塔开始无限旋转。我想是因为MainCamera是炮塔的孩子。所以我不知道该怎么做。
你能帮帮我吗?
发布于 2022-09-17 12:10:17
计算鼠标与炮塔之间的夹角,并用quaternion.lookat旋转
发布于 2022-09-17 13:19:47
你可以试试这样的东西。
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);
}
}https://stackoverflow.com/questions/73754556
复制相似问题