Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only. On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live. Read our full announcement for more information and let us know if you have any questions.

Bug Enemy will not aim at player

Discussion in 'Scripting' started by Mrhhdestroyer, Feb 22, 2024.

  1. Mrhhdestroyer

    Mrhhdestroyer

    Joined:
    May 12, 2021
    Posts:
    2
    So I have a enemy in my scene and everything works, I just cant get it to aim at my player.

    The Snowballs are launched out of the launchPoint but I cant figure out how to rotate it to aim directly at the player.

    Here's the code that makes him fire:
    Code (CSharp):
    1. void Fire()
    2. {
    3.  
    4.     if  (!alreadyAttacked)
    5.     {
    6.         Rigidbody rb = Instantiate(Snowball, launchPoint.position, launchPoint.rotation).GetComponent<Rigidbody>();
    7.         rb.AddForce(transform.forward * XForce, ForceMode.Impulse);
    8.         rb.AddForce(transform.up * YForce, ForceMode.Impulse);
    9.  
    10.         alreadyAttacked = true;
    11.         Invoke(nameof(ResetAttack), throwCoolDown);
    12.     }
    13. }
     
    Last edited: Feb 22, 2024
  2. APSchmidt

    APSchmidt

    Joined:
    Oct 31, 2023
    Posts:
    265
    What did you try?

    Does it work? I don't think I've seen anywhere a rigidbody being instantiated.
     
  3. Mrhhdestroyer

    Mrhhdestroyer

    Joined:
    May 12, 2021
    Posts:
    2
    Well I can re-write it as this:
    Code (CSharp):
    1. void Fire()
    2. {
    3.  
    4.     if  (!alreadyAttacked)
    5.     {
    6.         GameObject projectile = Instantiate(Snowball, launchPoint.position, launchPoint.rotation);
    7.         Rigidbody rb = projectile.GetComponent<Rigidbody>();
    8.         rb.AddForce(transform.forward * XForce, ForceMode.Impulse);
    9.         rb.AddForce(transform.up * YForce, ForceMode.Impulse);
    10.  
    11.         alreadyAttacked = true;
    12.         Invoke(nameof(ResetAttack), throwCoolDown);
    13.     }
    14. }
    The enemy fires is the general direction to the player, but doesn't hit the player even if the launchpoint is always rotated towards the player by adding this to the update function:
    Code (CSharp):
    1. launchPoint.transform.LookAt(target.position);

    If the player is higher or lower than the enemy, the enemy will just shoot straight every time.

    Would you know how to fix this?
     
    Last edited: Feb 22, 2024