2
votes

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;

Image of ball and racket's y position

I am really unable to understand and don't know what should I read to make myself understand this.

1
Well, work an example. Suppose the racket is 100 pixels long, the ball is at y position 220, and the middle of the racket is at y position 200. Where is the ball as a fraction of the length of the racket as described in the comment? - Eric Lippert
Thanks a lot Eric. col.transform.position will give the middle(y) position of the racket ? - user5234003

1 Answers

3
votes

The game physics are described in the tutorial

Pong game physics

  • 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).