Engine-Pong/Game/Behaviours/MovementBallBehaviour.cs

54 lines
1.9 KiB
C#
Raw Permalink Normal View History

2023-11-27 12:00:25 +03:00
using System;
2024-01-28 15:44:20 +03:00
2023-11-27 12:00:25 +03:00
using Syntriax.Engine.Core;
2024-01-27 21:50:28 +03:00
using Syntriax.Engine.Physics2D;
2023-12-04 14:06:52 +03:00
using Syntriax.Engine.Physics2D.Abstract;
2023-11-27 12:00:25 +03:00
namespace Pong.Behaviours;
2024-01-31 12:51:23 +03:00
2024-01-28 15:44:20 +03:00
public class MovementBallBehaviour : BehaviourOverride
2023-11-27 12:00:25 +03:00
{
2024-01-28 15:44:20 +03:00
public Vector2D StartDirection { get; private set; } = Vector2D.Zero;
public float Speed { get; set; } = 500f;
2024-01-29 12:34:27 +03:00
public float SpeedUpMultiplier { get; set; } = .0125f;
2023-11-27 12:00:25 +03:00
2024-01-27 21:50:28 +03:00
private IRigidBody2D rigidBody = null!;
2024-01-23 12:16:58 +03:00
protected override void OnFirstActiveFrame()
2023-11-27 12:00:25 +03:00
{
2024-01-27 21:50:28 +03:00
if (!BehaviourController.TryGetBehaviour(out IRigidBody2D? foundRigidBody))
throw new Exception($"{nameof(IRigidBody2D)} is missing on {GameObject.Name}.");
if (!BehaviourController.TryGetBehaviour(out ICollider2D? foundCollider))
throw new Exception($"{nameof(ICollider2D)} is missing on {GameObject.Name}.");
foundRigidBody.Velocity = StartDirection * Speed;
foundCollider.OnCollisionDetected += OnCollisionDetected;
2023-12-04 14:06:52 +03:00
2024-01-27 21:50:28 +03:00
rigidBody = foundRigidBody;
}
2024-01-29 12:34:27 +03:00
protected override void OnUpdate()
{
if (rigidBody.Velocity.MagnitudeSquared <= 0.01f)
return;
2024-02-01 18:47:27 +03:00
Vector2D speedUp = rigidBody.Velocity.Normalized * Time.DeltaTimeFrame;
2024-01-29 12:34:27 +03:00
rigidBody.Velocity += speedUp * SpeedUpMultiplier;
}
2024-01-27 21:50:28 +03:00
private void OnCollisionDetected(ICollider2D collider2D, CollisionDetectionInformation information)
{
if (Syntriax.Engine.Core.Math.Abs(information.Normal.Dot(Vector2D.Right)) > .25)
rigidBody.Velocity = information.Left.Transform.Position.FromTo(information.Right.Transform.Position).Normalized * rigidBody.Velocity.Magnitude;
else
rigidBody.Velocity = rigidBody.Velocity.Reflect(information.Normal);
2023-11-27 12:00:25 +03:00
}
2024-01-31 12:51:23 +03:00
public MovementBallBehaviour() { }
public MovementBallBehaviour(Vector2D startDirection, float speed)
{
StartDirection = Vector2D.Normalize(startDirection);
Speed = speed;
}
2023-11-27 12:00:25 +03:00
}