0
votes

I'm making a simple javascript game where the player shoots the incoming projectiles. Below is the code snippet that is not working.

['click', 'touchstart', 'touchend'].forEach(
    function (type) {
        window.addEventListener (type,
            function(event) {
                
                const angle = Math.atan2(event.clientY - yHalf, event.clientX - xHalf)

                const velocity = {
                x: Math.cos(angle) * 5,
                y: Math.sin(angle) * 5
                }

                projectiles.push(
                    new Projectile(
                        xHalf,
                        yHalf,
                        5,
                        'white',
                        velocity
                    )
                )
            }
        )
    }
)

A quick description of the code: when 'click' or 'touchstart' or 'touchend' event occurs, it adds a Projectile object into an array. The array is then drawn continuously (the function for this is not included in the above code snippet). Basically, when the mouse is clicked or the screen is touched, the player shoots a projectile.

But the problem is, when on a mobile phone, nothing happens when I touch the screen, which means the above code snippet is not working. However, it does work on a computer; if I press the mouse or if I simulate touching in developer tools, the player shoots a projectile.

I have the game hosted on my github pages as well as the full source code:

Game: https://v1ct0rv00rh33s.github.io/Space-Balls/

Source code: https://github.com/v1ct0rv00rh33s/Space-Balls

Can I have some help with making this work on a phone?

Edit: I'm using iPhone 7 Plus with iOS 12.4 and Safari.

1
could you add your brower, OS, and model? - Rojo
on which platform? Touch APIs are not synchronised across mobile browsers (and to an extent not even for desktop browsers) and various platforms have their own implementations of touch events. - rags2riches-prog

1 Answers

0
votes

I tested it on my phone and it works fine. Touch events are suppoted in most browsers but check https://caniuse.com/touch