Input

Now you know how to call functions, use variables, create functions, and use if statements. You also know how to modify variables over time to create animations, and you’ve seen that p5.js gives you predefined variables like width and height.


This is a companion discussion topic for the original entry at https://happycoding.io/tutorials/p5js/input

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 :sweat_smile:, 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);
    
  }
}
3 Likes

You might be looking for the mousePressed() function? That function is called automatically whenever the user presses the mouse, once per press.

Try moving your x = mouseX; and y = mouseY; lines to be inside the mousePressed() function:

function mousePressed() {
  x = mouseX;
  y = mouseY;
}

Now instead of setting x and y every frame, your sketch would only set them when the user first presses the mouse.

1 Like

Thank you very much! It was exactly what I was looking for. Now it works! :partying_face: Here’s my work and I added some more to practice what I learned from your tutorials. random walk

2 Likes

Oh wow this looks great! I couldn’t resist playing with it a little bit to see what cool designs I could make!

2 Likes

Looks sooooo cool!

1 Like