Reputation: 45
I'm trying to make a rotating image move with mouseX and mouseY and interact with key-commands: When the left or right arrow keys are pressed, the images should alternate between each other; the up arrow increases the rotation speed, while the down arrow should decrease rotation speed.
Applied some edits based on responses, but nothing displays when I run the code.
Amended code listed below:
var angle = 0.0;
var angleSpeed = 0.0;
var imageSwitcher = 0;
var images = [];
var img1;
var img2;
var img3;
function preload() {
images[0] = loadImage(image1);
images[1] = loadImage(image2);
images[2] = loadImage(image3);
function setup() {
createCanvas(900, 500);
background(100);
}
function draw() {
translate(mouseX, mouseY);
rotate(angle);
images(imageSwitcher % 2,-15, -15, 30, 30);
angle += angleSpeed;
}
function keyPressed() {
if (keyCode == LEFT_ARROW) {
images = img1;
}
else if (keyCode == RIGHT_ARROW) {
images = img2;
}
else if (keyCode == LEFT_ARROW) {
images = img3;
}
else if (keyCode == UP_ARROW) {
angleSpeed += 1.0;
}
else if (keyCode == DOWN_ARROW) {
angleSpeed -= 1.0;
}
}
}
Upvotes: 1
Views: 896
Reputation: 36
var angle = 0.0;
var angleSpeed = 0.0;
var images = [];
var imageSwitcher = 0;
function preload() {
images[0] = loadImage("ToyStoryLogo.png");
images[1] = loadImage("CarsLogo.png");
images[2] = loadImage("Incredibles.png");
}
function setup() {
createCanvas(900, 500);
background(204);
}
function draw() {
background(204);
translate(mouseX, mouseY);
rotate(angle);
image(images[abs(imageSwitcher) % 3], -15, -15, 30, 30);
angle += angleSpeed;
}
function keyPressed() {
if (keyCode == LEFT_ARROW) {
imageSwitcher--;
} else if (keyCode == RIGHT_ARROW) {
imageSwitcher++;
} else if (keyCode == UP_ARROW) {
angleSpeed += 0.1;
} else if (keyCode == DOWN_ARROW) {
angleSpeed -= 0.1;
}
}
Upvotes: 1
Reputation: 36
There are a few issues that I see.
The first has to do with the rotation speed control.
You want to add a variable to control the incrementation of the angle variable.
Create a variable, lets say angleSpeed.
var angle = 0.0;
var angleSpeed = 0.0;
...
In the draw function, change the line
angle += 0.1;
to
angle += angleSpeed;
This allows you to control the rotation in keyPressed( );
if keycode Up angleSpeed += 1.0; If keycode Down angleSpeed -= 1.0;
Switching through the images would be a little more complicated. I would look into creating a array of images, var images = [ ];
Then cycling through the array with a key press right or left. var image = [ ] var ImageSwitcher = 0 Then in preload images[0] = loadImage (image1); images[1] = loadImage (image2); images[2] = loadImage (image3);
In draw
image(images[imageSwitcher % 3], x,y,...);
For keycode right arrow ImageSwitcher++; For keycode left arrow ImageSwitcher--
Upvotes: 1