dimanche 18 septembre 2016

Simulate keypress javascript NO JQuery

I have a webgame I made in pure javascript using processing.js It works fine on desktop but I want it to work on mobile. It's on this website: http://ift.tt/2cVSdTu

I found a function to detect swipes

function swipedetect(el, callback){

var touchsurface = el,
swipedir,
startX,
startY,
distX,
distY,
threshold = 150, //required min distance traveled to be considered swipe
restraint = 100, // maximum distance allowed at the same time in perpendicular direction
allowedTime = 300, // maximum time allowed to travel that distance
elapsedTime,
startTime,
handleswipe = callback || function(swipedir){}

touchsurface.addEventListener('touchstart', function(e){
    var touchobj = e.changedTouches[0]
    swipedir = 'none'
    dist = 0
    startX = touchobj.pageX
    startY = touchobj.pageY
    startTime = new Date().getTime() // record time when finger first makes contact with surface
    e.preventDefault()
}, false)

touchsurface.addEventListener('touchmove', function(e){
    e.preventDefault() // prevent scrolling when inside DIV
}, false)

touchsurface.addEventListener('touchend', function(e){
    var touchobj = e.changedTouches[0]
    distX = touchobj.pageX - startX // get horizontal dist traveled by finger while in contact with surface
    distY = touchobj.pageY - startY // get vertical dist traveled by finger while in contact with surface
    elapsedTime = new Date().getTime() - startTime // get time elapsed
    if (elapsedTime <= allowedTime){ // first condition for awipe met
        if (Math.abs(distX) >= threshold && Math.abs(distY) <= restraint){ // 2nd condition for horizontal swipe met
            swipedir = (distX < 0)? 'left' : 'right' // if dist traveled is negative, it indicates left swipe
        }
        else if (Math.abs(distY) >= threshold && Math.abs(distX) <= restraint){ // 2nd condition for vertical swipe met
            swipedir = (distY < 0)? 'up' : 'down' // if dist traveled is negative, it indicates up swipe
        }
    }
    handleswipe(swipedir)
    e.preventDefault()
}, false)

}

I can activate and detect which direction was swiped like this

swipedetect(el, function(swipedir){
if (swipedir == 'left')
    alert('You just swiped left!')
});

My function to move the player is like this

var movePlayer = function(){
if(keyCode === LEFT){
    x -= 3.5*scaless;
}
if(keyCode === RIGHT){
    x += 3.5*scaless;
}
if(keyCode === UP){
    y -= 3.5*scaless;
}  
if(keyCode === DOWN){
    y += 3.5*scaless;
}
};
if(keyPressed){
    movePlayer();
}

How could I make the function that detects a swipe, simulate a keypress?




Aucun commentaire:

Enregistrer un commentaire