Engine-Pong/Game/Behaviours/MovementBallBehaviour.cs

64 lines
2.5 KiB
C#

using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Syntriax.Engine.Core;
using Syntriax.Engine.Input;
using Syntriax.Engine.Physics2D;
using Syntriax.Engine.Physics2D.Abstract;
namespace Pong.Behaviours;
public class MovementBallBehaviour(Vector2D StartDirection, float Speed) : BehaviourOverride
{
public Vector2D StartDirection { get; private set; } = Vector2D.Normalize(StartDirection);
public float Speed { get; set; } = Speed;
private IRigidBody2D rigidBody = null!;
protected override void OnFirstActiveFrame()
{
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;
rigidBody = foundRigidBody;
}
private void OnCollisionDetected(ICollider2D collider2D, CollisionDetectionInformation information)
{
rigidBody.Velocity = rigidBody.Velocity.Reflect(information.Normal);
}
// protected override void OnUpdate(GameTime time)
// {
// GameObject.Transform.Position += StartDirection * (time.ElapsedGameTime.Nanoseconds * .001f) * Speed;
// float absY = MathF.Abs(GameObject.Transform.Position.Y);
// float differenceY = absY - PlayAreaBehaviour.PlayArea.Y * 0.5f;
// if (differenceY > 0f)
// {
// if (GameObject.Transform.Position.Y > 0f)
// GameObject.Transform.Position -= Vector2.UnitY * differenceY * 2f;
// else
// GameObject.Transform.Position += Vector2.UnitY * differenceY * 2f;
// StartDirection = new(StartDirection.X, -StartDirection.Y);
// }
// float absX = MathF.Abs(GameObject.Transform.Position.X);
// float differenceX = absX - PlayAreaBehaviour.PlayArea.X * 0.5f;
// if (differenceX > 0f)
// {
// if (GameObject.Transform.Position.X > 0f)
// GameObject.Transform.Position -= Vector2.UnitX * differenceX * 2f;
// else
// GameObject.Transform.Position += Vector2.UnitX * differenceX * 2f;
// StartDirection = new(-StartDirection.X, StartDirection.Y);
// }
// }
}