0
\$\begingroup\$

I have some bots that can move via setting the x and y. I have already been able to make them move in a circle pattern, but how do I make them rotate around the player in a square pattern? I'm not very good at math, so I'd appreciate some help.

Here is what it looks like now:

here is how I did circle pattern.

var PI2 = 2 * Math.PI, FOLLOWADD = PI2 / 18/*PI2 / 360 * 20*/, BOTSLICE = PI2 / BOTS;

bots.follow = function(id) {
    if (!ppl()[id])
        id = protocol.id; //player is default

    var pos = getPos(id), a, i = BOTS;
    while (i--)
        if (this[i] && !this.busy) {
            a = BOTSLICE * i + f;
          this[i].pos.x = pos.x + (Math.cos(2 * Math.PI / BOTS * i + f) * 3);
            this[i].pos.y = pos.y + (Math.sin(2 * Math.PI / BOTS * i + f) * 3);
        }
    f = (f + FOLLOWADD) % PI2;
}.bind(bots);
\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

To keep the code similar, the bots could move around a larger circle which is then bounded in X and Y. The result would be a square inscribed in a circle:

Square inscribed inside circle - picture from Math Central

The radius of the circle is the distance from the centre of the square to a diagonal corner. This can be calculated by Pythagorean theorem:

$$radius = 0.5\times\sqrt(width^2+height^2)$$

For our example 50x50 boundary,

$$radius = 0.5\times\sqrt(50^2+50^2)$$ $$radius = 35.355$$

Once the radius has been calculated, the value can be inserted into the existing code. Then there are four lines to bound X and Y into min and max zones:

this[i].pos.x = pos.x + (Math.cos( ((2 * Math.PI) / (BOTS * i)) + f) * 35.355);
this[i].pos.y = pos.y + (Math.sin( ((2 * Math.PI) / (BOTS * i)) + f) * 35.355);

this[i].pos.x = Math.min( this[i].pos.x , pos.x + 25);
this[i].pos.x = Math.max( this[i].pos.x , pos.x - 25);
this[i].pos.y = Math.min( this[i].pos.y , pos.y + 25);
this[i].pos.y = Math.max( this[i].pos.y , pos.y - 25);

The 50x50 pixel boundary has been hard-coded here, but the 35.355 and 25 could be moved into variables.

\$\endgroup\$
1
  • \$\begingroup\$ Thanks, that almost works, but I'd prefer it if the bots would spread evenly around the square. Also, is there a way to speed it up, and make it not stop for a second at each corner? here is what it looks like right now: link. By the way, I made the 50 * 50 pixel boundary a 10* 10 boundary, so it's 5. \$\endgroup\$ Feb 5, 2019 at 21:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .