Orbit around a gameobject in unity

丶灬走出姿态 提交于 2020-03-04 23:04:57

问题


In Unity I have a camera with the following structure

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)

How can I fix it ?


回答1:


I do not like to use RotateAround() but their is a much simpler solution. 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. Something like this should do the trick:

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


来源:https://stackoverflow.com/questions/57975282/orbit-around-a-gameobject-in-unity

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!