- Home /
 
 
               Question by 
               fiterpilot · Dec 21, 2017 at 09:53 PM · 
                c#raycastgunprojectile  
              
 
              Raycast Projectile w/ Physics
I'm trying to make a raycast the responds to physics. I do NOT want to use the collision system since these projectiles will be moving rather fast and the collision system isn't very reliable with fast moving objects.
I've been trying but ultimately I have no idea what to do. Any help?
               Comment
              
 
               
              Answer by StetsonT22 · Dec 21, 2017 at 11:53 PM
You can make an array of a bunch of shorter raycasts, that way you can make adjustments to the line, such as gravity and/or ricochet/bounce...
Answer by ElijahShadbolt · Dec 22, 2017 at 01:14 AM
This is the technique I use. It's not as precise as kinematic formulas, but it works well.
 Projectile.cs
 using UnityEngine;
 
 public class Projectile : MonoBehaviour
 {
     public Vector3 velocity;
     public float gravityMultiplier = 1f;
     public LayerMask hitMask = -1; // all layers by default
 
     void FixedUpdate()
     {
         // apply acceleration
         velocity += Physics.gravity * gravityMultiplier * Time.fixedDeltaTime;
 
         // get difference between last position and next position
         Vector3 displacement = velocity * Time.fixedDeltaTime;
 
         // get Raycast ray (cache last position)
         Ray ray = new Ray(transform.position, displacement);
         RaycastHit hit;
 
         // apply displacement
         transform.position += displacement;
 
         // OPTIONAL: update rotation
         transform.rotation = Quaternion.LookRotation(displacement, Vector3.up);
 
         // raycast for any collisions since last position
         if (Physics.Raycast(ray, out hit, displacement.magnitude, hitMask))
         {
             // hit something!
             
             // example events
             Debug.Log(this.name + " has hit " + hit.collider.name + " at point " + hit.point);
             hit.collider.SendMessage("OnProjectileCollision", this, SendMessageOptions.DontRequireReceiver);
             Destroy(this.gameObject);
         }
     }
 }
 
               
 HitBox.cs
 using UnityEngine;
 
 public class HitBox : MonoBehaviour
 {
     private void OnProjectileCollision(Projectile proj)
     {
         Debug.Log(this.name + ": I've been hit by " + proj.name + "!");
     }
 }
 
              Your answer