Tuesday, September 3, 2019

c++ - what is the absolute simplest way to add physics to a simple 3D game


This physics does not have to be very complex at all.



There are a number of rectangles and one ball, all of which have the appropriate bounding volumes constrained to them, it would be great if the ball could knock them over and they in turn could knock into each other.


What is the most basic way of doing this?



Answer



The scenario you describe is already complex enough that I would strongly recommend using an external physics engine. I can't think of any other way of implementing this that I would personally consider as being simple.


The good news is that integrating a physics engine into your game - if done early on - is usually a very straightforward process.


Details will obviously vary from engine to engine but in most of them it consists of:



  1. Instatiating a World object which will manage the simulation

  2. Associating a Body object with each of your game objects, and adding them to the world.

  3. Updating the World and drawing each game object using the information from their Bodys.



Example


So if for instance, you had a class like this:


class GameObject
{
Vector3 position;
Quaternion rotation;
Model model;

void Draw()

{
model.RenderAt(position, rotation);
}
}

You could replace the transforms information in your object with that of a physics body instead:


class GameObject
{
Body body;
Model model;


void Draw()
{
model.RenderAt(body.Position, body.Rotation);
}
}

Of course when creating the Body you'd need more information about its shape and behavior, e.g. you could specify the shape of the body using the model's bounding box.


Then it's just a matter of registering the bodies in the world and updating it.


// Register bodies in world

foreach(var gameObject in gameObjects)
world.AddBody(gameObject.Body);

// Update world
world.Update(elapsed);

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...