# Question
Title: How can I get almost pixel perfect collision detection in a multiplayer game?
I'm currently working on a multiplayer game for iPhone. The problem I have, as with all multiplayer games, is that the other user will always see everything at a non-constant delay. The game I'm making needs to have an almost pixel perfect collision detection, but 1 or 2 pixels off is not that big of a deal. How can I possibly get this working? I guess I could just set local player to also be at X ms delay. However this will probably just be worse and feel sloppy when the user input. I know this problem is probably something network programmers deal with everyday and I would be glad if someone could give me a possible solution for this.

# Answer
> The game I'm making need to have a almost pixel perfect collision detection, but 1 or 2 pixels off is not that big of a deal. How can I possibly get this working?

Honestly, you probably can't. Part of your job as a game engineer is to give feedback to design on gameplay elements that simply aren't feasible. Getting perfect visual collision on all clients in a networked game isn't feasible, at least until we manage to break the speed of light.

"Pixel-perfect" implies client-side visuals while the collision is gameplay-related implying server-side physics. There is latency between the server and client and latency between all clients and each other. There isn't a way to make that not the case. The gameplay is going to be out of sync with the visuals and the best you can do is compensate for that fact and hide its consequences from players.

Your game is going to have to deal with the fact that the client won't actually know where any other client is with great accuracy. It's simply impossible; no matter how good you get your latency compensation, the remote game code won't know about the input from the client until X ms later (where X will likely be from 15 to 300, or more for some mobile/wireless networks).

You could as you say delay all input on the local client by the worst latency of all clients, but that is going to make your game feel incredibly sluggish and obnoxious to play, plus it won't account for spikes (your game won't even know if another client is experiencing a spike until well after the spike in many cases).

With any networked game, a large portion of what you have to do is *hide* the latency, often with gameplay compromises (and art) and hides how objects aren't in quite the same positions on all the clients. This is a problem for gameplay-relevant physics.

You can do the physics on the server and then, again, use gameplay compromises and art to hide the fact that objects might be colliding and reacting to things that are off from what the player actually sees.

Another option is to do the collision client-side but the results server-side. That is, if my client *thinks* we collided, tell the server. The server does some verification to make sure the collision was possible, some analysis to detect aimbots or cheating or the like, and then actually does whatever gameplay thing is supposed to happen in response to the collision. The collision results will not be "pixel-perfect" due to the latency (you can play the visual effects or sounds immediately on my client, though, since the client can assume it isn't being hacked and no cheating is going on) but the other players are going to see the effects of the latency no matter what you do. This optimizes for the best visual experience on the local client when attacking, which is usually what you want (optimize for the player with the most agency in a situation to get the best player experience... usually).

Art and gameplay rules can hide the effects of latency to a large degree. There was a great GDC talk on Halo 2 and how the "armor lock" shield system included in its design a variable-time activation delay that allowed for all clients to agree that there would be a shield before the shield activated, and then each client played the animation at the appropriate local speed to make the armor appear active at the moment it would actually be active. There was latency between the clients but that fact was hidden (outside of exceptionally laggy circumstances) to players.

Overall, though, you're almost certainly going to have to give up on pixel-perfect collision over the network in the general case. The design must deal with that fact.
> 2 votes

# Answer
Networking for games is hard. Valve knows this and have shared details on how they do it for games like Counter Strike.

You should do the following:

* Perform collision detection on both the server and client. It will allow the clients to performs physics locally, whilst waiting for the authoritative response from the server.
* Do entity interpolation and possibly some input prediction on client-side. Interpolation will make moving entities smoother in case of lag spikes (high intermittent delays). Prediction is something like the first point of this list where the client *assumes* what will happen in the next frame(s).
* Make sure you send a snapshot (e.g. absolute entity world position) every once in a while to clients. This will synchronize the entities, but might cause them to "snap" a bit. This can be mediated using interpolation.

You might not have to deal with all that since there should be many game/networking libraries out there that solve these issues.
> 3 votes

---
Tags: collision-detection, ios, multiplayer
---


# Question
Title: Is there a maximum delay an UDP packet can have?
I am currently implementing a real-time network protocol for a multiplayer game using UDP. I am not having any technical difficulties, but as I always have to care about late UDP packets I am wondering just *how* late they can arrive.

I have researched the topic and have not found any mention of it, so I assume there is no technical limitation, but I wonder if common network/internet architecture (or hardware) gives an effective limitation of how late a UDP packet can be delivered.

# Answer
> 4 votes
They can be as late as "never arriving at all."

As far as what you can expect, the elapsed time drops off pretty sharply. You can assume that 99% of the time, you'll get your packet within some time *x* (if you're going to get it at all), but there will always be a possibility of some stragglers. Your actual value for *x* can be determined by experimentation, but will vary according to a lot of factors outside of your control.

If you need 99.999% assurance, then increase *x* accordingly; if you only need 90% assurance, decrease it.

From a implementation perspective, if packets arrive after a certain elapsed time, they're probably worthless anyhow, so they can be discarded.

# Answer
> 0 votes
The default Time To Live for UDP packets sent over TCP/IP networks is 128 seconds (on Windows). One can reasonably assume that a router/network adapter will no longer forward the UDP packet after this. Of course this is a default value and can differ on different software/devices. I believe the maximum possible value for TTL is 255 seconds. Note that TTL is not an UDP feature but a feature of the protocol above it. So if you're using something else than TCP/IP (which I think is unlikely in your case) you'll have to find another source.

Source: http://www.binbert.com/blog/2009/12/default-time-to-live-ttl-values/

---
Tags: networking, udp
---


# Question
Title: How can I make permanent death in a MUD seem acceptable and fair to players?
I have considered writing a MUD for years, and I have a lot of ideas my friends think are really cool (and that's how I'd hope to get anywhere -- word of mouth).

Thing is, there's one thing I have always wanted, that my friends and strangers hated: permanent death. Now, the emotional response I get to this is visceral revulsion, every time. I'm pretty sure I am the only person that wants this, or if I'm not, I'm a tiny minority.

Now, the reason I want it is because I want the actions of the players to *matter*. Unlike a lot of other MUDs, which have a set of static city-states and social institutions etc, I want the things my players do, should I get any, to actually change the situation. And that includes killing people.

If you kill someone, you didn't send them to time out, you killed them. What happens when you kill people? They go away. They don't come back in half an hour to smack talk you some more. They're gone. *Forever*.

By making death non-permanent, you make death not matter. It would be similar if a climax to a character's arc is getting a speeding ticket. It cheapens it. Non-permanent death cheapens death.

How can I: 1) Convince my players (and random people!) that this is actually a good idea?, or

2) Find some other way to make death and violence *matter* as much as it does in real life (except within the game, of course) sans character deletion? What alternatives are there out there?

# Answer
When you want perma-death to matter as much for the victim as it matters in real-life, you also need equivalent consequences for the killer.

In just about any real-life society (present or historical), murder is the crime which receives the highest punishment that society is willing to administer. In any judical system of today, a murderer is either executed themself or imprisoned for the rest of their life. That means the consequence of intentionally taking someones life practically means losing your own life. Why is this? Because no society which tolerates murder can survive in the long-term. And so won't your game.

When you want murder to matter as much in your game as it does in real-life, the consequences for the murderer need to be equivalent. When a player destroys the progress of another player, they must be aware that as a consequence the same thing will likely happen to their own character.

You could model this by permanently turning the murderer into an outlaw. NPCs will try to capture and execute them (permanently, of course) and other players might be made aware of a murderer and be allowed to perma-kill them themself without suffering the same consequences (and maybe even receive a reward).

Make sure that there is no easy and reliable way to *permanently* escape prosecution. A player might be able to avoid the consequences temporarily, but when you add any loophole which allows them to permanently wipe their crime-record, you will encounter players who abuse this method.

Example: A player might be able to avoid criminal prosecution as long as they are a personal friend of the local figure of authority. But when that person changes or decides to no longer protect them, their amnesty is revoked and they can be prosecuted again.
> 10 votes

# Answer
I can't believe no one has mentioned successful MMOs centered around PVP permadeath: **DayZ** and **Eve Online** (or almost-permadeath in Eve's case). These are games that *reward* player killing, and have the entire gameplay experience built around that ability. If you are familiar with these games, you can stop reading and use them as case studies on how a permadeath MUD can work. I want to offer these as a counterpoint to the prevailing attitudes in the other answers, which seem to assume that player killing is a bad thing, even going so far as to suggest *punishing* the killer.

Here's a short description of the two games:

* DayZ is an MMO FPS about individuals surviving a zombie apocalypse. Players must scavenge for food and weapons, can work together but also kill each other to steal supplies - there are no restrictions on what players can do to each other. Players are paranoid and terrified of each other, and there are plenty of anecdotes of slavery, hostage-taking and of course, killing for fun.
* Eve Online is a space combat MMO where there is PVP and death can result in the loss of everything apart from character stats, but in a game where one must purchase ships at huge cost, the character means little. There is an NPC law-enforcement faction that attacks player killers which creates de-facto safe areas, but most gameplay takes place in lawless areas where piracy and open warfare between player factions are the norm. The huge range of ships and combined arms warfare encourages the formation of large player "corporations", but there are also many stories of political intrigue, shifting alliances, scams and espionage.

Giving players the ability to cause massive harm to each other leads to polarising opinions, and creates a large psychological factor to the gameplay. Permadeath alone makes the game take on a whole new tone, since even trivial choices (such as whether to quaff a potion) can have drastic consequences, so the game becomes more cerebral. Adding player killing to that mix makes things even more severe: not only do you have to weigh the benefits and costs of killing another player, you must also consider whether *she* considers killing *you* worthwhile, or even worse: whether she just wants to kill you for fun.

Another question to consider is: why is it that DayZ feels like the wild west, whereas Eve Online is like warring nations? In these games where there is so much player freedom (including the freedom to kill each other), **tiny changes in gameplay have huge consequences**. Things like whether players can kill each other in a split second, whether the combat favours small or big groups, whether there are safe areas, these all have a big impact on how players treat each other - suspicion, paranoia, the size and stability of groups. More learned folks than I have studied such phenomena, so I won't dwell here: find more reading online if you are interested. Bottom line is, PVP permadeath has huge implications for the game, and your level of control as a game designer; more often than not you'll feel like running a social experiment than crafting a world.

So to finally answer your questions:

1. *How can I convince people that PVP permadeath is good?*

You can start by pointing to examples of very successful games that have them. Keep in mind that they're not everyone's cup of tea, and different people have different thresholds for what they deem fair or acceptable. The Bartle Test is one way of looking at this: PVP permadeath greatly favours the *Killers*, which is necessarily at the expense of others (mostly *Achievers*), and different people like different things - not everyone is a Killer. A lot of people also won't find permadeath from other players acceptable or fair, but that's simply because people have different thresholds for fairness. One player's "unfair" is another's "that's just part of the game", whether that's an inconveniently-placed obstacle, a ruthless RNG, or player killing.
2. How can I find some other way to make death and violence matter as much as it does in real life (without permadeath)?

There's a range of punishments you can mete out, up to and including permadeath. Any kind of loss (XP, property or time) can be drastic and hence meaningful. Unfortunately the "death matters" that you want requires punishing the player, since only the fear of death (or great loss) can produce that kind of trepidation in normal gameplay, and the power-tripping satisfaction of having caused loss to another player characteristic of Killer types. Simply rewarding killers without punishing the killed won't produce these results. In the same sense, I don't see how punishing killers can be productive, since it removes the utilitarian motivation for killing and only leaves the purely sadistic.

Finally I want to point out the futility in making a game "like real life". Real life has permadeath, but it also has **no restarting**. That is what really makes life and death matter in real life.
> 6 votes

# Answer
The inherent problem here is that your character's life is no longer in your hands. Gamers can be very competitive, and it only takes one person that decides to be a royal d\*** to ruin the experience for everyone. Because of this, part of the question should be, "How do I ensure that players don't run wild perma - killing everyone they can?" Because of this, I would probably resolve this such that if a player beats another in a fight, they can take a non-trivial penalty to perma-kill the loser. This keeps the power in the hands of the strong, while preventing it from going rampant. It also helps to subtly push your players towards acting with respect towards other players, especially if the cost is relatively high.

With the prevalence of player killers in games regardless of the trivialities of death, many are turned off of perma-death because it is difficult to regulate. Penalties for doing it turn it into a self regulating system.

The only other feasible possibility would require a proportionally large selection of moderators, and that would require too much maintenance.
> 1 votes

# Answer
The question is what kind of game you want to make. MMORPGs typically depend heavily on grinding a single character for weeks, making progressing the only gameplay element of it. In this case killing a character is nothing but a punch into the guts, there is no value in it, it just needlessly punishes players.

Well, first of all you could remove most of the grind (stat/gear wise) and make any unlocks account-wide (game changing & visual stuff), this would make perma-death much less punishing as you could just make a new character and reach the same level again quickly.

Further you could make death much more common and randomizing the content (for example picking a random spawn position every time), this would put much more emphasis on survival and make it feel a bit more like a roguelike, which is genre permadeath worked pretty very well for in the past.

Note that player behavior is heavily influenced by gameplay, if you don't want players to try to kill other players make it a unrewarding experience, or give bonuses for helping strangers and penalties for betraying them.
> 1 votes

# Answer
The key to a good permadeath system is to make the player feel in control, and not feel *complete* sense of loss when permadeath occurs.

Consider the analogy of a well-designed platformer. A well-designed platformer should not be trivial to complete: there should be some tricky jumps that require some skill in there, to get the player's adrenaline going. But when you fail a tricky jump, you should not feel like the game was *unfair*, you should feel like the fault was yours and be able to see it. And a well-designed platformer starts you over on your next life far enough away from the failure point that you need to work to get back there, but not so far that you have to repeat *everything* up to that point.

Preserving those sensibilities can scale to permanent death as well. Tuning this is pretty difficult, of course (especially when you start to have other players involved, and those other players can potentially contribute to the death of any other player characters). Generally, this means:

* Designing the game system so the player has ample ability to avoid death through skillful play. Undetectable instant-kill traps are, consequently, not a very good idea. Similarly you want players to be able to learn from any failures to stay alive, so that less-skilled players can build up the requisite skill to survive such an encounter in the future. Make sure there are good "escape hatch" skills that every player has access to that can get them out of tricky situations, perhaps with appropriate foresight.
* Provide additional venues of progression independent of individual characters that continue even if an individual character dies. Roguelike games tend to do this with their "inherited monster memory" features, and you do similar things. Perhaps new characters get to inherit selected gear from the old character, or selected personality traits or skills. Allow the recruitment of followers who can assume the role of your "main" character when your previous character dies.

Multiplayer contexts make it harder to build these kinds of systems (especially the first one). However, you can simply make the decision that players cannot directly engage in combat with others, if you want. This solves a large class of player-versus-player permadeath problems related to griefing (high-skill, high-level characters preying on the weak neophytes).

If you want to allow player-versus-player direct combat, make sure there is a significant cost and consequence to killing another player. The balance here should generally be weighted heavily towards the player who *doesn't* want to go around killing other players, so any player who does so is significantly disadvantaged.

(Generally, I feel like the idea of combining permadeath and player-versus-player combat is usually just a recipe for disaster, since it only enables "fun" for the griefers; co-operative play tends to be much more rewarding in my experience -- especially with permanent death. But that's just my opinion.)
> 1 votes

# Answer
Recovering a character's body from a state of death might leave permanent damage to its physiology / neurology:

* XP/memory Loss (Diablo)
* Loss of physical integrity (D&D; constitution loss on Raise Dead)
* **Loss of skills, intellect etc.**

...I find the increased chances of raising a drooling idiot from the dead to be quite attractive as a gameplay dynamic, if not as a mental image. Not only does it make death count, it also has an element of puerile humour to it, which a MUD could tap into. What more could you ask?
> 1 votes

# Answer
There are some great points above, but I'm not seeing much along the lines of making a separation between player and characters in order to allow for deaths that can hurt but not necessarily unroll days/weeks/years of play.

For instance, let's say your game was about a zombie apocalypse. Instead of the player *being* their character, they could *hire* characters to fight zombies for their company. Success brings money and prestige for the company, allowing access to better weapons, more qualified mercs, etc. You could balance the situation in a way such that a veteran zombie slayer is somebody you do not want to lose - he's leveled up, he has unique skills that only come from surviving tough fights, etc. But maybe it only takes a short time (real-life) to get a rookie to that state.

This separation combined with the pain of death also affects other options available to players. For instance, your veteran is bitten during a rough battle. Do you chop of an arm hoping to avoid the infection? Burn him and start fresh? Spend a huge amount of your company's XP/prestige/money/whatever to get a cure? Just send him into a hopeless battle hoping for a blaze of glory that reflects well on your company? Etc.

And you get multiple factors contributing to the pain of death:

* The progression from rookie to veteran is how you decide the value of keeping mercenaries alive. If you can go into two battles and have a kick-ass warrior, death isn't a very big deal. If it takes six months to max out, on the other hand, you have a pretty significant loss on a death.
* The company rewards that are separate from the mercenary help temper the losses when death does inevitably happen. If successes increase a ton of company stats (money, prestige, maybe XP unlocking specially skills for future mercs, etc), death is less important. If successes only help a tiny bit, death is more important.

Balancing these two factors can be a living, ever-changing goal as you tweak rules to maximize enjoyment without necessarily sacrificing fear of death. If you want hard-core death rules, maybe it does take a player six months to get a single mercenary to an uber-high level. But the rewards to the company could be set up such that a high-level merc is providing tons of tertiary bonuses so that when he's dead, leveling up the next merc is only a five- or four-month process. Or maybe you have unlocked a new, higher level cap.

As an aside, I'm a huge fan of perma-death games like Nethack, but I always felt like it would be much better if each run-through left me with something extra based on my achievements. For instance, killing 100 orcs in a single game could mean unlocking a permanent +10% damage boost to orcs.
> 1 votes

---
Tags: multiplayer, mmo, mud
---


# Question
Title: How to avoid tons of `instanceof` in collision detection?
Consider a simple game with 4 kinds of entities: Robots, Dogs, Missiles, Walls.

Here's a simple collision-detection mechanism in psuedocode: *(I know, `O(n^2)`. Irrelevant for this question).*

```
for(Entity entityA in entities){
    for(Entity entityB in entities){
        if(collision(entityA, entityB)){
            if(entityA instanceof Robot && entityB instanceof Dog) entityB.die();
            if(entityA instanceof Robot && entityB instanceof Missile){
                entityA.die();
                entityB.die();
            }
            if(entityA instanceof Missile && entityB instanceof Wall) entityB.die();
            // .. and so on
        }
    }
}

```

Obviously this is very ugly, and will get bigger and harder to maintain the more entities there are, and the more conditions there are.

One option to make this better is to have separate lists for each kind of entity. For example a Robots list, a Dogs list etc. And than check for collisions of all Robots with Dogs, and all Dogs with Walls, etc.

This is better, but I still don't think it's good.

So my question is:

The collision detection system spotted a collision. Now what?

What is the common way to react to the collision? Should the system notify the entity itself that it collided with something, and have it decide for itself how to react? E.g. `entityA.reactToCollision(entityB)`.

Or is there some other solution?

# Answer
> 1 votes
> What is the common way to react to the collision? Should the system notify the entity itself that it collided with something, and have it decide for itself how to react? E.g. entityA.reactToCollision(entityB).

Yes.

Send a message to both entities. Let them figure out how they want to respond to any particular type of collision. That removes the decision from the central location in collision to the entities that actually encapsulate the relevant game logic.

# Answer
> 1 votes
> What is the common way to react to the collision? Should the system notify the entity itself that it collided with something, and have it decide for itself how to react? E.g. `entityA.reactToCollision(entityB)`.

Yes, but you could also do it the other way around. Have every entity have a default effect on its collidee, e.g. that a missile kills whatever it hits and also kills itself (as opposed to that a robot dies from being hit by a missile). You can do this via overridden (virtual) methods in your entities, so you won't need `instanceof`.

Then you could add another layer of indirection (`Entity.shouldDieFromExplosiveDamage()` instead of `Entity.die()`), and have your missile-resistant super robots react differently, or your dog bite have no effect on all robots.

---
Tags: collision-detection, oop
---


title: Multiple enemy array in LibGDX

text:
# Question
Title: Multiple enemy array in LibGDX
I am trying to make a multiple enemy array, where every 30 secods a new bullet comes from a random point. And if the bullet is clicked it should disapear and a pop like an explosion should appear. And if the bullet hits the ball then the ball pops. so the bullet should change to a different sprite or texture. same with the ball pop.

But all that happens is the bullet if touched pops and nothing else happens. And if modified then the bullet keeps flashing as the update is way too much.

I have added COMMENTS in the code to explain more on the issues.

below is the code. if more code is needed i will provide.

Thank you

```
public class GameRenderer {

private GameWorld myWorld;
private OrthographicCamera cam;
private ShapeRenderer shapeRenderer;
private SpriteBatch batcher;

// Game Objects
private Ball ball;
private ScrollHandler scroller;
private Background background;
private Bullet bullet1;
private BulletPop bPop;

private Array<Bullet> bullets;

    // This is for the delay of the bullet coming one by one every 30 seconds.
/** The time of the last shot fired, we set it to the current time in nano when the object is first created */
double lastShot = TimeUtils.nanoTime();
  /** Convert 30 seconds into nano seconds, so 30,000 milli = 30 seconds */
 double shotFreq = TimeUtils.millisToNanos(30000);

// Game Assets
private TextureRegion bg, bPop;
private Animation bulletAnimation, ballAnimation;
private Animation ballPopAnimation;

public GameRenderer(GameWorld world) {
    myWorld = world;
    cam = new OrthographicCamera();
    cam.setToOrtho(true, 480, 320);

    batcher = new SpriteBatch();
    // Attach batcher to camera
    batcher.setProjectionMatrix(cam.combined);

    shapeRenderer = new ShapeRenderer();
    shapeRenderer.setProjectionMatrix(cam.combined);

            // This is suppose to produce 10 bullets at random places on the background.
    bullets = new Array<Bullet>();
    Bullet bullet = null;
    float bulletX = 00.0f;
    float bulletY = 00.0f;
    for (int i = 0; i < 10; i++) {
        bulletX = MathUtils.random(-10, 10);
        bulletY = MathUtils.random(-10, 10);
        bullet = new Bullet(bulletX, bulletY);

        AssetLoader.bullet1.flip(true, false);
        AssetLoader.bullet2.flip(true, false);

        bullets.add(bullet);
    }

    // Call helper methods to initialize instance variables
    initGameObjects();
    initAssets();
}

private void initGameObjects() {
    ball = GameWorld.getBall();
    bullet1 = myWorld.getBullet1();
    bPop = myWorld.getBulletPop();
    scroller = myWorld.getScroller();
}

private void initAssets() {
    bg = AssetLoader.bg;
    ballAnimation = AssetLoader.ballAnimation;
    bullet1Animation = AssetLoader.bullet1Animation;
    ballPopAnimation = AssetLoader.ballPopAnimation;
}

    // This is to take the bullet away when clicked or touched.
public void onClick() {
    for (int i = 0; i < bullets.size; i++) {
        if (bullets.get(i).getBounds().contains(0, 0))
            bullets.removeIndex(i);
    }
}

private void drawBackground() {
    batcher.draw(bg1, background.getX(), background.getY(), background.getWidth(), backgroundMove.getHeight());
}

public void render(float runTime) {

    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);

    batcher.begin();
    // Disable transparency
    // This is good for performance when drawing images that do not require
    // transparency.
    batcher.disableBlending();

    drawBackground();

    batcher.enableBlending();

            // when the bullet hits the ball, it should be disposed or taken away and a ball pop sprite/texture should be put in its place
    if (bullet1.collides(ball)) {
                    // draws the bPop texture but the bullet does not go just keeps going around, and the bPop texture goes.
        batcher.draw(AssetLoader.bPop, 195, 273);
    }

    batcher.draw(AssetLoader.ballAnimation.getKeyFrame(runTime), ball.getX(), ball.getY(), ball.getWidth(), ball.getHeight());

           // this is where i am trying to make the bullets come one by one, and if removed via the onClick() then bPop animation
           // should play but does not???
    if(TimeUtils.nanoTime() - lastShot > shotFreq){
         // Create your stuff
        for (int i = 0; i < bullets.size; i++) {
            bullets.get(i);
            batcher.draw(AssetLoader.bullet1Animation.getKeyFrame(runTime), bullet1.getX(), bullet1.getY(), bullet1.getOriginX(), bullet1.getOriginY(), bullet1.getWidth(), bullet1.getHeight(), 1.0f, 1.0f, bullet1.getRotation());
            if (bullets.removeValue(bullet1, false)) {
                batcher.draw(AssetLoader.ballPopAnimation.getKeyFrame(runTime), bPop1.getX(), bPop1.getY(), bPop1.getWidth(), bPop1.getHeight());
            }
        }
         /* Very important to set the last shot to now, or it will mess up and go full auto */
         lastShot = TimeUtils.nanoTime();
      }

    // End SpriteBatch
    batcher.end();
}
}

```

Thank you

# Answer
> 1 votes
I don't know how the Bullet class works, so I am just doing this from your code, but in your if statement:

```
    if (bullet1.collides(ball)) {
                // draws the bPop texture but the bullet does not go just keeps going around, and the bPop texture goes.
    batcher.draw(AssetLoader.bPop, 195, 273);
}

```

You are not actually removing the bullet which is why the bullet keeps flying.

Also, in the loop for the bullets:

```
for (int i = 0; i < bullets.size; i++) {
        bullets.get(i);
        batcher.draw(AssetLoader.bullet1Animation.getKeyFrame(runTime), bullet1.getX(), bullet1.getY(), bullet1.getOriginX(), bullet1.getOriginY(), bullet1.getWidth(), bullet1.getHeight(), 1.0f, 1.0f, bullet1.getRotation());
        if (bullets.removeValue(bullet1, false)) {
            batcher.draw(AssetLoader.ballPopAnimation.getKeyFrame(runTime), bPop1.getX(), bPop1.getY(), bPop1.getWidth(), bPop1.getHeight());
        }
    }

```

You aren't storing bullets.get(i) anywhere. You should be writing:

```
for (int i = 0; i < bullets.size; i++) {
        Bullet b = bullets.get(i);//replace bullet1 before the if statement with b
        batcher.draw(AssetLoader.bullet1Animation.getKeyFrame(runTime), bullet1.getX(), bullet1.getY(), bullet1.getOriginX(), bullet1.getOriginY(), bullet1.getWidth(), bullet1.getHeight(), 1.0f, 1.0f, bullet1.getRotation());
        if (bullets.removeValue(bullet1, false)) {
            batcher.draw(AssetLoader.ballPopAnimation.getKeyFrame(runTime), bPop1.getX(), bPop1.getY(), bPop1.getWidth(), bPop1.getHeight());
        }
    }

```

And this if statement:

```
if (bullets.removeValue(bullet1, false))

```

Should be moved outside the loop as you only need to call it once. When the bullet is destroyed (i.e. in the collides if statement).
Your onClick() method should probably not be removing the bullet, if you want to do the explosion animation like you are doing. It could set that bullet to hidden, then in your render method you find all the hidden bullets and continue their explosion animation (although you might want to store which frame they're on somewhere.
They're might be some stuff that I missed, but I hope this helps a bit.

---
Tags: java, android, libgdx
---


# Question
Title: Drawing flaming letters in 3D with OpenGL ES 2.0
I am a bit confused about how to achieve this. What I want is to "draw with flames". I have achieved this with textures successfully, but now my concern is about doing this with particles to achieve the flaming effect. Am I supposed to create a path along which I should add many particle emitters that will be emitting flame particles? I understand the concept for 2D, but for 3D are the particles always supposed to be facing the user?

Something else I'm worried about is the performance hit that will occur by having that many particle emitters, because there can be many letters and drawings at the same time, and each of these elements will have many particle emitters.

**Update 1:**

A more detailed explanation:

I have a path of points, which is my model. Imagine a dotted letter "S" for example. I want make the "S" be on fire. The "S" is just an example it can be a circle, triangle, a line, pretty much any path described by my set of points.

For achieving this fire effect I thought about using particles. So I am using a program called "Particle Designer" to create a fire style particle emitter. This emitter looks perfect on 2D on the iphone screen dimensions. So then I thought that I could probably draw an S or any other figure if i place many particle emitters next to each other following the path described.

To move from the 2D version to the 3D version I thought about, scaling the emitter (with a scale matrix multiplication in its model matrix) and then moving it to a point in my 3D world. I did this and it works. So now I have 1 particle emitter in the 3D world.

My question is, is this how you would achieve a flaming letter? Is this too inefficient if i expect to have many flaming paths on my world? Am i supposed to rotate the particle's quad so that its always looking at the user? (the last one is because i noticed that if u look at it from the side the particles start to flatten out)

**Update 2:**

I tested this, by having multiple particle emitters and altho they look reasonably well the more particles i have the worst the FPS get. A common scenario will be having at lest around 50 different lines/letters at the same time.

Currently the particle emitter is on the cpu. It calculates the position of each of the particle's vertices and feeds the new vertices to the gpu. This works well for a few emitters, but not for enough to have "flaming" letters all around.

I was considering about moving the calculations performed by the particle emitter to the GPU in a shader but this seems a bit complicated since each particle has its own state and is modified with a time delta. In the CPU it is simply an object that changes its value with the previous value as reference, but the GPU shader is just run once per draw call isn't it?

# Answer
Yes, it is possible, and it has been done before many times.

What you want are called **Billboards**, they are simple planes that are transformed to always look at the camera. There is an implementation of it on GLSL Programming Wikibook.

You would want emitters which emits particles (which are billboards), there is no need for moving anything to the GPU, emitting particles is not that expensive, what is expensive is **drawing** hundreds or even *thousands* of particles on the screen, also, make sure to use a very light particle class and re-use old ones with the **`Object Pool` design pattern**, since garbage collection should hit you hard otherwise.

For your shaders, **make the billboard calculation on the vertex shader**, it should move some work to the GPU, make sure you only do not over-engineer the shaders, since they will be called to a lot of particles!

This should already leave you with performance to draw thousands of particles on the screen and still have performance for other game stuff. Even if it ends up eating all your mobile precious CPU, then make the emitters **emit less particles**. Most of the time you can still obtain a good effect with half the particles, be wise, spend performance only where it's necessary.

Your bigger problem will be arranging the emitters to make them feel like real text. Here are some options on the top of my head:

* Get a bitmap texture of low resolution, like 10px tall characters, for every gliph, scan the pixels, for each pixel set, record it's coordinates. Save all the coordinates is saved for all the gliphs. Scale them up later, use them as offsets when placing emitters on the world later.
* Get a vector font library, get the paths of each glyph, record even-spaced points for each path of the glyph. Use the points as offsets when placing emitters on the world later.
* Design a set of emitters on some software, or even with pencil and paper, write their values on some file or even hard code on arrays, use the points as offsets...
* Mix the last option with any of the two first. Generate then tweak it.

This should give you a very good start, good luck!
> 1 votes

---
Tags: iphone, opengl-es2, particles
---


# Question
Title: How to implement a simple bullet trajectory
I searched and searched and although it's a fair simple question, I don't find the proper answer but general ideas (which I already have).

I have a top-down game and I want to implement a gun which shoots bullets that follow a simple path (no physics nor change of trajectory, just go from A to B thing).

a: vector of the position of the gun/player. b: vector of the mouse position (cross-hair). w: the vector of the bullet's trajectory.

So, w=b-a. And the position of the bullet = \[x=x0+speed*time*normalized w.x , y=y0+speed\*time * normalized w.y\].

I have the constructor:

```
public Shot(int shipX, int shipY, int mouseX, int mouseY) {
//I get mouse with Gdx.input.getX()/getY()
...

  this.shotTime = TimeUtils.millis();

  this.posX = shipX;
  this.posY = shipY;

  //I used aVector = aVector.nor() here before but for some reason didn't work
  float tmp = (float) (Math.pow(mouseX-shipX, 2) + Math.pow(mouseY-shipY, 2));
  tmp = (float) Math.sqrt(Math.abs(tmp));

  this.vecX = (mouseX-shipX)/tmp;
  this.vecY = (mouseY-shipY)/tmp;
}

```

And here I update the position and draw the shot:

```
public void drawShot(SpriteBatch batch) {
  this.lifeTime = TimeUtils.millis() - this.shotTime;

  //position = positionBefore + v*t
  this.posX = this.posX + this.vecX*this.lifeTime*speed*Gdx.graphics.getDeltaTime();
  this.posY = this.posY + this.vecY*this.lifeTime*speed*Gdx.graphics.getDeltaTime();
...
}

```

Now, the behavior of the bullet seems very awkward, not going exactly where my mouse is (it's like the mouse is 30px off) and with a random speed. I know I probably need to open the old algebra book from college but I'd like somebody says if I'm in the right direction (or points me to it); if it's a calculation problem, a code problem or both. Also, is it possible that Gdx.input.getX() gives me non-precise position? Because when I draw the cross-hair it also draws off the cursor position.

Sorry for the long post and sorry if it's a very basic question. Thanks!

# Answer
> 1 votes
In shoot function you can find angle between player and mouse position

```
deltaX = mouseX - shipX
deltaY = mouseY - shipY
angle = atan2(deltaY, deltaX)

```

Then you can use that angle to update bullet position:

```
posX = posX + speed * deltaTime * cos(angle)
posY = posY + speed * deltaTime * sin(angle)

```

# Answer
> 0 votes
I use the same calculation and I don't have the same issue, perhaps the error is with the `Gdx.input.getX()`. I am not familiar with libgdx, so I can't comment directly on this. Maybe you can test this by shooting at an exact known location. One suggestion would be to color a pixel at say (300, 300), and shoot directly on it then check what the mouseX, and mouseY values.

I like how you calculate the trajectory separate from the draw since this operation only needs to be done once. One tip, the result of any number squared will never be negative so there is no need to use `Math.abs()`.

One more suggestion, if you are using a pointy image, like an arrow, as opposed to something round, like a fireball, you can rotate the image to match the trajectory. I took the liberty of rewriting something things for clarity of intent. You can generate a rotation angle and then rotate the sprite with this value.

```
private float rotation;
...

public Shot(int shipX, int shipY, int mouseX, int mouseY){
    this.posX = shipX;
    this.posY = shipY;

    int xTrajectory = mouseX - shipX;
    int yTrajectory = mouseY - shipY;
    float length = (float)Math.sqrt(xTrajectory*xTrajectgory + yTrajectory*yTrajectory);

    this.vecX = xTrajectory/length;
    this.vecY = yTrajectory/length;

    float angle = (float)Math.acos(vecX);

    if (yTrajectory > 0) {
        rotation = (float)Math.toDegrees(angle);
    }
    else {
        rotation = (float)Math.toDegrees(-angle);
    }
}

...
sprite.setRotation(rotation);

```

EDIT: I was curious so I looked this up. If you are using a custom cursor, you can set the hotspot. If the hotspot is off this could be the error you are seeing. With a cross hair the hot spot should be in the center, as opposed to a arrow, where the hot spot should be at the tip.

---
Tags: libgdx, bullet-physics, linear-algebra
---


# Question
Title: Connect players with same phone language settings
I am working on a turn-based multiplayer game using game center. The game also use Spanish localisation. It is enabled by reading the device language settings. Now my requirement is: When i start a turn based match, my opponent should have the same language setting in his/her phone as I am having. How can I make this possible.

I use the following code to connect

```
- (void)findTurnBasedMatchWithViewcontroller:(UIViewController *)viewController forDelegate:(id)argDelegate {
self.delegate = argDelegate;
presentingViewController = viewController;
GKMatchRequest *request = [[GKMatchRequest alloc] init];
request.minPlayers = 2;
request.maxPlayers = 2;
[manager setCurrentGameType:kTurnBased];
GKTurnBasedMatchmakerViewController *mmvc = [[GKTurnBasedMatchmakerViewController alloc] initWithMatchRequest:request];
mmvc.turnBasedMatchmakerDelegate = self;
mmvc.showExistingMatches = NO;
[presentingViewController presentViewController:mmvc animated:YES completion:^(void) {

 }];
}

```

# Answer
You can do this by setting the `request.playerGroup` property to different values depending on the users language. An excerpt from the documentation of GKMatchRequest:

> playerGroup
>
> A number identifying a subset of players allowed to join the match.
>
> @property(nonatomic, assign) NSUInteger playerGroup
>
> If your game sets the playerGroup property, only players whose requests share the same playerGroup value are automatched by Game Center. The value of a player group is arbitrary.
> 0 votes

---
Tags: ios
---


title: Failing Screen Resize Method

text:
# Question
Title: Failing Screen Resize Method
So I want my game to draw to a specific "optimal" size and then be stretched to fit screens that are a different size. I'm using LibGDX and figured that I could just draw everything to a FrameBuffer and then resize that buffer to the appropriate size when drawing it to the actual display. However, my method does not work, it just results in a black screen with the top right quarter of the screen white.
Intermediary is the FBO, interMatrix is a Matrix4 object, and camera is an OrthographicCamera.

```
    @Override
public void render()
{
    // update actors
    currentStage.act();

    //render to intermediary buffer
    batch.setProjectionMatrix(interMatrix);

    intermediary.begin();
    batch.begin();

    currentStage.draw();

    batch.flush();
    intermediary.end();

    //resize to actual width and height
    Sprite s = new Sprite(intermediary.getColorBufferTexture());
    s.flip(true, false);

    batch.setProjectionMatrix(camera.combined);

    batch.draw(s.getTexture(), 0, 0, width, height);

    batch.end();
}

```

These are the constructors for the above mentioned objects (GAME\_WIDTH and HEIGHT are the "optimal" settings, width and height are the actual sizes, which are the same when running on desktop). intermediary = new FrameBuffer(Format.RGBA8888, GAME\_WIDTH, GAME\_HEIGHT, false);

```
    interMatrix = new Matrix4();
    camera = new OrthographicCamera(width, height);

    interMatrix.setToOrtho2D(0, 0, GAME_WIDTH, GAME_HEIGHT);

```

Is there a better way of doing this or is this a viable option and how do I fix what I have?

**Edit**
So I changed some things around and it *mostly* works. This is my code now:

```
        sv = new StretchViewport(GAME_WIDTH, GAME_HEIGHT);
    currentStage = new StageMainMenu(sv);
}

@Override
public void render()
{
    // update actors
    currentStage.act();

    //render
    currentStage.draw();
}

```

However this results in some peculiar behavior when changing the window size, that I can't explain. This is what happens:
There should only be one "Press me!" button. The top button of the two does not seem to be scaled correctly and also flickers, but it should not be showing up at all...

# Answer
> 2 votes
There's no need to use a framebuffer for this, as you're already using a Scene2D, which automatically does the proper scaling for you.

You may be asking "LOL I've been using it all this time and haven't seen a single stretching!"

It is easy, when you create your Stage, instead of instantiating it with

```
stage = new Stage(new ScreenViewport());

```

do:

```
stage = new Stage(new StretchViewport(optimalWidth, optimalHeight));
stage = new Stage(new FitViewport(optimalWidth, optimalHeight)); //Or this

```

Play around with it, each viewport kind behaves differently, and only with testing you'll know what's best for your game.

For more info, take a look at Scene2D page on LibGDX wiki

Now for custom drawing (say you want a spriteBatch doing thing besides the Stage2D, just like your code suggests), use and abuse these functions:

This is it! Now you may have enough info, good luck on your way!

EDIT:

This should belong to another question, but anyway, you're forgetting to clear the screen :P Try this way:

```
public void render()
{
    // update actors
    currentStage.act();

    //render
    Gdx.gl20.glClearColor(backColor.r, backColor.g, backColor.b, 0.0f);
    Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT);
    currentStage.draw();
}

```

(If it doesn't work, try changing gl20 to gl10 or gl30. It depends on the version of GLES you're using)

---
Tags: java, libgdx, rendering, spritebatch
---


# Question
Title: How can I create a buffer suitable for dynamic updates in SharpDX?
I want to set a buffer that is updated every frame but can't figure it out, what i have to do.

The only working thing i have is this:

```
mdexcription = new BufferDescription(Matrix.SizeInBytes * Matrices.Length, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0);
instanceBuffer = SharpDX.Direct3D11.Buffer.Create(Device, Matrices, mdexcription);

vBB = new VertexBufferBinding(instanceBuffer, Matrix.SizeInBytes, 0);
DeviceContext.InputAssembler.SetVertexBuffers(1, vBB);

```

Draw:

```
//Change Matrices (Matrix[]) every frame...
instanceBuffer.Dispose();
instanceBuffer = SharpDX.Direct3D11.Buffer.Create(Device, Matrices, mdexcription);

vBB = new VertexBufferBinding(instanceBuffer, Matrix.SizeInBytes, 0);
DeviceContext.InputAssembler.SetVertexBuffers(1, vBB);

```

I guess Dispose() and creating a new buffer is slow and can be done much faster.

I've read about DataStream but i do not know, how to set this up properly.

What steps do i have to do to set up a DataStream to achieve fast every-frame update?

---

Edit:

Finally got it. I used that:

```
mdescription = new BufferDescription(Matrix.SizeInBytes * Matrices.Length, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0);
instanceBuffer = SharpDX.Direct3D11.Buffer.Create(Device, Matrices, mdescription);

vBB = new VertexBufferBinding(instanceBuffer, Matrix.SizeInBytes, 0);
DeviceContext.InputAssembler.SetVertexBuffers(instSlot, vBB);

```

Draw:

```
DataStream stream;
var dataBox = DeviceContext.MapSubresource(instanceBuffer, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out stream);
stream.WriteRange(Matrices);
DeviceContext.UnmapSubresource(instanceBuffer, 0); //to update the data on GPU

stream.Dispose();

```

# Answer
> 4 votes
There are two basic ways to update a buffer.

1. Use `DeviceContext.UpdateSubresource()`. `source` is your source data, in the form of a `DataBox` (you can pass most value types and arrays as `DataBox`), and `resource` is your vertex buffer.

This is the easiest way to copy small data in one pass, and I use it mostly for updating constant buffers.

In your case it could be:

```
DeviceContext.UpdateSubresource(yourMatrixArray, yourVertexBuffer);

```
2. Use `DeviceContext.MapSubresource`. `resource` is your vertex bufffer, `mode` is the way you want to update your data, `flags` are obviously flags, and you get a `DataStream` (inherits from `Stream`) which you can use to copy your data.

I use this when I'm updating complex data that may have complex structures, like vertex buffers.

In your case, it could be:

```
DataStream dataStream;

ImmediateContext.MapSubresource(yourVertexBuffer, MapMode.WriteDiscard, MapFlags.None, out dataStream);

dataStream.Write(...);

```

Don't forget to unmap the resource when finished.

```
dataStream.Dispose(); // Not 100% sure if necessary
ImmediateContext.UnmapSubresource(yourVertexBuffer, 0);

```

There are lots of other options, like when you're using subresources and stuff. Make sure you read the docs.

---
Tags: sharpdx
---


# Question
Title: Is it ok to destroy mesh directly from MeshFilter in Unity?
```
Mesh.Destroy(myGameObject.GetComponent<MeshFilter>());

```

May it cause any problems or undefined behaviour? (the reason I ask this is that I'm trying to destroy an exiting component which is returned from function.

# Answer
You're not destroying the mesh. You're using the `Destroy` method of the `Mesh` class, which is inherited from the `Object` class. Then you're calling that on the `MeshFilter` component of the game object. This doesn't destroy the mesh, it's going to destroy the `MeshFilter` component from your game object. Destroying in this way will delay the destroy until after the update loop, so, unless you're referencing the meshfilter yourself somewhere else, you won't have any problems.

It's OK to destroy a component in this way, but you can make it more clear with:

```
Destroy(myGameObject.GetComponent<MeshFilter>());

```

If you want to destroy the mesh, you'd do something like:

```
Destroy(myGameObject.GetComponent<MeshFilter>().mesh);

```

Which should destroy the instantiated mesh for that mesh filter. You'll have to do some testing around this, but I'm fairly sure Unity can handle its mesh being destroyed while still in use by the mesh filter.
> 2 votes

---
Tags: c#, unity, mesh
---


# Question
Title: Cocos2d-x v3.1 for WinPhone 8 auto change texture after resumed from background
I have some sprites in my game (for Windows Phone 8). These are my steps to reproduce the problem:

1. Open game
2. Play (this is an optional step)
3. Press `Windows` button to send game to background
4. Press `Back` button to resume game

The problem is: After the game has resumed, some sprites exchange textures, some sprites go black (like there is no texture being bound).

I'm using cocos2dx version 3.1. Can someone help me to solve this problem?

# Answer
Try reloading your gfx again in applicationWillEnterForeground(). This works for me, but I'm still seeing some issues with rendermodes occasionally not being quite correct after resuming.
> 1 votes

---
Tags: cocos2d-x
---


title: Predicted target location

text:
# Question
Title: Predicted target location
I'm having an issue with calculating the predicted linear angle a projectile needs to move in to intersect a moving enemy ship for my 2D game.

I've tried following the document here, but what I've have come up with is simply awful.

```
protected Vector2 GetPredictedPosition(float angleToEnemy, ShipCompartment origin, ShipCompartment target)
{
    // Below obviously won't compile (document wants a Vector, not sure how to get that from a single float?)
    Vector2 velocity = target.Thrust - 25f; // Closing velocity (25 is example projectile velocity)
    Vector2 distance = target.Position - origin.Position; // Range to close
    double time = distance.Length() / velocity.Length(); // Time

    // Garbage code, doesn't compile, this method is incorrect
    return target.Position + (target.Thrust * time);
}

```

I would be grateful if the community can help point out how this is done correctly.

**EDIT**

Here is my (working) method following the advice given:

```
protected Vector2 GetPredictedPosition(ShipCompartment origin, ShipCompartment target, Ship enemyShip, Ship firingShip)
{
    Vector2 targetVelocity = enemyShip.Direction * enemyShip.Thrust;
    Vector2 projectileVelocity = firingShip.Direction * 25f;

    Vector2 velocity = targetVelocity - projectileVelocity; // Closing velocity
    Vector2 distance = target.Position - origin.Position; // Range to close
    double time = distance.Length() / velocity.Length(); // Time

    return target.Position + new Vector2(Convert.ToSingle(targetVelocity.X * time), Convert.ToSingle(targetVelocity.Y * time));
}

```

# Answer
> 1 votes
Speed == a single value (like your 25).

Direction == a normalized vector pointing in the direction an object is traveling in.

Velocity == Direction * Speed. The result here is a vector.

The author of your guide is refering to a velocity vector, not a speed value.

For instance, Vector2(0,1) and Vector2(0,2) can both be thought of as velocity vectors that are going in the same direction but the 2nd one is going there twice as fast.

If you are accustom to thinking of direction as an angle as opposed to a vector, then you need to convert your direction angles to direction vectors before using this method.

```
float targetDirectionAngle = someArbirtaryAngle;
Vector2 targetDirection = new Vector2((float)Math.Cos(targetDirectionAngle ), (float)Math.Sin(targetDirectionAngle ));
targetDirection.Normalize();
Vector2 targetVelocity = targetDirection * speed;//usually speed is in pixels(units) per second

```

now `targetVelocity` is ready to plug into your method.

---
Tags: xna, c#, mathematics
---


# Question
Title: Unity: Rolling a ball around a spherical planet with forces
I'm trying to make a game in Unity where the player character is a ball (a sphere), and the game world is a planet (a very large sphere) that the ball can roll around on. The ball can be rolled in any direction, via the arrow keys. If the player holds the right arrow, the ball should roll smoothly to the right, all the way around the planet not leaving the ground, until it eventually reaches back to where it started. The camera follows the ball third person such that the ball always appears in the same position in the screen and the planet appears to be moving underneath it.

My question is, how can I use rigidbody.AddForce() to roll the ball in the way described above? What I think I need to do is to take the vector I get from taking the input values on the horizontal and vertical axes:

```
float moveX = Input.GetAxis ("Horizontal");
float moveY = Input.GetAxis ("Vertical");

Vector3 inputMovement = new Vector3 (moveX, 0.0f, moveY);

```

And rotate it somehow, so that I'm applying that vector as force to the ball but in the direction that's tangential to the point on the planet that the ball is currently on, and then apply it as force to the ball's rigidbody. So if you're looking at the planet head on, and the ball is at 3 o'clock, pressing the right arrow key should apply the force directly downwards.

Can anyone help me out here? I think it's probably really simple but I'm having trouble figuring it out exactly.

# Answer
> 1 votes
Subtract the position of the ball from the origin of the planet, that will give you the directional vector that you want. You can calculate the magnitude of the force you need to apply using simple newtonian gravity. Newton Gravity

Convert the direction into a unit vector, and multiply the magnitude of the force by the unit vector to create a force vector.

---
Tags: unity, 3d, physics, vector
---


# Question
Title: Generating Normal map from a Image with a given Albedo map
I am working on a research problem part of which involves generating normal map from a given image of a rusted object. I searched the internet for techniques to achieve the above and apparently crazybump is mentioned a lot. I tried it but it didn't produce the desirable effects. Also I am looking for a method which draws inspiration from an existing research paper not some closed source software. I turned my attention to the technique described in the this paper. Results from this technique are satisfactory for normal objects because of bias in the training data but it doesn't work very well in the case of rusted objects. After this I focussed my attention on generating Albedo map (the above problem would become more solvable if Albedo map is obtained). Fortunately I am able to generate pretty good albedo maps for images of rusted objects. I used this paper's approach to generate Albedo maps. Now I want to know a good technique to get Normal map given an image and it's corresponding Albedo map. To give you an idea of what kind of images I am working with I am attaching a sample.

Links to research material would be really appreciated. Thanks!

# Answer
> 1 votes
You could take a look at the source code implementation of the NVidia Texture Tools createNormalMap() function. Or you might even incorporate their library in your project.

Also, in the book Mathematics for 3D Game Programming and Computer Graphics there is a discussion on chapter 7 about bump mapping construction, which might be worth reading.

---
Tags: graphics, normal-mapping
---


# Question
Title: Which gaming engine can be used for pixel manipulation?
Here is the gist of where I am going with this. I work for a printer company and basically all of our input files(or output files for virtual printers) are bitmap files. We currently have a tool built in java over 10 years ago that works, but chokes on our high end 1600x1600 files.

So I was thinking, why not utilize a game engine's built-in ability to utilize the power of a gpu?

I am thinking all I would have to do is create a 1600x1600 plane, feed it the image file and draw the scene. I figure this is the easy part.

However, the hard part is reaching into the image for example and clicking the mouse on a particular pixel. Getting RGB data, converting to CYMK, making changes, converting back into RGB and then redrawing the scene. Not only that but pulling the modified texture out of memory and saving it back into a bitmap.

Is this even possible? I haven't used a game engine since college and that was opengl 2.0.

Just figured this looked like a good place to ask. Thanks.

# Answer
> 1 votes
ImageMagick has many tools for image manipulation built-in. I'm not sure what kinds of operations you want to perform, but I don't think you need a full-blown game engine to perform these manipulations. Based on your question, I'd recommend scripting ImageMagick for simple tasks.

Since it also sounds like you may want mouse interaction (click on a particular pixel), it could also make sense to include a GUI interface, which could be built in Java like your current system, and could use ImageMagick in the back-end for efficient processing.

Most game engines do not support exotic image manipulations, so you may also be looking for a tool like Photoshop or The GIMP, though The GIMP is much more limited on color space options than Photoshop.

---
Tags: textures, pixel
---


# Question
Title: Texture compression strategy for Android OpenGL ES that caters for alphas
I have a 2d Android game that is currently causing certain devices to run out of memory. I have a number of PNGs (about 10 MBs in total) that I use in the game at various times. At some points in the game, the majority of these need to be displayed at the same time.

I have tried just decreasing the resolution of my images but I am not happy with the quality after doing so.

I have read a number of posts about how to solve these memory issues and as far as I can see, texture compression is the best approach (feel free to correct me if I am wrong). I have also seen this post that covers how to determine which texture compression formats are supported on a device and I understand this part of things: https://stackoverflow.com/questions/9148795/android-opengl-texture-compression

My question is two-fold:

1. Most of my textures require alphas. I know that by default ETC1 does not support alpha, but I also know that when using ETC1 you can create a separate alpha compression as described here: http://sbcgamesdev.blogspot.com/2013/06/etc1-textures-loading-and-alpha.html. Shown in that link is how to apply the alphas using the NDK. I am battling to understand how to do this using the standard OpenGL ES Java wrappers though. Below is how I currently handle textures (i.e. no texture compression). How would I convert this to handle compressed textures where I need to load the alphas separately?

```
GLGraphics glGraphics;
FileIO fileIO;
String fileName;
int textureId;
int minFilter;
int magFilter;

public int width;
public int height;

private boolean loaded = false;

public Texture(GLGame glGame, String fileName) {
    this.glGraphics = glGame.getGLGraphics();
    this.fileIO = glGame.getFileIO();
    this.fileName = fileName;
    load();
}

public void load() {
    GL10 gl = glGraphics.getGL();
    int[] textureIds = new int[1];
    gl.glGenTextures(1, textureIds, 0);
    textureId = textureIds[0];

    InputStream inputStream = null;

    try {
        inputStream = fileIO.readAsset(fileName);
        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
        gl.glBindTexture(GL10.GL_TEXTURE_2D, textureId);
        GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
        setFilters(GL10.GL_NEAREST, GL10.GL_NEAREST);
        gl.glBindTexture(GL10.GL_TEXTURE_2D, 0);

        width = bitmap.getWidth();
        height = bitmap.getHeight();

        bitmap.recycle();
    } catch (IOException e) {
        throw new RuntimeException("Couldn't load texture '" + fileName + "'", e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                // do nothing
            }
        }
    }

    loaded = true;
}

public void reload() {
    load();
    bind();
    setFilters(minFilter, magFilter);
    glGraphics.getGL().glBindTexture(GL10.GL_TEXTURE_2D, 0);
}

public void setFilters(int minFilter, int magFilter) {
    this.minFilter = minFilter;
    this.magFilter = magFilter;

    GL10 gl = glGraphics.getGL();
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, minFilter);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, magFilter);
}

public void bind() {
    GL10 gl = glGraphics.getGL();
    gl.glBindTexture(GL10.GL_TEXTURE_2D, textureId);
}

public void dispose() {
    loaded = false;

    GL10 gl = glGraphics.getGL();
    gl.glBindTexture(GL10.GL_TEXTURE_2D, textureId);
    int[] textureIds = { textureId };
    gl.glDeleteTextures(1, textureIds, 0);
    gl.glBindTexture(GL10.GL_TEXTURE_2D, 0);
}

public boolean isLoaded() {
    return loaded;
}

public void setLoaded(boolean loaded) {
    this.loaded = loaded;
}

```
2. My understanding is that I would have to provide 4 compressed textures (one for each format) and a fall back uncompressed PNG for each of my images to support a wide range of devices. My concern is the required disk size increase that this will cause. Is there any solution to this? i.e. use compressed textures in order to lower the memory usage of my game without causing the size of the game on disk to explode?

# Answer
> 0 votes
So after looking into this quite a lot I have found that you can only really do it using shaders as @Andon M. Coleman mentioned. This, however, only works in OpenGL ES 2.0 and up.

I almost got this working in OpenGL ES 1.1 using multitexturing but eventually it became clear to me (through my own experimentation and other questions that I asked) that this was not going to work since it requires you to combine RGB channel values to get the alpha channel values.

If you want to stick to OpenGL ES 1.1, then I found that the best approach is to just compress your images that do not require alphas using ETC1. I then used quantization (via pngquant) to dramatically reduce the size and memory footprint of my images that do require alphas to be preserved. This approach has dramatically decreased my game's memory usage while still keeping the quality of the textures at a more-than-acceptable level.

---
Tags: android, opengl-es, memory-efficiency
---


# Question
Title: How do I implement multi-texturing using OpenGL ES 1.1 to combine separate RGB and alpha PKMs?
I have been trying to reduce the memory footprint of my textures in a Android game that I wrote without too much success. Based on research that I have done it seems that a good approach is to compress my textures using ETC1 since that is the mostly wided supported format for Android devices.

I am able to create the necessary PKMs from my PNGs using Mali ARM - no problems there. I can also render these PKMs just fine using ETC1Utils - again no problems so far.

The problem comes in with trying to handle alphas. I used Mali to create a separate alpha file for my PNGs, i.e. "xxx.png" is compressed into "xxx.pkm" and "xxx\_alpha.pkm". The one approach suggested to me in a different question that I asked was to use multi-texturing to combine these two textures since I can't use fragment shaders in OpenGL ES 1.1.

And this is where I am stuck. I am not too familiar with this stuff and I am not making much head way. Basically, as soon as I try to combine with my alpha texture, everything is just rendered white.

Here is a snippet of my code:

```
public class Texture {

    GLGraphics glGraphics;
    FileIO fileIO;
    String fileName;
    int textureId;
    int minFilter;
    int magFilter;

    public int width;
    public int height;

    private boolean loaded = false;

    public Texture(GLGame glGame, String fileName) {
        this.glGraphics = glGame.getGLGraphics();
        this.fileIO = glGame.getFileIO();
        this.fileName = fileName;
        load();
    }

    public void load() {
        GL10 gl = glGraphics.getGL();
        int[] textureIds = new int[2];
        gl.glGenTextures(2, textureIds, 0);
        textureId = textureIds[0];

        InputStream inputStream = null;

        try {
            inputStream = fileIO.readAsset(fileName + ".pkm");

            int rgbTexture = textureId;

            gl.glActiveTexture(GLES10.GL_TEXTURE0);
            gl.glBindTexture(GLES11.GL_TEXTURE_2D, rgbTexture);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_TEXTURE_ENV_MODE, GLES11.GL_MODULATE);

            ETC1Texture etcTexture = ETC1Util.createTexture(inputStream);
            ETC1Util.loadTexture(GLES11.GL_TEXTURE_2D, 0, 0, GLES11.GL_RGB, GLES11.GL_UNSIGNED_SHORT_5_6_5, etcTexture);

            int alphaTexture = textureId[1];

            gl.glActiveTexture(GLES11.GL_TEXTURE1);
            gl.glBindTexture(GLES11.GL_TEXTURE_2D, alphaTexture);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_TEXTURE_ENV_MODE, GLES11.GL_COMBINE);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_COMBINE_RGB, GLES11.GL_REPLACE);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_SRC0_RGB, GLES11.GL_PREVIOUS);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_OPERAND0_RGB, GLES11.GL_SRC_COLOR);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_COMBINE_ALPHA, GLES11.GL_MODULATE);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_SRC0_ALPHA, GLES11.GL_TEXTURE);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_OPERAND0_ALPHA, GLES11.GL_SRC_ALPHA);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_SRC1_ALPHA, GLES11.GL_PREVIOUS);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_OPERAND1_ALPHA, GLES11.GL_SRC_ALPHA);

            InputStream inputStreamAlpha = fileIO.readAsset(fileName + "_alpha.pkm");
            ETC1Texture etcAlphaTexture = ETC1Util.createTexture(inputStreamAlpha);
            ETC1Util.loadTexture(GLES11.GL_TEXTURE_2D, 0, 0, GLES11.GL_RGB, GLES11.GL_UNSIGNED_SHORT_5_6_5, etcAlphaTexture);

            setFilters(GL10.GL_NEAREST, GL10.GL_NEAREST);
            gl.glBindTexture(GL10.GL_TEXTURE_2D, 0);

            width = etcTexture.getWidth();
            height = etcTexture.getHeight();
        } catch (IOException e) {
            throw new RuntimeException("Couldn't load texture '" + fileName + "'", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    // do nothing
                }
            }
        }

        loaded = true;
    }

    public void reload() {
        load();
        bind();
        setFilters(minFilter, magFilter);
        glGraphics.getGL().glBindTexture(GL10.GL_TEXTURE_2D, 0);
    }

    public void setFilters(int minFilter, int magFilter) {
        this.minFilter = minFilter;
        this.magFilter = magFilter;

        GL10 gl = glGraphics.getGL();
        gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, minFilter);
        gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, magFilter);
    }

    public void bind() {
        GL10 gl = glGraphics.getGL();
        gl.glBindTexture(GL10.GL_TEXTURE_2D, textureId);
    }

    public void dispose() {
        loaded = false;

        GL10 gl = glGraphics.getGL();
        gl.glBindTexture(GL10.GL_TEXTURE_2D, textureId);
        int[] textureIds = { textureId };
        gl.glDeleteTextures(1, textureIds, 0);
        gl.glBindTexture(GL10.GL_TEXTURE_2D, 0);
    }

    public boolean isLoaded() {
        return loaded;
    }

    public void setLoaded(boolean loaded) {
        this.loaded = loaded;
    }
}

```

My main concern is the load() method. This code was put together through snippets that I have found on the web and coupled with my lack of understanding of multi-texturing in general, I have clearly gone wrong somewhere. Also note that when I render my textures I call:

```
GL10 gl = glGraphics.getGL();
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
gl.glEnable(GL10.GL_TEXTURE_2D);

camera.setViewportAndMatrices();
gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);

// call some objects that do my rendering stuff here

gl.glDisable(GL10.GL_BLEND);
gl.glDisable(GL10.GL_TEXTURE_2D);

```

When I render a texture I call the bind() method on my Texture class. As you can see, this binds to my global textureId variable which was used as the RGB PKMs ID when loading. I am not even sure if this is correct. Should I be binding to the RGB's ID or the alpha's ID? Or is that not even close to being on the right track? My problem may also relate to how I am loading the alphas using ETC1Utils - I have no idea if this approach is correct or not.

I am really quite stuck so any help pointing out where I have gone wrong and some sort of explanation about how multi-texturing is supposed to be implement to combine ETC1 alphas and RGBs would really be awesome.

# Answer
> 0 votes
Firstly, I was performing multi-texturing incorrectly. The answer for this question helped me correct my approach: Which texture do I bind to when implementing multi-texturing?

After sorting that out I eventually realised through my own experimentation and through some other questions that I asked that this is not really possible using OpenGL ES 1.1. The reason is that the alpha PKM stores its alpha values in the RGB channels and there is no decent way to combine these RGB values into a single alpha using multi-texturing.

So you need to upgrade to OpenGL ES 2.0 to be able to handle alphas with ETC1. Some more detail is given in the answer to this question: Is there a way to use the RGB channels of a texture as the alpha channel when applying multitexturing using OpenGL ES 1.1?

---
Tags: android, opengl-es, multitexturing
---


# Question
Title: How can I create a seesaw with Farseer Physics Engine?
I want to create a seesaw like in this picture:

I created two rectangular bodies, one for the diagonal rectangle and one for the little rectangle in the middle. But I don't know how to connect the two bodies. How can I do that?

How can I create a seesaw with Farseer Physics Engine 3.5?

# Answer
Use `JointFactory.CreateRevoluteJoint`, which creates a `RevoluteJoint` between two bodies.

Note that, by default, bodies connected by joints do not collide with each other (by default, joints have `CollideConnected = false`).

The Farseer samples have a few uses of revolute joints, if you search through them (although none of them are a simple seesaw).
> 1 votes

---
Tags: xna, c#, farseer-physics-engine
---


title: No animation clips in assets folder

text:
# Question
Title: No animation clips in assets folder
I'm trying to import an FBX file made in Blender into Unity so I can use the actions created in Blender in a Unity animation state machine. A lot of sites seem to suggest that simply dropping the FBX file into the assets will automatically import animation clips, but that doesn't seem to be happening. Unity does however recognize the discrete actions created.

Tutorial image:

My screen image:

I used the Blender export settings "Include Animation" and "All actions", but not "Include Default Take" as people recommend.

For reference, I'm trying to follow the animator controller tutorial at unity3d.com

How can I retrieve my animation clips from the fbx file, or is there another way to insert them into the Animator? Thanks!

# Answer
> 2 votes
The clips seems to be there, in fact the animation tab in the model importer show their names.

In order to select them from project tab, you simply need to expand the view clicking on the little arrow on the right of the model icon.

---
Tags: unity, animation, blender, importing
---


title: Storing object position and rotation

text:
# Question
Title: Storing object position and rotation
I only superficially understand the idea and I can't find any thorough explanation (partially because I can't find very good keywords to Google - English is not my first language):

Although I partially understand some things (next paragraph), my question is what data structure would you use to store a body's position and rotation and how does everything come together? I want to be able to translate that object to a (x, y) position, rotate it about the origin or about its centre (then fetch these things and draw a sprite using that position and rotation). Very similar to Unity's `Transform` object.

From my understanding I will need (at least) a 2/3-dimensional vector and a quaternion and then I should be able to generate a model matrix from them. How? Multiply what to what and in what order? I certainly have no idea how to get a 4 x 4 matrix from a 2/3-dimensional vector and a quaternion. Then if I change the position, I should probably update the model matrix again.

I'm using OpenGL ES 2 on Android, but I wouldn't mind an agnostic answer.

# Answer
> 2 votes
I use directx but it should be the same. There are some functions that create a matrix from a vector. You can search for "transformation matrix". ex. a 2d translation matrix:

```
[1 0 x]
[0 1 y]
[0 0 1]

```

a 2d scaling matrix: `[sx 0 0]
[0 sy 0]
[0 0 1]`

to obtain the final world matrix you have to multiply them, but be careful the order is important ( matrices haven't commutative property) so: if you do -scale\*position= the model is scaled about its centre and then translated -position\* scale = the model is first translated and then scaled (it will move to the origin) -position\* rotation = the model will rotate around the origin and not around its centre

usually you need world = rotation\*scale\*position.

In directx there is a function for each transformation: XMMatrixTranslation(x,y,z) XMMatrixRotationZ(r) .... each of them returns a matrix.

I think in opengl there are function like these so you dont need vector to stroe value, of course you can but you can use: float px,py,pz; float sx,sy,sz; float rx,ry,rz; or three arrays and then call translationMatrix=XMMAtrixTranslation(px,py,pz) or ( XMMatrixTranslation(position\[0\],position\[1\],position\[2\])

---
Tags: opengl-es2
---


# Question
Title: I want to make a pause button on the scene
I want to make a pause button on the scene. If I press the button it will show the `guiTexture` with a variety of buttons with each different script. So what steps should I take? 1. How do make it so if I press the pause button on a scene it will show guiTexture?

# Answer
One way would be to use NGUI here and save yourself from the trouble. Another would be to use a boolean flag which will be set to true on clicking the red button.

To give you some idea on how to use the flag method, you can use this code-snippet -

```
void OnGUI(){
    //Other GUI functions, such as drawing the red button
    if(pause_flag) //pause_flag is your boolean flag which will set to true only if you press the red button
    {
        //Code to draw your GUITexture and other buttons which will appear on clicking the pause button.
        //You can put a close button which will set the flag to false again to hide the texture.
    }
}

```

I hope the logic is clear enough for you to understand.
> 0 votes

---
Tags: c#, unity, unityscript
---


title: Scripts won't affect clones - Unity3d

text:
# Question
Title: Scripts won't affect clones - Unity3d
I made a script which swaps two game objects on click.But the script won't work because the objects are actualy clones of the original prefab.

This is the script (UnityScript):

```
#pragma strict

var object1 : GameObject;
var object2 : GameObject;
function OnMouseDown ()
{

Instantiate(object2,object1.transform.position,object1.transform.rotation);

Destroy(object1);
}

```

I use this script to create other game objects (clones)\[c#\] :

```
using UnityEngine;
using System.Collections;

public class Spawner : MonoBehaviour {

public GameObject[] obj;
public float spawnMin = 1f;
public float spawnMax = 2f;

// Use this for initialization
void Start () {
    Spawn ();
}

void Spawn()
{
    Instantiate(obj[Random.Range(0, obj.GetLength(0))],transform.position, Quaternion.identity);
                    Invoke ("Spawn", Random.Range (spawnMin, spawnMax));
                    }

}

```

The objects get renamed to *NAME* (Clone).

What I wanna do is make the script affect clones too.So they will swap when I click on them.

# Answer
I didn't understand your problem exactly, but I guess you're having difficulty in running same script on different clones of a single prefab. If you've already attached a script to the prefab then it should work, or if you havn't, you can attach a script at runtime too.

I guess you just need to swap the position of two gameobjects, then you can use the following script -

```
public GameObject prefab1;
public GameObject prefab2;
GameObject object1;
GameObject object2;
void Spawn() //call this method whenever you want to instantiate the objects
{
    object1 = Instantiate(prefab1, position, Quarternion.identity) as GameObject; //position can be your initial position for first object
    object2 = Instantiate(prefab2, position, Quarternion.identity) as GameObject; //position can be your initial position for second object

    //You don't actually need to rename the clones, but if you want to, you can use object1.name to rename it.
    //If you need to attach scripts at runtime, you can use object1.AddComponent<ClassName>(); method for that.
}

void Swap() // call this method whenever you want to swap their position
{
    Vector3 pos1 = object1.transform.position;
    object1.transform.position = object2.transform.position;
    object1.transform.position = pos1;
}

```

This all can be done in single script, don't forget to attach prefabs in prefab1 and prefab2 from Inspector.
> 0 votes

# Answer
Instantiate returns the created GameObject. You should be able to capture it in a variable and change the name and more.

```
// UnityScript
var obj : GameObject;
obj = Instantiate( ... );
obj.name = "Not A Clone!!!";

// C#
GameObject obj;
obj = Instantiate( ... ) as GameObject;
obj.name = "Not A Clone!!!";

```
> 1 votes

# Answer
Xerosigma's answer points out how you have to address this by using the object reference returned from Instantiate() but he didn't actually explain what you need to do.

The GameObject reference that you get back from the Instantiate() command then has to be passed to object1 (or object2, whichever you are trying to do) in the first script. I'm guessing you typically use those variables by dragging an object in the scene to the slot "object1" in the Inspector; however since the object you want to swap doesn't exist until the game is running, that object can't be referenced by that variable until after the game is running.

That means you can't drag the object in the editor manually; you'll have to set the variable in code. What I'm guessing you want to do is keep a reference to the swap script in the spawn script, and then pass in new objects that way. Something like:

```
public Swapper myswapper;

...

myswapper.object1 = Instantiate(etc.)

```
> 1 votes

# Answer
I remove the Clone text from the name by adding this simple method to any of the components for the object being instantiated.

```
   void OnEnable()
   {
      name = name.Replace("(Clone)", "");
   }

```
> -1 votes

---
Tags: c#, unity, unityscript
---


title: Collision detection recommendations

text:
# Question
Title: Collision detection recommendations
I am currently developing a prototype game for mobile devices in which the user will see several objects on the screen and will have to touch them one by one in the correct order to win. I guess it that you can say that it is similiar to a Whack a Mole game, but instead of having moles popping up on the screen, I will have several objects moving around.

I am having some difficulties in implementing a collision detection algorithm for this game, thefore I would like your recommendation on what is the best method to use.

For example suppose an object is moving in a given direction, then I could use the SAT to check if it collides with other objects. If it does collides, then it will stop and move in another direction which is randomly chosen.

Another option would be to divide my screen into square or hexagonal tiles. This way I could just check if the tiles are free or occupied before moving the objects.

My game be 2D and will use a top-down ortographic projection and I am developing it using Cocos2d-X and Marmalade SDK. I am not using any physics engine, because my game does not require them (the objects just have to move around, they don't bounce or need any sort of physics behavior).

# Answer
Real-time collision detection in gaming has two stages: the **broad phase** and the **narrow phase**:

In the broad phase you decide which pairs of objects *may* collide. If you have a low number of objects (and I suppose you have since they will all pop on the screen), you can check every object with every other object. Keep in mind that the complexity will be O(n\*n), but this is reasonable for something below 50 objects and is not complicated at all. If you really want to optimize it you should be using a different data structure, such as a quad-tree.

In the narrow phase you decide if a pair of objects is actually colliding. This phase heavily depends on the shape of your objects. You can enclose every object in a **bounding volume**, which will approximate the geometry of the object. This will do the job if the collision detection doesn't have to be very precise. One of the most trivial bounding volumes is the **sphere** and the collision check is just the boolean value of `( Distance( sphere1.center, sphere2.center ) < sphere1.radius + sphere2.radius )`.

You decide which pairs are to be checked for collision in the broad phase and then you check them in the narrow phase. If the narrow phase says they're colliding, you should resolve the collision, which means changing the direction in which the object moves.
> 1 votes

---
Tags: collision-detection, movement, collision-resolution
---


title: Path smoothing while path following

text:
# Question
Title: Path smoothing while path following
I can't find a nice way to do path smoothing while i'm following a path.

I have tried this piece of code but aparently it doesn't work as suspected. The idea of how it should work is:

* Edge 1 (the first location of the path)
* Edge 2 (the 2nd location of the path)
* while edge2 is not the last edge in the path, step through the edges checking to see if the agent can move without obstruction from the source node of edge1 to the destination node of edge2. If the agent can move between those positions then the two edges are replaced with a single edge.

```
public static LinkedList<Vector2> SmoothPathEdgesQuick(LinkedList<Vector2> path, Player player)
{
    LinkedList<Vector2> newLinkedList = new LinkedList<Vector2>();
    List<Vector2> toBeDeleted = new List<Vector2>();

    var edge1 = path.First;
    var edge2 = path.First.Next;
    while (edge2 != null && edge2.Next != null)
    {
        if (player.CanWalkBetween(edge1.Value, edge2.Next.Value))
        {
            toBeDeleted.Add(edge2.Value);
            edge1 = edge2.Next;
            if (edge1.Next == null)
            {
                break;
            }
            else
            {
                edge2 = edge1.Next;
            }
        }
        else
        {
            edge1 = edge2;
            edge2 = edge2.Next;
        }
    }
    if (edge1.Next != null)
    {
        if (edge2 != null && player.CanWalkBetween(edge1.Value, edge2.Value))
        {
            toBeDeleted.Add(edge1.Value);
        }
    }
    foreach (var vector2 in path)
    {
        if (toBeDeleted.Contains(vector2))
            continue;
        newLinkedList.AddLast(vector2);
    }
    return newLinkedList;
}

```

As when i go from 250,400 to 500,400 (which is just a line) it should get just 2 waypoints (so the newLinkedList should just have a count of 2). But instead of 2 it does gets more waypoints, which is strange as the example in the book doesn't get more than 2 waypoints for a straight line.

I've used the code below which is provided by the the book Programming Game AI by Example. And based my code on the logic in there.

```
void Raven_PathPlanner::SmoothPathEdgesQuick(Path& path)
{
  //create a couple of iterators and point them at the front of the path
  Path::iterator e1(path.begin()), e2(path.begin());

  //increment e2 so it points to the edge following e1.
  ++e2;

  //while e2 is not the last edge in the path, step through the edges checking
  //to see if the agent can move without obstruction from the source node of
  //e1 to the destination node of e2. If the agent can move between those
  //positions then the two edges are replaced with a single edge.
  while (e2 != path.end())
  {
    //check for obstruction, adjust and remove the edges accordingly
    if ( (e2->Behavior() == EdgeType::normal) &&
          m_pOwner->canWalkBetween(e1->Source(), e2->Destination()) )
    {
      e1->SetDestination(e2->Destination());
      e2 = path.erase(e2);
    }

    else
    {
      e1 = e2;
      ++e2;
    }
  }
}

```

# Answer
> 1 votes
Your code only makes a single test with `edge1` before advancing. This skips over certain nodes that are in a straight line. For example, if you have 5 points (A-\>B-\>C-\>D-\>E) all in a straight. The smoothed path should only contain two points (A-\>E). In your logic you test if you can travel between A-\>C and if you can then B is eliminated. You then check to see if you can get from C-\>E, and if you can then D is eliminated. Here you reach the end of the path and you are left with an extra waypoint (A-\>C-\>E).

Because you are moving your `edge1` further down the path at ever iteration you are not eliminating all possible waypoints. You should check to see if you can walk between `edge1.value` and `edge2.next.value`, if so, mark `edge2` for deletion and advance `edge2` to `edge2.next`. If you cannot walk between then advance `edge1` and `edge2`.

```
while (edge2 != null && edge2.Next != null)
{
    if (player.CanWalkBetween(edge1.Value, edge2.Next.Value))
    {
        toBeDeleted.Add(edge2.Value);
        edge2 = edge2.next;
    }
    else
    {
        edge1 = edge2;
        edge2 = edge2.Next;
    }
}

```

---
Tags: xna, c#, c++, ai, graph
---


title: Collision detection in ruby

text:
# Question
Title: Collision detection in ruby
I'm making a simple pong game in ruby.

I did the collision detection this way:

```
def collides_with(player)
      ((@x + @image.width >= player.x) && (@x <= player.x + player.image.width)) && ((@y + @image.height >= player.y) && (@y <= player.y + player.image.height))
end

```

If this is true I multiply the ball's y coordinate by -1 (to change its direction):

`@ball.vy *= -1`

This is working as expected, except in one case when the ball reaches the left (or right) side of the paddle while it's moving. this will cause the ball to move into the inside of the paddle,which seems strange.

What should I do to fix this?

# Answer
> 1 votes
Thanks for the additional details. The answer appears actually really simple: you're bouncing the ball back upward via:

`@ball.vy *= -1`

In the normal case, the ball's velocity is positive (downward), it hits the top of the pedal, and becomes negative (upward).

But if the ball hits the *side* of the pedal, it might bounce back upward *and immediately collide with the pedal again.* In fact, it might do this multiple times (once per frame) within a second, and you would only see the final velocity when it's released.

The real fix for this is to look at where the ball hit the pedal (eg. sides) and adjust the velocity accordingly (eg. bounce sideways but retain downward velocity). A common solution to this is separating axis theory, which is usually good (but fails in some cases with really high velocity objects).

---
Tags: collision-detection, ruby, libgosu
---


# Question
Title: GameObject once walked on, gives message using C#?
I'm struggling to figure this code out by myself. I'm able to check if the objects are in the scene, and if they are print a message. I now want the GameObject of tag Zone to display a message to let me know when I've walked on it or at very least, touched it.

Am I entirely wrong with trying to do this with Raycast, or would I be better off trying to figure out how to do this with purely Collisions or something? Just looking for advice more than anything, I really want to figure this out as best I can.

# Answer
> 2 votes
One way to do this is to use a collider (sphere, cube, cylinder, etc.). Then make the collider a trigger collider and add a rigid body.

Along with a collider attached to your Zone gameobject, you can attach a script with something like the following:

```
void OnTriggerEnter(Collider other) {
    Debug.Log("Zone triggered!");
}

```

The `OnTriggerEnter` method will fire once another collider has touched the trigger collider.

# Answer
> 0 votes
This can be done with raycasting. Cast a short ray (using the distance parameter) downwards from your walking object. Make the walked on object part of a special layer for trigger objects. When casting your ray, you can restrict it to only collide with that layer of objects.

This strategy allows you to keep all the code for checking when you walk over an object inside the object doing the walking.

---
Tags: c#, unity
---


# Question
Title: How does this data oriented design retain level data, while still offering cache-wise benefits?
I'm almost sold on the concept of a data oriented engine; however, one thing still eludes me. If we pack the data from a large level into huge arrays, and go over them, any visibility system that we have would basically render most of it as unprocessable.

---

Consider this exert:

```
void do_stuff_with_data(data* vdata, const const_data* cdata, int count)
{
    for ( int i = 0; i < count; ++i )
    {
        if ( vdata->active )
        {
            ... process data
        }
    }
}

```

Considering that most of the data is not visible, and due to stuff moving around, there is no sensible prediction for how to order it, and branch prediction is screwed. Doesn't that void the cache-wise benefits?

---

I have read up on article dealing with this specific problem, but most of the sources just show the "big picture", completely disregarding this important issue.

# Answer
Processing data in arrays is not component based or data driven design. Component based design is about aggregation and dynamic composition.

Much of the hype about component performance in the indie community is extremely ill-advised. I've seen great complex 3D games written from scratch in C++ with a fairly naive memory allocator and component implementation. Having a good understanding of memory usage and access, and data structures is way more important than trying to abide by some methodology.

To answer your question more directly, you're thinking about an application of data oriented design. This is also not component based design. Usually a sorting of data occurs (moving things around in memory) before some heavy processing occurs. This can allow data to be operated with smaller tighter loops, possibly allowing prefetching, perhaps lowers branching, and can relieve register pressure.

Sometimes only part of the data needs to be sorted, or only a partial sort needs to be run. As a programmer you'll have to make these judgement calls, and sometimes they are difficult to make. Writing good code is hard and there's no universal rules to follow.

But I don't really consider thinking about this sort of component optimization thing as high priority by any means for most games. It's my opinion that most games will benefit from the architecture choice, not from any potential magical array optimizations.
> 4 votes

# Answer
From what I understand, the idea is that moving simple data structures around in memory is cheap, so if your visibility calculation made sure that all the visible objects ended up in the front of the data list (say by swapping each visible item it found with the item immediately after the last visible item in the list), then you would just have to keep a count of how many items where visible, and stop after that number (so no vdata-\>active checks in the inner loop would be needed).
> 0 votes

---
Tags: component-based, data-oriented
---


title: Resolution independent physics

text:
# Question
Title: Resolution independent physics
I'm making a game like Doodlejump but don't know how to make the physics scale on multiple resolutions. I also can't find anything related to this on Google. Right now I'm scaling the game using letterboxing and tested scaling the jump height with this code:

```
gravity = graphics.getHeight() * 0.001f;
jumpVel = graphics.getHeight() * -0.04f;

...

velY += gravity;
y += velY;

```

But if I test this on my smartphone or emulator with different resolutions, I always get a slightly different jump height. I know that Farseer is resolution independent. How can I replicate this in my game?

Thanks in advance.

# Answer
> 1 votes
You don't scale your physics. Your physics should be based in an arbitrary coordinate system, completely independent of the device.

Then when you do your drawing, you translate your "physical" location to a screen location based on the screen resolution. You need to calculate the scaling amount based on the screen resolution.

For example, if you define your arbitrary world size as 1200 "units" wide, then on a device with a 1920 pixel wide screen, your view scale is: 1920/1200 = 1.6

So for example, gravity and jump velocity would simply be:

```
gravity = 0.001f;
jumpVel = -0.04f;

viewScale=graphics.getWidth()/WORLD_WIDTH;

```

Then when you draw your object, you'd use:

```
screenX=worldX*viewScale;
screenY=worldY*viewScale;

```

---
Tags: 2d, android, physics, scale
---