onlinecodesimulator/robot.js

55 lines
1.4 KiB
JavaScript

export class Robot {
constructor(id, x, y, color = "blue") {
this.id = id;
this.x = x;
this.y = y;
this.velocity = 0;
this.direction = 0; // Degrees
this.width = 20;
this.height = 20;
this.color = color;
}
update(ctx){
this.update_position();
this.draw(ctx);
}
update_position() {
const radians = (this.direction * Math.PI) / 180;
this.x += Math.cos(radians) * this.velocity;
this.y += Math.sin(radians) * this.velocity;
}
move(velocity) {
this.velocity = velocity;
}
turn(degrees) {
this.direction += degrees;
}
draw(ctx) {
ctx.fillStyle = this.color;
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate((this.direction * Math.PI) / 180);
// Draw the rectangle (tank body)
ctx.fillRect(-this.width / 2, -this.height / 2, this.width, this.height);
// Draw the triangle (direction indicator)
ctx.beginPath();
ctx.moveTo(this.width / 2, -this.height / 2); // Tip of the triangle (front)
ctx.lineTo(this.width, 0); // Bottom left of triangle
ctx.lineTo(this.width / 2, this.height / 2); // Bottom right of triangle
ctx.closePath();
ctx.fill(); // Fill both the rectangle and the triangle
ctx.restore();
}
}