- Home /
Question by
Eggtooth · Feb 06, 2018 at 07:07 AM ·
rigidbody.addforce
Addforce for shotgun raycasts
Hey, so basically I have issue where I want raycasts of shotgun fire to hit and cause object to fly back in spectacular manner.
I have this code but it doesn't work well at all.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.Characters.FirstPerson;
public class ShotgunScript : MonoBehaviour {
public GameObject ShotgunObject;
public Animator weaponShotgunAnimator;
public GameObject muzzleFlash;
public AudioSource audioSource;
public AudioClip audioClip;
public Transform camera;
public CameraShake camShake;
public HeadBob headBob;
public bool canShoot = true;
public RigidbodyFirstPersonController playerController;
public int shotFragments = 8;
public float spreadAngle = 10.0f;
public LayerMask layerMask = -1;
public Light light;
int damage = 15;
public float hitForce;
// Use this for initialization
void Start () {
weaponShotgunAnimator = ShotgunObject.GetComponent<Animator> ();
}
// Update is called once per frame
void Update () {
if (canShoot) {
if (Input.GetMouseButtonDown (0)) {
StartCoroutine(ShotgunShootTimer());
audioSource.PlayOneShot (audioClip);
}
// if (playerController.m_Jump) {
// weaponShotgunAnimator.SetBool ("IsWalking", false);
// if (playerController.isJumping = true) {
//
// }
}
}
IEnumerator ShotgunShootTimer(){
canShoot = false;
light.enabled = true;
weaponShotgunAnimator.SetBool ("IsShootingFirst", true);
// raycast and spawn object for pellet
for(int i = 0; i < shotFragments; i++)
{
RaycastHit hit;
Quaternion fireRotation = Quaternion.LookRotation(transform.forward);
Quaternion randomRotation = Random.rotation;
fireRotation = Quaternion.RotateTowards(fireRotation,randomRotation,Random.Range(0.0f,spreadAngle));
if(Physics.Raycast(transform.position,fireRotation*Vector3.forward,out hit,90f,layerMask))
{
if (hit.rigidbody != null) {
hit.rigidbody.AddForceAtPosition(hit.transform.position, transform.position * hitForce);
}
GunHit gunHit = new GunHit();
Debug.Log("I've hit something, yay!");
// gunHit.damage = damage;
gunHit.raycastHit = hit;
hit.collider.SendMessage("Damage",gunHit,SendMessageOptions.DontRequireReceiver);
}
}
yield return new WaitForSeconds (0.05f);
muzzleFlash.SetActive (true);
camShake.enabled = true;
headBob.enabled = false;
yield return new WaitForSeconds (0.05f);
light.enabled = false;
muzzleFlash.SetActive (false);
yield return new WaitForSeconds (0.5f);
weaponShotgunAnimator.SetBool ("IsShootingFirst", false);
canShoot = true;
camShake.enabled = false;
headBob.enabled = true;
camShake.shakeDuration = 0.5f;
}
}
As you see I did make AddForceAtPosition, and added like 8000 float to hitForce in inspector.. but rigidbody only slightly rotates each hit. Any help?
I want to have object basically fly backwards from direction where raycast hit.
Comment