1
\$\begingroup\$

I am making a simple game of mine mobile-friendly.

The goal is to:

  • Make character walk if a touchstart event is sensed on right half of screen.

  • Stop character if a touchend event is sensed on the right half.

  • Jump the character if a touchend event happens on the left half of the screen.

I have the logic working perfectly for mouse up and down events so I'm pretty sure it's something to do inside the touchstart and end functions.

If two fingers are used as one press it seems to work fine.

If only one finger is used it doesn't work properly: touching anywhere starts the movement but nothing will stop it.

Here is the code for the touch inputs and associated function:

CheckWhichScreenHalf = function(e) {

    loc = WindowToCanvas(e.pageX, e.pageY);
    onScreenY = loc.y >= 0 && loc.y <= gameCanvas.height;
    leftSideX = loc.x >= 0 && loc.x < gameCanvas.width/2;
    rightSideX = loc.x > gameCanvas.width/2 && loc.x <= gameCanvas.width;
    if (onScreenY && leftSideX){
        return 'left';
    }
    else if (onScreenY && rightSideX){
        return 'right';
    }
    else return 'neither';
};

TouchMove = false;
TouchJump = false;

gameCanvas.ontouchstart = function(e){

    if (imagesHaveBeenLoaded) {
        e.preventDefault();
        for (var i = 0; i < e.touches.length; i++){
            var side = CheckWhichScreenHalf(e.touches.item(i));
            if (side === 'right'){
                TouchMove = true;
            }
        }
    }
}
gameCanvas.ontouchend = function(e){

    if (imagesHaveBeenLoaded) {
        e.preventDefault();
        for (var i = 0; i < e.touches.length; i++){
            var side = CheckWhichScreenHalf(e.touches.item(i));
            if (side === 'right'){
                TouchMove = false;
            }
            else if (side === 'left'){
                playerJumping = true;
            }
        }
    }
}

The game can be played here: http://webstudentwork.com/jgossling/MMWD/mp2/mp2.html

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.