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 zmar0519 · Feb 11, 2011 at 08:36 PM · rigidbodyaddforceraycastinggun

How to fire a gun using raycasting and still add force

Hi. I have a gun code that I wrote and I was wondering if there was a way to make the rigidbodies that I shoot have a force applied at the point at which the raycast hit.

If necessary, here is my code:

enum FireType { RayCast, Projectile } enum ShotType { Semi_Auto, Full_Auto, } var Clips : int;

var clipSize : int;

var unlimited : boolean = false;

var autoReload : boolean = true;

var reloadTime : int;

var gunRange : int;

var fireRate : float;

var projectilePrefab : Rigidbody;

var projectileShotPower : float;

var Damage : int;

var fireType : FireType;

var shotType : ShotType;

var shotSound : AudioClip;

var OutOfAmmoSound : AudioClip;

var reloadSound : AudioClip;

var ShotEmitter : ParticleEmitter[];

var tipOfGun : Transform;

var centerScreen : Transform;

var WoodParticle : GameObject;

var MetalParticle : GameObject;

var ConcreteParticle : GameObject;

var DirtParticle : GameObject;

var SnowParticle : GameObject;

var WaterParticle : GameObject;

var EnemyParticle : GameObject;

var gunName : String;

var bulletMark : GameObject;

var gunCamera : Camera;

var guiTex : GUITexture;

var CrossHeir : Texture2D;

var crossHeirChangeColor : Color;

var reloadElapse : float;

var pushPower : float;

private var Audio : AudioSource; private var freeToShoot : boolean = true; private var freeToReload : boolean = true; private var shotsLeft : int; private var clipsLeft : int;

function Awake() { for(var i = 0; i < ShotEmitter.length; i++) { ShotEmitter[i].emit = false; } Audio = gameObject.GetComponent(AudioSource); shotsLeft = clipSize; clipsLeft = Clips; } function Update () { if(Input.GetButton("Fire1")) { if(fireType == FireType.RayCast) { if(shotType == ShotType.Semi_Auto) { Shoot(true, false); } else if (shotType == ShotType.Full_Auto) { Shoot(false, false); } } else if (fireType == FireType.Projectile) { Shoot(false, true); } } else { freeToShoot = true; }

 if(shotsLeft &lt;= 0 &amp;&amp; autoReload)
 {
     Reload();
     freeToShoot = false;
 } else if (shotsLeft &lt;= 0 &amp;&amp; !autoReload)
 {
     freeToShoot = false;
     if(Input.GetButtonDown("Fire2"))
     {
         Reload();
     }
 }
 if(clipsLeft == 0)
 {
     freeToReload = false;
 }

} function Shoot(oneShot : boolean, isProjectile : boolean) { if(freeToShoot == true) { if(oneShot) { var SAhit : RaycastHit; var SAfwd = transform.TransformDirection(Vector3.forward); GenerateShotGraphics(); Debug.Log("I am about to generate shot graphics"); if(!unlimited) { shotsLeft--; } if(Physics.Raycast(centerScreen.transform.position, SAfwd, SAhit, gunRange)) { if(SAhit.collider.tag != "Enemy") { GenerateHitGraphics(SAhit, SAhit); ApplyForce(SAhit); } else { HitEnemy(SAhit); } } freeToShoot = false; } if(!oneShot) { var nextShot : float; if(Time.time > nextShot) { nextShot = Time.time + fireRate; var FAhit : RaycastHit; var FAfwd = transform.TransformDirection(Vector3.forward); GenerateShotGraphics(); if(!unlimited) { shotsLeft--; } if(Physics.Raycast(centerScreen.transform.position, FAfwd, FAhit, gunRange)) { if(FAhit.collider.tag != "Enemy") { GenerateHitGraphics(FAhit, FAhit); ApplyForce(FAhit); } else { HitEnemy(FAhit); } } } } } } function GenerateHitGraphics(hit : RaycastHit, BMhit : RaycastHit) { var go : GameObject; var delta : float = -0.02; var hitUpDir : Vector3 = hit.normal; if(!BMhit.collider.rigidbody) { var bm = Instantiate(bulletMark, BMhit.point, Quaternion.FromToRotation(Vector3.forward, -BMhit.normal)); bm.AddComponent(BulletMark); } switch(hit.collider.tag) { case "Wood": go = Instantiate(WoodParticle, hit.point, Quaternion.FromToRotation(Vector3.forward, hitUpDir)) as GameObject; break; case "Metal": go = Instantiate(MetalParticle, hit.point, Quaternion.FromToRotation(Vector3.forward, hitUpDir)) as GameObject; break; case "Snow": go = Instantiate(SnowParticle, hit.point, Quaternion.FromToRotation(Vector3.forward, hitUpDir)) as GameObject; break; case "Concrete": go = Instantiate(ConcreteParticle, hit.point, Quaternion.FromToRotation(Vector3.forward, hitUpDir)) as GameObject; break; case "Dirt": go = Instantiate(DirtParticle, hit.point, Quaternion.FromToRotation(Vector3.forward, hitUpDir)) as GameObject; break; case "water": go = Instantiate(WaterParticle, hit.point, Quaternion.FromToRotation(Vector3.forward, hitUpDir)) as GameObject; break; } Destroy(go, go.gameObject.GetComponent(ParticleEmitter).maxEnergy); } function GenerateShotGraphics() { for(var i = 0; i < ShotEmitter.length; i++) { ShotEmitter[i].Emit(); } PlayShootSound(); } function HitEnemy(hit : RaycastHit) { var go : GameObject; var delta : float = -0.02; var hitUpDir : Vector3 = hit.normal; go = Instantiate(EnemyParticle, hit.point, Quaternion.FromToRotation(Vector3.forward, hitUpDir)) as GameObject; SendMessageUpwards("ApplyDamage", Damage, SendMessageOptions.DontRequireReceiver); Destroy(go, go.gameObject.GetComponent(ParticleEmitter).maxEnergy); } function ApplyForce(hit : RaycastHit) { var body : Rigidbody = hit.collider.rigidbody; if(body) { if(!body.isKinematic) { var direction : Vector3 = hit.collider.transform.position - centerScreen.position; body.AddForceAtPosition(direction.normalized * pushPower, hit.point, ForceMode.Impulse); } } } function Reload() { if(freeToReload) { //Debug.Log("I am reloading"); FreeToShoot = false; shotsLeft = clipSize; clipsLeft--; yield WaitForSeconds(reloadElapse); guiTex.texture = CrossHeir; FreeToShoot = true; } } //Audio functions

function PlayShootSound() { Audio.PlayOneShot(shotSound); }

function PlayOutOfAmmoSound() { Audio.PlayOneShot(OutOfAmmoSound, 1); Debug.Log("Out Of Ammo"); }

function PlayReloadSound() {

Audio.PlayOneShot(reloadSound, 1);

}

Comment
Add comment · Show 1
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 Bunny83 · Feb 11, 2011 at 09:02 PM 0
Share

I don't get what you really want from us... You already have the function ApplyForce() the uses AddForceAtPosition.

1 Reply

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

Answer by AVividLight · Feb 11, 2011 at 08:45 PM

hit.rigidbody(addForce);

or something like that...

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

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

No one has followed this question yet.

Related Questions

Help with addforce 1 Answer

Real gun range and rigidbody.addforce power? 1 Answer

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

Player isn't moving (AddForce) (Hook)(c#) 1 Answer

Add force to a rigid body with raycast 1 Answer


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