Hello Kevin! Thank you for making such great tutorials, it helps me a lot!!
After learning the previous tutorials, I tried to make a random walk animation program, the starting position of it is the position of the mouse, and it only starts walking when the mouse is pressed.
But I am stuck in how to pass the value of mouseX and mouseY for hours , I want to assign their values to the global variables x and y at the beginning, but mouseX and mouseY can’t be used outside the function, if they are assigned to x and y inside the draw() function, it will be updated every time the draw() function is called, so the program can’t achieve the goal of walking.
How should I go about this? Here’s my code. I’d really appreciate it if you could give me some advice!
let x;
let y;
let length = 15;
function setup() {
createCanvas(400, 400);
frameRate(30);
}
function draw() {
x = mouseX;
y = mouseY;
//choose one direction randomly
let allDirection = ["north", "south", "west", "east"];
let randomWalkDirection = random(allDirection);
//move only when mouse is pressed
if (mouseIsPressed) {
move(random(allDirection));
}else{
background(255);
}
}
function move(direction) {
if (direction == "north") {
line(x, y + length, x, y);
y += length;
circle(x, y, 5);
} else if (direction == "south") {
line(x, y - length, x, y);
y -= length;
circle(x, y, 5);
} else if (direction == "west") {
line(x, y, x - length, y);
x -= length;
circle(x, y, 5);
} else if (direction == "east") {
line(x, y, x + length, y);
x += length;
circle(x, y, 5);
}
}