[TIP] How I made ball-paddle impact position affect bounce

ball.cs code:
https://pastebin.com/Kkwb0vD3

  1. In Unity, create a tag “PlayerController” and select it on the paddle.
  2. In ball.cs declare and initialize a bool to later use in the collision function to confirm ball hit the paddle rather than another object: “private bool isPlayerController = false;”
  3. In the OnCollisionEnter2D function, first thing I do is set isPlayerController = (collision.gameObject.tag == “PlayerController”); This will return true if the ball’s collision is with the paddle.
  4. In same function, create an if statement "if (isPlayerController). The rest of this code is the executed code for this if statement.
  5. create a float (impactLocation) which gives a value between -0.5 and +0.5 depending on where the ball hits the paddle. The paddle is 1 unit long, so the difference in x coordinates will be 0.5 units either direction. “float impactLocation = this.transform.position.x - collision.transform.position.x;”
  6. The idea is to convert the impactLocation to an angle that the ball will be sent away at. I just decided that it would make sense to reflect @ 45 degrees at the edges. There’s probably a more elegant way to do it, but I just found the equation to map the values from -0.5 to 0.5 to the angles 135 deg to 45 degrees. So enter “float bounceAngleDegrees = 90.0f - (45.0f / 0.5f * (impactLocation/1.0f));” I added the division by 1.0f at the end so that I could scale the effect up or down by changing the divisor.
  7. Convert to radians (forgot to do this initially. doh!). float bounceAngleRadians = bounceAngleDegrees * 2.0f * 3.14159f / 360.0f;
  8. Modify the ball’s velocity vector components using trig functions to produce the desired angle without changing the magnitude of the velocity. “this.rigidbody2D.velocity = new Vector2 (ballSpeed* Mathf.Cos(bounceAngleRadians), ballSpeed * Mathf.Sin(bounceAngleRadians));”

Tested, and it works pretty well. Gives the player control over the bouncing, which makes it more fun. One thing to note is that the autotest feature we implemented will bounce the ball perfectly vertical, so my solution to this was to modify the auto-positioning of the paddle to include a small random offset.

That was really cool!
I am gonna follow your lead to improve my game too!
thx a lot

Hey I am following pretty well but I am wondering how to set the ball speed. Knowing that this is a public variable, setting it to 10 in unity is not working. Is there another script working here?

Thanks in advance!

Figured out my own problem. Works well!!

Privacy & Terms