Files
rudder-unity-sdk/Assets/LiveOpsExamples/Scripts/Snack.cs
T
2026-08-12 14:03:44 +03:00

46 lines
1.2 KiB
C#

using System;
using UnityEngine;
namespace LiveOpsExamples
{
/// <summary>
/// A collectible snack. Bobs gently (sine, 0.08 world units amplitude, 650 ms
/// half-period — mirrors the Phaser yoyo tween) and raises <see cref="Collected"/>
/// when the player overlaps its trigger, then destroys itself.
/// </summary>
[RequireComponent(typeof(SpriteRenderer))]
public class Snack : MonoBehaviour
{
private const float BobAmplitude = 0.08f;
private const float BobHalfPeriodSeconds = 0.65f;
public SpriteRenderer Player { get; set; }
public event Action<Snack> Collected;
private Vector3 _basePosition;
private float _elapsed;
private void Start()
{
_basePosition = transform.position;
}
private void Update()
{
_elapsed += Time.deltaTime;
var offset = Mathf.Sin(_elapsed * Mathf.PI / BobHalfPeriodSeconds) * BobAmplitude;
transform.position = _basePosition + new Vector3(0f, offset, 0f);
}
private void OnTriggerEnter2D(Collider2D other)
{
if (Player == null || other.gameObject != Player.gameObject)
return;
Collected?.Invoke(this);
Destroy(gameObject);
}
}
}