# [TIP] Logic for player to control direction of ball

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
bool bDir = rigidbody2D.velocity.x >= 0 ;  	 // Is Ball moving to the right?

// 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.

1 Like

I did something similar, however I made it such that the angle the ball reflects at depends on how far it is from the center of the paddle. I tagged the paddle with the “PlayerController” tag, and defined a bool “isPlayerControler”.

``````   //play boing sound on collision; make ball vector depend on location relevant to paddle
void OnCollisionEnter2D (Collision2D collision) {
isPlayerController = (collision.gameObject.tag == "PlayerController");
Debug.Log(collision.gameObject.tag);
if (isPlayerController) {
float impactLocation = this.transform.position.x - collision.transform.position.x;
//mapping of the intended bounce angle to the position difference {-0.5,0.5} to {135deg, 45 deg}
float bounceAngleDegrees = 90.0f - (45.0f / 0.5f * (impactLocation/1.0f));
//impactLocation is divided by a floating number (1.0 in this case) to allow me to tone down the effect of the paddle location relative to ball on reflect angle if so desired
float bounceAngleRadians = bounceAngleDegrees * 2.0f * 3.14159f / 360.0f;