Having physics in the animating sprite class

Topics: Developer Forum, User Forum
Aug 8, 2011 at 12:30 PM

HHey Guys , 

Been reading a stuff about XNA and farseer physics engine and I'm liking it. 

Now I've been playing around creating some collisions etc and it all worked. 

Now what I want is to clean up my code a little and create a AnimatedSprite class based on http://msdn.microsoft.com/en-us/library/bb203866.aspx  that includes the physics ( I have checked this site : http://www.progware.org/Blog/post/XNA-for-Windows-Phone-7-and-Physics.aspx )

I'm as you can see very new but I have been stumbling now with getting my animated sprite to have the physics. 

I've made all sorts of adjustements but I seem to be getting a little stuck  therefore I decided to ask you guys if someone could help me out. 

This is my AnimatedSprite class that I adjusted. 

 

#region File Description
//-----------------------------------------------------------------------------
// AnimatedTexture.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion

using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System.Diagnostics;
using FarseerPhysics.Dynamics;
using FarseerPhysics.Factories;
using Microsoft.Xna.Framework.Input.Touch;

namespace AnimatedPhysicsTest
{
    public class AnimatedTexture
    {
        private int framecount;
        private Texture2D myTexture;
        private float TimePerFrame;
        private int Frame;
        private float TotalElapsed;
        private bool Paused;
      
        //physics
        private Fixture puppetFixture;
        private World _world;
        
        public float Rotation, Scale, Depth;
        public Vector2 Origin;
     
        public AnimatedTexture(Vector2 origin, float rotation,
            float scale, float depth)
        {
            this.Origin = origin;
            this.Rotation = rotation;
            this.Scale = scale;
            this.Depth = depth;
            TouchPanel.EnabledGestures = GestureType.Flick;
        }

        private void LoadPuppetFixture()
        {
            puppetFixture = FixtureFactory.CreateRectangle(_world, myTexture.Width, myTexture.Height, 1f);
            puppetFixture.Body.BodyType = BodyType.Static;
            puppetFixture.Restitution = 0.7f;
            puppetFixture.Body.Position = new Vector2(300, 300);
        }


        public void Load(ContentManager content, string asset,
            int frameCount, int framesPerSec)
        {
            framecount = frameCount;
            myTexture = content.Load<Texture2D>(asset);
            TimePerFrame = (float)1 / framesPerSec;
            Frame = 0;
            TotalElapsed = 0;
            Paused = false;
            LoadPuppetFixture();
        }

        public void Initialize()
        {
             _world = new World(new Vector2(0, 9.81F));
        }
                
        // class AnimatedTexture
        public void UpdateFrame(float elapsed)
        {
            if (Paused)
                return;
            TotalElapsed += elapsed;
            if (TotalElapsed > TimePerFrame)
            {
                Frame++;
                // Keep the Frame between 0 and the total frames, minus one.
                Frame = Frame % framecount;
                TotalElapsed -= TimePerFrame;
            }

            while (TouchPanel.IsGestureAvailable)
            {
                GestureSample gesture = TouchPanel.ReadGesture();
                if (gesture.GestureType == GestureType.Flick)
                    stewieFixture.Body.ApplyForce(Vector2.Divide(gesture.Delta, 2.0f));
            }
             _world.Step(elapsed);
        }

        // class AnimatedTexture
        public void DrawFrame(SpriteBatch batch, Vector2 screenPos)
        {
            DrawFrame(batch, Frame, screenPos);
        }
        public void DrawFrame(SpriteBatch batch, int frame, Vector2 screenPos)
        {
            int FrameWidth = myTexture.Width / framecount;
            int intTestFr = 119;
            Rectangle sourcerect = new Rectangle(intTestFr * frame, 0,
                FrameWidth, myTexture.Height);
           // batch.Draw(myTexture, screenPos, sourcerect, Color.White, Rotation, Origin, Scale, SpriteEffects.None, Depth);
            batch.Draw(myTexture, stewieFixture.Body.Position, null, Color.White, stewieFixture.Body.Rotation, new Vector2(myTexture.Width, myTexture.Height), 1, SpriteEffects.None, 1f);
            Debug.WriteLine(_world);
          
        }

        public bool IsPaused
        {
            get { return Paused; }
        }
        public void Reset()
        {
            Frame = 0;
            TotalElapsed = 0f;
        }
        public void Stop()
        {
            Pause();
            Reset();
        }
        public void Play()
        {
            Paused = false;
        }
        public void Pause()
        {
            Paused = true;
        }
    }
}
This is my game class
using System;
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.Input.Touch;
using Microsoft.Xna.Framework.Media;
using FarseerPhysics.Factories;
using FarseerPhysics.Dynamics;

namespace AnimatedPhysicsTest
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        private AnimatedTexture SpriteTexture;
        private const float Rotation = 0;
        private const float Scale = 1.0f;
        private const float Depth = 0.5f;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            SpriteTexture = new AnimatedTexture(Vector2.Zero,
                Rotation, Scale, Depth);
#if ZUNE
            // Frame rate is 30 fps by default for Zune.
            TargetElapsedTime = TimeSpan.FromSeconds(1 / 30.0);
#endif
        }

        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            SpriteTexture.Initialize();
            base.Initialize();
        }

        private Viewport viewport;
        private Vector2 shipPos;
        private const int Frames = 8;
        private const int FramesPerSec = 8;
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
           
            // "shipanimated" is the name of the sprite asset in the project.
            SpriteTexture.Load(Content, "puppetTexture", Frames, FramesPerSec);
            viewport = graphics.GraphicsDevice.Viewport;
            shipPos = new Vector2(viewport.Width / 3, viewport.Height / 2);

      
        }

        /// <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();
           
        
            // Pauses and plays the animation.
            if (GamePad.GetState(PlayerIndex.One).Buttons.A ==
                ButtonState.Pressed)
            {
                if (SpriteTexture.IsPaused)
                    SpriteTexture.Play();
                else
                    SpriteTexture.Pause();
            }
            float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

            // TODO: Add your game logic here.
            SpriteTexture.UpdateFrame(elapsed);
            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
            spriteBatch.Begin();
            SpriteTexture.DrawFrame(spriteBatch, shipPos);
            
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}

I'm not getting my animated sprite and also my physics are not working. I'm wrapping the object in the fixture , so I'm confused as to why it is not working now ? 
Can anyone help me?