[Silverlight] farseer engine game

Source: Internet
Author: User

This is a small game made with the farseer physical engine. The gameplay is very simple: use the mouse to control the position of the white ball and try not to let the white ball touch the black ball. The farther away from the center, the less the score.

This is what I have learned about farseer. I am also the first time in contact with the physical engine. I only use a few features of the engine. Write down the learning and production experience for your reference only. [For details, refer to the source code .]

For those who have never understood the physical engine, the concept of the physical engine must be clarified. The physical engine is an engine that simulates and computes the mathematical model of an object. It uses data models internally, rather than the actual interface you see.

Farseer physical engine official documentation: http://farseerphysics.codeplex.com/documentation

An example of farseer: http://www.cnblogs.com/Aimeast/archive/2011/03/14/1984268.html

To simulate a moving object, four things are required: the World, a body, a shape and a fixture. What you need to do to develop a game using the farseer physical engine is to use the physical engine to build the data model of the simulated object and use the Loop Mechanism to drive the engine to run; then, associate the entire model with the input/output system.

First, we establish a loop mechanism. Use the storyboard provided by Silverlight to establish a loop.

Storyboard _gameLoop = new Storyboard();_gameLoop.Completed += new EventHandler(GameLoop);_gameLoop.Begin();private void GameLoop(object sender, EventArgs e){    //ToDo    _gameLoop.Begin();}

A game loop without any control will consume CPU resources. Therefore, we need to add a time control parameter to set a wait time for the storyboard. Duration Attribute.

Then, the model of the moving area boundary and moving object is established. Because the farseer engine does not support the direct creation of an inner-empty model, the circular boundary is formed by splicing several line segments.

            List<Vertices> borders = new List<Vertices>(GameSettings.NumberOfEdges);            float stepSize = (float)(2.0 * Math.PI / GameSettings.NumberOfEdges);            for (int i = 0; i < GameSettings.NumberOfEdges; i++)            {                Vertices v = PolygonTools.CreateLine(                    new Vector2(_gameRadius * (float)Math.Cos(i * stepSize), _gameRadius * (float)Math.Sin(i * stepSize)),                    new Vector2(_gameRadius * (float)Math.Cos((i + 1) * stepSize), _gameRadius * (float)Math.Sin((i + 1) * stepSize))                    );                v.Translate(_gameCenter);                borders.Add(v);            }            _border = BodyFactory.CreateCompoundPolygon(_world, borders, 1);

Create a ball model (for the ball class, see below)

            _balls = new List<Ball>();            Ball ball = new Ball(_gameCanvas, _world, Colors.White, false);            ball.Body.Position = _gameCenter;            ball.Body.OnCollision += new OnCollisionEventHandler(Ball_OnCollision);            _balls.Add(ball);            for (int i = 0; i < GameSettings.InitializeBallCount; i++)            {                ball = new Ball(_gameCanvas, _world, Colors.Black, true);                ball.Body.LinearVelocity = new Vector2(Tools.NextRangeFloat(GameSettings.BallInitializeVelocity),                    Tools.NextRangeFloat(GameSettings.BallInitializeVelocity));                ball.Body.Position = _gameCenter;                _balls.Add(ball);            }

Create a ball display interface. Use a ball. CS driver.

using System.Windows;using System.Windows.Controls;using System.Windows.Media;using System.Windows.Shapes;using FarseerPhysics.Dynamics;using FarseerPhysics.Factories;namespace SpeedGame{    public class Ball    {        private FrameworkElement element = null;        public Body Body { get; private set; }        public Ball(Canvas canvas, World world, Color color, bool isDynamic)        {            Body = BodyFactory.CreateCircle(world, GameSettings.BallRadius, 1);            if (isDynamic)            {                Body.BodyType = BodyType.Dynamic;                Body.Friction = 0f;                Body.Mass = 0f;                /*                 * 0 = fully absorb the collision : dont bounce at all : inelastic collision                 * 1 = perfect reflection : fully bounce back : elastic collision                 */                Body.Restitution = 1.0f;                Body.SleepingAllowed = false;            }            element = new Ellipse            {                Width = ConvertUnits.ToDisplayUnits(GameSettings.BallRadius * 2),                Height = ConvertUnits.ToDisplayUnits(GameSettings.BallRadius * 2),                Fill = new SolidColorBrush(color)            };            //Add objects to Game content so it renders            canvas.Children.Add(element);        }        public void Update()        {            //Move to correct location            TranslateTransform TT = new TranslateTransform();            TT.X = ConvertUnits.ToDisplayUnits(Body.Position.X) - element.ActualWidth / 2;            TT.Y = ConvertUnits.ToDisplayUnits(Body.Position.Y) - element.ActualHeight / 2;            TransformGroup transformGroup = new TransformGroup();            transformGroup.Children.Add(TT);            element.RenderTransform = transformGroup;        }    }}

In addition, the input information processing module and scoring module need to be set up. No code is posted here. You can view it in the source code Input Folder.

Let's talk about some problems encountered during the establishment process.

  1. The length units used in the simulated environment and the display environment are inconsistent. You need to convert the two units. The convertunits class is used here for conversion.
  2. By default, the farseer engine sets that the object running speed cannot exceed 64. You can set this parameter in settings. maxtranslation of the source code.
  3. The farseer engine provides automatic adaptation. If you do not perform the operation for a long time, it may enter the "Sleep" status.
  4. The default object collision is non-elastic collision. You can set X. Body. Restitution to determine whether it is an elastic collision (1) or an elastic collision (0), or between the two.

In this way, it is quite simple to build a game. However, it is difficult to do it by yourself, and many details need to be considered. If you are interested, hurry up and use the physical engine to make a game of your own!

 

PS: this game was just made out of boredom, and many details were not taken into account. For example, the scoring policy is not perfect, and many vulnerabilities can be exploited. Please give more comments and suggestions. Select debug to configure the environment for local testing.

 

In addition, Have you studied the farseer official farseer physics engine 3.3.1 simplesamples Silverlight friends? How does one automatically convert the body into an element on the interface?

 

Source code download: http://files.cnblogs.com/Aimeast/SLSpeedGame.zip

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.