Skip to content

Instantly share code, notes, and snippets.

@beardordie
Created November 8, 2019 03:32
Show Gist options
  • Save beardordie/131a1ff9454bcbab0692c47cd1cced47 to your computer and use it in GitHub Desktop.
Save beardordie/131a1ff9454bcbab0692c47cd1cced47 to your computer and use it in GitHub Desktop.
Corgi Engine character component to prevent weapon from shooting during specified MovementStates, such as WallClinging, Crouching, LookingUp, LedgeHanging, etc
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using MoreMountains.Tools;
namespace MoreMountains.CorgiEngine
{
/// <summary>
/// Add this class to a character so it is prevented from shooting while in a specified MovementState,
/// such as WallClinging, Crouching, LookingUp, LedgeHanging, etc
/// This is an alternative to extending the CharacterHandleWeapon class just to prevent this behavior.
/// </summary>
public class PreventShootingDuringMovementStates : MonoBehaviour, MMEventListener<MMStateChangeEvent<CharacterStates.MovementStates>>
{
public CharacterHandleWeapon character;
public CharacterStates.MovementStates[] statesToPreventShooting =
{
CharacterStates.MovementStates.WallClinging,
CharacterStates.MovementStates.Crouching
};
public bool interruptShooting = true;
bool wasWeaponPermitted;
// This tries to automatically set the CharacterHandleWeapon reference when the component is added
// to the character
private void OnValidate()
{
if (character == null && GetComponent<CharacterHandleWeapon>() != null)
character = GetComponent<CharacterHandleWeapon>();
}
protected void OnEnable()
{
this.MMEventStartListening<MMStateChangeEvent<CharacterStates.MovementStates>>();
}
protected void OnDisable()
{
this.MMEventStopListening<MMStateChangeEvent<CharacterStates.MovementStates>>();
}
public void OnMMEvent(MMStateChangeEvent<CharacterStates.MovementStates> eventType)
{
for (int i = 0; i < statesToPreventShooting.Length; i++)
{
if (eventType.NewState == statesToPreventShooting[i])
{
// Character just began WallClinging. Cache the AbilityPermitted value of CharacterHandleWeapon,
// then set it to false. Once the character exits WallClinging, we will restore that cached value
if (character != null)
wasWeaponPermitted = character.AbilityPermitted;
if (wasWeaponPermitted)
{
character.AbilityPermitted = false;
}
if (interruptShooting)
character.CurrentWeapon.WeaponInputStop();
break;
}
else if (eventType.PreviousState == statesToPreventShooting[i])
{
// Character was in a state that should prevent shooting and just exited that state,
// so restore the cached value
if (character != null)
character.AbilityPermitted = wasWeaponPermitted;
break;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment