问题
I want to draw at one place by dragging the mouse and have the line drawn at 3 places around the center of canvas, including one under the cursor itself. I am using following code which does draw 3 lines but none of them is under the mouse cursor:
void setup(){
size(300, 300); }
void draw() {
translate(width/2, height/2);
if(mousePressed)
for(int i=0; i<3; i++){
line(width/2 -mouseX, height/2 -mouseY,
width/2 -pmouseX, height/2 -pmouseY);
rotate(2*PI/3); }}
How can I correct this code so that one drawing is right under mouse cursor and other 2 are rotated accordingly?
回答1:
You have to think about where your points are in relation to your translate()
and rotate()
calls.
First you translate, so the origin is in the center of the screen instead of in the upper-left corner. So all of your points need to be relative to the center instead of relative to the upper-left corner.
To debug this, I'd start by getting rid of the for
loop and simply drawing a single point, or a single line:
void setup() {
size(300, 300);
}
void draw() {
translate(width/2, height/2);
if (mousePressed) {
line(width/2 -mouseX, height/2 -mouseY,
width/2 -pmouseX, height/2 -pmouseY);
}
}
You'll see that this is off, which means your logic for computing the line's position is wrong. You can play with this to notice a pattern, and you can think about some example points.
The center point is 150,150
. So if the mouse is at 160,160
, what position should we draw the point? Remember it's relative to 150,150
, so 160,160
becomes 10,10
.
In other words, we're subtracting the center from the mouse to figure out where to draw the point.
But your code subtracts the mouse from the center, which is backwards.
If you have similar problems in the future, I highly suggest going through the process of thinking of example points and figuring out where they should go. Graph paper is your best friend with stuff like this.
Note: I realize that you're basing your code off my answer to your other question, so that's my bad. I got the order wrong, but it didn't matter in your other question because you were translating 4 times (so the mouse cursor got covered anyway).
来源:https://stackoverflow.com/questions/41971432/not-drawing-under-the-mouse-in-processing