Why we use Vector2?

Hello there, I am just wondering why do we calculate the offset if we are not using it to universally find the ball anywhere, so we can stick it to the ball from any start position it would have?
I mean, if I apply your code and put my ball away from paddle and start the game, the ball will keep the same X and Y coordinates from the paddle, it will not stick to it . IT will only stay sticked to it if we put the ball on the paddle before the game start.

So, to get ball on the paddle, why I cannot simply use this:

void Update () {
transform.position = new Vector2(paddlePos.x, paddlePos.y+offset);
}

While offset is sum of height of the (ball + paddle) divided by two.

2 Likes

Hey Peter. This is what I thought of as well. I figure this way the logic could be reused, wrapped in a stick ball to paddle function to use during gameplay etc.

My approach (good or bad) was to provide the offset we want for the ball to the paddle. This way different offsets can be set based on different paddles and balls we may be using. On start we move the ball to the paddle at our offset, then have the ball follow the paddle around. I see the next lesson is releasing the ball, so I assume we will be changing the logic below so the ball may be released, etc.

Brett

public class Ball : MonoBehaviour
{
    [SerializeField]
    Paddle paddle0;

    [SerializeField]
    [Tooltip("The offset to use so the ball is stuck to the paddle correctly")]
    Vector2 stickBallToPaddleOffset;

    // Start is called before the first frame update
    void Start()
    {
        Vector3 setBallInitalPosition = paddle0.transform.position + new Vector3(stickBallToPaddleOffset.x, stickBallToPaddleOffset.y, 0f);
        transform.position = setBallInitalPosition;
    }

    // Update is called once per frame
    void Update()
    {
        Vector2 paddlePos = new Vector2(paddle0.transform.position.x, paddle0.transform.position.y);
        transform.position = paddlePos + stickBallToPaddleOffset;
    }
}

Privacy & Terms