From e50f0aefb1d46c3cdac38878daf43a4f159a92db Mon Sep 17 00:00:00 2001 From: Fries Date: Wed, 17 May 2023 14:16:31 -0700 Subject: [PATCH] add a random starting x direction to the ball this means the ball can either go left or righ randomly instead of always going left. --- Scripts/Ball.cs | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/Scripts/Ball.cs b/Scripts/Ball.cs index 96bf758..59b0518 100644 --- a/Scripts/Ball.cs +++ b/Scripts/Ball.cs @@ -18,8 +18,9 @@ public partial class Ball : CharacterBody2D { // 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. - _velocity = Vector2.Left * BallSpeed + new Vector2(0, rng.RandfRange(-_maxRandomAngle, _maxRandomAngle) * BallSpeed); + _velocity = GetRandomStartingDirection() * BallSpeed + new Vector2(0, rng.RandfRange(-_maxRandomAngle, _maxRandomAngle) * BallSpeed); } public override void _PhysicsProcess(double delta) @@ -38,4 +39,20 @@ public partial class Ball : CharacterBody2D if (collision == null) return; _velocity = _velocity.Bounce(collision.GetNormal()); } + + /// + /// this method generates a random number between 0 and 1 and + /// either returns Vector2.Left or Vector2.Right based on that number. + /// + private Vector2 GetRandomStartingDirection() { + using var rng = new RandomNumberGenerator(); + rng.Randomize(); + var range = rng.RandiRange(0,1); + + if (range == 0) { + return Vector2.Left; + } + + return Vector2.Right; + } }