# Question
Title: How can I get a cone shape of arbitrary size in an hex board?
I'm implementing engine tools for my hex board game and this one is becoming messy. I want to get a list of all the positions that a cone of size N would have, given "caster" origin X,Y and origin in X0, Y0 taking direction into account. So far I have been able to get a size one cone using a "simple pattern" approach, but it doesn't translate well for N-sized cones.

This is the original cone

and the code

```
public PositionArray getArcAdjacents(int originx, int originy, int targetx, int targety,
        int range) {
    final FloatPair direction = this.getDirectionVector(originx, originy, targetx, targety);
    final PositionArray highlights = new PositionArray(gameMap);
    highlights.add(new Pair(targetx, targety));
    int offset = 0;
    if ((targetx % 2) == 0) {
        offset = 1;
    }
    if (direction.x > 0) {
        if (direction.y >= 0) {
            highlights.add(new Pair(targetx - 1, (targety + 1) - offset));
            highlights.add(new Pair(targetx, targety - 1));
        } else {
            highlights.add(new Pair(targetx, targety + 1));
            highlights.add(new Pair(targetx - 1, targety - offset));
        }
    } else if (direction.x < 0) {
        if (direction.y >= 0) {
            highlights.add(new Pair(targetx + 1, (targety + 1) - offset));
            highlights.add(new Pair(targetx, targety - 1));
        } else {
            highlights.add(new Pair(targetx + 1, targety - offset));
            highlights.add(new Pair(targetx, targety + 1));
        }
    } else {
        if (direction.y > 0) {
            highlights.add(new Pair(targetx + 1, targety - offset));
            highlights.add(new Pair(targetx - 1, targety - offset));
        } else if (direction.y < 0) {
            highlights.add(new Pair(targetx + 1, (targety + 1) - offset));
            highlights.add(new Pair(targetx - 1, (targety + 1) - offset));
        }
    }
    return highlights;
}

```

# Answer
> 2 votes
I could fix it with a bit of algorithmics:

```
public PositionArray getArcRange(int originx, int originy, int targetx, int targety, int range) {
    if (range < 0) {
        range = 0;
    }
    final PositionArray open = new PositionArray(gameMap);
    final PositionArray closed = new PositionArray(gameMap);
    final FloatPair direction = this.getDirectionVector(targetx, targety, originx, originy);
    closed.add(new Pair(targetx, targety));
    while (closed.size > 0) {
        final Pair position = closed.removeIndex(0);
        if (!open.contains(position, false)
                && (this.getDistance(targetx, targety, position.x, position.y) <= range)) {
            closed.addAll(this.getArcAdjacents(position, direction));
            open.add(position);
        }
    }
    open.removeIndex(0);
    return open;
}

private PositionArray getArcAdjacents(Pair target, FloatPair direction) {
    final PositionArray highlights = new PositionArray(gameMap);
    int offset = 0;
    if ((target.x % 2) == 0) {
        offset = 1;
    }
    if (direction.x > 0) {
        if (direction.y >= 0) {
            highlights.add(new Pair(target.x - 1, (target.y + 1) - offset));
            highlights.add(new Pair(target.x, target.y - 1));
        } else {
            highlights.add(new Pair(target.x, target.y + 1));
            highlights.add(new Pair(target.x - 1, target.y - offset));
        }
    } else if (direction.x < 0) {
        if (direction.y >= 0) {
            highlights.add(new Pair(target.x + 1, (target.y + 1) - offset));
            highlights.add(new Pair(target.x, target.y - 1));
        } else {
            highlights.add(new Pair(target.x + 1, target.y - offset));
            highlights.add(new Pair(target.x, target.y + 1));
        }
    } else {
        if (direction.y > 0) {
            highlights.add(new Pair(target.x + 1, target.y - offset));
            highlights.add(new Pair(target.x - 1, target.y - offset));
        } else if (direction.y < 0) {
            highlights.add(new Pair(target.x + 1, (target.y + 1) - offset));
            highlights.add(new Pair(target.x - 1, (target.y + 1) - offset));
        }
    }
    return highlights;
}

```

Result:

**Beware of the trap, my PositionArray doesn't allow duplicates or positions outside the board.**

---
Tags: algorithm, hexagonal-grid
---


# Question
Title: How to properly implement message handling in a component based entity system?
I am implementing an entity system variant that has:

* An **Entity class** that is little more than an ID that binds components together
* A bunch of **component classes** that have no "component logic", only data
* A bunch of **system classes** (a.k.a "subsystems", "managers"). These do all the entity logic processing. In most basic cases, the systems just iterate trough a list of entities they are interested in and do an action on each of them
* A **MessageChannel class object** that is shared by all game systems. Each system can subscribe to specific type of messages to listen to and can also use the channel to broadcast messages to other systems

The initial variant of system message handling was something like this:

1. Run an update on each game system sequentially
2. If a system does something to a component and that action might be of interest to other systems, the system sends an appropriate message (for example, a system calls

```
messageChannel.Broadcast(new EntityMovedMessage(entity, oldPosition, newPosition))

```

whenever an entity is moved)
3. Each system that subscribed to the specific message gets it's message handling method called
4. If a system is handling an event, and the event processing logic requires another message to be broadcast, the message gets broadcast right away and another chain of message processing methods gets called

This variant was OK until I started optimizing the collision detection system (it was getting really slow as number of entities increased). At first it would just iterate each entity pair using a simple brute force algorithm. Then I added a "spatial index" that has a grid of cells that stores entities that are inside the area of a specific cell, thus allowing to do checks only on entities in neighboring cells.

Every time an entity moves, the collision system checks whether the entity is colliding with something in the new position. If it is, a collision gets detected. And if both colliding entities are "physical objects" (they both have RigidBody component and are meant to push each other away so as not to occupy the same space), a dedicated rigid body separation system asks the movement system to move the entities to some specific positions that would separate them. This in turn causes the movement system to send messages notifying about changed entity positions. The collision detection system is meant to react because it needs to update it's spatial index.

In some cases it causes a problem because the contents of the cell (a generic List of Entity objects in C#) get modified while they are being iterated over, thus causing an exception to be thrown by the iterator.

So... **how can I prevent the collision system from being interrupted while it checks for collisions?**

Of course I could add some "clever"/"tricky" logic that ensures the cell contents get iterated over correctly, but I think the problem lies not in the collision system itself (I also had similar problems in other systems), but the way messages get handled as they travel from system to system. What I need is some way to ensure that a specific event handling method gets do it's job without any interruptions.

What I have tried:

* **Incoming message queues**. Every time some system broadcasts a message, the message gets added to message queues of systems that are interested in it. These messages get processed when a system update is called each frame. **The problem**: if a system A adds a message to system's B queue, it works well if system B is meant to be updated later than system A (in the same game frame); otherwise it causes the message to processed the next game frame (not desirable for some systems)
* **Outgoing message queues**. While a system is handling an event, any messages it broadcasts are added to outgoing message queue. The messages don't need to wait for a system update to be processed: they get handled "right away" after the initial message handler has finished it's work. If handling of the messages causes other messages to be broadcast, they too are added to an outgoing queue, so all messages get handled the same frame. **The problem**: if entity lifetime system (I implemented entity lifetime management with a system) creates an entity, it notifies some systems A and B about it. While system A processes the message, it causes a chain of messages that eventually cause the created entity to be destroyed (for example, a bullet entity got created right where it collides with some obstacle, which causes the bullet to self destruct). While the message chain is being resolved, the system B does not get the entity creation message. So, if system B is also interested in entity destruction message, it gets it, and only after the "chain" is finished resolving, does it get the initial entity creation message. This causes the destruction message to be ignored, the creation message to be "accepted", and the whole system B now works as if the entity was never even destroyed (accessing a deleted entity also causes an exception).

**EDIT - ANSWERS TO QUESTIONS, COMMENTS:**

* **Who modifies the contents of the cell while the collision system iterates over them?**

While the collision system is doing collision checks on some entity and it's neighbors, a collision might get detected and the entity system will send a message that will be reacted upon right away by other systems. The reaction to the message might cause other messages to be created and also handled right away. So some other system might create a message that the collision system would then need to process right away (for example, an entity moved so the collision system needs to update it's spatial index), even though the earlier collision checks were not finished yet.

* **Can't you work with a global outgoing message queue?**

I tried a single global queue recently. It causes new problems. **Problem:** I move a tank entity into a wall entity (the tank is controlled with the keyboard). Then I decide to change direction of the tank. To separate the tank and wall each frame, the CollidingRigidBodySeparationSystem moves the tank away from the wall by the smallest amount possible. The separation direction should the opposite one of the movement direction of the tank (when the game drawing starts, the tank should look as if it never moved into the wall). But the direction becomes opposite of the NEW direction, thus moving the tank to a different side of the wall than it initially was. **Why the problem occurs:** This is how messages are handled now (simplified code):

```
public void Update(int deltaTime)
{
    m_messageQueue.Enqueue(new TimePassedMessage(deltaTime));
    while (m_messageQueue.Count > 0)
    {
        Message message = m_messageQueue.Dequeue();
        this.Broadcast(message);
    }
}

private void Broadcast(Message message)
{
    if (m_messageListenersByMessageType.ContainsKey(message.GetType()))
    {
        // NOTE: all IMessageListener objects here are systems.
        List<IMessageListener> messageListeners = m_messageListenersByMessageType[message.GetType()];
        foreach (IMessageListener listener in messageListeners)
        {
            listener.ReceiveMessage(message);
        }
    }
}

```

The code flows like this (let's assume it's not the first game frame):

1. *Systems* start processing TimePassedMessage
2. *InputHandingSystem* converts key presses to entity action (in this case, a left arrow turns into MoveWest action). Entity action is stored in ActionExecutor component
3. *ActionExecutionSystem*, in reaction to entity action, adds a MovementDirectionChangeRequestedMessage to the end of message queue
4. *MovementSystem* moves entity position based on Velocity component data and adds PositionChangedMessage message to end of queue. The movement is done using movement direction/velocity of previous frame (let's say north)
5. *Systems* stop processing TimePassedMessage
6. *Systems* start processing MovementDirectionChangeRequestedMessage
7. *MovementSystem* changes entity velocity/movement direction as requested
8. *Systems* stop processing MovementDirectionChangeRequestedMessage
9. *Systems* start processing PositionChangedMessage
10. *CollisionDetectionSystem* detects that because an entity moved, it ran into another entity (tank went inside a wall). It adds a CollisionOccuredMessage to the queue
11. *Systems* stop processing PositionChangedMessage
12. *Systems* start processing CollisionOccuredMessage
13. *CollidingRigidBodySeparationSystem* reacts to collision by separating tank and wall. Since the wall is static, only the tank is moved. The tanks' movement direction is used as an indicator of where the tank came from. It is offset in an opposite direction

**BUG:** When the tank moved this frame, it moved using movement direction from previous frame, but when it was being separated, the movement direction from THIS frame was used, even though it was already different. That's not how it should work!

To prevent this bug, the old movement direction needs to be saved somewhere. I could add it to some component just to fix this specific bug, but doesn't this case indicate some fundamentally wrong way of handling messages? Why should the separation system care which movement direction it uses? How can I solve this problem elegantly?

* **You may want to read gamadu.com/artemis to see what they did with Aspects, which side steps some of the problems you're seeing.**

Actually, I've been familiar with Artemis for quite a while now. Investigated it's source code, read the forums, etc. But I've seen "Aspects" being mentioned only in a few places and, as far as I understand it, they basically mean "Systems". But I can't see how Artemis side steps some of my problems. It doesn't even use messages.

* **See also: "Entity communication: Message queue vs Publish/Subscribe vs Signal/Slots"**

I've already read all gamedev.stackexchange questions regarding entity systems. This one does not seem to discuss the problems I am facing. Am I missing something?

* **Handle the two cases differently, updating the grid does not need to rely on the movement messages as it's part of the collision system**

I'm not sure what you mean. Older implementations of CollisionDetectionSystem would just check for collisions on an update (when a TimePassedMessage got handled), but I had to minimize checks as much as I could due to performance. So I switched to collision checking when an entity moves (most entities in my game are static).

# Answer
> 13 votes
You've probably heard of the God/Blob object anti-pattern. Well your problem is a God/Blob loop. Tinkering with your message passing system will at best provide a Band-Aid solution and at worst be a complete waste of time. In fact, your problem has nothing specifically to do with game development at all. I've caught myself trying to modify a collection while iterating over it several times, and the solution is always the same: subdivide, subdivide, subdivide.

As I understand the wording of your question, your method of updating your collision system currently looks broadly like the following.

```
for each possible collision
    check for collision
    handle collision
    modify collision world to reflect change // exception happens here

```

Written plainly like this, you can see that your loop has three responsibilities, when it should only have one. To solve your problem, split your current loop into three separate loops representing three different algorithmic *passes*.

```
for each possible collision
    check for collision, record it if a collision occurs

for each found collision
    handle collision, record the collision response (delete object, ignore, etc.)

for each collision response
    modify collision world according to response

```

By subdividing your original loop into three subloops, you no longer ever attempt to modify the collection over which you are currently iterating. Note also that you are not doing more work than in your original loop, and in fact you might gain some cache wins by doing the same operations many times sequentially.

There is also a further benefit, which is that you can now introduce **parallelism** into your code. Your combined-loop approach is inherently serial (which is fundamentally what the concurrent modification exception is telling you!), because each loop iteration potentially both reads and writes to your collision world. The three subloops I present above, however, all either read or write, but not both. At the very least the first pass, checking all possible collisions, has become embarrassingly parallel, and depending on how you write your code the second and third passes might be too.

# Answer
> 12 votes
**How to properly implement message handling in a component based entity system?**

I would say that you want two types of messages: Synchronous and Asynchonous. Synchronous messages are handled immediately while asynchronous are handled not in the same stack frame (but may be handled in the same game frame). The decision which is which is usually made on a "per message class" base, e.g. "all *EnemyDied* messages are asynchronous".

Some events are just handled much *much* easier with one of these ways. For example, in my experience an ObjectGetsDeletedNow - event is much less sexy and callbacks are much harder to implement than ObjectWillBeDeletedAtEndOfFrame. Then again, any "veto"-like message handler (code that can cancel or modify certain actions while they are executed, like an Shield-effect modifies the *DamageEvent*) are not going to be easy in asynchronous environments but are a piece of cake in synchronous calls.

Asyncronous might be more efficient in some cases (e.g. you can skip over some event handlers when the object gets deleted later anyway). Sometimes synchronous is more efficient, especially when calculating the *parameter* for an event is costly and you rather like to pass callback functions to retrieve certain parameters instead of already calculated values (in case nobody is interested in this particular parameter anyway).

You already mentioned another general problem with synchronous-only message systems: To my experience with syncronous message systems, one of the most cases of errors and grief in general are change of lists while iterating over these lists.

Think about it: It is in the nature of *synchronous* (immediately handle all after-effects of some action) and *message system* (decoupling receiver from sender so the sender does not know who is reacting to actions) that you will not be able to easily spot such loops. What I am saying is: Be prepared to handle this kind of self-modifying iteration a lot. Its kindof "by design". ;-)

**how can I prevent the collision system from being interrupted while it checks for collisions?**

For your particular problem with the collision detection, it might be good enough to make collision events asynchronous, so they get queued up until collision manager is finished and executed as one batch afterwards (or at some later point in the frame). This is your solution "incoming queue".

**The problem: if a system A adds a message to system's B queue, it works well if system B is meant to be updated later than system A (in the same game frame); otherwise it causes the message to processed the next game frame (not desirable for some systems)**

Easy:

while (!queue.empty()) { queue.pop().handle(); }

Just run the queue over and over until no message remains. (If you scream "endless loop" now, remember that you most probably would have this problem as "message spamming" if it would be delayed to the next frame. You can assert() for a sane number of iterations to detect endless loops, if you feel like it ;))

# Answer
> 5 votes
If you're actually trying to get make use of the data-oriented-design nature of ECS then you might want to think about the most DOD way of doing this.

Take a look at the BitSquid blog, specifically the part about events. A system that meshes well with ECS is presented. Buffer all events into a nice clean per-message-type queue, the same way systems in an ECS are per-component. Systems updated afterward can efficiently iterate over the queue for a particular message type to process them. Or just ignore them. Whichever.

For example, the CollisionSystem would generate a buffer full of collision events. Any other system run after collision can then iterate through the list and process those as needed.

It keeps the data-oriented parallel nature of the ECS design without all the complexity of message registration or the like. Only systems that actually care about a particular type of event iterate over the queue for that type, and doing a straight single-pass iteration over the message queue is about as efficient as you can get.

If you keep components consistently ordered in each system (e.g. order all components by entity id or something like that) then you even get the nice benefit that messages will be generated in the most efficient order for iterating over them and looking up corresponding components in the processing system. That is, if you have entities 1, 2, & 3 then messages are generated in that order and component lookups performed while processing the message will be in strictly increasing address order (which is the fastest).

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


# Question
Title: How to get the center of a rotated rectangle regardless of point of rotation
I need help working out the centre coordinate of a rotated rectangle *regardless of the point of rotation* (i.e. the rectangle doesn't rotate around its center). **I do not know the coordinates of the corners, so it's not a simple case of dividing those.**

It's easier to show than tell, so here's example 1:

http://gametest.mobi/rotate/index.php?f=point1.js&d=tests

Click to start/stop the rotation.

In this example I've got my sprite with the rotation point set to the bottom-right corner of it. If you click you'll see it rotate around that. I need to find a way to work out the coordinates of the center of the rectangle (represented by the middle red cross-hairs.)

Here is another example, this one is set to rotate at 0.3 x 0.8 into the rectangle:

http://gametest.mobi/rotate/index.php?f=point3.js&d=tests

You can see I added the circle into each demo, this is positioned on the sprites x/y coordinate and the radius was calculated from the distance of the center of the rectangle to the rotation origin.

I can visually see the correlation between the point of rotation and the circle, and I can see it tracks the centre of the rectangle beautifully on the circles perimeter! But I'm falling at the last hurdle in trying to calculate the actual value, so desperately need a fresh set of eyes on it please.

# Answer
Ok, that thing where you post a question up here and then solve it 10 mins later? Sorry, that was me just now. To help anyone else trying to achieve the same thing here is how I did it:

Get the angle between the point of the rotation and the center of the rectangle (i.e. the value of the width and height / 2):

```
var originAngle = Math.atan2(centerY - originY, centerX - originX);

```

Then add this as a constant to the rotation of the sprite (where sprite.rotation is in radians):

```
var px = sprite.x + distance * Math.cos(sprite.rotation + originAngle);
var py = sprite.y + distance * Math.sin(sprite.rotation + originAngle);

```

The `distance` value is the distance from the point of rotation to the center (as used to draw the circle in the demo in my original post).
> 1 votes

# Answer
If you know the points of all the corners, it's simply a matter of taking the average of each point component.

```
center_x = (p1_x + p2_x + p3_x + p4_x) / 4
center_y = (p1_y + p2_y + p3_y + p4_y) / 4

```

That should give you the center no matter how it's rotated.
> 3 votes

# Answer
Let `(X0, Y0)` be the coordinates of the rectangle’s center at rotation zero, while `(X1, Y1)` is the coordinates of the rectangle’s center at rotation of angle `theta` (both coordinate pairs relative to pivot point).

```
X1 = (X0 * cos(theta)) - (Y0 * sin(theta))
Y1 = (X0 * sin(theta)) + (Y0 * cos(theta))

```

Here is a short video explaining why these work.
> 3 votes

---
Tags: javascript
---


# Question
Title: What's the process for making a PS4 game?
Now that Sony has said that devs can self publish for PS4, I'm betting that a lot more people will be interested in producing games for that platform.

What is the process for getting the SDK, documentation, and testing environment for a PS4?

# Answer
Thus far, there is no indication that Sony's self-publishing option for the PlayStation 4 is actually an *open* publishing environment (like the PC). You still need to become a registered developer and that still involves being vetted and approved by Sony, licensing hardware, et cetera.

According to this press release:

> For more information about the SCEA Publisher and Developer Relations Group, please visit: http://us.playstation.com/develop or email selfpublish@playstation.sony.com.

You will note that the linked site details a four-step process to register, but notes that, before applying, the following requirements should be met:

* Form a corporate entity and have a tax ID number.
* Have a static IP for your company that Sony can whitelist for developer network access.
* Be physically located in US, Mexico, Central America, South America, or Canada.

The actual online application form asks for various other things an established company should have, as well as information about your development history and published titles, six-month product development plan, et cetera.
> 16 votes

---
Tags: playstation4
---


title: Font disappear after reloading

text:
# Question
Title: Font disappear after reloading
As this post title suggest, font of the scene become disappear when same scene call more than two time.

Following code I used for creating font.

```
 mNumberFontTexture = new BitmapTextureAtlas(
                            alienAttack.getTextureManager(), 256, 256);
 numberFont = new Font(alienAttack.getFontManager(), mNumberFontTexture,
                            Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 52, true,
                            Color.YELLOW);

```

Based on requirement I load a font texture as per the following way.

```
    public void loadLevelSelectGraphics() {
            levelSelectBitmapTextureAtlas.load();
            mNumberFontTexture.load();
            numberFont.load();
    }

    public void unloadLevelSelectGraphics() {
            levelSelectBitmapTextureAtlas.unload();
            numberFont.unload();
    }

```

I am using scene base approach for developing game. Please suggest me in which thing I am doing mistake. Thanks for your effort.

**EDIT**

Screenshot represent the problem which was occur after multiple load and unload font method.

# Answer
This happened to me in AndEngine when I loaded the texture but forgot to unload it. If I load it too many times, then the memory is full, new texture doesn't get loaded and this happens - the texture regions point to some garbage.

If it happens only after some time, it might be the case. To debug it, write a message to log on each load and each unload and make sure you load and unload the same number of times.

Also it can be another texture that fills the memory. In your example, you are loading `levelSelectBitmapTextureAtlas.load();` but you are not unloading it. It might have filled your memory and there is no more space for the font.
> 2 votes

---
Tags: andengine
---


# Question
Title: adding vertical scrolling to 2D platformer in libgdx
I am trying to make a two sided platform game in Libgdx. Where I am scrolling through the TiledMap. I was easily implementing the horizontal scrolling using..

camera.position.x = player.getPositionX();

and it works fine. But when it comes to Vertical scroll .. I am observing very bad effects doing the same thing on y-axis. I tried it many ways. But No code could give could a real look and feel. Later I happen to find this video

http://blog.mimeoverse.com/post/581467761/the-ideal-platformer-camera-should-minimize

it says " The ideal platformer camera should:

minimize vertical motion lead in the direction the player is facing remain motionless during horizontal micro-adjustments The secret to achieving all three is (what I call) the trap. The trap is an invisible rectangle (made visible for this demo), roughly twice as wide and tall as the player sprite, with the same starting coordinates. Rather than follow the player sprite directly the camera follows the trap. When the player moves within the trap, the camera does not move. The trap only moves when the player pushes against one of its edges. " it demonstrates a good idea but Still there still seems something bad .. I am writing some wrong code

```
Rectangle trap_old,trap_new;

.....

trap_old = new Rectangle(player.getPositionX()-2*player.getWidth(),
                        player.getPositionY()+5*player.getHeight(),
                        5*player.getWidth(),
                        6*player.getHeight());

//.. inside render

trap_new = getNewTrapArea(player.getPositionX(),
                        player.getPositionY(),
                        player.getWidth(),
                        player.getHeight());

camera.position.x = trap_new.x;
camera.position.y = trap_new.y;
camera.update();

private Rectangle getNewTrapArea(float positionX, float positionY, float width, float height) {
    Rectangle temp = new Rectangle(positionX, positionY, width, height);
    if(temp.overlaps(trap_old))
        trap_new = trap_old;
    else
        trap_old = trap_new = new Rectangle(positionX-2*width, positionY+5*height, 5*width, 6*height);
    return trap_new;
}

```

# Answer
> 2 votes
You need to rewrite the getNewTrapArea function. Instead of checking whether the two rectangles overlap, you should check whether the player is contained in the trap. Also, it's unnecessary to have two trap rectangles as fields of the class. The code below assumes you only have one, called `trap`.

Note: it wastes memory to recreate the rectangles every step. You should create the player and trap rectangles at the start of the game, and then just change the x and y values when the rectangles need to be moved.

Here is the code:

```
//in class
Rectangle trap, playerBounds;
//at start
playerBounds = new Rectangle(player.getPositionX(), player.getPositionY(), player.getWidth(), player.getHeight());
trap = new Rectangle(player.getPositionX()-2*player.getWidth(),
                    player.getPositionY()+5*player.getHeight(),
                    5*player.getWidth(),
                    6*player.getHeight());
//.. inside render
playerBounds.x = player.getPositionX();
playerBounds.y = player.getPositionY();
setNewTrapArea();
camera.position.x = trap.x;
camera.position.y = trap.y;
camera.update();

```

and the setNewTrapArea function:

```
private void setNewTrapArea() {
    if(trap.contains(playerBounds))
        return;
    if (playerBounds.x < trap.x)
        trap.x = playerBounds.x;
    else if (playerBounds.x + playerBounds.width > trap.x + trap.width)
        trap.x = playerBounds.x + playerBounds.width - trap.width;
    if (playerBounds.y < trap.y)
        trap.y = playerBounds.y;
    else if (playerBounds.y + playerBounds.height > trap.y + trap.height)
        trap.y = playerBounds.y + playerBounds.height - trap.height;
}

```

It might make more sense to have `bounds` be a field of the player class, but I'll leave that up to you.

---
Tags: android, libgdx, platformer, scrolling
---


title: How to implement tile enemies behavior?

text:
# Question
Title: How to implement tile enemies behavior?
I'm having a difficult time to understand , how to implement the behavior of an enemy in a tile based game,

* movement
* attack
* behavior per enemy level ( higher level enemies should be hard to kill)
* defend
* other behavior

since the game is a tile game written in javascript, the behavior of the enemies could be implement as functions like

* `Chaser` \- hunts its opponents
* `Brave` \- does not start running if with low HP
* `Sensitive` \- when damaged might take additional damage

using the standard entity class , based on the configuration defined for the enemy, could it be `extend` as the behavior?

Or write like standard enemy behavior and additionally write separate scripts per enemy on how they should behave against the opponent, surroundings, etc..

# Answer
> 3 votes
Here are my thoughts:

* Movement: you can do with path finding,if you find it hard to implement as an algorithm start with simple logic (`while move if hit wall do`...), and after that try to create a simple algorithm to make it more efficient. The A\* algorithm seems to be the best for path finding. If that's too hard use "zombie movements" (`if target.x>me.x me.x-=speed`...).
* Attack: you can use collision detection for close range (and timer so it wont attack every tick of game loop), check distance of entities, if close shot. Or you can use raycasting for FOV.
* Behavior per enemy level: check Pacman every ghost had a different behavior pattern. You can also use a finite state machine (i used it for patrolling enemy).
* Defend: like attack but you should randomize so it wont block every time, or create a weak spot an enemy can't defend from (in Golden Axe it was jump attack and from behind, and also when the enemy slept, ate, etc.).

As this is javascript you should take a look at some AS3 AI (and get a good SWF decompiler for educational purpose ).

Also check out waypoints, circular movement (mostly like circle point by point drawing functions with trigonometry), and move by path (irregular paths I found it simple to learn its easy math even for me).

Check Google for tutorials and info, research is the programmer's best friend. Here are some of my findings:

Edit: about tiles you can implement non-tile behavior if you know how to convert tile coordinates to normal x,y(,z?) coordinates, e.g.:

```
player.x = tile_cor_x * tile_size_width / 2
// same for y (and z?)

```

Or maybe a loop that checks who's on 20 tiles in front of a character, if there's an enemy shooting here, take cover and switch to a "coward" behavior.

---
Tags: javascript, ai, tiles, behavior
---


title: About making damage between units

text:
# Question
Title: About making damage between units
I am making my own Tower Defence game engine. I havent built one before and I don't know lot of stuff how games work.

I will take Starcraft as an example. You have a marine shooting a zergling from a certain distance. But you dont see the bullets traveling trough the air because the marine and the zergling are either too small. So if there are no bullets at all how does the game engine does damage to the zergling under the hood (Use hitTestObject() in flash with what :) )?

I have and idea to add in my game engine and it work this way as explained in the example but I dont know how to implement it trough code.

thanks

# Answer
> 10 votes
When you don't have actual projectile physics, an entity would just damage another entity directly. The update algorithm which is called every game tick would, in pseudocode, look like this:

```
for each object in the game
    if it has a target
        if the target is in range and weapon is ready to fire
            reduce the hit points of the target
        else
             stand around waiting

for each object in the game
    when its HP are <= 0
        remove the object

```

# Answer
> 3 votes
To understand this, you need to understand the basic architecture of any computer program. Typically you want split your application into tiers. One of the tiers should be the presentation tier and then you can have one or more tiers that take care of the rest, again usualy a logic tier and a data tier.

Now everything that happens in the game is happening in the logic tier. Your logic takes a marine and calls `marine.shoot(zergling)` that can look like this:

```
procedure shoot(target)
begin
 shootInDirection(target)
 showGunEffect()
 if target.hit() then
   calculateDamage(target)
   showDamage(target)
 else
   showMiss()
end

```

Methods like showGunEffect(), showDamage() and showMiss() are calls to the presentation tier to actually show the graphics.

Now let's make the program more complex:

```
procedure shoot(target)
begin
 bullet = shootInDirection(target)
 showNewObject(bullet)
 move(bullet, target)
 registerEventListener(bullet)
 showGunEffect()
end

procedure onBulletEvent(event)
begin
  if (event == hit)
    calculateDamage(target)
    showDamage(target)
  else if (event == miss)
    showMiss()
end

```

Now for the first program you simply need to show the gun effects, hits and misses. For the second one you actually need some kind of collision engine that will take care of the event like `bullet` colliding with `target`. The first one is of course very simple and as you said - the entities are so small, that it doesn't make sense to actually show bullets for each shot, not even talking about calculating the trajectories, hits etc.

But for both programs, everything that happens is just a calculation. And only the calls to presentation layer will make something visible. In the first case, the bullets probably fly instantly. So you don't have to show anything, or you can simply draw a line from marine to zergling to show the bullet trajectory.

In the second case, some game loop will be updating the bullets position and calling the rendering to show the bullet.

---
Tags: tower-defense, shooter
---


# Question
Title: What happened to sprite::setSize in SFML2?
I'm porting one of my old projects to sfml 2.0, and I had a background that I scaled using

`sprite.setSize(windowWidth, windowHeight)`

Now, it seems like `setSize` has ben removed in 2.0, and I'm wondering what the intended replacement is.

I know there is a `setScale` function, and that I could do something like:

```
auto size = sprite.getTexture()->getSize();
sprite.setScale(float(windowWidth)/size.x, float(windowHeight)/size.y);

```

but I think this is really ugly and clunky, is there another way to do it?

# Answer
> 8 votes
No, `setSize()` essentially has been replaced with `setScale()`, which will do the same things for you. The only difference here is, rather than telling the specific size to use, it will scale based on some factor (which is usually preferred, especially in pixel art 2D games).

The code example you posted would be perfectly fine to use here.

As an alternative, you could as well update your `sf::View` so the rendered view matches the texture's dimensions.

Or - probably the most elegant way to do it - you could just define a `sf::VertexArray` which will render a quad filling your window using the correct texture coordinates.

---
Tags: sfml
---


# Question
Title: Getting half plane direction relative from cam position
Im implementing certain Camera movements in my turn based games. I'm able to place and rotate the camera between two units that attack each other. However it will always move to the same "side". Which isn't necessarily wrong, the rotation of the camera just seems to be sharp when it's on the other side of the half plane ( as of right now it always goes on one half plane). I would like the camera to move to one side relative to the cameras position.

Essentially I just have to flip the Normal which gives me the direction where I have to place my camera:
A and B are units.
C is the current camera position
T is the target position.
Essential code

```
center =  Vector3.Lerp(attacker.transform.position, target.transform.position, 0.5f);
Vector3 diff = attacker.transform.position - target.transform.position;
Vector3 normal = Vector3.Normalize(diff);
normal = Vector3.Cross(Vector3.up,normal);

//CHECK HALF PLANE HERE
normal *= -1;

//Center is the target position.
center -=  normal * (diff.magnitude + 1.0f);

```

# Answer
> 2 votes
If I have understood your question correctly, as units A and B start attacking each other, you want the camera to move to a target position with a certain elevation and at equal and set distances from both units, thus defining two possible targets, both at opposite sides of the plane defined by A, B and the up vector. You want to determine which side of that plane the camera is on, so you can select the nearest target.

As you have calculated the normal of this plane, the problem has already been solved for the most part. The dot product of the normal vector and the vector from A (or B) to the camera will be positive on the side the normal is pointing towards and negative on the other. If, by definition, the normal is always perpendicular to the z-axis, you can omit that component and simply calculate the two-dimensional dot product, e.g.:

```
//Center is the target position.
if ( ((camera.x - attacker.x) * normal.x) + (camera.y - attacker.y) * normal.y) < 0 ) normal *= -1;
center -=  normal * (diff.magnitude + 1.0f);

```

Personally, I would prefer to keep variables like 'normal' and 'center' intact for later use, but I hope this example code gets the point across.

---
Tags: unity, mathematics, linear-algebra
---


title: Java Anti-Cheat Framework?

text:
# Question
Title: Java Anti-Cheat Framework?
Are there any anti-cheating frameworks for Java games in order to make it a bit harder to cheat? (eg. something that protects from things like Cheat-Engine) Obviously if the cheater were to develop his own tools this wouldn't help much, but I'm looking to protect the game from the average cheating 13 yr. old child.

# Answer
None ready that I know of.

Commercial (**expensive**) systems like PunkBuster exist, which constantly scan memory locations for changes, asserting that they haven't changed by impossible amounts or at impossible moments in time.

You could implement something like this yourself, by occasionally asserting that the changes to the contents of your variables make sense.

If it's a singleplayer game you're working on, I have a very personal request: *Please don't do it!* Back when I was 13, I learnt a lot about how games work by CheatEngineering or Poking them. It's like taking apart toasters and RC cars. I want my kids to live in a world where they can *choose* to break their things regardless of the opinion of a grown-up who "knows better".
> 10 votes

# Answer
When it's a single player game, there is really no reason to prevent cheating. Cheaters can only hurt their own game experience, not that of others. The cheaters themself, however, perceive the ability to cheat as a vast improvement of their game experience. So why bother?

When it's a multiplayer game, you can prevent cheating by designing the network protocol in a way that trust in the client application is not required. This is much better than any 3rd party AC-tool.

* Handle each message from a client on the server as a request which can be denied, not as an order.
* Have the whole game state and game mechanics on the server. Do not allow clients to alter the game state directly.
* Do not give the clients any information they are not supposed to show to the player
> 2 votes

# Answer
This is a simple way to do it:

```
public class SecureInt {
    private static int KEY = (int)System.nanoTime();
    private int secureValue;

    public void setValue(int value){
        secureValue = value ^ KEY;
    }

    public int getValue(){
        return secureValue ^ KEY;
    }
}

```

You just use the above class for ints, floats, etc.
> 1 votes

---
Tags: java, anti-cheat
---


# Question
Title: SharpDX - How do I write multiple streams to Texture2D?
I'm working on a 3D map that is cut as a simple grid of textures. The idea is to draw only one object with all those textures, instead of having a tile object for each of them. Correct me if I'm wrong, but only one big call is preferable to many small calls in terms of speed. Considering that textures loaded and shown are based on the camera view, ideally, it's not such a huge call.

Problem though, I need to put the corresponding textures altogether in a single Texture2D object I can pass to the shader. So I was thinking of having a rendertarget to create this Texture2D, but this beats the purpose of having only one draw call.

So basicaly, what I thought about is to load each texture, get their data and copy all of them in a new ordered Texture2D I can then pass to the object. Only thing is I have no idea on how to do that.

Any sample or suggestions on the matter? Or maybe someone tell me this is terribly wrong.

Thank you!

# Answer
What you're talking about is called a "texture atlas". The simplest way to do it is to create a static, precomputed atlas, containing all the textures in your whole game world. Each tile would have UVs set up to point to wherever its texture is in the atlas. It's a quite common technique to allow combining draw calls together.

The idea you had of a dynamic atlas - using a render target to build an atlas of just the textures to be used in the current frame - is workable, but overkill unless you have a really enormous number of textures, so that you can't possibly fit them all into a static atlas. This is a bit like a megatexture system, although there the emphasis is on streaming data from the hard drive into memory while the game is running, because the texture data for a level is too large to fit all in memory at once.
> 2 votes

---
Tags: textures, optimization, directx10, sharpdx
---


# Question
Title: Designing interface for interacting with game objects
I'm making a roguelike (-like) game, somewhat like Project Zomboid or Don't Starve. In my game, there are many different object in the world that the player can interact with; there are also many items, some of which may be required for a particular interaction.

Physically, all I have to trigger the interaction is the mouse click: when player clicks on an object, something happens (adding right-click is an option too, but staying with just one button is preferable).

There are several problems here:

1. For a given object, there might be several interactions possible. I might want do drive the car, or access its truk, or refuel it etc.
2. Some interactions may require an item: I need an axe to chop down trees or a fuel source to refuel a car.
3. Some interactions may be non-obvious, so I need to have some sort of discovery mechanism. Some way to say to the player: "You could chop down this tree if you had an axe".
4. Some interactions should be very quick. Whacking an enemy with a bat should NOT require clicking and then choosing an action from menu; just clicking should work.
5. **Added** The list of objects, items and interactions is pretty open-ended. I'm still developing the game, and in the future players might make mods. This means that the interface must be generic enough to adapt to new interactions automatically.

Given these constraints, I'm really struggling to devise a good interface for interactions. I can't show a menu of all possible actions on click, because that would break (4). I can't just leave one single on-click action, because that would break (3) and probably (1).

How can I present all options to the player in a usable and preferably obvious way?

# Answer
**Interaction**

Click vs click-and-hold. Click performs the "default" action for the item. Attacking for enemies, opening for chests, etc.

Click-and-hold can pop up a radial menu. Player moves slightly toward the option they want and lets go of the mouse to initiate the action.

Optionally, if the user lets go once the menu is open (while the cursor is still in the central "dead zone"), then leave the menu open until the user clicks again.

It's also quite reasonable to use right-click for opening the alternatives menu.

You should also condider a mouse icon that indicates what the default action is and an extra symbol to denote if more options are available, or show the radial menu dimmed out / transparent to indicate that it is available.

This is a less-than-perfect system. You might consider gamepad support and contextual keys. e.g. X is always "attack" if available, "mount" for ridable objects, etc., and then you can pop up a small display for "(X) - Drive" when on such an object.

You can also just allow more keys or key modifiers, as suggested. Supporting more than one is only a problem if you don't tell the user about them in an adequate way. A small introductory/tutorial area that requires the user to use all the extra keys (in a fun, non-hand-holding way) works well. Small reminders or on-screen hints in appropriate places and obstacles that require a certain key use to pass in a natural "makes sense to be there" tutorial area works a lot better than a contrived tutorial location with forced "click X now or you can't do anything" kind of things and is easier to implement anyway.

**Data**

Each *Item Definition*, shared by all instances of a particular item (some "unique items" may be the only instance of a particular definition) should contain a list of *Actions*. Each action should denote using a system-defined enumeration what *Interaction Method* it uses. This enum should map to a keyboard command list for keyboard input (if supported), gamepad buttons (if supported), and icons (for mouse input) plus string names (localizable, of course).

Each action then has a *Response Type*, which is what happens when that action is performed. It may make sense for this to be implicit by the interaction method, e.g. "Open" always opens the item's inventory. For maximal flexibility you might wants scripts or other special behavior attached to actions, such that you can have actions like "ring bell" or "kick" that do different things for different object. You could also simplify this by simple having an event sent for a particular interaction method type which can be intercepted by a script or go to a default system.

An item definition should not be allowed to contain multiple actions with the same interaction method. You might also want to have a way of denoting conflicts between interaction methods, especially for gamepad support (e.g. two methods that both map to the "x" button should never be on the same object).

At this point, you can generate mouse UI or gamepad UI for any object or check if a particular key press is relevant to the object. You can also invoke a particular response event handler or generic script.

You should also consider how you select the "defualt" action for the mouse assuming you go with the interaction ideas above. You might give each interaction method an innate priority, such that the most "important" method (like attack) is always the default. You might just use the first one listed on an item definition. You might allow the item definition to assign priorities. You might allow the item definition to just explicitly set a default. I would prefer anything explicit since it allows items to have no default, which is good if you want objects that should not be accidentally actionable but require a little more work. (for the mouse UI I presented, clicking an object with no default might do nothing or it might bring up the radial menu, your choice)

Lastly, consider supporting implicit actions. All enemies should have an implicit Attack-\>Combat action. Objects with inventories should have an implicit Open-\>Inventory action. Explicitly set actions that conflict with implicit ones should have priority.
> 2 votes

# Answer
You could change the mouse-pointer to show possible interactions and perform the appropriate action automatically, eg:

* A steering-wheel icon when you hover over the car's driver's seat (clicking will drive the car)
* A container icon when you hover over the car's trunk (clicking will open it)
* A canister icon when you hover over the car's fuel-thingy (clicking will refuel it)
* A bash-over-the-head icon when you hover over a monster

To avoid having to design a million icons, there could be just one for each type of interaction:

* use (for driving, refuelling, chopping down trees etc)
* pick-up (for picking up weapons, fuel, chopped wood)
* inspect (for looking into the trunk)
* attack (for shooting, bashing-over-the-head, "use chainsaw with zombie", etc)

If the player can't perform the action (don't have the car-keys, no fuel, no weapon, etc) you could give the icon a different colour or cross it out or have your character simply shrug their shoulders when you click

As for one-button input-methods: there's also double-click, click-and-hold, swipe-left/-right/-up/-down, holding the shift-key down, etc

(That being said, why would you be limited to just one mouse-button?! If even pigeons can figure out how to use multiple buttons, then certainly so can gamers :-D )

\[edit:\] ok, so the game-objects might be too small to target different areas. How about having to hold down keys while clicking?

* **just click**: walk
* **W + click**: run
* **A + click**: pick-up
* **S + click**: move the object
* **D + click**: bash the object (to attack, dismantle, etc)

Other option: differentiate between critical and non-critical objects. I.e. clicking a living (or undead) enemy will *always* attack them. Clicking a dead enemy/tree/car/what-ever will perform the most recent action. To change the most recent action, hold down the mouse-button to bring up a context-menu.
> 1 votes

# Answer
Even if "all you have is the mouse," you've got several mouse *gestures* available. Click, click-and-hold, double-click, and click-and-drag combine to give the effect you're after. A single click would be the default action. If the user tries to do something, but doesn't have a required item, launch a toast or similar non-blocking alert describing why. Click-and-hold or click-and-drag can bring up a menu to select an action-- this also becomes a discovery mechanism, in combination with the alert you give the user when they try to do something they can't do right now.
> 1 votes

# Answer
Keep in mind that limiting players to a left mouse button for all forms of interaction may be easier for you as the designer, but more complicated for them as players. We're used to standard interactions in games--WSAD to move, spacebar to jump, left click to attack, right click to inspect/zoom/target, etc.

The more you put on that one button, the greater the learning curve for your game. It also relies heavily on good mechanics. If you use click and drag right, but they click and drag slightly downward, will the menu respond correctly? See this in action: Play *Sorcery* on PS3 MOVE. If you shake the MOVE controller wrong, you don't get the desired spell.

Short answer? Use Button 3 to interact with everything. Left click to fight, scroll button to see item options/click on button to select the chosen option. Pop up clues are pretty standard ways of getting players to look for new ways to interact with an object or find a matching tool. "You need fire to create an explosion" leads them to find a way to make a fire.
> 1 votes

---
Tags: game-design, ui-design
---


# Question
Title: What is the edge glow shading technique used in Super Mario called?
What is this Super Mario shading technique (the edge glow) called? It can best be seen on the legs.

# Answer
> 12 votes
Rim lighting.

http://blog.wolfire.com/2009/09/character-rim-lighting/

Basically you increase the brightness of a surface the more the tangent is pointing away from the camera.

# Answer
> 7 votes
Looks to me to either be the Fresnel Falloff shader effect or some variant of a Rim Lighting. The pixels near the edges appear to be just brightened. You can see a similar effect described here.

---
Tags: shaders, graphics, terminology, glow
---


title: Dynamic graphical elements in a 2D game

text:
# Question
Title: Dynamic graphical elements in a 2D game
I'm an mobile and web developer. I got interested in game development couple of weeks ago and I'm really looking forward to work on a mobile game.

I will be doing everything including the game design part. The problem is that I never designed something from scratch. Simple and static objects are not my concern, my main concern is dynamic objects, like a moving character. Should I draw multiple images of the character in different steps or am I missing something?

I'm not looking for something advanced, all I need to know some details about drawing and design for 2d games development.

# Answer
> 3 votes
There are a lot of approaches for 2D animation.

The most common that I've seen is traditional frame-based animation where you draw multiple frames and just swap between them. Any art tool that you're comfortable with you can use (photoshop, illustrator, corel draw, whatever).

A slight variant I've seen of that is modeling/animating a character in a 3D studio package (like max or maya) and then just rendering out frames. You can get some interesting effects that way. One of the games I've shipped, Splode did that.

Another technique I've seen is to do 2D skeletal animations where you have mostly rigid body parts bind those to bones in a skeleton and animate that. It gives you a different look but has lots of benefits (at the cost of being a lot more complicated than just drawing a different image). A good example of that done in an iPhone game can be found here: http://www.thecareergamer.com/braaaains-zombieville-usa-tech-review/ Sometimes that's done with a combination of the frame-based animation (e.g. the head will have different frames for different expressions).

---
Tags: 2d, animation
---


# Question
Title: Repositioning and resizing when i change the size of my window
I am trying to write a game.

When someone resizes the window of my game, I need all the graphics i have drawn on the screen to reposition correctly so that the ratio of the graphics' width and height remain correct and that the new position determined by x and y, have been adjusted for the new size screen.

In the following image, the top left corner is 0,0... all coordinates / widths / heights are measured from this point.

What do I need to do to x, y, width and height from the variable width and height of my screen in order to keep this aspect ratio correct?

**SIDE NOTE: the aspect ratio of the screen will always be 16:9!**

# Answer
You have two values to work with, the change in X (dx) and the change in Y (dy) (really the ratio between the two sizes). When changing from one size to another while maintaining the same aspect ratio, dx and dy will be very close to each other (slight differences due to the integer aspect of pixel counts).

So, in your example:

```
dx = 1376/1920 = .716
dy = 768/1080 = .711

```

This is a factor you'll apply to size and position values to scale them to the new screen. So again, in your example, your box would be changed in size:

```
100*.716 = 71.6
100*.711 = 71.1

```

And the position would likewise change:

```
1850*.716 = 1325.8
20*.711 = 14.2

```

The general formula being:

```
NewPosition.x = (NewScreenWidth/OldScreenWidth) * CurrentPosition.x;
NewPosition.y = (NewScreenYHeight/OldScreenHeight) * CurrentPosition.y;

NewSize.x = (NewScreenWidth/OldScreenWidth) * OldSize.x;
NewSize.y = (NewScreenHeight/OldScreenHeight) * OldSize.y;

```
> 1 votes

---
Tags: aspect-ratio
---


title: Ray picking gives inversed results

text:
# Question
Title: Ray picking gives inversed results
I'm trying to do a simple ray picking implementation to allow a user to select a cell in a grid rendered in 3D. I'm almost there, but I've ran into an issue which I can't seem to solve.

Consider the following image:

The line represents the ray. The circled part is where the mouse is, and the line's green tip is where it intersects with the grid (XZ plane). When I move the mouse around, the green tip moves almost opposite of the mouse.

What is causing this?

I am converting screen coordinates to OpenGL coordinates using gluUnproject.

After obtaining the direction and position of the mouse, I use the properties of similar triangles to obtain the XZ interception. The ratio between the direction y and position y is the same for both x and z axis. Hence multiplying the direction x, z by the ratio and using y=0 should give the location of the XZ plane intersection. Essentially:

```
Ray ray = ...
float ratio = ray.point.y / ray.dir.y;
Vector3 intercept = new Vector3(ray.dir.x * ratio, 0, ray.dir.z * ratio);

```

And yet, as the image shows, its not. Is there something wrong with my reasoning, or something I've overlooked?

# Answer
A couple possible sources of error:

1) Is the double-negative on the Y-axis intentional?

```
Ray ray = getPickingRay(Mouse.getX(), Display.getHeight() - Mouse.getY());
...
float winY = (float) viewport.get(3) - (float) cursorY;

```

2) You're ignoring `ray.point.x` and `ray.point.z` in the final line

```
Vec3d intercept = new Vec3d(ray.dir.x * ratio, 0, ray.dir.z * ratio);

```
> 1 votes

---
Tags: opengl, 3d, grid, raycasting
---


title: Opentk: Move Bones model 3d

text:
# Question
Title: Opentk: Move Bones model 3d
I have a model in 3ds max and have exported to obj file using tutorials and I managed to load my model and apply a texture. My problem is that I have to move a part of this model and to move while their children. I've done things with XNA and it was very easy to do but not how to export opengl inheritance from my file 3ds max .. You have any idea how I can do this or any tutorials that can help me. thanks

# Answer
> 1 votes
**File Formats** \- OBJ does not support bones. You have to chose a file format that does, such as FBX or MD5.

**Loading Models in OpenGL** \- In terms of drawing graphics, OpenGL (and OpenTK) is little more than a low-level "Give-triangle-buffers-to-graphics-card" library, and has no concept of "models", "bones", or "animation". You could use model import libraries (such as AssImp) or more fully featured game engines (MonoGame, OGRE, Irrlicht, etc) to get this functionality, or you will have to code your own classes for them.

---
Tags: opengl
---


# Question
Title: Language & framework for fast prototyping Box2d problems
I am often in need of a fast prototype box2d scene where I can play with parameters. I work with AndEngine on Android which doesn't suit me for prototyping. It's good for the final game, but prototyping is slow.

My requirements are:

* Java or language similar to Java (C-like syntax with garbage collection), scripting languages are fine, but something with fast learning curve (Javascript maybe?). I know Java, Groovy and some remnants of JavaScript and C/C++ from the past, but learning a new language is good.
* Easy to use 2D framework. Must have boxes, circles, polygons and GUI elements like buttons and sliders, everything else is optional.
* Same physics eengine capabilities - maybe there is some HTML5 sandbox that will allow me to do this in browser, but then I need the same performace (like setting fixed step of the box2d engine) as in the phone and I want to see same results.
* Good IDE - currently I use eclipse, so eclipse would be an advantage
* doesn't need to be multiplatform, but must run on Windows
* Would be great if I could change code -\> recompile -\> see the results immediately (not the case in Java on Android :))

I like the Flash version of Box2d prototype from here, but I have no experience with ActionScript, Flash Frameworks, IDEs for it nor the Box2d version ported to Flash.

# Answer
LibGDX has a pretty decent implementation of Box2D. Its Java and even has a project creator to set up stuff for Eclipse. Its not an active editor, but its copy and paste. Its made for iOS and Android development, but it also compiles to desktop so iteration is much faster.

Most info: https://code.google.com/p/libgdx/wiki/PhysicsBox2D
> 1 votes

---
Tags: box2d, prototyping
---


# Question
Title: Continuous increase in heap memory in Android game
For my Android AndEngine game, I used the scene based approach. Game contains more graphics so I need to load and unload those graphics multiple time so that game runs smoothly.

But doing this, I found that there was continuous increase in heap memory. Following log trace represent that thing:

```
06-14 08:48:26.990: I/dalvikvm-heap(669): Grow heap (frag case) to 10.715MB for 2457616-byte allocation
...
06-14 08:48:40.619: I/dalvikvm-heap(669): Grow heap (frag case) to 11.110MB for 2457616-byte allocation

```

Is this normal behaviour?

# Answer
> 1 votes
This is normal JVM heap behaviour. Java allocates memory automatically for each object and releases it when it decides it's a good time to release it. Unless you hit an OutOfMemory error, don't worry about small increases. Also note that textures live in a different memory, not the JVM Heap. So loading and unloading textures has little to do with growing of your heap.

There are many types of objects in Java and based on their purpose and "age" they get collected at certain times. This is not really a GameDev question and you can find more information at Oracle website or StackOverflow.

---
Tags: android, andengine
---


# Question
Title: How exactly do you deconstruct the Tiled Map Editor exported tile ID?
I am trying to build 2D maps with Tiled Map Editor for my game, and I export them under text format, so a tile can look like this:

> 1,2,3,15,2,12,2
>
> 5,23,1,6,2,3,4,6

and so on, for many rows. In this link you can see an example of a map, to get a better idea.

Now let's say I have 3 layers, each using its own tileset. The numbers in the layer represent the ID of the tile, basically the number of the tile in the sheet. If grass is the 2nd tile, then the ID is 2, and so forth.

However, as you can see in the link, different tilesets will export different IDs per layer, notice how in the object layer I can have IDs such as 81, when in fact the ID is only 1, so it adds up 80 or so.

Since I am trying to make my map system as flexible as possible, I need the real ID in order to make some calculations. How does tiled export these sort of IDs? I simply want to determine what number to substract in order to get the id, like so:

> tile.id = currentid - something\_strange;

# Answer
> 4 votes
You are using Tiled map editor, but not using the TMX file format, right? I believe the `something_strange` comes from the first tile GID in the given tileset. Just save the tilemap as TMX and you should see something like:

```
 <tileset firstgid="49" name="nameoftileset" tilewidth="128" tileheight="128" spacing="2" margin="1">
  <image source="tiles.png" trans="ff00ff" width="520" height="260"/>
 </tileset>

```

`something_strange == firstgid`

---
Tags: tilemap
---


# Question
Title: Identifying Entity 'Types' in an Entity-Component System
If an Entity has no explicit 'type' (e.g. player) and is simply a collection of components, how do I identify the entities that my systems should and should not be working on? For example, in a game of Pong the paddle and ball both collide with the window boundaries. However, the collision handling systems for each will be different, therefore a system should not handle entities of the wrong type.

```
void PlayerCollisionSystem::update(std::vector<Entity *> entities) {
  typedef std::vector<Entity *>::iterator EIter;
  for (EIter i = entities.begin(); i != entities.end(); ++i) {
    Entity *player = *i; // How do I verify that the entity is a player?

    // Get relevant components.
    PositionComponent *position = player->getComponent<PositionComponent>();
    VelocityComponent *velocity = player->getComponent<VelocityComponent>();
    SpriteComponent *sprite = player->getComponent<SpriteComponent>();

    // Detect and handle player collisions using the components.
  }
}

```

Both the player and the ball share the same relevant component types for collision handling yet their system implementations will be different.

**If I have a container of all game entities, how do I identify specific types of entity** without inheriting `Entity` or including a member variable such as `std::string type`, in which case an entity is no longer simply a collection of components?

# Answer
Nicol Bolas' answer is straight on, but stepping aside and looking at your problem from a distance: you really don't need the type of the entity.

You only need to care whether "does the object have component `X`" or not and your problem is that you have not properly identified `X`. If two objects behave differently then give them different components or just put a boolean flag on the component if it to make it behave differently for different object configurations. Use the component system to make decisions about behavior, not the entity "type." That's the whole point of using components.

You are completely allowed to have a `PaddlePhysics` component/system and a separate `BallPhysics` component/system if they behave differently. Or you can break down the components into more granular pieces such that you have a `Bounce` component that only the Ball has and a `StopAtBoundary` component that both `Ball` and `Paddle` have if part of the behavior is complicated enough to justify sharing the code. Or you can just make a `PongPhysics` component that has a boolean flag `Bounces` set `true` for the `Ball` and `false` for the `Paddle`. You could even make a base `WallCollision` component and then derive that component to get a `BallWallCollision` that adds the extra behavior needed there.
> 22 votes

# Answer
A system is only useful if it is *useful.* If a system where an entity is "simply a collection of components" is less useful than a system where an entity is *mostly* a "collection of components", then *do that*.

Stop trying to make "pure" systems and focus on making *good* ones that do what you need. Use components until components are no longer useful for you. Then use something else.

You've already spent more time thinking about this than it deserves.
> 21 votes

# Answer
If you want to give entities a explicit type, the easiest way is to define a type variable in the entity class. Only keep to the EC pattern as long as its useful.

Otherwise the type is implied through the component attributes. For example, the physics component would have an attribute for mobile vs stationary. The system then knows when two mobiles collide (ball and paddle). Similarly you can have attributes for how the collision system should respond. Just stop the object or reflect it? Looking at the attributes should give you an idea of what the entity is, but it should be irrelevant. The systems shouldn't need to know what the entity type they're working with is, they should be given enough information using the components provided to them.

Finally, can add an additional component that contains a type, but, as with adding a type to the entity, you'll end up writing a lot of type specific code, defeating the purpose of the EC system.
> 5 votes

# Answer
An entity is a set of components. You can't assign neat labels to a random set. Giving up type constraints is the price for the great flexibility.

Of course you can have special (typed) entity classes which impose restrictions on the components.

Ideally components are independent. So the solution to your problem would be to call collision handling on each subcomponent, in order. In real applications there are interdependencies and ordering problems. If that's the case you need some 'dispatcher' logic in every method of the Entity class.
> 0 votes

---
Tags: c++, entity-system
---


title: Making a scroll bar in game

text:
# Question
Title: Making a scroll bar in game
I'm making a scroll bar for chat box in my game now but I can't calculate the height of thumb in scroll bar.

I try

`(containerHeight / contentHeight) * thumbHeight`

but it's not working.

please give me an idea, thanks.

Illustration:

# Answer
> 2 votes
I think you're just looking for the equation: `X / Y = A / B`, where `X` is to `A` what `Y` is to `B` then algebra yields:

```
X / Y = A / B

```

Multiply both sides by `Y` to get:

```
X = (A / B) * Y

```

Using some variables I made up because I don't completely know if Jimmy's interpretation is alright:

```
TabHeight / ScrollBarHeight = ViewableHeight / TotalHeight
TabHeight = (ViewableHeight / TotalHeight) * ScrollBarHeight

```

As long as you know any 3 variables in the equation, you can solve for the 4th.

---
Tags: c++
---


# Question
Title: Why do some .obj files have no newlines?
I'm working on a game engine and just started with mesh loading. I started with the format `.obj`. I ran into this problem:

The guide I'm following gave me a couple of `.obj` files to try and they all worked fine. I then asked a friend who is working with 3D animation to give me a couple of `.obj` files to try in addition, but his files, when opened up in a txt format, contain no newlines to separate the information at all. (Everything was on one line). The loading function I use depends on this to extract the information.

Are the files he gave me bad in some way? Is my function bad because it depends on newlines being there? (I can't see `.obj` files having any other delimiter character...)

My friend made and exported the 3D models in Blender. This is the guide I'm following.

# Answer
I'm assuming you opened the file in Notepad. Notepad doesn't recognize some new line formats.

The OBJ format does indeed use newlines as delimiters, and your files likely contain them. It's just not looking that way in Notepad. Try opening them in Notepad++ instead: I'll bet they'll appear correctly.

To make sure your parser function works correctly on all platforms, it should consider both `\n` (newline) and `\r` (carriage feed) characters as newlines.
> 5 votes

---
Tags: c++, 3d-meshes, obj, model-loader
---


title: Defining lines from a heightmap

text:
# Question
Title: Defining lines from a heightmap
To a pixel shader of a 2D game, I'm passing a 1-row heightmap that holds the height in UV coordinates of evenly distributed points throughout the texture I'm drawing, but as for *n points* there will obviously be *n-1 lines* connecting consecutive ones, I can't make these lines as wide as they should be. For example, filling the pixels below the lines of a heightmap that holds 3 values (`{0f, 1f, .5f}`) should result in something like:

but instead, it looks like this:

It is visible that the correct result lies on the first 2/3 of the second one, and the last 1/3 comes from clamping the heightmap.

Here is a simpler version of the pixel shader code.

```
float4 PixelShaderFunction(float4 texCoords:TEXCOORD0):COLOR0
{
    float verticesCount = 3;
    float verticesFrequency = 1/verticesCount;

    float lastHeight = tex2D(heightMapSampler, float2(texCoords.x, 0));
    float nextHeight = tex2D(heightMapSampler, float2(texCoords.x + verticesFrequency, 0));

    float delta = (texCoords.x % verticesFrequency)/verticesFrequency;
    float height = lerp(lastHeight, nextHeight, delta);
    if(texCoords.y > height)
        return float4(1, 0, 0, 1);
    return float4(0, 0, 0, 1);
}

```

I tried multiplying the texture coordinates by `(verticesCount-1)/verticesCount` but that didn't seem to do the job. Thank you!

# Answer
> 0 votes
Multiplying `texCoords.x` by `(verticesCount-1)/verticesCount` at the top should do the trick.

# Answer
> 0 votes
In this line verticesFrequency becomes equal to one third

```
float verticesFrequency = 1/verticesCount;

```

On this line you are adding one third to the texture coordinate

```
float nextHeight = tex2D(heightMapSampler, float2(texCoords.x + verticesFrequency, 0));

```

So for the first pixel you are sampling texture coordinate \[0.333, 0\] but you want to be sampling \[0.5, 0\] i.e. the middle of the three coordinates.

Perhaps you should use verticesCount - 1

---
Tags: xna, hlsl, fragment-shader, heightmap
---


# Question
Title: How do I derive the angular movement for a craft
I have the regular (linear) motion implemented like this:

```
class Craft{
...
Vector location, velocity, acceleration, angularVelocity, angularAcceleration;

...
//the move class responsible for linear motion
//this method works
 public void move(Vector target){
  Vector desired = target.sub(location);
  desired.normalise();
  accleration.set(desired.multipied(speed));
  velocity.add(acceleratio);
  location.add(velocity);
}

//the turn method
//I need help/tips

public void turn(float angle){
//I need the craft to gradually turn in a circular motion
// so that eventually maybe 10 secs, it makes 360 degrees turn

}

}

```

# Answer
Angular acceleration works just like linear acceleration on a single axis, except instead of working with a distance, you're working with angles.

So, for example, lets look at your linear motion converted into a single axis:

```
float desired = target - location;
//perform something similar to normalize, where you limit the size of `desired`
acceleration = desired * speed;
velocity += acceleration;
location += velocity;

```

We can easily imagine this to be converted using angles instead:

```
float desiredAngle = targetAngle - currentAngle;
//perform something similar to normalize, where you limit the size of `desiredAngle `
angularAcceleration = desiredAngle * speedOfRotation;
angularVelocity += angularcceleration;
currentAngle += angularVelocity;

```

Note: You may want to add your timestep into this equation, otherwise you'll have to set `speed` and `speedOfRotation` to something like: `desiredSpeed * timestep`. Basically, `speed` and `speedOfRotation` should already have the time factored in if you don't include it separately.

It would be preferable to add some kind of wrapping code to wrap `currentAngle` when it completes a circle, but it's not strictly necessary.
> 4 votes

# Answer
One solution is that you can have the method create a thread that adds 1/10 of a whole turn then sleeps a sec, then adds another 1/10 and so on until you have done that 10 times. Just remeber angles are usally measured in radians rather then degrees. You should also put up some safe guards so while a tread is active, you cant call the method until the other tread is finished. You should also make a conditional statment so whenever the angle reaches 2 pi you reset it to 0 again, otherwise it can get big really fast.

But that just one way you can do it, depends all on how much performance you want to use
> -1 votes

---
Tags: java, 3d, mathematics
---


# Question
Title: Tracking player location in realtime 2d mmo
I have read all of the answers here about tracking player locations, but still have some questions. I don't seem to understand how to do this efficiently, and feel that the internet could greatly benefit from an effective solution that is easy to find.

Anyway, I am making a 2d mmo (the first multiplayer game I have made that will handle this many people) and can't seem to come up with a good way to manage the location of players, and alert other players when they are near them. My map is tile-based, and I want the clients connected to know when a player of another client is withen 200 blocks from the other client.

My map uses x and y coordinates, and each block is a value. I read something I was linked to by a similar question here, that explained that a good way of managing this sort of thing is to create a box around each player, and to alert both player's when their boxes overlap (assuming I understood it correctly).

But how should I create these boxes without wasting tons of computing power and resources? I thought of storing it in SQL database, but that would be too slow. I then realized that player locations would have to be stored in the RAM. So what are some previously used strategies to track player movement in the RAM? Should I store a variable for each player containing the coordinates withen 200 blocks from them, and constantly have the server checking to see if two players overlap? This doesn't seem very efficient, and I believe that I am going about this the wrong way.

Any help is greatly valued.

# Answer
If you're willing to ease on the requirement that a client should be informed of other clients that are **exactly** 200 blocks away or closer, then here's an idea: split your map to squares of, say, 200 blocks each side. Then you can keep track of where the client is, and inform the client of all other clients in the adjacent squares. More detailed discussion can be found in another question.

So, instead of having a square of 200 blocks around each player, you'll have statically located squares, each of which know the clients contained within them.

Also, see information about quadtrees. Quadtrees are often used in collision checking, and in your case you want to know a kind of collision.
> 5 votes

---
Tags: networking, mmo, databases, node.js, websocket
---


title: Fog shader camera problem

text:
# Question
Title: Fog shader camera problem
I have some difficulties with my vertex-fragment fog shader in Unity. I have a good visual result but the problem is that the gradient is based on the camera's position, it moves as the camera moves. I don't know how to fix it.

Here is the shader code.

```
struct v2f {
    float4 pos : SV_POSITION;
    float4 grabUV : TEXCOORD0;
    float2 uv_depth : TEXCOORD1;
    float4 interpolatedRay : TEXCOORD2;
    float4 screenPos : TEXCOORD3;
};

v2f vert(appdata_base v) {
    v2f o;
    o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
    o.uv_depth = v.texcoord.xy;
    o.grabUV = ComputeGrabScreenPos(o.pos);
    half index = v.vertex.z;
    o.screenPos = ComputeScreenPos(o.pos);
    o.interpolatedRay = mul(UNITY_MATRIX_MV, v.vertex);
    return o;
}

sampler2D _GrabTexture;

float4 frag(v2f IN) : COLOR {
    float3 uv = UNITY_PROJ_COORD(IN.grabUV);
    float dpth = UNITY_SAMPLE_DEPTH(tex2Dproj(_CameraDepthTexture, uv));
    dpth = LinearEyeDepth(dpth);
    float4 wsPos = (IN.screenPos + dpth * IN.interpolatedRay); // Here is the problem but how to fix it
    float fogVert = max(0.0, (wsPos.y - _Depth) * (_DepthScale * 0.1f));
    fogVert *= fogVert;
    fogVert = (exp (-fogVert));
    return fogVert;
}

```

Thanks a lot !

# Answer
It seems that it's a Matrix problem

```
o.interpolatedRay = mul(UNITY_MATRIX_MV, v.vertex);

```
> -1 votes

---
Tags: opengl, unity, directx, shaders, fragment-shader
---


title: Rules to start and naming a game studio

text:
# Question
Title: Rules to start and naming a game studio
I would like to know if there is any copyright related rules to name a game studio specially for android appstore. I searched at the U.S. Copyright Office website and found many matches for same names. None of them are game studios though. Is it legal to choose one of those names if none of them are game studios? Also, what are the rules I need to know for starting a new indi game studio?

# Answer
Naming any business in the United States can be a drawn-out, expensive process. Oh, and IANAL.

The very first thing, is that you are looking in the wrong place. You should be checking the trademark registry at the United States Patent and Trademark Office Website.

There are a few things to consider is the class, multiple marks can exist with the same word because you register per class. While one company can hold all of the classes for their name, it's not always likely because the fees can get up there.

But it doesn't stop there, because when you file for a trademark it is published for opposition. If someone has been using the name in commerce before you, they can have your application ended. With the international nature of business you may even face external (to the US) opposition.

The solution to this, is to get a lawyer who can work with you along the path, including looking up common-law trademarks around the country, and possible places where you may reach conflicts before registering. The USPTO offers no service (aside from the basic registered mark check) for looking up this information.
> 8 votes

# Answer
First of all, if you're talking about the name of a company you're asking about trademarks, not copyrights.

Second, as long as there aren't other companies with the same name *in your industry* (i.e. games), it's probably OK. I used to work at a game studio called Sucker Punch Productions; there's also a movie, an art/architecture magazine, a motorcycle dealership, a small film studio, a pickle company, an online radio station, an athletic supply company, and many more all named Sucker Punch. These businesses can all coexist and have the same name because they're all in completely different industries.

Disclaimer: IANAL.
> 4 votes

---
Tags: copyright, business, trademark
---


# Question
Title: Recording and playing back sounds with LibGDX
How do I record a sound to PCM format and replay it from there?

# Answer
to record:

```
AudioRecorder recorder = Gdx.audio.newAudioRecorder(sampleRate, isMono);
short[] pCM = new float[1024]; // 1024 samples
recorder.readSamples(pCM, 0, pCM.length);
recorder.dispose();

```

to play back:

```
AudioDevice device = Gdx.audio.newAudioDevice(sampleRate, isMono);
device.writeSamples(pCM, 0, pCM.length);
device.dispose();

```
> 1 votes

---
Tags: android, libgdx
---


# Question
Title: How to Complete a Two Key Animation with One Key
I have a game where I need to perform an action by pressing `U` and `K` at the same time, but I also want it to be accomplished by only using one key, because pressing both at the same time ties up your hand a bit.

How would I accomplish this?

# Answer
> 4 votes
This is pretty simple. Basically, you just have another key call the same function as U+K does.

```
if((keyDown('U') && keyDown('K')) || keyDown('O'))
    doPowerBlock();

```

Basically that's saying if the U key AND the K key are pressed, OR the O key, do the action. Or depending on how you have things arranged, you could do something like:

```
if((keyDown('U'))
    doBlock();

if((keyDown('K'))
    doPower();

if((keyDown('O')) {
    doBlock();
    doPower();
}

```

---
Tags: keyboard
---


title: Collision detection-too fast

text:
# Question
Title: Collision detection-too fast
I've looked through a few other answers and it seems like I'm doing a dynamic timestep update and I'm checking about 10 pixels before the rectangle to see if it would intersect. However, the updating must be too fast, because it will register a detection (I checked via print statement debugging) it just wont fire the stop method.

My player update:

```
public void update(List<TouchEvent> touchEvents, int deltaTime) {
    gamescreen.xScroll += getSpeedX();
    gamescreen.yScroll += getSpeedY();

    this.xPos += getSpeedX();
    this.yPos += getSpeedY();

    if((gamescreen.getXScroll() + 800) >= (map.w * 64)) gamescreen.xScroll = (map.w * 64 - 800);
    if(this.getXPos() >= (map.w * 64)) this.xPos = (map.w * 64);

    if(gamescreen.getXScroll() <= 0) gamescreen.xScroll = 0;
    if(this.getXPos() <= 0) this.xPos = 0;

    if(gamescreen.getYScroll() <= 0) gamescreen.yScroll = 0;
    if(this.getYPos() > 0) this.yPos = 0;

    if((gamescreen.getYScroll() + 480) >= (map.h * 64)) gamescreen.yScroll = (map.h * 64 - 480);
    if(this.getYPos() >= (map.h * 64)) this.yPos = (map.h * 64);

    int len = touchEvents.size();
    for (int i = 0; i < len; i++) {
        TouchEvent event = touchEvents.get(i);

        if(event.type == TouchEvent.TOUCH_DOWN) {
            //Right.
            if (gamescreen.inBounds(event, 150, 330, 70, 70) && isMovingLeft() == false && (gamescreen.getXScroll() + 800) < (map.w * 64)) {
                if(gamescreen.checkEntities(map.trees).equals("right")) {
                    stopRight(deltaTime);
                }
                else {
                    moveRight(deltaTime);
                    setMovingRight(true);
                }
            }
            //Left.
            if (gamescreen.inBounds(event, 0, 350, 70, 70) && isMovingRight() == false && gamescreen.getXScroll() > 0) {
                if(gamescreen.checkEntities(map.trees).equals("left")) {
                    stopLeft(deltaTime);
                }
                else {
                    moveLeft(deltaTime);
                    setMovingLeft(true);
                }
            }
            //Up.
            if (gamescreen.inBounds(event, 50, 280, 70, 70) && isMovingDown() == false) {
                if(gamescreen.checkEntities(map.trees).equals("top")) {
                    stopUp(deltaTime);
                }
                else {
                    moveUp(deltaTime);
                    setMovingUp(true);
                }
            }
            //Down.
            if (gamescreen.inBounds(event, 50, 430, 70, 70) && isMovingUp() == false) {
                if(gamescreen.checkEntities(map.trees).equals("bottom")) {
                    stopDown(deltaTime);
                }
                else {
                    moveDown(deltaTime);
                    setMovingDown(true);
                }
            }
        }

        if (event.type == TouchEvent.TOUCH_UP) {
            if (gamescreen.inBounds(event, 150, 330, 80, 80)) {
                setMovingRight(false);
                stop(deltaTime);
            }
            if (gamescreen.inBounds(event, 0, 350, 80, 80)) {
                setMovingLeft(false);
                stop(deltaTime);
            }
            if (gamescreen.inBounds(event, 50, 280, 80, 80)) {
                setMovingUp(false);
                stop(deltaTime);
            }
            if (gamescreen.inBounds(event, 50, 430, 80, 80)) {
                setMovingDown(false);
                stop(deltaTime);
            }
        }
    }
    gamescreen.checkEntities(map.trees);

    if (playerHealth == 0 || gamescreen.clock.minutes == 5)
    gamescreen.state = GameState.GameOver;
}

```

entity check (kind of a mess):

```
public String checkEntities(BigEntity[] trees) {
    for(int j = 0; j < trees.length; j++) {
        if(player.getRect().right + 10 >= trees[j].getRect().left && player.getRect().bottom >= trees[j].getRect().top && player.getRect().top <= trees[j].getRect().bottom) {
            return "right";
        }
        if(player.getRect().left - 10 <= trees[j].getRect().right && player.getRect().bottom >= trees[j].getRect().top && player.getRect().top <= trees[j].getRect().bottom){
            return "left";
        }
        if(player.getRect().bottom + 10 >= trees[j].getRect().top && player.getRect().right >= trees[j].getRect().left && player.getRect().left <= trees[j].getRect().right) {
            return "bottom";
        }
        if(player.getRect().top - 10 <= trees[j].getRect().bottom && player.getRect().right >= trees[j].getRect().left && player.getRect().left <= trees[j].getRect().right) {
            return "top";
        }
    }
    return "null";
}

```

# Answer
> 1 votes
It looks like checkEntities is behaving in an unexpected manner.

The first things I would check are:

* trees has the right data
* the coordinate system has y=0 at the top of the screen

If these are both true then place a breakpoint at the start of the method and see where it goes wrong.

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


# Question
Title: Per frame: Many draw calls with fewer total vertices vs fewer draw calls with more total vertices?
Is there any chance draw calls like XNA's Graphics.DrawIndexedPrimitives has an extremely low overhead and performance issues are more than likely due to the complexity of the meshes?

If I had a million quads to render, how significant in XNA is it to pack the vertex buffer as full a possible before calling the draw (as an example)? I know many other methods of culling, vertex welding, etc to lower the count would probably have an even bigger impact if/when they are possible, but just for curiosity's sake lets not hit on those topics for this question.

My hope is that XNA indeed has a low overhead on most draw calls and pretty much buffers the 'transactions' necessary to the GPU in some kind of load balancing type way.

Thanks for any and all help.

# Answer
> 7 votes
Draw calls have a fair amount of CPU overhead, as the driver has to do a bunch of work internally on each call, so reducing the number of draw calls is often important for CPU performance. For the GPU, the number of vertices, triangles, textures etc. matters more than the number of draw calls. Conversely, the size of the draw calls doesn't matter very much for the CPU, only how many of them there are.

The rule of thumb that I've seen quoted often for DX9 (which XNA runs on) is no more than about 2,000-3,000 draws per frame to avoid becoming CPU-limited. YMMV, of course, but the limit is going to be on the order of several thousand, definitely not a million.

With very careful renderer design it's possible for games to push more draws. Firaxis gave a GDC talk describing how they achieved 15K draws in DX11. Another question here noted that Saints Row 3 apparently gets 7K draws in DX9.

In DX10-11 the CPU overhead of draw calls is supposed to be less than in DX9, but I haven't seen a measurement of how much less. The sense I have from talking to people about it is that this doesn't make a big difference, i.e. the draw call limit is still only a few thousand. DX11 also allows multithreaded draw call submission (deferred contexts), which is supposed to let you distribute the CPU overhead over multiple cores. However, internally the graphics driver may still be processing things with a single thread, so DX11 deferred contexts may not be very effective either.

On consoles, due to their lower-level APIs (which avoid a lot of layers of validation and conversion in D3D), you can use multithreading much more effectively and reach 10,000-20,000 draws per frame without being CPU-limited. (All of that doesn't help you for XNA; I mention it only for completeness.)

---
Tags: xna, performance
---


title: Game state management?

text:
# Question
Title: Game state management?
I'm running in circles here trying to figure out how to implement game states!

Many of the articles I have read use an abstract class that game states inherit, and another "manager" class that handles pushing/popping game states.

This is fine I guess, but for the game I'm planning on making, I can only imagine I'll have MANY classes, alot of which are nearly identical. For example, I have one game state which is basically a view of my scene with a few GUI buttons. Another game state gets entered when the user clicks the "Terraforming" button, which allows the user to modify the terrain. Both of those have many similarities - they are both rendering the same scene, the controls are the same, much of the GUI is the same except for a new window that contains terraforming controls, and mouse clicking is handled differently. It sounds silly to completely reconstruct a new game state when 90% of it will be identical.

Am I thinking about this the wrong way? Or is there a better solution for managing game states?

# Answer
> 1 votes
Game states can be implemented however makes the most sense for your game. If you simply have a new mode that slightly alters the running game (like an edit mode), there is nothing wrong with just adding a boolean flag to the game state that indicates edit-mode is on.

You can also keep using different states but put all the shared data in another place. Perhaps you have a singleton GameData that holds everything needed for a running game which is set up and torn down when you transition between the main menu states and the playing states.

Yet another option is to use sub states. You have top-level states like `LoadingMain`, `MainMenu`, `CharacterCreation`, `Playing`, etc. Inside the `Playing` state is another state machine with states like `LoadingLevel`, `InGame`, `Editing`, `Paused`, and so on. The game data is all conveniently stored on the `Playing` state object while the sub-states control how the simulation is run, what HUD UI is overlaid on the game scene, etc.

Sub states can be implemented by having a generic state machine engine which you can embed in your global engine object to handle top-level states and embedded in individual state objects for sub-states or even in sub-state objects to have sub-sub-states (e.g., if your in-game editor has multiple modes/states). You can also implement it via state stacks.

# Answer
> 0 votes
When I started to develop my game engine, I created StateManager and BaseState class, but further I found it extremly unpractical, and removed state management completely. Now I simply use SceneManager loading, unloading scenes. Main problem was transition between states. Now, I just use substates inside scene and that's all

---
Tags: c++, ogre, game-state
---


# Question
Title: How can I implement something like Destiny's public events?
Bungie has shown a gameplay trailer for their new game, Destiny. The part that really stood out for me was the 'public events' that can happen randomly while playing. Now I've thought about it for a while but I can't figure out how I might implement a feature like this.

Perhaps a dedicated event server that all game servers (or all clients) must connect to?

# Answer
I think a few games have done something similar (Warhammer online is the first that comes to mind). I believe how it has been done in the past is that players are put on a world server like any other MMO (or play locally, or with P2P) but when they enter a certain zone they are all transferred to the same server temporarily (or a specialised server) and put back when they exit the zone.
> 1 votes

---
Tags: architecture, networking, multiplayer
---