Danro/Assets/Scripts/Entities/Props/Platforms/TriggeringPlatform.cs

75 lines
2.3 KiB
C#

using System.Collections;
using UnityEngine;
using RR.Game2D.Core;
namespace RR.Game2D.Entities.Platforms
{
public class TriggeringPlatform : MonoBehaviour
{
[Header("Настройки движения платформы")]
[SerializeField] private float moveSpeed = 3f;
[SerializeField] private float pathLength = 5f;
[SerializeField] private Direction2D moveDirection = Direction2D.Right;
[Header("Прикрепление игрока")]
[SerializeField] private bool attachPlayer = true;
private Vector3 _startPosition;
private Vector3 _endPosition;
private void Awake()
{
_startPosition = transform.position;
_endPosition = moveDirection switch
{
Direction2D.Down => _startPosition + Vector3.down * pathLength,
Direction2D.Left => _startPosition + Vector3.left * pathLength,
Direction2D.Right => _startPosition + Vector3.right * pathLength,
Direction2D.Up => _startPosition + Vector3.up * pathLength,
_ => _startPosition
};
}
private void OnCollisionEnter2D(Collision2D other)
{
if (!attachPlayer) return;
if (!other.gameObject.CompareTag("Player")) return;
other.transform.SetParent(transform);
}
private void OnCollisionExit2D(Collision2D other)
{
if (!attachPlayer) return;
if (!other.gameObject.CompareTag("Player")) return;
other.transform.SetParent(null);
}
public void Move()
{
StopAllCoroutines();
StartCoroutine(MovePlatform(_endPosition));
}
public void MoveBack()
{
StopAllCoroutines();
StartCoroutine(MovePlatform(_startPosition));
}
private IEnumerator MovePlatform(Vector3 targetPosition)
{
while (transform.position != targetPosition)
{
transform.position = Vector3.MoveTowards(
transform.position,
targetPosition,
Time.deltaTime * moveSpeed);
yield return null;
}
transform.position = targetPosition;
}
}
}