Update: The ball still got stuck, if it was sandwiched between the wall and a brick, so I made a third tweak and a 9th if statement for when x is at 0 velocity.
Vector 2 tweak 3 = new Vector2 (1.5f , 0f);
if (hasStarted && this.GetComponent().velocity.x == 0f){
this.GetComponent().velocity += tweak3;
}
Update: I can finally keep the ball at a consistent speed. I added the following 8 if statements, took out the video’s tweak, and replaced it with 3 of my own to the OnCollisionExit2D and I haven’t seen a boring loop since I put them in. It also keeps the ball’s speed consistent.
private void OnCollisionExit2D(Collision2D collision){
Vector2 tweak1 = new Vector2(0.5f, 0f);
Vector2 tweak2 = new Vector2(0f, 2f);
if (hasStarted==true){
AudioSource audio = GetComponent();
audio.Play();
}
if (hasStarted && this.GetComponent().velocity.x <= 2f && this.GetComponent().velocity.x >= 0f) {
this.GetComponent().velocity += tweak1;
}
if (hasStarted && this.GetComponent().velocity.x <= 0f && this.GetComponent().velocity.x >= -2f){
this.GetComponent().velocity -= tweak1;
}
if (hasStarted && this.GetComponent().velocity.x >= 10f){
this.GetComponent().velocity -= tweak1;
}
if (hasStarted && this.GetComponent().velocity.x <= -10f){
this.GetComponent().velocity += tweak1;
}
if (hasStarted && this.GetComponent().velocity.y <= 2f && this.GetComponent().velocity.y >= 0f){
this.GetComponent().velocity += tweak2;
}
if (hasStarted && this.GetComponent().velocity.y <= 0f && this.GetComponent().velocity.y >= -2f){
this.GetComponent().velocity -= tweak2;
}
if (hasStarted && this.GetComponent().velocity.y >= 10f){
this.GetComponent().velocity -= tweak2;
}
if (hasStarted && this.GetComponent().velocity.y <= -10f){
this.GetComponent().velocity += tweak1;
}
}
Sometimes the ball starts going very slow. Sometimes it gets so slow that it comes down to rest on the paddle and doesn’t move anymore. It also goes too fast sometimes. Is there a way to keep the ball’s speed more consistent or even a way to reset the y velocity only when the paddle is hit?