Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by solly576 · Aug 31, 2013 at 07:05 PM · physicsraycastguncharacter controllershooter

Gun script using Physics.Raycast not working?

I am using these scripts for my game to make my gun fire and shoot zombies.

This is the script on the gun:

 function FireOneShot () {
     var direction = transform.TransformDirection(Vector3.forward);
     var hit : RaycastHit;
     Debug.DrawRay(transform.position, direction, Color.blue);
     // Did we hit anything?
     if (Physics.Raycast (transform.position, direction, hit, range)) {
         // Apply a force to the rigidbody we hit
         if (hit.rigidbody)
             hit.rigidbody.AddForceAtPosition(force * direction, hit.point);
         
         // Place the particle system for spawing out of place where we hit the surface!
         // And spawn a couple of particles
         if (hitParticles) {
             hitParticles.transform.position = hit.point;
             hitParticles.transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
             hitParticles.Emit();
         }
 
         // Send a damage message to the hit object            
         hit.collider.SendMessageUpwards("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
         Debug.Log("HIT " + hit.collider.name);
     }
     
     bulletsLeft--;
 
     // Register that we shot this frame,
     // so that the LateUpdate function enabled the muzzleflash renderer for one frame
     m_LastFrameShot = Time.frameCount;
     enabled = true;
     
     // Reload gun in reload Time        
     if (bulletsLeft == 0)
         Reload();            
 }

And this script on my zombie:

 function ApplyDamage (damage : float) {
 healthPoints -= damage;
 if (Time.time > gotHitTimer && painBig && painLittle) {


         if (healthPoints < maximumHitPoints * 0.2 || damage > 20) {
             audio.PlayOneShot(painBig, 1.0 / audio.volume);
             gotHitTimer = Time.time + Random.Range(painBig.length * 2, painBig.length * 3);
         } else {
             // Play a small pain sound
             audio.PlayOneShot(painLittle, 1.0 / audio.volume);
             gotHitTimer = Time.time + Random.Range(painLittle.length * 2, painLittle.length * 3);
         }
     }
     if (healthPoints <= 0.0)
         Die();
 }

Could anyone tell me why this is not working? My character and the zombie both have a character controller. The Debug.DrawRay doesn't appear to do anything, but the gun does fire!

Comment
Add comment · Show 5
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image cdrandin · Aug 31, 2013 at 07:11 PM 0
Share

What is not working? What are you trying to achieve that these scripts aren't doing?

avatar image cdrandin · Aug 31, 2013 at 07:15 PM 0
Share

Also, I do think your Debug.DrawRay does do something, but it does something for that 1 frame which happens too fast for the eye to see or even the screen to show.

avatar image cdrandin · Aug 31, 2013 at 07:18 PM 0
Share

if you want to see the ray put it in your update like this..

 function Update ()
 {
     ...
    var direction = transform.TransformDirection(Vector3.forward); // COuld be placed in Start()
    
     if(gunShot)
         Debug.DrawRay(transform.position, direction, Color.blue);
 }

Put is gunShot = true in the FireOneShot. Assu$$anonymous$$g gunShot is false when instantiated. Also, this will keep the ray active forever when the function is called. You can set it to false with a timer if you'd like.

avatar image robertbu · Aug 31, 2013 at 07:22 PM 0
Share
 Debug.DrawRay(transform.position, direction * 15.0, Color.blue, 0.5);

This makes the ray drawn 15 units long and displayed for 0.5 seconds.

avatar image solly576 · Aug 31, 2013 at 07:55 PM 0
Share

Ok, thanks for the tips about the ray. As for what I need doing, the gun appears to be firing, but doesn't seem to be damaging the enemy :(

2 Replies

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by solly576 · Aug 31, 2013 at 08:39 PM

Ok, I've fixed it - the gun was in a weird rotation so I made the ray cast originate at the parent gameobject instead.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by citizen_rafiq · Aug 31, 2013 at 07:46 PM

// attach this script with your gun and put an empty game object as a child of gun which work as spawn point of bullet

public class AutoFire : MonoBehaviour {

 public float frequency = 10;
 public float coneAngele = 1.0f;
 public bool firing = false;
 public float hitSoundVolume = 5f;
 public GameObject muzzleFlash;
 public AudioClip soundHit;
 private float _lastFireTime = -1;
 private RaycastHit _hitInfo;
 private Quaternion _coneRandomRotation;
 private Vector3 _force;
 private GameObject _bullet;
 private Transform _spawnPoint;
 RaycastHit hitInfo;
 void Start () {
     if(muzzleFlash) muzzleFlash.active = false;
     _force = new Vector3(0,0,0);
     _bullet=Resources.Load("Prefabs/bullet", typeof(GameObject))as GameObject;
     if(!_bullet){
         Debug.LogError("keep bullet prefab in Resources/Prefabs/bullet");
     }
     foreach(Transform tr in transform){
         if(tr){
             _spawnPoint=tr;
         }
     }
 }
 
 // Update is called once per frame
 void Update () {
     if (firing) {
         if (Time.time > _lastFireTime + 1 / frequency) {
             //coneRandomRotation= Quaternion.Euler (Random.Range(-coneAngele, coneAngele), Random.Range(-coneAngele, coneAngele),0);
             _coneRandomRotation = Quaternion.Euler(0, 0, 0);
             GameObject go= Instantiate(_bullet,_spawnPoint.position,Quaternion.Euler(Vector3.zero)) as GameObject;
             SimpleBulletOrMissile bulletOrMissile = go.GetComponent<SimpleBulletOrMissile>();
             _lastFireTime = Time.time;

               Physics.Raycast (go.transform.position, go.transform.up,out _hitInfo,Mathf.Infinity,-5);
             if (_hitInfo.transform)
             {
                 print(_hitInfo.transform.tag+"hitted");
                 Health targetHealth = _hitInfo.transform.GetComponent<Health>();
                 if (targetHealth)
                 {
                     //kill or health damage of target
                 }

                 if (_hitInfo.rigidbody)
                 {
                     //if want to apply force on enemy
                     hitInfo.rigidbody.AddForceAtPosition(_force, hitInfo.point, ForceMode.Impulse);
                 }
               
                 AudioSource.PlayClipAtPoint(soundHit, _hitInfo.point, hitSoundVolume);
                
                 bulletOrMissile.dist = _hitInfo.distance;
                 
                
             }
             else {
                 
                     bulletOrMissile.dist = 50;
             }
         }
         
     }
     if(Input.GetMouseButton(0)){
         OnStartFire();
     }
     if(Input.GetMouseButtonUp(0)){
         OnStopFire();
     }
 }

 void OnStartFire() {
     if (Time.timeScale == 0)
         return;

     firing = true;
     if(muzzleFlash) muzzleFlash.active = true;
     if (audio) audio.Play();
 }

 void OnStopFire() {
     firing = false;
     if(muzzleFlash) muzzleFlash.active = false;
     if (audio) audio.Stop();
 }

}

//attach this script with bullet

public class SimpleBulletOrMissile : MonoBehaviour {

public float speed = 10; public float lifeTime = 0.5f; public float dist = 100;

 private float _spawnTime = 0.0f;
 private Transform _tr; 
 // Use this for initialization
 void OnEnable () {
     _tr = transform;
     _spawnTime = Time.time;
 }
 
 // Update is called once per frame
 void Update () {
     _tr.position += _tr.forward * speed * Time.deltaTime;
     dist -= speed * Time.deltaTime;
     if (Time.deltaTime > _spawnTime + lifeTime || dist < 0) {
       //  print("Destroy form bullet");
        Destroy(gameObject);
     }
 }

}

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image solly576 · Aug 31, 2013 at 08:00 PM 0
Share

I originally used a script like this, but for performance sake, I didn't want to spawn individual bullets.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

16 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Gun collision problem 3 Answers

How to Implement First Shot Accuracy? 2 Answers

How do I make a raycast for a particle 1 Answer

RayCast in Third person Shooter 2 Answers

How can i make a ray cast take health from enemies 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges