Standard arkanoid collision

Hi!
I noticed that in arkanoids when the ball and the paddle collides the ball goes in a direction based on its position to the paddle. So if the ball hits the paddle on the left it goes left, on right it goes right and the further the ball is from the midpoint the more it goes sideways. I came up wtih a way to make this behaviour. See the code here:

    if(collision.collider.CompareTag("Player"))
    {
        float ballLocationX = transform.position.x;
        float paddleLocationX = collision.collider.transform.position.x;
        float difference = ballLocationX - paddleLocationX;
        myRigidBody2D.velocity = new Vector2(difference * tweakOnPaddleCollision, yPush);
    }

The only problem with this is i think by standard arkanoid rules (which i’m trying to keep my game to) the ball should have a constant speed except for when powerups are used. But the more the ball is on the side compared to the paddle, the faster it is, i guess because y and x velocity kinda’ adds together. How could i possibly solve this so the ball goes in a direction based on the collision point and keeps a constant speed? Thank you for your answers in advance!

Add:

myRigidbody2D.velocity = myRigidbody2D.velocity.normalized * myVelocity;

where myVelocity in Start():

myVelocity = Mathf.Sqrt(xVel * xVel + yVel * yVel);

1 Like

Not sure whether it will be of any help, I as I think you may have covered the point of impact, although I do use the local position also in this rather aged post;

1 Like

It’s working thank you! Is it possible that you add an explanation? :slight_smile:

English is not a language I am fluent in, so I apologize for any grammar or other error.

You have a vector 2 (Vx, Vy) that it gives the velocity magnitude in the axes x and y. Another form of representing this vector is saying: The general velocity is V (myVelocity) and goes (for example) 1/3 in the x axis, and 2/3 in the y axis. You want V constant and it is the proportion in x and y axis that changes. So, in the Start(), you need to calculate the V (the constant we don’t want to change), so we can adjust it in the other methods.

To calculate this constant, we have Vx and Vy, and (Pythagoras Theorem) V= square root of (Vx^2+Vy^2).

Now, we have the V value. There is a method (Vector2.normalized) that gives you the proportion (1/3 and 2/3 for example) of the vector. The vector that returns you is normalized, so its total value is 1, but preserves its directions. So you only need to multiply it by V to have a new vector with V as a value and the new directions.

I don’t know if my explanation is clear enough. I hope it helps you!

2 Likes

Privacy & Terms