Search Unity

  1. Get all the Unite Berlin 2018 news on the blog.
    Dismiss Notice
  2. Unity 2018.2 has arrived! Read about it here.
    Dismiss Notice
  3. Improve your Unity skills with a certified instructor in a private, interactive classroom. Learn more.
    Dismiss Notice
  4. ARCore is out of developer preview! Read about it here.
    Dismiss Notice
  5. Magic Leap’s Lumin SDK Technical Preview for Unity lets you get started creating content for Magic Leap One™. Find more information on our blog!
    Dismiss Notice
  6. Want to see the most recent patch releases? Take a peek at the patch release page.
    Dismiss Notice

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.         {
    268.             Rigidbody body = hit.collider.attachedRigidbody;
    269.             //dont move the rigidbody if the character is on top of it
    270.             if (m_CollisionFlags == CollisionFlags.Below)
    271.             {
    272.                 return;
    273.             }
    274.  
    275.             if (body == null || body.isKinematic)
    276.             {
    277.                 return;
    278.             }
    279.             body.AddForceAtPosition(m_CharacterController.velocity * 0.1f, hit.point, ForceMode.Impulse);
    280.  
    281.  
    282.  
    283.         }
    284.  
    285.         void ControlAttackAnimations()
    286.         {
    287.             anim = GetComponent<Animator>();
    288.             MouseX = Input.GetAxis("Mouse X");
    289.             MouseY = Input.GetAxis("Mouse Y");
    290.  
    291.             float mousLB = Input.GetAxis("Fire1");
    292.  
    293.             #region decide Attack type
    294.             if (mousLB > 0.1f)
    295.             {
    296.                 decTimer += Time.deltaTime;
    297.  
    298.                 int attackType = 0;
    299.  
    300.                 if (Mathf.Abs(MouseX) > Mathf.Abs(MouseY))
    301.                 {
    302.                     if (MouseX < 0)
    303.                     {
    304.                         attackType = 0;
    305.                         Debug.Log("attack");
    306.                     }
    307.  
    308.                     else
    309.                     {
    310.                         attackType = 1;
    311.                         Debug.Log("attack1");
    312.                     }
    313.                 }
    314.                 else
    315.                 {
    316.                     attackType = 2;
    317.                 }
    318.  
    319.                 anim.SetInteger("AttackType", attackType);
    320.  
    321.                 if (decTimer > .5f)
    322.                 {
    323.                     holdAttack = true;
    324.                     anim.SetBool("Attacking", true);
    325.                     decTimer = 0;
    326.                 }
    327.             }
    328.             #endregion
    329.  
    330.             if (mousLB < 0.1f)
    331.             {
    332.                 if (holdAttack)
    333.                     attack = true;
    334.             }
    335.  
    336.             if (holdAttack)
    337.             {
    338.                 if (attack)
    339.                 {
    340.                     aTimer += Time.deltaTime;
    341.  
    342.                     targetValue = 1;
    343.  
    344.                     if (aTimer > attackTimer)
    345.                     {
    346.                         holdAttack = false;
    347.                         attack = false;
    348.                         anim.SetBool("Attacking", false);
    349.                         aTimer = 0;
    350.                         targetValue = 0;
    351.  
    352.                     }
    353.                 }
    354.                 else
    355.                 {
    356.                     targetValue = 0;
    357.                 }
    358.  
    359.             }
    360.             else
    361.             {
    362.                 targetValue = 0;
    363.             }
    364.  
    365.             if (blockedAttack)
    366.                 targetValue = 0;
    367.  
    368.  
    369.  
    370.             curValue = Mathf.MoveTowards(curValue, targetValue, Time.deltaTime * lerpRate);
    371.             anim.SetFloat("Attack", curValue);
    372.         }
    373.  
    374.  
    375.         void ControlBlockAnimations()
    376.         {
    377.  
    378.             anim = GetComponent<Animator>();
    379.             float mousRB = Input.GetAxis("Fire2");
    380.  
    381.      
    382.                 if (mousRB > 0.1f)
    383.                 {
    384.                     decTimer += Time.deltaTime;
    385.  
    386.  
    387.                     if (!blocking)
    388.                     {
    389.                         float blockType = 0;
    390.  
    391.                         if (Mathf.Abs(MouseX) > Mathf.Abs(MouseY))
    392.                         {
    393.                             if (MouseX < 0)
    394.                             {
    395.                                 blockType = 1;
    396.                                 Debug.Log("Block1");
    397.                             }
    398.  
    399.                             else
    400.                             {
    401.                                 blockType = 2;
    402.                                 Debug.Log("Block2");
    403.                             }
    404.                         }
    405.                         else
    406.                         {
    407.                             blockType = 0;
    408.                         }
    409.  
    410.                         anim.SetFloat("BlockSide", blockType);
    411.                     }
    412.  
    413.                     if (decTimer > .5f)
    414.                     {
    415.                         anim.SetBool("Block", true);
    416.                         blocking = true;
    417.                         decTimer = 0;
    418.                     }
    419.                 else
    420.                 {
    421.                     anim.SetBool("Block", false);
    422.                     blocking = false;
    423.                 }
    424.  
    425.                 if (blockedAttack)
    426.                 {
    427.                     bTimer += Time.deltaTime;
    428.  
    429.                     if (bTimer > 1)
    430.                     {
    431.                         blockedAttack = false;
    432.                         bTimer = 0;
    433.                     }
    434.                 }
    435.  
    436.             }
    437.  
    438.         }
    439.     }
    440. }
    441.  
    442.  
    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.