Skip to content
Advertisement

How do I make this array of objects ‘spring’ into random positions on the canvas?

I’m trying to make an array of images ‘spring’ onto the canvas from the bottom of the screen and then land in random positions, like this image here:enter image description here (this is a screenshot of my canvas after you remove the physics)

Here is my attempt so far:

https://editor.p5js.org/holographicleah/sketches/DUY0EDnqN

I like the animation of the spring that i’ve managed, but I want the cats to be scattered across the whole screen like in the image above. I understand that i’m affecting the same ‘force’ on all of the objects, so it’s natural that they all end up at the same height at the top of the screen. How could I randomise it so that they end up everywhere? Should I have used some kind of lerp to absolute positions instead? Open to trying something different if needs be. Still a beginner to code really so classes are still new to me!

Inspiration for this code came from both https://www.youtube.com/watch?v=Rr-5HiXquhw&t=937s for the spring physics and https://www.youtube.com/watch?v=cl-mHFCGzYk&t=149s for the ‘particles’. I’ve adapted what I can but I’ve hit an experience wall!

Advertisement

Answer

You already have the x position covered in your linked code. In order to randomize the y position, change your constructor() method, by adding this line:

this.randomf = random(Math.floor(height/2) - 50);

Then, in the update() method, add this line:

this.pos.y += this.vel + this.randomf;

With the first line, you’re giving individual objects a property which tells them what their (randomly chosen) y limit should be.

With the second line, you’re limiting the y position. You would need to adjust it a bit, to fit your use case.

And some advice – with a large number of objects springing up, you might want to consider limiting the number of cycles, by dropping the updates, once the velocity falls below a certain value. Something like this:

    update(){
        if(this.vel <= 0.009) {
            let force = - spring * this.pos.y;
            this.vel+= force;
            this.pos.y += this.vel;
            this.vel*=0.9;
        }
    }
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement