Help with math for translating mouse coordinates?

edited August 2018 in Questions about Code

This is a very simplified program showing my problem. I need to draw to an image that is rotated. I can't use any of processing's line or point functions because of different type brushes in the real program. I have to draw directly to the pixel data. This program plots 4 black pixels under the mouse when its pressed. It works fine on the image that isn't rotated , but I need to know how to translate the x and y position so it works when the image is rotated. Here's the simple program: I also posted this on the new forum. I don't know which forum is seeing the most users.

PImage img;
float rotation = 0.0;
final float deg45 = 45 * PI /180;

void setup(){
     size(800,800);
     img = createImage(800,800,ARGB);
     img.loadPixels();
     for (int i=0; i < img.pixels.length;i++){
          img.pixels[i] = 0xFFFFFFFF;
     }
     img.updatePixels();
}
void draw(){
     background(0);
     if(rotation != 0.0){     
          pushMatrix();
          translate(img.width/2,img.height/2);
          rotate(rotation);
          translate(-img.width/2,-img.height/2);
     }
     int mx = mouseX;
     int my = mouseY;
     if(mousePressed){
          blot(mx,my);          
     }
     image(img,0,0);
     if(rotation != 0.0)     
          popMatrix();
}
void blot(int x,int y){
     img.loadPixels();
     img.pixels[y * img.width + x] = 0xFF000000;
     img.pixels[y * img.width + x+1] = 0xFF000000;
     img.pixels[y * img.width + img.width + x] = 0xFF000000;
     img.pixels[y * img.width + img.width + x+1] = 0xFF000000;
     img.updatePixels();
}
void keyPressed(){
     if(key == ' '){
          if(rotation == deg45)
               rotation = 0.0;
          else rotation = deg45;
     }
     else if ( key == 'c'){
          img.loadPixels();
          for (int i=0; i < img.pixels.length;i++){
               img.pixels[i] = 0xFFFFFFFF;
          }
          img.updatePixels();          
     }

}

Answers

  • Let‘s stick with the new forum- much more traffic than here

  • edited August 2018 Answer ✓

    I will, thanks. I found the answer at https://homepages.inf.ed.ac.uk/rbf/HIPR2/rotate.htm

    To get the translated mouse positions (rotation is in radians):
    mx = (int)(cos(-rotation) * (mouseX -img.width/2) -  sin(-rotation) * (mouseY-img.height/2) + img.width/2);
    my = (int)( sin(-rotation) * (mouseX-img.width/2) + cos(-rotation) * (mouseY - img.height/2) + img.height/2);
    
Sign In or Register to comment.