We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Rotating an image when key pressed
Page Index Toggle Pages: 1
Rotating an image when key pressed (Read 430 times)
Rotating an image when key pressed
Jul 22nd, 2009, 11:49am
 
Hello!  I am trying to make a game where the keyboard arrows controls the movement of a car across the screen.  However, I would like the car to point the way it is going.  I have tried to redefine the car image variable with a different image file, but that hasn't worked.  I also don't see anything in the Reference about rotating an image, just 2D graphics.  Any advice would be really appreciated!
Re: Rotating an image when key pressed
Reply #1 - Jul 22nd, 2009, 12:18pm
 
The rotate() function works the same way for images as it does for graphics. So just define a variable for rotation, then when an arrow key is hit, increase or decrease this value. Here's an example of what to do:

Code:

int angle; //the rotation variable
PImage img;

void setup(){
 size(200, 200);
 imageMode(CENTER);
 img = loadImage("YOUR_IMAGE");
 angle = 0;
}

void draw(){
 background(255);
 pushMatrix(); //push Matrix so we can rotate
 translate(width/2, height/2); //translate to where you want it
 rotate(radians(angle)); //rotate the image
 image(img, 0, 0); //draw at 0, 0 since we translated
 popMatrix(); //don't forget to pop the matrix
}

void keyPressed(){
 if(keyCode == 37){ //arrows are coded so you can't call "key"
   rot--; //left arrow rotates one way
 } else if(keyCode == 39){
   rot++; //right arrow rotates the other way
 }
}

Hope that helps!  Smiley
Page Index Toggle Pages: 1