Search Unity

Figuring out where a projectile will go

Discussion in 'Physics' started by eedok, Mar 7, 2016.

  1. eedok

    eedok

    Joined:
    Sep 21, 2009
    Posts:
    194
    I have an old school space game during a game jam and want to turn it into a full game, only issue I'm having is making an AI that can A) Hit things accurately and B) realize when projectiles are coming towards them and avoid them. What makes it difficult is the projectiles have wonky paths because they're affected by a crude approximation of gravity:


    Now how the projectiles move is the star in this picture has a component called Gravity Source on it, and it supplies the force calculations:
    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class GravitySource : MonoBehaviour
    5. {
    6.     public Vector3 ForceAtPoint(Vector3 xyz)
    7.     {
    8.         var newForce = transform.position - xyz;
    9.  
    10.         if (newForce.sqrMagnitude > 0.0f)
    11.         {
    12.             newForce = (newForce / newForce.sqrMagnitude) * 5000.0f;
    13.         }
    14.  
    15.         return newForce;
    16.     }
    17. }
    18.  
    and the missiles & player have a Gravity Receiver, the missiles having a 10x multiplier and players 1x

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class GravityReciever : MonoBehaviour {
    6.     public float gravityMultiplier = 1.0f;
    7.     public GravitySource gravitySource;
    8.     Rigidbody rb;
    9.  
    10.     void Start()
    11.     {
    12.         rb = GetComponent<Rigidbody>();
    13.     }
    14.  
    15. void FixedUpdate () {
    16.         rb.AddForce(gravitySource.ForceAtPoint(transform.position) * Time.fixedDeltaTime * gravityMultiplier, ForceMode.Acceleration);
    17.     }
    18. }
    19.  
    20.  
    Now my question is, how do I calculate where a projectile is going so I can have my AI make decent shots as well as dodging incoming fire?



    https://dl.dropboxusercontent.com/u/168938/Games/Space Melee/OrbitProjectileExample.zip (a copy of the physics code with all the assets removed to play around with/make examples)