Hey guys,
Im making a raycasting engine.
If you dont know what that is
http://www.permadi.com/tutorial/raycast/index.htmlThis is an awesome tutorial i would recommend you read. However if you do know what im talking about im having a problem with making one.
It seems that the edges of my walls extend a bit farther than they should. creating a odd clipping effect on the cubes.
Heres the code.
Code:int[][] wall = new int[300][300];
float[] ray = new float[641];
boolean[] keys = new boolean[4];
final int up = 0;
final int down = 1;
final int left = 2;
final int right = 3;
float px=50,py=200,pa;
float xa,ya,oldxa,oldya;
float xc,yc,rd;
int rn;
void setup(){
size(640,400);
smooth();
wall[3][2]=1;
wall[5][5]=1;
wall[6][5]=1;
wall[7][5]=1;
wall[8][5]=1;
wall[15][15]=1;
}
void draw(){
noStroke();
fill(255);
rect(0,0,width,height/2);
fill(50);
rect(0,height/2,width,height/2);
stroke(100);
raydist();
render();
controls();
}
void raydist(){
rn=0;
for(float r=-PI/6;r<PI/6;r=r+(PI/3)/640){
ray[rn]=-1;
//HORIZ
if(sin(pa+r)<0){
ya=floor(py/64)*64-1;
xc=64/tan(-(pa+r));
yc=-64;
}
else{
ya=floor(py/64)*64+64;
xc=64/tan(pa+r);
yc=64;
}
xa=px+((py-ya)/tan(-(pa+r)));
oldxa=xa;
oldya=ya;
for(int i=0;i<6;i++){
if(xa>0 &&xa<640){
if(ya>0 &&ya<640){
if(wall[floor(xa/64)][floor(ya/64)]==1){
rd=sqrt(sq(xa-px)+sq(ya-py));
if(ray[rn]==-1){
ray[rn]=rd*cos(r);
}
else{
if(rd<ray[rn]/cos(r)){
ray[rn]=rd*cos(r);
}
}
}
}
}
xa=oldxa+xc;
ya=oldya+yc;
oldxa=xa;
oldya=ya;
}
//VERT
if(sin(pa+PI/2+r)<0){
xa=floor(px/64)*64-1;
yc=64*tan(-(pa+r));
xc=-64;
}
else{
xa=floor(px/64)*64+64;
yc=64*tan(pa+r);
xc=64;
}
ya=py+((px-xa)/tan(pa+PI/2+r));
oldxa=xa;
oldya=ya;
for(int i=0;i<6;i++){
if(xa>0 &&xa<640){
if(ya>0 &&ya<640){
if(wall[floor(xa/64)][floor(ya/64)]==1){
rd=sqrt(sq(xa-px)+sq(ya-py));
if(ray[rn]==-1){
ray[rn]=rd*cos(r);
}
else{
if(rd<ray[rn]/cos(r)){
ray[rn]=rd*cos(r);
}
}
}
}
}
xa=oldxa+xc;
ya=oldya+yc;
oldxa=xa;
oldya=ya;
}
rn++;
}
}
void render(){
for(int rn=0;rn<640;rn++){
if(ray[rn]>0){
float wh=64/ray[rn]*255;
stroke(150);
line(rn,height/2+wh,rn,height/2-wh);
}
}
}
void controls(){
if(keys[up]==true){
px=px+cos(pa);
py=py+sin(pa);
}
if(keys[down]==true){
px=px-cos(pa);
py=py-sin(pa);
}
if(keys[left]==true){
pa-=.1;
}
if(keys[right]==true){
pa+=.1;
}
}
void keyPressed() {
if (keyCode == UP) {
keys[up] = true;
}
else if(keyCode == DOWN) {
keys[down] = true;
}
else if(keyCode == LEFT) {
keys[left] = true;
}
else if (keyCode == RIGHT) {
keys[right] = true;
}
}
void keyReleased() {
if (keyCode == UP) {
keys[up] = false;
}
else if(keyCode == DOWN) {
keys[down] = false;
}
else if(keyCode == LEFT) {
keys[left] = false;
}
else if (keyCode == RIGHT) {
keys[right] = false;
}
}
If anyone knows what im doing wrong it would be greatly appreciated.
Thanks in advance!
-Dev