public override void Keyboard(char key) { switch (key) { case ',': if (m_bullet != null) { m_world.DestroyBody(m_bullet); m_bullet = null; } { b2CircleShape shape = new b2CircleShape(); shape.Radius = 0.25f; b2FixtureDef fd = new b2FixtureDef(); fd.shape = shape; fd.density = 20.0f; fd.restitution = 0.05f; b2BodyDef bd = new b2BodyDef(); bd.type = b2BodyType.b2_dynamicBody; bd.bullet = true; bd.position.Set(-31.0f, 5.0f); m_bullet = m_world.CreateBody(bd); m_bullet.CreateFixture(fd); m_bullet.LinearVelocity = new b2Vec2(400.0f, 0.0f); } break; } }
public VaryingRestitution() { { b2BodyDef bd = new b2BodyDef(); b2Body ground = m_world.CreateBody(bd); b2EdgeShape shape = new b2EdgeShape(); shape.Set(new b2Vec2(-40.0f, 0.0f), new b2Vec2(40.0f, 0.0f)); ground.CreateFixture(shape, 0.0f); } { b2CircleShape shape = new b2CircleShape(); shape.Radius = 1.0f; b2FixtureDef fd = new b2FixtureDef(); fd.shape = shape; fd.density = 1.0f; float[] restitution = {0.0f, 0.1f, 0.3f, 0.5f, 0.75f, 0.9f, 1.0f}; for (int i = 0; i < 7; ++i) { b2BodyDef bd = new b2BodyDef(); bd.type = b2BodyType.b2_dynamicBody; bd.position.Set(-10.0f + 3.0f * i, 20.0f); b2Body body = m_world.CreateBody(bd); fd.restitution = restitution[i]; body.CreateFixture(fd); } } }
void CreateNinja() { spriteImageName = String.Format("{0}_standing", baseImageName); onGround = false; // Define the dynamic body. var bodyDef = new b2BodyDef(); bodyDef.type = b2BodyType.b2_staticBody; //or you could use b2DynamicBody to start the ninja as dynamic bodyDef.position.Set(initialLocation.X/Constants.PTM_RATIO, initialLocation.Y/Constants.PTM_RATIO); var shape = new b2CircleShape(); var radiusInMeters = (40 / Constants.PTM_RATIO) * 0.5f; //increase or decrease 40 for a different circle size definition shape.Radius = radiusInMeters; // Define the dynamic body fixture. var fixtureDef = new b2FixtureDef(); fixtureDef.shape = shape; fixtureDef.density = 1.0f; fixtureDef.friction = 1.0f; fixtureDef.restitution = 0.1f; CreateBodyWithSpriteAndFixture(theWorld, bodyDef, fixtureDef, spriteImageName); }
void InitPhysics() { var gravity = new b2Vec2(0.0f, -10.0f); world = new b2World(gravity); world.SetAllowSleeping(true); world.SetContinuousPhysics(true); var def = new b2BodyDef(); def.allowSleep = true; def.position = b2Vec2.Zero; def.type = b2BodyType.b2_staticBody; b2Body groundBody = world.CreateBody(def); groundBody.SetActive(true); b2EdgeShape groundBox = new b2EdgeShape(); groundBox.Set(b2Vec2.Zero, new b2Vec2(900, 100)); b2FixtureDef fd = new b2FixtureDef(); fd.friction = 0.3f; fd.restitution = 0.1f; fd.shape = groundBox; groundBody.CreateFixture(fd); }
public static b2FixtureDef Create() { b2FixtureDef d = new b2FixtureDef(); d.Defaults(); return(d); }
public void Create(b2Body body, b2FixtureDef def) { UserData = def.userData; Friction = def.friction; Restitution = def.restitution; Body = body; Next = null; m_filter = def.filter; m_isSensor = def.isSensor; Shape = def.shape.Clone(); // Reserve proxy space int childCount = Shape.GetChildCount(); m_proxies = b2ArrayPool <b2FixtureProxy> .Create(childCount, true); for (int i = 0; i < childCount; ++i) { m_proxies[i].fixture = null; m_proxies[i].proxyId = b2BroadPhase.e_nullProxy; } m_proxyCount = 0; Density = def.density; }
public JumpPad(b2Vec2 JumpImpuls, CCPoint Position, b2World gameWorld) { this.Texture = new CCTexture2D ("jumppad"); this.Scale = SpriteScale; this.Position = Position; this.IsAntialiased = false; jumpImpuls = JumpImpuls; totalJumps = 0; //box2d b2BodyDef jumpPadDef = new b2BodyDef (); jumpPadDef.type = b2BodyType.b2_kinematicBody; jumpPadDef.position = new b2Vec2 ((Position.X + this.ScaledContentSize.Width/2)/PhysicsHandler.pixelPerMeter, (Position.Y + this.ScaledContentSize.Height/4) / PhysicsHandler.pixelPerMeter); JumpPadBody = gameWorld.CreateBody (jumpPadDef); b2PolygonShape jumpPadShape = new b2PolygonShape (); jumpPadShape.SetAsBox ((float)this.ScaledContentSize.Width / PhysicsHandler.pixelPerMeter / 2, (float)this.ScaledContentSize.Height / PhysicsHandler.pixelPerMeter / 4);// /4 weil die hitbox nur die hälfte der textur ist b2FixtureDef jumpPadFixture = new b2FixtureDef (); jumpPadFixture.shape = jumpPadShape; jumpPadFixture.density = 0.0f; //Dichte jumpPadFixture.restitution = 0f; //Rückprall jumpPadFixture.friction = 0f; jumpPadFixture.userData = WorldFixtureData.jumppad; JumpPadBody.CreateFixture (jumpPadFixture); // }
public void Create(b2Body body, b2FixtureDef def) { m_userData = def.userData; m_friction = def.friction; m_restitution = def.restitution; m_body = body; Next = null; m_filter = def.filter; m_isSensor = def.isSensor; m_shape = def.shape.Clone(); // Reserve proxy space int childCount = m_shape.GetChildCount(); for (int i = 0; i < childCount; ++i) { b2FixtureProxy proxy = new b2FixtureProxy(); proxy.fixture = null; proxy.proxyId = b2BroadPhase.e_nullProxy; m_proxies.Add(proxy); } m_proxyCount = 0; m_density = def.density; }
public virtual b2Fixture CreateFixture(b2FixtureDef def) { if (m_world.IsLocked == true) { return(null); } b2Fixture fixture = new b2Fixture(); fixture.Create(this, def); if (m_flags.HasFlag(b2BodyFlags.e_activeFlag)) { b2BroadPhase broadPhase = m_world.ContactManager.BroadPhase; fixture.CreateProxies(broadPhase, m_xf); } fixture.Next = m_fixtureList; m_fixtureList = fixture; ++m_fixtureCount; fixture.Body = this; // Adjust mass properties if needed. if (fixture.Density > 0.0f) { ResetMassData(); } // Let the world know we have a new fixture. This will cause new contacts // to be created at the beginning of the next time step. m_world.Flags |= b2WorldFlags.e_newFixture; return(fixture); }
public virtual b2Fixture CreateFixture(b2Shape shape, float density) { b2FixtureDef def = b2FixtureDef.Create(); def.shape = shape; def.density = density; return(CreateFixture(def)); }
public SensorTest() { { b2BodyDef bd = new b2BodyDef(); b2Body ground = m_world.CreateBody(bd); { b2EdgeShape shape = new b2EdgeShape(); shape.Set(new b2Vec2(-40.0f, 0.0f), new b2Vec2(40.0f, 0.0f)); ground.CreateFixture(shape, 0.0f); } #if false { b2FixtureDef sd = new b2FixtureDef(); sd.SetAsBox(10.0f, 2.0f, new b2Vec2(0.0f, 20.0f), 0.0f); sd.isSensor = true; m_sensor = ground.CreateFixture(sd); } #else { b2CircleShape shape = new b2CircleShape(); shape.Radius = 5.0f; shape.Position = new b2Vec2(0.0f, 10.0f); b2FixtureDef fd = new b2FixtureDef(); fd.shape = shape; fd.isSensor = true; m_sensor = ground.CreateFixture(fd); } #endif } { b2CircleShape shape = new b2CircleShape(); shape.Radius = 1.0f; for (int i = 0; i < e_count; ++i) { b2BodyDef bd = new b2BodyDef(); bd.type = b2BodyType.b2_dynamicBody; bd.position.Set(-10.0f + 3.0f * i, 20.0f); bd.userData = i; // m_touching[i]; m_touching[i] = false; m_bodies[i] = m_world.CreateBody(bd); m_bodies[i].CreateFixture(shape, 1.0f); } } }
//public const int e_columnCount = 1; //public const int e_rowCount = 1; public VerticalStack() { { b2BodyDef bd = new b2BodyDef(); b2Body ground = m_world.CreateBody(bd); b2EdgeShape shape = new b2EdgeShape(); shape.Set(new b2Vec2(-40.0f, 0.0f), new b2Vec2(40.0f, 0.0f)); ground.CreateFixture(shape, 0.0f); shape.Set(new b2Vec2(20.0f, 0.0f), new b2Vec2(20.0f, 20.0f)); ground.CreateFixture(shape, 0.0f); } float[] xs = {0.0f, -10.0f, -5.0f, 5.0f, 10.0f}; for (int j = 0; j < e_columnCount; ++j) { b2PolygonShape shape = new b2PolygonShape(); shape.SetAsBox(0.5f, 0.5f); b2FixtureDef fd = new b2FixtureDef(); fd.shape = shape; fd.density = 1.0f; fd.friction = 0.3f; for (int i = 0; i < e_rowCount; ++i) { b2BodyDef bd = new b2BodyDef(); bd.type = b2BodyType.b2_dynamicBody; int n = j * e_rowCount + i; Debug.Assert(n < e_rowCount * e_columnCount); m_indices[n] = n; bd.userData = m_indices[n]; float x = 0.0f; //float32 x = RandomFloat(-0.02f, 0.02f); //float32 x = i % 2 == 0 ? -0.025f : 0.025f; bd.position.Set(xs[j] + x, 0.752f + 1.54f * i); b2Body body = m_world.CreateBody(bd); m_bodies[n] = body; body.CreateFixture(fd); } } m_bullet = null; }
public Confined() { { b2BodyDef bd = new b2BodyDef(); b2Body ground = m_world.CreateBody(bd); b2EdgeShape shape = new b2EdgeShape(); // Floor shape.Set(new b2Vec2(-10.0f, 0.0f), new b2Vec2(10.0f, 0.0f)); ground.CreateFixture(shape, 0.0f); // Left wall shape.Set(new b2Vec2(-10.0f, 0.0f), new b2Vec2(-10.0f, 20.0f)); ground.CreateFixture(shape, 0.0f); // Right wall shape.Set(new b2Vec2(10.0f, 0.0f), new b2Vec2(10.0f, 20.0f)); ground.CreateFixture(shape, 0.0f); // Roof shape.Set(new b2Vec2(-10.0f, 20.0f), new b2Vec2(10.0f, 20.0f)); ground.CreateFixture(shape, 0.0f); } float radius = 0.5f; b2CircleShape shape1 = new b2CircleShape(); shape1.Position = b2Vec2.Zero; shape1.Radius = radius; b2FixtureDef fd = new b2FixtureDef(); fd.shape = shape1; fd.density = 1.0f; fd.friction = 0.1f; for (int j = 0; j < e_columnCount; ++j) { for (int i = 0; i < e_rowCount; ++i) { b2BodyDef bd = new b2BodyDef(); bd.type = b2BodyType.b2_dynamicBody; bd.position.Set(-10.0f + (2.1f * j + 1.0f + 0.01f * i) * radius, (2.0f * i + 1.0f) * radius); b2Body body = m_world.CreateBody(bd); body.CreateFixture(fd); } } m_world.Gravity = new b2Vec2(0.0f, 0.0f); }
void CreatePlatform() { // Define the dynamic body. var bodyDef = new b2BodyDef(); bodyDef.type = b2BodyType.b2_staticBody; //or you could use b2_staticBody bodyDef.position.Set(initialLocation.X/Constants.PTM_RATIO, initialLocation.Y/Constants.PTM_RATIO); var shape = new b2PolygonShape(); var num = 4; b2Vec2[] vertices = { new b2Vec2(-102.0f / Constants.PTM_RATIO, -49.5f / Constants.PTM_RATIO), new b2Vec2(-113.0f / Constants.PTM_RATIO, -81.5f / Constants.PTM_RATIO), new b2Vec2(113.0f / Constants.PTM_RATIO, -84.5f / Constants.PTM_RATIO), new b2Vec2(106.0f / Constants.PTM_RATIO, -47.5f / Constants.PTM_RATIO) }; shape.Set(vertices, num); // Define the dynamic body fixture. var fixtureDef = new b2FixtureDef(); fixtureDef.shape = shape; fixtureDef.density = 1.0f; fixtureDef.friction = 0.3f; fixtureDef.restitution = 0.1f; CreateBodyWithSpriteAndFixture(theWorld, bodyDef, fixtureDef, spriteImageName); //CONTINUING TO ADD BODY SHAPE.... // THIS IS THE Sling base.... //row 1, col 1 var num2 = 4; b2Vec2[] vertices2 = { new b2Vec2(41.0f / Constants.PTM_RATIO, -6.5f / Constants.PTM_RATIO), new b2Vec2(35.0f / Constants.PTM_RATIO, -57.5f / Constants.PTM_RATIO), new b2Vec2(57.0f / Constants.PTM_RATIO, -65.5f / Constants.PTM_RATIO), new b2Vec2(49.0f / Constants.PTM_RATIO, -7.5f / Constants.PTM_RATIO) }; shape.Set(vertices2, num2); fixtureDef.shape = shape; body.CreateFixture(fixtureDef); }
protected void CreateBodyWithSpriteAndFixture(b2World world, b2BodyDef bodyDef, b2FixtureDef fixtureDef, string spriteName) { // this is the meat of our class, it creates (OR recreates) the body in the world with the body definition, fixture definition and sprite name RemoveBody(); //if remove the body if it already exists RemoveSprite(); //if remove the sprite if it already exists sprite = new CCSprite(spriteName); AddChild(sprite); body = world.CreateBody(bodyDef); body.UserData = this; if (fixtureDef != null) body.CreateFixture(fixtureDef); }
/** * the destructor cannot access the allocator (no destructor arguments allowed by C++). * We need separation create/destroy functions from the constructor/destructor because */ public void Create(b2Body body, b2Transform xf, b2FixtureDef def) { m_userData = def.userData; m_friction = def.friction; m_restitution = def.restitution; m_body = body; m_next = null; m_filter = def.filter.Copy(); m_isSensor = def.isSensor; m_shape = def.shape.Copy(); m_density = def.density; }
public Platform(List<CCPoint> platformWaypoints, int platformSpeed, Container gameContainer) { this.Texture = new CCTexture2D("platform"); this.Scale = SpriteScale; this.IsAntialiased = false; this.Position = platformWaypoints [0]; Waypoints = platformWaypoints; speed = platformSpeed; //umso geringer der speed umso schneller die platform CurrentWaypoint = 0; wayToMove = new CCSize (Waypoints [CurrentWaypoint + 1].X - Waypoints [CurrentWaypoint].X, Waypoints [CurrentWaypoint + 1].Y - Waypoints [CurrentWaypoint].Y); //box2d b2BodyDef platformDef = new b2BodyDef (); platformDef.type = b2BodyType.b2_kinematicBody; platformDef.position = new b2Vec2 (Waypoints[CurrentWaypoint].X / PhysicsHandler.pixelPerMeter, Waypoints[CurrentWaypoint].Y / PhysicsHandler.pixelPerMeter); platformBody = gameContainer.physicsHandler.gameWorld.CreateBody (platformDef); b2PolygonShape platformShape = new b2PolygonShape (); platformShape.SetAsBox ((float)this.ScaledContentSize.Width / PhysicsHandler.pixelPerMeter / 2, (float)this.ScaledContentSize.Height / PhysicsHandler.pixelPerMeter / 2); b2FixtureDef platformFixture = new b2FixtureDef (); platformFixture.shape = platformShape; platformFixture.density = 0.0f; //Dichte platformFixture.restitution = 0f; //Rückprall platformFixture.userData = WorldFixtureData.platform; platformBody.CreateFixture (platformFixture); // this.Position = new CCPoint (platformBody.Position.x * PhysicsHandler.pixelPerMeter, platformBody.Position.y * PhysicsHandler.pixelPerMeter); progressionX = wayToMove.Width/ (float)speed; progressionY = wayToMove.Height/(float)speed ; if (float.IsInfinity (progressionX)) progressionX = 0; if (float.IsInfinity (progressionY)) progressionY = 0; b2Vec2 Velocity = platformBody.LinearVelocity; Velocity.y = progressionY; Velocity.x = progressionX; platformBody.LinearVelocity = Velocity; }
private void CreateGround() { // Define the dynamic body. var bodyDef = new b2BodyDef(); bodyDef.type = b2BodyType.b2_staticBody; //or you could use b2_staticBody bodyDef.position.Set(initialLocation.X/Constants.PTM_RATIO, initialLocation.Y/Constants.PTM_RATIO); b2PolygonShape shape = new b2PolygonShape(); int num = 4; b2Vec2[] vertices = { new b2Vec2(-1220.0f / Constants.PTM_RATIO, 54.0f / Constants.PTM_RATIO), new b2Vec2(-1220.0f / Constants.PTM_RATIO, -52.0f / Constants.PTM_RATIO), new b2Vec2(1019.0f / Constants.PTM_RATIO, -52.0f / Constants.PTM_RATIO), new b2Vec2(1019.0f / Constants.PTM_RATIO, 54.0f / Constants.PTM_RATIO) }; shape.Set(vertices, num); // Define the dynamic body fixture. var fixtureDef = new b2FixtureDef(); fixtureDef.shape = shape; fixtureDef.density = 1.0f; fixtureDef.friction = 1.0f; fixtureDef.restitution = 0.1f; CreateBodyWithSpriteAndFixture(theWorld, bodyDef, fixtureDef, spriteImageName); if (!TheLevel.SharedLevel.IS_RETINA) { //non retina adjustment sprite.ScaleX = 1.05f; } else { // retina adjustment sprite.ScaleX = 2.05f; sprite.ScaleY = 2.0f; } }
public Chain() { b2Body ground = null; { b2BodyDef bd = new b2BodyDef(); ground = m_world.CreateBody(bd); b2EdgeShape shape = new b2EdgeShape(); shape.Set(new b2Vec2(-40.0f, 0.0f), new b2Vec2(40.0f, 0.0f)); ground.CreateFixture(shape, 0.0f); } { b2PolygonShape shape = new b2PolygonShape(); shape.SetAsBox(0.6f, 0.125f); b2FixtureDef fd = new b2FixtureDef(); fd.shape = shape; fd.density = 20.0f; fd.friction = 0.2f; b2RevoluteJointDef jd = new b2RevoluteJointDef(); jd.CollideConnected = false; const float y = 25.0f; b2Body prevBody = ground; for (int i = 0; i < 30; ++i) { b2BodyDef bd = new b2BodyDef(); bd.type = b2BodyType.b2_dynamicBody; bd.position.Set(0.5f + i, y); b2Body body = m_world.CreateBody(bd); body.CreateFixture(fd); b2Vec2 anchor = new b2Vec2(i, y); jd.Initialize(prevBody, body, anchor); m_world.CreateJoint(jd); prevBody = body; } } }
public void CreateCircle() { float radius = 2.0f; b2CircleShape shape = new b2CircleShape(); shape.Position = b2Vec2.Zero; shape.Radius = radius; b2FixtureDef fd = new b2FixtureDef(); fd.shape = shape; fd.density = 1.0f; fd.friction = 0.0f; b2Vec2 p = new b2Vec2(Rand.RandomFloat(), 3.0f + Rand.RandomFloat()); b2BodyDef bd = new b2BodyDef(); bd.type = b2BodyType.b2_dynamicBody; bd.position = p; //bd.allowSleep = false; b2Body body = m_world.CreateBody(bd); body.CreateFixture(fd); }
public BoxProp( b2World b2world, double[] size, double[] position ) { /* static rectangle shaped prop pars: size - array [width, height] position - array [x, y], in world meters, of center */ this.size = size; //initialize body var bdef = new b2BodyDef(); bdef.position = new b2Vec2(position[0], position[1]); bdef.angle = 0; bdef.fixedRotation = true; this.body = b2world.CreateBody(bdef); //initialize shape var fixdef = new b2FixtureDef(); var shape = new b2PolygonShape(); fixdef.shape = shape; shape.SetAsBox(this.size[0] / 2, this.size[1] / 2); fixdef.restitution = 0.4; //positively bouncy! this.body.CreateFixture(fixdef); }
/// <summary> /// ��һ���ڳ��������һ����̬��bird���� /// �ڶ�����bird�����ж��� /// ����������box-2d����������bird�����������з��� /// </summary> private void AddBird() { CCSprite bird = CCSprite.spriteWithFile("imgs/bird/bird_01"); bird.rotation = -15; // bird���ж���֡���� List<CCSpriteFrame> frames = new List<CCSpriteFrame>(); for (int i = 1; i < 3; i++) { // ֡��ͼ CCTexture2D texture = CCTextureCache.sharedTextureCache().addImage("imgs/bird/bird_0" + i); // �������һ�������bug����������õĻ����ͻᲥ�Ų��������� texture.Name = (uint)i; var frame = CCSpriteFrame.frameWithTexture(texture, new CCRect(0, 0, texture.ContentSizeInPixels.width, texture.ContentSizeInPixels.height)); frames.Add(frame); } // ���ж��� CCAnimation marmotShowanimation = CCAnimation.animationWithFrames(frames, 0.1f); CCAnimate flyAction = CCAnimate.actionWithAnimation(marmotShowanimation, false); flyRepeatAction = CCRepeat.actionWithAction(flyAction, 2); flyRepeatAction.tag = 0; bird.runAction(flyRepeatAction); // �����������ж���һ��body��������λ�ã�����bird��֮��Ӧ b2BodyDef ballBodyDef = new b2BodyDef(); ballBodyDef.type = b2BodyType.b2_dynamicBody; ballBodyDef.position = new b2Vec2(AppDelegate.screenSize.width / PTM_RATIO / 2, (float)(AppDelegate.screenSize.height / PTM_RATIO)); ballBodyDef.userData = bird; birdBody = world.CreateBody(ballBodyDef); // Ϊbody������״��������һЩ�������� b2PolygonShape shape = new b2PolygonShape(); shape.SetAsBox(bird.contentSize.width / 2 / PTM_RATIO, bird.contentSize.height / 2 / PTM_RATIO); b2FixtureDef fixtureDef = new b2FixtureDef(); fixtureDef.shape = shape; fixtureDef.density = 500.0f; fixtureDef.friction = 0.5f; birdBody.CreateFixture(fixtureDef); this.addChild(bird); }
public Dominos() { b2Body b1; { b2EdgeShape shape = new b2EdgeShape(); shape.Set(new b2Vec2(-40.0f, 0.0f), new b2Vec2(40.0f, 0.0f)); b2BodyDef bd = new b2BodyDef(); b1 = m_world.CreateBody(bd); b1.CreateFixture(shape, 0.0f); } { b2PolygonShape shape = new b2PolygonShape(); shape.SetAsBox(6.0f, 0.25f); b2BodyDef bd = new b2BodyDef(); bd.position.Set(-1.5f, 10.0f); b2Body ground = m_world.CreateBody(bd); ground.CreateFixture(shape, 0.0f); } { b2PolygonShape shape = new b2PolygonShape(); shape.SetAsBox(0.1f, 1.0f); b2FixtureDef fd = new b2FixtureDef(); fd.shape = shape; fd.density = 20.0f; fd.friction = 0.1f; for (int i = 0; i < 10; ++i) { b2BodyDef bd = new b2BodyDef(); bd.type = b2BodyType.b2_dynamicBody; bd.position.Set(-6.0f + 1.0f * i, 11.25f); b2Body body = m_world.CreateBody(bd); body.CreateFixture(fd); } } { b2PolygonShape shape = new b2PolygonShape(); shape.SetAsBox(7.0f, 0.25f, b2Vec2.Zero, 0.3f); b2BodyDef bd = new b2BodyDef(); bd.position.Set(1.0f, 6.0f); b2Body ground = m_world.CreateBody(bd); ground.CreateFixture(shape, 0.0f); } b2Body b2; { b2PolygonShape shape = new b2PolygonShape(); shape.SetAsBox(0.25f, 1.5f); b2BodyDef bd = new b2BodyDef(); bd.position.Set(-7.0f, 4.0f); b2 = m_world.CreateBody(bd); b2.CreateFixture(shape, 0.0f); } b2Body b3; { b2PolygonShape shape = new b2PolygonShape(); shape.SetAsBox(6.0f, 0.125f); b2BodyDef bd = new b2BodyDef(); bd.type = b2BodyType.b2_dynamicBody; bd.position.Set(-0.9f, 1.0f); bd.angle = -0.15f; b3 = m_world.CreateBody(bd); b3.CreateFixture(shape, 10.0f); } b2RevoluteJointDef jd = new b2RevoluteJointDef(); b2Vec2 anchor = new b2Vec2(); anchor.Set(-2.0f, 1.0f); jd.Initialize(b1, b3, anchor); jd.CollideConnected = true; m_world.CreateJoint(jd); b2Body b4; { b2PolygonShape shape = new b2PolygonShape(); shape.SetAsBox(0.25f, 0.25f); b2BodyDef bd = new b2BodyDef(); bd.type = b2BodyType.b2_dynamicBody; bd.position.Set(-10.0f, 15.0f); b4 = m_world.CreateBody(bd); b4.CreateFixture(shape, 10.0f); } anchor.Set(-7.0f, 15.0f); jd.Initialize(b2, b4, anchor); m_world.CreateJoint(jd); b2Body b5; { b2BodyDef bd = new b2BodyDef(); bd.type = b2BodyType.b2_dynamicBody; bd.position.Set(6.5f, 3.0f); b5 = m_world.CreateBody(bd); b2PolygonShape shape = new b2PolygonShape(); b2FixtureDef fd = new b2FixtureDef(); fd.shape = shape; fd.density = 10.0f; fd.friction = 0.1f; shape.SetAsBox(1.0f, 0.1f, new b2Vec2(0.0f, -0.9f), 0.0f); b5.CreateFixture(fd); shape.SetAsBox(0.1f, 1.0f, new b2Vec2(-0.9f, 0.0f), 0.0f); b5.CreateFixture(fd); shape.SetAsBox(0.1f, 1.0f, new b2Vec2(0.9f, 0.0f), 0.0f); b5.CreateFixture(fd); } anchor.Set(6.0f, 2.0f); jd.Initialize(b1, b5, anchor); m_world.CreateJoint(jd); b2Body b6; { b2PolygonShape shape = new b2PolygonShape(); shape.SetAsBox(1.0f, 0.1f); b2BodyDef bd = new b2BodyDef(); bd.type = b2BodyType.b2_dynamicBody; bd.position.Set(6.5f, 4.1f); b6 = m_world.CreateBody(bd); b6.CreateFixture(shape, 30.0f); } anchor.Set(7.5f, 4.0f); jd.Initialize(b5, b6, anchor); m_world.CreateJoint(jd); b2Body b7; { b2PolygonShape shape = new b2PolygonShape(); shape.SetAsBox(0.1f, 1.0f); b2BodyDef bd = new b2BodyDef(); bd.type = b2BodyType.b2_dynamicBody; bd.position.Set(7.4f, 1.0f); b7 = m_world.CreateBody(bd); b7.CreateFixture(shape, 10.0f); } b2DistanceJointDef djd = new b2DistanceJointDef(); djd.BodyA = b3; djd.BodyB = b7; djd.localAnchorA.Set(6.0f, 0.0f); djd.localAnchorB.Set(0.0f, -1.0f); b2Vec2 d = djd.BodyB.GetWorldPoint(djd.localAnchorB) - djd.BodyA.GetWorldPoint(djd.localAnchorA); djd.length = d.Length; m_world.CreateJoint(djd); { float radius = 0.2f; b2CircleShape shape = new b2CircleShape(); shape.Radius = radius; for (int i = 0; i < 4; ++i) { b2BodyDef bd = new b2BodyDef(); bd.type = b2BodyType.b2_dynamicBody; bd.position.Set(5.9f + 2.0f * radius * i, 2.4f); b2Body body = m_world.CreateBody(bd); body.CreateFixture(shape, 10.0f); } } }
/// <summary> /// ����ڵ��ϰ� /// </summary> /// <param name="interval"></param> private void AddBar(float interval) { int offset = new Random().Next(-160, 50); // upBar CCSprite upBar = CCSprite.spriteWithFile("imgs/bar/up_bar"); b2BodyDef upBarBodyDef = new b2BodyDef(); upBarBodyDef.position = new b2Vec2(AppDelegate.screenSize.width / PTM_RATIO, (AppDelegate.screenSize.height + offset + 80) / PTM_RATIO); upBarBodyDef.userData = upBar; // ��������Ӱ�죬�������ٶ� upBarBodyDef.type = b2BodyType.b2_kinematicBody; b2Body upBarBody = world.CreateBody(upBarBodyDef); b2PolygonShape upBarBox = new b2PolygonShape(); b2FixtureDef boxShapeDef = new b2FixtureDef(); boxShapeDef.shape = upBarBox; upBarBox.SetAsBox(upBar.contentSize.width / PTM_RATIO / 2, upBar.contentSize.height / PTM_RATIO / 2); upBarBody.LinearVelocity = new b2Vec2(-flySpeed, 0); upBarBody.CreateFixture(boxShapeDef); barLayer.addChild(upBar); if (upBars == null) { upBars = new Queue<CCSprite>(); } // ���²����Ķ�����뵽������ upBars.Enqueue(upBar); // downBar CCSprite downBar = CCSprite.spriteWithFile("imgs/bar/down_bar"); b2BodyDef downBarBodyDef = new b2BodyDef(); downBarBodyDef.position = new b2Vec2(AppDelegate.screenSize.width / PTM_RATIO, (downBar.contentSize.height + offset * 2 - 80) / 2 / PTM_RATIO); downBarBodyDef.userData = downBar; downBarBodyDef.type = b2BodyType.b2_kinematicBody; b2Body downBarBody = world.CreateBody(downBarBodyDef); b2PolygonShape downBarBox = new b2PolygonShape(); b2FixtureDef shapeDef = new b2FixtureDef(); shapeDef.shape = downBarBox; downBarBox.SetAsBox(downBar.contentSize.width / PTM_RATIO / 2, downBar.contentSize.height / PTM_RATIO / 2); downBarBody.LinearVelocity = new b2Vec2(-flySpeed, 0); downBarBody.CreateFixture(shapeDef); barLayer.addChild(downBar); }
public Car() { m_hz = 4.0f; m_zeta = 0.7f; m_speed = 50.0f; b2Body ground = null; { b2BodyDef bd = new b2BodyDef(); ground = m_world.CreateBody(bd); b2EdgeShape shape = new b2EdgeShape(); b2FixtureDef fd = new b2FixtureDef(); fd.shape = shape; fd.density = 0.0f; fd.friction = 0.6f; shape.Set(new b2Vec2(-20.0f, 0.0f), new b2Vec2(20.0f, 0.0f)); ground.CreateFixture(fd); float[] hs = {0.25f, 1.0f, 4.0f, 0.0f, 0.0f, -1.0f, -2.0f, -2.0f, -1.25f, 0.0f}; float x = 20.0f, y1 = 0.0f, dx = 5.0f; for (int i = 0; i < 10; ++i) { float y2 = hs[i]; shape.Set(new b2Vec2(x, y1), new b2Vec2(x + dx, y2)); ground.CreateFixture(fd); y1 = y2; x += dx; } for (int i = 0; i < 10; ++i) { float y2 = hs[i]; shape.Set(new b2Vec2(x, y1), new b2Vec2(x + dx, y2)); ground.CreateFixture(fd); y1 = y2; x += dx; } shape.Set(new b2Vec2(x, 0.0f), new b2Vec2(x + 40.0f, 0.0f)); ground.CreateFixture(fd); x += 80.0f; shape.Set(new b2Vec2(x, 0.0f), new b2Vec2(x + 40.0f, 0.0f)); ground.CreateFixture(fd); x += 40.0f; shape.Set(new b2Vec2(x, 0.0f), new b2Vec2(x + 10.0f, 5.0f)); ground.CreateFixture(fd); x += 20.0f; shape.Set(new b2Vec2(x, 0.0f), new b2Vec2(x + 40.0f, 0.0f)); ground.CreateFixture(fd); x += 40.0f; shape.Set(new b2Vec2(x, 0.0f), new b2Vec2(x, 20.0f)); ground.CreateFixture(fd); } // Teeter { b2BodyDef bd = new b2BodyDef(); bd.position.Set(140.0f, 1.0f); bd.type = b2BodyType.b2_dynamicBody; b2Body body = m_world.CreateBody(bd); b2PolygonShape box = new b2PolygonShape(); box.SetAsBox(10.0f, 0.25f); body.CreateFixture(box, 1.0f); b2RevoluteJointDef jd = new b2RevoluteJointDef(); jd.Initialize(ground, body, body.Position); jd.lowerAngle = -8.0f * b2Settings.b2_pi / 180.0f; jd.upperAngle = 8.0f * b2Settings.b2_pi / 180.0f; jd.enableLimit = true; m_world.CreateJoint(jd); body.ApplyAngularImpulse(100.0f); } // Bridge { int N = 20; b2PolygonShape shape = new b2PolygonShape(); shape.SetAsBox(1.0f, 0.125f); b2FixtureDef fd = new b2FixtureDef(); fd.shape = shape; fd.density = 1.0f; fd.friction = 0.6f; b2RevoluteJointDef jd = new b2RevoluteJointDef(); b2Body prevBody = ground; for (int i = 0; i < N; ++i) { b2BodyDef bd = new b2BodyDef(); bd.type = b2BodyType.b2_dynamicBody; bd.position.Set(161.0f + 2.0f * i, -0.125f); b2Body body = m_world.CreateBody(bd); body.CreateFixture(fd); b2Vec2 anchor = new b2Vec2(160.0f + 2.0f * i, -0.125f); jd.Initialize(prevBody, body, anchor); m_world.CreateJoint(jd); prevBody = body; } b2Vec2 anchor1 = new b2Vec2(160.0f + 2.0f * N, -0.125f); jd.Initialize(prevBody, ground, anchor1); m_world.CreateJoint(jd); } // Boxes { b2PolygonShape box = new b2PolygonShape(); box.SetAsBox(0.5f, 0.5f); b2Body body = null; b2BodyDef bd = new b2BodyDef(); bd.type = b2BodyType.b2_dynamicBody; bd.position.Set(230.0f, 0.5f); body = m_world.CreateBody(bd); body.CreateFixture(box, 0.5f); bd.position.Set(230.0f, 1.5f); body = m_world.CreateBody(bd); body.CreateFixture(box, 0.5f); bd.position.Set(230.0f, 2.5f); body = m_world.CreateBody(bd); body.CreateFixture(box, 0.5f); bd.position.Set(230.0f, 3.5f); body = m_world.CreateBody(bd); body.CreateFixture(box, 0.5f); bd.position.Set(230.0f, 4.5f); body = m_world.CreateBody(bd); body.CreateFixture(box, 0.5f); } // Car { b2PolygonShape chassis = new b2PolygonShape(); b2Vec2[] vertices = new b2Vec2[8]; vertices[0].Set(-1.5f, -0.5f); vertices[1].Set(1.5f, -0.5f); vertices[2].Set(1.5f, 0.0f); vertices[3].Set(0.0f, 0.9f); vertices[4].Set(-1.15f, 0.9f); vertices[5].Set(-1.5f, 0.2f); chassis.Set(vertices, 6); b2CircleShape circle = new b2CircleShape(); circle.Radius = 0.4f; b2BodyDef bd = new b2BodyDef(); bd.type = b2BodyType.b2_dynamicBody; bd.position.Set(0.0f, 1.0f); m_car = m_world.CreateBody(bd); m_car.CreateFixture(chassis, 1.0f); b2FixtureDef fd = new b2FixtureDef(); fd.shape = circle; fd.density = 1.0f; fd.friction = 0.9f; bd.position.Set(-1.0f, 0.35f); m_wheel1 = m_world.CreateBody(bd); m_wheel1.CreateFixture(fd); bd.position.Set(1.0f, 0.4f); m_wheel2 = m_world.CreateBody(bd); m_wheel2.CreateFixture(fd); b2WheelJointDef jd = new b2WheelJointDef(); b2Vec2 axis = new b2Vec2(0.0f, 1.0f); jd.Initialize(m_car, m_wheel1, m_wheel1.Position, axis); jd.motorSpeed = 0.0f; jd.maxMotorTorque = 20.0f; jd.enableMotor = true; jd.frequencyHz = m_hz; jd.dampingRatio = m_zeta; m_spring1 = (b2WheelJoint) m_world.CreateJoint(jd); jd.Initialize(m_car, m_wheel2, m_wheel2.Position, axis); jd.motorSpeed = 0.0f; jd.maxMotorTorque = 10.0f; jd.enableMotor = false; jd.frequencyHz = m_hz; jd.dampingRatio = m_zeta; m_spring2 = (b2WheelJoint) m_world.CreateJoint(jd); } }
public PhysicalRocket( StarlingGameSpriteWithRocketTextures textures_rocket, StarlingGameSpriteWithPhysics Context, bool issmoke = false, Image Explosion1 = null ) { this.issmoke = issmoke; this.Context = Context; this.textures_rocket = textures_rocket; this.CurrentInput = new KeySample(); visual = new Image(textures_rocket.rocket1()); visual.AttachTo(Context.Content); //this.CameraRotation = Math.PI / 2; #region smoke_b2world { var bodyDef = new b2BodyDef(); bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody; // stop moving if legs stop walking! bodyDef.linearDamping = 0; bodyDef.angularDamping = 6; //bodyDef.angle = 1.57079633; //bodyDef.fixedRotation = true; if (issmoke) { body = Context.smoke_b2world.CreateBody(bodyDef); } else { body = Context.damage_b2world.CreateBody(bodyDef); } var fixDef = new Box2D.Dynamics.b2FixtureDef(); fixDef.density = 0.1; fixDef.friction = 0.0; fixDef.restitution = 0; fixDef.shape = new Box2D.Collision.Shapes.b2CircleShape(0.5); // var fix = body.CreateFixture(fixDef); var fix_data = new Action <double>( jeep_forceA => { this.body.SetActive(false); this.visual.visible = false; // explode? this.speed = 0; this.CurrentInput = new KeySample(); Context.CreateExplosion( this.body.GetPosition().x, this.body.GetPosition().y ); } ); // this does NOT work! fix.SetUserData(fix_data); } #endregion Context.internalunits.Add(this); }
public PhysicalPed(StarlingGameSpriteWithPedTextures textures, StarlingGameSpriteWithPhysics Context) { this.CurrentInput = new KeySample(); this.textures = textures; this.Context = Context; for (int i = 0; i < 7; i++) { this.KarmaInput0.Enqueue( new KeySample() ); } visual = new VisualPed(textures, Context, AnimateSeed: Context.random.Next() % 3000 ); #region b2world { var bodyDef = new b2BodyDef(); bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody; // stop moving if legs stop walking! bodyDef.linearDamping = 0; bodyDef.angularDamping = 6; //bodyDef.angle = 1.57079633; //bodyDef.fixedRotation = true; body = Context.ground_b2world.CreateBody(bodyDef); var fixDef = new Box2D.Dynamics.b2FixtureDef(); fixDef.density = 0.1; fixDef.friction = 0.0; fixDef.restitution = 0; fixDef.shape = new Box2D.Collision.Shapes.b2CircleShape(1.0); var fix = body.CreateFixture(fixDef); var fix_data = new Action <double>( zombie_forceA => { if (zombie_forceA < 1) { return; } // zombie runs against a building if (zombie_forceA > 3.6) { if (visual.WalkLikeZombie) { Console.WriteLine(new { zombie_forceA }); this.body.SetActive(false); this.damagebody.SetActive(false); this.visual.LayOnTheGround = true; this.SetVelocityFromInput(new KeySample()); } } if (oncollision != null) { oncollision(this, zombie_forceA); } } ); fix.SetUserData(fix_data); } #endregion #region groundkarma_b2world { var bodyDef = new b2BodyDef(); bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody; // stop moving if legs stop walking! bodyDef.linearDamping = 0; bodyDef.angularDamping = 6; //bodyDef.angle = 1.57079633; //bodyDef.fixedRotation = true; karmabody = Context.groundkarma_b2world.CreateBody(bodyDef); var fixDef = new Box2D.Dynamics.b2FixtureDef(); fixDef.density = 0.1; fixDef.friction = 0.0; fixDef.restitution = 0; fixDef.shape = new Box2D.Collision.Shapes.b2CircleShape(1.0); var fix = karmabody.CreateFixture(fixDef); } #endregion #region damage_b2world { var bodyDef = new b2BodyDef(); bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody; // stop moving if legs stop walking! bodyDef.linearDamping = 0; bodyDef.angularDamping = 6; //bodyDef.angle = 1.57079633; //bodyDef.fixedRotation = true; damagebody = Context.damage_b2world.CreateBody(bodyDef); var fixDef = new Box2D.Dynamics.b2FixtureDef(); fixDef.density = 0.1; fixDef.friction = 0.0; fixDef.restitution = 0; fixDef.shape = new Box2D.Collision.Shapes.b2CircleShape(1.0); var fix = damagebody.CreateFixture(fixDef); var fix_data = new Action <double>( jeep_forceA => { if (jeep_forceA < 0.5) { return; } if (visual.WalkLikeZombie) { this.body.SetActive(false); this.damagebody.SetActive(false); this.visual.LayOnTheGround = true; this.SetVelocityFromInput(new KeySample()); } //if (jeep_forceA < 1) // return; //if (oncollision != null) // oncollision(this, jeep_forceA); } ); fix.SetUserData(fix_data); } #endregion Context.internalunits.Add(this); }
public StarlingGameSpriteWithHindControl() { // how much bigger are units in flight altidude? var textures_hind = new StarlingGameSpriteWithHindTextures(this.new_tex_crop); this.onbeforefirstframe += (stage, s) => { var physical0 = new PhysicalHind(textures_hind, this); for (int ix = 0; ix < 32; ix++) { var physical1 = new PhysicalHind(textures_hind, this); var physical2 = new PhysicalHind(textures_hind, this); var physical3 = new PhysicalHind(textures_hind, this); physical1.SetPositionAndAngle(10 + 20 * ix, 20); physical2.visual.Altitude = 1.0; physical2.SetPositionAndAngle(20 + 20 * ix, 40); physical3.visual.Altitude = 0.5; physical3.SetPositionAndAngle(30 + 20 * ix, 60); } bool mode_changepending = false; //bool visual0_flightmode = false; #region __keyDown stage.keyDown += e => { // http://circlecube.com/2008/08/actionscript-key-listener-tutorial/ if (e.altKey) { __keyDown[System.Windows.Forms.Keys.Alt] = true; } __keyDown[(System.Windows.Forms.Keys)e.keyCode] = true; }; stage.keyUp += e => { if (!e.altKey) { __keyDown[System.Windows.Forms.Keys.Alt] = false; } __keyDown[(System.Windows.Forms.Keys)e.keyCode] = false; }; #endregion this.current = physical0; // http://doc.starling-framework.org/core/starling/filters/ColorMatrixFilter.html // create an inverted filter with 50% saturation and 180° hue rotation var filter = new ColorMatrixFilter(); filter.adjustSaturation(-1.0); filter.invert(); filter.adjustContrast(0.5); this.filter = filter; this.stage.color = 0x808080; onsyncframe += delegate { #region mode if (!__keyDown[System.Windows.Forms.Keys.Space]) { // space is not down. mode_changepending = true; } else { if (mode_changepending) { (current as PhysicalHind).With( hind1 => { if (hind1.visual.Altitude == 0) { hind1.VerticalVelocity = 1.0; } else { hind1.VerticalVelocity = -0.4; } } ); mode_changepending = false; } } #endregion // for camera current.SetVelocityFromInput(__keyDown); #region simulate a weapone! if (__keyDown[System.Windows.Forms.Keys.ControlKey]) { if (frameid % 20 == 0) { var bodyDef = new b2BodyDef(); bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody; // stop moving if legs stop walking! bodyDef.linearDamping = 0; bodyDef.angularDamping = 0; //bodyDef.angle = 1.57079633; bodyDef.fixedRotation = true; var body = physical0.body.GetWorld().CreateBody(bodyDef); body.SetPosition( new b2Vec2( current.body.GetPosition().x + 2, current.body.GetPosition().y + 2 ) ); body.SetLinearVelocity( new b2Vec2( 100, 100 ) ); var fixDef = new Box2D.Dynamics.b2FixtureDef(); fixDef.density = 0.1; fixDef.friction = 0.01; fixDef.restitution = 0; fixDef.shape = new Box2D.Collision.Shapes.b2CircleShape(1.0); var fix = body.CreateFixture(fixDef); //body.SetPosition( // new b2Vec2(0, -100 * 16) //); } } #endregion }; }; }
public PhysicalBarrel(StarlingGameSpriteWithBunkerTextures textures, StarlingGameSpriteWithPhysics Context) { this.CurrentInput = new KeySample(); // hide in a barrel? //this.driverseat = new DriverSeat(); this.textures = textures; this.Context = Context; //for (int i = 0; i < 7; i++) //{ // this.KarmaInput0.Enqueue( // new KeySample() // ); //} visualshadow = new Image( textures.barrel1_shadow() ).AttachTo(Context.Content_layer2_shadows); visual = new Image( textures.barrel1() ).AttachTo(Context.Content_layer3_buildings); { //initialize body var bdef = new b2BodyDef(); bdef.type = Box2D.Dynamics.b2Body.b2_dynamicBody; bdef.linearDamping = 8.0; bdef.angularDamping = 8; bdef.angle = 0; this.body = Context.ground_b2world.CreateBody(bdef); //initialize shape var fixdef = new b2FixtureDef(); fixdef.density = 1; fixdef.friction = 0.01; //fixdef.restitution = 0.4; //positively bouncy! var shape = new b2PolygonShape(); fixdef.shape = shape; shape.SetAsBox(1.6, 1); var fix = this.body.CreateFixture(fixdef); var fix_data = new Action<double>( jeep_forceA => { if (jeep_forceA < 1) return; if (oncollision != null) oncollision(this, jeep_forceA); } ); fix.SetUserData(fix_data); } { //initialize body var bdef = new b2BodyDef(); bdef.type = Box2D.Dynamics.b2Body.b2_dynamicBody; bdef.linearDamping = 8.0; bdef.angularDamping = 8; bdef.angle = 0; this.karmabody = Context.groundkarma_b2world.CreateBody(bdef); //initialize shape var fixdef = new b2FixtureDef(); fixdef.density = 1; fixdef.friction = 0.01; //fixdef.restitution = 0.4; //positively bouncy! var shape = new b2PolygonShape(); fixdef.shape = shape; shape.SetAsBox(1.6, 1); this.karmabody.CreateFixture(fixdef); } Context.internalunits.Add(this); }
public PhysicalHind(StarlingGameSpriteWithHindTextures textures, StarlingGameSpriteWithPhysics Context) { this.CurrentInput = new KeySample(); this.driverseat = new DriverSeat(); this.Context = Context; visual = new VisualHind(textures, Context.Content, Context.airzoom); for (int i = 0; i < 7; i++) { this.KarmaInput0.Enqueue( new KeySample() ); } #region ground_b2world ground_current { var ground_bodyDef = new b2BodyDef(); ground_bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody; // stop moving if legs stop walking! ground_bodyDef.linearDamping = 10.0; ground_bodyDef.angularDamping = 4; //bodyDef.angle = 1.57079633; //ground_bodyDef.fixedRotation = true; ground_body = Context.ground_b2world.CreateBody(ground_bodyDef); var ground_fixDef = new Box2D.Dynamics.b2FixtureDef(); ground_fixDef.density = 0.1; ground_fixDef.friction = 0.01; ground_fixDef.restitution = 0; var ground_fixdef_shape = new b2PolygonShape(); ground_fixDef.shape = ground_fixdef_shape; // physics unit is looking to right ground_fixdef_shape.SetAsBox(2, 0.5); var ground_fix = ground_body.CreateFixture(ground_fixDef); } #endregion #region groundkarma_body { var ground_bodyDef = new b2BodyDef(); ground_bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody; // stop moving if legs stop walking! ground_bodyDef.linearDamping = 10.0; ground_bodyDef.angularDamping = 4; //bodyDef.angle = 1.57079633; //ground_bodyDef.fixedRotation = true; groundkarma_body = Context.groundkarma_b2world.CreateBody(ground_bodyDef); var ground_fixDef = new Box2D.Dynamics.b2FixtureDef(); ground_fixDef.density = 0.1; ground_fixDef.friction = 0.01; ground_fixDef.restitution = 0; var ground_fixdef_shape = new b2PolygonShape(); ground_fixDef.shape = ground_fixdef_shape; // physics unit is looking to right ground_fixdef_shape.SetAsBox(2, 0.5); var ground_fix = groundkarma_body.CreateFixture(ground_fixDef); } #endregion #region air_b2world air_current { var air_bodyDef = new b2BodyDef(); air_bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody; // stop moving if legs stop walking! air_bodyDef.linearDamping = 10.0; air_bodyDef.angularDamping = 4; //bodyDef.angle = 1.57079633; //air_bodyDef.fixedRotation = true; air_bodyDef.active = false; air_body = Context.air_b2world.CreateBody(air_bodyDef); var air_fixDef = new Box2D.Dynamics.b2FixtureDef(); air_fixDef.density = 0.1; air_fixDef.friction = 0.01; air_fixDef.restitution = 0; var air_fixdef_shape = new b2PolygonShape(); air_fixDef.shape = air_fixdef_shape; // physics unit is looking to right air_fixdef_shape.SetAsBox(2, 0.5); var air_fix = air_body.CreateFixture(air_fixDef); } #endregion #region smoke_b2world { var bodyDef = new b2BodyDef(); bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody; // stop moving if legs stop walking! bodyDef.linearDamping = 0; bodyDef.angularDamping = 6; //bodyDef.angle = 1.57079633; //bodyDef.fixedRotation = true; damage_body = Context.damage_b2world.CreateBody(bodyDef); //body = Context.ground_b2world.CreateBody(bodyDef); var fixDef = new Box2D.Dynamics.b2FixtureDef(); fixDef.density = 0.1; fixDef.friction = 0.0; fixDef.restitution = 0; fixDef.shape = new Box2D.Collision.Shapes.b2CircleShape(2); // var fix = damage_body.CreateFixture(fixDef); //var fix_data = new Action<double>( // jeep_forceA => // { // if (jeep_forceA < 1) // return; // if (Context.oncollision != null) // Context.oncollision(this, jeep_forceA); // } //); //fix.SetUserData(fix_data); } #endregion ApplyVelocityElapsed = Context.gametime.ElapsedMilliseconds; Context.internalunits.Add(this); }
public StarlingGameSpriteWithPedSync() { var textures_ped = new StarlingGameSpriteWithPedTextures(new_tex_crop, new_texsprite_crop); this.onbeforefirstframe += (stage, s) => { #region :ego var ego = new PhysicalPed(textures_ped, this) { Identity = sessionid + ":ego" }; ego.SetPositionAndAngle( random.NextDouble() * -8, random.NextDouble() * -8, random.NextDouble() * Math.PI ); current = ego; #endregion // 32x32 = 15FPS? // 24x24 35? #region others for (int ix = 2; ix < 4; ix++) { for (int iy = 2; iy < 4; iy++) { var p = new PhysicalPed(textures_ped, this); p.SetPositionAndAngle( 8 * ix, 8 * iy ); } } #endregion #region KeySample var __keyDown = new KeySample(); stage.keyDown += e => { // http://circlecube.com/2008/08/actionscript-key-listener-tutorial/ if (e.altKey) { __keyDown[Keys.Alt] = true; } __keyDown[(Keys)e.keyCode] = true; }; stage.keyUp += e => { if (!e.altKey) { __keyDown[Keys.Alt] = false; } __keyDown[(Keys)e.keyCode] = false; }; #endregion #region other Func <string, RemoteGame> other = __egoid => { // that other game has sent us a sync frame! var already_known_other = others.FirstOrDefault(k => k.__egoid == __egoid); if (already_known_other == null) { already_known_other = new RemoteGame { __egoid = __egoid, // this __syncframeid = this.syncframeid }; others.Add(already_known_other); } return(already_known_other); }; #endregion #region __at_sync __at_sync += __egoid => { // that other game has sent us a sync frame! var o = other(__egoid); o.__syncframeid++; // move on! }; #endregion #region __at_SetVelocityFromInput __at_SetVelocityFromInput += ( string __egoid, string __identity, string __KeySample, string __fixup_x, string __fixup_y, string __fixup_angle ) => { var o = other(__egoid); if (o.ego == null) { o.ego = new PhysicalPed(textures_ped, this) { Identity = __identity, RemoteGameReference = o }; o.ego.SetPositionAndAngle( double.Parse(__fixup_x), double.Parse(__fixup_y), double.Parse(__fixup_angle) ); } // set the input! o.ego.SetVelocityFromInput( new KeySample { value = int.Parse(__KeySample), fixup = true, x = double.Parse(__fixup_x), y = double.Parse(__fixup_y), angle = double.Parse(__fixup_angle) } ); }; #endregion bool mode_changepending = false; onsyncframe += delegate { // sync me! // tell others in the session about our game // a beacon #region simulate a weapone! if (__keyDown[Keys.ControlKey]) { if (frameid % 20 == 0) { var bodyDef = new b2BodyDef(); bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody; // stop moving if legs stop walking! bodyDef.linearDamping = 0; bodyDef.angularDamping = 0; //bodyDef.angle = 1.57079633; bodyDef.fixedRotation = true; var body = ground_b2world.CreateBody(bodyDef); body.SetPosition( new b2Vec2( current.body.GetPosition().x + 2, current.body.GetPosition().y + 2 ) ); body.SetLinearVelocity( new b2Vec2( 100, 100 ) ); var fixDef = new Box2D.Dynamics.b2FixtureDef(); fixDef.density = 0.1; fixDef.friction = 0.01; fixDef.restitution = 0; fixDef.shape = new Box2D.Collision.Shapes.b2CircleShape(1.0); var fix = body.CreateFixture(fixDef); //body.SetPosition( // new b2Vec2(0, -100 * 16) //); } } #endregion #region mode if (!__keyDown[Keys.Space]) { // space is not down. mode_changepending = true; } else { if (mode_changepending) { if (ego.visual.LayOnTheGround) { ego.visual.LayOnTheGround = false; } else { ego.visual.LayOnTheGround = true; } mode_changepending = false; } } #endregion ego.SetVelocityFromInput(__keyDown); __raise_SetVelocityFromInput( "" + sessionid, ego.Identity, "" + ego.CurrentInput.value, "" + ego.body.GetPosition().x, "" + ego.body.GetPosition().y, "" + ego.body.GetAngle() ); // tell others this sync frame ended for us __raise_sync("" + sessionid); }; }; }
public void Create(b2Body body, b2FixtureDef def) { m_userData = def.userData; m_friction = def.friction; m_restitution = def.restitution; m_body = body; Next = null; m_filter = def.filter; m_isSensor = def.isSensor; m_shape = def.shape.Clone(); // Reserve proxy space int childCount = m_shape.GetChildCount(); for (int i = 0; i < childCount; ++i) { b2FixtureProxy proxy = new b2FixtureProxy(); proxy.fixture = null; proxy.proxyId = b2BroadPhase.e_nullProxy; m_proxies.Add(proxy); } m_proxyCount = 0; m_density = def.density; }
public virtual b2Fixture CreateFixture(b2FixtureDef def) { if (m_world.IsLocked == true) { return null; } b2Fixture fixture = new b2Fixture(); fixture.Create(this, def); if (m_flags.HasFlag(b2BodyFlags.e_activeFlag)) { b2BroadPhase broadPhase = m_world.ContactManager.BroadPhase; fixture.CreateProxies(broadPhase, m_xf); } fixture.Next = m_fixtureList; m_fixtureList = fixture; ++m_fixtureCount; fixture.Body = this; // Adjust mass properties if needed. if (fixture.Density > 0.0f) { ResetMassData(); } // Let the world know we have a new fixture. This will cause new contacts // to be created at the beginning of the next time step. m_world.Flags |= b2WorldFlags.e_newFixture; return fixture; }
// http://blog.allanbishop.com/box2d-2-1a-tutorial-part-1/ public ApplicationSprite() { _world = new b2World(new b2Vec2(0, 10), true); var groundBodyDef = new b2BodyDef(); groundBodyDef.position.Set(SWF_HALF_WIDTH / PIXELS_TO_METRE, SWF_HEIGHT / PIXELS_TO_METRE - 20 / PIXELS_TO_METRE); var groundBody = _world.CreateBody(groundBodyDef); var groundBox = new b2PolygonShape(); groundBox.SetAsBox(SWF_HALF_WIDTH / PIXELS_TO_METRE, 20 / PIXELS_TO_METRE); var groundFixtureDef = new b2FixtureDef(); groundFixtureDef.shape = groundBox; groundFixtureDef.density = 1; groundFixtureDef.friction = 1; groundBody.CreateFixture(groundFixtureDef); var bodyDef = new b2BodyDef(); bodyDef.type = b2Body.b2_dynamicBody; bodyDef.position.Set(SWF_HALF_WIDTH / PIXELS_TO_METRE, 4); var body = _world.CreateBody(bodyDef); var dynamicBox = new b2PolygonShape(); dynamicBox.SetAsBox(1, 1); var fixtureDef = new b2FixtureDef(); fixtureDef.shape = dynamicBox; fixtureDef.density = 1; fixtureDef.friction = 0.3; body.CreateFixture(fixtureDef); var debugSprite = new Sprite(); addChild(debugSprite); var debugDraw = new b2DebugDraw(); debugDraw.SetSprite(debugSprite); debugDraw.SetDrawScale(PIXELS_TO_METRE); debugDraw.SetLineThickness(1.0); debugDraw.SetAlpha(1); debugDraw.SetFillAlpha(0.4); debugDraw.SetFlags(b2DebugDraw.e_shapeBit); _world.SetDebugDraw(debugDraw); // Add event for main loop this.stage.enterFrame += delegate { var timeStep = 1 / 30.0; var velocityIterations = 6; var positionIterations = 2; _world.Step(timeStep, velocityIterations, positionIterations); _world.ClearForces(); _world.DrawDebugData(); }; }
public void LaunchBomb(b2Vec2 position, b2Vec2 velocity) { if (m_bomb != null) { m_world.DestroyBody(m_bomb); m_bomb = null; } b2BodyDef bd = new b2BodyDef(); bd.type = b2BodyType.b2_dynamicBody; bd.position = position; bd.bullet = true; m_bomb = m_world.CreateBody(bd); m_bomb.LinearVelocity = velocity; b2CircleShape circle = new b2CircleShape(); circle.Radius = 0.3f; b2FixtureDef fd = new b2FixtureDef(); fd.shape = circle; fd.density = 20.0f; fd.restitution = 0.0f; b2Vec2 minV = position - new b2Vec2(0.3f, 0.3f); b2Vec2 maxV = position + new b2Vec2(0.3f, 0.3f); b2AABB aabb = new b2AABB(); aabb.LowerBound = minV; aabb.UpperBound = maxV; m_bomb.CreateFixture(fd); }
/// <summary> /// ��һ����ӵ��� /// �ڶ�������box-2d�������潫������Ϊ��̬������ӵ����������� /// </summary> private void AddGround() { ground = CCSprite.spriteWithFile("imgs/ground/ground"); ground.position = new CCPoint(ground.contentSize.width / 2, ground.contentSize.height / 2); b2BodyDef groundBodyDef = new b2BodyDef(); groundBodyDef.position = new b2Vec2(ground.contentSize.width / PTM_RATIO / 2, ground.contentSize.height / PTM_RATIO / 2); groundBodyDef.userData = ground; // ��������Ӱ�죬�����˶� groundBodyDef.type = b2BodyType.b2_staticBody; // ����ground���˶���ʹ���ٶ���bird�ķ����ٶ�һ�� var action1 = CCMoveTo.actionWithDuration(ground.contentSize.width / (4 * PTM_RATIO * flySpeed), new CCPoint(ground.contentSize.width / 4, ground.position.y)); var action2 = CCMoveTo.actionWithDuration(0, new CCPoint(ground.contentSize.width / 2, ground.position.y)); var action = CCSequence.actionOneTwo(action1, action2); var repeatAction = CCRepeatForever.actionWithAction(action); repeatAction.tag = 0; ground.runAction(repeatAction); b2Body groundBody = world.CreateBody(groundBodyDef); b2PolygonShape groundBox = new b2PolygonShape(); b2FixtureDef boxShapeDef = new b2FixtureDef(); boxShapeDef.shape = groundBox; groundBox.SetAsBox(ground.contentSize.width / PTM_RATIO / 2, ground.contentSize.height / PTM_RATIO / 2); groundBody.CreateFixture(boxShapeDef); this.addChild(ground); }
void AddBall() { if (ballsBatch.ChildrenCount < MAX_NUM_BALLS) { int idx = (CCRandom.Float_0_1 () > .5 ? 0 : 1); int idy = (CCRandom.Float_0_1 () > .5 ? 0 : 1); var sprite = new CCPhysicsSprite (ballTexture, new CCRect (32 * idx, 32 * idy, 32, 32), PTM_RATIO); ballsBatch.AddChild (sprite); CCPoint p = GetRandomPosition (sprite.ContentSize); sprite.Position = new CCPoint (p.X, p.Y); var def = new b2BodyDef (); def.position = new b2Vec2 (p.X / PTM_RATIO, p.Y / PTM_RATIO); def.linearVelocity = new b2Vec2 (0.0f, -1.0f); def.type = b2BodyType.b2_dynamicBody; b2Body body = world.CreateBody (def); var circle = new b2CircleShape (); circle.Radius = 0.5f; var fd = new b2FixtureDef (); fd.shape = circle; fd.density = 1f; fd.restitution = 0.85f; fd.friction = 0f; body.CreateFixture (fd); sprite.PhysicsBody = body; } }
private void Create(int index) { if (m_bodies[m_bodyIndex] != null) { m_world.DestroyBody(m_bodies[m_bodyIndex]); m_bodies[m_bodyIndex] = null; } b2BodyDef bd = new b2BodyDef(); float x = Rand.RandomFloat(-10.0f, 10.0f); float y = Rand.RandomFloat(10.0f, 20.0f); bd.position.Set(x, y); bd.angle = Rand.RandomFloat(-b2Settings.b2_pi, b2Settings.b2_pi); bd.type = b2BodyType.b2_dynamicBody; if (index == 4) { bd.angularDamping = 0.02f; } m_bodies[m_bodyIndex] = m_world.CreateBody(bd); if (index < 4) { b2FixtureDef fd = new b2FixtureDef(); fd.shape = m_polygons[index]; fd.friction = 0.3f; fd.density = 20.0f; m_bodies[m_bodyIndex].CreateFixture(fd); } else { b2FixtureDef fd = new b2FixtureDef(); fd.shape = m_circle; fd.friction = 0.3f; fd.density = 20.0f; m_bodies[m_bodyIndex].CreateFixture(fd); } m_bodyIndex = (m_bodyIndex + 1) % e_maxBodies; }
public StarlingGameSpriteWithPedControlTimetravel() { var textures = new StarlingGameSpriteWithPedTextures(new_tex_crop, new_texsprite_crop); this.onbeforefirstframe += (stage, s) => { // 1000 / 15 // this means 15 samples per second var ilag = 7; #region man_with_lag var man_with_lag = new PhysicalPed(textures, this); //karmaman.body.SetActive(false); for (int i = 0; i < ilag; i++) { man_with_lag.KarmaInput4.Enqueue( new KeySample() ); } man_with_lag.body.SetPosition( new b2Vec2(-8, 8) ); man_with_lag.karmabody.SetPosition( new b2Vec2(-8, 8) ); #endregion #region man_with_karma var man_with_karma = new PhysicalPed(textures, this); man_with_karma.SetPositionAndAngle(-8, -8); #endregion var physical0 = new PhysicalPed(textures, this); current = physical0; // 32x32 = 15FPS? // 24x24 35? #region the others for (int ix = 1; ix < 4; ix++) { for (int iy = 1; iy < 4; iy++) { var p = new PhysicalPed(textures, this); p.SetPositionAndAngle( 8 * ix, 8 * iy ); } } #endregion #region __keyDown var __keyDown = new KeySample(); stage.keyDown += e => { // http://circlecube.com/2008/08/actionscript-key-listener-tutorial/ if (e.altKey) { __keyDown[Keys.Alt] = true; } __keyDown[(Keys)e.keyCode] = true; }; stage.keyUp += e => { if (!e.altKey) { __keyDown[Keys.Alt] = false; } __keyDown[(Keys)e.keyCode] = false; }; #endregion bool mode_changepending = false; var man_with_karma_karmavisuals = new Queue <VisualPed>(); var physical0_karmavisuals = new Queue <VisualPed>(); var karmasw = new Stopwatch(); karmasw.Start(); //var inputfilter = new Stopwatch(); //inputfilter.Start(); onsyncframe += delegate { physical0.SetVelocityFromInput(__keyDown); man_with_karma.SetVelocityFromInput(__keyDown); man_with_lag.KarmaInput4.Enqueue(new KeySample { value = __keyDown.value }); var physical2_karmastream_keydown = man_with_lag.KarmaInput4.Dequeue(); // this one lives in the past? man_with_lag.SetVelocityFromInput(physical2_karmastream_keydown); #region karmavisuals if (karmasw.ElapsedMilliseconds > (1000 / 15)) { karmasw.Restart(); { physical0_karmavisuals.Enqueue(physical0.visual); if (physical0_karmavisuals.Count > ilag) { physical0_karmavisuals.Dequeue().Orphanize(); } physical0.visual.shadow.visible = false; physical0.visual.currentvisual.alpha = 0.2; physical0.visual = new VisualPed(textures, this, physical0.visual.AnimateSeed) { LayOnTheGround = physical0.visual.LayOnTheGround }; physical0.ShowPositionAndAngle(); } { man_with_karma_karmavisuals.Enqueue(man_with_karma.visual); if (man_with_karma_karmavisuals.Count > 4) { man_with_karma_karmavisuals.Dequeue().Orphanize(); } man_with_karma.visual.shadow.visible = false; man_with_karma.visual.currentvisual.alpha = 0.2; man_with_karma.visual = new VisualPed(textures, this, man_with_karma.visual.AnimateSeed) { LayOnTheGround = man_with_karma.visual.LayOnTheGround }; man_with_karma.ShowPositionAndAngle(); } } #endregion }; onframe += delegate { this.Text = new { da = (man_with_lag.body.GetAngle() - physical0.body.GetAngle()).RadiansToDegrees(), dx = man_with_lag.body.GetPosition().x - physical0.body.GetPosition().x, dy = man_with_lag.body.GetPosition().y - physical0.body.GetPosition().y }.ToString(); #region simulate a weapone! if (__keyDown[Keys.ControlKey]) { if (frameid % 20 == 0) { var bodyDef = new b2BodyDef(); bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody; // stop moving if legs stop walking! bodyDef.linearDamping = 0; bodyDef.angularDamping = 0; //bodyDef.angle = 1.57079633; bodyDef.fixedRotation = true; var body = ground_b2world.CreateBody(bodyDef); body.SetPosition( new b2Vec2( current.body.GetPosition().x + 2, current.body.GetPosition().y + 2 ) ); body.SetLinearVelocity( new b2Vec2( 100, 100 ) ); var fixDef = new Box2D.Dynamics.b2FixtureDef(); fixDef.density = 0.1; fixDef.friction = 0.01; fixDef.restitution = 0; fixDef.shape = new Box2D.Collision.Shapes.b2CircleShape(1.0); var fix = body.CreateFixture(fixDef); //body.SetPosition( // new b2Vec2(0, -100 * 16) //); } } #endregion #region mode if (__keyDown[Keys.Space]) { // space is not down. mode_changepending = true; } else { if (mode_changepending) { if (physical0.visual.LayOnTheGround) { physical0.visual.LayOnTheGround = false; } else { physical0.visual.LayOnTheGround = true; } mode_changepending = false; } } #endregion }; }; }
public StarlingGameSpriteWithTestDriversWithAudio() { // http://www.mochigames.com/game/gunship_v838523/ textures_ped = new StarlingGameSpriteWithPedTextures(this.new_tex_crop, this.new_texsprite_crop); var textures_map = new StarlingGameSpriteWithMapTextures(new_tex_crop); var textures_jeep = new StarlingGameSpriteWithJeepTextures(this.new_tex_crop); var textures_hind = new StarlingGameSpriteWithHindTextures(this.new_tex_crop); var textures_tank = new StarlingGameSpriteWithTankTextures(this.new_texsprite_crop); var textures_cannon = new StarlingGameSpriteWithCannonTextures(this.new_tex_crop); var textures_bunker = new StarlingGameSpriteWithBunkerTextures(this.new_tex_crop); var textures_rocket = new StarlingGameSpriteWithRocketTextures(this.new_tex_crop); var textures_explosions = new StarlingGameSpriteWithMapExplosionsTextures(new_tex96); this.disablephysicsdiagnostics = true; this.onbeforefirstframe += (stage, s) => { var explosins = new List <ExplosionInfo>(); s.stage.color = 0xB27D51; // error JSC1000: ActionScript : failure at starling.display.Stage.add_keyUp : Object reference not set to an instance of an object. #region F2 stage.keyUp += e => { if (e.keyCode == (uint)System.Windows.Forms.Keys.F2) { this.Content_layer2_shadows.visible = !this.Content_layer2_shadows.visible; } }; #endregion #region F3 stage.keyUp += e => { if (e.keyCode == (uint)System.Windows.Forms.Keys.F3) { this.Content_layer0_tracks.visible = !this.Content_layer0_tracks.visible; } }; #endregion #region F1 stage.keyUp += e => { if (e.keyCode == (uint)System.Windows.Forms.Keys.F1) { if (this.internalscale == 0.3) { this.internalscale = 0.05; } else { this.internalscale = 0.3; } } }; #endregion var hud = new Image(textures_ped.hud_look()).AttachTo(this); #region hill1 for (int i = 0; i < 32; i++) { new Image(textures_map.hill1()).AttachTo(Content_layer0_ground).With( hill => { hill.x = 2048.Random(); hill.y = 2048.Random() - 1024; } ); new Image(textures_map.hole1()).AttachTo(Content_layer0_ground).With( hill => { hill.x = 2048.Random(); hill.y = 2048.Random() - 1024; } ); new Image(textures_map.grass1()).AttachTo(Content_layer0_ground).With( hill => { hill.x = 2048.Random(); var y = -2048.Random() - 512 - 256; hill.y = y; } ); } #endregion for (int i = -12; i < 12; i++) { new Image(textures_map.road0()).AttachTo(Content_layer0_ground).x = 256 * i; if (i % 3 == 0) { var z = new PhysicalPed(textures_ped, this); z.SetPositionAndAngle(16 * i, 0, random.NextDouble() * Math.PI); z.BehaveLikeZombie(); } } var needdshop = true; #region other units for (int i = 3; i < 7; i++) { { new PhysicalCannon(textures_cannon, this).SetPositionAndAngle( i * 16, -20, -random.NextDouble() ); new PhysicalCannon(textures_cannon, this).SetPositionAndAngle( i * 16, 36, random.NextDouble() ); } if (i % 3 == 0) { new PhysicalBunker(textures_bunker, this, IsShop: needdshop).SetPositionAndAngle( i * 16, -8, random.NextDouble() ); needdshop = false; new PhysicalBunker(textures_bunker, this).SetPositionAndAngle( i * 16, 24, random.NextDouble() ); var ibunker = new PhysicalBunker(textures_bunker, this); ibunker.SetPositionAndAngle( i * 16, 64, random.NextDouble() ); ibunker.visualshadow.Orphanize(); //.AttachTo(this.Content_layer10_hiddenforgoggles); ibunker.visual.Orphanize().AttachTo(this.Content_layer10_hiddenforgoggles); } else if (i % 3 == 1) { new PhysicalBarrel(textures_bunker, this).SetPositionAndAngle(i * 16, -4 - 3); new PhysicalBarrel(textures_bunker, this).SetPositionAndAngle(i * 16 + 2, -4); new PhysicalBarrel(textures_bunker, this).SetPositionAndAngle(i * 16, -4 + 3); new PhysicalWatertower(textures_bunker, this).SetPositionAndAngle( i * 16, 16, random.NextDouble() ); new PhysicalWatertower(textures_bunker, this).SetPositionAndAngle( i * 16 - 4, 16 + 4, random.NextDouble() ); new PhysicalWatertower(textures_bunker, this).SetPositionAndAngle( i * 16 + 4, 16 + 4, random.NextDouble() ); } else { new PhysicalBarrel(textures_bunker, this).SetPositionAndAngle(i * 16, 24 - 3); new PhysicalBarrel(textures_bunker, this).SetPositionAndAngle(i * 16 + 2, 24); new PhysicalBarrel(textures_bunker, this).SetPositionAndAngle(i * 16, 24 + 3); new PhysicalSilo(textures_bunker, this).SetPositionAndAngle( i * 16, -4, random.NextDouble() ); } } #endregion new PhysicalBarrel(textures_bunker, this).SetPositionAndAngle(12, 0); new PhysicalBarrel(textures_bunker, this).SetPositionAndAngle(12, -4); new PhysicalBarrel(textures_bunker, this).SetPositionAndAngle(12, -8); new Image(textures_map.touchdown()).AttachTo(Content_layer0_ground).MoveTo(256, -256); new Image(textures_map.touchdown()).AttachTo(Content_layer0_ground).y = 256; new PhysicalTank(textures_tank, this).SetPositionAndAngle(128 / 16, 128 * 3 / 16); new Image(textures_map.tree0_shadow()).AttachTo(Content).y = 128 + 16; new Image(textures_map.tree0()).AttachTo(Content).y = 128; // can I have // new ped, hind, jeep, tank var egoped = new PhysicalPed(textures_ped, this) { AttractZombies = true, }; egoped.visual.StandWithVisibleGun = true; current = egoped; current.SetPositionAndAngle( 16.Random(), 16.Random(), 360.Random().DegreesToRadians() ); var jeep2 = new PhysicalJeep(textures_jeep, this); jeep2.SetPositionAndAngle( 16, 16, random.NextDouble() ); var jeep3 = new PhysicalJeep(textures_jeep, this); jeep3.visual0.shadow.Orphanize(); //.AttachTo(this.Content_layer10_hiddenforgoggles); jeep3.visual0.currentvisual.Orphanize().AttachTo(this.Content_layer10_hiddenforgoggles); jeep3.SetPositionAndAngle( -16, 16, random.NextDouble() ); #region tree0 for (int i = 0; i < 128; i++) { { var x = 2048.Random(); var y = -2048.Random() - 512 - 256; new Image(textures_map.tree0_shadow()).AttachTo(Content_layer2_shadows).MoveTo(x + 16, y + 16); new Image(textures_map.tree0()).AttachTo(Content).MoveTo(x, y); } { var x = 2048.Random(); var y = 2048.Random() + 512 + 128; new Image(textures_map.tree0_shadow()).AttachTo(Content_layer2_shadows).MoveTo(x + 16, y + 16); new Image(textures_map.tree0()).AttachTo(Content).MoveTo(x, y); } } #endregion // 12 = 34FPS //new PhysicalHind(textures_hind, this) new PhysicalHindWeaponized(textures_hind, textures_rocket, this) { AutomaticTakeoff = true }.SetPositionAndAngle((128 + 256) / 16, -128 / 16); #region mouseWheel stage.mouseWheel += e => { e.preventDefault(); if (e.delta < 0) { this.internalscale -= 0.05; } if (e.delta > 0) { this.internalscale += 0.05; } }; #endregion #region __keyDown stage.keyDown += e => { e.preventDefault(); __keyDown.forcex = 1.0; __keyDown.forcey = 1.0; // http://circlecube.com/2008/08/actionscript-key-listener-tutorial/ if (e.altKey) { __keyDown[System.Windows.Forms.Keys.Alt] = true; } __keyDown[(System.Windows.Forms.Keys)e.keyCode] = true; }; stage.keyUp += e => { e.preventDefault(); if (!e.altKey) { __keyDown[System.Windows.Forms.Keys.Alt] = false; } __keyDown[(System.Windows.Forms.Keys)e.keyCode] = false; }; #endregion #region CreateExplosion this.CreateExplosion = (x, y) => { var size = 0.2 + 0.2 * random.NextDouble(); sb.snd_explosion_small.play( sndTransform: new ScriptCoreLib.ActionScript.flash.media.SoundTransform(size) ); var exp = new Image(textures_explosions.explosions[0]()).AttachTo(Content); var cm = new Matrix(); cm.translate(-32, -32); cm.scale(10 * size, 10 * size); cm.rotate(random.NextDouble() * Math.PI); cm.translate(16 * x, 16 * y); exp.transformationMatrix = cm; explosins.Add( new ExplosionInfo { visual = exp } ); }; #endregion bool nightvision_changepending = false; bool entermode_changepending = false; bool mode_changepending = false; onframe += delegate { //var v = current.body.GetLinearVelocity(); //Text = new { move_zoom, v.x, v.y }.ToString(); #region hud { var cm = new Matrix(); cm.scale(0.5, 0.5); cm.translate( 16 + HudPadding, stage.stageHeight - 64 - 24); hud.transformationMatrix = cm; } #endregion }; // ego + local environment #region Soundboard // http://www.nasa.gov/vision/universe/features/halloween_sounds.html sb.loopsand_run.MasterVolume = 0; sb.loopsand_run.Sound.play(); sb.loophelicopter1.MasterVolume = 0; sb.loophelicopter1.Sound.play(); sb.loopjeepengine.MasterVolume = 0; sb.loopjeepengine.Sound.play(); sb.loopdiesel2.MasterVolume = 0; sb.loopdiesel2.Sound.play(); sb.loopcrickets.MasterVolume = 0; sb.loopcrickets.Sound.play(); sb.loopstrange1.MasterVolume = 0; sb.loopstrange1.Sound.play(); sb.loop_GallinagoDelicata.MasterVolume = 0; sb.loop_GallinagoDelicata.Sound.play(); var jeep_forceA = 0.0; var ped_forceA = 0.0; var pedzombie_forceA = 0.0; var barrel_forceA = 0.0; var hardmetal_forceA = 0.0; this.oncollision += (u, force) => { if (u is PhysicalTank) { hardmetal_forceA = hardmetal_forceA.Max(force); } if (u is PhysicalSilo) { hardmetal_forceA = hardmetal_forceA.Max(force); } if (u is PhysicalBunker) { hardmetal_forceA = hardmetal_forceA.Max(force); } if (u is PhysicalWatertower) { hardmetal_forceA = hardmetal_forceA.Max(force); } if (u is PhysicalCannon) { hardmetal_forceA = hardmetal_forceA.Max(force); } }; PhysicalJeep.oncollision += (u, value) => { jeep_forceA = jeep_forceA.Max(value); }; PhysicalPed.oncollision += (u, value) => { if (u.visual.WalkLikeZombie) { pedzombie_forceA = pedzombie_forceA.Max(value); } else { ped_forceA = ped_forceA.Max(value); } }; PhysicalBarrel.oncollision += (u, value) => { barrel_forceA = barrel_forceA.Max(value); }; #endregion var nightvision_filter = new ColorMatrixFilter(); var nightvision_filter_age = new Stopwatch(); nightvision_filter_age.Start(); Action nighvision_handler = null; bool nightvision_mode = false; #region hud_update hud_update = delegate { if (nightvision_mode) { hud.texture = textures_ped.hud_look_goggles(); return; } if (current is PhysicalPed) { hud.texture = textures_ped.hud_look(); } else if (current == jeep3) { hud.texture = textures_ped.hud_look_onlygoggles(); } else { if (current.body.GetType() == Box2D.Dynamics.b2Body.b2_dynamicBody) { hud.texture = textures_ped.hud_look_goggles(); } else { hud.texture = textures_ped.hud_look_building(); } } }; #endregion #region nightvision_mode #region nightvision_on nightvision_on = delegate { if (nightvision_mode) { return; } nightvision_mode = true; hud_update(); nightvision_filter_age.Restart(); this.Content_layer10_hiddenforgoggles.visible = true; sb.snd_nightvision.play( sndTransform: new SoundTransform( 0.5 ) ); nighvision_handler = delegate { // http://doc.starling-framework.org/core/starling/filters/ColorMatrixFilter.html // create an inverted filter with 50% saturation and 180° hue rotation nightvision_filter = new ColorMatrixFilter(); nightvision_filter.adjustSaturation(-1.0); nightvision_filter.invert(); //nightvision_filter.adjustContrast(1.0); var a = (nightvision_filter_age.ElapsedMilliseconds / 1100.0).Min(1); nightvision_filter.adjustContrast( 16 - 14 * a ); // V:\web\FlashHeatZeeker\TestDriversWithAudio\Library\StarlingGameSpriteWithTestDriversWithAudio___c__DisplayClass29___c__DisplayClass30.as(266): col: 28 Error: Implicit coercion of a value of type __AS3__.vec:Vector.<Object> to an unrelated type __AS3__.vec:Vector.<Number>. //filter3.concat(vector_14); // ^ // public function concat(matrix:Vector.<Number>):void // public override void concat(Vector<object> matrix); // X:\jsc.svn\examples\actionscript\test\TestVectorOfNumber\TestVectorOfNumber\ApplicationSprite.cs #if FNGHTVISION nightvision_filter.concat( new double[] { //new object[] { 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 } ); #endif this.filter = nightvision_filter; this.stage.color = 0x006E00; if (a == 1) { nighvision_handler = null; } }; }; #endregion #region nightvision_off nightvision_off = delegate { if (!nightvision_mode) { return; } nightvision_mode = false; hud_update(); this.Content_layer10_hiddenforgoggles.visible = false; sb.snd_SelectWeapon.play( sndTransform: new SoundTransform( 0.3 ) ); nightvision_filter_age.Restart(); nighvision_handler = delegate { nightvision_filter = new ColorMatrixFilter(); // nightvision_filter.adjustBrightness( // 1 - (nightvision_filter_age.ElapsedMilliseconds / 200.0).Min(1) //); var a = (nightvision_filter_age.ElapsedMilliseconds / 500.0).Min(1); nightvision_filter.adjustBrightness( 0.5 - 0.5 * a ); this.filter = nightvision_filter; this.stage.color = 0xB27D51; if (a == 1) { nighvision_handler = null; } }; }; #endregion onframe += delegate { if (nighvision_handler != null) { nighvision_handler(); } }; #endregion //(units.FirstOrDefault(k => k is PhysicalBunker) as PhysicalBunker).With( // shop => // { // shop.IsShop = true; // } //); var mode_gun = false; onsyncframe += delegate { while (Content_layer0_tracks.numChildren > 128) { Content_layer0_tracks.removeChildAt(0); } #region textures_explosions foreach (var item in explosins.ToArray()) { item.index++; if (item.index == textures_explosions.explosions.Length) { item.visual.Orphanize(); explosins.Remove(item); } else { item.visual.texture = textures_explosions.explosions[item.index](); } } #endregion #region Soundboard if (barrel_forceA > 0) { sb.snd_woodsmash.play( sndTransform: new SoundTransform( Math.Min(1.0, barrel_forceA / 30.0) * (0.15 + 0.15 * random.NextDouble()) ) ); barrel_forceA = 0; } else if (hardmetal_forceA > 0) { sb.snd_hardmetalsmash.play( sndTransform: new SoundTransform( Math.Min(1.0, hardmetal_forceA / 30.0) * (0.2 + 0.2 * random.NextDouble()) ) ); hardmetal_forceA = 0; } else if (jeep_forceA > 0) { sb.snd_metalsmash.play( sndTransform: new SoundTransform( Math.Min(1.0, jeep_forceA / 30.0) * (0.2 + 0.2 * random.NextDouble()) ) ); jeep_forceA = 0; } else if (ped_forceA > 0) { sb.snd_ped_hit.play( sndTransform: new SoundTransform( Math.Min(1.0, ped_forceA / 30.0) * (0.15 + 0.15 * random.NextDouble()) ) ); ped_forceA = 0; } else if (pedzombie_forceA > 0) { sb.snd_Argh.play( sndTransform: new SoundTransform( Math.Min(1.0, pedzombie_forceA / 30.0) * (0.15 + 0.15 * random.NextDouble()) ) ); pedzombie_forceA = 0; } if (this.syncframeid == 200) { sb.snd_whatsthatsound.play(); } if (this.syncframeid == 400) { sb.snd_needweapon.play(); } if (this.syncframeid == 800) { sb.snd_didyouhearthat.play(); } if (this.syncframeid == 1200) { sb.snd_whatsthatsound.play(); } sb.loopcrickets.MasterVolume = (1 - move_zoom) * 0.09; sb.loop_GallinagoDelicata.MasterVolume = (1 - move_zoom) * 0.3; sb.loopstrange1.MasterVolume = (1 - move_zoom) * 0.04; sb.loophelicopter1.MasterVolume = 0.0; sb.loopjeepengine.MasterVolume = 0.0; sb.loopdiesel2.MasterVolume = 0.0; sb.loopsand_run.MasterVolume = 0.0; if (current is PhysicalPed) { sb.loopsand_run.MasterVolume = 0.5; sb.loopsand_run.LeftVolume = 0.0 + move_zoom * 0.9; sb.loopsand_run.RightVolume = 0.0 + move_zoom * 0.9; sb.loopsand_run.Rate = 0.9 + move_zoom * 0.1; } else if (current is PhysicalHind) { sb.loopcrickets.MasterVolume = 0; sb.loophelicopter1.MasterVolume = 0.3 + (current as PhysicalHind).visual.Altitude * 0.2; sb.loophelicopter1.LeftVolume = 0.7 + move_zoom * 0.1; sb.loophelicopter1.RightVolume = 0.8; sb.loophelicopter1.Rate = 0.7 + (current as PhysicalHind).visual.Altitude * 0.25 + move_zoom * 0.05; } else if (current is PhysicalJeep) { sb.loopjeepengine.MasterVolume = 0.5; sb.loopjeepengine.LeftVolume = 0.4 + move_zoom * 0.7; sb.loopjeepengine.RightVolume = 1; sb.loopjeepengine.Rate = 0.9 + move_zoom * 0.5; } else if (current is PhysicalTank) { sb.loopcrickets.MasterVolume = 0; sb.loopdiesel2.MasterVolume = 0.5; sb.loopdiesel2.LeftVolume = 0.3 + move_zoom * 0.7; sb.loopdiesel2.RightVolume = 1; sb.loopdiesel2.Rate = 0.9 + move_zoom; } else { sb.loopcrickets.MasterVolume = 0.2; sb.loop_GallinagoDelicata.MasterVolume = 0.2; } // stereoeffect // siren sb.loopstrange1.LeftVolume = 0.2 * (1 + Math.Cos(this.gametime.ElapsedMilliseconds * 0.00001)) / 2.0; sb.loopstrange1.RightVolume = 0.4 * (1 + Math.Cos(this.gametime.ElapsedMilliseconds * 0.00001)) / 2.0; sb.loopcrickets.LeftVolume = (1 + Math.Sin( this.gametime.ElapsedMilliseconds * 0.0001 + this.current.CameraRotation + this.current.body.GetAngle() )) / 2.0; sb.loopcrickets.RightVolume = (3 + Math.Cos(this.gametime.ElapsedMilliseconds * 0.001 + this.current.CameraRotation + this.current.body.GetAngle() )) / 4.0; sb.loop_GallinagoDelicata.LeftVolume = sb.loopcrickets.RightVolume; sb.loop_GallinagoDelicata.RightVolume = sb.loopcrickets.LeftVolume; #endregion if (disable_enter_and_space) { // implemented elsewhere } else { #region Enter if (!__keyDown[System.Windows.Forms.Keys.Enter]) { // space is not down. entermode_changepending = true; } else { if (entermode_changepending) { entermode_changepending = false; // enter another vehicle? var candidatedriver = current as PhysicalPed; if (candidatedriver != null) { var target = from candidatevehicle in units where candidatevehicle.driverseat != null // can enter if the seat is full. // unless we kick them out before ofcourse where candidatevehicle.driverseat.driver == null let distance = new __vec2( (float)(candidatedriver.body.GetPosition().x - candidatevehicle.body.GetPosition().x), (float)(candidatedriver.body.GetPosition().y - candidatevehicle.body.GetPosition().y) ).GetLength() where distance < 6 orderby distance ascending select new { candidatevehicle, distance }; target.FirstOrDefault().With( x => { Console.WriteLine(new { x.distance }); //current.loc.visible = false; current.body.SetActive(false); x.candidatevehicle.driverseat.driver = candidatedriver; candidatedriver.seatedvehicle = x.candidatevehicle; current = x.candidatevehicle; if (current is PhysicalJeep) { sb.snd_jeepengine_start.play(); } else if (current is PhysicalBunker) { if ((current as PhysicalBunker).visual_shopoverlay.visible) { sb.snd_its_a_shop.play(); } else { if (random.NextDouble() > 0.8) { sb.haarp.play(); } else { if (random.NextDouble() > 0.5) { sb.snd_itsempty.play(); } else { sb.snd_nothinghere.play(); } } } } else { sb.snd_dooropen.play( sndTransform: new SoundTransform( 0.3 ) ); } //if (current is PhysicalHind) //{ // nightvision_on(); //} hud_update(); //switchto(x.x); move_zoom = 1; // fast start //(current as PhysicalHind).With( // hind => hind.VerticalVelocity = 1 //); } ); } else { (current.driverseat.driver as PhysicalPed).With( driver => { // get out of the lift.. //nightvision_off(); current.driverseat.driver = null; driver.seatedvehicle = null; current.SetVelocityFromInput(new KeySample()); // crashland? (current as PhysicalHind).With( hind => { if (hind.visual.Altitude > 0) { hind.VerticalVelocity = -1; sb.snd_touchdown.play(); } } ); sb.snd_dooropen.play( sndTransform: new SoundTransform( 0.3 ) ); //if (current.body.GetType() != Box2D.Dynamics.b2Body.b2_dynamicBody) //{ // sb.snd_letsgo.play(); //} current = driver; driver.body.SetActive(true); driver.body.SetAngularVelocity(-11); hud_update(); move_zoom = 1; } ); } } } #endregion #region Space if (!__keyDown[System.Windows.Forms.Keys.Space]) { // space is not down. mode_changepending = true; } else { if (mode_changepending) { (current as PhysicalHind).With( hind1 => { if (hind1.visual.Altitude == 0) { //nightvision_on(); hind1.VerticalVelocity = 1.0; } else { //nightvision_off(); hind1.VerticalVelocity = -0.4; sb.snd_touchdown.play(); } } ); (current as PhysicalPed).With( physical0 => { if (physical0.visual.LayOnTheGround) { physical0.visual.LayOnTheGround = false; sb.snd_letsgo.play( sndTransform: new SoundTransform( 0.3 * (0.15 + 0.15 * random.NextDouble()) ) ); } else { physical0.visual.LayOnTheGround = true; sb.snd_ped_hit.play( sndTransform: new SoundTransform( 0.3 * (0.15 + 0.15 * random.NextDouble()) ) ); } } ); mode_changepending = false; } } #endregion } #region N if (!__keyDown[System.Windows.Forms.Keys.N]) { // space is not down. nightvision_changepending = true; } else { if (nightvision_changepending) { if (nightvision_mode) { nightvision_off(); } else { nightvision_on(); } nightvision_changepending = false; } } #endregion current.SetVelocityFromInput(__keyDown); #region simulate a weapone! if (__keyDown[System.Windows.Forms.Keys.ControlKey]) { if (syncframeid % 3 == 0) { (this.current as PhysicalHindWeaponized).With( h => { sb.snd_missleLaunch.play( sndTransform: new SoundTransform(0.5) ); h.FireRocket(); } ); } } #endregion #region simulate a weapone! if (__keyDown[System.Windows.Forms.Keys.ControlKey]) { mode_gun = true; } else { if (mode_gun) { mode_gun = false; (this.current as PhysicalPed).With( h => { h.visual.StandWithVisibleGunFire.Restart(); sb.snd_shotgun3.play(); #region CreateBullet Action <double> CreateBullet = a => { var bodyDef = new b2BodyDef(); bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody; // stop moving if legs stop walking! bodyDef.linearDamping = 0; bodyDef.angularDamping = 0; //bodyDef.angle = 1.57079633; bodyDef.fixedRotation = true; var dx = Math.Cos(current.body.GetAngle() + current.CameraRotation + a); var dy = Math.Sin(current.body.GetAngle() + current.CameraRotation + a); var body = damage_b2world.CreateBody(bodyDef); body.SetPosition( new b2Vec2( current.body.GetPosition().x + dx * 0.3, current.body.GetPosition().y + dy * 0.3 ) ); body.SetLinearVelocity( new b2Vec2( dx * 100, dy * 100 ) ); var fixDef = new Box2D.Dynamics.b2FixtureDef(); fixDef.density = 20; fixDef.friction = 0.0; fixDef.restitution = 0; fixDef.shape = new Box2D.Collision.Shapes.b2CircleShape(0.3); var fix = body.CreateFixture(fixDef); }; #endregion CreateBullet(-6.DegreesToRadians()); CreateBullet(-2.DegreesToRadians()); CreateBullet(2.DegreesToRadians()); CreateBullet(6.DegreesToRadians()); } ); } } #endregion }; }; }
void InitPhysics() { CCSize s = Layer.VisibleBoundsWorldspace.Size; var gravity = new b2Vec2 (0.0f, -10.0f); world = new b2World (gravity); world.SetAllowSleeping (true); world.SetContinuousPhysics (true); var def = new b2BodyDef (); def.allowSleep = true; def.position = b2Vec2.Zero; def.type = b2BodyType.b2_staticBody; b2Body groundBody = world.CreateBody (def); groundBody.SetActive (true); b2EdgeShape groundBox = new b2EdgeShape (); groundBox.Set (b2Vec2.Zero, new b2Vec2 (s.Width / PTM_RATIO, 0)); b2FixtureDef fd = new b2FixtureDef (); fd.shape = groundBox; groundBody.CreateFixture (fd); }
public Wheel( b2World b2world, double x, double y, double width, double length, bool revolving, bool powered ) { this.revolving = revolving; this.powered = powered; this.Initialize = car => { /* wheel object pars: car - car this wheel belongs to x - horizontal position in meters relative to car's center y - vertical position in meters relative to car's center width - width in meters length - length in meters revolving - does this wheel revolve when steering? powered - is this wheel powered? */ var position = new double[] { x, y }; //this.car=pars.car; //this.revolving=pars.revolving; //this.powered=pars.powered; //initialize body var def = new b2BodyDef(); def.type = b2Body.b2_dynamicBody; def.position = car.body.GetWorldPoint(new b2Vec2(position[0], position[1])); def.angle = car.body.GetAngle(); this.body = b2world.CreateBody(def); //initialize shape var fixdef = new b2FixtureDef(); fixdef.density = 1; fixdef.isSensor = true; //wheel does not participate in collision calculations: resulting complications are unnecessary var fixdef_shape = new b2PolygonShape(); fixdef.shape = fixdef_shape; fixdef_shape.SetAsBox(width / 2, length / 2); body.CreateFixture(fixdef); var jointdef = new b2RevoluteJointDef(); //create joint to connect wheel to body if (revolving) { jointdef.Initialize(car.body, body, body.GetWorldCenter()); jointdef.enableMotor = false; //we'll be controlling the wheel's angle manually } else { jointdef.Initialize(car.body, body, body.GetWorldCenter() //, new b2Vec2(1, 0) ); jointdef.enableLimit = true; //jointdef.lowerTranslation = 0; //jointdef.upperTranslation = 0; } b2world.CreateJoint(jointdef); #region setAngle this.setAngle = (angle) => { /* angle - wheel angle relative to car, in degrees */ body.SetAngle(car.body.GetAngle() + angle.DegreesToRadians()); }; #endregion #region getLocalVelocity Func<double[]> getLocalVelocity = delegate { /*returns get velocity vector relative to car */ var res = car.body.GetLocalVector(car.body.GetLinearVelocityFromLocalPoint(new b2Vec2(position[0], position[1]))); return new double[] { res.x, res.y }; }; #endregion #region getDirectionVector Func<double[]> getDirectionVector = delegate { /* returns a world unit vector pointing in the direction this wheel is moving */ if (getLocalVelocity()[1] > 0) return vectors.rotate(new double[] { 0, 1 }, body.GetAngle()); else return vectors.rotate(new double[] { 0, -1 }, body.GetAngle()); }; #endregion #region getKillVelocityVector Func<double[]> getKillVelocityVector = delegate { /* substracts sideways velocity from this wheel's velocity vector and returns the remaining front-facing velocity vector */ var velocity = body.GetLinearVelocity(); var sideways_axis = getDirectionVector(); var dotprod = vectors.dot(new[] { velocity.x, velocity.y }, sideways_axis); return new double[] { sideways_axis[0] * dotprod, sideways_axis[1] * dotprod }; }; #endregion #region killSidewaysVelocity this.killSidewaysVelocity = delegate { /* removes all sideways velocity from this wheels velocity */ var kv = getKillVelocityVector(); body.SetLinearVelocity(new b2Vec2(kv[0], kv[1])); }; #endregion }; }
public Car( b2World b2world, double width, double length, double[] position, double angle, double power, double max_steer_angle, double max_speed, Wheel[] wheels ) { // /* // pars is an object with possible attributes: // width - width of the car in meters // length - length of the car in meters // position - starting position of the car, array [x, y] in meters // angle - starting angle of the car, degrees // max_steer_angle - maximum angle the wheels turn when steering, degrees // max_speed - maximum speed of the car, km/h // power - engine force, in newtons, that is applied to EACH powered wheel // wheels - wheel definitions: [{x, y, rotatable, powered}}, ...] where // x is wheel position in meters relative to car body center // y is wheel position in meters relative to car body center // revolving - boolean, does this turn rotate when steering? // powered - is force applied to this wheel when accelerating/braking? // */ // this.max_steer_angle=pars.max_steer_angle; // this.max_speed=pars.max_speed; // this.power=pars.power; var wheel_angle = 0.0;//keep track of current wheel angle relative to car. // //when steering left/right, angle will be decreased/increased gradually over 200ms to prevent jerkyness. //initialize body var def = new b2BodyDef(); def.type = b2Body.b2_dynamicBody; def.position = new b2Vec2(position[0], position[1]); def.angle = angle.DegreesToRadians(); def.linearDamping = 0.15; //gradually reduces velocity, makes the car reduce speed slowly if neither accelerator nor brake is pressed def.bullet = true; //dedicates more time to collision detection - car travelling at high speeds at low framerates otherwise might teleport through obstacles. def.angularDamping = 0.3; this.body = b2world.CreateBody(def); //initialize shape var fixdef = new b2FixtureDef(); fixdef.density = 1.0; fixdef.friction = 0.3; //friction when rubbing agaisnt other shapes fixdef.restitution = 0.4; //amount of force feedback when hitting something. >0 makes the car bounce off, it's fun! var fixdef_shape = new b2PolygonShape(); fixdef.shape = fixdef_shape; fixdef_shape.SetAsBox(width / 2, length / 2); body.CreateFixture(fixdef); //initialize wheels foreach (var item in wheels) { item.Initialize(this); } //return array of wheels that turn when steering IEnumerable<Wheel> getRevolvingWheels = from w in wheels where w.revolving select w; // //return array of powered wheels IEnumerable<Wheel> getPoweredWheels = from w in wheels where w.powered select w; #region setSpeed Action<double> setSpeed = (speed) => { /* speed - speed in kilometers per hour */ var velocity0 = this.body.GetLinearVelocity(); //Console.WriteLine("car setSpeed velocity0 " + new { velocity0.x, velocity0.y }); var velocity2 = vectors.unit(new[] { velocity0.x, velocity0.y }); //Console.WriteLine("car setSpeed velocity2 " + new { x = velocity2[0], y = velocity2[1] }); var velocity = new b2Vec2( velocity2[0] * ((speed * 1000.0) / 3600.0), velocity2[1] * ((speed * 1000.0) / 3600.0) ); //Console.WriteLine("car setSpeed SetLinearVelocity " + new { velocity.x, velocity.y }); this.body.SetLinearVelocity(velocity); }; #endregion #region getSpeedKMH Func<double> getSpeedKMH = delegate { var velocity = this.body.GetLinearVelocity(); var len = vectors.len(new double[] { velocity.x, velocity.y }); return (len / 1000.0) * 3600.0; }; #endregion #region getLocalVelocity Func<double[]> getLocalVelocity = delegate { /* returns car's velocity vector relative to the car */ var retv = this.body.GetLocalVector(this.body.GetLinearVelocityFromLocalPoint(new b2Vec2(0, 0))); return new double[] { retv.x, retv.y }; }; #endregion #region update this.update = (msDuration) => { #region 1. KILL SIDEWAYS VELOCITY //kill sideways velocity for all wheels for (var i = 0; i < wheels.Length; i++) { wheels[i].killSidewaysVelocity(); } #endregion #region 2. SET WHEEL ANGLE //calculate the change in wheel's angle for this update, assuming the wheel will reach is maximum angle from zero in 200 ms var incr = (max_steer_angle / 200.0) * msDuration; if (steer == STEER_RIGHT) { wheel_angle = Math.Min(Math.Max(wheel_angle, 0) + incr, max_steer_angle); //increment angle without going over max steer } else if (steer == STEER_LEFT) { wheel_angle = Math.Max(Math.Min(wheel_angle, 0) - incr, -max_steer_angle); //decrement angle without going over max steer } else { wheel_angle = 0; } //update revolving wheels getRevolvingWheels.WithEach( w => w.setAngle(wheel_angle) ); #endregion #region 3. APPLY FORCE TO WHEELS var base_vect = new double[2]; //vector pointing in the direction force will be applied to a wheel ; relative to the wheel. //if accelerator is pressed down and speed limit has not been reached, go forwards var lessthanlimit = (getSpeedKMH() < max_speed); var flag1 = (accelerate == ACC_ACCELERATE) && lessthanlimit; if (flag1) { base_vect = new double[] { 0, -1 }; } else if (accelerate == ACC_BRAKE) { //braking, but still moving forwards - increased force if (getLocalVelocity()[1] < 0) { base_vect = new double[] { 0, 1.3 }; } //going in reverse - less force else { base_vect = new double[] { 0, 0.7 }; } } else { base_vect[0] = 0; base_vect[1] = 0; } //multiply by engine power, which gives us a force vector relative to the wheel var fvect = new double[] { power * base_vect[0], power * base_vect[1] }; //apply force to each wheel getPoweredWheels.WithEachIndex( (w, i) => { var wp = w.body.GetWorldCenter(); var wf = w.body.GetWorldVector(new b2Vec2(fvect[0], fvect[1])); //Console.WriteLine("getPoweredWheels ApplyForce #" + i); w.body.ApplyForce(wf, wp); } ); //if going very slow, stop - to prevent endless sliding var veryslow = (getSpeedKMH() < 4); var flag2 = veryslow && (accelerate == ACC_NONE); if (flag2) { //Console.WriteLine("setSpeed 0"); setSpeed(0); } #endregion }; #endregion }
public PhysicalTank(StarlingGameSpriteWithTankTextures textures, StarlingGameSpriteWithPhysics Context) { this.CurrentInput = new KeySample(); this.textures = textures; this.Context = Context; this.driverseat = new DriverSeat(); this.visual = new VisualTank(textures, Context); for (int i = 0; i < 7; i++) { this.KarmaInput0.Enqueue( new KeySample() ); } #region b2world { var bodyDef = new b2BodyDef(); bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody; // stop moving if legs stop walking! bodyDef.linearDamping = 1.0; bodyDef.angularDamping = 8; //bodyDef.angle = 1.57079633; //bodyDef.fixedRotation = true; body = Context.ground_b2world.CreateBody(bodyDef); //current = body; var fixDef = new Box2D.Dynamics.b2FixtureDef(); fixDef.density = 0.1; fixDef.friction = 0.01; fixDef.restitution = 0; var fixdef_shape = new b2PolygonShape(); fixDef.shape = fixdef_shape; // physics unit is looking to right fixdef_shape.SetAsBox(3, 2); var fix = body.CreateFixture(fixDef); var fix_data = new Action <double>( jeep_forceA => { if (jeep_forceA < 1) { return; } Context.oncollision(this, jeep_forceA); } ); fix.SetUserData(fix_data); } { var bodyDef = new b2BodyDef(); bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody; // stop moving if legs stop walking! bodyDef.linearDamping = 1.0; bodyDef.angularDamping = 8; //bodyDef.angle = 1.57079633; //bodyDef.fixedRotation = true; karmabody = Context.groundkarma_b2world.CreateBody(bodyDef); //current = body; var fixDef = new Box2D.Dynamics.b2FixtureDef(); fixDef.density = 0.1; fixDef.friction = 0.01; fixDef.restitution = 0; var fixdef_shape = new b2PolygonShape(); fixDef.shape = fixdef_shape; // physics unit is looking to right fixdef_shape.SetAsBox(3, 2); var fix = karmabody.CreateFixture(fixDef); } #endregion #region b2world { var bodyDef = new b2BodyDef(); bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody; // stop moving if legs stop walking! bodyDef.linearDamping = 1.0; bodyDef.angularDamping = 8; //bodyDef.angle = 1.57079633; //bodyDef.fixedRotation = true; damagebody = Context.damage_b2world.CreateBody(bodyDef); //current = body; var fixDef = new Box2D.Dynamics.b2FixtureDef(); fixDef.density = 0.1; fixDef.friction = 0.01; fixDef.restitution = 0; var fixdef_shape = new b2PolygonShape(); fixDef.shape = fixdef_shape; // physics unit is looking to right fixdef_shape.SetAsBox(3, 2); var fix = damagebody.CreateFixture(fixDef); var fix_data = new Action <double>( jeep_forceA => { if (jeep_forceA < 1) { return; } Context.oncollision(this, jeep_forceA); } ); fix.SetUserData(fix_data); } #endregion Context.internalunits.Add(this); }
public StarlingGameSpriteWithPedControl() { // http://armorgames.com/play/13701/ var textures_ped = new StarlingGameSpriteWithPedTextures( this.new_tex_crop, this.new_texsprite_crop ); //this.disablephysicsdiagnostics = true; this.onbeforefirstframe += (stage, s) => { var patrol1 = new PhysicalPed(textures_ped, this) { speed = 10 }; var physical0 = new PhysicalPed(textures_ped, this) { AttractZombies = true //speed = 8 }; //physical0.visual.WalkLikeZombie = true; physical0.visual.StandWithVisibleGun = true; current = physical0; // 32x32 = 15FPS? // 24x24 35? stage.mouseWheel += e => { if (e.delta < 0) { this.internalscale -= 0.05; } if (e.delta > 0) { this.internalscale += 0.05; } }; #region others for (int ix = 0; ix < 4; ix++) { for (int iy = 0; iy < 4; iy++) { var p = new PhysicalPed(textures_ped, this); p.SetPositionAndAngle( 32 * ix, 32 * iy, random.NextDouble() ); if (ix == 0) { p.BehaveLikeZombie(); } } } #endregion #region __keyDown stage.keyDown += e => { // http://circlecube.com/2008/08/actionscript-key-listener-tutorial/ if (e.altKey) { __keyDown[Keys.Alt] = true; } __keyDown[(Keys)e.keyCode] = true; this.Text = new { e.keyCode, Keys.A }.ToString(); }; stage.keyUp += e => { if (!e.altKey) { __keyDown[Keys.Alt] = false; } __keyDown[(Keys)e.keyCode] = false; }; #endregion bool mode_changepending = false; var mode_gun = false; var sb = new Soundboard(); onsyncframe += delegate { #region patrol1 if (syncframeid % 300 == 100) { patrol1.body.SetAngle( 45.DegreesToRadians() ); var partol_commands = new KeySample(); partol_commands[Keys.Up] = true; patrol1.SetVelocityFromInput(partol_commands); } if (syncframeid % 300 == 150) { var partol_commands = new KeySample(); //partol_commands[Keys.Left] = true; patrol1.SetVelocityFromInput(partol_commands); } if (syncframeid % 300 == 200) { patrol1.body.SetAngle( (180 + 45).DegreesToRadians() ); var partol_commands = new KeySample(); partol_commands[Keys.Up] = true; patrol1.SetVelocityFromInput(partol_commands); } if (syncframeid % 300 == 250) { var partol_commands = new KeySample(); //partol_commands[Keys.Left] = true; patrol1.SetVelocityFromInput(partol_commands); } #endregion current.SetVelocityFromInput(__keyDown); #region simulate a weapone! if (__keyDown[Keys.ControlKey]) { mode_gun = true; } else { if (mode_gun) { mode_gun = false; (current as PhysicalPed).With( ped => { ped.visual.StandWithVisibleGunFire.Restart(); } ); sb.snd_shotgun3.play(); #region CreateBullet Action <double> CreateBullet = a => { var bodyDef = new b2BodyDef(); bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody; // stop moving if legs stop walking! bodyDef.linearDamping = 0; bodyDef.angularDamping = 0; //bodyDef.angle = 1.57079633; bodyDef.fixedRotation = true; var dx = Math.Cos(current.body.GetAngle() + current.CameraRotation + a); var dy = Math.Sin(current.body.GetAngle() + current.CameraRotation + a); var body = damage_b2world.CreateBody(bodyDef); body.SetPosition( new b2Vec2( current.body.GetPosition().x + dx * 0.3, current.body.GetPosition().y + dy * 0.3 ) ); body.SetLinearVelocity( new b2Vec2( dx * 100, dy * 100 ) ); var fixDef = new Box2D.Dynamics.b2FixtureDef(); fixDef.density = 20; fixDef.friction = 0.0; fixDef.restitution = 0; fixDef.shape = new Box2D.Collision.Shapes.b2CircleShape(0.3); var fix = body.CreateFixture(fixDef); }; #endregion CreateBullet(-6.DegreesToRadians()); CreateBullet(-2.DegreesToRadians()); CreateBullet(2.DegreesToRadians()); CreateBullet(6.DegreesToRadians()); //body.SetPosition( // new b2Vec2(0, -100 * 16) //); } } #endregion #region mode if (!__keyDown[Keys.Space]) { // space is not down. mode_changepending = true; } else { if (mode_changepending) { if (physical0.visual.LayOnTheGround) { physical0.visual.LayOnTheGround = false; } else { physical0.visual.LayOnTheGround = true; } mode_changepending = false; } } #endregion }; }; }