Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int windowWidth = 800;
- int windowHeight = 800;
- Camera camera = new Camera();
- void settings(){
- size(windowWidth, windowHeight);
- }
- void setup(){
- colorMode(HSB, 360, 255, 255);
- frameRate(60);
- }
- void draw(){
- background(10);
- pushMatrix();
- translate(camera.offset.x, camera.offset.y);
- scale(camera.zoom);
- // Draw a grid centered on the world origin
- drawGrid();
- // Draw a circle at the world origin
- fill(200);
- circle(0, 0, 50);
- // Draw a circle at the mouse's position in world space
- PVector sMouse = camera.GetScreenToWorld(new PVector(mouseX, mouseY));
- fill(255);
- circle(sMouse.x, sMouse.y, 50);
- popMatrix();
- stroke(255);
- text("offset: "+camera.offset, 10,10);
- text("wMouse: "+camera.GetScreenToWorld(new PVector(mouseX, mouseY)), 10,20);
- text("worldOriginToScreen: "+camera.GetWorldToScreen(new PVector(0,0)), 10, 30);
- }
- class Camera{
- PVector target = new PVector(0,0); // Not implemented
- PVector offset = new PVector(0,0);
- float zoom = 1.0;
- Camera(){
- offset = GetScreenToWorld(new PVector(windowWidth/2,windowHeight/2));
- }
- PVector GetWorldToScreen(PVector world){
- PVector screen = world.copy();
- screen.add(offset);
- screen.div(zoom);
- return screen;
- }
- PVector GetScreenToWorld(PVector screen){
- PVector world = screen.copy();
- world.sub(offset);
- world.mult(1/zoom);
- return world;
- }
- }
- void mouseDragged(){
- camera.offset.add(GetMouseDelta());
- }
- void mouseWheel(MouseEvent event){
- float mouseWheel = event.getCount();
- PVector zDelta = camera.GetScreenToWorld(new PVector(mouseX, mouseY));
- camera.zoom -= mouseWheel * (camera.zoom / 5);
- zDelta.sub(camera.GetScreenToWorld(new PVector(mouseX, mouseY)));
- zDelta.mult(camera.zoom);
- camera.offset.sub(zDelta);
- }
- PVector GetMouseDelta(){
- return new PVector(mouseX - pmouseX, mouseY - pmouseY);
- }
- void drawGrid(){
- int lines = 10;
- float s = 100;
- stroke(150);
- for(int i = -lines; i <= lines; ++i){
- if(i == 0) strokeWeight(4); else strokeWeight(1);
- line(-s*lines, i*s, s*lines, i*s);
- line(i*s,-s*lines, i*s, s*lines);
- }
- }
Add Comment
Please, Sign In to add comment