Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question How can I have my gun barrel point at the enemy when aim locked? Right now only the player does.

Discussion in 'Scripting' started by Eversmann, Apr 16, 2023.

  1. Eversmann

    Eversmann

    Joined:
    May 3, 2013
    Posts:
    29
    As you can see in the picture, if I aim lock, the gun barrel will point to the side, but I want the barrel to actually point at the enemy cuz that is where the Ray is shot from. Here is the part of the code that handles aim lock. aimLockPosition is an empty game object that is on the gun, just under the barrel slightly.

    Code (CSharp):
    1. public void LockOnEnemy()
    2.     {
    3.         LayerMask lockOnLayer = LayerMask.GetMask("Enemy");
    4.        
    5.         Collider[] enemies = Physics.OverlapSphere(transform.position, lockOnRadius, lockOnLayer);
    6.        
    7.         if (enemies.Length > 0)
    8.         {
    9.             Debug.Log("Targeting " + enemies[0].name);
    10.             float nearestDistance = Mathf.Infinity;
    11.             foreach (Collider enemy in enemies)
    12.             {
    13.                 float distance = Vector3.Distance(transform.position, enemy.transform.position);
    14.                 if (distance < nearestDistance)
    15.                 {
    16.                     nearestDistance = distance;
    17.                     targetEnemy = enemy.transform;
    18.                 }
    19.             }
    20.         }
    21.         else
    22.         {
    23.             targetEnemy = null;
    24.         }
    25.        
    26.         if (targetEnemy != null)
    27.         {
    28.             // Rotate the player towards the target enemy.
    29.             Vector3 direction = (targetEnemy.position - aimLockPoint.position).normalized;
    30.             direction.y = 0;
    31.             transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction), Time.deltaTime * 10f);
    32.         }
    33.     }
    34.    
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,947
    A great video on gun parallax / aim offset:

     
    Eversmann likes this.
  3. Eversmann

    Eversmann

    Joined:
    May 3, 2013
    Posts:
    29
    Thank you. I forgot to mention I am using fixed camera angles, with auto lock in the style of RE games. Does this apply to that too?