我用box2D来制作物理效果,这是我的代码集
public class Main extends SpriteVisualElement
{
public var world:b2World;
public var wheelArray:Array;
public var stepTimer:Timer;
public var scaleFactor:Number = 20;
public function Main()
{
if (stage)
init();
else
addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
getStarted();
}
private function getStarted():void
{
var gravity:b2Vec2 = new b2Vec2(0, 10);
world = new b2World(gravity, true);
wheelArray = new Array();
for (var i:int = 0; i < 20; i++)
{
createWheel(
Math.random() * 0.5,
Math.random() * (stage.stageWidth - 20) + 10,
Math.random() * (stage.stageHeight - 20) + 10,
(Math.random() * 100) - 50,
0
);
}
createBoundaries();
stepTimer = new Timer(0.025 * 1000);
stepTimer.addEventListener(TimerEvent.TIMER, onTick);
graphics.lineStyle(3, 0xff0000);
stepTimer.start();
}
private function createBoundaries():void
{
trace(this.height,this.width,stage.height,stage.width);
// need some code here
}
protected function onTick(event:TimerEvent):void
{
graphics.clear();
graphics.lineStyle(3, 0xff0000);
world.Step(0.025, 10, 10);
for each (var wheelBody:b2Body in wheelArray)
{
graphics.drawCircle(
wheelBody.GetPosition().x * scaleFactor,
wheelBody.GetPosition().y * scaleFactor,
(wheelBody.GetFixtureList().GetShape() as b2CircleShape).GetRadius() * scaleFactor
);
}
}
private function createWheel(radius:Number, startX:Number, startY:Number, velocityX:Number, velocityY:Number):void
{
var wheelBodyDef:b2BodyDef = new b2BodyDef();
wheelBodyDef.type = b2Body.b2_dynamicBody;
wheelBodyDef.position.Set(startX / scaleFactor, startY / scaleFactor);
var wheelBody:b2Body = world.CreateBody(wheelBodyDef);
var circleShape:b2CircleShape = new b2CircleShape(radius);
var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();
wheelFixtureDef.shape = circleShape;
wheelFixtureDef.restitution = (Math.random() * 0.5) + 0.5;
wheelFixtureDef.friction = (Math.random() * 1.0);
wheelFixtureDef.density = Math.random() * 20;
var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);
var startingVelocity:b2Vec2 = new b2Vec2(velocityX, velocityY);
wheelBody.SetLinearVelocity(startingVelocity);
wheelArray.push(wheelBody);
}
}
}
我已将此添加到主视图中,如此
var main:Main = new Main();
this.addElement(main);
它的工作原理但在检测舞台边界方面存在问题。 目标:我想设置边界,所以任何帮助...
答案 0 :(得分:1)
Box2D没有这样的边界系统,你必须
bullet
- 标志设置为true。