• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Truerror

Farseer Physics collision detection problem.

3 posts in this topic

I recently started to learn Farseer engine by following Roy Triesscheijn's tutorial. After the tutorial, I attempted a little platformer project (very simple really, just 2 boxes and a single platform) so I can get used to it. I added a control mechanism to the first box (call it box1), so I can move it around the platform and see if it works. It compiles without a problem and when it hits the other box (box2), it 'pushes' box2, which is what I expected.

 

However, I accidentally (just a twich of the finger) pressed the left arrow key, which moved box1 to the left briefly, and released it again, all while still holding the right arrow key (to explain it further, at the time I was holding right arrow key and was pushing box2 to the right). And to my surprise, while box1 continued to move right, it no longer collided with box2. Instead, it simply goes behind it, and move right. No collision occurred afterwards, even when I tried to hit box2 again, either form the right side, or left side. It simply went through it.

 

I have 2 classes. One is the default Game1.cs, and the other is DrawablePhysicsObject.cs. Here they are:

 

DrawablePhysicsObject.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using FarseerPhysics.Dynamics;
using FarseerPhysics.Factories;

namespace FarseerTest
{
    class DrawablePhysicsObject
    {
        // First, unit conversion, since Farseer uses meters
        public const float UNIT_TO_PIXEL = 100f;
        public const float PIXEL_TO_UNIT = 1 / UNIT_TO_PIXEL;

        public Body body;
        public Texture2D texture;
        private Vector2 _size;

        /// <summary>
        /// The position of the body
        /// </summary>
        public Vector2 Position
        {
            get { return body.Position * UNIT_TO_PIXEL; }
            set { body.Position = value * PIXEL_TO_UNIT; }
        }

        /// <summary>
        /// Getter and setter for _size
        /// </summary>
        public Vector2 Size
        {
            get { return _size * UNIT_TO_PIXEL; }
            set { _size = value * PIXEL_TO_UNIT; }
        }

        /// <summary>
        /// Creates a new DrawablePhysicsObject
        /// </summary>
        /// <param name="world"></param>
        /// <param name="texture"></param>
        /// <param name="size"></param>
        /// <param name="mass"></param>
        public DrawablePhysicsObject(World world, Texture2D texture, Vector2 size, float mass)
        {
            body = BodyFactory.CreateRectangle(world, size.X * PIXEL_TO_UNIT, size.Y * PIXEL_TO_UNIT, mass);
            body.BodyType = BodyType.Dynamic;

            this.Size = size;
            this.texture = texture;
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            Vector2 scale = new Vector2(Size.X / (float)texture.Width, Size.Y / (float)texture.Height);
            spriteBatch.Draw(texture, Position, null, Color.White, body.Rotation, new Vector2(texture.Width / 2f, texture.Height / 2f), scale, SpriteEffects.None, 0);
        }
    }
}

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 FarseerPhysics.Dynamics;
using FarseerPhysics.Factories;

namespace FarseerTest
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        World world;
        List<DrawablePhysicsObject> boxList;
        DrawablePhysicsObject floor;
        DrawablePhysicsObject box1;
        DrawablePhysicsObject box2;
        Vector2 boxSize;
        Texture2D boxTexture;
        Vector2 speed;
        KeyboardState prevKeyboardState;


        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()
        {
            boxSize.X = 10f;
            boxSize.Y = 10f;
            boxTexture = Content.Load<Texture2D>(@"Images/Crate");
            speed.X = 1f;
            speed.Y = 0;

            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);
            world = new World(new Vector2(0, 9.8f));

            floor = new DrawablePhysicsObject(world, Content.Load<Texture2D>(@"Images/Floor"),
                new Vector2(GraphicsDevice.Viewport.Width, 100f), 1000);

            floor.Position = new Vector2(GraphicsDevice.Viewport.Width / 2f, // Set it to half the screen width
                GraphicsDevice.Viewport.Height - 50); // And 50 pixels from the bottom

            floor.body.BodyType = BodyType.Static;

            box1 = new DrawablePhysicsObject(world, boxTexture, boxSize, 1f);
            box2 = new DrawablePhysicsObject(world, boxTexture, boxSize, 1f);

            box1.Position = new Vector2(0, 50);
            box2.Position = new Vector2(200, 50);
        }

        /// <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();

            world.Step((float)gameTime.ElapsedGameTime.TotalSeconds);

            if (Keyboard.GetState().IsKeyDown(Keys.Right))
            {
                box1.Position += speed;
            }

            if (Keyboard.GetState().IsKeyDown(Keys.Left))
            {
                box1.Position -= speed;
            }

            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);

            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque);
            box1.Draw(spriteBatch);
            box2.Draw(spriteBatch);
            floor.Draw(spriteBatch);
            spriteBatch.End();

            base.Draw(gameTime);
        }

    }
}

And I've attached a demo so you can see the situation for yourself. To reproduce the problem, keep holding right arrow key and, while pushing box2, hit left arrow, but don't release right arrow key.

 

Thank you for your answers.

0

Share this post


Link to post
Share on other sites

It sounds like (apologies if this is already apparent) your rendering and your physics simulation are out of sync.  Two questions:

 

What happens in world.step?

Are you using any debug output to confirm that the location of the box as you're seeing it lines up with where the simulation thinks it is?

1

Share this post


Link to post
Share on other sites

Ah, I hadn't thought of that. I think I can set up a debug text somewhere on the screen. I'll update later on what I find.

 

The world.Step() is for updating the physics. As parameter, it takes the time needed (in float) for each step.

0

Share this post


Link to post
Share on other sites

Update: I've learned a new lingo today: "Tunneling". Apparently, my world.Step() is still too big, despite its value being taken from the actual gameTime. Slved the problem by changing it to

world.Step((float)gameTime.ElapsedGameTime.TotalSeconds / 10);

Thanks for bringing the world.Step() to my attention, BCullis. Really appreciate it. smile.png

0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0