开发者

Randomly place an MovieClip on an irregularly shaped object?

Is there anyway to randomly place a MovieClip/Sprite on an irregularly shaped object?

For a rect开发者_StackOverflow社区angle, it seems pretty straightforward (i.e. use Math.random with the range being the coordinates of an object)...but what if say, you would like to avoid placing objects in the center?


You could try defining a Shape object, using the drawing API to create your irregular shape, and then doing a hitTestPoint() against a randomly generated point within the boundaries of your Shape. In your position placement code, you can create a loop that repeats until the hit test returns false, meaning the point is not within the avoid region.

var avoidMe:Shape = new Shape();
avoidMe.graphics.beginFill(0x0000FF, 0); //make it transparent fill
avoidMe.graphics.lineTo(x1, y1);
avoidMe.graphics.lineTo(x2, y2);
avoidMe.graphics.lineTo(x3, y3);
avoidMe.graphics.lineTo(xn, yn);
avoidMe.endFill();
addChild(avoidMe);

var w:Number = 100; //width of placement area
var h:Number = 100; //height of placement area
var p:Point = new Point();

do {
  p.x = Math.random() * w;
  p.y = Math.random() * h;
}
while (avoidMe.hitTestPoint(p.x, p.y));

var s:Sprite = new Sprite();
s.x = p.x;
s.y = p.y;

addChild(s);

You could also do something very similar with hitTestObject() to test the actual boundaries of your objects instead of a point.


You could draw an image map where allowed regions are white and blocked regions are black. Now you can check for every randomly chosen position if it's blocked or not.

This tutorial illustrates what I mean, even if it's a little outdated: The blocked areas of the game at the bottom of the page are determined by the green color of the sprite shown in the embedded swf above.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜