将2D位置/旋转转换为3D

时间:2019-02-10 16:32:03

标签: c# unity3d math

我有一个播放器对象,以及一个播放器和一个作为子项的摄像机。

我想使相机围绕播放器旋转一圈,使其始终面对播放器(以0,0,0为中心)。

我有2D方法,我需要转换3D。

对于3D来说,该脚本是什么样的?

谢谢。

 using UnityEngine;
 using System.Collections;

 public class circularMotion : MonoBehaviour {

 public float RotateSpeed;
 public float Radius;

 public Vector2 centre;
 public float angle;

 private void Start()
 {
     centre = transform.localPosition;
 }

 private void Update()
 {

     angle += RotateSpeed * Time.deltaTime;

     var offset = new Vector2(Mathf.Sin(angle), Mathf.Cos(angle)) * Radius;
     transform.localPosition = centre + offset;
 }
 }

1 个答案:

答案 0 :(得分:0)

好吧,一种方法可能是定义一个向上的向量,然后绕相应的轴旋转。

using UnityEngine;

public class circularMotion : MonoBehaviour
{
    public float RotateSpeed = 1;
    public float Radius = 1;

    public Vector3 centre;
    public float angle;

    public Vector3 upDirection = Vector3.up; // upwards direction of the axis to rotate around

    private void Start()
    {
        centre = transform.localPosition;
    }

    private void Update()
    {
        transform.up = Vector3.up;
        angle += RotateSpeed * Time.deltaTime;

        Quaternion axisRotation = Quaternion.FromToRotation(Vector3.up, upDirection);

        // position camera
        Vector3 offset = axisRotation * new Vector3(Mathf.Sin(angle), 0, Mathf.Cos(angle)) * Radius;
        transform.localPosition = centre + offset;

        // look towards center
        transform.localRotation = axisRotation * Quaternion.Euler(0, 180 + angle * 180 / Mathf.PI, 0);
    }
}