简体   繁体   中英

Orbit around a gameobject in unity

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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