We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I'm trying to use heading to position a row of squares with an angle in direction to the mouse. Just as a test for using vector's and angles. I wrote a function for the squares, and generate an angle with mouseX and mouseY. Though P5 calculates the angles from the 0,0 point of the canvas, so i tried to create the vector in a matrix, but this doesn't seem to change much. So the question is; is there a way to generate the angle with mouseX/mouseY relative to the position of the object that has been created. or do I have to use if statements to check whether the X/Y of the mouse is </> relative to the objects position.
Code:
var rectArray = [];
var mouseVector;
function setup() {
createCanvas(windowWidth,windowHeight);
for (i = 0;i < 100; i++) {
rectArray.push(new Square(10*i,40));
}
}
function draw() {
for (i = 0; i < rectArray.length; i++) {
rectArray[i].rotation();
rectArray[i].update();
rectArray[i].display();
}
}
function Square(x,y) {
this.x = x;
this.y = y;
this.size = 20;
this.color = color(200);
this.target = 0;
this.rotationValue = 0;
this.rotation = function() {
push();
translate(this.x,this.y);
mouseVector = createVector(mouseX,mouseY);
this.target = mouseVector.heading();
this.rotationValue = this.target;
pop();
}
this.update = function() {
//this.x = this.x + 1;
}
this.display = function() {
push();
translate(this.x,this.y);
rectMode(CENTER);
rotate(this.rotationValue);
fill(this.color);
rect(0,0,this.size,this.size);
pop();
}
}
Answers
https://forum.Processing.org/two/discussion/8045/how-to-format-code-and-text
Thanks for that tip GoToLoop ;) I guess my first error 'out in the open' has just been made... :)
is there a way to generate the angle with mouseX/mouseY relative to the position of the object that has been created.
If you have an object at position objX and objY then the angle made by the line from the object to the mouse is given by
angle = atan2(mouseY - objY, mouseX - objX);
The angle is in the range -PI to +PI to convert to 0-2*PI then use
angle = (angle < 0) ? TWO_PI + angle : angle
Processing does have a function called angleBetween which probably does this for you.
Indeed class PVector in Java Mode & class p5.Vector in p5.js got a method called angleBetween():
https://Processing.org/reference/PVector_angleBetween_.html
http://p5js.org/reference/#/p5.Vector/angleBetween
angleBetween() won't work.
var angle = p5.Vector.angleBetween(p1, p2);
is the same of:var angle = p1.headings() - p2.headings();
To have a vector that comes "from the positon of the object towards the mouse position" you just need to subtract the position of the object from your mouseVector:
http://natureofcode.com/book/chapter-1-vectors/