【问题标题】:Unity: Allow child object rotation in specified axes only with parent rotationUnity:仅允许子对象在指定轴上旋转父旋转
【发布时间】:2020-12-15 13:35:41
【问题描述】:

我创建了一个小地图,并在小地图(右上角)中显示了敌人的当前位置,因此我创建了导航图像并附加为敌人 GameObject 的子对象。

但是导航图像也会随着它的父游戏对象(敌人)一起旋转,在小地图中也是如此。我希望导航图像仅在 x 轴上旋转,以便在小地图中正确可见。

using UnityEngine.AI;

[RequireComponent(typeof(NavMeshAgent))]
public class EnemyFollow : MonoBehaviour {

    private RaycastHit hit;
    
    NavMeshAgent mAgent;
    
    public Transform player;
    
    private TargetPlayer target;
    
    public GameObject impactEffect;
    
    public int damageToPlayer = 10;
    private int range = 100;



    void Start() {
        mAgent = GetComponent<NavMeshAgent>();
      
    }

    void Update() {
    
        transform.LookAt(player);
        
        if (Physics.Raycast(transform.position, transform.forward, out hit, range)) {
        
            if ("Player".Equals(hit.transform.tag)) {
            
                //follow player
                mAgent.destination = player.position;
                
                //shoot bullet
                GameObject impactDestroy = Instantiate(impactEffect, hit.point, Quaternion.LookRotation(hit.normal));
                Destroy(impactDestroy, 1f);
                
                //damage to Player
                target = hit.transform.GetComponent<TargetPlayer>();
                if (target != null) {
                    target.TakeDamage(damageToPlayer);
                }
            }
            
         
        }
    }

}

【问题讨论】:

    标签: c# unity3d rotation parent


    【解决方案1】:

    我找到了一个非常简单的解决方案

    只需将此脚本附加到您只想在 x 轴上旋转的子对象中

    Using Unity
    
    public class BlockRotation: MonoBehaviour {
    
        void Update()  {
    
        transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0);
    
        }
    }
    

    【讨论】:

      【解决方案2】:

      对小地图应用旋转时,另一个简单的解决方案是使用Transform.RotateAround()。如果您还没有它,则需要确定当前角度与所需角度之间的差异;它看起来像这样:

        float deltaAngle = desiredAngle - currentAngle;
        transform.RotateAround(transform.position, Vector3.up, deltaAngle);
      

      【讨论】:

        猜你喜欢
        • 2016-03-01
        • 1970-01-01
        • 2015-06-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多