86 lines
2.4 KiB
C#
86 lines
2.4 KiB
C#
using PashaBibko.Pacore.Attributes;
|
|
using UnityEngine.UI;
|
|
using UnityEngine;
|
|
|
|
namespace Fruitomation
|
|
{
|
|
public class FruitBehaviour : MonoBehaviour
|
|
{
|
|
[Header("References")]
|
|
[SerializeField] private RectTransform RectTransform;
|
|
[SerializeField] private Rigidbody2D Body2D;
|
|
[SerializeField] private Button Button;
|
|
|
|
[Header("Read only")]
|
|
[InspectorReadOnly, SerializeField] private Canvas AttachedCanvas;
|
|
[InspectorReadOnly, SerializeField] private FruitSpawner Spawner;
|
|
[InspectorReadOnly, SerializeField] private bool EnteredCanvas;
|
|
|
|
public void InitFruitBehaviour(Canvas canvas, FruitSpawner spawner)
|
|
{
|
|
AttachedCanvas = canvas;
|
|
EnteredCanvas = false;
|
|
Spawner = spawner;
|
|
|
|
Body2D.velocity = Random.insideUnitCircle * 2.5f;
|
|
|
|
Button.onClick.AddListener(OnPlayerClicked);
|
|
}
|
|
|
|
private void OnPlayerClicked() => TriggerDestruction();
|
|
|
|
private void Update()
|
|
{
|
|
if (!GameStateController.Is(GameState.Simulation))
|
|
{
|
|
TriggerDestruction();
|
|
}
|
|
}
|
|
|
|
private void FixedUpdate()
|
|
{
|
|
bool contained = IsWithinCanvas(RectTransform, AttachedCanvas.GetComponent<RectTransform>());
|
|
EnteredCanvas = EnteredCanvas || contained;
|
|
|
|
if (!contained && EnteredCanvas)
|
|
{
|
|
TriggerDestruction();
|
|
}
|
|
}
|
|
|
|
private void TriggerDestruction()
|
|
{
|
|
MoneyController.Add((ulong)Random.Range(1, 5));
|
|
|
|
Spawner.RemoveFruit(this);
|
|
Destroy(gameObject);
|
|
}
|
|
|
|
private static bool IsWithinCanvas(RectTransform element, RectTransform canvas)
|
|
{
|
|
Vector3[] elementCorners = new Vector3[4];
|
|
Vector3[] canvasCorners = new Vector3[4];
|
|
|
|
element.GetWorldCorners(elementCorners);
|
|
canvas.GetWorldCorners(canvasCorners);
|
|
|
|
Rect bounds = new
|
|
(
|
|
canvasCorners[0].x,
|
|
canvasCorners[0].y,
|
|
canvasCorners[2].x - canvasCorners[0].x,
|
|
canvasCorners[2].y - canvasCorners[0].y
|
|
);
|
|
|
|
foreach (Vector3 corner in elementCorners)
|
|
{
|
|
if (bounds.Contains(corner))
|
|
{
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
}
|
|
} |