hajimehoshi / ebiten

Ebitengine - A dead simple 2D game engine for Go
https://ebitengine.org
Apache License 2.0
11.12k stars 664 forks source link

ebiten.CursorPosition() does not always return (0,0) on mobile, when the game is compiled to WASM and runs in browser. #3087

Closed Duxo closed 2 months ago

Duxo commented 2 months ago

Ebitengine Version

v2.7.8

Operating System

Go Version (go version)

1.23.1

What steps will reproduce the problem?

Game: (built with env GOOS=js GOARCH=wasm go build -o test.wasm)

package main

import (
    "fmt"
    "log"

    "github.com/hajimehoshi/ebiten/v2"
)

type Game struct{}

func (g *Game) Layout(w int, h int) (int, int) {
    return w, h
}

func (g *Game) Update() error {
    fmt.Println(ebiten.CursorPosition())
    return nil
}

func (g *Game) Draw(screen *ebiten.Image) {}

func main() {
    err := ebiten.RunGame(&Game{})
    if err != nil {
        log.Fatal(err)
    }
}

HTML:

<!DOCTYPE html>

<html>

<head>
    <style>
        #mobile-input {
            position: absolute;
            height: 100%;
            width: 100%;
        }
    </style>
</head>

<body>
    <div id="mobile-input"></div>
    <script src="wasm/wasm_exec.js"></script>
    <script>
        const mobileInput = document.getElementById('mobile-input')
        const go = new Go();
        WebAssembly.instantiateStreaming(fetch("wasm/test.wasm"), go.importObject).then(result => {
            go.run(result.instance)
            mobileInput.addEventListener('touchstart', (event) => { mobileInput.style.zIndex = '-1' })
        })
    </script>
</body>

</html>

What is the expected result?

I expected that ebiten.CursorPosition() will always return (0,0) on mobile.

What happens instead?

After the mobile screen is touched, the ebiten.CursorPosition() returns the coordinates of the touch.

Anything else you feel useful to add?

The problem is present in Firefox and Chrome.

hajimehoshi commented 2 months ago

CursorPosition can return a mouse cursor position if you use a mouse for Android. There is no assumption that CursorPosition returns (0, 0) by default.

hajimehoshi commented 2 months ago

For touches, use the APIs for touches. https://pkg.go.dev/github.com/hajimehoshi/ebiten/v2#TouchID

Duxo commented 2 months ago

The problem is that the CursorPosition() returned a different value than (0,0) on Android without the mouse. Also, the documentation says: "CursorPosition always returns (0, 0) on mobiles."

Sorry for sounding assertive; it is the most compact way I managed to write it.

hajimehoshi commented 2 months ago

Ah, yes, that seems an issue.

Also I was misunderstanding that Ebitengine detected a mouse for Android apps but was actually not (yet). I'm sorry, I'll take a look.

hajimehoshi commented 2 months ago

The confusing point is

I'll update the comment.