Run-and-capture/Assets/Scripts/CaptureController.cs
mamontow ceb2ff5351 Revert "some bugs"
This reverts commit 2fecae89c6d9b6d7a9eee4e271d88342ec2e31ee.
2021-08-31 22:39:13 +03:00

136 lines
3.6 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(PlayerState))]
public class CaptureController : MonoBehaviour
{
public float neutralCaptureTime = 3f, enemyCaptureTime = 5f/*, fastCaptureTime = 0f*/;
[SerializeField]
private GameObject capVFX;
private PlayerState _playerState;
private float _captureProgress= 0f;
//public Action OnCaptureStart, OnCaptureFailed;
//public Action<TileInfo, float> OnCaptureEnd;
private IEnumerator _currentCoroutine;
private void Awake()
{
_playerState = GetComponent<PlayerState>();
_playerState.OnInitializied += CaptureStartTile;
_playerState.OnCharStateChanged += CheckCapturing;
//OnCaptureEnd += CaptureTile;
}
private void CheckCapturing(CharacterState newState)
{
switch (newState)
{
case CharacterState.Idle:
TryToCaptureTile();
break;
case CharacterState.Move:
StopCapturingTile();
break;
default:
return;
}
}
private void TryToCaptureTile()
{
TileInfo tile = _playerState.currentTile;
if (_playerState.ownerIndex != tile.tileOwnerIndex)
{
_playerState.SetNewState(CharacterState.Capture);
if (tile.easyCaptureFor.Contains(_playerState.ownerIndex) || tile.easyCapForAll)
{
CaptureTile(tile);
}
else
{
if (tile.tileOwnerIndex == TileOwner.Neutral)
{
_currentCoroutine = Capturing(tile, neutralCaptureTime);
StartCoroutine(_currentCoroutine);
}
else
{
_currentCoroutine = Capturing(tile, enemyCaptureTime);
StartCoroutine(_currentCoroutine);
}
}
}
}
private void CaptureStartTile()
{
//Debug.Log("capStartTile");
if (_playerState.currentTile.tileOwnerIndex != _playerState.ownerIndex)
{
CaptureTile(_playerState.currentTile);
}
}
private void StopCapturingTile()
{
if (_currentCoroutine != null)
{
//OnCaptureFailed?.Invoke();
_captureProgress = 0f;
StopCoroutine(_currentCoroutine);
_currentCoroutine = null;
}
}
private void CaptureTile(TileInfo tile)
{
TileManagment.ChangeTileOwner(tile, _playerState.ownerIndex);
_playerState.SetNewState(CharacterState.Idle);
if (capVFX != null)
{
Instantiate(capVFX, tile.tilePosition + capVFX.transform.position, capVFX.transform.rotation);
}
}
private IEnumerator Capturing(TileInfo tile, float captureTime)
{
//OnCaptureStart?.Invoke();
_captureProgress = 0f;
float captureTimer = 0f;
while (_captureProgress < 1f)
{
captureTimer += Time.fixedDeltaTime;
_captureProgress = captureTimer / captureTime;
yield return new WaitForFixedUpdate();
}
_captureProgress = 0f;
//OnCaptureEnd?.Invoke(tile, captureTime);
CaptureTile(tile);
StopCapturingTile();
//StopCoroutine(_currentCoroutine);
}
public float GetCaptureProgress()
{
return _captureProgress;
}
}