module.exports = class Player { constructor() { this.id = 0; this.socket = null; this.position = {x: 60, y: 60}; this.velocity = {x: 0, y: 0}; this.maxSpeed = 3; this.turnRate = Math.PI / 8; this.moveToTarget = false; this.targetDestination = {x: 60, y: 60}; this.targetAngle = 0; this.angleRadians = 0; this.shipColor = null; this.playerName = "Player"; this.shipColor = "#DD3333"; } getData(keys) { var response = {}; for(var i in keys) { if(this.hasOwnProperty(keys[i])) { response[keys[i]] = this[keys[i]]; } } return response; } sendMessage(data) { data.timestamp = new Date().getTime(); this.socket.sendUTF(JSON.stringify(data, null, "\t")); } update(delta) { //this.angleRadians = this.targetAngle; /*if(this.angleRadians != this.targetAngle) { if(this.angleRadians > this.targetAngle) { this.angleRadians += Math.min(this.angleRadians - this.targetAngle, -this.turnRate); } if(this.angleRadians < this.targetAngle) { this.angleRadians += Math.min(this.angleRadians + this.targetAngle, this.turnRate); } }*/ if(this.moveToTarget) { if(this.targetDestination.x > this.position.x) { //we're moving right if(this.position.x + this.velocity.x * delta > this.targetDestination.x) { this.position.x = this.targetDestination.x; this.velocity.x = 0; } else { this.position.x += this.velocity.x * delta; } } else if(this.targetDestination.x < this.position.x) { //we're moving left if(this.position.x + this.velocity.x * delta < this.targetDestination.x) { this.position.x = this.targetDestination.x; this.velocity.x = 0; } else { this.position.x += this.velocity.x * delta; } } else { this.position.x += this.velocity.x * delta; } if(this.targetDestination.y > this.position.y) { //we're moving down if(this.position.y + this.velocity.y * delta > this.targetDestination.y) { this.position.y = this.targetDestination.y; this.velocity.y = 0; } else { this.position.y += this.velocity.y * delta; } } else if(this.targetDestination.y < this.position.y) { //we're moving up if(this.position.y + this.velocity.y * delta < this.targetDestination.y) { this.position.y = this.targetDestination.y; this.velocity.y = 0; } else { this.position.y += this.velocity.y * delta; } } else { this.position.y += this.velocity.y * delta; } if(this.targetDestination.x == this.position.x && this.targetDestination.y == this.position.y) { //we're moving right this.moveToTarget = false; this.sendUpdate(this); } } else { this.position.x += this.velocity.x * delta; this.position.y += this.velocity.y * delta; } } sendUpdate(sender) { var keys = ["id", "position", "velocity", "targetDestination", "shipColor", "moveToTarget", "targetAngle", "angleRadians", "playerName"]; if(sender == this) { this.sendMessage({player: this.getData(keys)}); } else { this.sendMessage({other: sender.getData(keys)}); } } logout() { this.socket.close(); } };