As you can see on the forum there are usually two ways to do mouseOvers. Either mathematically or through color buffers. I am assuming you want to find a mathematical solution. Which leads me to the question...
Is the line
horizontal,
vertical or
diagonal?
The first two are easy:
- horizontal: is mouseY equal to lineY, is mouseX between lineStartX and lineEndX
- vertical: is mouseX equal to lineX, is mouseY between lineStartY and lineEndY
The latter (a line for any two given points) is a bit harder. Perhaps too advanced for a beginner.
Here is a code example that does this. You can press the mouse to randomly place the line.
Code Example
- PVector p1 = new PVector(200, 200);
- PVector p2 = new PVector(600, 600);
- PVector p3 = new PVector();
-
- void setup() {
- size(800, 800);
- smooth();
- }
-
- void draw() {
- background(255);
- p3.set(mouseX, mouseY, 0);
- PVector cp = closestPoint(p1, p2, p3);
- noStroke();
- fill(0);
- ellipse(p1.x, p1.y, 10, 10);
- ellipse(p2.x, p2.y, 10, 10);
- ellipse(p3.x, p3.y, 10, 10);
- if (p3.dist(cp)<10) {
- strokeWeight(4);
- stroke(0, 0, 255);
- } else {
- strokeWeight(1);
- stroke(0);
- }
- line(p1.x, p1.y, p2.x, p2.y);
- noStroke();
- fill(255, 0, 0);
- ellipse(cp.x, cp.y, 15, 15);
- }
-
- void mousePressed() {
- p1.set(random(width), random(height), 0);
- p2.set(random(width), random(height), 0);
- }
-
- PVector closestPoint(PVector a, PVector b, PVector p) {
- PVector v1 = a.get();
- PVector v2 = b.get();
- PVector v3 = p.get();
- v2.sub(v1);
- v3.sub(v1);
- float t = v3.dot(v2) / pow(v2.mag(), 2);
- if (t < 0.0) {
- return a.get();
- } else if (t > 1.0f) {
- return b.get();
- }
- v2.mult(t);
- return PVector.add(v1, v2);
- }