# Question
Title: Many sources of movement in an entity system
I'm fairly new to the idea of entity systems, having read a bunch of stuff (most usefully, this great blog and this answer).

Though I'm having a little trouble understanding how something as simple as being able to manipualate the position of an object by an undefined number of sources.

That is, I have my entity, which has a position component. I then have some event in the game which tells this entity to move a given distance, in a given time.

These events can happen at any time, and will have different values for position and time. The result is that they'd be compounded together.

In a traditional OO solution, I'd have some sort of `MoveBy` class, that contains the distance/time, and an array of those inside my game object class. Each frame, I'd iterate through all the `MoveBy`, and apply it to the position. If a `MoveBy` has reached its finish time, remove it from the array.

With the entity system, I'm a little confused as how I should replicate this sort of behavior.

If there were just one of these at a time, instead of being able to compound them together, it'd be fairly straightforward (I believe) and look something like this:

`PositionComponent` containing `x, y`

`MoveByComponent` containing `x, y, time`

`Entity` which has both a `PositionComponent` and a `MoveByComponent`

`MoveBySystem` that looks for an entity with both these components, and adds the value of `MoveByComponent` to the `PositionComponent`. When the `time` is reached, it removes the component from that entity.

I'm a bit confused as to how I'd do the same thing with many move by's.

My initial thoughts are that I would have:

`PositionComponent`, `MoveByComponent` the same as above

`MoveByCollectionComponent` which contains an array of `MoveByComponent`s

`MoveByCollectionSystem` that looks for an entity with a `PositionComponent` and a `MoveByCollectionComponent`, iterating through the `MoveByComponent`s inside it, applying/removing as necessary.

I guess this is a more general problem, of having many of the same component, and wanting a corresponding system to act on each one. My entities contain their components inside a hash of component type -\> component, so strictly have only 1 component of a particular type per entity.

1. Is this the right way to be looking at this?
2. Should an entity only ever have one component of a given type at all times?

# Answer
> 6 votes
For your scenario, we typically add three components to a game object:

1. TransformComponent (position, orientation, scale)
2. VelocityComponent (speed, direction)
3. ControllerComponent

When game objects need some type of AI functionality such as moving along a path as you described, we assign an AIController to it's list of components. AIControllers are really nothing more beyond a wrapper that steps a Behavioral Tree. The behavior tree is where we design the actual functionality we want to have the game object perform such as:

```
BehaviorTree* tree(new SequentialNode());
tree->addChild(new MoveToNode(x,y,z));
tree->addChild(new WaitNode(30));
tree->addChild(new MoveToNode(a,b,c));
tree->addChild(new WaitNode(30));
gameObject->addComponent(new AIController(tree));

```

The AI subsystem manages AIControllers and so that subsystem ticks the controller which in turn steps the Behavior Tree. The MoveToNode() looks at the present position/orientation, calculates a direction vector and speed to where you want to move to based on it's constructor arguments and sets the values on the velocity component. The movement system is responsible for reading movement components with values and applying physics thus updating the position/orientation accordingly.

The above code simply moves a game object from spawn location to x,y,z in world space, then waits a minimum of 30 seconds, then moves the game object to location a,b,c and then waits another 30 seconds. Once the wait is over, the behavior sequence has finished, so it repeats from the start.

This allows you to easily define whatever AI functionality you need all self contained in the AI subsystem with minimal impact to your Entity subsystem. It also allows you to keep your entity system component list lean without too much granularity too.

# Answer
> 1 votes
An option is to add controllers to your design. Entities own data to represent position (in the case of my engine they have data that remember the previous positions too, so I can know the velocity vector and if they are being moved or teleported), but they don't know nothing about physics or AI. Controllers move entities and you can have many controllers affecting the same entity or one controller affecting various entities.

For example: create a base Controller class with a run() method, or if you don't like the name call it think(), update() or tick(). Then you inherit from it and create a MoveController, NPCController, PlayerInputController (for the player entity), PhysicController; then you implement the run() method. I would put your MoveByComponent in the MoveController and not in Entity.

These Controllers can be instantiated by each Entity if they hold data specific of an Entity. They can be destroyed or reseted for reuse latter. Also you can use a Controller for move a group of entities, in a RTE game for example, if you need to move various units as a group, have a controller by each unit may hurt game performance, then you can simply assign all the units to a GroupController or LegionController and let it move the units as part of a organized group. When fighting, if the game allows individual unit behavior, and probably most games do, you will have to switch to a UnitController but it's better to do that only when needed than from the beginning.

In my developing game I have a MoveController that moves entities following a path, one MoveController exists for each NPC and the player character. Occasionally one is created for boxes or rock that the player can push. The PhysicController, only one instance, that will check positions of all entities assigned to it, if some entity is colliding another assigned entity the resulting position of both is calculated (it actually does more than that but you get the idea). The NPCController is the AI, one instance per NPC. It checks the situation of the NPC and decides where to move, then push the path to a MoveController, that actually moves the NPC. Controllers have a priority, so I can determine in advance their order, the PhysicController is the last to execute.

I advocate for controllers but is not the only "correct" option. For example I remember an Entity interface in Cafu engine that have the think() method in the Entity itself, the user of the class must inherit from Entity and implement think(), I remember a derived class called CompanyBot (that comes with the example game) that do some collision check in that method, as it is called "think" we can assume AI code is expected to be there too. While NeoAxis engine (last time I looked into it) have AI and physics separated from the entities.

There exists a Controller pattern that I have listened about. Maybe you should search for it, and that probably is not exactly what I'm talking about here but sounds like a good solution too.

---
Tags: architecture, component-based, entity-system
---


title: Points around a circumference C#

text:
# Question
Title: Points around a circumference C#
Im trying to get a list of vectors that go around a circle, but i keep getting the circle to go around several times. I want one circel and the dots to be placed along its circumference. I want the first dot to start at 0 and the last dot to end just before 360. Also i need to be able to calculate the spacing by the ammount of points.

```
  List<Vector2> pointsInPath = new List<Vector2>();
    private int ammountOfPoints = 5;
    private int blobbSize = 200;
    private Vector2 topLeft = new Vector2(100, 100);
    private Vector2 blobbCenter;
    private int endAngle = 50;
    private int angleIncrementation;
    public Blobb()
    {
        blobbCenter = new Vector2(blobbSize / 2, blobbSize / 2) + topLeft;
        angleIncrementation = endAngle / ammountOfPoints;

        for (int i = 0; i < ammountOfPoints; i++)
        {
            pointsInPath.Add(getPointByAngle(i * angleIncrementation, 100, blobbCenter));
          //  pointsInPath.Add(getPointByAngle(i * angleIncrementation, blobbSize / 2, blobbCenter));
        }
    }

    private Vector2 getPointByAngle(float angle, float distance, Vector2 centre)
    {
        return new Vector2((float)(distance * Math.Cos(angle) ), (float)(distance * Math.Sin(angle))) + centre ;
    }

```

# Answer
> 3 votes
Set `endAngle` to 2π. The spacing between points **in radians** is your `angleIncrement`.
To get the Euclidean distance between two point the easiest way is calculating the distance between any two neighbouring points of the result.

Also convert `endAngle` and `angelIncrement` to float.

---
Tags: c#, trigonometry
---


# Question
Title: How to properly do weapon cool-down reload timer in multi-player laggy environment?
I want to handle weapon cool-down timers in a fair and predictable way on both client on server.

Situation:

1. Multiple clients connected to server, which is doing hit detection / physics
2. Clients have different latency for their connections to server ranging from 50ms to 500ms.
3. They want to shoot weapons with fairly long reload/cool-down times (assume exactly 10 seconds) It is important that they get to shoot these weapons close to the cool-down time, as if some clients manage to shoot sooner than others (either because they are "early" or the others are "late") they gain a significant advantage.
4. I need to show time remaining for reload on player's screen
5. Clients can have clocks which are flat-out wrong (bad timezones, etc.)

What I'm currently doing to deal with latency:

1. Client collects server side state in a history, tagged with server timestamps
2. Client assesses his time difference with server time:

```
behindServerTimeNs = (behindServerTimeNs + (System.nanoTime() - receivedState.getServerTimeNs())) / 2

```
3. Client renders all state received from server 200 ms behind from his current time, adjusted by what he believes his time difference with server time is (whether due to wrong clocks, or lag). If he has server states on both sides of that calculated time, he (mostly LERP) interpolates between them, if not then he (LERP) extrapolates.
4. No other client-side prediction of movement, e.g., to make his vehicle seem more responsive is done so far, but maybe will be added later

So how do I properly add weapon reload timers?

My first idea would be for the server to send each player the time when his reload will be done with each world state update, the client then adjusts it for the clock difference and thus can estimate when the reload will be finished in client-time (perhaps considering also for latency that the shoot message from client to server will take as well?), and if the user mashes the "shoot" button after (or perhaps even slightly before?) that time, send the shoot event.

The server would get the shoot event and consider the time shot was made as the server time when it was received. It would then discard it if it is nowhere near reload time, execute it immediately if it is past reload time, and hold it for a few physics cycles until reload is done in case if it was received a bit early.

It does all seem a bit convoluted, and I'm wondering whether it will work (e.g., whether it won't be the case that players with lower ping get better reload rates), and whether there are more elegant solutions to this problem.

# Answer
> 2 votes
Is it totally necessary to manage reload times server side? Often the simplest way to do this is on the client side for both fairness and responsiveness. I'm no expert but what I would predict is that the current system encourages spamming and the server has to check whether each request is valid before discarding it, taking up more processing power.

Drawing up a basic model (ignoring processing times etc) of a client with 60ms ping we get:

```
Client sends event at 0ms
Server receives event at 30ms
Server sends time back to client, arrives 60ms
Client can shoot at 10030ms according to both server and client

If ping constant and player clicks once when told shot is ready:
    Client clicks to shoot at 10030ms
    Message arrives at server 10060ms
    Server sends back timer for 20060ms

If ping constant and player spams:
    Messages sent repeatedly to server between 30 and 10030ms
    Around 10030ms one of these messages arrives and is instantly accepted
    Server sends back timer of 20030ms

If ping spikes to ~250ms:
    Spamming is not affected as much as one of the messages will get through
    Single click is delayed by another ~100ms

```

It's a fair system as long as everyone is constantly clicking to shoot near the end of the reload but if you were to manage it client side the effect would only slow the time for the shot to fire and not the reload time itself (which would trigger instantly). In the above example every reload loses a few milliseconds which will build up until entire shots worth of time have been missed.

If the shot is sent to the server and the reload is local then the shot might be late but the reload will always be on time. The initial problem with slow/fast clocks is probably still a thing however. Depending on the language/framework you're using it might be possible to get a better measure of time. Beyond that I'm afraid I can't help much.

---
Tags: networking, multiplayer, client-server, lag, latency
---


title: How can I improve my Animation

text:
# Question
Title: How can I improve my Animation
The first approaches in animation for my game relied mostly on sine and cosine functions with the time as parameter.

Here is an example of a very basic jump I implemented.

```
if(jumping)
{
    height = sin(time);
    if(height < 0) jumping = false; // player landed
    player.position.z = height;
}

if(keydown(SPACE) && !jumping)
{
    jumping = true;
    time = now(); // store the starting time
}

```

So my player jumped in a perfect sine function. That seems quite natural, because he slows down when he reached the top position, and in the fall he speeds up again. But patching every animation out of sine and cosine is stretched to its limits soon.

So can I improve my animation and provide a more abstract layer?

# Answer
> 7 votes
Movement in games is usually approached as constantly changing states, rather than functions. Programming requires a different approach to math than teached in school because it often requires iterative approaches.

```
Character::Update()
{
  [...]
  onGround = [... has the character ground under his feets? ...];
  dt = [... time difference between now and the last time this function was called ...];
  if(keydown(SPACE) && onGround)
  {
    yDir = 40; // Can be anything depending on how high you want the jump to be.
    onGround = false;
  }
  if(!onGround)
  {
    yDir-=gravity*dt;
    y+=yDir*dt;
    if([... collision with the landscape occured...])
    {
      y=[... y-coordinate of the ground];
      yDir=0;
    }
  }
  [...]
}

```

Basically you have two components per coordinate, the position and the velocity. Now every frame the gravity is applied to the y-velocity and checked for collision, in which case the y-velocity is zeroed (= not moving in y direction). Moving left and right is done the same way, just that it isn't affected by gravity.

```
  if(onGround) // You can only walk with feet on the ground
  {
    xDir=0;
    if(keydown(LEFT))
    {
      xDir = -40; // How far should he move?
    }
    else if(keydown(RIGHT))
    {
      xDir =  40;
    }
  }
  x+=xDir*dt;
  if([... collision with the landscape occured...])
  {
    x=[... x-coordinate of the wall];
    xDir=0;
  }

```

---

## General Animation Appendix

Animations are usually hand crafted by artists. In 3D usually bones are used for this, in 2D the animations are usually baked into a spritesheet, in which case it doesn't matter for the engine how they are created. Modern engines often include Inverse Kinematics (IK) for more dynamic motions. Sometimes 2D engines use bones too for the sake of IK.

Other than that there aren't really any "basic concepts" how animations are done, in the end whether a animation looks good or not depends on you fine tuning the parameters. There is no all-in-one solution, everything requires some artistic input.

# Answer
> 1 votes
It depends on your needs, but mostly it is a good idea to implement it as it implemented in real life: by physics! =) You can use 3rd party libraries or write your own stuff. AFAIK most popular lib now is Bullet.

If you don't need all of this, just implement mass, jumping force, gravity force and use Newton laws to calculate position (so your objects will jump with decceleration and fall with acceleration with parabolic trajectories). It will look accurately for any game entity, because its like a real.

---
Tags: animation, jumping
---


# Question
Title: XNA Moddable Game - Architecture Design and Reflection
I've decided to embark on an XNA moddable game project of a simple rogue style. For all purposes of this question, I'm going to not be using a scripting engine, but rather allow modders to directly compile assemblies that are loaded by the game at run time. I know about the security problems this may raise.

So in order to expose the moddable content, I have gone about creating a generic project in XNA called `MyModel`. This contains a number of interfaces that all inherit from `IPlugin`, such as `IGameSystem`, `IRenderingSystem`, `IHud`, `IInputSystem` etc.

Then I've created another project called `MyRogueModel`. This references `MyModel` project, and holds interfaces such as `IMonster`, `IPlayer`, `IDungeonGenerator`, `IInventorySystem`. More rogue specific interfaces, but again, all interfaces in this project inherit from `IPlugin`.

Then finally, I've created *another* project called `MyRogueGame`, that references both `MyModel` and `MyRogueModel` projects. This project will be the game that you run and play. Here I have put the actual implementation of the `Monster`, `DungeonGenerator`, `InputSystem` and `RenderingSystem` classes. This project will also scan the mods directory during run time and load any `IPlugin`s it finds using reflection and override anything it finds from the default. For example if it finds a new implementation of the `DungeonGenerator` it will use that one instead.

Now my question is, in order to get this far, I have effectively 2 projects that contain nothing but interfaces... which seems a little... strange ? For people to create mods for the game, I would give them both the `MyModel` and `MyRogueModel` assemblies in which they would reference. I'm not sure whether this is the right way to do it, but my reasoning goes as follows :

If I write 1 input system, I can use it in any game I write.

If I create 3 rogue like games, and a modder writes 1 rendering system, that modder could use the rendering system for all *3* games, because it all comes from the `MyModel` project.

I come from a more web based C# role, so having empty interface projects doesn't *seem* wrong, its just something I haven't done before. Before I embark on something that might be crazy, I'd just like to know whether this is a foolish idea and whether there's a better (or established) design principle I should be following ?

# Answer
This is a summary of the question comments.

Your solution is good.

It's completely fine to mix abstract classes and interfaces. They have distinct purposes: **Abstract classes** define behaviour expected of its subclasses. **Interfaces** define no behaviour, but only an interface to it. This article goes into more depth.

(By the way, the Code Review beta site is likely better for code structure questions.)
> 3 votes

---
Tags: c#, xna, architecture, modding
---


# Question
Title: Keeping the meshes "thickness" the same when scaling an object
I've been bashing my head for the past couple of weeks trying to find a way to help me accomplish, on first look very easy task. So, I got this one object currently made out of 5 cuboids (2 **sides**, 1 **top**, 1 **bottom**, 1 **back**), this is just for an example, later on there will be whole range of different set ups. Now, the thing is when the user chooses to scale the whole object this is what should happen:

**X** scale: **top** and **bottom** cuboids should get scaled by a scale factor, **sides** should get moved so they are positioned just like they were before(in this case at both ends of **top** and **bottom** cuboids), **back** should get scaled so it fits like before(if I simply scale it by a scale factor it will leave gaps on each side).

**Y** scale: **sides** should get scaled by a scale factor, **top** and **bottom** cuboid should get moved, and **back** should also get scaled.

**Z** scale: **sides**, **top** and **bottom** cuboids should get scaled, **back** should get moved.

Hope you can help,

---

**EDIT** I am asking you, if any of you have any idea on how to accomplish this scaling.

I have tried whole bunch of things, from scaling all of the object by the same scale factor, to subtracting and adding sizes to get the right size. But nothing I tried worked, if one mesh got scaled correctly then others didn't.

Donwload the example object.

# Answer
You have a few options.

* Apply a scale matrix to all the vertices that make up all the objects used to create your form. This is a common procedure, I'm sure XNA has something built in for this. This should be your preferred approach. It's the most common and it will produce the results you want. Additionally, it will work for any combination of shapes you make.
* Scale an invisible box and resize/move your objects to fit around it. Just have six positions that represent each face of a invisible cube. Move those along the axis they represent (top/bottom = y axis, left/right = x axis, front/back = z axis), and have your cuboids make their size and positions match up to the positions. This method would be useful if you wanted to maintain the thickness of your "walls" even after scaling.

+ For example, the top cuboid would use the `top` position as it's position. It would then use each of the side positions to set its width and height.

**EDIT** to clarify the second option.

You have 6 positions:

Those positions define the positions and size of the shapes you have attached.

For example, the top cuboid would defined as such:

```
position = YP
width = XP-XM
height = wallThickness
depth = ZP-ZM

```

Or the back cuboid would be defined as:

```
position = ZP
width = XP-XM
height = YP-YM
depth = wallThickness

```
> 2 votes

---
Tags: xna, c#, algorithm
---


# Question
Title: How to design a character animation system?
I'm searching for suggestions and resources on the possible ways to design a character animation system. I mean a system built on top of the graphics engine (as graphics engine I use Ogre3D, that provide an animation layer), and in strict contact with the logic of the game.

It's for a sports title, so the question is not easy.

**Edit:** What I'm searching for are suggestions and resources about the *action state mechines* (or *animation state machines*), that is build on top of the *animation pipeline* already provided by the graphics engine. So, a state-driver animation interface for use by virtually all higher-level game code.

# Answer
> 1 votes
All the mesh objects I have loaded by OGRE3D have the skeletal poses and animations built into them which simply means that using an Ogre::Entity gives me access to all that information. Assuming you're doing the same, an animation system would allow the following:

1. Allow playing multiple animation with varying weights.
2. Allow deactivating specific animations
3. Play a new animation blending it in while fading existing animations out.

With this wrapped up into a subsystem, you can either choose to expose it to the rest of your game logic either through an interface or through some message queue paradigm.

Realize that certain animations may likely have a higher priority than others too. For example, you want movement animations and attack animations to have similiar priorities so that the player gets the illusion of realistic play with no input lag. Conversely, animations such as deflecting an attack, blood spatter from taking damage, or a dodge animation are great effects, but have a much lower priority.

For example, a player takes damage from an attack from a foe but immediately moves but just doesn't move fast enough. You certainly don't want your being hit animation to affect the realism of the player's movement, and so you may opt to ignore the take damage animation entirely and simply strafe as the player's input dictated. Naturally the sound system may still play the attacked sound clip, but doesn't mean animation must play it either.

---
Tags: architecture, animation, ogre
---


# Question
Title: Sprite and Physics components or sub-components?
I'm taking my first dive into creating a very simple entity framework. The key concepts (classes) are:

* `Entity` (has 0+ components, can return components by type)
* `SpriteEntity` (everything you need to draw on screen, including lighting info)
* `PhysicsEntity` (velocity, acceleration, collision detection)

I started out with physics notions in my sprite component, and then later removed them to a sub-component. The separation of concerns makes sense; a sprite is enough information to draw anything (X, Y, width, height, lighting, etc.) and physics piggybacks (uses the parent sprite to get X/Y/W/H) while adding physics notions of velocity and collisions.

The problem is that I would like collisions to be on an entity level -- meaning "no matter what your representation is (be it sprites, text, or something else), collide against this entity." So I refactored and redirected collision handling from entities to `sprite.physics`, while mapping and returning the right entity on physics collisions.

The problem is that writing code like `this.GetComponent<SpriteComponent>().physics` is a violation of abstraction. Which made me think (this is the TLDR): **should I keep physics as a separate component from sprites, or a sub-component, or something else?** How should I share data and separate concerns?

# Answer
You should keep them separate, yes, a sprite has nothing to do with physics, even if your physics get information like size from the sprite. You could have a `CollisionComponent` with that information, or maybe a `SizeComponent` that both sprite and collision can access. I would recommend the `CollisionComponent` having the size on itself, so you don't actually need a Sprite at all. You will still need to share the position, which brings to the next point: Sharing the data.

Sharing the data is a really difficult question, to which I say it depends. In my code I have systems, they are the ones with logic and they can access more than one component, so a physics system could access the `SpriteComponent` and get the size (probably with no need for a `PhysicsComponent` if *every* object is going to act the same.) In your case, since you didn't mention systems, I'm assuming your components have a pointer to their owner entity, you can simply do something like:

```
class PhysicsComponent
{
...
    void updatePhysics()
    {
        owner->getComponent<SpriteComponent>().position = vec2(...);
        ...
    }
...
}

```

Which is fine for a simple game, you can also make a message system, so your components don't actually depend on other components, they can simply receive and react to generic messages.

I think using systems is a much better approach, but there's nothing wrong with a direct pointer or messages, it's a matter of what makes more sense to you.
> 4 votes

# Answer
I would say that separating out the physics from the sprite is the best way to go. It would otherwise violate the single responsibility principle of the class.

Is there any reason that your solid implementations of these concepts cannot inherit from both of them ? Say for example, you had a `Ball` entity. It would be both a `ISpriteEntity` and a `IPhysicsEntity`. The `Ball` could then be acted upon by both a physics engine, and a rendering engine, for example `PhysicsEngine.Update(IPhysicsEntity)` and `RenderingEngine.Draw(ISpriteEntity)`. This would separate the concerns nicely.

It would also allow your game to 'work' without having a rendering device, say for example if you were running a dedicated server (where there is no need to render anything), the `Ball` would still have its position and velocity updated.

The `Ball` itself would contain the information about its size (height, width etc) rather than relying on the sprite to determine its size. The sprite is just a visual representation of the data behind it, it should not be the data itself. You wouldn't base an objects behavior on the sound it creates, so why do so for the vision it creates ?

You want text to collide as well ? Well your text objects would also implement `IPhysicsEntity` and contain information about its size and position. The physics engine would update all `IPhysicsEntity`s irrespective of what concrete class they actually are.
> 2 votes

# Answer
Definition (Wikipedia): "Sprite: a two-dimensional image or animation that is integrated into a larger scene."

Your own words: SpriteEntity (everything you need to draw on screen, including lighting info)

This is a clear separation of concerns. The physics don't care how the data is displayed on the screen, and the display doesn't care how the object being displayed interacts.

Neither of these objects should inform each other at all, from a purist perspective. What should happen is probably something like this:

```
abstract class GameEntity
{
    Physics _physics;
    Sprite _sprite;

    public Physics Physics
    {
        get {return _physics;}
        private set{_physics = value;}
    }

    public Sprite Sprite
    {
        get { return _sprite; }
        private set { _sprite = value; }
    }

    public GameEntity(Physics physics, Sprite sprite)
    {
        this.Physics = physics;
        this.Sprite = sprite;
    }
}

class Physics { }

class Sprite { }

class SomeObject : GameEntity
{
    public SomeObject()
    {
        Physics p = new Physics(args);
        Sprite s = new Sprite(args);
    }

    protected SomeObject(Physics p, Sprite s)
        : base(p, s) { }
}

```
> 0 votes

# Answer
How two components (what you call *SpriteEntity/PhysicsEntity*) is often something that drastically varies between implementations. Some developers prefer the message/event approach to keep everything absolutely decoupled and not aware of the world outside it's purview of purpose. Others often decide to expose each other through carefully well defined interface classes to minimize the exposure of one component to another. But component systems always face this same problem of shared data exchange.

My preference has always been to separate data and logic when it comes to systems like this. A very trivial example based on your two components would be:

```
// An abstract class to allow for storing components in containers
class IComponent {};

class SpriteComponent : public IComponent {
  /* stores sprite properties like mesh, etc */
};

class PhysicsComponent : public IComponent {
  /* stores rigid body, physics-ish proeprties */
};

```

In this example, I am deriving the two components from a parent class but nothing in dictates that this is necessary. It makes it convenient if you wanted to store these two components in a hetrogenious container but also allows a means to store common API methods between two different component types too.

Now if you wanted to get the position from a physics component, you could do it like the following by using your entity class as the mediator to lookup the needed component reference:

```
class SpriteSystem {
  void Update(float delta) {
    BOOST_FOREACH(SpriteVector::value_type& sprite, mSpriteList) {
      sprite.SetPosition(sprite.GetEntity()->GetComponent<PhysicsComponent>()->GetPosition());
    }
  }
};

```

What I dislike here is that the SpriteSystem which manages my SpriteComponent objects now has complete knowledge of the PhysicsComponents. It also implies that there is most likely some dynamic\_cast\<\> going on under the hood because you probably have a simple hetergenious list storing your components which isn't ideal for performance. It's obviously a pre-optimization no no but dynamic\_cast\<\> are often things I avoid particularly if it's in code that will be executed often in a loop.

Some may be fine with such a solution, but now if that PhysicsComponent's interface changes, I impact the SpriteSystem. One could argue that you cuold abstract that away and subclass PhysicsComponent from a IPhysicsComponent to avoid that probability, but it still doesn't hide the fact that my sprite system is directly dependent on the existing and exposed API of the physics component itself.

So how about we deal with this by providing another layer of indirection?

If we were to consider some slight changes, where entity doesn't actually exist as a class but rather an identifier that categorizes a subset of components across systems and we make a rule in the sand that systems talk to systems and components talk to systems, we've now added that layer of indirection. Combine that with well defined interfaces and you could get something like:

```
class IPhysicsSystem {
  // provides means of getting an entity's position
  Vector3& GetEntityPosition(TEntityId entityId) = 0;
};

class PhysicsSystem : public IPhysicsSystem {
};

class SpriteSystem : public ISpriteSystem {
public:
  SpriteSystem(IPhysicsSystem& physics) : mPhysicsSystem(physics) {}

  void Update(float delta) {
    BOOST_FOREACH(SpriteVector::value_type& sprite, mSpriteList) {
      Vector3& position = mPhysicsSystem.GetEntityPosition(sprite.entityId());
      sprite.SetPosition(position);
    }
};

```

The great part of this design is that you can clearly see the system dependencies because we use constructor injection to represent them. This helps knowing how to order these systems in the update loop so that all your state changes remain consistent in each iterative loop.

The above example demonstrates reactive updates. If you would have rather done proactive updates instead, possibility minimizing the number of sprites to update each pass and the number of physics system calls, you could easily have your physics system check whether a physics component's position changed since the last frame. If it did, send an event/message indicating the entity id and new position. The sprite system could cache those events for when it updates and it would have looked like this:

```
class SpriteSystem : public ISpriteSystem {
public:
  void Update(float delta) {
    BOOST_FOREACH(PositionEventList::value_type& positionEvent, mPositionEventList) {
      GetSpriteByEntityId(positionEvent.entityId).SetPosition(positionEvent.position);
    }
};

```

How you get the events into the sprite system is an entirely different discussion.

The point here is that there are many methods of handling the exchange of data between different components, but believe me when I say that if you can keep your components as decoupled as possible, the ability to maintain and mold your game from iteration to iteration into something bigger and better will be far easier for you.
> 0 votes

---
Tags: xna, 2d, entity-system
---


title: how to organize rendering

text:
# Question
Title: how to organize rendering
I use a deferred rendering. During g-buffer stage my rendering loop for a sponza model (obj format) looks like this:

```
int i = 0;
int sum  = 0;
map<string, mtlItem *>::const_iterator itrEnd = mtl.getIteratorEnd();
for(map<string, mtlItem *>::const_iterator itr = mtl.getIteratorBegin(); itr != itrEnd; ++itr)
{
   glActiveTexture(GL_TEXTURE0 + 0);
   glBindTexture(GL_TEXTURE_2D, itr->second->map_KdId);
   glDrawElements(GL_TRIANGLES, indicesCount[i], GL_UNSIGNED_INT, (GLvoid*)(sum * 4));
   sum += indicesCount[i];
   ++i;
   glBindTexture(GL_TEXTURE_2D, 0);
}

```

I sorted faces based on materials. I switch only a diffuse texture but I can place there more material properties. Is it a good approach ? I also wonder how to handle a different kind of materials, for example: some material use a normal map, other doesn't use. Should I have a different shaders for them ?

# Answer
Optimising render state changes is definitely good.

* You should sort the materials by render state, preferably rating more expensive states (texture change, shader change) higher.
* You should render big and visible geometry first, to increase z culling efficiency. Eg level geometry.
* When there are no expensive render states to change between a group of objects or when the fragment shader is very expansive, sorting them front to back can be faster.
* You should keep track of the render states yourself as opengl doesn't do it and redundant state change are not free at all.
* Sorting by vertex declaration can give considerable performance gains on some platforms.
* Profile

As to writing a seperate shader for features like normal mapping: Normal mapping using tangent space normals requires a different or an additional vertex stream, an additional texture and some decent computations which outweight the fragment shader change in nearly all cases. When sorting the object rendering order you can even remove most of the shader changes. The benefit depends on how costly the feature is and how many objects you render with the feature. Eg if you have 100 objects using normal maps and one object not using them and the object is small it might be faster to render it with an identity normal map. Some simple features, like applying a constant ambient, should just get applied to all objects even if some get black ambient.

I think these are the most important aspects to consider, most importantly test and compare. This msdn article has very details informations on how to accurately measure state changes inn directx which should apply to opengl, linux, macos and mobile platforms too.

Deferred Shading shouldn't change anything it normally leads to less materials due to less freedom when shading and not requiring the many light related state changes which makes sorting more efficiently.
> 5 votes

---
Tags: opengl, glsl, deferred-rendering
---


# Question
Title: How do I add leaderboard feature of OpenFeint in android?
I am developing a game in android, by extending a class with view. I have integrated OpenFeint in it by studying the tutorial provided on the OpenFeint site, but I am not able to add the leaderboard feature in my app. How can I achieve it?

My game class is like this

```
public class GameActivity extends Activity {

Intent i;

Grapic g;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    setContentView(new Grapic(this));

```

and Grapic is a class which extends view and where scoring is done with touch events.

# Answer
If you're getting stuck trying to add OpenFeint (or now GREE) leaderboards to your Android game, then take a look at Swarm (aka SwarmConnect). It's incredibly easy and straight forward to implement and some pretty popular games are already using it (Logo Quiz with 10 million to 50 million downloads is one example).
> 1 votes

---
Tags: android, openfeint
---


title: XNA When to call LoadContent

text:
# Question
Title: XNA When to call LoadContent
I have an enum in my game that denotes the game state ie MainMenu, InGame, GameOver, Exit and I was wondering if it would be advisable to add a new one in for PrepGame - in which the game creates viewports for however many players there are, creates the battlefield etc.

I feel like this is a good idea except for one thing: should I make a call back to LoadContent() in this state? I could just put a switch statement in the LoadContent for my currentGameState. If it equals PrepGame load things like the skybox, ship models, texures, HUD graphics etc. Or is it a good idea to create an Asset Manager class in the first call to LoadContent() and load everything then.

I feel like both approaches have different benefits: faster, but more load times vs slower initial load time, but then all my objects are referencing the same variables so I only have to load each on once.

Any help is greatly appreciated.

Thanks, Peter

# Answer
> 2 votes
If you write down the SWITCH-statement into LoadContent there will be no actions you expect, because LoadContent is invoked only one time - during the initialization. I thing that in LoadContent you should load only resources which common for every game state & level. But it will be good to create methods like LoadContentForLevel1(), LoadContentForLevel2() & others for special states and call it in your state-dependent code.

PS sorry for my english :)

---
Tags: xna, xna-content-pipeline
---


title: How stoper one annimation model on XNA?

text:
# Question
Title: How stoper one annimation model on XNA?
I do not understand how to pause an animation of XNA. I can "Start" the animation of my model but not stop it. I use SkinningSample\_4\_0 sample dll

Here is my code to use.

Here is my code to use.

```
    protected override void LoadContent()
        {
            //Model - Player
            model_player = Content.Load<Model>("Models\\Player\\models");
            // Look up our custom skinning information.
            SkinningData skinningData = model_player.Tag as SkinningData;

            if (skinningData == null)
                throw new InvalidOperationException
                    ("This model does not contain a SkinningData tag.");

            // Create an animation player, and start decoding an animation clip.
            animationPlayer = new AnimationPlayer(skinningData);

            AnimationClip clip = skinningData.AnimationClips["ArmLowAction_006"];

            animationPlayer.StartClip(clip);

}

protected overide update(GameTime gameTime)
{
            animationPlayer.Update(gameTime.ElapsedGameTime, true, Matrix.Identity);
            KeyboardState key = Keyboard.GetState();

            //  If player don't move -> stop anim
            if (!key.IsKeyDown(Keys.W) && !keyStateOld.IsKeyUp(Keys.S) &&           !keyStateOld.IsKeyUp(Keys.A) && !keyStateOld.IsKeyUp(Keys.D))
            {
                //animation stop ? not exist ?
                animationPlayer.Stop();
                isPlayerStop = true;
            }
            else
            {
                if(isPlayerStop == true)
                {
                     isPlayerStop = false;
                     animationPlayer.StartClip(Clip);
            }
}

```

# Answer
I have finally found myself ^^

```
if (!key.IsKeyDown(Keys.W) && !key.IsKeyDown(Keys.A) && !key.IsKeyDown(Keys.D) && !key.IsKeyDown(Keys.S))
{
             //Stop animation for player walking
             animationPlayer.Update(new TimeSpan(0, 0, 0), true, Matrix.Identity);
}
else
{
             //Continue the animation
             animationPlayer.Update(gameTime.ElapsedGameTime, true, Matrix.Identity);
}

```
> 0 votes

---
Tags: xna, c#, animation, models, skeletal-animation
---


# Question
Title: best way of rendering more 3D models in three.js that not slow down page?
I am in the way of creating a 3D web game using threeJS library. This is a multi-player game that players are 3D human models in game, and I need to add a human 3D model for each player that enters the game. Additionally, I want to animate the humans while they walking, but the problem, here is that adding a 3D model and animating that for each player will slow down the game or maybe cause the browser to crash.

question: what is the better way of showing and animating the player's models that will not slow down the game?

# Answer
You can't do extra work for free.

What you need to do instead is do some testing on a range of hardware and browsers, and find out how many players you can handle on the slowest platform you want to support. You can then limit the maximum number of players to that number.

More players also means more network bandwidth is required, you may run out of that before rendering performance becomes an issue.
> 1 votes

---
Tags: webgl, three.js
---


title: Game Timer In C++

text:
# Question
Title: Game Timer In C++
I need to be able to find out how many milliseconds since that last update. Is there any way I can find it out with time rather then a thread that counts like I did below?

```
#include <iostream>
#include<windows.h>
#include<time.h>
#include<process.h>

using namespace std;

int Timer = 0;
int LastTimer = 0;
bool End = false;

void Update(int Ticks)
{

}

void UpdateTimer()
{
    while (true)
    {
        LastTimer = Timer;
        Timer++;
         Sleep(1);
        if (End)
            break;
    }
}

int WINAPI WinMain(HINSTANCE par1, HINSTANCE par2, LPSTR par3, int par4)
{
    _beginthread(UpdateTimer, 0, NULL);
    while(true)
    {
        if (Timer == 1000)
        Timer = 0;
        Update(Timer - LastTimer);
    }
}

```

# Answer
> 4 votes
You should just read the current time from the system; for Windows, use QueryPerformanceCounter or timeGetTime. If you are using some free library for window management (which I highly recommend) like SDL or SFML, they have their own functions. Google 'real time game loop' or 'game loop' for multiple examples of this done right.

BTW, that thread is the most resource-consuming, completely inaccurate way of measuring time that I have seen. Sleep() is very imprecise. You should generally not use threads in a game except for performance reasons, and if you are new to the field you shouldn't use them at all. Even if you need to perform an action every few seconds, don't use a thread with sleep for that, just run it from your main loop.

# Answer
> 4 votes
Your Game loop should look something like this

```
lastTime =  time();
while (!quit)
{
   currentTime = time();
   deltaTime = currentTime - lastTime;
   lastTime = currentTime;
   UpdateFrame(deltaTime);
}

```

For a crossplatform way to get the time check out this project https://github.com/rampantpixels/timer\_lib

now this is called a variable time step update if your game involves physics check out this link http://gafferongames.com/game-physics/fix-your-timestep/

and also see this question here When should I use a fixed or variable time step?

# Answer
> 4 votes
If your using C++11 it has a new Chrono library that allows you to get the system time in milliseconds so you don't have to rely on functions shipped with a 3rd party library. There is also a Boost version if you need to backport it to a non-C++11 system.

# Answer
> 2 votes
You want to use the High performance counter on Windows. Here is my `Timer` class:

```
class Timer
{
  LARGE_INTEGER startTime ;
  double fFreq ;

public:
  Timer() {
    LARGE_INTEGER freq ;
    QueryPerformanceFrequency( &freq ) ;
    fFreq = (double)freq.QuadPart ;
    reset();
  }

  void reset() {   QueryPerformanceCounter( &startTime ) ;  }

  // Gets the most up to date time.
  double getTime() const {
    LARGE_INTEGER endTime ;
    QueryPerformanceCounter( &endTime ) ;
    return ( endTime.QuadPart - startTime.QuadPart ) / fFreq ; // as double
  }
} ;

```

Use:

```
int main()
{
  Timer t ;

  // do some things..
  printf( "time: %f\n", t.getTime() );

  t.reset() ;
  // do some more things
  printf( "time: %f\n", t.getTime() );
}

```

# Answer
> 1 votes
I use this in most of my projects:

```
//define these somewhere
unsigned int currentframe;
double framerate;
double oldtime;
double newtime;
__int64 counter;
__int64 frequency;
double timeperframe;

//framerate management, call this every frame
QueryPerformanceCounter( (LARGE_INTEGER*)&counter );
QueryPerformanceFrequency( (LARGE_INTEGER*)&frequency );
newtime = (double)counter / (double)frequency;
timeperframe = newtime - oldtime;
framerate = 1.0 / timeperframe;
oldtime = newtime;
currentframe++;

```

---
Tags: c++, windows, timer
---


# Question
Title: Is good practice to optimize FPS even when it's above the lower limit to give illusion of movement?
I started over 50 FPS on the iPhone, but now I'm bellow 30 PFS, I've seen most iPhone games clamped to either 60 or 30 FPS, even when 24 or less would give the illusion of movement.

I've concidered my limit to be a little bit over 15 FPS, in fact my physics simulation is updated at that rate (15.84 steps/s) as that is the lowest that still give fluid movement, a bit lower gives jerky motion.

**Is there a practical reason why to clamp FPS way above the lower limit?**

Update:

The following image could help to clarify

I can independently set the physic simulation step, frame rate, and simulation interval update.

My concern is why should I clamp any of those to values greater than the minimum?

For instance to conserve battery life I could just to choose the lower limits, but it seems that 60 or 30 FPS are the most used values.

# Answer
> 6 votes
There is no fixed "lower limit" when motion looks smooth. It's all dependent on the resolution of the display, the amount of movement, the speed of movement, and on high-DPI displays like an iPad 3/4, the resolution of the player's eyes and their distance from the screen.

If nothing in your game moves or reacts more than one pixel every second, you don't need anything more than 1fps. If something in your game moves 25 pixels a second, 25fps will look smoother than 24fps. Conversely, even at 60fps, sufficiently fast or large motion will appear jerky.

# Answer
> 4 votes
While 24fps is the framerate of movies and that gives the illusion of movement visually, there are a couple of caveats to consider.

First off, movie frames have motion blur in them naturally and that makes fast movements look more continuous between frames. Games generally don't have motion blur to connect fast movement between frames, so they need higher framerates in order for fast movements to look continuous.

Secondly, our sensitivity to responsiveness is greater than our sensitivity to visuals. In other words, in a fast paced twitchy game the controls will feel sluggish if there is too much of a lag between when you press a button and when the game responds. The difference between 30fps and 60fps in responsiveness isn't going to be noticed on a slower paced puzzle game, but will be noticed on something like a multiplayer first-person shooter.

# Answer
> -1 votes
A framerate which is experienced as "smooth" by the player depends greatly on the perspective of your game.

When you have a 2d game which never moves the viewpoint, 12 fps already seem smooth enough.

When you add scrolling, you need at least 24 to make the scrolling feel smooth.

A 3d first person perspective doesn't seem really smooth unless you have at least 60 fps.

---
Tags: iphone, frame-rate
---


# Question
Title: Is it possible to have the main callback functions in different files with love2d?
Is it possible to have love.load(), love.draw() and love.update() in different files? and if so how would I go about doing that?

# Answer
> 1 votes
**EDIT**

It seems I misunderstood your question; you are not asking how to switch between different callbacks, you want to have them in different files.

The principle is the same:

```
load_module = require "main_load"
love.load = load_module.load

```

---

I've written a scene manager to do just that. I will open source it some day but to give you an idea here's how it is used:

```
-- main.lua
function love.load()
  scene_manager.add(require "scenes/foo")
  scene_manager.add(require "scenes/bar")
  scene_manager.change("foo")
end

```

The `change` method looks like this:

```
  unload_scene()
  current_scene = scenes[scene_name]
  load_scene()

```

Basically you need to iterate over the various methods (`load`, `update` as well as `mousereleased` for instance) and then do `love[method_name] = nil`.

Then in `load_scene` you need to set it `love[method_name] = current_scene[method_name]`.

I know this is not a comprehensive answer but it should get you started. So, yes, it can be done.

---
Tags: lua, love2d
---


# Question
Title: How should I plan the inheritance structure for my game?
I am trying to write a platform shooter in C++ with a really good class structure for robustness. The game itself is secondary; it is the learning process of writing it that is primary.

I am implementing an inheritance tree for all of the objects in my game, but I find myself unsure on some decisions.

One specific issue that it bugging me is this:

I have an `Actor` that is simply defined as anything in the game world. Under `Actor` is `Character`. Both of these classes are abstract.

Under `Character` is the `Philosopher`, who is the main character that the user commands. Also under `Character` is `NPC`, which uses an AI module with stock routines for friendly, enemy and (maybe) neutral alignments.

So under `NPC` I want to have three subclasses: `FriendlyNPC`, `EnemyNPC` and `NeutralNPC`. These classes are not abstract, and will often be subclassed in order to make different types of NPC's, like `Engineer`, `Scientist` and the most evil `Programmer`.

Still, if I want to implement a generic NPC named Kevin, it would nice to be able to put him in without making a new class for him. I could just instantiate a `FriendlyNPC` and pass some values for the AI machine and for the dialogue; that would be ideal.

But what if Kevin is the one benevolent `Programmer` in the whole world? Now we must make a class for him (but what should it be called?). Now we have a character that should inherit from `Programmer` (as Kevin has all the same abilities but just uses the friendly AI functions) but also should inherit from `FriendlyNPC`.

`Programmer` and `FriendlyNPC` branched away from each other on the inheritance tree, so inheriting from both of them would have conflicts, because some of the same functions have been implemented in different ways on the two of them.

**1)** Is there a better way to order these classes to avoid these conflicts? Having three subclasses; `Friendly`, `Enemy` and `Neutral`; from each type of NPC; `Engineer`, `Scientist`, and `Programmer`; would amount to a huge number of classes.

I would share specific implementation details, but I am writing the game slowly, piece by piece, and so I haven't implemented past `Character` yet.

**2)** Is there a place where I can learn these programming paradigms? I am already trying to take advantage of some good design patterns, like MVC architecture and Mediator objects. The whole point of this project is to write something in good style.

It is difficult to tell what should become a subclass and what should become a state (i.e. Friendly boolean v. Friendly class). Having many states slows down code with `if` statements and makes classes long and unwieldy. On the other hand, having a class for everything isn't practical. **3)** Are there good rules of thumb or resources to learn more about this?

**4)** Finally, where does templating come in to this? How should I coordinate templates into my class structure? I have never actually taken advantage of templating honestly, but I hear that it increases modularity, which means good code.

# Answer
> 9 votes
Refer to the popular software engineering principle, "Prefer composition over inheritance". Class proliferation concerns are the central reason behind the Component-Based Entity Systems (CBEs) so often mentioned on this site, which is a gamedev-specific embodiment of the aforementioned principle.

The essence of the matter is that inheritance hierarchies are compile-time-composable ONLY, whereas composition hierarchies (objects consisting of other objects and primitives) are runtime-composable. Immutable vs. mutable. Your choice.

See Mick West's introduction to CBES. Also see answers like this one (ahem), by searching this site for "composition inheritance".

# Answer
> 4 votes
Regarding question two:

http://www.oodesign.com/

Look for:

* Singleton
* Visitor
* Observer
* Command
* Proxy

---
Tags: c++, game-design, inheritance
---


# Question
Title: Is there a prohibition against scaling collision shapes at runtime?
So, I have a StaticMeshComponent attached to an Actor:

```
Begin Object Class=StaticMeshComponent Name=StaticMeshComponentObject
    StaticMesh=StaticMesh'QF_Art_Powers.Mesh.GP_ForcePush'
    CollideActors=true
    BlockActors=false
    //Scale3D=(X=5, Y=1.5, Z=3) // ALMODEBUG
End Object
CollisionComponent=StaticMeshComponentObject
Components.Add(StaticMeshComponentObject)

```

Ordinarily, the actor gets spawned, anything touching it gets bumped, and the actor despawns itself. If I set the Scale3D as a default property, everything works as I expect.

But I want to scale it at runtime, like this:

```
function SetImpulseComponentTemplate(QuadForceBoxImpulseComponent Value)
{
    Local Vector ScaleVec;

    ScaleVec.X = Value.Length;
    ScaleVec.Y = Value.Width;
    ScaleVec.Z = Value.Height;
    CollisionComponent.SetScale3D(ScaleVec);
}

```

When I do this, the thing only collides as if it were not scaled. If I leave the actor spawned so I can see it, it is scaled. If I also "show collision", the collision displays correctly as well.

Is there a prohibition against scaling collision shapes at runtime?

# Answer
Just as a note, "show collision" only shows the default collision. You need to "nxvis collision" to show the physics collision. You'll notice if you scale at runtime the default collision scales, but the physics one stays at the initial value. I myself am struggling with this issue atm. I think the only hope is to remove the mesh (and physics) and re-add it after scaling the actor, then manually reinitialise the rigidbody physics system. The last part I can't get to work without massive errors, the furthest I've got is the physics collision updating to the correct size, but then everything is frozen.

Here is a link to a thread about the issue, there is a link in the 6th post with another more detailed thread. http://forums.epicgames.com/threads/889495-Resizing-a-KActor
> 1 votes

---
Tags: udk
---


title: Speed up content loading

text:
# Question
Title: Speed up content loading
I am using WinForms Sample downloaded from microsoft website. The problem is, that the model loading time is quite long, using:

```
contentBuilder.Add(ModelPath, ModelName, null, "ModelProcessor");
contentManager.Load<Model>(ModelName);

```

even a simple model, such as a cube with no textures, takes 4+ seconds to load. Now, I am no expert on this, but is there anyway to decrease loading time?

---

**EDIT:**

I've gone thru the code and found out that calling `contentBuilder.Build();` ,which comes right after `contentBuilder.Add()` method takes up most of the time.

# Answer
I've found out that adding all models to contentBuilder: `contentBuilder.Add(ModelPath, ModelName, null, "ModelProcessor");`, and when all models are added, calling `contentBuilder.Build();` and then looping thru all models and loading them `contentManager.Load(ModelName);` speeds things up. Before one model took around 3-4 seconds to load, this way 8 models took around 6 seconds to load, so it is a improvement but I still think this is a bit to much, but agan I am no expert on this matter.
> 0 votes

---
Tags: xna, c#, xna-4.0
---


# Question
Title: Picking a suitable resolution for a modern low-res game?
I'm working on a 2D game project right now (using SFML+OpenGL and C++) and I'm trying to figure out how to go about choosing a resolution. I want my game to have a pixel resolution that is around that of classic '16bit' era consoles like the Super Nintendo or Neo Geo. However, I'd also like to have my game fit the 16:9 aspect ratio that most modern PC monitors use. Finally I'd like to be able to include an option for running full screen.

I know that I could create my own low-res 16:9 resolution that is more-or-less around the size of SNES or NeoGeo games. However, the problem seems to be that doing so would leave me with a non-standard resolution that my monitor would not be able to support in fullscreen mode.

For example, if i divide the common 16:9 resolution 1920x1080 by 4, I would get a 16:9 resolution that is relatively close to the resolution used by 16bit era games; 480x270. That would be fine in a windowed mode, but I don't think that it would be supported in fullscreen mode.

How can I choose a resolution that suits my needs? Can I use something like 480x270? If so, how would I go about getting fullscreen mode to work with such a non-standard resolution? (I'm guessing OpenGL/SFML might have a way of up-scaling...but..)

# Answer
You found the right answer yourself - you will have to render things to an off-screen buffer and upscale it to any of the supported resolutions. This will be very easy since oldschool games didn't have anything better than nearest neighbor interpolation anyway.

If you use GPU for this, it's possible to avoid a resolution switch (upscaling to large resolutions can cost quite a lot of CPU time otherwise).

It would also allow the use of better upscaling algorithms, if you're interested. I'd highly suggest looking into these, at least for the people with bigger monitors than whatever laptops usually offer since nearest neighbor interpolation will look really bad for those people. They usually also have a good GPU so it isn't much of an implementation problem.
> 2 votes

---
Tags: opengl, sfml, screen, resolution, pixel
---


title: Multiply mode in SpriteBatch

text:
# Question
Title: Multiply mode in SpriteBatch
I have a "lighting" texture (black background with white or colours for lights) that I want to draw as a multiplcation operation. `SpriteBatch.Begin` can specify `BlendState.Additive`, but there's no `BlendState.Multiplicative`.

I also tried the solution in this answer, but it didn't work -- even when I (incorrectly?) changed the code to work with XNA 4 style `ColorDestinationBlend`, I ended up with the final solution being inverted (black area where the light is, everything else is visible).

I initially thought of a shader, but I couldn't get shaders to work with MonoGame, so I'm falling back to `SpriteBatch`.

# Answer
Create your own BlendState, eg:

```
BlendState blend = new BlendState();
blend.ColorBlendFunction = BlendFunction.Add;
blend.ColorSourceBlend = Blend.DestinationColor;
blend.ColorDestinationBlend = Blend.Zero;

```

This will result in out.rgb = source.rgb * destination.rgb + 0;

**Edits by questioner:** I had to also set the drawing mode to `SpriteSortMode.Immediate` before this worked.
> 5 votes

---
Tags: xna, lighting, monogame
---


# Question
Title: How can I compute the distance between two actors in Stencyl?
How do U use the "distance" behavior in Stencyl?

I need to know the distance between two actors in order to start a timer.

# Answer
> 2 votes
You need to create a Custom Block. With the custom block you can make your own logic, and lucky for you, the page even provides distance between actors (X distance anyway) as the example:

Remember the documentation is always an excellent place to start with questions like this, and Stencyl appears to have great documentation.

---
Tags: stencyl
---


# Question
Title: VBO and shaders confusion, what's their connection?
Considering OpenGL 2.1 VBOs and 1.20 GLSL shaders:

* When creating an entity like "Zombie", is it good to initialize just the VBO buffer with the data once and do N `glDrawArrays()` calls per each N zombies? Is there a more efficient way? (With a single call we cannot pass different uniforms to the shader to calculate an offset, see point 3)
* When dealing with logical object (player, tree, cube etc), should I always use the same shader or should I customize (or be able to customize) the shaders per each object? Considering an entity class, should I create and define the shader at object initialization?
* When having a movable object such as a human, is there any more powerful way to deal with its coordinates than to initialize its VBO object at 0,0 and define an uniform offset to pass to the shader to calculate its real position?

# Answer
1. For dynamic, animated objects reducing draw calls is not that easy as much data is required for each instance. You can pass multiple transformations at once as long as you have constant registers left and use GL\_ARB\_draw\_instanced to let opengl draw the VBO multiple times with an automatically incrementing instanceId that you can use to access the transformations from your uniforms belonging to the current instance. The amount of instances you can draw using this technique is limited by your target hardware and the number of bones of the object. This is a decent method to render a big amount of non-animated dynamic objects too but for this GL\_ARB\_instanced\_arrays is probably better as it allows basically passing an unlimited amount of instances using a second vertex stream with a different frequency (advances once for each instance). But this method will not work for animated data as it is not possible to pass all bones in one vertex. You could use textures thought.
2. As many objects look differrently and require different shaders I would allow specifying a shader per object and sort the objects before rendering to remove obsolete shader changes.
3. No. The object could move each frame. The camera could move each frame. All vertices need to be transformed and projected for rendering each frame. Applying a movement in world space is basically free as it is simply added into the transformation the gpu has to do anyway.
4. **I would recommend to extract this into a seperate question.** I would probably store an array of all positions, all orientation etc. for all objects into seperate arrays and store one or multiple indices in the typed objects as most of this information is not exclusively required by zombies and some calculations are faster this way. But I'm not very experienced with that design yet.
> 3 votes

---
Tags: opengl, game-design, shaders, vbo
---


# Question
Title: How can I test if my rotated rectangle intersects a corner?
I have a square, tile-based collision map. To check if one of my (square) entities is colliding, I get the vertices of the 4 corners, and test those 4 points against my collision map. If none of those points are intersecting, I know I'm good to move to the new position.

I'd like to allow entities to rotate. I can still calculate the 4 corners of the square, but once you factor in rotation, those 4 corners alone don't seem to be enough information to determine if the entity is trying to move to a valid state.

**For example:**

In the picture below, black is unwalkable terrain, and red is the player's hitbox. The left scenario is allowed because the 4 corners of the red square are not in the black terrain.

The right scenario would *also* be (incorrectly) allowed, because the player, cleverly turned at a 45\* angle, has its corners in valid spaces, even if it is (quite literally) cutting the corner.

How can I detect scenarios similar to the situation on the right?

# Answer
> 6 votes
I finally got a decent collision detection implemented. I wound up using a 3d version of XenoCollide / Minkowski Portal Refinement, a la Gary Snethen in Game Programming Gems 7.

I've created a C# implementation of MPR below. It will return the direction of the minimum penetration vector. I know it's possible to return actual collision points, but I've not been able to implement that part, yet.

At any rate, here's the code for Minkowski Portal Refinement (MPR) / XenoCollide in 3d:

```
using System.Collections;
using System.Collections.Generic;

    //make the associated dot / cross products easier to read
    public static class Vector3Extensions
    {
        public static float Dot(this Vector3 op1, Vector3 op2)
        {
            return Vector3.Dot(op1, op2);
        }

        public static Vector3 Cross(this Vector3 op1, Vector3 op2)
        {
            return Vector3.Cross(op1, op2);
        }
    }

public static class MPRCollision {

    //points used by the algorithm
    static Vector3 v0;
    static Vector3 v1;
    static Vector3 v2;
    static Vector3 v3;
    static Vector3 v4;

    //if the difference in iteration is less than this,
    //we aren't going to (can't!) converge.
    static float kCollideEpsilon = 1e-3f;

    static Vector3 GetSupport(List<Vector3> shape, Vector3 direction)
    {

        Vector3 point = shape[0];

        for(int i = 1; i < shape.Count; i++)
        {
            //is the current point more "direction" than our result point?
            if ( (shape[i] - point).Dot(direction) > 0 )
            {
                //new result point
                point = shape[i];
            }
        }
        return point;

    }

    public static bool CheckCollide(List<Vector3> shape1, List<Vector3> shape2,
                                    Vector3 center1, Vector3 center2, ref Vector3 penVector)
    {
        //holding variables
        Vector3 n = Vector3.zero;
        Vector3 swap = Vector3.zero;

        // v0 = center of Minkowski sum
        v0 = center2 - center1;

        // Avoid case where centers overlap -- any direction is fine in this case
        if (v0 == Vector3.zero) v0 = new Vector3(0, 0.00001f, 0);

        // v1 = support in direction of origin
        n = -v0;

        //get the differnce of the minkowski sum
        Vector3 v11 = GetSupport(shape1, -n);
        Vector3 v12 = GetSupport(shape2, n);

        v1 = v12 - v11;

        //if the support point is not in the direction of the origin
        if (v1.Dot(n) <= 0)
        {
            //return the direction of the origin, because we're not colliding
            if (penVector != null) penVector = n;
            return false;
        }

        // v2 - support perpendicular to v1,v0
        n = v1.Cross(v0);
        if (n == Vector3.zero)
        {
            //v1 and v0 are parallel, which means
            //the origin is within the first portal?
            n = v1 - v0;

            if (penVector != null) penVector = n.normalized;
            return true;
        }

        //no early outs yet, so get the new support point
        Vector3 v21 = GetSupport(shape1, -n);
        Vector3 v22 = GetSupport(shape2, n);
        v2 = v22 - v21;

        if (v2.Dot(n) <= 0)
        {
            //can't reach the origin in this direction, ergo, no collision
            if (penVector != null) penVector = n;
            return false;
        }

        // Determine whether origin is on + or - side of plane (v1,v0,v2)
        //tests linesegments v0v1 and v0v2
        n = (v1 - v0).Cross(v2 - v0);
        float dist = n.Dot(v0);

        // If the origin is on the - side of the plane, reverse the direction of the plane
        if (dist > 0)
        {
            //swap the winding order of v1 and v2
            swap = v1;
            v1 = v2;
            v2 = swap;

            //swap the winding order of v11 and v12
            swap = v12;
            v12 = v11;
            v11 = swap;

            //swap the winding order of v11 and v12
            swap = v22;
            v22 = v21;
            v21 = swap;

            //and swap the plane normal
            n = -n;
        }

        ///
        // Phase One: Identify a portal

        while (true)
        {
            // Obtain the support point in a direction perpendicular to the existing plane
            // Note: This point is guaranteed to lie off the plane
            Vector3 v31 = GetSupport(shape1, -n);
            Vector3 v32 = GetSupport(shape2, n);
            v3 = v32 - v31;

            if (v3.Dot(n) <= 0)
            {
                //can't enclose the origin within our tetrahedron
                if (penVector != null) penVector = n;
                return false;
            }

            // If origin is outside (v1,v0,v3), then eliminate v2 and loop
            if (v1.Cross(v3).Dot(v0) <= 0)
            {
                //failed to enclose the origin, adjust points;
                v2 = v3;
                v21 = v31;
                v22 = v32;
                n = (v1 - v0).Cross(v3 - v0);
                continue;
            }

            // If origin is outside (v3,v0,v2), then eliminate v1 and loop
            if (v3.Cross(v2).Dot(v0) < 0)
            {
                //failed to enclose the origin, adjust points;
                v1 = v3;
                v11 = v31;
                v12 = v32;
                n = (v3 - v0).Cross(v2 - v0);
                continue;
            }

            bool hit = false;

            ///
            // Phase Two: Refine the portal

            int phase2 = 0;

            // We are now inside of a wedge...
            while (phase2 < 20)
            {
                phase2++;

                // Compute normal of the wedge face
                n = (v2 - v1).Cross(v3 - v1);

                n.Normalize();

                // Compute distance from origin to wedge face
                float d = n.Dot(v1);

                // If the origin is inside the wedge, we have a hit
                if (d >= 0 && !hit )
                {
                    if (penVector != null) penVector = n;
                    hit = true;
                }

                // Find the support point in the direction of the wedge face
                Vector3 v41 = GetSupport(shape1, -n);
                Vector3 v42 = GetSupport(shape2, n);
                v4 = v42 - v41;

                float delta = (v4 - v3).Dot(n);
                float separation = -(v4.Dot(n));

                if (delta <= kCollideEpsilon || separation >= 0)
                {
                    //Debug.Log("Non-convergance detected");
                    if (penVector != null) penVector = n;
                    return hit;
                }

                // Compute the tetrahedron dividing face (v4,v0,v1)
                float d1 = v4.Cross(v1).Dot(v0);

                // Compute the tetrahedron dividing face (v4,v0,v2)
                float d2 = v4.Cross(v2).Dot(v0);

                // Compute the tetrahedron dividing face (v4,v0,v3)
                float d3 = v4.Cross(v3).Dot(v0);

                if (d1 < 0)
                {
                    if (d2 < 0)
                    {
                        // Inside d1 & inside d2 ==> eliminate v1
                        v1 = v4;
                        v11 = v41;
                        v12 = v42;
                    }
                    else
                    {
                        // Inside d1 & outside d2 ==> eliminate v3
                        v3 = v4;
                        v31 = v41;
                        v32 = v42;
                    }
                }
                else
                {
                    if (d3 < 0)
                    {
                        // Outside d1 & inside d3 ==> eliminate v2
                        v2 = v4;
                        v21 = v41;
                        v22 = v42;
                    }
                    else
                    {
                        // Outside d1 & outside d3 ==> eliminate v1
                        v1 = v4;
                        v11 = v41;
                        v12 = v42;
                    }
                }
            }

            return false;
        }
    }
}

```

---
Tags: collision-detection
---


# Question
Title: Can I publish an indie game on XBL made with directx
So I know that XNA can be used to publish games on Xbox Live Indie Games and I signed up for the $100/year subscription thing.

I haven't downloaded XNA yet but I was wondering if I can publish a game made entirely in DirectX onto it or do I have to go through XNA?

# Answer
> 2 votes
XNA is the only method for a consumer (such as your yourself) to get a game onto the 360, and it requires managed code.

Licensed developers can use native code toolchains, which provides access to an API much like Direct3D (but which isn't *exactly* Direct3D).

---
Tags: directx, xbox-live
---


# Question
Title: Organizing an entity system with external component managers?
I'm designing a game engine for a top-down multiplayer 2D shooter game, which I want to be reasonably reuseable for other top-down shooter games. At the moment I'm thinking about how something like an entity system in it should be designed. First I thought about this:

I have a class called EntityManager. It should implement a method called Update and another one called Draw. The reason for me separating Logic and Rendering is because then I can omit the Draw method if running a standalone server.

EntityManager owns a list of objects of type BaseEntity. Each entity owns a list of components such as EntityModel (the drawable representation of an entity), EntityNetworkInterface, and EntityPhysicalBody.

EntityManager also owns a list of component managers like EntityRenderManager, EntityNetworkManager and EntityPhysicsManager. Each component manager keeps references to the entity components. There are various reasons for moving this code out of the entity's own class and do it collectively instead. For example, I'm using an external physics library, Box2D, for the game. In Box2D, you first add the bodies and shapes to a world (owned by the EntityPhysicsManager in this case) and add collision callbacks (which would be dispatched to the entity object itself in my system). Then you run a function which simulates everything in the system. I find it hard to find a better solution to do this than doing it in an external component manager like this.

Entity creation is done like this: EntityManager implements the method RegisterEntity(entityClass, factory) which registers *how* to create an entity of that class. It also implements the method CreateEntity(entityClass) which would return an object of type BaseEntity.

Now comes my problem: How would the reference to a component be registered to the component managers? I have no idea how I would reference the component managers from a factory/closure.

# Answer
Systems should store a key value pair of Entity to Component in some sort of Map, Dictionary Object, or Associative Array (depending on language used). Furthermore, when you create your Entity Object, I wouldn't worry about storing it in a manager unless you need to be able to unregister it from any of the Systems. An Entity is a composite of components, but it shouldn't handle any of the component updates. That should be handled by the Systems. Instead treat your Entity as a key that is mapped to all components it contains in the systems, as well as a communication hub for those components to talk to each other.

The great part about Entity-Component-System models is that you can implement the ability to pass messages from one component to the rest of an entity's components quite easily. This allows a component to talk to another component without actually knowing who that component is or how to handle the component it's changing. Instead it passes a message and lets the component change itself (if it exists)

For instance, a Position System would not have much code in it, only keeping track of Entity Objects mapped to their Position Components. But when a position changes, they can send a message to the Entity involved, which in turn is handed off to all of that entity's components. A position changes for what ever reason? Position System sends Entity a message saying that the position changed, and somewhere, that entity's image rendering component gets that message and updates where it'll draw itself next.

Conversely, A Physics System needs to know what all of it's objects are doing; It must be able to see all world objects to test collisions. When a collision happens, it updates the Entity's direction component by sending some sort of "Direction Change Message" to the entity instead of referring to the Entity's component directly. This decouples the manager from needing to know how to change directions by using a message instead of relying on a specific component being there (which it may not be there at all, in which case the message would just fall on deaf ears instead of some error occurring because an expected object was absent).

You'll notice a huge advantage from this since you mentioned you have a Network Interface. A Network Component would listen to all messages coming in that everyone else should know about. It loves the gossip. Then when the Network System updates, the Network components send those messages to other Network Systems on other client machines, which then resend those messages to all the other components to update player positions, etc. Special logic might be needed so that only certain entities can send messages over the network but that's the beauty of the System, you can just have it control that logic by registering the right things to it.

In short:

Entity is a composition of Components that can receive messages. Entity can receive messages, delegating said messages to all of their components to update them. (Position changed Message, Speed Change Direction, etc) It's like a central mailbox that all components can hear from each other instead of talking directly to each other.

Component is a small part of an Entity that stores some state of the entity. These are able to parse certain messages and throw other messages out. For instance, a "Direction Component" would only care about "Direction Change Messages" but not "Position Change Messages". Components update their own state based on messages, and then update other components' states by sending messages from their System.

System manages all components of a certain type, and is responsible for updating said components each frame, as well as dispatching messages from the component's they manage to the Entities that the Components belong to

Systems could be able to update all of their components in parallel, and store all messages as they go. Then when execution of all Systems' update methods complete, you ask each system to dispatch their messages in a specific order. Controls first possibly, followed by Physics, followed by direction, position, rendering, etc. It matters which order they are dispatched in since a Physics Direction Change should Always out weigh a control based direction change.

Hope this helps. It's a hell of a Design Pattern, but it's ridiculously powerful if done right.
> 6 votes

# Answer
1) Your Factory method should be passed a reference to the EntityManager that called it (I'll use C# as an example):

```
delegate BaseEntity EntityFactory(EntityManager manager);

```

2) Have CreateEntity also receive an id (e.g. a string, integer, it's up to you) besides the class/type of the entity, and automatically register the created entity on a Dictionary using that id as a key:

```
class EntityManager
{
    // Rest of class omitted

    BaseEntity CreateEntity(string id, Type entityClass)
    {
        BaseEntity entity = factories[entityClass](this);
        registry.Add(id, entity);
        return entity;
    }

    Dictionary<Id, BaseEntity> registry;
}

```

3) Add a Getter to EntityManager to get any entity by ID:

```
class EntityManager
{
    // Rest of class omitted

    BaseEntity GetEntity(string id)
    {
        return registry[id];
    }
}

```

And that's all you need to reference any ComponentManager from within your Factory method. For instance:

```
BaseEntity CreateSomeSortOfEntity(EntityManager manager)
{
    // Create and configure entity
    BaseEntity entity = new BaseEntity();
    RenderComponent renderComponent = new RenderComponent();
    entity.AddComponent(renderComponent);

    // Get a reference to the render manager and register component
    RenderEntityManager renderer = manager.GetEntity("RenderEntityManager") as RenderEntityManager;
    if(renderer != null)
        renderer.Register(renderComponent)

    return entity;
}

```

Besides Id you can also use some sort of Type property (a custom enum, or just rely on the language's type system), and create a getter that returns all BaseEntities of a certain type.
> 0 votes

# Answer
I'm using a similar system in my engine and the way I've done it is each Entity contains a list of Components. From the EntityManager, I can query each of the Entities and see which ones contain a given Component. Example:

```
class Component
{
    private uint ID;
    // etc...
}

class Entity
{
    List<Component> Components;
    // etc...
    public bool Contains(Type type)
    {
        foreach(Component comp in Components)
        {
            if(typeof(comp) == type)
                return true;
        }
        return false;
    }
}

class EntityManager
{
    List<Entity> Entities;
    // etc...
    public List<Entity> GetEntitiesOfType(Type type)
    {
        List<Entity> results = new List<Entity>();
        foreach(Entity entity in Entities)
        {
            if(entity.Contains(type))
                results.Add(entity);
        }
        return results;
    }
}

```

Obviously this isn't the exact code (you'd actually need a template function to check for different component types, rather than using `typeof`) but the concept is there. Then you could take those results, reference the component you're looking for, and register it with your factory. This prevents any direct coupling between Components and their managers.
> 0 votes

---
Tags: entity-system, component-based
---


title: Starting to make 2D games in C++

text:
# Question
Title: Starting to make 2D games in C++
I'm fairly experienced with C and C#, but I've only ever created console/windows applications. I'm also experienced with AS3 and I've made some flash games.

I want to make proper 2D games in C++, but I have no idea where to begin with graphics. There are entire books devoted to game development in C++ that only work with console applications and I'm finding the lack of resources and tutorials for proper 2D games frustrating... I'm also not particularly interested in using existing engines because I want total control of what I create.

I've heard of the Allegro library; is it something that I should look into? How will I use DirectX?

Any resources or links to tutorials or information is greatly appreciated.

# Answer
> 6 votes
A very nice starting point for 2D development in C++ is SFML. Taken from the official website:

> SFML is a portable and easy to use multimedia API written in C++. You can see it as a modern, object-oriented alternative to SDL. SFML is composed of several packages to perfectly suit your needs. You can use SFML as a minimal windowing system to interface with OpenGL, or as a fully-featured multimedia library for building games or interactive programs.

I've been using SFML for a while, it's an object-oriented API which has a lot of examples on the site for you to learn from, as well as tutorials. If you are confused whether to use 1.6 or 2.0 I'd suggest going with 2.0 because eventually you'll still have to upgrade.

Even better, SFML is not C++ exclusive, it works with the following languages:

* C
* C++
* .net (C#, VB .net, C++/CLI)
* Python
* D
* Ruby

And the nice thing is, you can use OpenGL with it and the Qt framework as well. I think it's a nice starting point for 2D development, but if you want alternatives you can try out Allegro or SDL

# Answer
> 1 votes
On some level, you're going to have to manage gamestates, your video hardware, audio hardware, etc. While it can be a good learning experience to dabble with DirectX, DirectSound, and the like, if you immediately want to make a game, it's best to use some layer of abstraction.

SDL is cross-platform, open-source, works with C++ natively, and has great documentation and tutorials to get you started.

SDL Website

# Answer
> -1 votes
I highly recommend OpenGL for starting your game programming exercises. 2D game is basically flatted display in terms of 3D. For links and tutorials, I think you should be able to actually learn to display some primitive shapes such as a triangle first. Such tutorials on basic display is all over the web and youtube.

---
Tags: c++, graphics, graphics-programming
---


# Question
Title: No sense of direction of what to do next in C++, what to learn next?
I am studying game dev. I have learnt C++ on my own I would say my skills are about intermediate level but I most of my stuff is done from console games i.e anything text based.

What is the next step I should take? I have looked at some DirectX stuff it does not look to appealing is there any steps anyone could offer?

# Answer
> 1 votes
I'm not sure if you're question is GDSE appropriate, but this is all I can offer:

Grab a library/engine. Follow the instruction/tutorials. Start building. A lot of stuff is already done for you ( like sound/graphics/controls ) so you don't have to reinvent the wheel. Here is a list of engines ( check the licenses, some might not be free. I havn't checked them all ).

# Answer
> 1 votes
There are many components in game programming, e.g. rendering, audio, input, data structures, AI, networking etc. DirectX is a package that offers API for several of that, and as such makes it a relatively difficult package for learning.

For me, as a noob in this area, I learnt other programming lanaguages that offer out-of-the-box GUI rendering e.g. VB6, .NET, JAVA, ActionScript. This removes the need for handling the rendering myself.

Then I play some retro games like Pong, Pacman, Tetris, Space Invaders, Paddle Ball etc and try to implement the same thing with the programming langauges to hone me skills in game architecture.

As I try to make my games better, and from 2D to 3D, I eventually hit hard limitations and then I "upgrade" my technology by using more low level APIs. Doing this allowed myself to appreciate the need and reasoning behind each API's implementation.

When you are expert enough, you can forget all the low level stuff and use an engine like Unity3D.

---
Tags: c++
---


title: Collisions on complex map 2D

text:
# Question
Title: Collisions on complex map 2D
I'm currently thinking about collision and map system that I want to use in my next game and I'm kind of puzzled. Maps are going to be somewhat complex with lots of irregularities and thus tiling is out of question.

I thought about an editor where you'd draw rectangles on the map that would represent areas that are collidable with and then saving such "collision map" with only black/white gfx. Or maybe should I save exact rectangles data with their x/y/width/height into some text file and go from there?

What would you recommend? Thanks.

# Answer
> 1 votes
I also use complex maps with "lots of irregularities" in my game (pretty much like the game Worms). I have premade graphical elements which I put at arbitrary positions. These elements have minimal bounding rectangles (MBR's). When a character is inside the MBR of a map element, I do a per-pixel collision detection. It is important, that I'm taking into account only the intersection of the map element's MBR vs the character's MBR.

TL;DR: Minimal bounding rectangles, then a finer (e.g. per-pixel) collision detection when they intersect.

---
Tags: 2d, collision-detection
---


title: Crash when using Cocos2d

text:
# Question
Title: Crash when using Cocos2d
Sorry about the poor question title, it's just that this seems to big for a title. So here's the dirt:

I am making a game (obviously) and I want the enemies to shoot (not necessarily at the player). I want the shoot method to be in the Enemies file, so as not to clutter up my HelloWorldLayer.m file even more. Here's what I'm using right now:

HelloWorldLayer.m

```
-(void)addEnemy:(BigAndStrongEnemy *)enemy {
enemy = nil;
if((arc4random() % 4) == 3) {
    enemy = [BigAndStrongEnemy enemy];
} else {
    enemy = [SmallAndFastEnemy enemy];
}

if(buffDude.position.y > character.position.y || buffDude.position.y < (character.position.y + 10)) {

}

int rand = arc4random() % 320;

if((arc4random() % 2 == 1)) {
    [enemy setPosition:ccp(0,rand)];
}else{
    [enemy setPosition:ccp(480,rand)];
}
[self animateEnemy:enemy];
[self addChild:enemy];
}

-(void)animateEnemy:(BigAndStrongEnemy *)enemy2 {
    float randX = arc4random() % 480;
    float randY = arc4random() % 320;
    int rand = arc4random() % 320;

CGPoint moveToPoint = CGPointMake(randX, (randY - rand));

[enemies addObject:enemy2];

action = [CCSequence actions:
          [CCMoveBy actionWithDuration:1 position:ccpMult(ccpNormalize(ccpSub(moveToPoint, enemy2.position)), 75)],
          [CCMoveBy actionWithDuration:3 position:ccp(buffDude.position.x,buffDude.position.y)],
          nil];

CCCallFuncO *a = [CCCallFuncO actionWithTarget:self selector:(@selector(shoot:)) object:enemy2];
CCSequence *s = [CCSequence actions:action,a, nil];

CCRepeatForever *repeat = [CCRepeatForever actionWithAction:s];

[enemy2 runAction:repeat];
}

```

And here's the Shoot info from the Enemies class:

Enemies.m:

```
    -(void)shoot:(id)sender {
    self = (BigAndStrongEnemy *)sender;
    [self shoot];
}

-(void)spriteMoveFinished:(id)sender {
    CCSprite *b = (CCSprite *)sender;
    [self removeChild:b cleanup:YES];
}

-(void)shoot {
    self = [CCSprite spriteWithFile:@"bigAndStrongEnemy.gif"];
    CCSprite *b = [CCSprite spriteWithFile:@"bullet.gif"];
    b.position = ccp(self.position.x,self.position.y);
    b.tag = 2;
    [self addChild:b];
    [bullets addObject:b];

CGSize winSize = [[CCDirector sharedDirector] winSize];

CGPoint point = CGPointMake((winSize.width - (winSize.width - self.position.x)),0);

[b runAction:[CCSequence actions:
              [CCMoveBy actionWithDuration:0.5 position:point],
              [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)],
              nil]];
}

```

Every time the 3 seconds goes by, the app crashes, and goes to the breakpoint in the CCCallFuncO file. I haven't touched it, is the thing. I am completely confused. Any help is greatly appreciated.

# Answer
> 3 votes
Use the XCode debugger and do a stack track to see the last line of your code where the crash happened. That should give you a clue on what is causing the error

# Answer
> 0 votes
I had a similar problem with "CCCallFunc". It turned out I needed to be using "CCCallFuncN" instead, confusing because they are so similarly named. I would try replacing the line of code it's tripping up on with

```
CCCallFuncN *a = [CCCallFuncN actionWithTarget:self selector:(@selector(shoot:)) object:enemy2];

```

# Answer
> 0 votes
The enemy class has

```
[self addChild]

```

and

```
[self removeChild]

```

that I think make more sense in the Layer class, unless the Enemy class is based on Layer.

Did you try moving the enemy code to the HelloWorldLayer? I know this is not where you want it to be, but it may be simpler to get it to work, then change it from there.

# Answer
> -3 votes
Bingo. The problem exists in `CCCallFunc`, so try `CCCallFuncN` instead. Hope everything goes well.

---
Tags: iphone, cocos2d-iphone, cocos2d
---


# Question
Title: Is there a collection of images (GUI - interface) program or web page available for programmers / developers games?
I would like to add a GUI in my basic XNA games. Before starting work on "Photoshop" or "Illustrator". I wanted to ask you the following question: Do you know of a website or other resource program offering a graphics collection ? Oriented (GUI - interface) free preference available to developers ?

# Answer
> 8 votes
OpenGameArt has a few. Just search for tags like 'UI', 'Menu' or something like that. Roencia has some as well. I believe the same will be true for all sites that offer some kind of graphics for developers to use.

---
Tags: xna, graphics, interface
---


# Question
Title: Can I legally make a free clone of a game and use the same name?
I gather from Is it legally possible to make a clone of the game? and How closely can a game legally resemble another? that I should not try to profit from a clone if it is using the same assets, and, I presume, the same name. My question is whether it's legal to make a game like "Set" or "Catch Phrase", using the same name, and release it for free. What would I be risking if I did so -- just a take down notice, or could there be financial risk too?

**Edit:** I guess my real question is whether the legal freedom is greater for a free game than one that is trying to make a profit. I just want a version of the game I can play remotely.

**Edit 2:** I don't understand why this is being considered off-topic. I read the FAQ and it says it'S OK to ask questions about project management, which includes Publishing. And naming a game is a key aspect to publishing. That's what my question is about - choosing a legal name for my game with the consideration that I might post/publish it.

# Answer
There's basically three things you might be breaking:

* Copyright
* Trademarks
* Patents

If you do a straight-on clone of a game, using the same name even, you're possibly breaking all of the above. This is not recommended.

If for some reason you feel you just have to do so, contact the rights owner and discuss terms of licensing. Depending on the case, you may even get the rights for free, but I wouldn't bet on it. (contact info for 'the set game').

Much better idea would be just to write your own game. Everybody has more game ideas than time to implement them, why bother rewriting other people's games?

As for the risk - as I said in the comments, this is basically just asking for trouble and pondering what the severity of the trouble will be. It's likely you'll just be ignored. Or on the other end it's possible this is the end of your life as you know it, but that's less likely.

If you want legal counsel, get a lawyer, don't ask on random web sites.
> 7 votes

# Answer
You **can not** use the same name, because it is copyrighted. The name of a company or a product is protected. The Set Game, for example, when searched on Google, it is presented with *"®"* (registered trademark), that means the name is a trademark, protected by the law. So the name can not be copied. However, this trademark has a duration and expires after many years and then, the product becomes a kind of *"common use"* (i don't know how it is called out of Brazil). **These laws depends the country where you are**.

Edit: Sorry, the symbol, is ®, not ™. Thanks, Sam Hocevar.
> -3 votes

---
Tags: legal, copyright
---