xxxxxxxxxx
71
let player;
let pressedKey = {};
function setup() {
createCanvas(512, 512);
rectMode(CENTER);
player = new Player(width / 2, height / 2);
}
function draw() {
background(255);
player.show();
player.movement();
}
class Player {
constructor(x, y) {
this.pos = createVector(x, y);
this.vel = createVector(0, 0);
this.speed = 1;
this.theta = 0;
this.r = 10;
}
show() {
fill(255, 0, 0);
noStroke();
push();
translate(this.pos.x, this.pos.y);
this.theta = this.vel.heading();
rotate(this.theta);
triangle(-this.r, -this.r/2, -this.r, this.r/2, this.r, 0);
pop();
}
movement() {
if (pressedKey.a) {
this.vel.x -= 0.01 * deltaTime;
this.pos.add(this.vel)
}
if (pressedKey.d) {
this.vel.x += 0.01 * deltaTime;
this.pos.add(this.vel)
}
if (pressedKey.w) {
this.vel.y -= 0.01 * deltaTime;
this.pos.add(this.vel)
}
if (pressedKey.s) {
this.vel.y += 0.01 * deltaTime;
this.pos.add(this.vel)
}
this.vel.setMag(this.speed);
this.vel.normalize();
}
}
function keyPressed() {
pressedKey[key] = true;
}
function keyReleased() {
delete pressedKey[key];
}