Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 11 Next capture
2021 2022 2023
1 capture
11 Jun 22 - 11 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 M4347 · Aug 13, 2015 at 09:03 AM · rigidbodyfpsunity5gun script

Need help applying force to objects hit by raycast

Hi, I have this gun script which uses a raycast to hit and damage an enemy. How would I go about adding force upon the hit so that the enemy is knocked back (sort of like when gun impacts in movies are exaggerated and a person flies back upon being hit)? Also I would like to be able to do the same with static gameobjects in the world (in boxes move when shot etc).

Here is my gun code (I know its quite poorly coded and the reload doesn't add up right, but I'm learning trying to piece bits together). Also if anyone has any suggestions how to fix the KickBack function that would be great, its meant to make the gun move when fired like recoil, but it only moves the gun once and doesn't return to its original position.

 using UnityEngine;
 using System.Collections;
 
 public class PerformsAttack : MonoBehaviour {
 
     public float cooldown = 0.2f;
     float cooldownRemaining = 0;
     public float range = 100.0f;
     public GameObject bulletSpwan;
 
     public GameObject projectilePrefab;
 
     public GameObject debrisPrefab;
 
     public float damage = 50f;
 
     public GameObject mainCamera;
     public GameObject weaponCamera;
     public int FOV = 40;
     public float zoomSpeed = 0.5f;
     
     public float bullets = 5.0f;
     public float ammoClip = 5.0f;
     public float maxClips = 3.0f;
 
     private bool aiming = false;
 
     public AudioClip gunshot;
     public AudioClip reload;
 
     private Vector3 curVect;
     public Vector3 aimPosition;
     public float aimSpeed = 0.25f;
     public Vector3 hipPosition;
     public float maxInaccuracyHIP = 5.0f;
     public float maxInaccuracyAIM = 1.0f;
     private float baseInaccuracy;
     public float baseInaccuracyAIM = 0.005f;
     public float baseInaccuracyHIP = 1.5f;
     private float maximumInaccuracy;
 
     public Transform kickGO;
     public float kickUpside = 0.5f;
     public float kickSideways = 0.5f;
 
 
     // Use this for initialization
     void Start () {
         weaponCamera = GameObject.FindWithTag("WeaponCamera");
         mainCamera = GameObject.FindWithTag("MainCamera");
         GetComponent<AudioSource> ();
     }
     
     // Update is called once per frame
     void Update () {
         cooldownRemaining -= Time.deltaTime;
 
         if (Input.GetButton ("Fire1") && cooldownRemaining <=0 && bullets >= 1) {
             Shooting ();
         }
 
         if (Input.GetButtonDown ("Reload")){
             Reload ();
         }
 
         if (Input.GetButton("Fire2"))
         {
             if (!aiming)
             {
                 aiming = true;
                 curVect = aimPosition - transform.localPosition;
             }
             if (transform.localPosition != aimPosition && aiming)
             {
                 if (Mathf.Abs(Vector3.Distance(transform.localPosition, aimPosition)) < curVect.magnitude / aimSpeed * Time.deltaTime)
                 {
                     transform.localPosition = aimPosition;
                 }
                 else
                 {
                     transform.localPosition += curVect / aimSpeed * Time.deltaTime;
                 }
             }
         }
         else
         {
             if (aiming)
             {
                 aiming = false;
                 curVect = hipPosition - transform.localPosition;
 
             }
             
             if (Mathf.Abs(Vector3.Distance(transform.localPosition, hipPosition)) < curVect.magnitude / aimSpeed * Time.deltaTime)
             {
                 transform.localPosition = hipPosition;
             }
             else
             {
                 transform.localPosition += curVect / aimSpeed * Time.deltaTime;
             }
         }
         
         if (aiming)
         {
             maximumInaccuracy = maxInaccuracyAIM;
             baseInaccuracy = baseInaccuracyAIM;
             mainCamera.GetComponent<Camera>().fieldOfView -= FOV * Time.deltaTime / zoomSpeed;
             if (mainCamera.GetComponent<Camera>().fieldOfView < FOV)
             {
                 mainCamera.GetComponent<Camera>().fieldOfView = FOV;
             }
             weaponCamera.GetComponent<Camera>().fieldOfView -= 40 * Time.deltaTime / zoomSpeed;
             if (weaponCamera.GetComponent<Camera>().fieldOfView < 40)
             {
                 weaponCamera.GetComponent<Camera>().fieldOfView = 40;
             }
         }
         else
         {
             maximumInaccuracy = maxInaccuracyHIP;
             baseInaccuracy = baseInaccuracyHIP;
             mainCamera.GetComponent<Camera>().fieldOfView += 60 * Time.deltaTime / 0.5f;
             if (mainCamera.GetComponent<Camera>().fieldOfView > 60)
             {
                 mainCamera.GetComponent<Camera>().fieldOfView = 60;
             }
             weaponCamera.GetComponent<Camera>().fieldOfView += 50 * Time.deltaTime / 0.5f;
             if (weaponCamera.GetComponent<Camera>().fieldOfView > 50)
             {
                 weaponCamera.GetComponent<Camera>().fieldOfView = 50;
             }
         }
     }
 
     //Fire weapon
     void Shooting () {
         cooldownRemaining = cooldown;
         bullets -= 1;
         GetComponent<AudioSource>().PlayOneShot (gunshot);
 
         Ray ray = new Ray (bulletSpwan.transform.position, bulletSpwan.transform.forward);
         RaycastHit hitInfo;
         
         if (Physics.Raycast (ray, out hitInfo, range)) {
             Vector3 hitPoint = hitInfo.point;
             GameObject go = hitInfo.collider.gameObject;
             Debug.Log ("Hit Point: " + hitPoint);
             
             //Health h = go.GetComponent<Health>();
             EnemyControllerTest h = go.GetComponent<EnemyControllerTest> ();
             
             if (h != null) {
                 h.RecieveDamage (damage);
             }
             
             if (debrisPrefab != null) {
                 Instantiate (debrisPrefab, hitPoint, Quaternion.identity);
             }
 
             if (bullets == 0) {
                 Reload ();
             }
 
         }
 
         KickBack ();
     }
 
     void OnGUI() {
         if (GUI.Button (new Rect (10, 10, 90, 25), "Bullets : " + bullets)){}
         
     }
 
         void Reload () {
 
         GetComponent<AudioSource>().PlayOneShot (reload);
         if (maxClips >= 1) {
         
             bullets = ammoClip;
             maxClips -= 1;
         }
 
     }
 
     void KickBack()
     {
         kickGO.localRotation = Quaternion.Euler(kickGO.localRotation.eulerAngles - new Vector3(kickUpside, Random.Range(-kickSideways, kickSideways), 0));
     }
 
 
 }
 
 
 
 
 
 
 
 
 

 
Comment
Add comment
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

2 Replies

· Add your reply
  • Sort: 
avatar image
1

Answer by Runalotski · Aug 13, 2015 at 02:18 PM

http://docs.unity3d.com/ScriptReference/Rigidbody.html

Get the rigidbody component of the gameObject you hit and then call one of the functions listed in the API.

but you would probably want the AddForceAtPosition

using Hit.point : as the position

and use the bulletSpwan.transform.forward * force : as the force

and ForceMode.Inpulse would make most sense for an impact

You could make an animation of being knocked back when they are shot like alot of games, otherwise you would need to allow the physics to contol the character. If it is dying then you can apply the force to the rag doll of the pesron.

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 M4347 · Aug 13, 2015 at 07:33 PM 0
Share

Thanks I'll look at that and give it a try when I get a chance.

avatar image
0

Answer by Calvin_ · Aug 28, 2015 at 06:48 AM

You could simply add a rigidbody to all enemies, and then set a variable to the enemy that is hit. Then add negative force to that object. I made a video on how to make a gravity gun in Unity 3D here. Some of the code may be helpful, since it deals with applying force.

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

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

RigidbodyFPSWalker climbing walls 2 Answers

How can I get a responsive rigidbody FPS controller without acceleration that reacts to forces? 2 Answers

Low FPS after updating to Unity5. 0 Answers

How do I add force To rigidbody based On Character's Walking direction? 0 Answers

I don't understand, the following coding is my recoil coding for c sharp. 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