简体   繁体   English

围绕一个游戏对象旋转

[英]Orbit around a gameobject in unity

In Unity I have a camera with the following structure 在Unity中,我有一个具有以下结构的相机

GameObject Pan
    => GameObject Rotation
       => GameObject Zoom
          => GameObject Camera (the component that have the camera script)

I have an object target 我有一个对象目标

GameObject target;

I want to rotate in all the direction around that object. 我想围绕该对象沿所有方向旋转。 Like if it's a flying plane, so I can rotate up down left right. 就像是一架飞行的飞机一样,所以我可以左右旋转。

I have the following code 我有以下代码

void ChangePosition()
{
    if(Input.GetAxis("Horizontal") != 0 || Input.GetAxis("Vertical") != 0)
    {
        if (target)
        {
            transform.RotateAround(target.transform.position, transform.right, -Input.GetAxis("Vertical") * speed);
            transform.RotateAround(target.transform.position, transform.up, -Input.GetAxis("Horizontal") * speed);

            rotationObject.transform.LookAt(target.transform.position);
        }
    }
}

It works great when you move only Left, or only up. 当您仅向左或向上移动时,此功能非常有用。

But if you move booth in the same time, the rotation is not intuitive anymore. 但是,如果您同时移动展位,则旋转不再直观。 It also rotate the camera on herself. 它还会旋转照相机。

I would like the camera to only move left or up (so rotate around on 2 axis but never on herself) 我希望相机仅向左或向上移动(所以绕2轴旋转,但不对自己旋转)

How can I fix it ? 我该如何解决?

I do not like to use RotateAround() but their is a much simpler solution. 我不喜欢使用RotateAround()但是它们是一个更简单的解决方案。 First modify your hierarchy, add a new object that is your rotation center a place it at the center of your Target object. 首先修改层次结构,添加一个新对象,该对象是旋转中心,并将其放置在目标对象的中心。

GameObject Target (your target game object)
    => GameObject RotationCenter (local position: 0, 0, 0. The center of Target)
         => GameObject Camera

Then simply rotate you new gameobject RotationCenter . 然后只需旋转您的新游戏对象RotationCenter Something like this should do the trick: 这样的事情应该可以解决问题:

RotationCenter.Rotate(Input.GetAxis("Vertical") * speed, Input.GetAxis("Vertical") * speed);

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

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