Munashedov

Camera

Dec 18th, 2021
272
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.16 KB | None | 0 0
  1. int windowWidth = 800;
  2. int windowHeight = 800;
  3. Camera camera = new Camera();
  4.  
  5. void settings(){
  6.   size(windowWidth, windowHeight);
  7. }
  8.  
  9. void setup(){
  10.   colorMode(HSB, 360, 255, 255);
  11.   frameRate(60);
  12. }
  13.  
  14. void draw(){
  15.   background(10);
  16.  
  17.   pushMatrix();
  18.   translate(camera.offset.x, camera.offset.y);
  19.   scale(camera.zoom);
  20.  
  21.   // Draw a grid centered on the world origin
  22.   drawGrid();
  23.  
  24.  
  25.   // Draw a circle at the world origin
  26.   fill(200);
  27.   circle(0, 0, 50);
  28.  
  29.   // Draw a circle at the mouse's position in world space
  30.   PVector sMouse = camera.GetScreenToWorld(new PVector(mouseX, mouseY));
  31.   fill(255);
  32.   circle(sMouse.x, sMouse.y, 50);
  33.  
  34.   popMatrix();
  35.  
  36.   stroke(255);
  37.   text("offset: "+camera.offset, 10,10);
  38.   text("wMouse: "+camera.GetScreenToWorld(new PVector(mouseX, mouseY)), 10,20);
  39.   text("worldOriginToScreen: "+camera.GetWorldToScreen(new PVector(0,0)), 10, 30);
  40. }
  41.  
  42. class Camera{
  43.   PVector target = new PVector(0,0); // Not implemented
  44.   PVector offset = new PVector(0,0);
  45.   float zoom = 1.0;
  46.  
  47.   Camera(){
  48.     offset = GetScreenToWorld(new PVector(windowWidth/2,windowHeight/2));
  49.   }
  50.  
  51.   PVector GetWorldToScreen(PVector world){
  52.     PVector screen = world.copy();
  53.     screen.add(offset);
  54.     screen.div(zoom);
  55.     return screen;
  56.   }
  57.   PVector GetScreenToWorld(PVector screen){
  58.     PVector world = screen.copy();
  59.     world.sub(offset);
  60.     world.mult(1/zoom);
  61.     return world;
  62.   }
  63. }
  64.  
  65. void mouseDragged(){
  66.   camera.offset.add(GetMouseDelta());
  67. }
  68.  
  69. void mouseWheel(MouseEvent event){
  70.   float mouseWheel = event.getCount();
  71.  
  72.   PVector zDelta = camera.GetScreenToWorld(new PVector(mouseX, mouseY));
  73.  
  74.   camera.zoom -= mouseWheel * (camera.zoom / 5);
  75.  
  76.   zDelta.sub(camera.GetScreenToWorld(new PVector(mouseX, mouseY)));
  77.   zDelta.mult(camera.zoom);
  78.   camera.offset.sub(zDelta);
  79. }
  80.  
  81. PVector GetMouseDelta(){
  82.   return new PVector(mouseX - pmouseX, mouseY - pmouseY);
  83. }
  84.  
  85. void drawGrid(){
  86.   int lines = 10;
  87.   float s = 100;
  88.   stroke(150);
  89.   for(int i = -lines; i <= lines; ++i){
  90.     if(i == 0) strokeWeight(4); else strokeWeight(1);
  91.     line(-s*lines, i*s, s*lines, i*s);
  92.     line(i*s,-s*lines, i*s, s*lines);
  93.   }
  94. }
Add Comment
Please, Sign In to add comment