i am trying to create 2d game. i dont know what is the name of this game but i think its airhockey(paddle are vertical rect). there are two paddles and one ball. and you have to hit the ball. if u dont hit the ball and it goes behind your padder than other person get a score. you can move your paddle only up or down.
// ex of a left paddle, right paddle and b = ball. ____________________________ | _ _ | | | | | | | | | | b | | | | | | | | | | | | | | | | | | | | | | - _ | -------------------------------------
dx = 5; //ball x postion speed dy = 5; //ball y postion speed //collision detection //if ball hit the paddler if(...) { if(..) { //change direction of ball dx = -dx; dy = -dy; } }
code above just change ball direction if it hit the paddle.
so if ball hit paddle on right than ball will go left.
now the problem with this code is that ball will goes the same place. so if you do not move the both paddles than ball will keep gooing left and right in same patterns. i am not sure how games online like this make the pattern different.
i was thinking i can check where did the ball hit first than change dy or dx. so..
//if ball hit top of paddle if(...) { dx = -dx; dy = -dy+1; //so ball direction will go lil up } //if ball hit middle of paddle if(...) { dx = -dx; //just change direction dy = -dy; } //if ball hit bottom of paddle if(...) { dx = -dx; dy = -dy-1; //ball direction will go lil down }
i am not sure if this is the best way or if this is how people create this kind of game.