I'm using P5.js, but the question is applicable to Javascript in general
In p5.js we have a class p5.Vector which is useful to manipulate vectors, since it already implements a variety of methods for vectors (addition, heading, magnitude, rotation...)
Vector components are stored in the x and y attributes, so they are intuitively easy to access
let myVector = createVector(1, 2);
myVector.x; // returns 1
Now, some functions in P5.js don't accept vectors, but expect one parameter for x and one parameter for y
For example, drawing a circle:
circle(10, 20, 5); // draws a circle at position (10, 20) of diameter 5
Now the question:
My functions usually return vectors, and sometimes I want to use this vectors to call native P5.js functions that don't accept vectors, but individual coordinates.
In this case, I use an auxiliary variable.
let myPosition = calculatePosition(); // calculatePosition returns a vector
circle(myPosition.x, myPosition.y, 5);
Is there a way that I could do that without using an auxiliary variable, and somehow unpack the x and y components so they get passed to the appropriate parameters of circle?
I couldn't find this option in the documentation, but you can overwrite this behaviour using Symbol.iterator
p5.Vector.prototype[Symbol.iterator] = function*() {
yield this.x
yield this.y
yield this.z
}
function setup() {
const v = createVector(1, 2, 3)
console.log('test', ...v)
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With