【问题标题】:Converting 2D position / rotation to 3D将 2D 位置/旋转转换为 3D
【发布时间】:2019-07-04 05:41:41
【问题描述】:

我有一个播放器对象,以及一个作为子对象连接到它的播放器和相机。

我想将相机绕玩家旋转一圈,使其始终面向玩家(以 0,0,0 为中心)。

我有一个需要转换 3D 的 2D 方法。

这个脚本在 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;
 }
 }

【问题讨论】:

  • 你不妨看看四元数 - en.wikipedia.org/wiki/Quaternion
  • 如果您不介意使用内置方法,可以使用Transform.LookAtTransform.RotateAround 来创建想要的效果。
  • @DogeAmazed 我想使用角度方法。

标签: c# unity3d math


【解决方案1】:

嗯,一种方法是定义一个向上的向量,然后围绕相应的轴旋转。

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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-16
    • 2013-11-22
    • 2012-05-24
    • 2015-02-09
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多