简体   繁体   中英

Unity: Allow child object rotation in specified axes only with parent rotation

在此处输入图片说明

I have created a mini-map and I am showing the current location of the enemy in the mini-map (on top right corner) so I created navigation image and attached as a child of the enemy GameObject.

But navigation image also rotates along with its parent Gameobject (enemy) so does it in the mini-map. I want the navigation image to rotate only in the x-axis so it is visible correctly in the mini-map.

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);
                }
            }
            
         
        }
    }

}

在此处输入图片说明

I found a very easy solution

Just attach this script in the child object which you want to rotate only in x-axis

Using Unity

public class BlockRotation: MonoBehaviour {

    void Update()  {

    transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0);

    }
}

When applying rotation to your minimap, another easy solution would be to use Transform.RotateAround() . If you don't already have it, you'd need to determine the difference between the current angle and your desired angle; it'd look something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM