- Home /
change to raycast shooting instead of rigidbody shooting
I have two scripts; on is a shooting script and the other is bullet damage. The shooting script at the moment shoots rigidbody bullets. Is there a way I can change the shooting script to shoot raycast bullets instead of rigidbody bullets and then change the damage script to accommodate the raycast bullets?
shooting script:
RequireComponent(AudioSource);
var audioSource: AudioSource;
var Projectile : Rigidbody;
var ProjectileSpeed : int = 10;
var FireRate : float = 10; // The number of bullets fired per second
var lastfired : float; // The value of Time.time at the last firing moment
var gunshot : AudioClip;
var muzzleflash :Transform;
function Start() {
audioSource = GetComponent.<AudioSource>();
}
function Update ()
{
if (Input.GetAxis("Fire1")>0f)
{
if (Time.time - lastfired > 1 / FireRate)
{
lastfired = Time.time;
var clone : Rigidbody;
clone = Instantiate(Projectile, transform.position, transform.rotation);
clone.velocity = transform.TransformDirection (Vector3.forward * ProjectileSpeed);
audioSource.PlayOneShot(gunshot, 0.7F);
Instantiate (muzzleflash,transform.position,transform.rotation);
}
}
}
bullet damage script:
var dmg:float = 20;
function OnTriggerEnter(hit:Collider){
if(hit.tag == "Player"){
hit.transform.SendMessage("Damage",dmg);
}
}
Answer by shadowpuppet · Apr 16, 2018 at 03:32 PM
you can do away with the bulletDamage script if you use rayCast. This is C#. I don't know JS but should be close enough to adapt to Java
Ray bulletRay;
RaycastHit rayHit;
public int dist = 45; //distance ray/bullet travel
public float lastfired;
Update () {
if (Input.GetAxis("Fire1")>0f)
{
if (Time.time - lastfired > 1 / FireRate)
{
lastfired = Time.time;
bulletRay = new Ray(transform.position, transform.forward*dist);
Debug.DrawRay (transform.position, transform.forward*dist, Color.yellow);
if (Physics.Raycast(transform.position, transform.forward, out rayHit,dist))
{
if(rayHit.transform.gameObject.tag == ("Player"))
hit.transform.SendMessage("Damage",dmg);
}
}
}
@shadowpuppet I didn't have to convert it to javascript, the damage message goes to my javascript health script just fine. If I wanted to make a railgun using the same script how do I make the raycast visible ?
not sure how to make the raycast visible. $$anonymous$$aybe a Line Render from the ray origin to the object it is hitting https://docs.unity3d.com/$$anonymous$$anual/class-LineRenderer.html I have ,on one of my guns, where I shoot tracers bullets. so in addition to the raycast I instantiate a tiny glowing sphere that has a Trail Rnderer component on it https://docs.unity3d.com/$$anonymous$$anual/class-TrailRenderer.html
Your answer
Follow this Question
Related Questions
shooting raycast 1 Answer
Best way to shoot physical bullets? 2 Answers
Multiplayer FPS Bullets: should they be rigid bodies or raycast? 1 Answer
fps shooting enemy 1 Answer
RayCast Shooting And Errors 1 Answer