ArgRugby Posted January 7, 2015 Share Posted January 7, 2015 So I want to make a flocking program. I create a group with 20 sprites in the map, they find the closes member of the group and walk towards it, stoping 50 pixels from it. everything works fine, except that they dont want to face the right way. When I run the code, the flocking works, and I get random groups, but they are not facing the way I want them to face. I want them to face towards their target (the closest member of the group). Im not sure what Im doing wrong. I tried so many combinations. Here is my code: Note: Herd is the name of the group and Herbivore is the name of each individual function update () { herd.forEach (function(m) //check each member of herd, call them "m" for now { var targetx; var targety; var targetAngle; var shortDis; var delta; m.parent.forEach //check each member of the parent of "m" (herd), and call them "f" for now (function(f) { if (m == f) return; //if m and f are the same, the skip this var distance = this.game.math.distance(m.x, m.y, f.x, f.y); //check distance between m and every single f if ((distance < shortDis) || (!shortDis)) // if the distance found is smaller than the shortest distance recorded, { // or if there is no shortest distance recorded shortDis = distance; // record the length of the distance targetx = f.x; // record the X targety = f.y; // record the Y if (distance >= 50){ m.speed = 50} // if its more than or equal to 50, give it speed else if (distance < 50){m.speed = 0}; //if its less than 50, speed is 0 } } ) //move towards the target (closest member of group) if (m.x < targetx) {m.body.velocity.x = m.speed;} else if (m.x > targetx) {m.body.velocity.x = m.speed * -1} else {m.body.velocity.x = 0} if (m.y < targety) {m.body.velocity.y = m.speed;} else if (m.y > targety) {m.body.velocity.y = m.speed * -1} else {m.body.velocity.y = 0}; //find desired angle (for some reason I ened up with an angle between 1 and -1) targetAngle = this.game.math.angleBetween(m.x, m.y, targetx, targety); //figure out the difference between my angle and the target angle (how much I have to turn) delta = m.angle - targetAngle; //if its less than 5, just make them equal if (delta < 5) {m.angle = targetAngle;} if (m.angle !== targetAngle) //if they are not equal { if (delta > Math.PI) delta -= Math.PI * 2; //for efficiency, transform all angles to be between 180 and -180 if (delta < -Math.PI) delta += Math.PI * 2; if (delta > 0) { //find out which way to turn // Turn clockwise m.angle += 1; } else { // Turn counter-clockwise m.angle -= 1; } } } )}; Im going nuts, they all just turn until they are facing down, and then snap to face up, and they stay there, no matter if they are still walking towards their partner or if they are standing still. Link to comment Share on other sites More sharing options...
Recommended Posts