Pong - A JavaScript GamesteemCreated with Sketch.

in #programming7 years ago (edited)

So I've recently gotten into JavaScript programming and I decided to make a little simple game... or so I thought... I eagerly began making the paddles as its the easiest object, it only goes up and down on the screen, after about 5-10 minutes I have the basic paddle engine working with the up and down arrows/W and S buttons depending on the player. Now comes the fun part I thought to myself, the ball! I quickly made a ball.js file and made the basic parameters thinking "well the ball needs an x and a y so I can keep track of the position, and a velocity in the x and y-direction to make it move." I made some basic functions and then proceeded to watch the ball fly across the screen and through my paddle... I probably stared at my ball.hit function for an hour before getting annoyed closing my IDE and going to bed. The next day I got a little help from a friend and he fixed my small little syntax error (rooky mistake) and the ball now bounced back and forth between the two paddles, success!! Well until I had to come up with a way to make it bounce at an angle..... so I came up with a little simple trigonometry algorithm to solve this issue and confidently ran my index.html to watch the ball and all my hopes and dreams bounce off the paddle and into the infinite void of the bottom of the screen.. I realized I didn't take into account the top and bottom of the screen. I threw together some code that I figured was logical, just reverse the y velocity as it reaches or exceeds the boundaries of the screen, 5 = -5, 10 = -10. I cannot tell you how many times I tried this method without success finally I got frustrated and went to bed. In bed, I just kept thinking about it until I thought "If I'm just going to stay up thinking about it I might as well get up and code it." so I changed what I had to two functions called this.hitTop() and this.hitBottom() and put either this.ballVy += (-2 * this.ballVy); or this.ballVy -= (2 * this.ballVy); instead of this.ballVy * -1; both ways technically change 5 to -5 and -5 to 5 but for some reason, this way worked and the other didn't. So this pretty much concludes my JavaScript journey to make Pong, I hope you enjoyed!



Github link for those interested in seeing my ugly code:

https://github.com/robert-macdonald/Personal-Web/tree/master/Pong

Sort:  

Thanks, a lot comes from following through with what you set out to do.

Awesome, you're more fluent in JavaScript than I am, still don't know how to use Canvases yet lol, probably will learn some time. This is cool :3

The createCanvas function is actually part of the p5js library. The draw and setup are also from that library. I am better at javascript than I am at java, but I'm getting there.

Coin Marketplace

STEEM 0.18
TRX 0.13
JST 0.028
BTC 57340.70
ETH 3072.28
USDT 1.00
SBD 2.37