I wasnted to know if it was possible to do something along the lines of:
var test = function(testValue){
if(testValue == true) doThing1();
if(testValue == false) doThing2();
}
The context of what this is for, I'm obviously new to JS and am creating a small game similar to an agario-but-simpler and I'm using it for movement. My ideal setup is:
class Player {
/*
* @param {int} x - x position
* @param {int} y - y position
* @param {int} size - size of object
*
*/
constructor(x, y, size) {
this.x = x;
this.y = y;
this.size = size;
this.points = 0;
this.velocity = 1;
this.color = 'white';
}
addPoints(amount) {
points = amount;
}
changeVelocity(newVelocity) {
velocity = newVelocity;
}
moveLeft = function (canMove) {
if (canMove) { this.x -= this.velocity; }
}
moveRight = function (canMove) {
if (canMove) { this.x = this.velocity; }
}
moveUp = function (canMove) {
if (canMove) { this.y -= this.velocity; }
}
moveDown = function (canMove) {
if (canMove) { this.y = this.velocity; }
}
}
I'm looking to have keyDown 'w' set moveUp to true and then complete the movement per screen refresh where I redraw every screen element. Then when I keyUp 'w' set moveUp to false. I'm looking mostly for if this style of variable-value-parameter-passing is possible.
*EDIT: I'm looking for the keyUp/keyDown to change the variable's value which in turn ALSO directly changes the param passed to the corresponding function.
CodePudding user response:
I don't think you need function parameters, use an object property instead. The keyup/keydown code can call player.enableMove()
and player.disableMove()
.
Also, addPoints()
and changeVelocity()
need to assign this.xxx
.
class Player {
/*
* @param {int} x - x position
* @param {int} y - y position
* @param {int} size - size of object
*
*/
constructor(x, y, size) {
this.x = x;
this.y = y;
this.size = size;
this.points = 0;
this.velocity = 1;
this.color = 'white';
this.canMove = true;
}
addPoints(amount) {
this.points = amount;
}
changeVelocity(newVelocity) {
this.velocity = newVelocity;
}
enableMove() {
this.canMove = true;
}
disableMove() {
this.canMove = false;
}
moveLeft = function() {
if (this.canMove) {
this.x -= this.velocity;
}
}
moveRight = function() {
if (this.canMove) {
this.x = this.velocity;
}
}
moveUp = function() {
if (this.canMove) {
this.y -= this.velocity;
}
}
moveDown = function() {
if (this.canMove) {
this.y = this.velocity;
}
}
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>