Skip to content

Instantly share code, notes, and snippets.

@jweimann
Created November 14, 2016 05:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jweimann/d1b325a3b27151f502efaad2e9081a93 to your computer and use it in GitHub Desktop.
Save jweimann/d1b325a3b27151f502efaad2e9081a93 to your computer and use it in GitHub Desktop.
Weapon Script
using UnityEngine;
public class Weapon : MonoBehaviour
{
[SerializeField]
private WeaponSettings _weaponSettings;
[SerializeField]
private Transform _muzzlePoint;
private SteamVR_TrackedController _controller;
private float _nextFireTime;
private WeaponAmmo _weaponAmmo;
private bool CanFire { get { return Time.time >= _nextFireTime; } }
#region UnityEvents
private void Start()
{
_weaponAmmo = new WeaponAmmo(_weaponSettings);
}
private void OnEnable()
{
_controller = GetComponentInParent<SteamVR_TrackedController>();
_controller.TriggerClicked += HandleTriggerClicked;
_controller.Gripped += HandleGripClicked;
}
private void OnDisable()
{
_controller.TriggerClicked -= HandleTriggerClicked;
}
#endregion
private void HandleGripClicked(object sender, ClickedEventArgs e)
{
_weaponAmmo.Reload();
}
private void HandleTriggerClicked(object sender, ClickedEventArgs e)
{
if (CanFire)
{
if (_weaponAmmo.TryTakeBullet())
Fire();
}
}
private void Fire()
{
ResetWeaponRefreshTimer();
RaycastHit hitInfo;
if (Physics.Raycast(GetRay(), out hitInfo, _weaponSettings.MaxRange, GetLayerMask()))
{
var shootable = hitInfo.collider.GetComponent<IShootable>();
if (shootable != null)
HitShootable(shootable);
else
DrawDecal(hitInfo);
}
}
private void ResetWeaponRefreshTimer()
{
_nextFireTime = Time.deltaTime + _weaponSettings.FireDelay;
}
private void HitShootable(IShootable shootable)
{
shootable.TakeShot(GetDamage());
}
private int GetDamage()
{
return _weaponSettings.Damage;
}
private Ray GetRay()
{
return new Ray(_muzzlePoint.position, _muzzlePoint.forward);
}
private int GetLayerMask()
{
return LayerMask.GetMask("Default");
}
private void DrawDecal(RaycastHit hitInfo)
{
// Add an impact decal to the ground/building/etc using hitinfo point & normal.
}
private void OnDrawGizmos()
{
Gizmos.color = Color.green;
Gizmos.DrawRay(_muzzlePoint.position, _muzzlePoint.forward);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment