82 lines
2.2 KiB
JavaScript
82 lines
2.2 KiB
JavaScript
|
class Player {
|
||
|
constructor(position) {
|
||
|
this.position = position;
|
||
|
this.rays = [];
|
||
|
this.distances = [];
|
||
|
this.fov = 90;
|
||
|
this.angle = 0;
|
||
|
|
||
|
}
|
||
|
|
||
|
|
||
|
show() {
|
||
|
fill(100);
|
||
|
noStroke();
|
||
|
ellipse(this.position.x, this.position.y, 10);
|
||
|
}
|
||
|
|
||
|
update() {
|
||
|
const sight = sightSlider.value() * 10;
|
||
|
const fov = fovSlider.value();
|
||
|
const rotationSpeed = rotationSpeedSlider.value();
|
||
|
const velocity = velocitySlider.value();
|
||
|
if (keyIsDown(LEFT_ARROW)) {
|
||
|
this.angle -= rotationSpeed;
|
||
|
}
|
||
|
|
||
|
if (keyIsDown(RIGHT_ARROW)) {
|
||
|
this.angle += rotationSpeed;
|
||
|
}
|
||
|
if (keyIsDown(UP_ARROW)) {
|
||
|
this.position = angleToVector(this.position.x, this.position.y, this.angle, velocity);
|
||
|
}
|
||
|
|
||
|
if (keyIsDown(DOWN_ARROW)) {
|
||
|
this.position = angleToVector(this.position.x, this.position.y, this.angle, -velocity);
|
||
|
}
|
||
|
|
||
|
this.rays = [];
|
||
|
for (let i = 0 - floor(fov / 2); i < floor(fov / 2); i=i+0.5) {
|
||
|
this.rays.push(new Ray(this.position.x, this.position.y, radians(i + this.angle), sight));
|
||
|
}
|
||
|
|
||
|
for (let r of this.rays) {
|
||
|
for (let w of walls) {
|
||
|
r.cast(w);
|
||
|
}
|
||
|
r.show();
|
||
|
}
|
||
|
this.distances = [];
|
||
|
for(let i = 0; i<this.rays.length; i++){
|
||
|
this.distances[i] = this.rays[i].cast();
|
||
|
}
|
||
|
display(this.distances);
|
||
|
}
|
||
|
|
||
|
}
|
||
|
|
||
|
function angleToVector(xCoord, yCoord, angle, length) {
|
||
|
length = typeof length != 'undefined' ? length : 10;
|
||
|
angle = angle * Math.PI / 180; // if you're using degrees instead of radians
|
||
|
return createVector(length * Math.cos(angle) + xCoord, length * Math.sin(angle) + yCoord);
|
||
|
}
|
||
|
|
||
|
|
||
|
function display(distances) {
|
||
|
let c = color(0, 0, 0)
|
||
|
fill(c);
|
||
|
rect(961,0,960,850);
|
||
|
fill(200);
|
||
|
stroke(200);
|
||
|
let length = distances.length;
|
||
|
let width = ceil(960/length);
|
||
|
for(let i = 0; i<length; i++){
|
||
|
if(distances[i]){
|
||
|
let height = 100000 * (1/distances[i]);
|
||
|
c = color(map(1/distances[i],0,0.01,0,255));
|
||
|
fill(c);
|
||
|
noStroke();
|
||
|
rect(960 + width*i, 430 - height/2,width,height);
|
||
|
}
|
||
|
}
|
||
|
}
|