yuripourre / anne-beth-bomb-edition

Bomberman written in JavaScript
http://bombergirl.matousskala.cz
MIT License
1 stars 0 forks source link

[Enhancement] Make it playable on Mobile #15

Open yuripourre opened 2 hours ago

yuripourre commented 2 hours ago

We can add an on-screen joystick.

Better yet, we can add two!

yuripourre commented 2 hours ago
<!DOCTYPE html>
<html>
<head>
    <title>EaselJS Joystick</title>
    <script src="https://code.createjs.com/1.0.0/easeljs.min.js"></script>
</head>
<body>
    <canvas id="gameCanvas" width="500" height="500"></canvas>

    <script>
        const canvas = document.getElementById("gameCanvas");
        const stage = new createjs.Stage(canvas);

        const joystickRadius = 50;
        const knobRadius = 20;
        const centerX = 100;
        const centerY = 400;

        // Create the joystick base
        const joystickBase = new createjs.Shape();
        joystickBase.graphics.beginFill("gray").drawCircle(0, 0, joystickRadius);
        joystickBase.x = centerX;
        joystickBase.y = centerY;

        // Create the joystick knob
        const joystickKnob = new createjs.Shape();
        joystickKnob.graphics.beginFill("red").drawCircle(0, 0, knobRadius);
        joystickKnob.x = centerX;
        joystickKnob.y = centerY;

        // Add to stage
        stage.addChild(joystickBase, joystickKnob);

        let isTouching = false;

        // Handle touch/mouse events
        joystickKnob.on("mousedown", function(evt) {
            isTouching = true;
        });

        stage.on("stagemousemove", function(evt) {
            if (isTouching) {
                const dx = evt.stageX - centerX;
                const dy = evt.stageY - centerY;
                const distance = Math.sqrt(dx * dx + dy * dy);

                // Limit the knob's movement to within the joystick's radius
                if (distance < joystickRadius) {
                    joystickKnob.x = evt.stageX;
                    joystickKnob.y = evt.stageY;
                } else {
                    // Calculate the limited position
                    const angle = Math.atan2(dy, dx);
                    joystickKnob.x = centerX + joystickRadius * Math.cos(angle);
                    joystickKnob.y = centerY + joystickRadius * Math.sin(angle);
                }

                // Calculate and log joystick direction (dx, dy)
                const directionX = (joystickKnob.x - centerX) / joystickRadius;
                const directionY = (joystickKnob.y - centerY) / joystickRadius;
                console.log("Direction: ", { x: directionX, y: directionY });
            }
        });

        stage.on("stagemouseup", function(evt) {
            isTouching = false;

            // Return the joystick knob to the center
            joystickKnob.x = centerX;
            joystickKnob.y = centerY;
        });

        createjs.Ticker.on("tick", stage);
    </script>
</body>
</html>