【问题标题】:Rotating a child gameobject relative to immediate parent相对于直接父对象旋转子游戏对象
【发布时间】:2020-02-06 19:01:23
【问题描述】:

大家好,我正在尝试相对于另一个子游戏对象旋转一个子游戏对象。例如,如下面的层次结构所示,我正在尝试分别相对于它们的直接父级 PA_DroneWingLeft(和 PA_DroneWingRight)旋转 PA_DroneBladeLeft(和 PA_DroneBladeRight)。我希望这些刀片旋转到位。相反,我让它们在 y 方向上相对于主要父级(Air Drone)全局旋转。我认为我注释掉的 Update 方法中的那行应该有效,它确实有效,但它仍然相对于 Air Drone 旋转而不是到位。第二行,RotateAround 方法 我尝试创建一个名为 Left Pivot 的空游戏对象,并将其放置在左翼中心附近,并让左刀片围绕该中心旋转,但没有用。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LeftBladeRotation : MonoBehaviour
{
  GameObject leftBlade;
  private float speed;
  private float angle;
  GameObject leftPivot;

// Start is called before the first frame update
void Start()
{
    speed = 10f;
    leftBlade = transform.Find("PA_DroneBladeLeft").gameObject;
    angle = 0f;
    leftPivot = GameObject.FindGameObjectWithTag("Air Drone").transform.Find("PA_Drone").transform.Find("PA_DroneWingLeft").transform.Find("Left Pivot").gameObject;
}

// Update is called once per frame
void Update()
{
    angle += speed * Time.deltaTime;
    Quaternion rotation = Quaternion.Euler(new Vector3(0f, angle, 0f));

    //leftBlade.transform.localRotation = rotation;
    leftBlade.transform.RotateAround(leftPivot.transform.localPosition, Vector3.up, angle);

}

}

【问题讨论】:

    标签: unity3d rotation transform local quaternions


    【解决方案1】:

    这是您的脚本,稍作改动。当我将它附加到刀片游戏对象上时,它实际上可以工作。

    using UnityEngine;
    
    public class BladeRotate : MonoBehaviour
    {
        private float _speed;
        private float _angle;
    
        private void Start()
        {
            _speed = 400f;
            _angle = 0f;
        }
    
        private void Update()
        {
            _angle += _speed * Time.deltaTime;
            var rotation = Quaternion.Euler(new Vector3(0f, _angle, 0f));
            transform.localRotation = rotation;
        }
    }
    

    第二行不起作用,因为您将刀片绕全局 y 轴旋转 Vector3.up

    这是另一种选择。在刀片上附加以下脚本。

    using UnityEngine;
    
    public class BladeRotate : MonoBehaviour
    {
        [SerializeField] private int speed = 400;
        private Transform _transform;
    
        private void Start()
        {
            _transform = transform;
        }
    
        private void Update()
        {
            transform.RotateAround(_transform.position, _transform.up, speed * Time.deltaTime);
        }
    }
    

    【讨论】:

    • 嘿Musap,感谢您的帮助。不幸的是,您的两个解决方案均无效。在第一个解决方案中,机翼和叶片都围绕主父(Air Drone)的 y 轴旋转。在第二种解决方案中,只有刀片围绕 Air Drone 父级的 y 轴旋转。似乎它一直认为父母是空中无人机。也许如果我使用 SetParent();
    • @user1867845 非常抱歉!我的意思是您需要将脚本附加到刀片而不是机翼上。我现在正在改变我的答案。对不起。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-03
    • 1970-01-01
    相关资源
    最近更新 更多