- Joined
- Jul 3, 2017
- Messages
- 261
I was trying to implement something here (CrazyGames SDK), when I ran into a series of problems. Long story short, MouseX() and MouseY() were not working with their SDK implementation, mostly due to Monkey/Cerberus just using canvas.onmousemove, canvas.onmouseup and etc, instead of using canvas.addEventListener('mousemove', ...) and so on.
After I began to get mouse coords again, they were all over the place. So I went into the html5 target and to my horror I see this:
Every time you move your mouse, those two functions are called. If your canvas is deep into several elements, its clear this is highly inneficient!
So I took code from my games in PixiJS and rewrote those functions to something much simpler:
You can remove the "if (canvas) {" part if you want, looking at it now as I write I see it as unnecessary, but I'll leave it just in case
I haven't tested this extensively on Cerberus/Monkey - but it seems to work fine (including in the CrazyGamesSDK), so I decided to post it here, maybe hoping this could improve the target a bit
After I began to get mouse coords again, they were all over the place. So I went into the html5 target and to my horror I see this:
HTML:
function mouseX( e ){
var x=e.clientX+document.body.scrollLeft;
var c=canvas;
while( c ){
x-=c.offsetLeft;
c=c.offsetParent;
}
return x*xscale;
}
function mouseY( e ){
var y=e.clientY+document.body.scrollTop;
var c=canvas;
while( c ){
y-=c.offsetTop;
c=c.offsetParent;
}
return y*yscale;
}
Every time you move your mouse, those two functions are called. If your canvas is deep into several elements, its clear this is highly inneficient!
So I took code from my games in PixiJS and rewrote those functions to something much simpler:
HTML:
function mouseX( e ){
var x = 0;
if (canvas) {
var rect = canvas.getBoundingClientRect(),
root = document.documentElement;
// relative mouse position
x = e.clientX - rect.left - root.scrollLeft;
}
return x*xscale;
}
function mouseY( e ){
var y = 0;
if (canvas) {
var rect = canvas.getBoundingClientRect(),
root = document.documentElement;
// relative mouse position
y = e.clientY - rect.top - root.scrollTop;
}
return y*yscale;
}
You can remove the "if (canvas) {" part if you want, looking at it now as I write I see it as unnecessary, but I'll leave it just in case
I haven't tested this extensively on Cerberus/Monkey - but it seems to work fine (including in the CrazyGamesSDK), so I decided to post it here, maybe hoping this could improve the target a bit