Search Unity

Help with weapon collision with objects

Discussion in 'Scripting' started by Soarino, Jan 13, 2018.

  1. Soarino

    Soarino

    Joined:
    Nov 16, 2017
    Posts:
    23
    With help ive programmed a so far a first person controller with a attack animation handler and a sword with a collider attached to the sword.
    If you hold the mouse button it the sword is raised and if you let go it plays the rest of the attack animation as soon as you attack an object with a colldier attached it stays in the blocked stage, ive tried to add in a timer but it doesn't seem to work


    My scripts:

    My fps controller basically Unity default but with added animation controllers

    Code (CSharp):
    1. using System;
    2. using UnityEngine;
    3. using UnityStandardAssets.CrossPlatformInput;
    4. using UnityStandardAssets.Utility;
    5. using Random = UnityEngine.Random;
    6.  
    7. namespace UnityStandardAssets.Characters.FirstPerson
    8. {
    9.     [RequireComponent(typeof(CharacterController))]
    10.     [RequireComponent(typeof(AudioSource))]
    11.     public class FirstPersonController : MonoBehaviour
    12.     {
    13.         [SerializeField] private bool m_IsWalking;
    14.         [SerializeField] private float m_WalkSpeed;
    15.         [SerializeField] private float m_RunSpeed;
    16.         [SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten;
    17.         [SerializeField] private float m_JumpSpeed;
    18.         [SerializeField] private float m_StickToGroundForce;
    19.         [SerializeField] private float m_GravityMultiplier;
    20.         [SerializeField] private MouseLook m_MouseLook;
    21.         [SerializeField] private bool m_UseFovKick;
    22.         [SerializeField] private FOVKick m_FovKick = new FOVKick();
    23.         [SerializeField] private bool m_UseHeadBob;
    24.         [SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob();
    25.         [SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob();
    26.         [SerializeField] private float m_StepInterval;
    27.         [SerializeField] private AudioClip[] m_FootstepSounds;    // an array of footstep sounds that will be randomly selected from.
    28.         [SerializeField] private AudioClip m_JumpSound;           // the sound played when character leaves the ground.
    29.         [SerializeField] private AudioClip m_LandSound;           // the sound played when character touches back on ground.
    30.  
    31.  
    32.         //Attack Variables
    33.         float targetValue;
    34.         float curValue;
    35.         public float lerpRate = 5;
    36.         bool holdAttack;
    37.         bool attack;
    38.         public float attackTimer = 1;
    39.         float aTimer;
    40.         float decTimer;
    41.  
    42.         //Block Variables
    43.         bool blocking;
    44.         float bTimer;
    45.         public bool blockedAttack;
    46.  
    47.         // Mouse Variables
    48.         float MouseX;
    49.         float MouseY;
    50.  
    51.         private Camera m_Camera;
    52.         private bool m_Jump;
    53.         private float m_YRotation;
    54.         private Vector2 m_Input;
    55.         private Vector3 m_MoveDir = Vector3.zero;
    56.         private CharacterController m_CharacterController;
    57.         private CollisionFlags m_CollisionFlags;
    58.         private bool m_PreviouslyGrounded;
    59.         private Vector3 m_OriginalCameraPosition;
    60.         private float m_StepCycle;
    61.         private float m_NextStep;
    62.         private bool m_Jumping;
    63.         private AudioSource m_AudioSource;
    64.         private Animator anim;
    65.  
    66.  
    67.         // Use this for initialization
    68.         private void Start()
    69.         {
    70.             m_CharacterController = GetComponent<CharacterController>();
    71.             m_Camera = Camera.main;
    72.             m_OriginalCameraPosition = m_Camera.transform.localPosition;
    73.             m_FovKick.Setup(m_Camera);
    74.             m_HeadBob.Setup(m_Camera, m_StepInterval);
    75.             m_StepCycle = 0f;
    76.             m_NextStep = m_StepCycle / 2f;
    77.             m_Jumping = false;
    78.             m_AudioSource = GetComponent<AudioSource>();
    79.             m_MouseLook.Init(transform, m_Camera.transform);
    80.         }
    81.  
    82.  
    83.         // Update is called once per frame
    84.         private void Update()
    85.         {
    86.             RotateView();
    87.             // the jump state needs to read here to make sure it is not missed
    88.             if (!m_Jump)
    89.             {
    90.                 m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
    91.             }
    92.  
    93.             if (!m_PreviouslyGrounded && m_CharacterController.isGrounded)
    94.             {
    95.                 StartCoroutine(m_JumpBob.DoBobCycle());
    96.                 PlayLandingSound();
    97.                 m_MoveDir.y = 0f;
    98.                 m_Jumping = false;
    99.             }
    100.             if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded)
    101.             {
    102.                 m_MoveDir.y = 0f;
    103.             }
    104.  
    105.             m_PreviouslyGrounded = m_CharacterController.isGrounded;
    106.             ControlAttackAnimations();
    107.             ControlBlockAnimations();
    108.         }
    109.  
    110.  
    111.         private void PlayLandingSound()
    112.         {
    113.             m_AudioSource.clip = m_LandSound;
    114.             m_AudioSource.Play();
    115.             m_NextStep = m_StepCycle + .5f;
    116.         }
    117.  
    118.  
    119.         private void FixedUpdate()
    120.         {
    121.             float speed;
    122.             GetInput(out speed);
    123.             // always move along the camera forward as it is the direction that it being aimed at
    124.             Vector3 desiredMove = transform.forward * m_Input.y + transform.right * m_Input.x;
    125.  
    126.             // get a normal for the surface that is being touched to move along it
    127.             RaycastHit hitInfo;
    128.             Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo,
    129.                                m_CharacterController.height / 2f, Physics.AllLayers, QueryTriggerInteraction.Ignore);
    130.             desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized;
    131.  
    132.             m_MoveDir.x = desiredMove.x * speed;
    133.             m_MoveDir.z = desiredMove.z * speed;
    134.  
    135.  
    136.             if (m_CharacterController.isGrounded)
    137.             {
    138.                 m_MoveDir.y = -m_StickToGroundForce;
    139.  
    140.                 if (m_Jump)
    141.                 {
    142.                     m_MoveDir.y = m_JumpSpeed;
    143.                     PlayJumpSound();
    144.                     m_Jump = false;
    145.                     m_Jumping = true;
    146.                 }
    147.             }
    148.             else
    149.             {
    150.                 m_MoveDir += Physics.gravity * m_GravityMultiplier * Time.fixedDeltaTime;
    151.             }
    152.             m_CollisionFlags = m_CharacterController.Move(m_MoveDir * Time.fixedDeltaTime);
    153.  
    154.             ProgressStepCycle(speed);
    155.             UpdateCameraPosition(speed);
    156.  
    157.             m_MouseLook.UpdateCursorLock();
    158.         }
    159.  
    160.  
    161.         private void PlayJumpSound()
    162.         {
    163.             m_AudioSource.clip = m_JumpSound;
    164.             m_AudioSource.Play();
    165.         }
    166.  
    167.  
    168.         private void ProgressStepCycle(float speed)
    169.         {
    170.             if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0))
    171.             {
    172.                 m_StepCycle += (m_CharacterController.velocity.magnitude + (speed * (m_IsWalking ? 1f : m_RunstepLenghten))) *
    173.                              Time.fixedDeltaTime;
    174.             }
    175.  
    176.             if (!(m_StepCycle > m_NextStep))
    177.             {
    178.                 return;
    179.             }
    180.  
    181.             m_NextStep = m_StepCycle + m_StepInterval;
    182.  
    183.             PlayFootStepAudio();
    184.         }
    185.  
    186.  
    187.         private void PlayFootStepAudio()
    188.         {
    189.             if (!m_CharacterController.isGrounded)
    190.             {
    191.                 return;
    192.             }
    193.             // pick & play a random footstep sound from the array,
    194.             // excluding sound at index 0
    195.             int n = Random.Range(1, m_FootstepSounds.Length);
    196.             m_AudioSource.clip = m_FootstepSounds[n];
    197.             m_AudioSource.PlayOneShot(m_AudioSource.clip);
    198.             // move picked sound to index 0 so it's not picked next time
    199.             m_FootstepSounds[n] = m_FootstepSounds[0];
    200.             m_FootstepSounds[0] = m_AudioSource.clip;
    201.         }
    202.  
    203.  
    204.         private void UpdateCameraPosition(float speed)
    205.         {
    206.             Vector3 newCameraPosition;
    207.             if (!m_UseHeadBob)
    208.             {
    209.                 return;
    210.             }
    211.             if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded)
    212.             {
    213.                 m_Camera.transform.localPosition =
    214.                     m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude +
    215.                                       (speed * (m_IsWalking ? 1f : m_RunstepLenghten)));
    216.                 newCameraPosition = m_Camera.transform.localPosition;
    217.                 newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset();
    218.             }
    219.             else
    220.             {
    221.                 newCameraPosition = m_Camera.transform.localPosition;
    222.                 newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset();
    223.             }
    224.             m_Camera.transform.localPosition = newCameraPosition;
    225.         }
    226.  
    227.  
    228.         private void GetInput(out float speed)
    229.         {
    230.             // Read input
    231.             float horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
    232.             float vertical = CrossPlatformInputManager.GetAxis("Vertical");
    233.  
    234.             bool waswalking = m_IsWalking;
    235.  
    236. #if !MOBILE_INPUT
    237.             // On standalone builds, walk/run speed is modified by a key press.
    238.             // keep track of whether or not the character is walking or running
    239.             m_IsWalking = !Input.GetKey(KeyCode.LeftShift);
    240. #endif
    241.             // set the desired speed to be walking or running
    242.             speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed;
    243.             m_Input = new Vector2(horizontal, vertical);
    244.  
    245.             // normalize input if it exceeds 1 in combined length:
    246.             if (m_Input.sqrMagnitude > 1)
    247.             {
    248.                 m_Input.Normalize();
    249.             }
    250.  
    251.             // handle speed change to give an fov kick
    252.             // only if the player is going to a run, is running and the fovkick is to be used
    253.             if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0)
    254.             {
    255.                 StopAllCoroutines();
    256.                 StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown());
    257.             }
    258.         }
    259.  
    260.  
    261.         private void RotateView()
    262.         {
    263.             m_MouseLook.LookRotation(transform, m_Camera.transform);
    264.         }
    265.  
    266.  
    267.         private void OnControllerColliderHit(ControllerColliderHit hit)
    268.         {
    269.             Rigidbody body = hit.collider.attachedRigidbody;
    270.             //dont move the rigidbody if the character is on top of it
    271.             if (m_CollisionFlags == CollisionFlags.Below)
    272.             {
    273.                 return;
    274.             }
    275.  
    276.             if (body == null || body.isKinematic)
    277.             {
    278.                 return;
    279.             }
    280.             body.AddForceAtPosition(m_CharacterController.velocity * 0.1f, hit.point, ForceMode.Impulse);
    281.  
    282.  
    283.  
    284.         }
    285.  
    286.         void ControlAttackAnimations()
    287.         {
    288.             anim = GetComponent<Animator>();
    289.             MouseX = Input.GetAxis("Mouse X");
    290.             MouseY = Input.GetAxis("Mouse Y");
    291.  
    292.             float mousLB = Input.GetAxis("Fire1");
    293.  
    294.             #region decide Attack type
    295.             if (mousLB > 0.1f)
    296.             {
    297.                 decTimer += Time.deltaTime;
    298.  
    299.                 int attackType = 0;
    300.  
    301.                 if (Mathf.Abs(MouseX) > Mathf.Abs(MouseY))
    302.                 {
    303.                     if (MouseX < 0)
    304.                     {
    305.                         attackType = 0;
    306.                         Debug.Log("attack");
    307.                     }
    308.  
    309.                     else
    310.                     {
    311.                         attackType = 1;
    312.                         Debug.Log("attack1");
    313.                     }
    314.                 }
    315.                 else
    316.                 {
    317.                     attackType = 2;
    318.                 }
    319.  
    320.                 anim.SetInteger("AttackType", attackType);
    321.  
    322.                 if (decTimer > .5f)
    323.                 {
    324.                     holdAttack = true;
    325.                     anim.SetBool("Attacking", true);
    326.                     decTimer = 0;
    327.                 }
    328.             }
    329.             #endregion
    330.  
    331.             if (mousLB < 0.1f)
    332.             {
    333.                 if (holdAttack)
    334.                     attack = true;
    335.             }
    336.  
    337.             if (holdAttack)
    338.             {
    339.                 if (attack)
    340.                 {
    341.                     aTimer += Time.deltaTime;
    342.  
    343.                     targetValue = 1;
    344.  
    345.                     if (aTimer > attackTimer)
    346.                     {
    347.                         holdAttack = false;
    348.                         attack = false;
    349.                         anim.SetBool("Attacking", false);
    350.                         aTimer = 0;
    351.                         targetValue = 0;
    352.  
    353.                     }
    354.                 }
    355.                 else
    356.                 {
    357.                     targetValue = 0;
    358.                 }
    359.  
    360.             }
    361.             else
    362.             {
    363.                 targetValue = 0;
    364.             }
    365.  
    366.             if (blockedAttack)
    367.                 targetValue = 0;
    368.  
    369.  
    370.  
    371.             curValue = Mathf.MoveTowards(curValue, targetValue, Time.deltaTime * lerpRate);
    372.             anim.SetFloat("Attack", curValue);
    373.         }
    374.  
    375.  
    376.         void ControlBlockAnimations()
    377.         {
    378.  
    379.             anim = GetComponent<Animator>();
    380.             float mousRB = Input.GetAxis("Fire2");
    381.  
    382.      
    383.                 if (mousRB > 0.1f)
    384.                 {
    385.                     decTimer += Time.deltaTime;
    386.  
    387.  
    388.                     if (!blocking)
    389.                     {
    390.                         float blockType = 0;
    391.  
    392.                         if (Mathf.Abs(MouseX) > Mathf.Abs(MouseY))
    393.                         {
    394.                             if (MouseX < 0)
    395.                             {
    396.                                 blockType = 1;
    397.                                 Debug.Log("Block1");
    398.                             }
    399.  
    400.                             else
    401.                             {
    402.                                 blockType = 2;
    403.                                 Debug.Log("Block2");
    404.                             }
    405.                         }
    406.                         else
    407.                         {
    408.                             blockType = 0;
    409.                         }
    410.  
    411.                         anim.SetFloat("BlockSide", blockType);
    412.                     }
    413.  
    414.                     if (decTimer > .5f)
    415.                     {
    416.                         anim.SetBool("Block", true);
    417.                         blocking = true;
    418.                         decTimer = 0;
    419.                     }
    420.                 else
    421.                 {
    422.                     anim.SetBool("Block", false);
    423.                     blocking = false;
    424.                 }
    425.  
    426.                 if (blockedAttack)
    427.                 {
    428.                     bTimer += Time.deltaTime;
    429.  
    430.                     if (bTimer > 1)
    431.                     {
    432.                         blockedAttack = false;
    433.                         bTimer = 0;
    434.                     }
    435.                 }
    436.  
    437.             }
    438.  
    439.         }
    440.     }
    441. }
    442.  
    443.  
    My weapon collider

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityStandardAssets.Characters.FirstPerson;
    5.  
    6.  
    7. public class WeaponCollisons : MonoBehaviour {
    8.  
    9.     FirstPersonController _PC;
    10.  
    11.     // Use this for initialization
    12.     void Start()
    13.     {
    14.         _PC = GetComponentInParent<FirstPersonController>();
    15.     }
    16.  
    17.     void OnTriggerEnter(Collider other)
    18.     {
    19.         if(other.gameObject.tag == "Weapon")
    20.         {
    21.             _PC.blockedAttack = true;
    22.         }
    23.         else if(other.GetComponentInParent<FirstPersonController>())
    24.         {
    25.             FirstPersonController pC = other.GetComponentInParent<FirstPersonController>();
    26.  
    27.             if(pC != _PC)
    28.             {
    29.                 //DAMAGE
    30.             }
    31.         }
    32.         else
    33.         {
    34.             _PC.blockedAttack = true;
    35.         }
    36.     }
    37. }

    Any help would be greatly appreciated and im still every much a noob and learning.