DEV Community

Cover image for Vanilla JavaScript Archery Game

Vanilla JavaScript Archery Game

glenntippett profile image Glenn Tippett ・2 min read

So it's a bit rainy today, can't go outside - so I thought maybe I'd play some archery inside... JS style!

Here is the CodePen:

Alt Text

I won't go into too much detail here, I'll let the CodePen do the talking but if you have any questions please comment.

There's a lot of ways this could have been done and this was just a quick throw together so it's not perfect - and please don't open on mobile unless you want Internet-Explorer-design-style flashbacks.

The target itself is just one </div> tag utilising the box-shadow property to give that multi-color effect.

Alt Text

The position of the arrow hitting the target is determined by some Math.Random() calls to set the X and Y position on the target.

Alt Text

The plusOrMinusOdds is calculating that 50% of the time the posOrNeg variable will be either a - or a +.
This is pre-pended to the pixel value to allow the arrow to land either side of the middle of the target.

I ran into some issues when viewing on a larger screen so I gave the body a max-width to help with this.

The game also looks best if you click 'Reset' between each shot, so the arrow goes off-screen and comes back. Otherwise the arrow just does this weird glide thing...

I may come back to this at a later date to fix the bugs and implement a few other features like a score counter, sound effects etc.

Until then, enjoy!

Discussion (0)

Editor guide