diff --git a/virtualjoystick.js b/virtualjoystick.js index bc6b7e0..e590e9c 100644 --- a/virtualjoystick.js +++ b/virtualjoystick.js @@ -24,6 +24,13 @@ var VirtualJoystick = function(opts) this._stickX = 0; this._stickY = 0; + this._updatePositionOfContainer(); + window.onresize = (function (joystick) { + return function () { + return joystick._updatePositionOfContainer(); + } + })(this); + var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; this._$onTouchStart = __bind(this._onTouchStart , this); this._$onTouchEnd = __bind(this._onTouchEnd , this); @@ -31,6 +38,7 @@ var VirtualJoystick = function(opts) this._container.addEventListener( 'touchstart' , this._$onTouchStart , false ); this._container.addEventListener( 'touchend' , this._$onTouchEnd , false ); this._container.addEventListener( 'touchmove' , this._$onTouchMove , false ); + if( this._mouseSupport ){ this._$onMouseDown = __bind(this._onMouseDown , this); this._$onMouseUp = __bind(this._onMouseUp , this); @@ -41,6 +49,21 @@ var VirtualJoystick = function(opts) } } +VirtualJoystick.prototype._updatePositionOfContainer = function () { + var x = 0, y = 0; + + var element = this._container; + while (element && !isNaN(element.offsetLeft) && !isNaN(element.offsetTop)) { + x += element.offsetLeft - element.scrollLeft; + y += element.offsetTop - element.scrollTop; + element = element.offsetParent; + } + this._containerX = x; + this._containerY = y; + + console.log("updated x="+x+" y="+y) +} + VirtualJoystick.prototype.destroy = function() { this._container.removeChild(this._baseEl); @@ -153,7 +176,6 @@ VirtualJoystick.prototype._onDown = function(x, y) this._stickX = x; this._stickY = y; - this._stickEl.style.display = ""; this._stickEl.style.left = (x - this._stickEl.width /2)+"px"; this._stickEl.style.top = (y - this._stickEl.height/2)+"px"; @@ -185,15 +207,17 @@ VirtualJoystick.prototype._onMouseUp = function(event) VirtualJoystick.prototype._onMouseDown = function(event) { - var x = event.clientX; - var y = event.clientY; + var x = event.clientX - this._containerX; + var y = event.clientY - this._containerY; + return this._onDown(x, y); } VirtualJoystick.prototype._onMouseMove = function(event) { - var x = event.clientX; - var y = event.clientY; + var x = event.clientX - this._containerX; + var y = event.clientY - this._containerY; + return this._onMove(x, y); } @@ -217,8 +241,8 @@ VirtualJoystick.prototype._onTouchStart = function(event) this._touchIdx = touch.identifier; // forward the action - var x = touch.pageX; - var y = touch.pageY; + var x = touch.clientX - this._containerX; + var y = touch.clientY - this._containerY; return this._onDown(x, y) } @@ -257,8 +281,9 @@ VirtualJoystick.prototype._onTouchMove = function(event) event.preventDefault(); - var x = touch.pageX; - var y = touch.pageY; + var x = touch.clientX - this._containerX; + var y = touch.clientY - this._containerY; + return this._onMove(x, y) }