Space-Smash-Out/Assets/Scripts/ForceField.cs

63 lines
1.4 KiB
C#

using System.Collections.Generic;
using System.Reflection;
using log4net;
using UnityEngine;
public class ForceField : MonoBehaviour
{
private static ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
[Tooltip("Multiplied by the current gravity strength factor for the ship.")]
[Range(0, 10)]
public float StrengthFactor = 2;
private List<Ship> ships = new();
private void FixedUpdate()
{
foreach (Ship ship in ships)
{
// Direction towards center
var direction = transform.up;
ship._body.AddForce(direction * ship.Props.GravitStrength * StrengthFactor
, ForceMode.Acceleration);
}
}
/// <summary>
/// Adds a ship to the force field when in range
/// </summary>
/// <param name="collider"></param>
private void OnTriggerEnter(Collider collider)
{
if (collider.tag == "Ship")
{
if (!collider.TryGetComponent(out Ship shipComponent))
{
Log.Error($"Collider: {collider} was tagged as Ship, but has no Ship component.");
return;
}
ships.Add(shipComponent);
}
}
/// <summary>
/// Removes the player when he leaves the force field
/// </summary>
/// <param name="collider"></param>
private void OnTriggerExit(Collider collider)
{
if (collider.tag == "Ship")
{
if (!collider.TryGetComponent(out Ship shipComponent))
{
Log.Error($"Collider: {collider} was tagged as Ship, but has no Ship component.");
return;
}
ships.Remove(shipComponent);
}
}
}