eventListener() with This dodger game
how ever when I try to move the dodger to the right side without going off the container(The dodger width is 40px) it doesn’t work here is my codepen
any hint will be greatly appreciated .
What do you want it to do?
Your html has error. Its codepend related. Leave only this part of the html:
<div id="game"> <div id="dodger" style="bottom: 0px; left: 180px;"></div> </div>
In codepen, the
html tag, the
head and the
Since for both left and right movement, you utilize same event(“keydown”), you can directly move those move left and right functions in the same event listener and execute the appropriate one, when the correct key is pressed, just how you do.
You can call
dodger.getBoundingClientRect(), which will give you some positioning stats of the element you call it on(your dodger rectangle). Using those values, you can determine when for example, the move right function should not be executed(when its +200 px from dodger starting position, in your case, or something alongthe lines). You can composite the condition many ways, so it fits your purpose.
Another option, without checkign the element position is to try and set some global state of your dodger, to estimate how much it has moved left and right from its initial position and put limits based on it. Everytime you move left, you will add the movement value to the left(-) and everytime you move right, you add it to right(+) and not let it go over 200px left or right