Reputation: 77
I was going through a tutorial and I understood most of it. I want to ask 1 thing. This is the tutorial I am following:
https://noobtuts.com/unity/2d-pong-game
This is the Method which is called function HitFactor.
if (col.gameObject.name == "RacketLeft") {
// Calculate hit Factor
float y = hitFactor(transform.position, col.transform.position, col.collider.bounds.size.y);
// Calculate direction, make length=1 via .normalized
Vector2 dir = new Vector2(1, y).normalized;
// Set Velocity with dir * speed
GetComponent<Rigidbody2D>().velocity = dir * speed;
}
And the Hit Factor moethod is
float hitFactor(Vector2 ballPos, Vector2 racketPos,
float racketHeight) {
// ascii art:
// || 1 <- at the top of the racket
// ||
// || 0 <- at the middle of the racket
// ||
// || -1 <- at the bottom of the racket
return (ballPos.y - racketPos.y) / racketHeight;
}
Can anyone explain this to me with an example?
(ballPos.y - racketPos.y) / racketHeight;
I am really unable to understand and don't know what should I read to make myself understand this.
Upvotes: 2
Views: 8307
Reputation: 9703
The game physics are described in the tutorial
- If the racket hits the ball at the top corner, then it should bounce off towards our top border.
- If the racket hits the ball at the center, then it should bounce off towards the right, and not up or down at all.
- If the racket hits the ball at the bottom corner, then it should bounce off towards our bottom border.
This means that the direction is detemined by the hit point on the racket. This is what the formula
(ballPos.y - racketPos.y) / racketHeight
expresses. If ballPos.y
and racketPos.y
are equal, then the racket is hit on the center and the ball should fly vertically (Y direction equals 0). If the racket is hit on the top corner, the ball should fly in a 45° angle upwards (Y is 1, see ASCII art) and if the racket is hit on the bottom, the ball should fly in a 45° angle downwards (Y is -1, see ASCII art). The 45° angle (upwards or downwards) is achieved by the X and Y component of the velocity having the same absolute value. Anything in between will yield values somewhere between.
Since this behavior is independent from the measures of the racket, the distance of the ball from the center of the racket is divided by the length of the racket (actually I think it should be the half of the size, since otherwise the top would be .5 and the bottom -.5).
Upvotes: 5