How can i add knockback to the player when firing my shotgun? (3d)
,im trying to make a game where when i fire my shotgun the player gets knocked back backward or upward depending the direction he's facing please help me !!! also here is the script that im using for the gun (using raycast for bullets)(THE "impactforce" variable is used to add KNOCK BACK TO THE OBJECTs THAT THE BULLET HITS) (im a begginer so try to make it easy for me xD) using UnityEngine;
public class GUNscriptshotgun : MonoBehaviour
{
Animator m_animator;
public float damage = 10f;
public float range = 100f;
public Camera fpscam;
public ParticleSystem muzzleflash;
public GameObject impacteffect;
public float impactforce = 50f;
public float firerate = 30f;
private float nexttimetofire = 0f;
public AudioClip gunshot;
void Start() {
m_animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0) && Time.time >= nexttimetofire)
{
GetComponent<AudioSource>().PlayOneShot(gunshot);
muzzleflash.Play();
m_animator.SetTrigger("shootshotty");
nexttimetofire = Time.time + 1f/firerate;
shoot();
}
}
void shoot ()
{
RaycastHit hit;
if (Physics.Raycast(fpscam.transform.position, fpscam.transform.forward, out hit, range))
{
Debug.Log(hit. transform.name);
Target target = hit.transform.GetComponent<Target>();
if (target != null)
{
target.TakeDamage(damage);
}
if (hit.rigidbody != null)
{
hit.rigidbody.AddForce(-hit.normal * impactforce);
}
GameObject impactGO = Instantiate(impacteffect, hit.point, Quaternion.LookRotation(hit.normal));
Destroy(impactGO, 2f);
}
}
}
Comment
Your answer
Follow this Question
Related Questions
Unet isLocalplayer issues with child objects of player 0 Answers
2D Bullet Not Working 1 Answer
Y Axis rotation is increasing too fast 0 Answers
How to pass weapon owner name to projectile?, 0 Answers
Firing bullets ( Tnx for the help ) 1 Answer