Game Bucks

Bullet Trajectory/Physics (C#)

Well, this is sort of like OMA’s COD Kit script because it is from Jeremy Clark but cannot implement penetration… Translated to C# and modified a bit.

using UnityEngine;
using System.Collections;

public class RealBullet : MonoBehaviour {
public GameObject bulletHole;
public GameObject hitEffect;

public LayerMask layersToAffect;

public int minDamage = 20;
public int maxDamage = 25;
public float force = 4;
public float muzzleVelocity = 600;
public float minRange = 50;
public float maxRange = 500;

private Vector3 travelVelocity;
private Vector3 newPos;
private Vector3 oldPos;
private bool hasHit = false;
private float distance;
private Vector3 dir;
private float dist;
private int finalDmg;
private float damageRangeFactor;
private float percDmgRed;

void Start() {
newPos = transform.position;
oldPos = newPos;
travelVelocity = transform.forward * muzzleVelocity;
CalculateDamage();
}

void Update() {
if(hasHit) {
return;
}

newPos += (travelVelocity + transform.forward) * Time.deltaTime;
dir = newPos - oldPos;
dist = dir.magnitude;

if(dist > 0) {
dir /= dist;
OnHit();
}

oldPos = transform.position;
transform.position = newPos;
}

void OnHit() {
RaycastHit hit;
if(Physics.Raycast(oldPos, dir, out hit, dist, layersToAffect.value)) {
newPos = hit.point;

if(hit.collider) {
hit.collider.SendMessageUpwards("ApplyDamage", finalDmg * damageRangeFactor, SendMessageOptions.DontRequireReceiver);
}

if(hit.collider.rigidbody) {
hit.collider.rigidbody.AddForce((transform.forward * force) / hit.rigidbody.mass, ForceMode.Impulse);
}

GameObject hole = Instantiate(bulletHole, hit.point + (hit.normal * Random.Range(0.024f, 0.025f)), Quaternion.LookRotation(hit.normal)) as GameObject;
Instantiate(hitEffect, hit.point + (hit.normal * 0.1f), Quaternion.LookRotation(hit.normal));
if(hit.collider.rigidbody || (hit.collider.animation && hit.collider.animation.isPlaying)) {
hole.transform.parent = hit.collider.transform;
}

hasHit = true;
transform.DetachChildren();
Destroy(gameObject);
}
}

private void CalculateDamage() {
finalDmg = Random.Range(minDamage, maxDamage);

RaycastHit dmgChk;
if(Physics.Raycast(transform.position, transform.forward, out dmgChk, maxRange, layersToAffect.value)) {
distance = Vector3.Distance(transform.position, dmgChk.point);
percDmgRed = (distance - minRange) / (maxRange - minRange);
damageRangeFactor = Mathf.Clamp01(damageRangeFactor);
if(distance - minRange > 0 && distance < maxRange) {
damageRangeFactor = 1 - percDmgRed;
}
else if(distance - minRange < 0) {
damageRangeFactor = 1;
}
else if(distance > maxRange) {
damageRangeFactor = 0;
}
}
}
}

Game Bucks

Add comment

Follow us

Don't be shy, get in touch. We love meeting interesting people and making new friends.