- Home /
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));
}
}
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.
Thanks I'll look at that and give it a try when I get a chance.
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220611235614im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
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