1

So I have my controls set up as space bar to jump but I want my HTML5 game to work everywhere so I need to change it to mouse/touch. Mouse/touch doesnt have a keycode so whats the most optimal way to do it for this code? Do I need to do mouse and touch separately?

if (KEY_STATUS.space && player.dy === 0 && !player.isJumping) {
  player.isJumping = true;
  player.dy = player.jumpDy;
  jumpCounter = 12;
  assetLoader.sounds.jump.play();
}

// jump higher if the space bar is continually pressed
if (KEY_STATUS.space && jumpCounter) {
  player.dy = player.jumpDy;
}
GoogleFailedMe
  • 125
  • 1
  • 1
  • 7

1 Answers1

1

You are talking about touch events in JavaScript. You will have to add an event listener and catch if the user touches screen. Here you can find a well documented tutorial in how to use it on both touchscreen and mouse.

Check out the first answer, you will have to do it like that. You will have to add an event listener on the canvas itself, like the guy did it on myDiv.

Here is an example I wrote (don't mind me being weird, please):

<div id="fakeCanvas">
    Click or touch me!
</div>

<script type="text/javascript">
    var fakeCanvas = document.getElementById('fakeCanvas');

    function methodToInvokeForClick() {
        alert('I have been clicked!');
    }

    function methodToInvokeForTouch() {
        alert('I have been touched!');
    }

    fakeCanvas.addEventListener("click", methodToInvokeForClick, false);
    fakeCanvas.addEventListener("touchstart", methodToInvokeForTouch, false);
</script>

I think you can take it over from now. What I did to the fakeCanvas div, you will have to do the same to your canvas by giving it an id etc. Good luck!

Community
  • 1
  • 1
ihsan
  • 576
  • 2
  • 5
  • 18
  • Thanks for the reply! I have read the tutorial and it doesnt help with my problem I dont know how to incorporated into my game. – GoogleFailedMe Dec 31 '14 at 15:31
  • @GoogleFailedMe, I edited my answer. Check it out, it may help you out. – ihsan Dec 31 '14 at 15:37
  • If I add an event listener on the canvas itself how do I use it in my if statement so I can get the player to jump? Can you edit my code so I can see how it would be done? thanks I am a beginner so sorry for not knowing – GoogleFailedMe Dec 31 '14 at 15:49
  • @GoogleFailedMe, oh by the way, I forgot to mention that I edited my answer again. – ihsan Jan 01 '15 at 12:55