Make a Coordinate Widget

Step 1
Find the coordinates!

In this lesson, we will add a helpful tool to our project that helps of find the X and Y coordinates for shape functions.

If you are already good at finding X and Y coordinates, you do NOT need to do this lesson.

Step 2
Create the drawXYlines function

Define a new function called `drawXYlines, and call it as the last thing in your draw function.

Step 3
Draw a line to the middle of the canvas

If you only give a line one point, it will assume the start is at 0, 0

Temp1542759764 Temp1542759894
Step 4
Make the line horizontal.
Temp1542760027 Temp1542760154
Step 5
Add another line to represent the X coordinate

In this case, the starting coordinate should be 250, 0, and still go to the middle coordinate of 250, 250

Step 6
Give the lines different colors
Temp1542760540 Temp1542760634
Step 7
Change the lines to go to the mouse position

mouseX and mouseY are special variables in p5 that are assigned to the X and Y coordinates of the mouse.

Check Your Work
Step 8
Save and Run to see the lines follow your mouse.
Step 9
Copy the code to display the coordinates

Now that you have lines drawing to your mouse position, copy and paste the code below after the lines to show the X and Y coordinates:

  rect(mouseX - 25, mouseY/2-10, 50, 20)
  rect(mouseX/2 - 25, mouseY-10, 50, 20)
  text("Y: " + mouseY, mouseX -15, mouseY/2+5)
  text("X: " + mouseX, mouseX/2 -15, mouseY+5)
Step 10
Make a "click" variable

Declare a new global variable called click and assign it equal to false in the setup function

Step 11
Create functions to listen for mouse presses

Just like keyPressed and keyReleased, mousePressed and mouseReleased are special functions that wait for user inputs. Use these to make **click`` true when the user is holding the mouse down.

Step 12
Make the coordinates show up when the mouse is pressed

Change the code in your draw function to only call drawXYlines() when the click variable is true

Step 13
Check out the numbers displayed for X and Y.
Step 14
Remove the background

Take the background out of the drawXYlines function so that you can see the lines on top of your project

Check Your Work
Step 15
Save and Run to find the coordinates for new elements in your project!
Make a Coordinate Widget Info


MVCode Clubs

Created By

Mandala2 slinkous


Side Scroll Adventure

Access Level


For Teachers and Schools

Teach coding to your students with MVCode Teach

MVCode offers an integrated product designed to teach coding to students.

Learn more about MVCode Teach