So im trying to write a 2d raycaster for the first time, and im having trouble only drawing lines to the closest walls. i cant find what to do next
Code:
Source source;
Ray ray;
Wall[] walls = new Wall[2];
void setup() {
size(600, 600);
frameRate(60);
source = new Source(new PVector(width/2, height/2));
walls[0] = new Wall(100, 400, 100, 500);
walls[1] = new Wall(50, 500, 20, 300);
}
void draw() {
background(0);
source.show();
for (int i = 0; i < walls.length; i++) {
walls[i].show();
}
//Controls
noCursor();
source.pos = new PVector(mouseX, mouseY);
}
Ray class:
class Ray {
PVector pos;
PVector dir;
PVector pt;
boolean ptExist = false;
Ray (PVector setpos, float angle) {
pos = setpos;
dir = PVector.fromAngle(angle);
}
void show() {
stroke(255);
push();
translate(pos.x, pos.y);
line(0, 0, dir.x * 10, dir.y * 10);
pop();
update();
}
void update() {
pos= source.pos;
}
void setDir(float x, float y) {
dir.x = x - pos.x;
dir.y = y - pos.y;
dir.normalize();
}
void cast(int wall) {
float x1 = walls[wall].a.x;
float y1 = walls[wall].a.y;
float x2 = walls[wall].b.x;
float y2 = walls[wall].b.y;
float x3 = pos.x;
float y3 = pos.y;
float x4 = pos.x+dir.x;
float y4 = pos.y+dir.y;
float den = (x1-x2) * (y3-y4) - (y1-y2) * (x3-x4);
if (den == 0) {
return;
}
float t = ((x1-x3) * (y3-y4) - (y1-y3) * (x3-x4)) / den;
float u = -((x1-x2) * (y1-y3) - (y1-y2) * (x1-x3)) / den;
if (t > 0 && t < 1 && u > 0) {
pt = new PVector();
pt.x = x1 + t * (x2-x1);
pt.y = y1 + t * (y2-y1);
ptExist = true;
} else {
ptExist = false;
}
}
}
Source class:
class Source {
PVector pos;
PVector closest = new PVector(0, 0);
float record;
float heading;
float fov;
int i=0;
Ray[] rays = new Ray[360];
Source(PVector setpos) {
pos = setpos;
heading = 0;
fov = 45;
for (float a=0; a < 360; a+=1) {
rays[i] = new Ray(pos, radians(a));
i++;
}
}
void look() {
for (int i=0; i<rays.length; i++) {
for (int j = 0; j < walls.length; j++) {
for (int k=0; k<walls.length; k++) {
record = 10000000;
rays[i].cast(j);
PVector pt = rays[i].pt;
if (rays[i].ptExist) {
float d = PVector.dist(pos, pt);
if (d < record) {
record = d;
closest = pt;
record = min(d, record);
}
}
}
}
if (closest.x!=0&&closest.y!=0) {
line(pos.x, pos.y, closest.x, closest.y);
}
}
}
void show() {
fill(255);
noStroke();
ellipse(pos.x, pos.y, 4, 4);
for (int i=0; i<rays.length; i++) {
rays[i].show();
}
look();
}
}
Wall class:
class Wall {
PVector a;
PVector b;
Wall(float x1, float y1, float x2, float y2) {
a = new PVector(x1, y1);
b = new PVector(x2, y2);
}
void show() {
stroke(255);
line(a.x, a.y, b.x, b.y);
}
}