围绕一个游戏对象旋转 [英] Orbit around a gameobject in unity

查看:118
本文介绍了围绕一个游戏对象旋转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我有一个对象目标

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.

我有以下代码

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.

我希望相机仅向左或向上移动(所以绕2轴旋转,但绝不对自己旋转)

I would like the camera to only move left or up (so rotate around on 2 axis but never on herself)

我该如何解决?

推荐答案

我不喜欢使用RotateAround(),但是它们是一个简单得多的解决方案.首先修改层次结构,添加一个新对象,将其作为旋转中心,并将其放置在目标对象的中心.

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

然后只需旋转您新的游戏对象RotationCenter.这样的事情应该可以解决问题:

Then simply rotate you new gameobject RotationCenter. Something like this should do the trick:

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

这篇关于围绕一个游戏对象旋转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆