Scrolling / Camera

The whole world drawing can be wrapped in a transform matrix to simulate a “camera” following certain coordinates

...
world.step();
  background(0);
 
  pushMatrix();
 
  //translate based on the protagonist position and offset to the center of the screen
  float tx = -protagonist.getX()*zoom+width/2;
  float ty = -protagonist.getY()*zoom+height/2;
 
  translate(tx, ty);
  scale(zoom);
 
  world.draw();
  popMatrix();
...

Full example:

 
import fisica.*;
 
FWorld world;
 
FCircle protagonist;
 
float SPEED = 100;
 
float zoom = 2; //200% bigger
 
//this is for the keyboard state detection - leave it here
boolean[] keys = new boolean[526];
 
 
void setup() {
  //sketch size
  size(800, 600);
 
  //initialize the library
  Fisica.init(this);
 
  //create a new Fisica world
  world = new FWorld();
 
  //for this example we are disabling the grab
  world.setGrabbable(false);
 
  //no gravity
  world.setGravity(0, 0);
 
  protagonist = new FCircle(20);
  protagonist.setNoStroke();
  protagonist.setPosition(width/2, height/2);
  protagonist.setDamping(10);
  world.add(protagonist);
 
  for (int i = 0; i< 10; i++)
  {
    FBox box = new FBox(20, 20);
    box.setPosition(random(width), random(height));
    world.add(box);
  }
}
 
 
void draw() {
  world.step();
  background(0);
 
  pushMatrix();
 
  //translate based on the protagonist position and offset to the center of the screen
  float tx = -protagonist.getX()*zoom+width/2;
  float ty = -protagonist.getY()*zoom+height/2;
 
  translate(tx, ty);
  scale(zoom);
 
  world.draw();
  popMatrix();
 
  //normal coordinates are restored for interface overlays etc
 
  if (keyIsDown(RIGHT)) {
    protagonist.adjustVelocity(SPEED, 0);
  }
 
  if (keyIsDown(LEFT)) {
    protagonist.adjustVelocity(-SPEED, 0);
  }
 
  if (keyIsDown(DOWN)) {
    protagonist.adjustVelocity(0, SPEED);
  }
 
  if (keyIsDown(UP)) {
    protagonist.adjustVelocity(0, -SPEED);
  }
}
 
//this function is called when a key is pressed
void keyPressed() {
 
  //update the state in the array
  keys[keyCode] = true;
}
 
//this function is called when a key is released
void keyReleased() {
  println("The key "+ key+ " just went up");
 
  //update the state in the array
  keys[keyCode] = false;
}
 
//This may be a little exotic, just leave it there
boolean keyIsDown(char c) { 
  String s = c + "";
  return keyIsDown(int(s.toUpperCase().charAt(0)));
}
boolean keyIsDown(String s) { 
  return keyIsDown(int(s.toUpperCase().charAt(0)));
}
boolean keyIsDown(int code) { 
  if (keys.length >= code) { 
    return keys[code];
  } 
  return false;
}
Posted in

Post a comment