how to rotate images with a mouse

edited December 2017 in Questions about Code

I can't figure out how to make images rotate with a mouse. Here is the code I have for generating random leaves. But I want to be able to also rotate the leaves with a mouse or key.

PImage a1;

int x1=1; int y1=1; int front;

boolean a1IsSet= false;

void setup() { size(600, 400); frameRate(9); background(255,255,255); }

void draw() {

front = int(random(1,5));

if (a1IsSet) image (a1, x1, y1 ); }

void mousePressed() {

if (mousePressed ) {

 float angle = atan2(mouseY, mouseX );

pushMatrix(); rotate(angle); PImage imgFront = loadImage(front + "leaf.jpg"); image(imgFront, mouseX-150, mouseY-200); popMatrix(); } }

Tagged:

Answers

  • edited December 2017

    Some major issues I see...

    1) Don't load your images anywhere except in setup(). You only need to load them once when the sketch starts, not every time the mouse is pressed!

    2) Inside your mousePressed() function, the mousePressed boolean is always true - checking for this with an if statement is thus redundant.

    3) Do all your drawing inside draw() - you can set values for global variables in mousePressed(), sure, but using them to determine what to draw should happen in draw().

    4) You seem to have posted twice about this same topic. Whoops! At least this post has the code you're talking about.

    5) Your code isn't formatted for the forums. Did you read the stuck discussion about how to format your code?

    6) I'm not sure if you need a frameRate() call.

  • edited December 2017 Answer ✓

    7) Ah, I see. You have many images. You should load them into an ARRAY.

    PImage[] images;
    
    void setup() { 
      size(600, 400);
      for( int i = 1; i < 5; i++){
        images[i] = loadImage( i + "leaf.jpg" );
      }
      background(255);
    }
    
    void draw() {
      image( images[int(random(1,5))], mouseX-150, mouseY-200 );
    }
    
  • where can I read about how to format my code?

  • this belongs before setup ():

    float angle ;

    in mousePressed say angle=..... without float

    do all the drawing in draw () and use angles there

  • I used angles in draw and it said NullPointerException

  • angle?

    Did you do as I said?

  • I loaded images into an array, but now its saying NullPointerException

  • I copied the code in the box and it said NullPointerException

  • Thank you for your help! I added more to the code and the array works now.

Sign In or Register to comment.