Volver al Inicio Microsoft Student Tech Club: Universidad Libre

Tutorial de XNA: Aplicando Física. Parte 4.

En esta lección trataremos de colisiones entre varios objetos

Paso 1: Se genera un nuevo proyecto y se le hace referencia al motor de física como se vio en el capítulo anterior.

Paso 2: Las librerías que deben usarse en el programa

//Librerías del motor de física
using FarseerGames.FarseerPhysics;
using FarseerGames.FarseerPhysics.Collisions;
using FarseerGames.FarseerPhysics.Dynamics;
using FarseerGames.FarseerPhysics.Factories;

Paso 3: Se requiere una textura en forma rectangular

Paso 4: Las variables de clase

        //Textura del cuadrado
        private Texture2D TexturaCaja;
        //Simulador de física que conecta los diferentes cuerpos en un solo contexto físico
        PhysicsSimulator SimuladorFisica;
        //Cuerpos (usados por el simulador de física)
        Body CuerpoCaja;
        //Geometría de los cuerpos
        Geom GeometriaCaja;
        //Cajas a golpear
        private ObjetosJuego[] CajasGolpea;
        const int MAXCAJASGOLPEA = 5;

Paso 5: Lo que debe ir en el LoadContent

            //Crea el objeto SimuladorFisica y en el constructor se coloca el vector de gravedad
            SimuladorFisica = new PhysicsSimulator(new Vector2(0, 0));
            // TODO: use this.Content to load your game content here
            TexturaCaja = Content.Load<Texture2D>("Cuadrado");
            CuerpoCaja = BodyFactory.Instance.CreateRectangleBody(SimuladorFisica, TexturaCaja.Width, TexturaCaja.Height, 1);
            CuerpoCaja.Position = new Vector2(350, 100);
            GeometriaCaja = GeomFactory.Instance.CreateRectangleGeom(SimuladorFisica, CuerpoCaja, TexturaCaja.Width, TexturaCaja.Height);
            //Cargar e inicializar las cajas que se van a golpear
            CajasGolpea = new ObjetosJuego[MAXCAJASGOLPEA];
            for (int Cont = 0; Cont < MAXCAJASGOLPEA; Cont++)
            {
                CajasGolpea[Cont] = new ObjetosJuego(Content.Load<Texture2D>("Cuadrado"));
                CajasGolpea[Cont].CuerpoCajasGolpea = BodyFactory.Instance.CreateRectangleBody(SimuladorFisica, CajasGolpea[Cont].TexturaCajasGolpea.Width, CajasGolpea[Cont].TexturaCajasGolpea.Height, 1);
                CajasGolpea[Cont].GeometriaCajasGolpea = GeomFactory.Instance.CreateRectangleGeom(SimuladorFisica, CajasGolpea[Cont].CuerpoCajasGolpea, CajasGolpea[Cont].TexturaCajasGolpea.Width, CajasGolpea[Cont].TexturaCajasGolpea.Height);
                CajasGolpea[Cont].CuerpoCajasGolpea.Position = new Vector2((Cont + 1) * 100, 300);
            }

Paso 6: Lo que debe ir en Update

//Esta es una compilación condicional. El teclado y el mouse solo son leídos si la aplicación ejecuta en un PC
#if !XBOX
            const float IncrementoFuerza = 50;
            Vector2 Fuerza = Vector2.Zero;
            //Código para leer el teclado
            KeyboardState estadoTeclado = Keyboard.GetState();
            
            //Aplica un vector de fuerza a la caja
            if (estadoTeclado.IsKeyDown(Keys.A)) { Fuerza = new Vector2(-IncrementoFuerza, 0); }
            if (estadoTeclado.IsKeyDown(Keys.S)) { Fuerza = new Vector2(0, IncrementoFuerza); }
            if (estadoTeclado.IsKeyDown(Keys.D)) { Fuerza = new Vector2(IncrementoFuerza, 0); }
            if (estadoTeclado.IsKeyDown(Keys.W)) { Fuerza = new Vector2(0, -IncrementoFuerza); }
            CuerpoCaja.ApplyForce(Fuerza);
            //Aplica un vector de torque a la caja
            const float IncrementoTorque = 1000;
            float Torque = 0;
            if (estadoTeclado.IsKeyDown(Keys.Left)) { Torque = -IncrementoTorque; }
            if (estadoTeclado.IsKeyDown(Keys.Right)) { Torque = IncrementoTorque; }
            CuerpoCaja.ApplyTorque(Torque);
#endif
            //Actualiza el simulador de física
            SimuladorFisica.Update(gameTime.ElapsedGameTime.Milliseconds * 0.001f);

 

Paso 7: Lo que debe ir en Draw

            //Dibuja las cajas haciendo uso de la posición y rotación de los cuerpos dado por el motor de física
            spriteBatch.Begin(SpriteBlendMode.AlphaBlend);
            spriteBatch.Draw(TexturaCaja, CuerpoCaja.Position, null, Color.White, CuerpoCaja.Rotation,
                new Vector2(TexturaCaja.Width / 2, TexturaCaja.Height / 2), 1, SpriteEffects.None, 0);
            foreach (ObjetosJuego Cajas in CajasGolpea)
                spriteBatch.Draw(Cajas.TexturaCajasGolpea, Cajas.CuerpoCajasGolpea.Position, null, Color.White, Cajas.CuerpoCajasGolpea.Rotation,
                new Vector2(Cajas.TexturaCajasGolpea.Width / 2, Cajas.TexturaCajasGolpea.Height / 2), 1, SpriteEffects.None, 0);

Este es el código completo de Game1.cs

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
//Librerías del motor de física
using FarseerGames.FarseerPhysics;
using FarseerGames.FarseerPhysics.Collisions;
using FarseerGames.FarseerPhysics.Dynamics;
using FarseerGames.FarseerPhysics.Factories;
namespace GiraCuadrado
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        //Textura del cuadrado
        private Texture2D TexturaCaja;
        //Simulador de física que conecta los diferentes cuerpos en un solo contexto físico
        PhysicsSimulator SimuladorFisica;
        //Cuerpos (usados por el simulador de física)
        Body CuerpoCaja;
        //Geometría de los cuerpos
        Geom GeometriaCaja;
        //Cajas a golpear
        private ObjetosJuego[] CajasGolpea;
        const int MAXCAJASGOLPEA = 5;
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            base.Initialize();
        }
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            //Crea el objeto SimuladorFisica y en el constructor se coloca el vector de gravedad
            SimuladorFisica = new PhysicsSimulator(new Vector2(0, 0));
            // TODO: use this.Content to load your game content here
            TexturaCaja = Content.Load<Texture2D>("Cuadrado");
            CuerpoCaja = BodyFactory.Instance.CreateRectangleBody(SimuladorFisica, TexturaCaja.Width, TexturaCaja.Height, 1);
            CuerpoCaja.Position = new Vector2(350, 100);
            GeometriaCaja = GeomFactory.Instance.CreateRectangleGeom(SimuladorFisica, CuerpoCaja, TexturaCaja.Width, TexturaCaja.Height);
            //Cargar e inicializar las cajas que se van a golpear
            CajasGolpea = new ObjetosJuego[MAXCAJASGOLPEA];
            for (int Cont = 0; Cont < MAXCAJASGOLPEA; Cont++)
            {
                CajasGolpea[Cont] = new ObjetosJuego(Content.Load<Texture2D>("Cuadrado"));
                CajasGolpea[Cont].CuerpoCajasGolpea = BodyFactory.Instance.CreateRectangleBody(SimuladorFisica, CajasGolpea[Cont].TexturaCajasGolpea.Width, CajasGolpea[Cont].TexturaCajasGolpea.Height, 1);
                CajasGolpea[Cont].GeometriaCajasGolpea = GeomFactory.Instance.CreateRectangleGeom(SimuladorFisica, CajasGolpea[Cont].CuerpoCajasGolpea, CajasGolpea[Cont].TexturaCajasGolpea.Width, CajasGolpea[Cont].TexturaCajasGolpea.Height);
                CajasGolpea[Cont].CuerpoCajasGolpea.Position = new Vector2((Cont + 1) * 100, 300);
            }
        }
        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }
        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
            // TODO: Add your update logic here
//Esta es una compilación condicional. El teclado y el mouse solo son leídos si la aplicación ejecuta en un PC
#if !XBOX
            const float IncrementoFuerza = 50;
            Vector2 Fuerza = Vector2.Zero;
            //Código para leer el teclado
            KeyboardState estadoTeclado = Keyboard.GetState();
            
            //Aplica un vector de fuerza a la caja
            if (estadoTeclado.IsKeyDown(Keys.A)) { Fuerza = new Vector2(-IncrementoFuerza, 0); }
            if (estadoTeclado.IsKeyDown(Keys.S)) { Fuerza = new Vector2(0, IncrementoFuerza); }
            if (estadoTeclado.IsKeyDown(Keys.D)) { Fuerza = new Vector2(IncrementoFuerza, 0); }
            if (estadoTeclado.IsKeyDown(Keys.W)) { Fuerza = new Vector2(0, -IncrementoFuerza); }
            CuerpoCaja.ApplyForce(Fuerza);
            //Aplica un vector de torque a la caja
            const float IncrementoTorque = 1000;
            float Torque = 0;
            if (estadoTeclado.IsKeyDown(Keys.Left)) { Torque = -IncrementoTorque; }
            if (estadoTeclado.IsKeyDown(Keys.Right)) { Torque = IncrementoTorque; }
            CuerpoCaja.ApplyTorque(Torque);
#endif
            //Actualiza el simulador de física
            SimuladorFisica.Update(gameTime.ElapsedGameTime.Milliseconds * 0.001f);
            base.Update(gameTime);
        }
        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            // TODO: Add your drawing code here
            //Dibuja las cajas haciendo uso de la posición y rotación de los cuerpos dado por el motor de física
            spriteBatch.Begin(SpriteBlendMode.AlphaBlend);
            spriteBatch.Draw(TexturaCaja, CuerpoCaja.Position, null, Color.White, CuerpoCaja.Rotation,
                new Vector2(TexturaCaja.Width / 2, TexturaCaja.Height / 2), 1, SpriteEffects.None, 0);
            foreach (ObjetosJuego Cajas in CajasGolpea)
                spriteBatch.Draw(Cajas.TexturaCajasGolpea, Cajas.CuerpoCajasGolpea.Position, null, Color.White, Cajas.CuerpoCajasGolpea.Rotation,
                new Vector2(Cajas.TexturaCajasGolpea.Width / 2, Cajas.TexturaCajasGolpea.Height / 2), 1, SpriteEffects.None, 0);
            spriteBatch.End();
            base.Draw(gameTime);
        }
    }
}

 

Y por supuesto es necesario el objetosjuego.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
//Librerías del motor de física
using FarseerGames.FarseerPhysics;
using FarseerGames.FarseerPhysics.Collisions;
using FarseerGames.FarseerPhysics.Dynamics;
using FarseerGames.FarseerPhysics.Factories;
namespace GiraCuadrado
{
    class ObjetosJuego
    {
        public Texture2D TexturaCajasGolpea; //La textura (o imagen)
        public Body CuerpoCajasGolpea;
        public Geom GeometriaCajasGolpea;
        //Constructor
        public ObjetosJuego(Texture2D textura)
        {
            TexturaCajasGolpea = textura; //Recibe la textura por parámetro
        }
    }
}

Al ejecutar el programa, se puede aplicar fuerza de desplazamiento con las teclas A, S, D y W. Y se aplica fuerza de torque con las teclas de flecha izquierda y derecha. La inercia se tiene en consideración. Obsérvese como las otras cajas reaccionan al golpe que les da la que controlamos.

 

Volver al Inicio Célula Microsoft. Universidad Libre