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); // }
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); }
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; }
/// <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 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 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 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); }
// REVISADO ===================================================================== b2Fixture j2b2Fixture(b2Body body, JObject fixtureValue) { if (null == fixtureValue) return null; b2FixtureDef fixtureDef = new b2FixtureDef(); //Fixture fixtureDef = new Fixture(); fixtureDef.restitution = jsonToFloat("restitution", fixtureValue); fixtureDef.friction = jsonToFloat("friction", fixtureValue); fixtureDef.density = jsonToFloat("density", fixtureValue); fixtureDef.isSensor = fixtureValue["sensor"] == null ? false : (bool)fixtureValue["sensor"]; fixtureDef.filter.categoryBits = (fixtureValue["filter-categoryBits"] == null) ? (ushort)0x0001 : (ushort)fixtureValue["filter-categoryBits"]; fixtureDef.filter.maskBits = fixtureValue["filter-maskBits"] == null ? (ushort)0xffff : (ushort)fixtureValue["filter-maskBits"]; fixtureDef.filter.groupIndex = fixtureValue["filter-groupIndex"] == null ? (short)0 : (short)fixtureValue["filter-groupIndex"]; b2Fixture fixture = null; if (null != fixtureValue["circle"]) { JObject circleValue = (JObject)fixtureValue["circle"]; b2CircleShape circleShape = new b2CircleShape(); circleShape.Radius = jsonToFloat("radius", circleValue); circleShape.Position = jsonToVec("center", circleValue); fixtureDef.shape = circleShape; fixture = body.CreateFixture(fixtureDef); } else if (null != fixtureValue["edge"]) { JObject edgeValue = (JObject)fixtureValue["edge"]; b2EdgeShape edgeShape = new b2EdgeShape(); edgeShape.Vertex1 = jsonToVec("vertex1", edgeValue); edgeShape.Vertex2 = jsonToVec("vertex2", edgeValue); edgeShape.HasVertex0 = edgeValue["hasVertex0"] == null ? false : (bool)edgeValue["hasVertex0"]; edgeShape.HasVertex3 = edgeValue["hasVertex3"] == null ? false : (bool)edgeValue["hasVertex3"]; if (edgeShape.HasVertex0) edgeShape.Vertex0 = jsonToVec("vertex0", edgeValue); if (edgeShape.HasVertex3) edgeShape.Vertex3 = jsonToVec("vertex3", edgeValue); fixtureDef.shape = edgeShape; fixture = body.CreateFixture(fixtureDef); } else if (null != fixtureValue["loop"]) {// support old // format (r197) JObject chainValue = (JObject)fixtureValue["loop"]; b2ChainShape chainShape = new b2ChainShape(); int numVertices = ((JArray)chainValue["x"]).Count; b2Vec2[] vertices = new b2Vec2[numVertices]; for (int i = 0; i < numVertices; i++) vertices[i] = jsonToVec("vertices", chainValue, i); chainShape.CreateLoop(vertices, numVertices); fixtureDef.shape = chainShape; fixture = body.CreateFixture(fixtureDef); } else if (null != fixtureValue["chain"]) { // FPE. See http://www.box2d.org/forum/viewtopic.php?f=4&t=7973&p=35363 JObject chainValue = (JObject)fixtureValue["chain"]; b2ChainShape chainShape = new b2ChainShape(); int numVertices = ((JArray)chainValue["vertices"]["x"]).Count; var vertices = new b2Vec2[numVertices]; for (int i = 0; i < numVertices; i++) vertices[i] = jsonToVec("vertices", chainValue, i); chainShape.CreateChain(vertices, numVertices); chainShape.HasPrevVertex = chainValue["hasPrevVertex"] == null ? false : (bool)chainValue["hasPrevVertex"]; chainShape.HasNextVertex = chainValue["hasNextVertex"] == null ? false : (bool)chainValue["hasNextVertex"]; if (chainShape.HasPrevVertex) chainShape.PrevVertex = (jsonToVec("prevVertex", chainValue)); if (chainShape.HasNextVertex) chainShape.NextVertex = (jsonToVec("nextVertex", chainValue)); fixtureDef.shape = chainShape; fixture = body.CreateFixture(fixtureDef); } else if (null != fixtureValue["polygon"]) { JObject polygonValue = (JObject)fixtureValue["polygon"]; b2Vec2[] vertices = new b2Vec2[b2Settings.b2_maxPolygonVertices]; int numVertices = ((JArray)polygonValue["vertices"]["x"]).Count; if (numVertices > b2Settings.b2_maxPolygonVertices) { Console.WriteLine("Ignoring polygon fixture with too many vertices."); } else if (numVertices < 2) { Console.WriteLine("Ignoring polygon fixture less than two vertices."); } else if (numVertices == 2) { Console.WriteLine("Creating edge shape instead of polygon with two vertices."); b2EdgeShape edgeShape = new b2EdgeShape(); edgeShape.Vertex1 = jsonToVec("vertices", polygonValue, 0); edgeShape.Vertex2 = jsonToVec("vertices", polygonValue, 1); fixtureDef.shape = edgeShape; fixture = body.CreateFixture(fixtureDef); } else { b2PolygonShape polygonShape = new b2PolygonShape(); for (int i = 0; i < numVertices; i++) vertices[i] = jsonToVec("vertices", polygonValue, i); polygonShape.Set(vertices, numVertices); fixtureDef.shape = polygonShape; fixture = body.CreateFixture(fixtureDef); } } String fixtureName = fixtureValue["name"] == null ? "" : fixtureValue["name"].ToString(); if (fixtureName != "") { SetFixtureName(fixture, fixtureName); } return fixture; }
public b2Body createPhysicsBody(b2World bodyWorld) { //definiert den physikalischen körper des Männchens if (characterBody == null) { b2BodyDef characterDef = new b2BodyDef (); characterDef.type = b2BodyType.b2_dynamicBody; characterDef.position = new b2Vec2 (CharacterPosition.X / PhysicsHandler.pixelPerMeter, CharacterPosition.Y / PhysicsHandler.pixelPerMeter); characterBody = bodyWorld.CreateBody (characterDef); b2PolygonShape characterShape = new b2PolygonShape (); characterShape.SetAsBox ((float)CharacterSize.Width / PhysicsHandler.pixelPerMeter / 2, (float)CharacterSize.Height / PhysicsHandler.pixelPerMeter / 2); b2FixtureDef characterFixture = new b2FixtureDef (); characterFixture.shape = characterShape; characterFixture.density = 0.0f; //Dichte characterFixture.friction = 0f; characterFixture.restitution = 0f; //Rückprall characterBody.CreateFixture (characterFixture); b2PolygonShape characterGroundSensorShape = new b2PolygonShape (); b2Vec2 GroundSensorPosition = new b2Vec2 (0f, -0.29f * CharacterSprite.ScaleY); characterGroundSensorShape.SetAsBox (((float)CharacterSize.Width - 1f) / PhysicsHandler.pixelPerMeter / 2, 5f / PhysicsHandler.pixelPerMeter, GroundSensorPosition, 0f); //untergrundsensor b2FixtureDef groundSensor = new b2FixtureDef (); groundSensor.isSensor = true; groundSensor.userData = WorldFixtureData.playergroundsensor; groundSensor.shape = characterGroundSensorShape; groundSensor.density = 0.0f; //Dichte groundSensor.friction = 0f; groundSensor.restitution = 0f; //Rückprall characterBody.CreateFixture (groundSensor); b2PolygonShape characterLeftSensorShape = new b2PolygonShape (); b2Vec2 LeftSensorPosition = new b2Vec2 (-0.15f * CharacterSprite.ScaleX, -0.5f); characterLeftSensorShape.SetAsBox ((float)5f / PhysicsHandler.pixelPerMeter, CharacterSize.Height / PhysicsHandler.pixelPerMeter / 4, LeftSensorPosition, 0f); //leftsensor b2FixtureDef leftSensor = new b2FixtureDef (); leftSensor.isSensor = true; leftSensor.userData = WorldFixtureData.playerleftsensor; leftSensor.shape = characterLeftSensorShape; leftSensor.density = 0.0f; //Dichte leftSensor.friction = 0f; leftSensor.restitution = 0f; //Rückprall characterBody.CreateFixture (leftSensor); b2PolygonShape characterRightSensorShape = new b2PolygonShape (); b2Vec2 RightSensorPosition = new b2Vec2 (0.15f * CharacterSprite.ScaleX, -0.5f); characterRightSensorShape.SetAsBox ((float)5f / PhysicsHandler.pixelPerMeter, CharacterSize.Height / PhysicsHandler.pixelPerMeter / 4, RightSensorPosition, 0f); //rightsensor b2FixtureDef rightSensor = new b2FixtureDef (); rightSensor.isSensor = true; rightSensor.userData = WorldFixtureData.playerrightsensor; rightSensor.shape = characterRightSensorShape; rightSensor.density = 0.0f; //Dichte rightSensor.friction = 0f; rightSensor.restitution = 0f; //Rückprall characterBody.CreateFixture (rightSensor); } return characterBody; }
static void ApplyForce() { _world.Gravity = b2Vec2.Zero; float k_restitution = 0.4f; b2Body ground; { b2BodyDef bd = b2BodyDef.Create(); bd.position.Set(0.0f, 20.0f); ground = _world.CreateBody(bd); b2EdgeShape shape = new b2EdgeShape(); b2FixtureDef sd = b2FixtureDef.Create(); sd.shape = shape; sd.density = 0.0f; sd.restitution = k_restitution; // Left vertical shape.Set(new b2Vec2(-20.0f, -20.0f), new b2Vec2(-20.0f, 20.0f)); ground.CreateFixture(sd); // Right vertical shape.Set(new b2Vec2(20.0f, -20.0f), new b2Vec2(20.0f, 20.0f)); ground.CreateFixture(sd); // Top horizontal shape.Set(new b2Vec2(-20.0f, 20.0f), new b2Vec2(20.0f, 20.0f)); ground.CreateFixture(sd); // Bottom horizontal shape.Set(new b2Vec2(-20.0f, -20.0f), new b2Vec2(20.0f, -20.0f)); ground.CreateFixture(sd); } { b2Transform xf1 = new b2Transform(); xf1.q.Set(0.3524f * b2Settings.b2_pi); xf1.p = xf1.q.GetXAxis(); b2Vec2[] vertices = new b2Vec2[3]; vertices[0] = b2Math.b2Mul(xf1, new b2Vec2(-1.0f, 0.0f)); vertices[1] = b2Math.b2Mul(xf1, new b2Vec2(1.0f, 0.0f)); vertices[2] = b2Math.b2Mul(xf1, new b2Vec2(0.0f, 0.5f)); b2PolygonShape poly1 = new b2PolygonShape(); poly1.Set(vertices, 3); b2FixtureDef sd1 = b2FixtureDef.Create(); sd1.shape = poly1; sd1.density = 4.0f; b2Transform xf2 = new b2Transform(); xf2.q.Set(-0.3524f * b2Settings.b2_pi); xf2.p = -xf2.q.GetXAxis(); vertices[0] = b2Math.b2Mul(xf2, new b2Vec2(-1.0f, 0.0f)); vertices[1] = b2Math.b2Mul(xf2, new b2Vec2(1.0f, 0.0f)); vertices[2] = b2Math.b2Mul(xf2, new b2Vec2(0.0f, 0.5f)); b2PolygonShape poly2 = new b2PolygonShape(); poly2.Set(vertices, 3); b2FixtureDef sd2 = b2FixtureDef.Create(); sd2.shape = poly2; sd2.density = 2.0f; b2BodyDef bd = b2BodyDef.Create(); bd.type = b2BodyType.b2_dynamicBody; bd.angularDamping = 5.0f; bd.linearDamping = 0.1f; bd.position = new b2Vec2(0.0f, 2.0f); bd.angle = b2Settings.b2_pi; bd.allowSleep = false; m_body = _world.CreateBody(bd); m_body.CreateFixture(sd1); m_body.CreateFixture(sd2); } { b2PolygonShape shape = new b2PolygonShape(); shape.SetAsBox(0.5f, 0.5f); b2FixtureDef fd = b2FixtureDef.Create(); fd.shape = shape; fd.density = 1.0f; fd.friction = 0.3f; for (int i = 0; i < 10; ++i) { b2BodyDef bd = b2BodyDef.Create(); bd.type = b2BodyType.b2_dynamicBody; bd.position = new b2Vec2(0.0f, 5.0f + 1.54f * i); b2Body body = _world.CreateBody(bd); body.CreateFixture(fd); float gravity = 10.0f; float I = body.Inertia; float mass = body.Mass; // For a circle: I = 0.5 * m * r * r ==> r = sqrt(2 * I / m) float radius = b2Math.b2Sqrt(2.0f * I / mass); b2FrictionJointDef jd = new b2FrictionJointDef(); jd.localAnchorA.SetZero(); jd.localAnchorB.SetZero(); jd.BodyA = ground; jd.BodyB = body; jd.CollideConnected = true; jd.maxForce = mass * gravity; jd.maxTorque = mass * radius * gravity; _world.CreateJoint(jd); } } }
public LiquidTest() { hash = new List<int>[40, 40]; for (int i = 0; i < 40; ++i) { for (int j = 0; j < 40; ++j) { hash[i, j] = new List<int>(); } } hashWidth = 40; hashHeight = 40; //if (firstTime) //{ // setCamera(new Vec2(0, 2), 35f); // firstTime = false; //} //m_getWorld().setGravity(new Vec2(0.0f,0.0f)); b2Body ground = null; { b2BodyDef bd = new b2BodyDef(); bd.position.Set(0.0f, 0.0f); ground = m_world.CreateBody(bd); b2PolygonShape shape = new b2PolygonShape(); shape.SetAsBox(5.0f, 0.5f); ground.CreateFixture(shape, 0); shape.SetAsBox(1.0f, 0.2f, new b2Vec2(0.0f, 4.0f), -0.2f); ground.CreateFixture(shape, 0); shape.SetAsBox(1.5f, 0.2f, new b2Vec2(-1.2f, 5.2f), -1.5f); ground.CreateFixture(shape, 0); shape.SetAsBox(0.5f, 50.0f, new b2Vec2(5.0f, 0.0f), 0.0f); ground.CreateFixture(shape, 0); shape.SetAsBox(0.5f, 3.0f, new b2Vec2(-8.0f, 0.0f), 0.0f); ground.CreateFixture(shape, 0); shape.SetAsBox(2.0f, 0.1f, new b2Vec2(-6.0f, -2.8f), 0.1f); ground.CreateFixture(shape, 0); b2CircleShape cd = new b2CircleShape(); cd.Radius = 0.5f; cd.Position.Set(-0.5f, -4.0f); ground.CreateFixture(cd, 0); } liquid = new b2Body[nParticles]; float massPerParticle = totalMass / nParticles; // PointDef pd = new PointDef(); // pd.mass = massPerParticle; // pd.restitution = 0.0f; // pd.filter.groupIndex = -10; b2CircleShape pd = new b2CircleShape(); b2FixtureDef fd = new b2FixtureDef(); fd.shape = pd; fd.density = 1f; fd.filter.groupIndex = -10; pd.Radius = .05f; fd.restitution = 0.4f; fd.friction = 0.0f; float cx = 0.0f; float cy = 25.0f; for (int i = 0; i < nParticles; ++i) { b2BodyDef bd = new b2BodyDef(); bd.position = new b2Vec2(Rand.RandomFloat(cx - boxWidth * .5f, cx + boxWidth * .5f), Rand.RandomFloat(cy - boxHeight * .5f, cy + boxHeight * .5f)); bd.fixedRotation = true; bd.type = b2BodyType.b2_dynamicBody; b2Body b = m_world.CreateBody(bd); b.CreateFixture(fd).UserData = LIQUID_INT; b2MassData md = new b2MassData(); md.mass = massPerParticle; md.I = 1.0f; b.SetMassData(md); b.SetSleepingAllowed(false); liquid[i] = b; } b2PolygonShape polyDef = new b2PolygonShape(); polyDef.SetAsBox(Rand.RandomFloat(0.3f, 0.7f), Rand.RandomFloat(0.3f, 0.7f)); b2BodyDef bodyDef = new b2BodyDef(); bodyDef.position = new b2Vec2(0.0f, 25.0f); bodyDef.type = b2BodyType.b2_dynamicBody; bod = m_world.CreateBody(bodyDef); bod.CreateFixture(polyDef, 1f); }
private void checkBounds() { for (int i = 0; i < liquid.Length; ++i) { if (liquid[i].WorldCenter.y < -10.0f) { m_world.DestroyBody(liquid[i]); float massPerParticle = totalMass / nParticles; var pd = new b2CircleShape(); var fd = new b2FixtureDef(); fd.shape = pd; fd.density = 1.0f; fd.filter.groupIndex = -10; pd.Radius = .05f; fd.restitution = 0.4f; fd.friction = 0.0f; float cx = 0.0f + Rand.RandomFloat(-0.6f, 0.6f); float cy = 15.0f + Rand.RandomFloat(-2.3f, 2.0f); var bd = new b2BodyDef(); bd.position = new b2Vec2(cx, cy); bd.fixedRotation = true; bd.type = b2BodyType.b2_dynamicBody; var b = m_world.CreateBody(bd); b.CreateFixture(fd).UserData = LIQUID_INT; var md = new b2MassData(); md.mass = massPerParticle; md.I = 1.0f; b.SetMassData(md); b.SetSleepingAllowed(false); liquid[i] = b; } } if (bod.WorldCenter.y < -15.0f) { m_world.DestroyBody(bod); var polyDef = new b2PolygonShape(); polyDef.SetAsBox(Rand.RandomFloat(0.3f, 0.7f), Rand.RandomFloat(0.3f, 0.7f)); var bodyDef = new b2BodyDef(); bodyDef.position = new b2Vec2(0.0f, 25.0f); bodyDef.type = b2BodyType.b2_dynamicBody; bod = m_world.CreateBody(bodyDef); bod.CreateFixture(polyDef, 1f); } }
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); }
private void defineGround(float mapSizeWidth) { //definiert den Boden b2BodyDef groundDef = new b2BodyDef (); groundDef.position = new b2Vec2 (0, -3f); Ground = gameWorld.CreateBody(groundDef); b2PolygonShape groundShape = new b2PolygonShape (); groundShape.SetAsBox (mapSizeWidth, 3f); Ground.CreateFixture (groundShape,0.0f); }