开发者

fish in a pool, when mouse is near must go away

i'd like to make something like a fish pool. when no action is happening, animated fish goes around. when mouse go near that, they go away from the mouse. i think it has been done many times, but i'm not able to find tutorials that explain this problem. i'm looking fo开发者_StackOverflowr a tutorial thanks


( this is not a trivial problem at all )

hi,

this kind of motion is called flocking. there are fairly simple rules to put together and your boids will become autonomous. the original concept of boids was found and developed by Craig Reynolds and is available here: http://www.red3d.com/cwr/boids/.

explainations and an implementation in actionscript were done by Keith Peters in his book AdvncED actionscript 3.0.

the chapter concerning flocking is available here: http://books.google.fr/books?id=QuwsOHYA0p4C&pg=PA92&lpg=PA93&vq=flocking#v=onepage&q=flocking&f=false

and the material ( classes and samples files ) are available here: http://www.friendsofed.com/download.html?isbn=1430216085

note that other implementations exist, I'd recommend this one http://blog.inspirit.ru/?p=231

you might also be interested in grant skinner's wander motion class: http://gskinner.com/blog/archives/2009/11/wander_motion_c.html


Depending on how elaborate the fish's movement is, you have to measure the distance and angle between the fish and the mouse position on Event.ENTER_FRAME (or at a Timer interval), then have the fish move in the opposite direction, if the distance is less than the minimum value.

These might help:

function getDistance ( posa:Point, posb:Point ) : Number {
    var distanceX : Number = posa.x - posb.x;
    var distanceY : Number = posa.y - posb.y;
    return Math.sqrt( Math.pow(distanceX, 2) + Math.pow (distanceY, 2) );
}

function getAngle ( posa:Point, posb:Point ) : Number {
    var distanceX : Number = posa.x - posb.x;
    var distanceY : Number = posa.y - posb.y;
    var angleInRadians : Number = Math.atan2 ( distanceY, distanceX );
    var angleInDegrees : Number = angleInRadians * (180 / Math.PI);
    return angleInDegrees > 0 ? angleInDegrees : angleInDegrees + 360; // always returns a positive value to avoid confusion when used with the rotation property
}

usage:

var posa:Point = fish.parent.localToGlobal (new Point (fish.x, fish.y);  // fish position relative to the stage
var posb:Point = new Point (stage.mouseX, stage.mouseY);                 // mouse position relative to the stage
var distance:Number = getDistance (posa, posb);                          // distance in pixels
var angle:Number = getAngle (posa, posb);                                // angle in degrees
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜