如何使用四元数旋转实例化的对象?

时间:2019-09-15 01:17:22

标签: c# unity3d

我有一个球体脚本,在碰撞时它会实例化一个圆柱体(object3),然后一旦圆柱体出现,圆柱体应该以某种方式旋转,旋转方向无关紧要。但是我的代码没有使圆柱体旋转。我尝试了不同的代码行,并尝试将四元数行放在了update函数和on on碰撞函数中,但是都没有办法使圆柱体旋转。我不确定这是否与我的代码有关,或者我是否必须在统一的3d设置中进行某些操作。有什么建议么?

public class sphereBehavior : MonoBehaviour
{
    public GameObject object3;
    private Vector3 direction = new Vector3(-1, 0, 0);
    private Vector3 rotateDirection = new Vector3(0, 0, 1);

    // Update is called once per frame
    void Update()
    {
        transform.Translate(direction * Time.deltaTime, Space.World);
        transform.Rotate(rotateDirection, Space.World);

        Quaternion Cylinder = Quaternion.Euler(90,50,69);
        transform.rotation = Quaternion.Slerp(transform.rotation, Cylinder, Time.deltaTime);

    }

    //void OnCollisionEnter(Collision collision) => Instantiate(object3, new Vector3(0, 1, -2), Quaternion.identity);

    void OnCollisionEnter(Collision collision)
    {
        Instantiate(object3, new Vector3(0, 1, -2), Quaternion.identity);
        Destroy(collision.gameObject);
    }

}

1 个答案:

答案 0 :(得分:3)

要旋转圆柱,您需要旋转圆柱

transform.rotation指的是脚本附加到的对象(即,如果要使用的类名是您的领域)。为了旋转生成的圆柱体,您需要:

  1. 在生成它后保存对它的引用
  2. 引用它的变换

仅调用局部变量Cylinder是不够的。因此,我将其重命名为更具信息性的内容。

public class sphereBehavior : MonoBehaviour
{
    public GameObject object3;
    private Vector3 direction = new Vector3(-1, 0, 0);
    private Vector3 rotateDirection = new Vector3(0, 0, 1);
    private GameObject theCylinder;

    // Update is called once per frame
    void Update()
    {
        transform.Translate(direction * Time.deltaTime, Space.World);
        transform.Rotate(rotateDirection, Space.World);

        Quaternion newRotation = Quaternion.Euler(90,50,69);
        theCylinder.transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, Time.deltaTime); //reference it
    }

    void OnCollisionEnter(Collision collision)
    {
        theCylinder = Instantiate(object3, new Vector3(0, 1, -2), Quaternion.identity); //save a reference
        Destroy(collision.gameObject);
    }
}

请注意,这一次只能引用一个生成的圆柱体,因此,最好创建一个新的脚本来处理旋转并将其附加到预制件上。