dist()
The `dist()` function calculates the distance between two points in a 2D space, which is essential for determining how far apart objects are from one another. Creative coders use it to create interactions and effects based on proximity, such as detecting mouse clicks on shapes or simulating physical behaviors like flocking or particle systems. For instance, in an interactive color mixing tool, `dist()` can help determine if the user's mouse is close enough to a colored circle to blend colors together.
📖 p5.js Reference →🧠 See The Whole Picture
Imagine the canvas as a flat grid. When you call `dist()`, it's like measuring the straight line distance between two dots on that grid. Each dot is defined by its x and y coordinates, and the function calculates how long that line is, similar to using a ruler to measure the distance between two points on paper.
📖 Visual Learner's Guide
The Big Picture:
When you run this code, you'll see two circles: one at a fixed point and one that moves with your mouse. The distance between these circles is shown as a number on the canvas.
Visual Analogy:
Think of `dist()` like using a string to measure how far apart two points are - you stretch the string from one point to the other and it tells you the distance.
The Numbers Decoded:
The first two numbers (x1, y1) are like coordinates on a treasure map, telling you where to find the first X. The second pair (x2, y2) tells you where to find the second X. The result is the length of the string you would need to connect these two points.
Connection Map:
The `fill()` function sets the color for the circles before drawing them. The `dist()` function then calculates how far apart they are based on their positions. This interaction creates a dynamic visual experience.
Common Gotcha:
Remember the distance is always calculated as a straight line between the two points, not a path that follows edges or corners!
🔄 How It Works
This diagram illustrates how your code flows into the `dist()` function, which calculates the distance and outputs that value.
📝 Syntax
📖 How to Read This
Read `dist(x1, y1, x2, y2)` as: Calculate the distance from the point (x1, y1) to (x2, y2). Each pair of numbers represents a point's coordinates on the canvas, and the parentheses are like a delivery box - you hand the function the information it needs to compute the distance.
dist(param1, param2, ...)
Example: dist(200, 150, 80)
🔀 Different Ways to Call It
dist(value)
This variant is used for calculating the distance from a single point to the origin (0,0), which can be useful for determining how far away an object is from the center of the canvas.
dist(128)
→ This produces the distance from the origin to the point (128, 128).
dist(v1, v2, v3)
This variant computes the distance between two points defined by their x and y coordinates.
dist(255, 100, 50)
→ This calculates the distance between the point (255, 100) and (50, 50).
↩️ What It Returns
Type: Number
`dist()` returns a numeric value representing the distance between two points, similar to measuring the length of a line drawn between them on a canvas.
Parameters
x1
Number
required
A Number represents any point along the horizontal axis on the canvas, like a ruler measuring distance from the left edge.
The x-coordinate of the first point. It controls the horizontal position, with 0 being the far left of the canvas.
Range: 0 to width of canvas
0 → Point located at the far left of the canvas.
200 → Point located halfway horizontally on a 400px wide canvas.
400 → Point located at the far right of the canvas.
y1
Number
required
A Number represents any point along the vertical axis on the canvas, like a ruler measuring distance from the top edge.
The y-coordinate of the first point. It controls the vertical position, with 0 being the top of the canvas.
Range: 0 to height of canvas
0 → Point located at the top of the canvas.
200 → Point located halfway vertically on a 400px high canvas.
400 → Point located at the bottom of the canvas.
x2
Number
required
A Number representing the second point's x-coordinate, similar to x1.
The x-coordinate of the second point. It defines where the second point lies horizontally.
Range: 0 to width of canvas
0 → Point located at the far left of the canvas.
200 → Point located halfway horizontally.
400 → Point located at the far right.
y2
Number
required
A Number representing the second point's y-coordinate, similar to y1.
The y-coordinate of the second point. It defines where the second point lies vertically.
Range: 0 to height of canvas
0 → Point located at the top of the canvas.
200 → Point located halfway vertically.
400 → Point located at the bottom.
💡 How Parameters Work Together
The parameters interact like coordinates on a grid system. The first two numbers define the first point, while the last two define the second point. It's like drawing a line between two locations on a map, where the distance tells you how far you have to travel to get from one point to the other.
💻 Working Example
// Complete working example with comments
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
// Define two points
let x1 = 100, y1 = 100;
let x2 = mouseX, y2 = mouseY;
// Calculate distance between them
let distance = dist(x1, y1, x2, y2);
// Display distance
textSize(32);
fill(0);
text('Distance: ' + distance, 10, height - 10);
// Draw points
fill(255, 0, 0);
ellipse(x1, y1, 20);
fill(0, 0, 255);
ellipse(x2, y2, 20);
}
Try This Code →
⚙️ How It Works
When you call `dist()`, the function retrieves the x and y coordinates provided as inputs. It then applies the distance formula: sqrt((x2 - x1)^2 + (y2 - y1)^2) to calculate the straight-line distance. This computed value is returned to the calling code, allowing it to be used for further interaction or visual feedback.
🎓 Learn Prompt Patterns
These patterns help you write better prompts for ANY function:
🎭 Persona Pattern
Tell the AI to act as a specific type of creator
"Act as a creative coder making generative art. Use `dist()` to create a visual interaction based on distance."
Why it works: Giving the AI a persona helps it understand the context and style you want.
📋 Recipe Pattern
Ask for step-by-step instructions
"Give me step-by-step code to use `dist()` to create an interactive distance measuring tool."
Why it works: Breaking down into steps helps you understand each part and learn incrementally.
📝 Template Pattern
Provide a structure for the AI to fill in
"Use this template: setup creates canvas, draw uses `dist()` with mouse coordinates to determine distance from a fixed point."
Why it works: Templates give the AI clear constraints, resulting in more predictable output.
🔄 Refinement Pattern
Start simple and iterate
"Start with a basic `dist()` example. Then I'll ask you to add: colors, animations, interactions."
Why it works: Building up gradually helps you understand each addition.
🎯 Direct Prompts - Name the Function
Tell the AI exactly which function to use:
"Create an interactive sketch that shows the distance between the mouse and a fixed point using `dist()`."
💡 Why this is good: It clearly defines the task and encourages exploration of distance.
📚 What you learn: How to use `dist()` for interactivity.
// Complete working code that demonstrates this interaction.
"Design a generative art piece that changes color based on the distance between two moving points using `dist()`."
💡 Why this is good: It encourages creativity while applying distance calculations.
📚 What you learn: How to creatively manipulate colors based on distance.
// Full working code for a generative art piece.
🔮 Indirect Prompts - Describe What You Want
Don't name the function - see if the AI figures out to use dist():
"Describe a visual effect where two circles change appearance based on their proximity without naming `dist()`."
💡 Why this is good: This teaches you to communicate visual intent without knowing function names.
� What you learn: How to express visual ideas in code.
// Code showing how `dist()` was derived from the description.
🖼️ See It In Real Sketches
How dist() is used in actual gallery sketches:
AI Color Mixer Lab
`dist()` is utilized to determine if the mouse is close enough to a color circle to interact with it for color mixing.
const d = dist(mouseX, mouseY, c.x, c.y);...
View Sketch →
AI Wave Function Simulator
`dist()` calculates the distance from the mouse to wave sources to visualize interference patterns.
const d1 = dist(mouseX, mouseY, source1.x, source1.y);...
View Sketch →
🔀 Fun Function Combinations
Try asking the AI to combine dist() with these:
dist() + map()
→ Creates a visual effect where the size or color of an object changes based on the distance calculated.
Try: "Use `dist()` to change the size of a shape based on its distance from the mouse."
// Using dist() to scale a circle based on distance from the mouse
function draw() {
let distance = dist(mouseX, mouseY, 200, 200);
let size = map(distance, 0, 400, 100, 10);
ellipse(200, 200, size);
}
⚠️ Common Mistakes & Fixes
❌ Mistake: Using `dist()` with fewer than four parameters.
🤔 Why it's wrong: `dist()` requires exactly four parameters to calculate the distance between two points.
✅ Fix: Ensure you provide both x and y coordinates for each point.
🗺️ Learning Path
💡 Project Ideas
- Create an interactive distance measuring tool
- Build a game where distance affects gameplay mechanics
🤖 Ask xelsed-alpha6 to Explain
"Explain what dist() does in p5.js"
Try this prompt in p5js.AI to see how the AI explains it!
Try in p5js.AI →💡 Prompt AI to Write Code Using dist()
"Create something using dist()"
🔧 Ask AI to Help Debug
"My dist() isn't working, help me debug"
✨ Creative Combinations with AI
"Combine dist() with other functions for interesting effects"
Ready to Try dist()?
Open p5js.AI and ask the AI to help you use dist() in your own creative project.
Start Coding with AI →