xxxxxxxxxx
110
let FOV = Math.PI / 2;
let HALF_FOV = FOV / 2;
let MAG = 100;
class Player {
constructor(pos) {
this.pos = pos;
this.speed = 0.25;
this.angle = 0;
}
draw() {
fill(color(255,255,255))
circle(this.pos.x, this.pos.y, 20);
this.drawFov();
}
getAngleFov() {
return createVector(this.pos.x + cos(this.angle) * MAG, this.pos.y + sin(this.angle) * MAG);
}
drawFov() {
let des = this.getAngleFov();
line(this.pos.x, this.pos.y, des.x, des.y)
let halfLeft = createVector(this.pos.x + cos(this.angle - HALF_FOV) * 100, this.pos.y + sin(this.angle - HALF_FOV) * 100)
line(this.pos.x, this.pos.y, halfLeft.x, halfLeft.y)
let halfRight = createVector(this.pos.x + cos(this.angle + HALF_FOV) * 100, this.pos.y + sin(this.angle + HALF_FOV) * 100)
line(this.pos.x, this.pos.y, halfRight.x, halfRight.y)
}
}
class Obstacle {
constructor(pos) {
this.pos = pos;
}
draw() {
circle(this.pos.x, this.pos.y, 20)
}
}
var player;
var obstacles = [];
function setup() {
createCanvas(400, 400);
player = new Player(createVector(width / 2, height / 2))
obstacles.push(new Obstacle(createVector(width / 4, height / 4)));
obstacles.push(new Obstacle(createVector(width - width / 4, height - height / 4)));
}
function draw() {
background(220);
movePlayer();
player.draw();
for(let i = 0; i < obstacles.length; i++) {
if (isInsideFov(player.pos, player.getAngleFov(), obstacles[i].pos)) {
fill(color(255,0,0))
} else {
fill(color(255,255,0))
}
obstacles[i].draw()
}
}
function isInsideFov(origin, view, target) {
let targetDistance = p5.Vector.sub(target, origin)
let viewDistance = p5.Vector.sub(view, origin)
let dotProduct = p5.Vector.dot(targetDistance, viewDistance)
let totalMag = targetDistance.mag() * viewDistance.mag();
let result = dotProduct / totalMag;
let angleInRad = acos(result);
if (angleInRad < HALF_FOV && targetDistance.mag() < MAG) {
return true;
}
return false;
}
function movePlayer() {
let dx = 0, dy = 0;
if (keyIsDown(UP_ARROW)) {
dy = +sin(player.angle) * (player.speed * deltaTime);
dx = +cos(player.angle) * (player.speed * deltaTime);
}
if (keyIsDown(DOWN_ARROW)) {
dy = -sin(player.angle) * (player.speed * deltaTime);
dx = -cos(player.angle) * (player.speed * deltaTime);
}
if (keyIsDown(LEFT_ARROW)) {
player.angle -= 0.01 * (player.speed * deltaTime);
}
if (keyIsDown(RIGHT_ARROW)) {
player.angle += 0.01 * (player.speed * deltaTime)
}
player.pos.x += dx;
player.pos.y += dy
}