Pong/Scripts/Objects/Ball.cs
Fries 65ef70f583 the enemy can now see when the screen is adjusted.
the scaling manager now controls when the various objects are active so stuff won't be null because of stuff running too fast or slow.
2023-06-02 17:15:44 -07:00

61 lines
1.8 KiB
C#

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