I've several static bodies and I want them behave like planets. Each static body should have gravity like force to affect on dynamic bodies. Currently I'm applying applyForce:atLocalPoint to dynamic bodies if distance to them less that some value. But current implementation do not behave like gravity, objects are start rotating and moving not to the centre of static bodies. Is the predefined behaviour in cocos 2d v3 with chipmunk for such behaviour?
Related
I'm writing code for mouse picking in 3D space. So far I've made Ray and AABB classes. What I need is a function for Ray-AABB intersecting. I know how to write it and make it work, my question is which class should define said funcion? Should it be a member of Ray or AABB, both, neither? What are the best practices for object oriented approach?
For me it makes the most sense to implement that function as a member of "engine" class, more like a procedure rather than a function. However I want my code to be truly object oriented.
I would say: neither.
Ray: Structure (Members: Start, End)
AABB: Structure (Members: Position, Size).
Ray-AABB intersection method could be in a Physics or Intersection class (Depends on your actual context) as static methods (Or functions in a namespace, depends on your coding convention).
Object oriented is fine, but it doesn't mean that everything you create should be a class.
Data oriented is a very good approach (CPU friendly with less cache misses).
EDIT: A good coding rule is to think your things independently, meaning that the AABB implementation shouldn't be dependent on the Ray implementation.
Why should you even use kinematic bodies instead of dynamic bodies with no gravity? I mean a dynamic body can also collide with static bodies and have some other adjustable parameters that kinematic bodies do not have, right. Therefore, I would really love to hear why you would want to do this and if it even can be lead to some advantages.
Your time is much appreciated!
It's a matter of what you want b2World::Step to do to the body. Basically this method's body related post-conditions are as follows:
Static bodies are unmoved.
Kinetic bodies are moved based on their previous velocities.
Dynamic bodies are moved based on their previous velocities, gravity, applied forces, applied impulses, masses, damping, and the restitution and friction values of their fixtures when they experience collisions.
So kinematic bodies can be useful when the only thing that you want to have happen to the body is to have it moved based on a velocity you'd given it.
I had a question regarding the way I am designing my particle system.
Right now I have a class P, which stores all the information about a particle such as speed, position, direction, type, etc. I also have a main file I will be drawing these particles, updating and instantiating them in. I want to create a list of these particles using the c++ std list library, so initially I did
std::list<P> listOfParticles;
in the main file. Here is the problem. By doing this I will essentially be forced to make my update and draw functions in the main file. I feel like this is bad practice, and that everything to do with the particle should be kept in one class, but I am unsure where to go from here in terms of best practice. Would it be a good idea to just create a list of particles in the class P where I am defining what a particle is? I feel like this isn't a smart idea though..
If anyone could guide me in the right direction I would really appreciate it.
"By doing this I will essentially be forced to make my update and draw functions in the main file"
No one is stopping you from putting declarations/definitions of class members in same/different .h/.cpp files.
EDIT:-
That's what I said, better it would be if you make this List a member of some other class where you would put all functions to manipulate this list.
Your list of particles most probably deserves its own class, let C, that will handle storage, initial spatial distribution, temporal updates... i.e. all global operations on the particle cloud. If you are sure that you will ever handle a single list, you can make it a static member.
The class that represents the individual particles (P) can be nested into (C) if there is no need to see it from outside. It will encapsulate particle data and possibly also model pairwise interaction with another particle and other single-particle operations.
I'm developing a base for a 2D game. My general design is something like this:
class Entity:
Every object class (like a wall, an enemy, floor etc.) derives
from this class. Most of the functions are pure virtual. There is
a hitbox as well.
class Scene:
Contains pointers to Entity-objects. When an Entity-pointer is added,
it will be given a Scene-pointer to its parent so it may access that.
Scene also has a collision-detecting function:
getIntersections<T> (Entity *)
getIntersections<T...> (Entity *)
(both return a std::vector<Entity *>)
This basically gets all Entity *s intersecting the parameter-Entity * (by checking the hitbox) and then tries to dynamic_cast<T *> them. All matching Entity *s (not the casted ones) are then returned. The variadic template is used for checking for more then one intersecting class.
My basic idea behind that was, if I had a Player-class (which represents the player obviously), and some other classes like Enemy, Wall, etc., it would be an easy task to check if a Player-object was colliding with one(or more) of these:
// (inside Player::tick(); quick and dirty)
{
if ( (this->parentScene->getIntersections<Wall>(this)).empty() )
// player does not collide with a wall, just move.
else
// player does collide with a wall, do whatever.
}
However, I have got two questions on that:
Does my (general) design show up flaws for the need of dynamic_cast<T *> as replacement for instanceof (like there is in Java for example)
Is it a performant solution on the task? Since for every collision check, Scene basically loops through every Entity * it contains, checks if it collides with the given Entity * and finally casts it to check if it derives from another given class. If that is not performant, what changes were to make in my design to make it performant?
On the performance part it would be better to separate entities in separate vectors by primitive type. Not only you can specifically test a plane vs a sphere for example it eliminates the need to have dynamic_cast entirely ( -> extra speedup ). Also since you already separated the types in vectors you can just ignore the virtual functions and go for non virtual call providing additional performance improvement;
So your scene would look something like this:
class scene
{
std::vector<PlaneEntity> m_planes;
std::vector<CircleEntity> m_circles;
};
And regarding the design of this it is much easier to select the right algorithm when intersecting primities:
This is an example on how a basic collision checking would look based on this design:
void colide(const PlaneEntity & e)
{
for each plane
call plane vs plane collision
for each circle
call plane vs circle collision;
};
void colide(const CircleEntity & e)
{
for each plane
call plane vs circle collision;
for each circle
call circle vs circle collision;
};
So to answer your question:
1: it is not a rule weather to use or not dynamic_cast, it is known that not using it is better for performance.
2: The design described above is not performant at all. Also your design with dynamic cast is even slower. To improve this you need to look into accelerations structures (this is huge topic so i can't explaing everything here) to speed up collision detection. They basically reduce the number of collision check for each primitive giving a massive improvement in performance. Basic structures are KD-Tree, Quad-Trees, Spacial-Hash , Grid, etc. You can find lots of code for each just by googleing them.
Hope this helps,
Raxvan.
I'm trying to make a 2D platform based game (in SFML) for my university work. I'm not asking for anyone to write some code for me but if anyone could offer some pointers I'd be extremely grateful :)
At present I have around 13 classes, including:
BaseEntity (Most game objects derive from this)
Player (Inherits from BE)
Beetle (Inherits from BE - the game is called 'Beetle Dodger' so there will be moving beetles as a threat to the player)
Gem
MagicGem (players needs these to advance through the levels)
Platform
SolidBlock (inherits from Platform)
DownBlock (inherits from Platform - player can fall through but not jump up through this block)
UpBlock (as above but vice versa)
GameSound
Game (The game manager)
I've built most of the games 'building blocks' so to speak - every class has its own update function which is called in Game::Update. The same applies to each object's Draw() function. Every class holds a pointer to the game window so it can achieve these things and they're also passed a number of variables from Game, such as what key is currently being pressed and also the elapsed time (for movement calcs).
All seemed fine and dandy up to here - then I met collisions. Whilst I understand the basis of how they work, I've tried two or three different approaches to implementing them. At first I began with just having the Player class hold a bunch of functions such as CollidesWith( Beetle& b ) and CollidesWith( Platform& plat ). Obviously this is extremely strenuous when testing against every object in my level (including gems of course) and I began to consider how to implement broad phase collision detection. I then tried using an AABB class defined by 2 2DVectors (SFML's built in class). And this is where I got slightly stuck and decided to come and ask for help here. I went back to testing collisions using purely the size of the sprites (as they are defined by a box - the same as AABB's, right?) but I'm not sure this is/was a wise path to take.
Before I make a serious mess up of what're the good foundations of a game, can anyone offer some friendly advice on a good way to implement broad phase and narrow phase collision detection? I had narrow working quite well at one stage and then I realised that a player could still move through the side of a platform, heh.
Should I create a dedicated class for collisions? Or should I continue as I was, using the size of the sprites of each object (each object has it's own sprite and image - in fact I'll show an example):
class BaseEntity
{
public:
// Constructors
BaseEntity();
BaseEntity(sf::RenderWindow* gameWin, string imgPath, sf::Vector2f position = sf::Vector2f(0,0), sf::Vector2f velocity = sf::Vector2f(0,0));
virtual ~BaseEntity();
// Setters
void SetCurrentPos(sf::Vector2f newPos); // Set the current position
void SetPreviousPos(sf::Vector2f newPrevPos); // Shouldn't be needed but there may be rare circumstances
void SetCurrentVel(sf::Vector2f newVel); // Set the velocity
// Getters
sf::Vector2f GetCurrentPos(); // Returns the current position values
sf::Vector2f GetPreviousPos(); // Returns the previous position values
sf::Vector2f GetCurrentVel(); // Returns the current velocity values
void virtual SetSprite(string imgPath); // Set up the images for the sprite
void virtual Update(float elapsedTime); // The function that handles the updating of movement
void virtual Draw(); // The function that handles the 'Draw' aspect of this object
protected:
sf::RenderWindow* p_GameWin; // A pointer to the game window (used for drawing)
sf::Vector2f currentPos;
sf::Vector2f previousPos;
sf::Vector2f currentVel;
sf::Sprite mySprite; // This objects sprite
sf::Image myImage; // This objects image
};
The player class inherits from this and has a few extra functions such as CheckBoundaries, CollidesWith, Jump and also holds a few variables - bool isColliding may be of interest in this scenario.
Cheers guys, and sorry for the essay!
As you have found out solving the collision cannot be considered just at the level of a single game object. You need an object that can keep track of all the objects that participate in collision, and can read from them all the properties that affect collision. If this is done then it can solve collision globally for all the objects once every game update tick.
What I recommend is creating an interface through which you can get all the information required to process the collision detection. All objects that participate in collision will need to inherit from this. The interface will allow you to smoothly transition from the per object case and the global case.
This is just an example to help you understand. You need to adapt it to your own code.
class ICollidable
{
public:
// we use these function to retrieve collision relevant information
// (can be optimised)
virtual sf::Vector2f GetPosition() = 0; // objects have position
virtual sf::Vector2f GetSize() = 0; // objects have a size
// using this function, we notify the object that it collided with something else
virtual void ProcessCollision(ICollidable* other) = 0;
// if you use virtual methods, you need a virtual destructor
virtual ~ICollidable{};
};
Now you can create a collision system. A collision system would hold a list of ICollidable objects that can interact with each other. You can even choose some objects to not participate in collisions at all. This will be responsible to solving the collision at the global level.
class CollisionSystem
{
private:
// hold all objects that participate in collision
std::vector<ICollidable*> objectList;
public:
void AddToCollisionList(ICollidable* obj);
void RemoveFromCollisionList(ICollidable* obj);
void ProcessCollisionList();
}
The CollisionSystem::ProcessCollisionList(); contains the implementation of the collision checking algorithm. It will get the position and size of each object. Base on that information it will decide that two objects collide and call ICollidable::ProcessCollision(ICollidable& other); for each object that collides. This method will be overriden by subclasses to provide class specific functionality.
Inside CollisionSystem, you can use data structures like quad trees or binary trees to speed up the time it takes to solve all collisions. As a first step I recommend just sorting on X axis. By keeping the list sorted you only have to check the neighbors that are not further away than the size of you object.
If the requirements for your game change, you can update with better collision checking algorithm, you can add more attributes to ICollidable. In general you also need to process physics, you could also provide the functionality for that through ICollidable.
And as a tip, if two objects collide, I recommend immediately moving them away from each other so that they don't collide in the next game tick.
Depending on the amount of entities you are dealing with, just checking collision for every object in the game might have a huge cost, in terms of memory and/or in terms of performance.
You might want to pre-treat your objects to classify them by an axis, like increasing x coordinate, to simplify the collision checking. It could be even better to prepare all your objects and sort them before the game even starts, as an initiation to a level for example. I think that would be the way i'd choose to do it, for a first try.