From 47f5d98477ad1d0c42eb7d5efa7dca58c432ae01 Mon Sep 17 00:00:00 2001 From: maxsoulard Date: Wed, 11 Mar 2015 11:57:15 +0100 Subject: [PATCH] Simulates joystick click Simulates joystick click by calculating if the virtual stick position is within the canvas circle. basic example also updated to test the center position. --- examples/basic.html | 1 + virtualjoystick.js | 16 +++++++++++++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/examples/basic.html b/examples/basic.html index c9d15e6..ca90faf 100644 --- a/examples/basic.html +++ b/examples/basic.html @@ -76,6 +76,7 @@ + (joystick.up() ? ' up' : '') + (joystick.left() ? ' left' : '') + (joystick.down() ? ' down' : '') + + (joystick.center() ? ' center' : '') }, 1/30 * 1000); diff --git a/virtualjoystick.js b/virtualjoystick.js index 804af04..b1622fb 100644 --- a/virtualjoystick.js +++ b/virtualjoystick.js @@ -3,6 +3,7 @@ var VirtualJoystick = function(opts) opts = opts || {}; this._container = opts.container || document.body; this._strokeStyle = opts.strokeStyle || 'cyan'; + this._canvasRadius = 40 this._stickEl = opts.stickElement || this._buildJoystickStick(); this._baseEl = opts.baseElement || this._buildJoystickBase(); this._mouseSupport = opts.mouseSupport !== undefined ? opts.mouseSupport : false; @@ -140,6 +141,15 @@ VirtualJoystick.prototype.left = function(){ if( Math.abs(deltaY) > 2*Math.abs(deltaX) ) return false; return true; } +VirtualJoystick.prototype.center = function(){ + if( this._pressed === false ) return false; + var deltaX = this.deltaX(); + var deltaY = this.deltaY(); + if( this.baseX == 0 ) return false; + if( this.baseY == 0 ) return false; + if (Math.pow(this._stickX-this._baseX, 2)+Math.pow(this._stickY-this._baseY, 2)>Math.pow(this._canvasRadius, 2)) return false; + return true; +} ////////////////////////////////////////////////////////////////////////////////// // // @@ -325,13 +335,13 @@ VirtualJoystick.prototype._buildJoystickBase = function() ctx.beginPath(); ctx.strokeStyle = this._strokeStyle; ctx.lineWidth = 6; - ctx.arc( canvas.width/2, canvas.width/2, 40, 0, Math.PI*2, true); + ctx.arc( canvas.width/2, canvas.width/2, this._canvasRadius, 0, Math.PI*2, true); ctx.stroke(); ctx.beginPath(); ctx.strokeStyle = this._strokeStyle; ctx.lineWidth = 2; - ctx.arc( canvas.width/2, canvas.width/2, 60, 0, Math.PI*2, true); + ctx.arc( canvas.width/2, canvas.width/2, this._canvasRadius+20, 0, Math.PI*2, true); ctx.stroke(); return canvas; @@ -349,7 +359,7 @@ VirtualJoystick.prototype._buildJoystickStick = function() ctx.beginPath(); ctx.strokeStyle = this._strokeStyle; ctx.lineWidth = 6; - ctx.arc( canvas.width/2, canvas.width/2, 40, 0, Math.PI*2, true); + ctx.arc( canvas.width/2, canvas.width/2, this._canvasRadius, 0, Math.PI*2, true); ctx.stroke(); return canvas; }