Files
Barrack-Unity/Assets/Scripts/Game/Balls/BasicBall.cs
T

96 lines
3.1 KiB
C#
Raw Normal View History

2026-07-26 00:59:17 -04:00
using UnityEngine;
2026-08-05 01:23:47 -04:00
public class BasicBall : BallBase
2026-07-26 00:59:17 -04:00
{
private Bounds boardBounds;
private Collider2D selfCollider;
private bool hasBoardBounds = false;
// Faster pull keeps the ball on its current board half while magnet is active.
private float magnetBounceDuration = 0.35f;
// Prevents magnet bounces from reaching the board center line.
private float magnetCenterLeeway = 0.12f;
private MagnetBounceAxisState xMagnetBounceState;
private MagnetBounceAxisState yMagnetBounceState;
2026-07-26 00:59:17 -04:00
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
audioSource = GetComponent<AudioSource>();
animator = GetComponent<Animator>();
selfCollider = GetComponent<Collider2D>();
2026-07-26 00:59:17 -04:00
speed = new Vector2(Random.Range(-0.05f, 0.05f), Random.Range(-0.05f, 0.05f));
hasBoardBounds = TryCacheGameBoardBounds(out boardBounds);
2026-07-26 00:59:17 -04:00
audioSource.PlayOneShot(spawnSound);
}
// Update is called once per frame
void FixedUpdate()
2026-08-19 13:18:26 -04:00
{
2026-07-26 00:59:17 -04:00
AnimatorStateInfo stateInfo = animator.GetCurrentAnimatorStateInfo(0);
if (stateInfo.IsName("BasicBallMove")) {
transform.Translate(speed);
if (affectedByMagnet && hasBoardBounds)
{
Vector3 currentPosition = transform.position;
currentPosition.x = ApplyMagnetBounceAxis(
currentPosition.x,
boardBounds.min.x,
boardBounds.max.x,
magnetActiveLeftRight,
ref xMagnetBounceState,
selfCollider != null ? selfCollider.bounds.extents.x : 0.0f,
magnetBounceDuration,
magnetCenterLeeway
);
currentPosition.y = ApplyMagnetBounceAxis(
currentPosition.y,
boardBounds.min.y,
boardBounds.max.y,
magnetActiveTopBottom,
ref yMagnetBounceState,
selfCollider != null ? selfCollider.bounds.extents.y : 0.0f,
magnetBounceDuration,
magnetCenterLeeway
);
transform.position = currentPosition;
}
2026-07-26 00:59:17 -04:00
}
}
void OnCollisionEnter2D(Collision2D collision)
{
2026-08-03 01:47:14 -04:00
if (collision.gameObject.CompareTag("Wall") ||
collision.gameObject.CompareTag("BasicBall") ||
2026-08-11 21:47:03 -04:00
collision.gameObject.CompareTag("FruitBall") ||
collision.gameObject.CompareTag("Shark"))
2026-07-26 00:59:17 -04:00
{
2026-08-19 13:18:26 -04:00
// Force reset the rotation.
transform.rotation = Quaternion.identity;
2026-07-26 00:59:17 -04:00
ContactPoint2D contact = collision.GetContact(0);
speed = Vector2.Reflect(speed, contact.normal);
2026-08-11 21:47:03 -04:00
if (collision.gameObject.CompareTag("Shark"))
{
audioSource.PlayOneShot(bounceSound);
}
}
else
{
Physics2D.IgnoreCollision(collision.collider, GetComponent<Collider2D>(), true);
2026-07-26 00:59:17 -04:00
}
}
}