Mike Irish
Mike Irish

Reputation: 960

JavaScript process device touchscreen being held down

I am making a JavaScript canvas game and I need to detect if the touchScreen on a device is being held down as apposed to being tapped. I have it working to pick up a touch but I cant figure out how to keep calling a method while it is held down.

So I add the event handelers

function addTouchEventHandlers() 
{      
screen.canvas.addEventListener( 'touchstart', touchStart);      
screen.canvas.addEventListener( 'touchend', touchEnd );   
}

I have touch start and touch end

function touchStart(e) {      
if (gameStarted) {         
// Prevent players from inadvertently          
// dragging the game canvas         
e.preventDefault();       
}};

function touchEnd(e) {      
    var x = e.changedTouches[0].pageX;  
    var y = e.changedTouches[0].pageY; 

    if (gameStarted) {         
        if (x > screen.width/2) 
        {            
           processRightTap();            
        }         
        else if (x < screen.width/2 && y < screen.height/2) 
        {                 
           processTopLeftTap();   <- I want to keep calling this method when held down     
        }
        else if (x < screen.width/2 && y > screen.height/2) 
        {                       
           processBottomLeftTap();  <- I want to keep calling this method when held down           
        }  
        // Prevent players from double         
       // tapping to zoom into the canvas         
        e.preventDefault();       
}   
};

The Methods simply change my sprites y position

function processBottomLeftTap() {      
 ship.y += 4;
}

function processTopLeftTap() {      
ship.y -= 4;
}

Is their something similar to the keyboard method isPressed and isDown? or how would I create a while loop around the method? something like this.

while(The screen is being touched at X position)
{
processTopLeftTap();
}

Upvotes: 0

Views: 57

Answers (1)

amuramoto
amuramoto

Reputation: 2848

You could use setInterval() in your touchStart with processTopLeftTap() in the callback, then call clearInterval() on touchEnd.

Upvotes: 1

Related Questions