Raycast Bullet Physics Simulator

I had been working on this piece of code to simulate ballistics accurately using raycasts, and figured that maybe some other people could get some use out of it. Just spawn an object with the desired rotation (I have it setup here to take the rotation of the object and use it to calculate the path, you can change it if need be), gravity, and velocity. The script will take it from there. I hope this comes in handy for those who want it!

  • using UnityEngine;
  • using System.Collections;
    • public class BulletPhysics : MonoBehaviour {
  • public float gravity = -9.81f;
  • public float velocity = 10000;
  • public Vector3 origin;
    • float increment = 0;
    • void Start(){
  • origin = transform.position;
  • }
    • void FixedUpdate () {
  • //displacement = v0*t + 0.5at^2
  • Debug.DrawLine (disp(increment), disp(increment + 0.02f), Color.red, 60);
  • RaycastHit hit;
    • if (Physics.Linecast(disp(increment), disp(increment + 0.02f), out hit)) {
  • Destroy (gameObject);
  • }
    • transform.position = disp (increment + 0.02f);
  • increment += 0.02f; //<— fixedupdate time (sorta)
  • }
    • Vector3 disp (float t){
  • Vector3 vel = new Vector3 (velocity * Mathf.Cos(Mathf.Deg2Rad * transform.localEulerAngles.x), velocity * Mathf.Sin(Mathf.Deg2Rad * -transform.localEulerAngles.x), 0);
  • Vector3 disp = Quaternion.Euler (0, transform.eulerAngles.y, transform.eulerAngles.z) * new Vector3 (0, vel.y * t + 0.5f * Mathf.Pow(t, 2) * gravity, vel.x * t) + origin;
  • return disp;
  • }
  • }
1 Like

Good job man