首页 > 解决方案 > 脚本附加到多个对象时旋转单个对象

问题描述

我在 Unity 中有一个游戏,其中添加了三个对象(立方体、圆柱体、胶囊)。对于这些游戏对象,我添加了一个脚本,当他们按下左键和 x、y 或 z 时,它们沿轴旋转,沿各自的轴旋转对象。但是当我尝试旋转单个对象时,其他对象也会旋转。如何在不影响其他对象的情况下旋转每个对象。

if (Input.GetMouseButton(0) && Input.GetKey(KeyCode.Z))
{
    transform.RotateAround(transform.position, transform.forward, Time.deltaTime * 90f);
}
if (Input.GetMouseButton(0) && Input.GetKey(KeyCode.X))
{
    transform.RotateAround(transform.position, transform.right, Time.deltaTime * 90f);
}
if (Input.GetMouseButton(0) && Input.GetKey(KeyCode.Y))
{
    transform.RotateAround(transform.position, transform.up, Time.deltaTime * 90f);
}

标签: c#unity3drotationtransformgame-development

解决方案


分别使用输入条件Input.GetKey(KeyCode.X),尝试三个单独的单一行为:Input.GetKey(KeyCode.Y)Input.GetKey(KeyCode.Z)

if (Input.GetMouseButton(0) && Input.GetKey(KeyCode.X)) { 
    transform.RotateAround(transform.position, transform.forward, Time.deltaTime * 90f); 
}

transform适用于附加到的游戏对象的转换Monobehvaiour,因此如果您将脚本附加到许多游戏对象,则逻辑适用于所有游戏对象。

您需要制作 3 个不同Monobehaviours的并分别处理输入逻辑,或者制作一个全局Monobehaviour旋转处理程序,在其中为每个游戏对象保留一个引用,以便您可以分别处理每个变换。


推荐阅读