Concept
WITHIN means positioned inside the boundaries or limits of something else. In this example, circles are "within" the container when their center point is inside the rectangular boundary.
Translation Strategy
To create "within" relationships on screen:
- Boundary Checking: Test if an object's position is inside a container's edges
- Coordinate Comparison: Check X and Y coordinates against container bounds
- Visual Feedback: Change colors to show containment status
Key P5.js Methods
Coordinate System:
•
createCanvas(width, height) - Creates coordinate system where (0,0) is top-left
•
rect(x, y, width, height) - Draw rectangular container
Boundary Checking:
• Compare object position with container edges
• Use logical AND (&&) to check all four boundaries
•
dist(x1, y1, x2, y2) - Calculate distance for collision detection
Visual Feedback:
•
fill(r, g, b) - Change colors based on containment
•
stroke(r, g, b) - Change border colors
•
ellipse(x, y, width, height) - Draw circular objects
Mouse Interaction:
•
mousePressed() - Detect when mouse is clicked
•
mouseDragged() - Detect when mouse is dragged
•
mouseReleased() - Detect when mouse is released
Code Structure
Basic Pattern for "Within":
1. Define container: Create rectangular boundary
let container = {x: 100, y: 80, width: 200, height: 140};
2. Define objects: Create objects to test containment
let movingObject = {x: 150, y: 120, radius: 20};
3. Check containment: Test if center is inside bounds
function checkWithinContainer(obj) {
return (obj.x >= container.x &&
obj.x <= container.x + container.width &&
obj.y >= container.y &&
obj.y <= container.y + container.height);
}
4. Visual feedback: Change appearance based on status
if (isWithin) {
stroke(50, 200, 50); // Green border when within
} else {
stroke(200, 50, 50); // Red border when outside
}