2023-05-17 06:15:31 +00:00
|
|
|
using Godot;
|
|
|
|
|
|
|
|
namespace Pong.Scripts;
|
|
|
|
|
|
|
|
public partial class Ball : CharacterBody2D
|
|
|
|
{
|
|
|
|
[Export] private double _ballSpeed;
|
2023-05-17 17:52:55 +00:00
|
|
|
[Export] private double _maxRandomAngle;
|
2023-05-17 06:15:31 +00:00
|
|
|
|
|
|
|
private Vector2 _velocity;
|
2023-05-17 06:47:24 +00:00
|
|
|
|
2023-05-17 06:15:31 +00:00
|
|
|
/// <summary>
|
2023-05-18 06:41:26 +00:00
|
|
|
/// this property multiples the ballSpeed by the <see cref="Constants.Meter">Meter</see> constant.
|
2023-05-17 06:15:31 +00:00
|
|
|
/// </summary>
|
|
|
|
private double BallSpeed => _ballSpeed * Constants.Meter;
|
2023-05-17 06:47:24 +00:00
|
|
|
|
2023-05-17 06:15:31 +00:00
|
|
|
public override void _Ready()
|
|
|
|
{
|
2023-05-17 06:47:24 +00:00
|
|
|
// this should dispose when this method goes out of scope (this means after the velocity variable is assigned)
|
|
|
|
using var rng = new RandomNumberGenerator();
|
2023-05-17 21:16:31 +00:00
|
|
|
rng.Randomize();
|
2023-05-17 06:47:24 +00:00
|
|
|
// set the velocity currently to the left of the screen with a random y angle.
|
2023-05-17 21:16:31 +00:00
|
|
|
_velocity = GetRandomStartingDirection() * BallSpeed + new Vector2(0, rng.RandfRange(-_maxRandomAngle, _maxRandomAngle) * BallSpeed);
|
2023-05-17 06:15:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public override void _PhysicsProcess(double delta)
|
|
|
|
{
|
|
|
|
Velocity = _velocity;
|
|
|
|
CollisionCheck(delta);
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// this method moves the ball and bounces if it collides with something.
|
|
|
|
/// </summary>
|
2023-05-18 06:41:26 +00:00
|
|
|
/// <param name="delta">delta time from the <see cref="_PhysicsProcess">_PhysicsProcess</see> method.</param>
|
2023-05-17 06:15:31 +00:00
|
|
|
private void CollisionCheck(double delta)
|
|
|
|
{
|
|
|
|
var collision = MoveAndCollide(_velocity * delta);
|
|
|
|
if (collision == null) return;
|
|
|
|
_velocity = _velocity.Bounce(collision.GetNormal());
|
|
|
|
}
|
2023-05-17 21:16:31 +00:00
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// this method generates a random number between 0 and 1 and
|
2023-05-18 06:41:26 +00:00
|
|
|
/// either returns <see cref="Vector2.Left">Vector2.Left</see> or <see cref="Vector2.Right">Vector2.Right</see>
|
|
|
|
/// based on that number.
|
2023-05-17 21:16:31 +00:00
|
|
|
/// </summary>
|
2023-05-18 06:41:26 +00:00
|
|
|
private static Vector2 GetRandomStartingDirection() {
|
2023-05-17 21:16:31 +00:00
|
|
|
using var rng = new RandomNumberGenerator();
|
|
|
|
rng.Randomize();
|
|
|
|
var range = rng.RandiRange(0,1);
|
|
|
|
|
|
|
|
if (range == 0) {
|
|
|
|
return Vector2.Left;
|
|
|
|
}
|
|
|
|
|
|
|
|
return Vector2.Right;
|
|
|
|
}
|
2023-05-17 06:15:31 +00:00
|
|
|
}
|