Example #1
0
        public void Initialize(float mapSizeWidth, Character Character, CCTileMapLayer physicsLayer, CCTileMap physicsMap, Container gameContainer)
        {
            mapSizeWidth /= pixelPerMeter;
            gameWorld = new b2World (new b2Vec2 (0, -9.8f));
            gameWorld.AllowSleep = false;

            //definiert den MainCharacter
            Character.createPhysicsBody (gameWorld);
            defineGround (mapSizeWidth);

            createBox2DWorldByLayer (physicsLayer, physicsMap);

            debugDrawer = new DebugDraw ();
            gameWorld.SetDebugDraw (debugDrawer);
            debugDrawer.AppendFlags (b2DrawFlags.e_shapeBit);

            collusionSensor = new CollusionSensor (gameContainer);
            gameWorld.SetContactListener (collusionSensor);
        }
		protected override void AddedToScene()
		{
			base.AddedToScene();

			layerInstance = this;

			//get screen size
			screenSize = Window.WindowSizeInPixels; //CCDirector::sharedDirector()->getWinSize();



			//INITIAL VARIABLES.... (D O N T    E D I T )

			// enable touches
#if XBOX || OUYA
            TouchEnabled = false;
            GamePadEnabled = true;
#else
			//TouchEnabled = true;

			CCEventListenerTouchAllAtOnce tListener = new CCEventListenerTouchAllAtOnce();

			tListener.OnTouchesBegan = TouchesBegan;
			//tListener.OnTouchesCancelled = TouchesCancelled;
			tListener.OnTouchesEnded = TouchesEnded;
			tListener.OnTouchesMoved = TouchesMoved;

			AddEventListener(tListener, this);

#endif


			// enable accelerometer
			//AccelerometerEnabled = false;

#if iPHONE || iOS
			IS_IPAD = MonoTouch.UIKit.UIDevice.CurrentDevice.UserInterfaceIdiom 
				== MonoTouch.UIKit.UIUserInterfaceIdiom.Pad;

			IS_RETINA = MonoTouch.UIKit.UIScreen.MainScreen.Bounds.Height 
				* MonoTouch.UIKit.UIScreen.MainScreen.Scale >= 1136;
#endif
#if WINDOWS || MACOS || MONOMAC || LINUX || OUYA || XBOX
			IS_IPAD = true;
			IS_RETINA = true;
#endif

			IS_IPHONE = !IS_IPAD;

			// ask director for the window size
			screenWidth = (int)screenSize.Width;
			screenHeight = (int)screenSize.Height;

			throwInProgress = false; //is a throw currently in progress, as in, is a ninja in midair (mostly used to prevent tossing two ninjas, one right after another)
			areWeInTheStartingPosition = true;  //is the world back at 0 on the X axis (if yes, then we can put a ninja in the sling)

			throwCount = 0;
			dotTotalOnOddNumberedTurn = 0;
			dotTotalOnEvenNumberedTurn = 0;

			currentLevel = GameData.SharedData.Level;  // use currentLevel =  0 for testing new shapes, will call [self buildLevelWithAllShapes];

			pointTotalThisRound = 0;
			pointsToPassLevel = GameData.SharedData.PointsToPassLevel;
			bonusPerExtraNinja = GameData.SharedData.BonusPerExtraNinja;

			CCLog.Log(string.Format("The level is {0}, you need {1} to move up a level", currentLevel, pointsToPassLevel));

			//PREFERENCE VARIABLES....

			openWithMenuInsteadOfGame = false; // start with the menu opening the game

			continuePanningScreenOnFingerRelease = true; // if the screen panning is midway between either the sling or targets, when you release your finger the screen will continue panning the last direction it moved (jumpy on iPhone if set to NO)
			reverseHowFingerPansScreen = false; //switch to yes to reverse. 
			topRightTouchEnablesDebugMode = true;  //SET TO NO IN FINAL BUILD
			useImagesForPointScoreLabels = true; //IF NO, means you use Marker Felt text for scores

			//set up background art

			backgroundLayerClouds = new CCSprite(GameData.SharedData.BackgroundCloudsFileName);  // will return the background clouds file for a particular level
			AddChild(backgroundLayerClouds, Constants.DepthClouds);

			backgroundLayerHills = new CCSprite(GameData.SharedData.BackgroundHillsFileName);  // will return the background hills file for a particular level
			AddChild(backgroundLayerHills, Constants.DepthHills);
			backgroundLayerHills.ScaleX = 1.05f;

			slingShotFront = new CCSprite("slingshot_front");
			AddChild(slingShotFront, Constants.DepthSlingShotFront);

			strapFront = new CCSprite("strap");
			AddChild(strapFront, Constants.DepthStrapFront);


			strapBack = new CCSprite("strapBack");
			AddChild(strapBack, Constants.DepthStrapBack);

			strapEmpty = new CCSprite("strapEmpty");
			AddChild(strapEmpty, Constants.DepthStrapBack);


			strapBack.Visible = false;  //visible only when stretching
			strapFront.Visible = false; //visible only when stretching



			//setup positions and variables for iPad devices or iPhones

			if (IS_IPAD)
			{
				areWeOnTheIPad = true;

				//vars 

				maxStretchOfSlingShot = 75; //best to leave as is, since this value ties in closely to the image size of strap.png. (should be 1/4 the size of the source image)
				multipyThrowPower = 1; // fine tune how powerful the sling shot is. Range is probably best between .5 to 1.5, currently for the iPad 1.0 is good

				worldMaxHorizontalShift = -(screenWidth);  // This determines how far the user can slide left or right to see the entire board. Always a negative number. 
				maxScaleDownValue = 1.0f; //dont change
				scaleAmount = 0; // increment to change the scale of the entire world when panning  
				initialPanAmount = 30; //how fast the screen pan starts
				extraAmountOnPanBack = 10; // I like a faster pan back. Adding a bit more
				adjustY = 0; // best to leave at 0 for iPad (moves the world down when panning)

				//background stuff

				backgroundLayerClouds.Position = new CCPoint(screenWidth, screenHeight / 2);
				backgroundLayerHills.Position = new CCPoint(screenWidth, screenHeight / 2);

				if (!IS_RETINA)
				{


					//non retina adjustment


				}
				else
				{

					//retina adjustment

					backgroundLayerClouds.Scale = 2.0f;
					backgroundLayerHills.Scale = 2.0f;
				}


				menuStartPosition = new CCPoint(130, screenSize.Height - 24);
				currentScoreLabelStartPosition = new CCPoint(200, screenSize.Height - 60);
				highScoreLabelStartPosition = new CCPoint(200, screenSize.Height - 80);

				fontSizeForScore = 22;

				//ground plane and platform

				groundPlaneStartPosition = new CCPoint(screenWidth, 50);
				platformStartPosition = new CCPoint(340, 190);

				//sling shot
				slingShotCenterPosition = new CCPoint(370, 255);

				slingShotFront.Position = new CCPoint(374, 240);
				strapFront.Position = new CCPoint(slingShotCenterPosition.X, slingShotCenterPosition.Y);
				strapBack.Position = new CCPoint(slingShotCenterPosition.X + 33, slingShotCenterPosition.Y - 10);
				strapEmpty.Position = new CCPoint(378, 235);

				//ninja

				ninjaStartPosition1 = new CCPoint(380, 250);
				ninjaStartPosition2 = new CCPoint(300, 155);
				ninjaStartPosition3 = new CCPoint(260, 155);
				ninjaStartPosition4 = new CCPoint(200, 120);
				ninjaStartPosition5 = new CCPoint(160, 120);

			}

			else if (IS_IPHONE)
			{
				//CCLOG (@"this is an iphone");

				areWeOnTheIPad = false;

				//vars 
				maxStretchOfSlingShot = 75; //best to leave as is, since this value ties in closely to the image size of strap.png. (should be 1/4 the size of the source image)
				multipyThrowPower = 1.0f; // fine tune how powerful the sling shot is. Range is probably best between .5 to 1.5, and a little goes a long way

				worldMaxHorizontalShift = -(screenWidth); // This determines how far the user can slide left or right to see the entire board. Always a negative number
				maxScaleDownValue = 0.65f; //range should probably be between 0.75 and 1.0;
				scaleAmount = .01f; // increment to change the scale of the entire world when panning
				adjustY = -34;

				initialPanAmount = 20; //how fast the screen pan starts
				extraAmountOnPanBack = 0; // best to leave at 0 on iPhone

				//background stuff



				if (!IS_RETINA)
				{

					//non retina adjustment

					backgroundLayerClouds.Position = new CCPoint(screenWidth, 192);
					backgroundLayerClouds.Scale = .7f;
					backgroundLayerHills.Position = new CCPoint(screenWidth, 245);
					backgroundLayerHills.Scale = .7f;

				}
				else
				{

					//retina adjustment

					backgroundLayerClouds.Position = new CCPoint(screenWidth, 192);
					backgroundLayerClouds.Scale = 1.7f;
					backgroundLayerHills.Position = new CCPoint(screenWidth, 265);
					backgroundLayerHills.Scale = 1.7f;
				}



				menuStartPosition = new CCPoint(70, screenSize.Height - 17);
				currentScoreLabelStartPosition = new CCPoint(140, screenSize.Height - 50); //score label
				highScoreLabelStartPosition = new CCPoint(140, screenSize.Height - 70);
				fontSizeForScore = 18;

				//ground plane and platform

				groundPlaneStartPosition = new CCPoint(screenWidth, -25);
				platformStartPosition = new CCPoint(130, 120);

				//sling shot

				slingShotCenterPosition = new CCPoint(160, 185);
				slingShotFront.Position = new CCPoint(164, 170);
				strapFront.Position = new CCPoint(slingShotCenterPosition.X, slingShotCenterPosition.Y);
				strapBack.Position = new CCPoint(slingShotCenterPosition.X + 33, slingShotCenterPosition.Y - 10);
				strapEmpty.Position = new CCPoint(168, 163);

				//ninja

				ninjaStartPosition1 = new CCPoint(170, 175);
				ninjaStartPosition2 = new CCPoint(110, 82);
				ninjaStartPosition3 = new CCPoint(65, 82);
				ninjaStartPosition4 = new CCPoint(90, 65);
				ninjaStartPosition5 = new CCPoint(43, 65);



			}

			SetUpParticleSystemSun();

			CCMenuItemImage button1 = new CCMenuItemImage("gameMenu", "gameMenu", ShowMenu);

			MenuButton = new CCMenu(button1);
			MenuButton.Position = menuStartPosition;
			AddChild(MenuButton, Constants.DepthScore);



			// assign CCPoints to keep track of the starting positions of objects that move relative to the entire layer.

			hillsLayerStartPosition = backgroundLayerHills.Position;
			cloudLayerStartPosition = backgroundLayerClouds.Position;

			// Define the gravity vector.

			yAxisGravity = -9.81f;

			b2Vec2 gravity = b2Vec2.Zero;
			gravity.Set(0.0f, yAxisGravity);


			// Construct a world object, which will hold and simulate the rigid bodies.
			world = new b2World(gravity);

			world.AllowSleep = false;

			world.SetContinuousPhysics(true);

			//EnableDebugMode();


			// Define the ground body.
			var groundBodyDef = new b2BodyDef();  // Make sure we call 
			groundBodyDef.position.Set(0, 0); // bottom-left corner

			// Call the body factory which allocates memory for the ground body
			// from a pool and creates the ground box shape (also from a pool).
			// The body is also added to the world.
			b2Body groundBody = world.CreateBody(groundBodyDef);

			// Define the ground box shape.
			b2EdgeShape groundBox = new b2EdgeShape();

			int worldMaxWidth = screenWidth * 4; //If you ever want the BOX2D world width to be more than it is then increase this  (currently, this should be plenty of extra space)
			int worldMaxHeight = screenHeight * 3; //If you ever want the BOX2D world height to be more  than it is then increase this (currently, this should be plenty of extra space)

			// bottom
			groundBox.Set(new b2Vec2(-4, 0), new b2Vec2(worldMaxWidth / Constants.PTM_RATIO, 0));
			groundBody.CreateFixture(groundBox, 0);

			// top
			groundBox.Set(new b2Vec2(-4, worldMaxHeight / Constants.PTM_RATIO), new b2Vec2(worldMaxWidth / Constants.PTM_RATIO, worldMaxHeight / Constants.PTM_RATIO));
			groundBody.CreateFixture(groundBox, 0);

			// left
			groundBox.Set(new b2Vec2(-4, worldMaxHeight / Constants.PTM_RATIO), new b2Vec2(-4, 0));
			groundBody.CreateFixture(groundBox, 0);

			// right
			groundBox.Set(new b2Vec2(worldMaxWidth / Constants.PTM_RATIO, worldMaxHeight / Constants.PTM_RATIO), new b2Vec2(worldMaxWidth / Constants.PTM_RATIO, 0));
			groundBody.CreateFixture(groundBox, 0);

			//Contact listener 
			contactListener = new ContactListener();
			world.SetContactListener(contactListener);

			//Set up the ground plane

			theGroundPlane = new GroundPlane(world, groundPlaneStartPosition, GameData.SharedData.GroundPlaneFileName);
			AddChild(theGroundPlane, Constants.DepthFloor);


			//Set up the starting platform

			thePlatform = new StartPlatform(world, platformStartPosition, "platform");
			AddChild(thePlatform, Constants.DepthPlatform);

			//Set up ninjas

			ninjaBeingThrown = 1; //always starts at 1 (first ninja, then second ninja, and so on) 
			ninjasToTossThisLevel = GameData.SharedData.NumberOfNinjasToTossThisLevel;  //total number of ninjas to toss for this level



			ninja1 = new Ninja(world, ninjaStartPosition1, @"ninja");
			AddChild(ninja1, Constants.DepthNinjas);

			currentBodyNode = ninja1;

			currentBodyNode.SpriteInSlingState();

			if (ninjasToTossThisLevel >= 2)
			{

				ninja2 = new Ninja(world, ninjaStartPosition2, @"ninjaRed");
				AddChild(ninja2, Constants.DepthNinjas);
				ninja2.SpriteInStandingState();

			}
			if (ninjasToTossThisLevel >= 3)
			{

				ninja3 = new Ninja(world, ninjaStartPosition3, @"ninjaBlue");
				AddChild(ninja3, Constants.DepthNinjas);
				ninja3.SpriteInStandingState();
			}
			if (ninjasToTossThisLevel >= 4)
			{

				ninja4 = new Ninja(world, ninjaStartPosition4, @"ninjaBrown");
				AddChild(ninja4, Constants.DepthNinjas);
				ninja4.SpriteInStandingState();
			}
			if (ninjasToTossThisLevel >= 5)
			{

				ninja5 = new Ninja(world, ninjaStartPosition5, @"ninjaGreen");
				AddChild(ninja5, Constants.DepthNinjas);
				ninja5.SpriteInStandingState();
			}

			//Build the Stack. 

			stack = new TheStack(world);
			AddChild(stack, Constants.DepthStack);


			//give the stack a moment to drop, then switches every pieces to static (locks it into position, until the first slingshot)...
			ScheduleOnce(SwitchAllStackObjectsToStatic, 1.0f);

			currentScoreLabel = new CCLabelTtf(String.Format("{0}: Needed", pointsToPassLevel), "MarkerFelt", fontSizeForScore);
			AddChild(currentScoreLabel, Constants.DepthScore);
			currentScoreLabel.Color = new CCColor3B(255, 255, 255);
			currentScoreLabel.Position = currentScoreLabelStartPosition;
			currentScoreLabel.AnchorPoint = new CCPoint(1, .5f);
			// HighScoreForLevel
			highScoreLabel = new CCLabelTtf(String.Format("High Score: {0}", GameData.SharedData.HighScoreForLevel), "MarkerFelt", fontSizeForScore);
			AddChild(highScoreLabel, Constants.DepthScore);
			highScoreLabel.Color = new CCColor3B(255, 255, 255);

			highScoreLabel.Position = currentScoreLabel.Position - new CCPoint(0, highScoreLabel.ContentSize.Height);// highScoreLabelStartPosition;
			highScoreLabel.AnchorPoint = new CCPoint(1, .5f);
			highScoreLabelStartPosition = highScoreLabel.Position;


			var levelString = string.Format("Level: {0}", currentLevel);
			ShowBoardMessage(levelString);

			CCLog.Log(" ");
			CCLog.Log(" ");
			CCLog.Log(" ");
			CCLog.Log("/////////////////////////////////////////////////////");
			CCLog.Log("/////////////////////////////////////////////////////");
			CCLog.Log(" ");
			CCLog.Log(" ");
			CCLog.Log(" ");
			CCLog.Log("The art and animation in this template is copyright CartoonSmart LLC");
			CCLog.Log("You must make significant changes to the art before submitting your game to the App Store");
			CCLog.Log("Please create your own characters, backgrounds, etc and spend the time to make the game look totally unique");
			CCLog.Log(" ");
			CCLog.Log(" ");
			CCLog.Log(" ");
			CCLog.Log("The Video guide for this template is at https://vimeo.com/cartoonsmart/angryninjasguide  ");
			CCLog.Log(" ");
			CCLog.Log(" ");
			CCLog.Log(" ");
			CCLog.Log("/////////////////////////////////////////////////////");
			CCLog.Log("/////////////////////////////////////////////////////");
			CCLog.Log(" ");
			CCLog.Log(" ");




			GameSounds.SharedGameSounds.IntroTag();

			if (GameData.SharedData.Level == 1)
			{

				GameSounds.SharedGameSounds.PlayBackgroundMusic(AmbientFXSounds.Frogs);

			}
			else
			{

				GameSounds.SharedGameSounds.PlayBackgroundMusic(AmbientFXSounds.Insects);
			}

			if (GameData.SharedData.FirstRunEver && openWithMenuInsteadOfGame)
			{
				CCLog.Log("First run ever");
				Schedule(ShowMenuFromSelector, 2f);
				GameData.SharedData.FirstRunEver = false;
			}

			// Always do this last.
			this.Schedule(Tick);
		}
Example #3
0
        public GameScene(Game game)
        {
            this.game = game;
            // ��ʼ��world
            b2Vec2 gravity = new b2Vec2(0f, -20f);
            world = new b2World(gravity);
            world.AllowSleep = false;
            InitBack();
            AddBarLayer();

            InitScore();
            AddGround();
            AddBird();
            world.SetContactListener(new BirdContactListener(this, (CCSprite)(birdBody.UserData)));
            this.schedule(tick);

            SimpleAudioEngine.sharedEngine().playBackgroundMusic(@"musics/background", true);
        }
Example #4
0
        public Test()
        {
            m_destructionListener = new DestructionListener();
            m_debugDraw = new CCBox2dDraw("fonts/arial-12", 1);

            b2Vec2 gravity = new b2Vec2();
            gravity.Set(0.0f, -10.0f);
            m_world = new b2World(gravity);
            m_bomb = null;
            m_textLine = 30;
            m_mouseJoint = null;
            m_pointCount = 0;

            m_destructionListener.test = this;
            m_world.SetDestructionListener(m_destructionListener);
            m_world.SetContactListener(this);
            m_world.SetDebugDraw(m_debugDraw);
            m_world.SetContinuousPhysics(true);
            m_world.SetWarmStarting(true);

            m_bombSpawning = false;

            m_stepCount = 0;

            b2BodyDef bodyDef = new b2BodyDef();
            m_groundBody = m_world.CreateBody(bodyDef);
        }
        public StarlingGameSpriteWithPhysics()
        {
            sessionid = random.Next();


            //b2Body ground_current = null;
            //b2Body air_current = null;




            #region ground_b2world
            // first frame  ... set up our physccs
            // zombies!!
            ground_b2world = new b2World(new b2Vec2(0, 0), false);
            ground_b2world.SetContactListener(
               new XContactListener()
            );

            var ground_b2debugDraw = new b2DebugDraw();

            ground_dd = new ScriptCoreLib.ActionScript.flash.display.Sprite();
            ground_dd.transform.colorTransform = new ColorTransform(0.0, 0, 1.0);





            ground_b2debugDraw.SetSprite(ground_dd);
            // textures are 512 pixels, while our svgs are 400px
            // so how big is a meter in our game world? :)
            ground_b2debugDraw.SetDrawScale(16);
            ground_b2debugDraw.SetFillAlpha(0.1);
            ground_b2debugDraw.SetLineThickness(1.0);
            ground_b2debugDraw.SetFlags(b2DebugDraw.e_shapeBit);

            ground_b2world.SetDebugDraw(ground_b2debugDraw);





            #endregion


            #region groundkarma_b2world
            // first frame  ... set up our physccs
            // zombies!!
            groundkarma_b2world = new b2World(new b2Vec2(0, 0), false);

            var groundkarma_b2debugDraw = new b2DebugDraw();

            groundkarma_dd = new ScriptCoreLib.ActionScript.flash.display.Sprite();
            groundkarma_dd.transform.colorTransform = new ColorTransform(0.0, 1.0, 0.0);





            groundkarma_b2debugDraw.SetSprite(groundkarma_dd);
            // textures are 512 pixels, while our svgs are 400px
            // so how big is a meter in our game world? :)
            groundkarma_b2debugDraw.SetDrawScale(16);
            groundkarma_b2debugDraw.SetFillAlpha(0.1);
            groundkarma_b2debugDraw.SetLineThickness(1.0);
            groundkarma_b2debugDraw.SetFlags(b2DebugDraw.e_shapeBit);

            groundkarma_b2world.SetDebugDraw(groundkarma_b2debugDraw);





            #endregion

            #region air_b2world
            // first frame  ... set up our physccs
            // zombies!!
            air_b2world = new b2World(new b2Vec2(0, 0), false);

            var air_b2debugDraw = new b2DebugDraw();

            air_dd = new ScriptCoreLib.ActionScript.flash.display.Sprite();

            // make it red!
            air_dd.transform.colorTransform = new ColorTransform(1.0, 0, 0);
            // make it slave
            air_dd.alpha = 0.3;





            air_b2debugDraw.SetSprite(air_dd);
            // textures are 512 pixels, while our svgs are 400px
            // so how big is a meter in our game world? :)
            air_b2debugDraw.SetDrawScale(16);
            air_b2debugDraw.SetFillAlpha(0.1);
            air_b2debugDraw.SetLineThickness(1.0);
            air_b2debugDraw.SetFlags(b2DebugDraw.e_shapeBit);

            air_b2world.SetDebugDraw(air_b2debugDraw);








            #endregion

            #region damage_b2world
            // first frame  ... set up our physccs
            // zombies!!
            damage_b2world = new b2World(new b2Vec2(0, 0), false);
            damage_b2world.SetContactListener(
               new XContactListener { DiscardSmallImpulse = false }
            );

            var damage_b2debugDraw = new b2DebugDraw();

            damage_dd = new ScriptCoreLib.ActionScript.flash.display.Sprite();

            // make it red!
            //air_dd.transform.colorTransform = new ColorTransform(1.0, 0, 0);
            // make it slave
            damage_dd.alpha = 0.3;





            damage_b2debugDraw.SetSprite(air_dd);
            // textures are 512 pixels, while our svgs are 400px
            // so how big is a meter in our game world? :)
            damage_b2debugDraw.SetDrawScale(16);
            damage_b2debugDraw.SetFillAlpha(0.1);
            damage_b2debugDraw.SetLineThickness(1.0);
            damage_b2debugDraw.SetFlags(b2DebugDraw.e_shapeBit);

            damage_b2world.SetDebugDraw(damage_b2debugDraw);








            #endregion

            #region smoke_b2world
            // first frame  ... set up our physccs
            // zombies!!
            smoke_b2world = new b2World(new b2Vec2(0, 0), false);

            var smoke_b2debugDraw = new b2DebugDraw();

            smoke_dd = new ScriptCoreLib.ActionScript.flash.display.Sprite();

            // make it red!
            //air_dd.transform.colorTransform = new ColorTransform(1.0, 0, 0);
            // make it slave
            smoke_dd.alpha = 0.3;





            smoke_b2debugDraw.SetSprite(air_dd);
            // textures are 512 pixels, while our svgs are 400px
            // so how big is a meter in our game world? :)
            smoke_b2debugDraw.SetDrawScale(16);
            smoke_b2debugDraw.SetFillAlpha(0.1);
            smoke_b2debugDraw.SetLineThickness(1.0);
            smoke_b2debugDraw.SetFlags(b2DebugDraw.e_shapeBit);

            smoke_b2world.SetDebugDraw(smoke_b2debugDraw);








            #endregion



            //#region obstacles
            //{
            //    var bodyDef = new b2BodyDef();

            //    bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody;

            //    // stop moving if legs stop walking!
            //    bodyDef.linearDamping = 10.0;
            //    bodyDef.angularDamping = 0.3;
            //    //bodyDef.angle = 1.57079633;
            //    bodyDef.fixedRotation = true;

            //    var body = air_b2world.CreateBody(bodyDef);
            //    body.SetPosition(new b2Vec2(10, 10));

            //    var fixDef = new Box2D.Dynamics.b2FixtureDef();
            //    fixDef.density = 0.1;
            //    fixDef.friction = 0.01;
            //    fixDef.restitution = 0;


            //    fixDef.shape = new Box2D.Collision.Shapes.b2CircleShape(4);


            //    var fix = body.CreateFixture(fixDef);

            //    body.SetPosition(
            //        new b2Vec2(-8, 0)
            //    );
            //}

            //{
            //    var bodyDef = new b2BodyDef();

            //    bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody;

            //    // stop moving if legs stop walking!
            //    bodyDef.linearDamping = 10.0;
            //    bodyDef.angularDamping = 0.3;
            //    //bodyDef.angle = 1.57079633;
            //    bodyDef.fixedRotation = true;

            //    var body = ground_b2world.CreateBody(bodyDef);
            //    body.SetPosition(new b2Vec2(10, 10));

            //    var fixDef = new Box2D.Dynamics.b2FixtureDef();
            //    fixDef.density = 0.1;
            //    fixDef.friction = 0.01;
            //    fixDef.restitution = 0;


            //    fixDef.shape = new Box2D.Collision.Shapes.b2CircleShape(4);


            //    var fix = body.CreateFixture(fixDef);


            //    body.SetPosition(
            //        new b2Vec2(8, -8)
            //    );
            //}

            //{
            //    var bodyDef = new b2BodyDef();

            //    bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody;

            //    // stop moving if legs stop walking!
            //    bodyDef.linearDamping = 10.0;
            //    bodyDef.angularDamping = 0.3;
            //    //bodyDef.angle = 1.57079633;
            //    bodyDef.fixedRotation = true;

            //    var body = groundkarma_b2world.CreateBody(bodyDef);
            //    body.SetPosition(new b2Vec2(10, 10));

            //    var fixDef = new Box2D.Dynamics.b2FixtureDef();
            //    fixDef.density = 0.1;
            //    fixDef.friction = 0.01;
            //    fixDef.restitution = 0;


            //    fixDef.shape = new Box2D.Collision.Shapes.b2CircleShape(4);


            //    var fix = body.CreateFixture(fixDef);


            //    body.SetPosition(
            //        new b2Vec2(8, 8)
            //    );
            //}
            //#endregion


            physicstime.Start();

            this.onbeforefirstframe += (stage, s) =>
            {
                if (!disablephysicsdiagnostics)
                {
                    s.nativeOverlay.addChild(ground_dd);
                    s.nativeOverlay.addChild(groundkarma_dd);
                    s.nativeOverlay.addChild(air_dd);
                    s.nativeOverlay.addChild(damage_dd);
                }
                // 1000 / 15
                var syncframeinterval = 1000 / 15;
                var syncframesince = 0L;
                var syncframeextra = 0L;


                // NaN ?
                syncframeid = 0;
                syncframetime = 0;


                var prevvelocity = 0.0;
                onframe +=
                    delegate
                    {
                        // drop frames
                        //if (frameid % 2 == 0)
                        //    return;

                        var physicstime_elapsed = physicstime.ElapsedMilliseconds + syncframeextra;
                        syncframeextra = 0;

                        // physicstime_elapsed needs to be split!

                        var physicstime_elapsed_PRE = physicstime_elapsed;




                        physicstime.Restart();

                        // add up the time we are spending
                        syncframesince += physicstime_elapsed;

                        #region raise_onsyncframe
                        var raise_onsyncframe = false;
                        // time for sync frame yet?
                        if (syncframesince >= syncframeinterval)
                        {
                            // time for syncframe!
                            raise_onsyncframe = true;

                            // does it actually help us? disabled for now
                            var dx = syncframesince - syncframeinterval;
                            syncframesince = 0;

                            // Error: raise_onsyncframe: { physicstime_elapsed_PRE = 275, dx = 75, physicstime_elapsed_POST = 0 }

                            physicstime_elapsed_PRE -= dx;
                            syncframeextra += dx;


                            // dropping frames?
                            //syncframeextra = Math.Min(syncframeextra, syncframeinterval);
                        }
                        #endregion


                        var iterations = 10;

                        syncframetime += physicstime_elapsed_PRE;

                        #region PRE Step

                        //update physics world
                        ground_b2world.Step(physicstime_elapsed_PRE / 1000.0, iterations, iterations);
                        groundkarma_b2world.Step(physicstime_elapsed_PRE / 1000.0, iterations, iterations);
                        air_b2world.Step(physicstime_elapsed_PRE / 1000.0, iterations, iterations);
                        damage_b2world.Step(physicstime_elapsed_PRE / 1000.0, iterations, iterations);
                        smoke_b2world.Step(physicstime_elapsed_PRE / 1000.0, iterations, iterations);
                        #endregion

                        ground_b2world.ClearForces();
                        groundkarma_b2world.ClearForces();
                        air_b2world.ClearForces();
                        damage_b2world.ClearForces();
                        smoke_b2world.ClearForces();


                        #region DrawDebugData ClearForces
                        if (!disablephysicsdiagnostics)
                        {

                            ground_b2world.DrawDebugData();
                            groundkarma_b2world.DrawDebugData();
                            air_b2world.DrawDebugData();
                            damage_b2world.DrawDebugData();
                            smoke_b2world.DrawDebugData();
                        }
                        #endregion

                        // syncframe
                        if (raise_onsyncframe)
                        {
                            syncframeid++;
                            this.onsyncframe(stage, s);

                            foreach (var item in units)
                            {
                                item.FeedKarma();
                            }
                        }


                        #region air_dd vs ground_dd
                        if (current != null)
                            if (current.body.GetWorld() == air_b2world)
                            {
                                air_dd.alpha = 0.6;
                                ground_dd.alpha = 0.1;
                            }
                            else
                            {
                                air_dd.alpha = 0.1;
                                ground_dd.alpha = 0.6;
                            }
                        #endregion

                        #region DisableDefaultContentDransformation
                        DisableDefaultContentDransformation = true;
                        {
                            var cm = new Matrix();

                            var any_movement = 0.0;

                            if (current != null)
                            {
                                cm.translate(
                                    -(current.body.GetPosition().x * 16),
                                    -(current.body.GetPosition().y * 16)
                                );



                                cm.rotate(-current.body.GetAngle() - Math.PI / 2 + current.CameraRotation);


                                if (current.body.GetType() == Box2D.Dynamics.b2Body.b2_dynamicBody)
                                {
                                    any_movement = (
                                        current.body.GetLinearVelocity().Length() +
                                        Math.Abs(current.body.GetAngularVelocity())
                                        )

                                    / 15.0;
                                }
                                else
                                {
                                    // force movement mode in a building
                                    any_movement = 1.0;
                                }

                            }


                            //cm.rotate(-current.GetAngle());








                            move_zoom +=
                               (any_movement - 0.5) *
                                 physicstime_elapsed * 0.004;
                            move_zoom = move_zoom.Max(0.0).Min(1.0);

                            var xinternalscale = internalscale;

                            if (disable_movezoom_and_altitude_for_scale)
                            {
                                // nop
                            }
                            else
                            {
                                xinternalscale +=
                                    +0.20 * (1.0 - current.Altitude)
                                    + ((1.0 - move_zoom) * 0.04);
                            }

                            var diagonal = new __vec2
                            {
                                x = stage.stageWidth,
                                y = stage.stageHeight
                            };

                            //stagescale = xinternalscale * (stage.stageWidth) / (800.0);
                            stagescale = xinternalscale * (diagonal.GetLength()) / (1000.0);


                            cm.scale(stagescale, stagescale);


                            cm.translate(
                                (stage.stageWidth * 0.5),
                                (stage.stageHeight * internal_center_y)
                            );


                            Content.transformationMatrix = cm;

                            ground_dd.transform.matrix = cm;
                            groundkarma_dd.transform.matrix = cm;
                            air_dd.transform.matrix = cm;
                            damage_dd.transform.matrix = cm;
                        }
                        #endregion



                        foreach (var item in units)
                        {
                            item.ShowPositionAndAngle();

                            #region driverseat
                            if (item.driverseat != null)
                                if (item.driverseat.driver != null)
                                {
                                    var driver = item.driverseat.driver;

                                    driver.SetPositionAndAngle(


                                            item.body.GetPosition().x + Math.Cos(item.body.GetAngle() - Math.PI * 0.5 - item.CameraRotation) * 2.2,
                                            item.body.GetPosition().y + Math.Sin(item.body.GetAngle() - Math.PI * 0.5 - item.CameraRotation) * 2.2
                                        ,
                                        item.body.GetAngle() - item.CameraRotation
                                    );

                                    driver.ShowPositionAndAngle();
                                }
                            #endregion

                            item.ApplyVelocity();
                        }





                    };
            };


        }
Example #6
0
        static void SetupWorld(bool setupGround)
        {
            var gravity = new b2Vec2(0.0f, -10.0f);
            _world = new b2World(gravity);
            _world.SetAllowSleeping(true);
            _world.SetContinuousPhysics(true);
            _world.SetSubStepping(true);
            _world.SetWarmStarting(true);
            _world.SetDestructionListener(new Destructo());
            _world.SetContactListener(new Contacto());
            if (!setupGround)
            {
                return;
            }
            // Call the body factory which allocates memory for the ground body
            // from a pool and creates the ground box shape (also from a pool).
            // The body is also added to the world.
            b2BodyDef def = b2BodyDef.Create();
            def.allowSleep = true;
            def.position = b2Vec2.Zero;
            def.type = b2BodyType.b2_staticBody;
            b2Body groundBody = _world.CreateBody(def);
            groundBody.SetActive(true);

            // bottom
            b2EdgeShape groundBox = new b2EdgeShape();
            groundBox.Set(b2Vec2.Zero, new b2Vec2(width, 0));
            b2FixtureDef fd = b2FixtureDef.Create();
            fd.shape = groundBox;
            groundBody.CreateFixture(fd);

            // top
            groundBox = new b2EdgeShape();
            groundBox.Set(new b2Vec2(0, height), new b2Vec2(width, height));
            fd.shape = groundBox;
            groundBody.CreateFixture(fd);

            // left
            groundBox = new b2EdgeShape();
            groundBox.Set(new b2Vec2(0, height), b2Vec2.Zero);
            fd.shape = groundBox;
            groundBody.CreateFixture(fd);

            // right
            groundBox = new b2EdgeShape();
            groundBox.Set(new b2Vec2(width, height), new b2Vec2(width, 0));
            fd.shape = groundBox;
            groundBody.CreateFixture(fd);

            _world.Dump();
        }
Example #7
0
        private void InitB2World()
        {
            world = new Box2D.Dynamics.b2World(new Box2D.Common.b2Vec2(0, -100));
            world.SetContactListener(new Myb2Listener());
            world.SetAllowSleeping(true);
            world.SetContinuousPhysics(true);
            // Call the body factory which allocates memory for the ground body
            // from a pool and creates the ground box shape (also from a pool).
            // The body is also added to the world.
            def            = new b2BodyDef();
            def.allowSleep = true;
            def.position   = b2Vec2.Zero;
            def.type       = b2BodyType.b2_staticBody;
            b2Body groundBody = world.CreateBody(def);

            groundBody.SetActive(true);

            // Define the ground box shape.

            // bottom
            b2EdgeShape groundBox = new b2EdgeShape();

            groundBox.Set(b2Vec2.Zero, new b2Vec2(Resources.DisplayMetrics.WidthPixels, 0));
            b2FixtureDef fd = new b2FixtureDef();

            fd.shape = groundBox;
            groundBody.CreateFixture(fd);

            // top
            groundBox = new b2EdgeShape();
            groundBox.Set(new b2Vec2(0, Resources.DisplayMetrics.HeightPixels), new b2Vec2(Resources.DisplayMetrics.WidthPixels, Resources.DisplayMetrics.HeightPixels));
            fd.shape = groundBox;
            groundBody.CreateFixture(fd);

            // left
            groundBox = new b2EdgeShape();
            groundBox.Set(new b2Vec2(0, Resources.DisplayMetrics.HeightPixels), b2Vec2.Zero);
            fd.shape = groundBox;
            groundBody.CreateFixture(fd);

            // right
            groundBox = new b2EdgeShape();
            groundBox.Set(new b2Vec2(Resources.DisplayMetrics.WidthPixels, Resources.DisplayMetrics.HeightPixels), new b2Vec2(Resources.DisplayMetrics.WidthPixels, 0));
            fd.shape = groundBox;
            groundBody.CreateFixture(fd);

            //
            bodydef          = new b2BodyDef();
            bodydef.active   = true;
            bodydef.position = new b2Vec2(100, 100);
            bodydef.type     = b2BodyType.b2_dynamicBody;
            b2Body buttonBody = world.CreateBody(bodydef);

            buttonBody.SetActive(true);

            var shape = new b2EdgeShape();

            shape.Set(new b2Vec2(100, 100), new b2Vec2(150, 100));
            buttonBody.CreateFixture(new b2FixtureDef()
            {
                density = 10,
                shape   = shape,
            });
        }