Search code examples
javascriptkaboom

Making sprites equally spaced while moving around a circle


I am trying to make a number of circles rotate around a point. I have gotten the spacing to work properly, but now I need some sort of script that can calculate how many circles are rotating, and be able to add more circles while equally spacing all of them. Here is my current code:

    let petals = [
        {
            name: "basic-common",
            damage: 2,
            health: 5,
            reloadtime: 3
        }
    ]

    petals.forEach(el => {
        const petal = add([
            sprite(el.name),
            pos(center()),
            area(),
            rotate(0),
            origin("center"),
            // origin("right"),
            health(el.health),
            "petal",
        ]);

        petal.onUpdate(() => {
            petal.angle += 3
        })
    });

The point that the circles has to rotate must be able to change too, so the code can not only use a single point.


Solution

  • To add the functionality you are asking for, you can add a variable to keep track of the number of circles, and update the code that calculates the spacing between the circles to dynamically adjust based on the number of circles. Here's an example:

    let petals = [{        
        name: "basic-common",  
        damage: 2,    
        health: 5,     
        reloadtime: 3
    }];
    
    let numCircles = petals.length;
    let angleStep = 360 / numCircles;
    
    petals.forEach((el, i) => {
        const petal = add([
            sprite(el.name),
            pos(center()),
            area(),
            rotate(angleStep * i),
            origin("center"),
            // origin("right"),
            health(el.health),
            "petal",
        ]);
    
        petal.onUpdate(() => {
            petal.angle += 3
        })
    });
    
    

    This code uses the angleStep variable to calculate the amount each circle should be rotated by. The angleStep is calculated by dividing 360 (the number of degrees in a full circle) by the number of circles. Then, for each circle in the petals array, the rotate property is set to angleStep * i, where i is the index of the current circle in the array.

    To add more circles to the rotation, you can simply add more objects to the petals array and the code will automatically adjust to include the new circles in the rotation.