physics-based third-person or fps character controller

Problems building or running the engine, queries about how to use features etc.
slapin
Bronze Sponsor
Bronze Sponsor
Posts: 77
Joined: Fri May 23, 2025 5:04 pm
x 2

physics-based third-person or fps character controller

Post by slapin »

Hi, all!
Is there some example of physics-based (capsule + kinematic/dynamic rigid body + camera setup) character congtoller? Any help is appreciated

Ogre Version: master branch
Operating System: Ubuntu 22.04
Render System: GL ES 2.0

User avatar
sercero
Bronze Sponsor
Bronze Sponsor
Posts: 513
Joined: Sun Jan 18, 2015 4:20 pm
Location: Buenos Aires, Argentina
x 188

Re: physics-based third-person or fps character controller

Post by sercero »

Which physics engine are you going to use?

Bullet?

slapin
Bronze Sponsor
Bronze Sponsor
Posts: 77
Joined: Fri May 23, 2025 5:04 pm
x 2

Re: physics-based third-person or fps character controller

Post by slapin »

Bullet which comes with Ogre.

slapin
Bronze Sponsor
Bronze Sponsor
Posts: 77
Joined: Fri May 23, 2025 5:04 pm
x 2

Re: physics-based third-person or fps character controller

Post by slapin »

Well, I found that btCompoundShape is still not supported by OgreBullet so I have to use Bullet directly but be compatible with OgreBullet.
I managed to create Capsule and trimesh, had to copy-paste some functions and classes from OgreBullet.cpp.

Code: Select all

 
                switch(ct) {
                case Ogre::Bullet::CT_TRIMESH: {
                        cs = Ogre::Bullet::VertexIndexToShape(ent).createTrimesh();
                        if (mass != 0)
                                cs->calculateLocalInertia(mass, inertia);
                } break;
                case Ogre::Bullet::CT_CAPSULE: {
                        cs = new btCompoundShape();
                        btScalar height = 1.0f;
                        btScalar radius = 0.3f;
                        shape = new btCapsuleShape(radius, 2 * height - 2 * radius);
                        btTransform transform;
                        transform.setIdentity();
                        transform.setOrigin(btVector3(0, 1, 0));
                        static_cast<btCompoundShape *>(cs)->addChildShape(transform, shape);
                        btScalar masses[1] = {mass};
                        btTransform principal;
                        static_cast<btCompoundShape *>(cs)->calculatePrincipalAxisTransform(masses, principal, inertia);
               } break;
                default:
                        assert(false);
                        break;
                }
                btRigidBody *body = new btRigidBody(mass, state, cs, inertia);
                getBtWorld()->addRigidBody(body, group, mask);
                body->setUserPointer(new EntityCollisionListener{ent, nullptr});
                return body;

If I set mass to 0 I get kinematic or static body, but kinematic body can't recieve any outside influence so that have to be implemented for kinematic controller by test motions which I'm trying to do. The idea is to do something like move_and_slide in Godot or do something better more inline with builtin
Bullet kinematic character controller. Additionally I need to drive motion via animation using root motion...

User avatar
sercero
Bronze Sponsor
Bronze Sponsor
Posts: 513
Joined: Sun Jan 18, 2015 4:20 pm
Location: Buenos Aires, Argentina
x 188

Re: physics-based third-person or fps character controller

Post by sercero »

Hello, In my case I'm using bullet directly becase at that time the current integration was not in place.

But anyway I don't think the integration with bullet that OGRE has right now is very useful for games.

Here are all the notes I took when putting up physics (sorry but its a lot)

Tener en cuenta esto para la parte de fisica:
http://gameprogrammingpatterns.com/observer.html
“stay off the UI thread”.

BULLET
http://www.ogre3d.org/tikiwiki/tiki-ind ... OgreBullet
http://www.ogre3d.org/tikiwiki/tiki-ind ... Tutorial+1
http://www.ogre3d.org/tikiwiki/tiki-ind ... ource+Code
http://www.ogre3d.org/tikiwiki/tiki-ind ... Tutorial+2
http://www.ogre3d.org/tikiwiki/tiki-ind ... ebugDrawer

ALTERNATIVA: Newton Dynamics -> dicen que el CC podria ser mejor que el de Bullet

  • Al final estoy usando Bullet directamente con alguna funcionalidad de btOgre
    viewtopic.php?f=5&t=46856
    NOTA: Intente usar btOgre, pero no me gusto mucho. (DebugDraw no usa colores, y no coincide la clase con el uso en el demo)
    Lo ideal seria tratar de replicar el codigo que crea un mesh

(OK) TODO: BulletTest, una esfera que cae
http://www.bulletphysics.org/Bullet/php ... f=9&t=7468
http://bulletphysics.org/mediawiki-1.5. ... d_Triggers
http://bulletphysics.org/mediawiki-1.5. ... _Detection
http://bulletphysics.org/mediawiki-1.5. ... ion_Shapes
La deteccion de colision con la espada solo importa durante el ataque y la del escudo solo importa durante ShieldUp

(OK) TODO: GameLoop -> Arreglar el Game Loop de AOF

TODO: Sincronizacion

TODO: Character Controller (Kinematic o Dynamic)

  • Estimo que me conviene probar primero Kinematic, parece el mas apropiado

  • Probar de capear los FPS a 60 y 30 a ver si se arregla (FAIL, salvo que lo haya capeado mal)

  • Probar con warp() (SUCCESS!!)

  • Modificar la orientacion de la capsula? (tiene sentido?)

  • Probar tambien con Dynamic (El CC de Evolved Creatures, tambien GameKit y OpenMorowwind)

  • Probar con otra de las implementaciones de KCC

  • Probar con un KCC de alguna version mas nueva de Bullet

    La idea seria probar el KinematicChar y ver si tengo que hacer uno propio o no.
    Probar:

  • Slopes (Se desliza, se puede seleccionar la pendiente maxima para trepar)

  • Paredes (Funciona OKish, pero con jitter)

  • Escalera (Funciona)

  • Ascensor (Funciona)

  • Plataforma en movimiento
    DATO: En el DeS las escaleras son rampas desde un punto de vista fisico (incluso usan un raycast fisico para camera occlusion)

(OK) TODO: Probar de poner el origen de la escalera en el piso a ver como lo toma Blender

  • CTRL-SHIFT-ALT-c en Blender me permite elegir el origen (lo pongo donde esta el cursor 3D, que se va al origen presionando SHIFT-c por cierto)
  • Quizas convenga ponerlo en el piso para la geometria en lugar de usar el centro de masa

TODO: Nivel -> Terrain + Blender

  • Terrain (Bullet)
  • Blender (usar btOgre?) (como voy a importar los collision meshes?)
  • Como usar el MeshStrider:
    viewtopic.php?t=68588

ATENCION: Cuidado con el mesh de colision, seguir los pasos de este tutorial:

(OK) TODO: Probar BulletMeshStrider y convertir una escalera para probar el KCC

TODO: Probar el Terrain de Bullet y el de OGRE

TODO: Character Controller para el Enemigo

  • Probar el empuje

TODO: Ataque

  • Quizas convenga usar un Ghost Object que refleje el movimiento de la espada y vea con que colisiona (Si es una pared, Un escudo, Un Kinematic Char...)
    https://web.archive.org/web/20170716030 ... d_Triggers
    https://pybullet.org/Bullet/phpBB3/view ... =9&t=11423
    IDEA1: Los escudos tienen un hitbox gigante posiblemente un semicirculo casi del tamaño del jugador (testear)
  • Lo bueno de esta idea es que solo hay que chequear contra que choco el arma si contra jugador/enemigo o contra escudo/pared
  • Posiblemente necesite un hashMap collisionShape -> worldObjet para avisarle al objeto
  • Otra posibilidad es avisarle al GameWorld que tal objeto recibio un impacto de espada y que se encarge del sonido y registro de daño
  • El tema es que justamente la espada sabe cuanto saca y que sonido hace
  • Ver tambien que es posible obtener el objeto padre de un collision object (EvolvedCreatures, weapon class)

IDEA2: La defensa no estaria determinada por el escudo sino por el angulo de ataque (prefiero IDEA1)

IDEAS del EvolvedCreatures:

  • En la clase weapon muestra como obtener el objeto de la colisión, además el arma sabe cuanto saca y que sonido hace.

IDEAs del dungeonhack:
(La verdad es que en general la arquitectura no es muy buena)

  • m_Player->setNoClip(); // m_Player->showHUD();
  • Weapon* newWeapon = new Weapon(); // Probablemente haya que hacer una clase weapon (El player tendria apuntadores al mismo)
  • const RenderTarget::FrameStats& stats = m_root->getAutoCreatedWindow()->getStatistics();
  • (OK) El destructor del CharacterController() muestar como borrar bien los objetos
  • PhysicsManager() -> Tiene buenas ideas
  • PhysicsManager::getSingletonPtr()->toggleDebugDraw();
  • (OK) Npcactor.cpp -> display->attachEntityToSkeleton(testShirtEntity, -1); (Interesante, que la ropa sea independiente, hay que investigar eso)
  • Revisar en main.cpp que tambien hay buenas ideas
  • Item.cpp -> Armas, Ropa, Llaves, Anillos, etc. (todos tienen icono, mesh, posicion en el mundo, nombre, descripcion, peso)
  • InputManager.cpp -> Tiene codigo util para comparar la parte de OIS
  • HDR.cpp -> Si algun dia voy a usar HDR
  • GuiHUD.cpp -> Clase que maneja el HUD
  • GameWorld.cpp -> Probablemente necesite un Game World (carga de mapas, actores en el mundo, etc.)
  • GameObject.h -> No coincido mucho con la arquitectura pero se puede ver como referencia
  • GameCorona.cpp -> Corona para el Sol, puede ser interesante
  • GameActor.h -> int faction_id; (Distintas facciones para determinar quien es enemigo)

IDEAS de GameKit:
-

CHARACTER CONTROLLER

IMPORTANTE:

Character Controller:

https://web.archive.org/web/20150519221 ... llers.aspx

slapin
Bronze Sponsor
Bronze Sponsor
Posts: 77
Joined: Fri May 23, 2025 5:04 pm
x 2

Re: physics-based third-person or fps character controller

Post by slapin »

Well, the Ogre's Bullet integration is quite basic and does its thing well i.e. provides access to Bullet objects and connects objects to scene nodes.
There are some shortcomings like inability to create collision shapes separately from RigidBidies and lack of support of btCompoundShape but I can cope with that with some patching and reimplementing things locally. Nobody expected complete Bullet wrapper and I can just play directly with Bullet but get some help from Ogre.

slapin
Bronze Sponsor
Bronze Sponsor
Posts: 77
Joined: Fri May 23, 2025 5:04 pm
x 2

Re: physics-based third-person or fps character controller

Post by slapin »

Thanks a lot for your links, going through it.

slapin
Bronze Sponsor
Bronze Sponsor
Posts: 77
Joined: Fri May 23, 2025 5:04 pm
x 2

Re: physics-based third-person or fps character controller

Post by slapin »

I managed to implement the motion via Bullet's btRigidBody in kinematic
mode and applying the offset of root bone to entity's parent node.
This works quite well. But now I need to implement collisions so it can't go through static/dynamic
objects and push everything as object with infinite inertia.

slapin
Bronze Sponsor
Bronze Sponsor
Posts: 77
Joined: Fri May 23, 2025 5:04 pm
x 2

Re: physics-based third-person or fps character controller

Post by slapin »

As I understand the core of the thing should be btGhostObject which collects collisions and a function for de-penetration of the body which depend on collider (capsule in my case). Both btRigidBody and btGhostObject should share the same btCollisionShape (btCompoundShape in my case)
and each frame should be de-penetrated from other bodies. The only thing which remains to understand if it should be done from world's
tick function or can be just done separately by moving the node... I guess as kinematic body is considered out of physics engine it can be done
anywhere...

User avatar
sercero
Bronze Sponsor
Bronze Sponsor
Posts: 513
Joined: Sun Jan 18, 2015 4:20 pm
Location: Buenos Aires, Argentina
x 188

Re: physics-based third-person or fps character controller

Post by sercero »

Bullet has a Kinematic controller object have you seen that?

Another question: why aren't you using Godot? I'm curious about that.

slapin
Bronze Sponsor
Bronze Sponsor
Posts: 77
Joined: Fri May 23, 2025 5:04 pm
x 2

Re: physics-based third-person or fps character controller

Post by slapin »

Bullet's kinematic btRigidBody acts one side only, but does not respond to collisions itself, hence btGhostObject is needed to implement other side
and respond to collisions and do de-penetration. There is no road blockers here, just need some enlightenment and time.

I actually use Godot, but this project is not fit for Godot's usecase. I tried really hard. It is not possible by design without major engine changes.

User avatar
sercero
Bronze Sponsor
Bronze Sponsor
Posts: 513
Joined: Sun Jan 18, 2015 4:20 pm
Location: Buenos Aires, Argentina
x 188

Re: physics-based third-person or fps character controller

Post by sercero »

Have you seen the class "btKinematicCharacterController"?

I'm using that for the player and enemies.

slapin
Bronze Sponsor
Bronze Sponsor
Posts: 77
Joined: Fri May 23, 2025 5:04 pm
x 2

Re: physics-based third-person or fps character controller

Post by slapin »

Yes, but it is quite complicated and I try to learn it by reimplementing now.

slapin
Bronze Sponsor
Bronze Sponsor
Posts: 77
Joined: Fri May 23, 2025 5:04 pm
x 2

Re: physics-based third-person or fps character controller

Post by slapin »

btKinematicCharacterController can't handle compound shapes so I can't use it.
Will have to do custom one.

slapin
Bronze Sponsor
Bronze Sponsor
Posts: 77
Joined: Fri May 23, 2025 5:04 pm
x 2

Re: physics-based third-person or fps character controller

Post by slapin »

Looks like it is impossible to control btKinematicCharacterController. All I can do now is try to understand how btPairCachingGhostObject works and make my own controller. It is super hard to digest...

paroj
OGRE Team Member
OGRE Team Member
Posts: 2180
Joined: Sun Mar 30, 2014 2:51 pm
x 1168

Re: physics-based third-person or fps character controller

Post by paroj »

if you are hitting a roadblock with bullet, you might want to take a look at jolt:
https://github.com/jrouwe/JoltPhysics

I have prototyping the Ogre integration with it on my todo, but did not get around to do it.

However from the looks of it, it seems to have better documentation and an API closer to Ogre when compared with bullet.

slapin
Bronze Sponsor
Bronze Sponsor
Posts: 77
Joined: Fri May 23, 2025 5:04 pm
x 2

Re: physics-based third-person or fps character controller

Post by slapin »

It is not road block, it is like to go home you have to climb over 10km mountain... Not impossible but unexpected complexity for no much gain.
I just dropped the idea of using btKinematicCharacterController and btGhostObject all together and implement Godot's world sweep tests based
move_and_collide/move_and_slide. I guess it is super ineffective but it is possible to do as I don't have all time in the world. People who made btKinematicCharacterController and btPairCachingGhostObject are geniuses but I'm not. Sorry.

slapin
Bronze Sponsor
Bronze Sponsor
Posts: 77
Joined: Fri May 23, 2025 5:04 pm
x 2

Re: physics-based third-person or fps character controller

Post by slapin »

As for Jolt - I have plans to look at it but not now, my physics requirements are quite low now as I need to finish prototype with all
the primitives I have in Godot project including GUIs and behavior tree and utility-based smart object AI. Only then I can move on with
bits here and there. Also I will need to add flecs and make all game architecture around it. And only after that I can look at Jolt.

RevenantStorm
Gnoblar
Posts: 6
Joined: Tue Oct 29, 2024 12:10 am
x 2

Re: physics-based third-person or fps character controller

Post by RevenantStorm »

slapin wrote: Sat May 31, 2025 3:39 am

Looks like it is impossible to control btKinematicCharacterController. All I can do now is try to understand how btPairCachingGhostObject works and make my own controller. It is super hard to digest...

When I was dealing with the character controller problem in my project, I ended up just using regular btCapsule rigid bodies, setting friction high and applying "stopping" forces when the player lifts one of the movement keys.

That handles 95% of cases well and gives all the flexibility of using rigid bodies. For stairs, I put a ground-testing vector on the edge of the capsules which would detect stairs and apply corrective forces up or down to smooth out the movement.

With all that in place, the kinematic controllers seem quite limited and quirky. As I understand them, ghost objects are mostly useful in the case where the player is shooting a cylindrical energy beam a couple meters wide and you want to query all objects in its path.

slapin
Bronze Sponsor
Bronze Sponsor
Posts: 77
Joined: Fri May 23, 2025 5:04 pm
x 2

Re: physics-based third-person or fps character controller

Post by slapin »

well, I managed to make my controller using btPairCachingGhostShape, there were a few poorly documented things on a path.
See https://github.com/OGRECave/ogre/commit ... 489310bd3f
You just move node around and body will de-penetrate itself and correct node's position. I think it is quite cool.
btRigidBody does not go too well with root motion animation. Also btPairCachingGhostShape is perfect for implementing triggers
where you want to check player or NPC to arrive at particular point. And that is quite useful. Going to do that too.