Infinite Terrain in Processing

Wrote some optimized code to generate infinite land(?) in both the direction. Here’s the code and a sneak peak into how the project looks so far.
Uses standard keys[UP,DOWN,LEFT,RIGHT] for navigation as of now. Will try to map that to an android phone using an arduino in the future.

import processing.opengl.*;

int lookX=0,lookY=-100,lookZ=0;
int camX=0,camY=-200,camZ=-200; 

void setup(){
  size(640,480,OPENGL);  
}

void draw(){
  background(255);
  camera(camX,camY,camZ, lookX,lookY,lookZ, 0,1,0);

  float x=calculateCenter(camX);
  float z=calculateCenter(camZ);


  for(int j=-7;j<=7;j++){
    for(int i=-7;i<=7;i++){
      pushMatrix();    
      translate(i*100+x,0,j*100+z);
//      drawAxes();
      drawBox();  
      popMatrix();  
    } 
  }
println("camX = "+camX+"x = "+x+ " camZ = "+ camZ +" z = "+z );  
}

void drawBox(){
  strokeWeight(4);
  stroke(230,226,175);
  fill(4,99,128);
  box(60,10,60);
}

void drawAxes(){
  stroke(255,0,0);
  line(-100,0,0, 100,0,0);
  stroke(0,255,0);
  line(0,-100,0, 0,100,0);
  stroke(0,0,255);
  line(0,0,-100, 0,0,100);
}

void keyPressed(){
  if(key==CODED){
    if(keyCode==UP){
      lookZ+=10;
      camZ+=10;
    }
    if(keyCode==DOWN){
      lookZ-=10;
      camZ-=10;
    }
    if(keyCode==LEFT){
      camX+=10;
      lookX+=10;
    }
    if(keyCode==RIGHT){
      camX-=10;
      lookX-=10;
    }    
  }
  if(key==' '){
    lookY-=10;
    camY-=10;
  }
}

float calculateCenter(int input){
  /*Calculates the center point of the region.*/  
  if((input<=0 && input>-100)||(input>=0 && input<100)){
    return 0;
  }
  String a=""+input;
  String b=""+ a.charAt(a.length()-2)+a.charAt(a.length()-1);
  int c=int(b);
  if(input>0){
    return input-c;
  }
  else{
    return input+c;
  }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s