89 lines
2.3 KiB
C#
89 lines
2.3 KiB
C#
using Cysharp.Threading.Tasks;
|
|
using System;
|
|
using System.Threading;
|
|
using UnityEngine;
|
|
|
|
|
|
[RequireComponent(typeof(Collider))]
|
|
public class AmmoBox : MonoBehaviour
|
|
{
|
|
public static Action OnAmmoBoxConsumed;
|
|
|
|
[SerializeField] float acceleration = 9;
|
|
[SerializeField] float maxSpeed = 25;
|
|
[SerializeField] float initialSpeed = 10;
|
|
|
|
private float speed = 0;
|
|
private Transform playerTransform;
|
|
|
|
private bool configured = false;
|
|
|
|
[SerializeField] AudioClip TakeAmmo;
|
|
[SerializeField] AudioClip Secret;
|
|
|
|
public void Configure()
|
|
{
|
|
playerTransform = G.PlayerStateModel.PlayerComponent.transform;
|
|
speed = initialSpeed;
|
|
MoveToPlayerAsync(this.GetCancellationTokenOnDestroy()).Forget();
|
|
|
|
|
|
configured = true;
|
|
}
|
|
|
|
private void OnTriggerEnter(Collider other)
|
|
{
|
|
if (!configured) return;
|
|
|
|
if (IsPlayer(other))
|
|
DropAmmo();
|
|
else
|
|
DestroyBox();
|
|
}
|
|
|
|
bool IsPlayer(Collider other)
|
|
{
|
|
if (other.TryGetComponent(out Hitbox h) && h.Owner == G.PlayerStateModel.PlayerComponent.gameObject)
|
|
{
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
private void DropAmmo()
|
|
{
|
|
// тут бы вызывать какой то менеджер оружия или типа того
|
|
var torpedoWeapon = G.WeaponModel.Weapons[0];
|
|
var missileWeapon = G.WeaponModel.Weapons[1];
|
|
|
|
torpedoWeapon.FillAmmo();
|
|
missileWeapon.FillAmmo();
|
|
OnAmmoBoxConsumed?.Invoke();
|
|
|
|
|
|
SoundManager.PlayReplica(TakeAmmo);
|
|
if (UnityEngine.Random.Range(0f, 1f) < 0.01f)
|
|
SoundManager.PlayReplica(Secret);
|
|
DestroyBox();
|
|
}
|
|
|
|
private void DestroyBox()
|
|
{
|
|
Destroy(gameObject);
|
|
}
|
|
|
|
private async UniTask MoveToPlayerAsync(CancellationToken token)
|
|
{
|
|
while (!token.IsCancellationRequested)
|
|
{
|
|
speed += acceleration * Time.fixedDeltaTime;
|
|
speed = Mathf.Min(speed, maxSpeed);
|
|
|
|
Vector3 directionToPlayer = (playerTransform.position - transform.position).normalized;
|
|
transform.Translate(directionToPlayer * speed * Time.fixedDeltaTime, Space.World);
|
|
|
|
await UniTask.Yield(PlayerLoopTiming.FixedUpdate);
|
|
}
|
|
}
|
|
}
|