I am trying to add touch compatibility to my js game and need to know the location of the touch event on window object, With clicks you get e.x,e.y but there is no such property for touch start.
I tried to adjust the code but it not work , this is what im working with:
window.addEventListener('touchstart',(e)=>{
console.log(e.x,e.y)//error undefined or NaN
})
the same code works for:
window.addEventListener('click',(e)=>{
console.log(e.x,e.y)//works
})
I need this for the functionality of my game as i need to detect when the user is touching a sprite drawn on canvas and not a html element, I’m okay to use any other listeners but i need the to work on touchscreen.
How to get the location of the touch event???
2
Answers
You can detect touch and obtain coordinates using this example:
Please change
e.touches[0].clientX
instead ofe.x
ande.touches[0].clientY
instead ofe.y
.And if you get delta location or position, you can use this below method.
deltaX = e.changedTouches[0].clientX - clientX;
deltaY = e.changedTouches[0].clientY - clientY;