Phaser virtual joystick
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <reference path="../lib/phaser.d.ts"/> | |
/// <reference path="../lib/socket.io.d.ts"/> | |
/// <reference path="ship.ts"/> | |
module AstRoidGame { | |
export class ControlStick extends Phaser.Group { | |
controlField: Phaser.Sprite; | |
stickCenterPos: Phaser.Point; | |
stick: Phaser.Sprite; | |
game: Phaser.Game; | |
isUp: boolean; | |
isDown: boolean; | |
isLeft: boolean; | |
isRight: boolean; | |
constructor(game: Phaser.Game, group: Phaser.Group, x:number, y:number) { | |
super(game, group, 'ControlStick'); | |
this.game = game; | |
this.controlField = this.game.add.sprite(x, y, 'hud-control-field', 0, this); | |
this.controlField.fixedToCamera = true; | |
this.controlField.anchor.set(0, 1); | |
var centerX = this.controlField.x + (this.controlField.width / 2); | |
var centerY = this.controlField.y - (this.controlField.height / 2); | |
this.stickCenterPos = new Phaser.Point(centerX, centerY); | |
this.stick = this.game.add.sprite(centerX, centerY, 'hud-control-stick', 0, this); | |
if(!this.game.device.desktop){ | |
this.stick.scale.set(1.15); | |
} | |
this.stick.anchor.set(0.5); | |
this.stick.fixedToCamera = true; | |
this.stick.inputEnabled = true; | |
this.stick.input.enableDrag(); | |
this.stick.events.onDragUpdate.add(this.dragStart, this); | |
} | |
dragStart(sprite, pointerDirection) { | |
var deltaX = pointerDirection.x - this.stickCenterPos.x; | |
var deltaY = pointerDirection.y - this.stickCenterPos.y; | |
var maxPixel = 50; | |
var minPixel = -50; | |
var threshold = 30; | |
if(deltaX > maxPixel){ | |
this.stick.cameraOffset.x = this.stickCenterPos.x + maxPixel; | |
}else if(deltaX < minPixel){ | |
this.stick.cameraOffset.x = this.stickCenterPos.x + minPixel; | |
}else { | |
this.stick.cameraOffset.x = this.stickCenterPos.x + deltaX; | |
} | |
this.isRight = false; | |
this.isLeft = false; | |
if(deltaX > threshold){ | |
this.isRight = true; | |
}else if(deltaX < -threshold){ | |
this.isLeft = true; | |
} | |
if(deltaY > maxPixel){ | |
this.stick.cameraOffset.y = this.stickCenterPos.y + maxPixel; | |
}else if(deltaY < minPixel){ | |
this.stick.cameraOffset.y = this.stickCenterPos.y + minPixel; | |
}else { | |
this.stick.cameraOffset.y = this.stickCenterPos.y + deltaY; | |
} | |
this.isUp = false; | |
this.isDown = false; | |
if(deltaY < -threshold){ | |
this.isUp = true; | |
}else if(deltaY > threshold){ | |
this.isDown = true; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment