You didn't mention this in your post, but I'm assuming you want to not change the velocity if it didn't hit the paddle, so let's make an if function that wraps our entire velocity-changing code:
if(paddle.x + paddle.size > player.x && player.x + player.size > paddle.s){
//Code to be ran to change velocity
}
This only works if the player is square at the bottom. If you want to just go off of the middle of the player instead of the edges run this code instead:
if(paddle.x + paddle.size > player.x + (player.size/2) && player.x + (player.size/2) > paddle.x){
//Code to be ran to change velocity
}
Now that we know that the player actually hit the paddle, let's adjust the velocity for where it hit the paddle. You could do this many different ways (and please tell me if you want it differently), but I would do this by creating a velocity based on the position it hit the paddle and add the current velocity to it. I am going to have the range span from -5
to 5
.
player.vel.x += (player.x + (player.size/2) - paddle.x + (paddle.size/2)) /
(paddle.size/2) * 5;
The first line calculates where the position of the player is in relation to the paddle, and the second line puts that into a ratio between -1
and 1
and multiplies it by 5
.
All of this is added to the current velocity. The variable 5
should be changed to your liking.
The last thing to do is adjust for the paddle velocity. This should be really easy as long as you aren't going to make the paddle have less or more of an effect on the overall velocity.
player.vel.x += paddle.vel.x;
Quite simple code there is all you really need.
So to put it all together:
if(paddle.x + paddle.size > player.x + (player.size/2) && player.x + (player.size/2) > paddle.x){
player.vel.x += (player.x + (player.size/2) - paddle.x + (paddle.size/2)) /
(paddle.size/2) * 5 + paddle.vel.x;
}
Very simple code and no trigonometry needed. (yay!)
If you would like for this to be changed I can help as I actually do know math very well, I just wanted to simplify it because I'm not sure if it really needs to be more advanced.