Hello. I am curremtly making a game that needs realistic shooting. Is it better to do this with raycasting or rigidbody physics attached to a bullet object. I have heard in places that rigidbodied bullets can go through things but they are more realistic. I would prefer to use rigidbody physics as well because I have knowledge on them. Is the rigidbody going through objects a problem and if it is how can I solve it?
Thanks, drift501
You can reasonably simulate a real shot with raycasting: do a first exploratory raycast when the fire button is pressed; based on the hit.distance, calculate the drop and flight time, wait for the flight time delay and do the actual raycast shot taking the drop into account - like this:
var bulletSpeed: float = 1000; // bullet speed in meters/second var shotSound: AudioClip; function Fire(){ if (audio) audio.PlayOneShot(shotSound); // the sound plays immediately var hit: RaycastHit; // do the exploratory raycast first: if (Physics.Raycast(transform.position, transform.forward, hit)){ var delay = hit.distance / bulletSpeed; // calculate the flight time var hitPt = hit.point; hitPt.y -= delay * 9.8; // calculate the bullet drop at the target var dir = hitPt - transform.position; // use this to modify the shot direction yield WaitForSeconds(delay); // wait for the flight time // then do the actual shooting: if (Physics.Raycast(transform.position, dir, hit){ // do here the usual job when something is hit: // apply damage, instantiate particles etc. } }
You should separate the logic from the visual representation.
Use raycasting for the actual hit detection since it’s more reliable. Then you can use actual bullet objects (even with rigidbody physics if you like) or any other form of visual representation of the shot (in my current project we are using a particle emitter for a machine gun for example).