Shubham Pandit
Shubham Pandit

Reputation: 47

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

enter image description here

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

}

Upvotes: 0

Views: 1290

Answers (2)

rodamn
rodamn

Reputation: 2211

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

Upvotes: 0

Shubham Pandit
Shubham Pandit

Reputation: 47

enter image description here

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

    }
}

Upvotes: 1

Related Questions