Added a base class for item behaviour
This commit is contained in:
105
Assets/Scripts/Game/Items/ItemBehaviour.cs
Normal file
105
Assets/Scripts/Game/Items/ItemBehaviour.cs
Normal file
@@ -0,0 +1,105 @@
|
||||
using System;
|
||||
using Fruitomation.Global;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Fruitomation.Game.Items
|
||||
{
|
||||
public enum ItemType
|
||||
{
|
||||
Apple,
|
||||
Grape,
|
||||
Banana,
|
||||
Kiwi,
|
||||
Mango,
|
||||
Pitaya,
|
||||
Durian,
|
||||
BuddhasHand
|
||||
}
|
||||
|
||||
public class ItemBehaviour : MonoBehaviour
|
||||
{
|
||||
protected RectTransform RectTransform { get; private set; }
|
||||
protected Rigidbody2D Body2D { get; private set; }
|
||||
protected Canvas AttachedCanvas { get; private set; }
|
||||
protected bool EnteredCanvas { get; private set; }
|
||||
|
||||
private ItemType InternalItemType;
|
||||
|
||||
public ItemType CurrentType
|
||||
{
|
||||
get => InternalItemType;
|
||||
set
|
||||
{
|
||||
InternalItemType = value;
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual void OnInitialized() { }
|
||||
|
||||
public void InitBehaviour(Canvas canvas)
|
||||
{
|
||||
RectTransform = transform.GetComponent<RectTransform>();
|
||||
Body2D = transform.GetComponent<Rigidbody2D>();
|
||||
|
||||
AttachedCanvas = canvas;
|
||||
EnteredCanvas = false;
|
||||
|
||||
OnInitialized();
|
||||
}
|
||||
|
||||
private void UpdateItem()
|
||||
{
|
||||
}
|
||||
|
||||
protected void Update()
|
||||
{
|
||||
if (!GameStateController.Is(GameState.Simulation))
|
||||
{
|
||||
TriggerDestruction(false);
|
||||
}
|
||||
}
|
||||
|
||||
private void FixedUpdate()
|
||||
{
|
||||
bool contained = IsWithinCanvas(RectTransform, AttachedCanvas.GetComponent<RectTransform>());
|
||||
EnteredCanvas = EnteredCanvas || contained;
|
||||
|
||||
if (!contained && EnteredCanvas)
|
||||
{
|
||||
TriggerDestruction();
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
public void TriggerDestruction(bool harvest = true)
|
||||
{
|
||||
Destroy(gameObject);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user