问题
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