topical media & game development

talk show tell print

#page-snake-color.pde / pde



  /*Processing.js
  Snake
  A snake that follows your cursor.
  
  RIP: moving as in snake
  Snake
  
  Sebas E. first steps in processing
  */
  float positionX =250;
  float positionY =250;
  float px=100;
  float py=200;
  
  float[] x = new float[20];
  float[] y = new float[20];
  float segLength = 10;
  
  void setup() {
    size(500, 500);
    smooth();
     background(20,20);
  }
  
  void draw() {
   
    //image( loadImage("dirt.jpg"), 0, 0 );
    dragSegment(0, positionX ,positionY);
    for(int i=0; i < x.length-1; i++) {
      dragSegment(i+1, x[i], y[i]);
    }
    //set new position
    positionX = (positionX + 0.1*px);
    positionY= (positionY + 0.1*py);
   
   
   if((positionX<=0 && px<0) || (positionX>=width && px>0)){px *=-1;}
   if(positionY>=height && py>0){py *=-1.001; background(random
  (255),random(255),random(255),20);} // AE: transp adapted 
   if(positionY<=0 && py <0){py *=-1;}
   
   py +=7;
   
   constrain(positionX,0,width);
   constrain(positionY,0,height);
  }
  
  //push and pause
  void keyPressed(){
    if(key == 'd'){ px += 5;}
    if(key == 'a'){  px += -5;}
    if(key == 's'){  py=1;}
    if(key == 'w'){  py=-1;}
    if(key == 'p'){px = 0; py=0;}
  }
  
  void dragSegment(int i, float xin, float yin) {
    float dx = xin - x[i];
    float dy = yin - y[i];
    float angle = atan2(dy, dx);  
    x[i] = xin - cos(angle) * segLength;
    y[i] = yin - sin(angle) * segLength;
    //stroke(23, 79, 4, 220);
    
  
    pushMatrix();
    translate(x[i], y[i]);
    rotate(angle);
    
    color c;
    
    if ( i % 3 == 1 )
      c = color(0, 0, 0, 255);
    else if ( i % 3 == 2 )
      c = color(255, 255, 0, 255);
    else
      c = color(255, 0, 0, 255);
  
    stroke( c );
    strokeWeight(10);
    line(0, 0, segLength, 0);
    
    if ( i == x.length - 1 )
    {
      fill( c );
      noStroke();
      beginShape(TRIANGLES);
      vertex(0, 5);
      vertex(-2 * segLength, 0);
      vertex(0, -5);
      endShape();
    }
    
    if ( i == 0 )
    {
     // stroke(0, 255);
     noStroke();
     fill(0, 255);
     ellipse(segLength, -2, 3, 3);
     ellipse(segLength, 2, 3, 3);
      //point(segLength, -2);
      //point(segLength, 2);
    }
    
    popMatrix();
  }
  


(C) Æliens 20/2/2008

You may not copy or print any of this material without explicit permission of the author or the publisher. In case of other copyright issues, contact the author.