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.

Temp1542762247
Step 2
Create the drawXYlines function

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

Temp1542759459
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
Challenge
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

Temp1542760282
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.

Temp1542760775
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:

noStroke();
  fill(255);
  rect(mouseX - 25, mouseY/2-10, 50, 20)
  rect(mouseX/2 - 25, mouseY-10, 50, 20)
  fill(0)
  text("Y: " + mouseY, mouseX -15, mouseY/2+5)
  text("X: " + mouseX, mouseX/2 -15, mouseY+5)
Challenge
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.

Temp1542761376
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

Temp1542761609
Step 13
Check out the numbers displayed for X and Y.
Temp1542761925
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

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

Account

MVCode Clubs

Created By

Mandala2 slinkous

Course:

Side Scroll Adventure

Access Level

public

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