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.

Question Need help with an AI aiming system

Discussion in 'Scripting' started by cofcof, May 20, 2024.

  1. cofcof

    cofcof

    Joined:
    Sep 17, 2013
    Posts:
    19
    For some reason I had this same script working in the same conditions before but now it's not working in the same situation i have one projectile that just fires from the location of the entity shooting it. That works fine and is really accurate, but when a projectile is far away from the "Caster" it stops working and is like way behind the intended target. By exactly 4 meters everytime it misses by one in-game cell everytime.


    Code (CSharp):
    1.  
    2. //This is my aiming script
    3. public static Vector3 Aimbot(Transform target, Vector3 startPos, float projectileSpeed)
    4.     {
    5.         Vector3 enemyPostion = target.transform.position;
    6.         Enemy enemy = target.GetComponent<Enemy>();
    7.         Vector3 enemyPosition = target.GetComponent<Collider>().bounds.center;
    8.  
    9.         float distance = Vector3.Distance(startPos, enemyPosition);
    10.         float travelTime = distance / (projectileSpeed + (enemy.velocity.magnitude));
    11.  
    12.         Vector3 predictedPosition = enemyPosition + (enemy.velocity * travelTime);
    13.  
    14.         return predictedPosition;
    15.     }
    Code (CSharp):
    1.  
    2. //this is called when the projectile is created look at where I need to hit then move forward at a set speed.
    3. void Start()
    4.     {
    5.         if(startVFX != null)
    6.         Instantiate(startVFX, transform.position, startVFX.transform.rotation);
    7.        
    8.         if(GetComponent<Rigidbody>() == null)
    9.         {
    10.             Rigidbody rb = gameObject.AddComponent<Rigidbody>();
    11.             rb.constraints = RigidbodyConstraints.FreezeAll;
    12.             rb.useGravity = false;
    13.         }
    14.        
    15.         transform.LookAt(DamageManager.Aimbot(target.transform, transform.position, speed));
    16.     }

    Code (CSharp):
    1.  
    2. //calculate the targets velocity per frame
    3. IEnumerator CalcVelocity()
    4.     {
    5.         while(true)
    6.         {
    7.             yield return new WaitForSeconds(Time.deltaTime);
    8.  
    9.             Vector3 currentPosition = transform.position;
    10.             velocity = (currentPosition - lastPosition) / Time.deltaTime;
    11.  
    12.             lastPosition = currentPosition;
    13.         }
    14.     }