New Technology – Cocos2D HTML5 and Screen Coordinates

It’s always interesting to start using some new tech, and I’ve just started dabbling with Cocos2d-html5:

It’s nice because you now write in JavaScript and easily port your game across iPhone, Android and browser. However, it is *nowhere* near as well-supported by the community as Cocos2D for iPhone is. As such, a particular headache of mine recently has been trying to get accurate screen coordinates from a moving mouse pointer. Bascially I want to orient a sprite to point at the mouse pointer when it’s hovered over the game area. The problem I was having is that the onMouseMoved() event returns the coordinates in the browser window, not the game area. Also, coordinates were in window format rather than the game world, so some conversion was needed there. The following function is my solution (with a little help from the forums), and should return world coordinates when the mouse is hovered. It takes the event passed to onMouseMoved() as a parameter.

    var scale = cc.Director.getInstance().getContentScaleFactor();
    var origin = cc.EGLView.getInstance().getViewPortRect();
    mouse.getLocation().x -= origin.origin.x;
    mouse.getLocation().y -= origin.origin.y;
    mouse.getLocation().x /= scale;
    mouse.getLocation().y /= scale;
    var location = mouse.getLocation();
    // work out proportion into screen of mouse coords, then apply to world dimensions to get "proper" touch location
    size = cc.Director.getInstance().getWinSize();
    var propX = location.x / origin.width;
    var propY = location.y / origin.height;
    location.x = size.width * propX;
    location.y = size.height * propY;
    return location;

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>