Hi,
I’m working on my n-th mini project. I would like to have multiple parallel lines pointing to mouse position on a click. Here’s the code I wrote:
//introducing vectors
PVector vMouse, u, w;
//introducing arrays
//of integers, to store coordinates
int[] xA;
int[] yA;
int[] yB;
//and of vectors, to draw the lines
PVector[] v1;
PVector[] v2;
void setup() {
size(640, 370);
background(255);
//setting arrays' length
xA = new int[width/10];
yA = new int[height/20];
yB = new int[height/20];
v1 = new PVector[xA.length];
v2 = new PVector[xA.length];
//setting x coordinates for the lines
for (int i = 0, j = 0; i < width; i += 10) {
xA[j] = i + 10;
j++;
}
//setting a couple of y coordinates for the lines
for (int i = 10, j = 0; i < height; i += 20) {
yA[j] = i;
yB[j] = i + 10;
j++;
}
//based on coordinates previously set up,
//I define a bunch of vectors
for (int i = 0; i < width/10; i ++) {
for (int j = 0; j < height/20; j++) {
v1[i] = new PVector(xA[i], yA[j]);
v2[i] = new PVector(xA[i], yB[j]);
}
}
}
void draw() {
if (mousePressed == true) {
background(255);
//defining a vector going from origin to mouse position
vMouse = new PVector(mouseX, mouseY);
//using a for loop to cycle through the arrays of coordinates
for (int i = 0; i < width/10; i ++) {
for (int j = 0; j < height/20; j++) {
//copying the vector going from origin to (xA, yB)
u = v2[i].copy();
//copying the mouse position vector
w = vMouse.copy();
//finding the difference between vectors:
//u - v1
u.sub(v1[i]);
//finding the magnitude of u
float m = u.mag();
//finding the difference between vectors:
//w - v1
w.sub(v1[i]);
//finding w's unit length
w.normalize();
//and multiplying it by u's magnitude
//to have the same lengths
w.mult(m);
//then shifting the origin
translate(v1[i].x, v1[i].y);
//and drawing the line to the expected coordinates
line(0, 0, w.x, w.y);
}
}
//if mouse is not pressed
} else {
background(255);
//I use a for cycle to go through the arrays of coordinates
for (int i = 0; i < width/10; i ++) {
for (int j = 0; j < height/20; j++) {
//and draw the lines based on the coordinates
line(xA[i], yA[j], xA[i], yB[j]);
}
}
}
}
Now, it seems all ok except for the fact that only 1 line is pointing to mouse position (by the way, why just that line on the lower left??). I guess the point is on lines 82 to 85
//then shifting the origin
translate(v1[i].x, v1[i].y);
//and drawing the line to the expected coordinates
line(0, 0, w.x, w.y);
where I shift the origin to draw the lines; I can’t figure out how to make the lines simultaneously rotate towards mouse position. Any idea?