Hey, everyone. I’ve added a piece of code that allows the player to control the direction of the ball based on what side of the paddle it hits. I have seen this functionality among other block breakers.
Below is the code if you are interested. It’s placed in the ball script in the OnCollision trigger. I tried to write it as tidy as I could, but surely there is an even cleaner way. I was scratching my head on a clever way to determine through math whether or not the ball should reverse direction, but the best I could come up with was two pairs of booleans.
void OnCollisionEnter2D (Collision2D collision){
// Original code. Add variance to bounce.
Vector2 tweak = new Vector2 (Random.Range(-1f, 1f), 0);
rigidbody2D.velocity += tweak;
// Player controlled direction
if(collision.transform.gameObject.name == "Paddle"){ // If collision with Paddle
bool bDir = rigidbody2D.velocity.x >= 0 ; // Is Ball moving to the right?
bool pPos = paddle.transform.position.x >= transform.position.x ; // Is Paddle ahead of Ball?
// Ball is moving right and Paddle is ahead of Ball OR Ball is moving left and Paddle is behind Ball
if ( bDir && pPos || !bDir && !pPos ) {
// Reverse direction Reverse X spd / Original Y spd
Vector2 inverse = new Vector2(rigidbody2D.velocity.x * -1, rigidbody2D.velocity.y);
rigidbody2D.velocity = inverse;
}
}
}
Cheers.