I’m reading The Nature of Code but I stuck with a stupid question on vector.
I tried to make a line drawn from the center of the screen to my mouse with the help of vectors.
Here : https://editor.p5js.org/Erjaeger42/sketches/TfeqmxjEw
I have a working version when I use a translate(width/2, height/2) and line(0,0…) but I don’t understand why I have to use a translate and not just use line(width/2, height/2, …).
When I do that I have some strange result. I made some research but I haven’t find something useful. I would like to really understand that before moving along. So I wish you can help me !
When I use the line(center.x, center.y, test.x, test.y); it’s look like the origin is on the bottom right… I really don’t understand.
In your code it won’t make much of a difference, but in some scenarios it can be handy to use translate instead of calculating the x/y positioning elsewhere. I’m certain you’re going to stumble upon more translate examples throughout the Nature of Code tutorials, so for now I wouldn’t worry too much about it.
I’m not familiar yet with p5.Vector.sub, but if you use the code below you can make an estimated guess through observing the red line’s behaviour when you move the mouse around.
@madscientist I could do it with just a line, but the point is to use the vector, to have access to normalize, magnitude, etc…
@Tiemen
Thank you for your constructive answer. Yes I certainly find translate many more time in the book, but I would like to understand the basic stuff before dive in more complicated exemple. I still have some difficulties to see the difference between the translate and the line(width/2, height/2…)
The sub values is calculated from 0,0. So the substraction gives negative values.
If I want to change the origin of my vector with line(width/2, height/2,…) I have to add width/2, height/2 to my vector values.
If I do,
function setup() {
createCanvas(640, 480);
}
function draw() {
background(220);
const center = createVector(width/2, height/2);
const mouse = createVector(mouseX, mouseY);
const test = p5.Vector.sub(mouse,center);
stroke("blue")
line(0, 0, center.x, center.y);
stroke("green")
line(0, 0, mouse.x, mouse.y);
stroke("red")
line(center.x, center.y, test.x+width/2, test.y+height/2);
}