drawkcaB | Backward Compatible logo

rants and tips about software

Capturing mouse movement with Cocos2d-html5 and replacing default cursor

I decided to try to use Cocos2d instead of jQuery and DOM for my next browser game. I find Cocos2d documentation confusing, and googling around you are more likely to get Cocos2d-iPhone documentation that simply does not apply for some stuff.

I spent a couple of hours trying to understand how to handle mouse or if it is even possible. I found examples using Cocos2d-javascript that worked fine, but using the same code with Cocos2d-html5 did not. At one point I was close to conclude that mouse is not supported as everything tries to emulate touch. However, this is not the case, mouse handling works fine.

Currently (Cocos2d-html5 version 2.1.3), the best documentation is to read the file CCMouseDispatcher.js in cocos2d/touch_dispatcher directory. In your code, in layer object you can use onMouseMoved and other methods found in this file. You might need to figure out the parameters yourself. For example, onMouseMoved returns an event object which has getLocation() function, which returns another object with x and y properties. So, the code to draw a custom cursor would be something like creating the sprite and then updating its position like this:

onMouseMoved:function (event) {
    cursorSprite.setPosition(cc.p(
        event.getLocation().x,
        event.getLocation().y)
    );
}

Now, this would give you two cursors. I tried setting the cursor for the canvas element to none via CSS, but it did not work. Another workaround would be to set a transparent 1x1 pixel cursor using CSS like:

canvas { cursor: url('transparent-image.png') }

I'm yet to try if this works, but somehow I feel it won't. This is all using Firefox 16 on Linux.

Milan Babuškov, 2013-05-07
Copyright © Milan Babu┼íkov 2006-2017