Class player
Player class with méthods
by DupontTD
HTML
<p>
player 1 : move "q,z,d,x" player 2 : key arrows
</p>
<session></session>
CSS
session {
position: absolute;
top: 20px;
left: 50px;
width: 180px;
height: 120px;
border: solid 5px;
z-index: -1;
}
div {
position: absolute;
width: 20px;
height: 20px;
border: solid 1px;
border-radius: 10px;
z-index: 1;
}
.outZone {
border-radius: 1px;
}
.inZone {
background-color: teal;
}
.yellow {
background-color: yellow;
}
.blue {
background-color: blue;
}
JavaScript
class Player {
constructor({
keysMap,
x,
y,
speed
}) {
Object.assign(this, {
keysMap,
x,
y,
speed
});
this.moveX = 0;
this.moveY = 0;
this._node = Player.drawn();
}
handleInput(keyPressed) {
console.log("handleinput key = " + keyPressed);
// don't move with bad key touch
if (!this.keysMap.has(keyPressed)) {
console.log(" pas la clef" + this.keysMap.has(keyPressed))
return;
}
// not finish first move, please wait !
if (this.moveX !== 0 || this.moveY !== 0) {
console.log("bug if long, take care of this.speed mod 5, this.speed = 3 not work");
return;
}
// use virtual key (up,down ...)
let key = this.keysMap.get(keyPressed);
// don't let player go off zonescreen.
if (this.x > 200 && key === 'right') {
this._node.classList.remove("inZone");
this._node.classList.add("outZone");
return;
}
if (this.x < 50 && key === 'left') {
this._node.classList.remove("inZone");
this._node.classList.add("outZone");
return;
}
if (this.y < 50 && key === 'up') {
this._node.classList.remove("inZone");
this._node.classList.add("outZone");
return;
}
if (this.y > 100 && key === 'down') {
this._node.classList.remove("inZone");
this._node.classList.add("outZone");
return;
}
this._node.classList.remove("outZone");
this._node.classList.add("inZone");
const k = 40; // test new value;
// set player movement variables
if (key === 'up') {
this.moveY -= k;
return
}
if (key === 'down') {
this.moveY += k;
return
}
if (key === 'left') {
this.moveX -= k;
return
}
if (key === 'right') {
this.moveX += k;
return
}
}
update(dt) {
//console.log(dt);
if (this.moveX > 0) {
this.x += this.speed;
this.moveX -= this.speed;
}
if...