53 lines
1.7 KiB
C#
53 lines
1.7 KiB
C#
using System;
|
||
using UnityEngine;
|
||
|
||
namespace CharacterPreview
|
||
{
|
||
public class ModelMove:MonoBehaviour
|
||
{
|
||
private Camera _camera;
|
||
public Camera currentCamera
|
||
{
|
||
get
|
||
{
|
||
if (!_camera)
|
||
{
|
||
_camera = Camera.main;
|
||
if (!_camera)
|
||
{
|
||
_camera = FindObjectOfType<Camera>();
|
||
}
|
||
}
|
||
return _camera;
|
||
}
|
||
}
|
||
private void Start()
|
||
{
|
||
if (currentCamera)
|
||
{
|
||
var worldPos = CameraLocalToWorld(currentCamera, new Vector3(1, -1, 1));
|
||
transform.position = worldPos;
|
||
}
|
||
else
|
||
{
|
||
transform.position = new Vector3(8, 8, -16);
|
||
}
|
||
}
|
||
/// <summary>
|
||
/// 将摄像机局部坐标系中的点转换为世界坐标系中的点。
|
||
/// 假设摄像机局部坐标系:前向为 +Z,右为 +X,上为 +Y。
|
||
/// </summary>
|
||
/// <param name="camera">目标摄像机</param>
|
||
/// <param name="localPoint">在摄像机局部坐标系中的点</param>
|
||
/// <returns>对应的世界坐标</returns>
|
||
public static Vector3 CameraLocalToWorld(Camera camera, Vector3 localPoint)
|
||
{
|
||
if (camera == null)
|
||
throw new System.ArgumentNullException(nameof(camera));
|
||
|
||
Transform camTransform = camera.transform;
|
||
// 旋转局部点到世界方向,然后加上摄像机位置
|
||
return camTransform.position + camTransform.rotation * localPoint;
|
||
}
|
||
}
|
||
} |