简体   繁体   English

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

[英]Converting 2D position / rotation to 3D

I have a player-object, and a player and a camera attached to it as childs. 我有一个播放器对象,还有一个播放器和一台照相机,作为一个孩子。

I would like to rotate the camera in a circle around the player so that it always faces the player (which is centered at 0,0,0). 我想将相机绕播放器旋转一圈,使其始终面对播放器(以0,0,0为中心)。

I have a 2D approach which I need to convert 3D. 我有2D方法,我需要转换3D。

What would this script look like for 3D? 对于3D,此脚本将是什么样?

Thank you. 谢谢。

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

Well, one approach could be to define an upwards vector and then rotate around the corresponding axis. 好吧,一种方法可能是定义一个向上的向量,然后绕相应的轴旋转。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM