Javascript
i'm having problems moving around two shapes at the same time, can anyone help
This is difficult to answer without seeing your code. It also depends on how you want to move your shapes.
In order to create an animation, you need three things:
1) A global variable
2) To use that global variable to define the position or size of your drawing
3) A function assigned to the draw
variable that changes the value of the global variable
If you want your shapes to move in the same direction, at the same speed, you would write code like Pamela did for the car:
noStroke();
// position of the car - GLOBAL VARIABLE
var x = 10;
// FUNCTION ASSIGNED TO DRAW
draw = function() {
// all lines of code inside here will be run repeatedly
background(151, 244, 247);
// draw the car body
fill(255, 0, 115);
// USE THE GLOBAL VARIABLE (x) TO DEFINE THE SHAPES
rect(x, 200, 100, 20);
rect(x + 15, 178, 70, 40);
// draw the wheels
fill(77, 66, 66);
ellipse(x + 25, 221, 24, 24);
ellipse(x + 75, 221, 24, 24);
// CODE TO CHANGE THE VALUE OF THE GLOBAL VARIABLE
x = x + 1;
};
If you want your shapes to move in different directions, you will need separate global variables - one for each shape. You will still only assign one function to draw. Your code would look something like:
// GLOBAL VARIABLES
var circleX = 400;
var squareX = 0;
//ASSIGN A FUNCTION TO DRAW
draw = function() {
//draw a white background
background(255, 255, 255);
//remove outlines
noStroke();
// draw a red circle using GLOBAL VARIABLE circleX
fill(255, 0, 0);
ellipse(circleX, 100, 20,20);
//draw a blue square using GLOBAL VARIABLE squareX
fill(0, 0, 255);
rect(squareX, 250, 20, 20);
// move the circle left by changing the value of circleX
circleX = circleX - 1;
//move the square right by changing the value of squareX
squareX = squareX + 1;
};
Please sign in to leave a comment.