feat: basic pong manager networking added

This commit is contained in:
2025-05-21 22:45:21 +03:00
parent 8f9c9f77f0
commit 2853a6130b
3 changed files with 95 additions and 53 deletions

View File

@@ -1,5 +1,3 @@
using System;
using Syntriax.Engine.Core;
using Syntriax.Engine.Physics2D;
@@ -7,47 +5,28 @@ namespace Pong.Behaviours;
public class BallBehaviour : Behaviour2D
{
public Vector2D StartDirection { get; private set; } = Vector2D.Zero;
public float Speed { get; set; } = 500f;
public float SpeedUpMultiplier { get; set; } = .0125f;
private readonly Random random = new();
private IRigidBody2D rigidBody = null!;
public IRigidBody2D rigidBody = null!;
protected override void OnFirstActiveFrame()
{
BehaviourController.GetRequiredBehaviour<ICollider2D>().OnCollisionDetected += OnCollisionDetected;
rigidBody = BehaviourController.GetRequiredBehaviour<IRigidBody2D>();
if (UniverseObject.Universe.TryFindBehaviour(out PongManagerBehaviour? pongManager))
{
pongManager.OnReset += ResetBall;
pongManager.OnScored += ResetBall;
pongManager.OnFinished += DisableBall;
}
}
private void DisableBall(PongManagerBehaviour pongManager)
public void LaunchBall(Vector2D launchDirection)
{
rigidBody.Velocity = launchDirection * Speed;
}
public void ResetBall()
{
Transform.Position = Vector2D.Zero;
rigidBody.Velocity = Vector2D.Zero;
}
private void ResetBall(PongManagerBehaviour pongManager)
{
StateEnable.Enabled = true;
Transform.Position = Vector2D.Zero;
rigidBody.Velocity = GetRandomDirection() * Speed;
}
private Vector2D GetRandomDirection()
{
const float AllowedRadians = 45f * Syntriax.Engine.Core.Math.DegreeToRadian;
float rotation = (float)random.NextDouble() * 2f * AllowedRadians - AllowedRadians;
bool isBackwards = (random.Next() % 2) == 1;
return Vector2D.Right.Rotate(isBackwards ? rotation + Syntriax.Engine.Core.Math.PI : rotation);
}
protected override void OnUpdate()
{
if (rigidBody.Velocity.MagnitudeSquared <= 0.01f)
@@ -59,16 +38,12 @@ public class BallBehaviour : Behaviour2D
private void OnCollisionDetected(ICollider2D collider2D, CollisionDetectionInformation information)
{
if (Syntriax.Engine.Core.Math.Abs(information.Normal.Dot(Vector2D.Right)) > .25)
if (Math.Abs(information.Normal.Dot(Vector2D.Right)) > .25)
rigidBody.Velocity = information.Detected.Transform.Position.FromTo(information.Detector.Transform.Position).Normalized * rigidBody.Velocity.Magnitude;
else
rigidBody.Velocity = rigidBody.Velocity.Reflect(information.Normal);
}
public BallBehaviour() { }
public BallBehaviour(Vector2D startDirection, float speed)
{
StartDirection = Vector2D.Normalize(startDirection);
Speed = speed;
}
public BallBehaviour(float speed) => Speed = speed;
}