# Question
Title: How do I teach my artist to do art for games?
So my girlfriend is an artist and I'm a programmer and we often talk about joining talents and doing some small games or other fun stuff for the different popular platforms currently out.

But because I haven't really done any serious game development yet, I have a hard time explaining to her how she should create or package the assets she'd make, so we always end up not doing anything about it.

What I'm mostly thinking about here is when doing frame by frame animation. I know sprite sheets are used for this kind of thing, but then come questions like frames per second and stuff like that. Not program wise but art wise.

How should we tackle this?

# Answer
> 23 votes
The answer will vary in some cases, depending on what style of art you're looking for. There's a few options for what style of artist you have.

## Creation

* **Classic hand drawn frame-by-frame animation**: Probably the easiest for an artist to get into or at least it's the least technical. There are tutorials for this type of animation everywhere. It can be done on paper or in digital format. Some key points about creating animations:

+ Onion skinning: Very useful for consistency between frames.
    + Frame frequency: This is an artistic decision you'll make with your artist. It depends on the style of art you want.
    + Rotoscoping: Great for complex animations like walking or jumping. Essentially tracing live action to generate your animations.
    + One pretty neat tool for this is Pencil a free open-source application specifically for classic animation.
    + There's also loads of different artistic styles to choose from. Ranging from pixelated sprites to HD sprites, from clunky animations to smooth, and so on.
* **2D Skeletal animation**: Many of the same techniques can be used from classic animation here. However, this involves animating a skeleton, which can be re-used for other characters. Interpolation can be used to cut down the time for creating the animations. This is great, for example, if you have multiple bipedal characters and you want them all to be able to walk, jump and dance. Then you only have to animate once and apply it to each character. This also reduces the memory requirements of your game. Though this does put you solely in the digital art realm. There are special tools available for this. (And a tutorial for the programming side)
* **3D Skeletal animation**: Here's the most complex form. Don't let the 3D fool you, this is great for 2D art too. Project Zomboid uses this for their 2D animations. It allows you to create a full 3D character and animate them to create animations of them facing whatever direction you need. Great for isometric games where your character can be viewed from the front, back and sides. There's also lots of tools and tutorials available for this.

## Where code and art meet

This will depend on what method you're using from above.

* **2D frame-by-frame**: You can generate 2D frames from any of the above methods. Depending on your style you'll choose a frame rate to display these at, 24 frames per second is typical. Typically these are output into sprite sheets. There are application specific tutorials for outputting frames into sprite sheets. However, if your artist is not comfortable with those aspects, it's easy to just have them output each frame as a single image with common centering and cropping for each frame. There are applications that will take a folder full of individual images and generate a sprite sheet with an associated file that describes the location of each image and its dimensions. Do teach your artist proper organization and naming skills, those will be very important for generating these sprite sheets.
* **2D Skeletal animation**: Unfortunately this will vary greatly from implementation to implementation. Specifics will include: how bones are defined (zones of a single image, separate images (for each limb?)), how bones are transformed (rotations + positions, matrices) and more.
* **3D Skeletal animation**: Not something that's specified in your question, but it'll be close to the same as 2D skeletal animation. This will vary. However it's more likely to involve a hierarchy of matrices that define bone rotations, offsets and scales. Those matrices will be used to transform vertices to pose the model in different poses and can be interpolated to smooth animations.

All in all, you should approach this like you're learning to do this yourself. Your artist will be able to handle the artistic details right away. As a programmer, you're more likely to pick up the technical details right away. At first you can work together to on the art-\>game steps, and eventually your artist should be able to take over and output the art in a format that's easily imported or read by your game.

# Answer
> 9 votes
For artists in general you should **make it as easy as possible to add or change content** in your engine, the more freedom he/she has and the easier he/she can experiment the better.

* As few restrictions as possible: Allow 32 bit colors, alpha transparency and any size possible.
* Use standard formats such as PNG.
* Avoid the need of engine specific tools if possible. (For example: Plain text files instead of some kind of binary format only your engine tool can edit.)
* Allow dynamic changing and loading of the art assets so the artist can test themselves what works and what doesn't.
* Give room for experimentation without recompiling.

Ask the artist what he/she needs, he/she is the one with the artistic vision on how the game should look like and what he/she needs to archive it. If you really need to optimize the engine and it's content do that after all the art is done.

*PS: I'm both artist and programmer*

---
Tags: art
---


# Question
Title: A specific but basic tutorial for Corona SDK?
I have been looking at Corona SDK and it would be helpful if I could see a tutorial/example to accomplish the following:

1. Load an image as a background/map
2. Draw a circle on the screen
3. user can tap elsewhere and the circle moves to that location (this can be repeated)

Does anyone know of any examples out there?

# Answer
> 0 votes
Very easy to do - here's a plug and play sample;

```
local background = display.newRect( 0, 0, 320, 480 )
background:setFillColor(0, 200, 255)

local circle = display.newCircle( -100, 0, 20 )

local function moveCircle(event)
    circle.x = event.x
    circle.y = event.y
end
background:addEventListener("tap", moveCircle)

```

Though obviously you'd you an image, I'm using a rectangle.

---
Tags: corona-sdk
---


# Question
Title: Rain effect using DirectX 9 capabilities
Is it possible to achieve something similar to nVidia's rain demo using only shader model 3.0 capabilities? If yes, could you point out a few documents/web resources that are suitable candidates and do not require a heavy programming load (e.g. not more than two hard weeks of programming for one single person)?

It would be nice if the answer could also contain a pro/con phrase for the proposed idea (e.g. postprocessing rain shader vs. a particle based effect).

# Answer
The document just describes a particle system. Particle systems are nothing new, the difference with the demo is just that it uses the geometry shader to generate the geometry needed for the single partices. You can do the same on the CPU, the only drawback is that it is slower. Everything else can be done on SM 3.0 in a similar way as described in the document.
> 6 votes

# Answer
The basic answer is that once you have programmable shaders, everything is possible. It's not really valid to speak of DX9 or 11 "capabilities" in these terms as they can both achieve the same end result; the difference exists in the code that you need to write to get there. So what on DX9 may be a complex multipass algorithm which is heavy on draw calls and state changes could be expressed on 11 with a much simpler, cleaner and faster setup.
> 1 votes

# Answer
Yes you can achieve this effect, however like I said to someone else, it isn't always better: Link

I suggest reading that, it is an interesting solution to a problem that he was having and may suit your game better
> 1 votes

---
Tags: shaders, directx9, special-effects
---


# Question
Title: How to create a mathematical mechanism in order for a game to be balanced?
For example, in a game like Diablo, how did they decide how much damage each skill does? Is it the amount of clicks that the player needs to do? Or maybe the expected lifetime of a player? Maybe calculate the probability that the player will die?

# Answer
> 6 votes
There are a few things to point out, balance isn't done exclusively by the programmer, and in most cases shouldn't actually rely (entirely) on the programmer, but the designer instead. Which leads me to the important notice, that it doesn't usually depend on the algorithm itself (unless it needs a big change) but the variables OF the algorithm. For example, the Starcraft II team had something in the editor that could exclusively edit balance through the various inputs and testing the actual design inputs by hand (through play testing combine with common sense and decidind (as previously posted) what is "fun")

In other words, it's up to you how the actual algorithm works entirely. Some people will base it on damage per second, meaning the designer only has to alter how much damage, that the unit will 'do' per second. And the algorithm will say maybe, "once every second, do amount of damage" and it will recieve from the DPS that the designer put into the files via la editor.

# Answer
> 12 votes
This is called "experience." Blizzard has made games before and learned from experience. The heuristic to rating and improving that knowledge is "Is it fun?"

In Blizzard's case they are known for iterating when trying to find fun and balance, **a lot**, and that shows that there is no secret math but just a lot of work.

A better question might be "once I find out what feels fun, how do I create the math and code to match so that all of my game is fun?"

# Answer
> 8 votes
With a lot of iteration and playtesting.

I think this is what makes interesting the job of a Game designer. You can imagine balancing the game is a big part of what a game designer does once the coding has started.

I've always found Sirlin's articles very enlightening on the kind of work you have to do. He used to work at Capcom as a game designer. Here are a few you can check and are pretty good:

Balancing Multiplayer Games

Super Balance Articles II Turbo (How he balanced the remake of Street Fighter II)

Balancing Puzzle Fighter

He is algo very good at picking apart other games and figuring how they work. Check his site.

# Answer
> 4 votes
There are countless factors to consider. Question is too broad IMO :)

It's all relative too... dmg is only relative to hp, etc. Damage over time (eg damage per second) is likely a good place to start when evaluating a weapon's power. Divide an enemy's HP by the Damage to get the amount of time it would optimally take to kill it... and so on. I'm just talking flow-of-consciousness... I'll stop.

# Answer
> 3 votes
Well the first step is to define what "balanced" is. How long an encounter should be, how much "grinding" there is, how much health should a given NPC take away from the player, that kind of thing.

From there you can pick some equations that get you something close to what you want. From there's it's a matter of testing and iteration. Some things don't have a complete corollary to your predefined values (i.e., how long a stun is worth X amount of damage, that kind of thing) and you have to do testing to figure out what the ratio of things are.

Someone linked to a article in a similar question here that goes into this process a bit more: http://www.eldergame.com/2010/11/how-to-balance-an-mmo-and-how-to-stop/

# Answer
> 2 votes
This is answered but I thought I would comment on Diablo 3 balance, specifically, and how it was described by Jay Wilson and other designers. D3 works off of one large "monster spreadsheet." The rows are monsters and the columns are monster attributes weighted in %. So 100% would be considered average. Paraphrased/very simple view:

```
Monster   | Health  | Damage  |   Exp
------------------------------------------
Monster_A   100%       100%      100%
Monster_B   80%        50%       65%
Boss_A      200%       120%      300%

```

This way, they can tune different monsters along the same relative scale. Smaller monsters that appear in packs have lower individual health and damage, but other monsters that appear alone may have higher health and damage (relatively speaking). As others stated, there is tons and tons of play-testing an iteration involved to get both the weighted and base values in a good place against what the players are capable of doing.

Diablo games, in general, use a lot of different tables/weightings to make everything easily scalable.

# Answer
> 1 votes
It sounds odd but Rock, Paper, Scissors is a condensed version of what you’re talking about. I don’t need to explain the rules, but there is a clear balance between the different elements.

Similarly, as most games progress, there are elements of levelling-up as the player increases in skill. RPGs are most notable for this: you have a level which then applies a multiplier on your attack, defence, health etc.

You could try to design the interactions between the numbers beforehand, but it’s easier to adapt them by hand to suit the gameplay you want to achieve. If you want some kind of “method” then you could start by picking a realistic number and then, if that’s not right, halve or double it. If that number isn’t right either, choose a number halfway between and repeat. Eventually, you’ll reach a satisfactory point.

---
Tags: mathematics, game-mechanics, balance
---


title: android multitouch problem

text:
# Question
Title: android multitouch problem
Im aware that there a a couple of posts on this matter, but Ive tried all of them and none of them gets rid of my problem.

Im starting to get close to the end of my game so I bought a cabel to try it on a real phone, and as I expected my multitouch dosnt work. I use 2 joysticks, one to move my character and one to change his direction so he can shoot while walking backwards etc.

my local variable:

```
public void update(MotionEvent event) {
    if (event == null && lastEvent == null) {
        return;
    } else if (event == null && lastEvent != null) {
        event = lastEvent;
    } else {
        lastEvent = event;
    }

    int index = event.getActionIndex();
    int pointerId = event.getPointerId(index);

```

statement for left Joystick:

```
if (pointerId == 0 && event.getAction() == MotionEvent.ACTION_DOWN && (int) event.getX() > steeringxMesh - 50 && (int) event.getX() < steeringxMesh + 50 && (int) event.getY() > yMesh - 50 && (int) event.getY() < yMesh + 50) {
    dragging = true;
} else if (event.getAction() == MotionEvent.ACTION_UP) {
    dragging = false;
}

if (dragging) {
     touchingPoint.x = (int) event.getX(); //used to calculate angle of sprites movement
     touchingPoint.y = (int) event.getY();

     //code for moving my character

```

statement for my right joystick:

```
if (pointerId == 1 && event.getAction() == MotionEvent.ACTION_DOWN && (int) event.getX() > shootingxMesh - 50 && (int) event.getX() < shootingxMesh + 50 && (int) event.getY() > yMesh - 50 && (int) event.getY() < yMesh + 50) {
    shooting = true;
} else if (event.getAction() == MotionEvent.ACTION_UP) {
    shooting = false;
}

if (shooting) {

    touchingPoint2.x = (int) event.getX(); //used to calculate sprites angle and get the correct direction
    touchingPoint2.y = (int) event.getY();
    // code for aiming
}

```

This class is my main-Views onTouchListener and is called in a update-method that gets called in my game-loop, so its called every frame.

Im really at a loss here, I've done a couple of tutorials and Ive tried all relevant solutions to similar posts. Can post entire Class if necessary but I think this is all the relevant code. Just hope someone can make some sence out of this.

EDIT: both shooting and dragging joysticks work fine, but only when I press them one at a time, so I cant drag and shoot at the same time. I've looked around for a bit more and have understood that you need a `MotionEvent.ACTION_POINTER_UP` and `MotionEvent.ACTION_POINTER_DOWN` , but still dont know a way to implement it, some people use loops that goes through `event.getPointerCount`. Also with this Code my `pointerId` is always 0. To sum up: I want to be able to use both joysticks at the same time.

# Answer
> 5 votes
Your code is only looking at the Single Touch portion of the event. You will only ever receive information about the first finger to hit the screen. If you lift that finger, your event will jump over to the second finger that is down, right?

You need to implement MotionEvent.ACTION\_MASK to get the multi-touch parts. Something like:

```
        int action = event.getAction() & MotionEvent.ACTION_MASK;

```

action can now contain MotionEvent.ACTION\_POINTER\_DOWN events in addition to the normal MotionEvent.ACTION\_DOWN events you're polling for.

In addition, you need to get the index of the pointer associated with the event (i.e. the second finger down, third finger down, kind of).

```
        int pointerId = event.getPointerId(pointerIndex);

```

I'm sorry I'm very hazy on this as I didn't implement it directly myself for my project. This might be of help: http://tutorials-android.blogspot.com/2011/09/multi-touch-in-android.html

# Answer
> 4 votes
What exactly "doesn't work" about the multi-touch? The second touch provides no apparent effect at all, or it provides some input but the inputs don't work properly?

Many Android phones, even newer ones, may not have "true" multi-touch. These phones have hardware limitations that effectively let them mimic pinching and rotating gestures, but don't actually provide true multi-touch. These phones break down when two touch inputs are near each other on the horizontal or vertical axis - as your two joysticks are very likely to be.

Further reading: http://www.badlogicgames.com/wordpress/?p=1007

Further Post-Edit Edit: The Galaxy Nexus *does* support **true** multi-touch. This answer is unrelated to the problem you're currently facing.

---
Tags: 2d, android, game-mechanics, html-canvas, touch
---


# Question
Title: Android Java: Way to effectively pause system time while debugging?
In my project, I call nanoTime and use that to get a deltaTime which I pass to my entities and animations.

However, while debugging (for example, stepping through my code), the system time on my phone is happily chugging along, so it's impossible to look at, say, two sequential frames of data in the debugger (since by the time I'm done looking at the first frame, the system time has continued to move ahead by seconds or even minutes).

Is there a programming practice or method to pause the system clock (or a way for my code to intercept and fake my deltaTime) whenever I pause execution from the debugger?

Additional Information:

* I'm using Eclipse Classic with the ADT plugin and a Samsung SII, coding in Java.
* My code invoking nanoTime: http://pastebin.com/0ZciyBtN
* I do all display via a Canvas object (2D sprites and animations).

# Answer
> 4 votes
Instead of grabbing the system time and calculating the delta time each frame, just keep the delta frame time constant in the debug build (deltaTime is just always 16ms, for example). This way each simulation frame has a fixed time step regardless of how much debugging you did in between frames. Of course this should only be done in your debug build.

---
Tags: java, android, debugging, timer
---


# Question
Title: P2P synchronization: can a player update fields of other players?
I know that synchronization is a huge topic, so I have minimized the problem to this example case.

Let's say, Alice and Bob are playing a P2P game, fighting against each other. If Alice hits Bob, how should I do the network component to make Bob's HP decrease?

I can think of two approaches:

1. Alice perform a Bob.HP--, then send Bob's reduced HP to Bob.
2. Alice send a "I just hit Bob" signal to Bob. Bob checks it, and reduce its own HP, then send his new HP to everyone including Alice.

I think the second approach is better because I don't think a player in a P2P game should be able to modify other players' private fields. Otherwise cheating would be too easy, right?

My philosophy is that in a P2P game especially, a player's attributes and all attributes of its belonging objects should only be updated by the player himself. However, I can't prove that this is right. Could someone give me some evidence? Thanks :)

# Answer
> 3 votes
It's not good practice to directly alter other players' properties, so I would recommend your second option.

Though I would also recommend adding checks to make sure that peers don't spam "I hit you" messages without actually having hit the player.

---
Tags: networking, synchronization, anti-cheat
---


title: game multiplayer service development

text:
# Question
Title: game multiplayer service development
I'm currently working on a multiplayer game. I've looked at a number of multiplayer services(player.io, playphone, gamespy, and others) but nothing really hits the mark. They are missing features, lack platform support or cost too much. What I'm looking for is a simple poor man's version of steam or xbox live. Not the game marketplace side of those two but the multiplayer services.

User accounts, profiles, presence info, friends, game stats, invites, on/offline messaging. Basically I'm looking for a unified multiplayer platform for all my games across devices.

Since I can't find what I'm planning to roll my own piece by piece. I plan to save on server resources by making most of the communication p2p. Things like game data and voice chat can be handled between peers and the server keeps track of user presence and only send updates when needed or requested. I know this runs the risk of cheating but that isn't a concern right now. I plan to run this on a Amazon ec2 micro server for development then move to a small to large instance when finished.

I figure user accounts would be the simplest to start with. Users can create accounts online or using in game dialog, login/out, change profile info. The user can access this info online or in game. I will need user authentication and secure communication between server and client. I figure all info will be stored in a database but I dont know how it can be stored securely and accessed from webserver and game services.

I would appreciate and links to tutorials, info or advice anyone could provide to get me started. Any programming language is fine but I plan to use c# on the server and c/c++ on devices. I would like to get started right away but I'm in no hurry to get it finished just yet. If you know of a service that already fits my requirements please let me know.

# Answer
Raknet has an abstraction for a Lobby system (friends, rooms, emails, ranking) with different backends. You can choose between your own PC Lobby server backend (the "simple poor man's version" as you called it), or use their implementations for services like XBox Live, Steam, Games for Windows Live, in case you find out later you are allowed to publish on those services.

For more details search for "Lobby" in the manual

Even though Raknet is written in C++, there is a C# integration using Swig coming with Raknet 4

RakNet 4 is free for the PC, Mac, iPhone, gPhone or Linux for qualified Indy developers.
> 5 votes

# Answer
Badumna provides similar functionality and includes support for peer-to-peer networking as you seem to want. It actually has a hybrid model that can provide peer-to-peer and server based networking and the ability to pick and choose the approach for individual functionality.
> 0 votes

---
Tags: networking, multiplayer, client-server, databases, security
---


# Question
Title: ERROR #342: DEVICE_SHADER_LINKAGE_SEMANTICNAME_NOT_FOUND
I've stared at this for at least half an hour now and I cannot figure out what directx is complaining about. I know this error normally means you put float3 instead of a float4 or something like that, but I've checked over and over and as far as I can tell, everything matches.

This is the full error message:

`D3D11: ERROR: ID3D11DeviceContext::DrawIndexed: Input Assembler - Vertex Shader linkage error: Signatures between stages are incompatible. The input stage requires Semantic/Index (COLOR,0) as input, but it is not provided by the output stage. [ EXECUTION ERROR #342: DEVICE_SHADER_LINKAGE_SEMANTICNAME_NOT_FOUND ]`

This is the vertex shader's input signature as seen in PIX:

```
// Input signature:
//
// Name                 Index   Mask Register SysValue Format   Used
// -------------------- ----- ------ -------- -------- ------ ------
// POSITION                 0   xyz         0     NONE  float   xyz
// NORMAL                   0   xyz         1     NONE  float
// COLOR                    0   xyzw        2     NONE  float

```

The HLSL structure looks like this:

```
struct VertexShaderInput
{
    float3 Position : POSITION0;
    float3 Normal : NORMAL0;
    float4 Color: COLOR0;
};

```

The input layout, from PIX, is:

The C# structure holding the data looks like this:

```
[StructLayout(LayoutKind.Sequential)]
public struct PositionColored
{
    public static int SizeInBytes = Marshal.SizeOf(typeof(PositionColored));

    public static InputElement[] InputElements = new[]
    {
        new InputElement("POSITION", 0, Format.R32G32B32_Float, 0),
        new InputElement("NORMAL", 0, Format.R32G32B32_Float, 0),
        new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 0)
    };

    Vector3 position;
    Vector3 normal;
    Vector4 color;

    #region Properties
    ...
    #endregion

    public PositionColored(Vector3 position, Vector3 normal, Vector4 color)
    {
        this.position = position;
        this.normal = normal;
        this.color = color;
    }
    public override string ToString()
    {
        StringBuilder sb = new StringBuilder(base.ToString());
        sb.Append(" Position=");
        sb.Append(position);
        sb.Append(" Color=");
        sb.Append(Color);
        return sb.ToString();
    }
}

```

SizeInBytes comes out to 40, which is correct (4\*3 + 4\*3 + 4\*4 = 40). Can anyone find where the mistake is?

# Answer
> 1 votes
Turns out that removing the normal and color (I wasnt using them anyway) from the VertexShaderInput struct makes the warning go away. I suspect this is just covering up some other problem but unless someone has any other ideas, I'll go with this for now.

---
Tags: directx, directx11, slimdx
---


title: gradient coloring of an object

text:
# Question
Title: gradient coloring of an object
I have an object(FBX format) in my project, it's a line drawn in 3D max. I want to color the line in XNA so that the color starts from a specific RGB color in both the start and end points of the line and finish in a specific RGB color.(e.x., from (255,255,255) to (128,128,128). Something like gradient coloring of an object. I need to do that programmatically, since later in my code I have to change these two specific colors a lot.

# Answer
In 3DS Max, select your line geometry and apply the `VertexPaint` modifier to it. This way you can paint individual vertices with the color of your choice, although I don't know if FBX format supports exporting this information.

If you need to change the color later, paint one end in pure white and the other in a middle gray; then, inside your code, change the `DiffuseColor` of your `BasicEffect` to achieve the desired tinting.
> 1 votes

# Answer
This article talks about gradient shaders:

You might be able to adapt that to shade your model (draw it with the shader) instead of the skybox.
> 0 votes

---
Tags: xna-4.0, color
---


# Question
Title: Space invaders clone not moving properly
I'm trying to make a basic space invaders clone in allegro 5, I've got my game set up, basic events and such, here is the code:

```
#include <allegro5/allegro.h>
#include <allegro5/allegro_image.h>
#include <allegro5/allegro_primitives.h>
#include <allegro5/allegro_font.h>
#include <allegro5/allegro_ttf.h>
#include "Entity.h"

// GLOBALS ==========================================
const int width = 500;
const int height = 500;
const int imgsize = 3;
bool key[5] = {false, false, false, false, false};
bool running = true;
bool draw = true;

// FUNCTIONS ========================================
void initSpaceship(Spaceship &ship);
void moveSpaceshipRight(Spaceship &ship);
void moveSpaceshipLeft(Spaceship &ship);
void initInvader(Invader &invader);
void moveInvaderRight(Invader &invader);
void moveInvaderLeft(Invader &invader);
void initBullet(Bullet &bullet);
void fireBullet();
void doCollision();
void updateInvaders();
void drawText();

enum key_t { UP, DOWN, LEFT, RIGHT, SPACE };
enum source_t { INVADER, DEFENDER };

int main(void)
{
    if(!al_init())
        { return -1; }

    Spaceship ship;
    Invader invader;
    Bullet bullet;

    al_init_image_addon();
    al_install_keyboard();
    al_init_font_addon();
    al_init_ttf_addon();

    ALLEGRO_DISPLAY *display = al_create_display(width, height);
    ALLEGRO_EVENT_QUEUE *event_queue = al_create_event_queue();
    ALLEGRO_TIMER *timer = al_create_timer(1.0 / 60);
    ALLEGRO_BITMAP *images[imgsize];
    ALLEGRO_FONT *font1 = al_load_font("arial.ttf", 20, 0);

    al_register_event_source(event_queue, al_get_keyboard_event_source());
    al_register_event_source(event_queue, al_get_display_event_source(display));
    al_register_event_source(event_queue, al_get_timer_event_source(timer));

    images[0] = al_load_bitmap("defender.bmp");
    images[1] = al_load_bitmap("invader.bmp");
    images[2] = al_load_bitmap("explosion.bmp");

    al_convert_mask_to_alpha(images[0], al_map_rgb(0, 0, 0));
    al_convert_mask_to_alpha(images[1], al_map_rgb(0, 0, 0));
    al_convert_mask_to_alpha(images[2], al_map_rgb(0, 0, 0));

    initSpaceship(ship);
    initBullet(bullet);
    initInvader(invader);

    al_start_timer(timer);
    while(running)
    {
        ALLEGRO_EVENT ev;
        al_wait_for_event(event_queue, &ev);

        if(ev.type == ALLEGRO_EVENT_TIMER)
          {
              draw = true;
            if(key[RIGHT] == true)
                moveSpaceshipRight(ship);

            if(key[LEFT] == true)
                moveSpaceshipLeft(ship);
          }

        else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
            running = false;

        else if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
          {
            switch(ev.keyboard.keycode)
            {
                case ALLEGRO_KEY_ESCAPE:
                    running = false;
                    break;

                case ALLEGRO_KEY_LEFT:
                    key[LEFT] = true;
                    break;

                case ALLEGRO_KEY_RIGHT:
                    key[RIGHT] = true;
                    break;

                case ALLEGRO_KEY_SPACE:
                    key[SPACE] = true;
                    break;
            }
          }

        else if(ev.type == ALLEGRO_KEY_UP)
            {
                switch(ev.keyboard.keycode)
                {
                    case ALLEGRO_KEY_LEFT:
                        key[LEFT] = false;
                        break;

                    case ALLEGRO_KEY_RIGHT:
                        key[RIGHT] = false;
                        break;

                    case ALLEGRO_KEY_SPACE:
                        key[SPACE] = false;
                        break;
                }
            }

        if(draw && al_is_event_queue_empty(event_queue))
        {
            draw = false;

            al_draw_bitmap(images[0], ship.pos_x, ship.pos_y, 0);
            al_flip_display();
            al_clear_to_color(al_map_rgb(0, 0, 0));
        }
    }

    al_destroy_font(font1);
    al_destroy_event_queue(event_queue);
    al_destroy_timer(timer);
    for(int i = 0; i < imgsize; i++)
        al_destroy_bitmap(images[i]);
    al_destroy_display(display);
}

// FUNCTION LOGIC ======================================
void initSpaceship(Spaceship &ship)
{
    ship.lives = 3;
    ship.speed = 2;
    ship.pos_x = width / 2;
    ship.pos_y = height - 20;
}

void initInvader(Invader &invader)
{
    invader.health = 100;
    invader.count = 40;
    invader.speed = 0.5;
    invader.pos_x = 300;
    invader.pos_y = 300;
}

void initBullet(Bullet &bullet)
{
    bullet.speed = 10;
}

void moveSpaceshipRight(Spaceship &ship)
{
        ship.pos_x += ship.speed;
        if(ship.pos_x >= width)
            ship.pos_x = width-30;
}

void moveSpaceshipLeft(Spaceship &ship)
{
    ship.pos_x -= ship.speed;
    if(ship.pos_x <= 0)
        ship.pos_x = 0+30;
}

```

However it's not behaving the way I want it to behave, in fact the behavior for the ship movement is un-normal. Basically I specified that the ship only moves when the right/left key is down, however the ship is moving constantly to the direction of the key pressed, it never stops although it should only move while my key is down. Even more weird behavior, when I press the opposite key the ship completely stops no matter what else I press.

What's wrong with the code? Why does the ship move constantly even after I specified it only moves when a key is down?

# Answer
> 5 votes
Based on your description it appears `key[LEFT] = false;` and `key[RIGHT] = false;` are never reached. The if-condition for that piece of code reads `if(ev.type == ALLEGRO_KEY_UP)`, however the key down handling code's condition looks like this: `if(ev.type == ALLEGRO_EVENT_KEY_DOWN)`.

Without knowing any Allegro, I suggest you use `ALLEGRO_EVENT_KEY_UP` in the key up handling code's condition.

---
Tags: c++, behavior, allegro
---


# Question
Title: Control convention for circular movement?
I'm currently doing a kind of training project in Unity (still a beginner). It's supposed to be somewhat like Breakout, but instead of just going left and right I want the paddle to circle around the center point. This is all fine and dandy, but the problem I have is: how do you control this with a keyboard or gamepad? For touch and mouse control I could work around the problem by letting the paddle follow the cursor/finger, but with the other control methods I'm a bit stumped.

With a keyboard for example, I could either make it so that the `Left` arrow always moves the paddle clockwise (it starts at the bottom of the circle), or I could link it to the actual direction - meaning that if the paddle is at the bottom, it goes left and up along the circle or, if it's in the upper hemisphere, it moves left and down, both times toward the outer left point of the circle.

Both feel kind of weird. With the first one, it can be counter intuitive to press `Left` to move the paddle right when it's in the upper area, while in the second method you'd need to constantly switch buttons to keep moving.

So, long story short: is there any kind of existing standard, convention or accepted example for this type of movement and the corresponding controls? I didn't really know what to google for (`control conventions for circular movement` was one of the searches I tried, but it didn't give me much), and I also didn't really find anything about this on here. If there is a Question that I simply didn't see, please excuse the duplicate.

# Answer
> 2 votes
Usually the player remembers the direction each keys gives regardless of the position. Because of that exact moment of use. It's not an issue if each key just gives one direction.But do not take my word for it; You should play test it. There is no convention for this. Let your friends play both inputs and request feedback.

Play testing is fundamental to understand your game-design and the players better.

---
Tags: unity, movement, keyboard, control, standards
---


# Question
Title: Coding games similar to Machinarium in Java?
I wan't to see how great of an idea is to start a game project like Machinarium coded in Java. I'm not really good at Java yet, but it's the programming language I decided to go with first. Not really to learn a lot about games, but rather to have programming base if I ever decide to go with C++/C.

# Answer
JAVA is a perfectly viable language for creating an adventure game like Machinarium. All the tools are there. However if you haven't created a game before it might be a good idea to first get a good feel on how games are structured (code wise). Maybe follow a tutorial on creating text-based adventure like this one http://www.javacoffeebreak.com/text-adventure/index.html first. And then later tack on the graphics. You can use OpenGL and what not for that :).

As always, small small steps at first :)
> 3 votes

# Answer
I'm going to give my opinions about Java and explain why it's not good for games in general:

1. it's performance hungry, especially for the memory ( RAM and CPU/memory controller ), this also means that to run a simple game you need at least a computer with medium range specs
2. the JVM it's not standardize, especially on Mac, the first official Java version on Mac is the actual version ( Java 7, first and only one ), the previous versions are provided by Apple and are not standard, especially for the part related to the window system and the graphical appearance, also in many GNU/Linux installations the default JVM is OpenJDK and not Java from Oracle
3. Java generates bytecode and not compiled code, even if you obfuscates the code it's really really easy to crack, sometimes it's also easy to do reverse engineer
4. If you distribute java code you are implicitly asking the user for installing the JVM, most of the users do not have this abilities and most of the times they just expect that your program will run/install right after the download without additional software
5. for what i know Machinarium is in Flash ( probably even worst than Java ), the original one on PC/MAC/Linux, the others are porting.
6. if you are interested in Java and you want to code games, do yourself a favor and just use C#
> -1 votes

---
Tags: 2d, java, adventure-games
---


title: PokeMMO. How they do it?

text:
# Question
Title: PokeMMO. How they do it?
Well PokeMMO is a JAVA game project which basically is the original FireRed title for the GBA made online. They know this type of projects don't last long because of the copyrighted material used, but they somehow made their client extract resources from ROMS. So they don't offer any copyrighted material on their download. I wonder what technique they could be using for this? All I know is that they use LWJGL.

# Answer
> 3 votes
LWJGL is just used as a wrapper for graphics, input handling, audio etc. To extract the data from the roms, you need the specification of the ROM file format. The rom is a collection of data, that has been written by a certain rule set (the format specification). If you know this specification (by documentation or reverse engineering), you can open that file and extract the data.

You could do this with java, c, c++, c# or whatever language you like, that supports reading files.

You should find some information about the format on this page: http://nocash.emubase.de/gbatek.htm (look for the gba cartridges section).

---
Tags: 2d, java, lwjgl
---


# Question
Title: Is the game Wakfu really fully coded in JAVA?
If so, this shows that you can develop **amazing** logic/graphic wise games with JAVA. I think this should be used as an example when people ask about games developed in java instead of just mincraft and runescape.

# Answer
I'm not sure if this is some kind of weakly disguised advertising, but a quick googling says yes, Wakfu seems to be written in Java. But while it looks very nice, I don't see anything "amazing" with regard to Java or technology in general. I've only seen the trailer now and not played myself, but Minecraft seems to still be far more complex with regard to game logic - just think about the terrain generation alone. A crafting system, enemy AI, fluid spreading, day/night cycle, lighting, portals and all that won't create themselves either.

From a grahpic point of view, Minecraft doesn't have too much to show, but Wakfu seems to be made up of pretty drawn sprites and tiles, which has nothing to do with the programming language or even the engine, but more with the artists and their tools.

A game will look as good as the artwork, animations, shaders and stuff you put into it, and as long as we're not talking about really high end, GPU melting games like Crysis, I don't see why Java shouldn't be able to do it. It's the same misconception a lot of people have about specific engines: Unreal Engine 3 doesn't automatically make your game look good and a free engine doesn't automatically look bad.
> 4 votes

---
Tags: 2d, java, lwjgl
---


# Question
Title: IndexOutOfRangeException on World.Step after enabling/disabling a Farseer physics body?
Earlier, I posted a question asking how to swap fixtures on the fly in a 2D side-scroller using Farseer Physics Engine. The ultimate goal being that the player's physical body changes when the player is in different states (I.e. standing, walking, jumping, etc). After reading this answer, I changed my approach to the following:

1. Create a physical body for each state when the player is loaded
2. Save those bodies and their corresponding states in parallel lists
3. Swap those physical bodies out when the player state changes (which causes an exception, see below)

The following is my function to change states and swap physical bodies:

```
new protected void SetState(object nState)
{
    //If mBody == null, the player is being loaded for the first time
    if (mBody == null)
    {
        mBody = mBodies[mStates.IndexOf(nState)];
        mBody.Enabled = true;
    }
    else
    {
        //Get the body for the given state
        Body nBody = mBodies[mStates.IndexOf(nState)];

        //Enable the new body
        nBody.Enabled = true;

        //Disable the current body
        mBody.Enabled = false;

        //Copy the current body's attributes to the new one
        nBody.SetTransform(mBody.Position, mBody.Rotation);
        nBody.LinearVelocity = mBody.LinearVelocity;
        nBody.AngularVelocity = mBody.AngularVelocity;

        mBody = nBody;
    }

    base.SetState(nState);
}

```

Using the above method causes an `IndexOutOfRangeException` when calling `World.Step`:

```
mWorld.Step(Math.Min((float)nGameTime.ElapsedGameTime.TotalSeconds, (1f / 30f)));

```

I found that the problem is related to changing the `.Enabled` setting on a body. I tried the above function without setting `.Enabled`, and there was no error thrown. Turning on the debug views, I saw that the bodies were updating positions/rotations/etc properly when the state was changes, but since they were all enabled, they were just colliding wildly with each other.

Does Enabling/Disabling a body remove it from the world's body list, which then causes the error because the list is shorter than expected?

**Update:**

For such a straightforward issue, I feel this question has not received enough attention. Has anyone else experienced this? Would anyone try a quick test case? I know this issue can be sidestepped - I.e. by not disabling a body during the simulation - but it seems strange that this issue would exist in the first place, especially when I see no mention of it in the documentation for farseer or box2d. I can't find any cases of the issue online where things are more or less kosher, like in my case. Any leads on this would be helpful.

# Answer
Does the erroneous line in your `World.step()` method have square brackets in it anywhere? Or a `get()` method of some sort with an index in it.

This error suggests that you're asking for an object in an array or list by providing an index outside of the array bounds. Array bounds start at 0, and end at `array.Length - 1`.

So a lot of the time this error is caused by looping through objects in an array up to and including `array.Length` or `list.Count`

EDIT:

The issue appears to be here (like you suggested):

```
//Enable the new body
nBody.Enabled = true;

//Disable the current body
mBody.Enabled = false;

//Copy the current body's attributes to the new one
nBody.SetTransform(mBody.Position, mBody.Rotation);
nBody.LinearVelocity = mBody.LinearVelocity;
nBody.AngularVelocity = mBody.AngularVelocity;

```

I was looking at the code for the `.Enabled` setter in body.cs in Farseer -- I haven't used Farseer personally so I don't know the exact details of the implementation, but it does a lot of disposing and destroying things when you set enabled to false. I would recommend just rearranging your code like this and giving it a go:

```
//Enable the new body
nBody.Enabled = true;

//Copy the current body's attributes to the new one
nBody.SetTransform(mBody.Position, mBody.Rotation);
nBody.LinearVelocity = mBody.LinearVelocity;
nBody.AngularVelocity = mBody.AngularVelocity;

//Disable the current body
mBody.Enabled = false;

mBody = nBody;

```
> 2 votes

# Answer
I had this same issue and it seems like the broad phase collision detection is still run including the disabled body if this body was disabled before starting the game (something must not be catching up quickly enough). I would assume this is a bug.

I've found two solutions:

* Create the body wou will disable somewhere it will not generate a collision in the broadphase collision detection. (Very ugly, I know)
* Add the following to the ContactManager.cs-file in the method Collide() before calling BroadPhase.TestOverlap-function. (Actually I added it at line 249)

```
        if (bodyA.Enabled == false || bodyB.Enabled == false)
        {
            continue;
        }

```

If someone else has a better explanation or solution please comment or edit, I'd love to know!
> 1 votes

# Answer
It looks like the error is most likely coming from one of the two instances of this

```
mBodies[mStates.IndexOf(nState)];

```

There are two primary reasons this would happen:

* `mStates` is larger than `mBodies`, and `nState` occurs late enough in the sequence that `mStates.IndexOf(nState)` is greater than or equal to the size of `mBodies`.
* `nState` is null, or otherwise does not occur in `mStates`, causing `mStates.IndexOf(nState)` to return -1, which is most certainly out of bounds.

I suggest wrapping these occurences with a try-catch block, and throwing a new exception that gives you more detail, such as this:

```
try
{
     //Get the body for the given state
     Body nBody = mBodies[mStates.IndexOf(nState)];
}
catch
{
    throw new Exception("mBodies.Length = " + mBodies.Length + " and mStates.IndexOf(nState) = " + mStates.IndexOf(nState));
}

```

Then instead of the `IndexOutOfRange` exception, you will get an explanation of why it is out of range. If the second value is -1, nState is not in mStates. If the first value is smaller than you expected, then mBodies does not contain all the items it should (Disabled =\> Removed).
> 0 votes

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


# Question
Title: Xna, after mouse click cpu usage goes 100%
Hi i have following code and it is enough just if i click on blue window then cpu goes to 100% for like at least one minute even with my i7 4 cores. I just check even with empty project and is the same !!!

```
public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    private Texture2D cursorTex;
    private Vector2 cursorPos;
    GraphicsDevice device;

    float xPosition;
    float yPosition;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);

        Content.RootDirectory = "Content";

    }

    protected override void Initialize()
    {
        Viewport vp = GraphicsDevice.Viewport;

        xPosition = vp.X + (vp.Width / 2);
        yPosition = vp.Y + (vp.Height / 2);
        device = graphics.GraphicsDevice;
        base.Initialize();
    }

    protected override void LoadContent()
    {

        spriteBatch = new SpriteBatch(GraphicsDevice);
        cursorTex = Content.Load<Texture2D>("strzalka");
    }

    protected override void UnloadContent()
    {
        // TODO: Unload any non ContentManager content here
    }

    protected override void Update(GameTime gameTime)
    {
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {

        GraphicsDevice.Clear(Color.CornflowerBlue);

        spriteBatch.Begin();
        spriteBatch.Draw(cursorTex, cursorPos, Color.White);
        spriteBatch.End();
        base.Draw(gameTime);
    }
}

```

# Answer
Having a single core go to 100% while running the game loop is common, even in the boilerplate project. Games run a continual update/draw loop. Though you'll see different frequency for Update() vs Draw() depending on what your game is doing, they're both running in a fast loop.

If it's starting after the mouse click, I'm guessing it's because that's when the app becomes active.
> 2 votes

# Answer
**Answer for most XNA users:** This is because your game is probably running at the highest framerate it can. You can fix the framerate to solve this problem.

Inside of your function `public Game1()` place this code: `this.IsFixedTimeStep = true`

For some CPUs setting IsFixedTimeStep to true will not solve the issue. This is an XNA problem. Setting it to false will cause the application to loop with no delays between frames, allowing the framerate to go as high as the computer can get it to go. This will cause GPU usage to be higher for any users of your application, and higher CPU usage for any user that isn't experiencing the issue that the OP is.

**Answer for the OP:** XNA has issues with certain CPUs it seems like, in your specific case you'll want to set `this.IsFixedTimeStep = false`

It's also worth noting that even with `IsFixedTimeStep` is set to false, when the XNA window loses focus it will revert back to a fixed time step so that the application doesn't kill the performance of other applications when it's not in focus.
> -1 votes

---
Tags: xna
---


# Question
Title: How to build list of items available in World of Warcraft?
There are a number of non-Blizzard sites that show a complete list of available items in World of Warcraft (such as wowhead, etc). I would like to know the best (easiest) way to compile a similar list.

I believe some sites are based on user-entered input, which I would like to avoid. Looking at the lua API, it seems that there are functions to get a list of items, but it's not clear if I can just download everything (I remember a reference to throttling somewhere, can't find it now). Does anyone have code samples that would do this, or links to source?

Also, Eve Online has made a database of items available (and I do mean SQL database file for download, not the Armory) - is there anything similar for Wow?

I'm just looking for the names and stats, not the graphic icons.

# Answer
> 6 votes
Information on items, quests, etc. is all requested from the server on demand. Items have an ID and that, plus some other parameters for the things like current enchant, are what's transmitted on a chat channel when you link an item using shift-click.

There is an RPC accessible from LUA that returns a formatted description of the item which is what the UI shows in tooltips. It will also include an ID for the model (model and item ID aren't the same thing because lots of items share a model).

How do you get the IDs of the items in order to request their details? Well, players get IDs back when they loot, when they query the auction house, when they examine other players and a bunch of other ways. It's important to realise that there is no publically accessible list of all items in the game.

Websites like Thottbot and Wowhead rely on users running an addin that captures all this information and more and stores it in the file on logout. A Windows/Mac application then uploads that file to Wowhead's servers which de-dupe submissions, sanity-check it, etc. So to start a site from scratch you are going to need to develop a similar 'looter' addin and recruit players to run it and submit their data to you - the more the better.

There is another technique whereby you write some addin code that just guesses item IDs and requests the details for that item (if it exists). The issue with this is that it's against the WoW terms of use to do it on live realms (they seem to tollerate people doing it on PTRs but I wouldn't try it from my main account).

To learn how to do this you could look through the client UI's LUA source, which is included in human-readable format in the install directory. A quicker route though would be to download one of the client apps from existing WoW database sites and look at their code since that will be focussed on exactly what you want.

# Answer
> 6 votes
Every object in the game is on the client side, it's just the server side that says what that object can do. All this involves is finding a program that will unpack the proprietary data files: MPQ's and then extract them. Then you'll probably need to figure out a way to parse that data into easy to an easy to use format (XML), then you can create a program to do whatever you want with it.

HERE is an article on how to get Character Models from MPQs, I would imagine any item would be very similar.

# Answer
> 1 votes
Parts of game data is delivered to client side at all times - models, maps, intro screens etc. They were once required to be downloaded completely before you can even play, but with incremental downloading introduced in Cataclysm, you can start playing and let missing stuff download as you play, with priority given to data you need right now.

Most spell data is part of game client and so is always available once you're in game. (This, BTW, is the reason why changing tooltips require client patch even when server-side mechanic already works differntly)

As for item data and quest data, it is requested on demand for everything you see in world or query from your mailbox, equipment, inventory, auction, etc. While most sites indeed use collectors and this most of this data is available from inside the game through Lua API, as U62 mentions, many collectors only parse player-specific data in Lua and get item/quest/text data directly from WDB cache files where WoW stores everything info it downloads until wipe on next patch. It have advantage of having most complete information, less hurdles with localized data and saves you from slowing down game with collection task.

---
Tags: world-of-warcraft-modding
---


title: Updating "Inactive" Chunks

text:
# Question
Title: Updating "Inactive" Chunks
In my game, the only chunks (4x4 areas of tiles) in memory are the ones that the player is in. However, chunks need to have updates applied to them over time. A (likely) well-known example would be MineCraft: even if the player isn't in a chunk, the wheat still needs to grow over time.

My current solution is to call a method and pass in the time since the chunk was active.. but what if the chunk depends on nearby chunks for information, i.e. vines spreading or similar? Is there any reasonable solutions to this problem, or should I simply not depend on nearby chunks?

# Answer
Well, first of all in Minecraft there is a "grid" with a default radius of 10 (for a total of 21x21 or 441 chunks) around the player that is basically a grid of loaded chunks. ONLY the chunks that are inside this "grid" are updated. The chunks that are out of reach, and do not get updated. So vines will not update, and items wont despawn.

read this for more about the Minecraft chunk system:

http://www.minecraftwiki.net/wiki/Chunks

About the solution if you still would like to do this, maybe you could do some thing similar to block update in Minecraft, you could update the adjacent chunks aswell, and have an "age" to a vine and when updating it will update the adjacent blocks (even if different chunks) according to the age... I'm not sure how you would do this but I'm sure if you give it some thought you could figure out an efficient way. Although I would not recommend updating chunks that are outside of range too much because It could get to be a HUGE amount of chunks if you explore too much of the world. and then have a significant hit on performance.

Good luck!
> 0 votes

# Answer
In my game I have a similar scenario, it is a city full of NPCs (10,000+) that all need to be updated at some point, but only those in the player's view are updated every frame. However, my NPCs aren't so dependent on their surroundings so they can be updated independently of other NPCs in the area.

Here's psudo-code for how my update works.

```
void Update(float time)
{
    for (GameObject object : this.objectsNearPlayer)
    {
        // Always update all the objects near the player
        object.Update(time);
    }

    // This loops over your game objects each frame and only updates 1000 of them
    for (int index = this.startIndex; index < this.startIndex + 1000; i++)
    {
        if (index >= this.allObjects.length)
        {
            // We reached the end of the array, just break out of the loop
            // You could improve this by start at the beginning again for the remaining
            // N objects
            break;
        }

        if (this.objectsNearPlayer.Contains(this.allObjects[index]))
        {
            // Don't update nearby objects twice in one frame
            continue;
        }

        // Each game object should remember the last time they were updated
        // and use the delta between updates in their logic
        this.allObjects[index].Update(time);
    }

    // Next frame update the next 1000 objects
    this.startIndex += 1000;

    // If we reached the end of the object array, start over again
    if (this.startIndex >= this.allObjects.length)
        this.startIndex = 0;
}

```
> 0 votes

---
Tags: 2d, java, algorithm, simulations
---


# Question
Title: How to get GameElements (RigidBody) size in Unity?
I've made a prefab consisting of a Cube which I've first scaled to more resemble a brick. There's also a Rigidbody added to the cube (in the prefab). Now I want to use that prefab in a c# script to make a wall out of multiple bricks.

My question is, how can I access the dimensions of my brick (width, height, the z dimension size) so that in my script I can make bricks which are placed one next to the other (and then one on top of the other)?

I've looked at the documentation for GameObject and Rigidbody but I can't find anything helpful.

Just for refference, my script so far is:

```
public GameObject brick;

void Start () {
        Instantiate(this.brick, new Vector3(0.01326297f, -30.07855f, 100f), Quaternion.identity);
        // int brickWidth = this.brick.????;

    }

```

# Answer
> 2 votes
Have you tried using bounds ?

I guess you can achieve what you're looking for using :

```
float brickWidth = brick.renderer.bounds.size.x;

```

---
Tags: unity
---


# Question
Title: Calculating the correct particle angle in an outwards explosion
I'm creating a simple particle explosion but am stuck in finding the correct angle to rotate my particle. The effect I'm going for is similar to this:

Where each particle is going outwards from the point of origin and at the correct angle. This is what I currently have:

As you can see, each particle is facing the same angle, but I'm having a little difficulty figuring out the correct angle. I have the vector for the point of emission and the new vector for each particle, how can I use this to calculate the angle?

Some code for reference:

```
 private Particle CreateParticle()
        {
...

            Vector2 velocity = new Vector2(2.0f * (float)(random.NextDouble() * 2 - 1), 2.0f * (float)(random.NextDouble() * 2 - 1));

            direction = velocity - ParticleLocation;

            float angle = (float)Math.Atan2(direction.Y, direction.X);

...

            return new Particle(texture, position, velocity, angle, angularVelocity, color, size, ttl, EmitterLocation);
        }

```

I am then using the angle created as so in my particles Draw method:

```
spriteBatch.Draw(Texture, Position, null, Color, Angle, origin, Size, SpriteEffects.None, 0f);

```

# Answer
> 4 votes
First figure out the direction based on where the particle is in reference to where it came from (the explosion). Then you take the arc-tangent of that to get the angle.

```
Vector2 direction = particlePosition - explosionPosition;
float angle = Math.Atan2(direction.Y, direction.X);

```

# Answer
> 3 votes
Since your particles have a velocity you must have a velocity vector. Let's call the components `vx`and `vy`. You can then get the angle using:

```
atan2(vy, vx)

```

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


title: Source SDK Crash at loading screen?

text:
# Question
Title: Source SDK Crash at loading screen?
I have followed all the instructions on how to make HL2 SDK compile under Visual Studio 2010. But when I get to the loading screen I get this error from Visual Studio: Unhandled exception at 0x774815ee in hl2.exe: 0x00000000: The operation completed successfully.
I have built and debugged neither make a difference. Anyone know whats going on?

# Answer
> 0 votes
All you need to do is install the game thats required for the SDK you chose. Good luck! :)

---
Tags: c++
---


# Question
Title: Rotate canvas along its center based on user touch - Android
I want to rotate the canvas circularly on its center axis based on user touch.

i want to rotate based on center but its rotating based on top left corner .

so i am able to see only 1/4 for rotation of image.

any idea..

Like a old phone dialer .

I have tried like as follows

```
onDraw(Canvas canvas){
  canvas.save();
  // do my rotation
  canvas.rotate(rotation,0,0);
  canvas.drawBitmap( ((BitmapDrawable)d).getBitmap(),0,0,p );
  canvas.restore();
}

@Override
        public boolean onTouchEvent(MotionEvent e) {
                  float x = e.getX();
              float y = e.getY();
              updateRotation(x,y);
              mPreviousX = x;
              mPreviousY = y;
            invalidate();
        }

  private void updateRotation(float x, float y) {

          double r = Math.atan2(x - centerX, centerY - y);
            rotation = (int) Math.toDegrees(r);
        }

```

# Answer
> 5 votes
The core problem in your code is probably that you pass in `0, 0` as the pivot point to rotate about in your rotate call.

For a more robust way of expressing your transformation, in linear algebra the way to rotate about an *arbitrary point* is to *translate* the world in such a way that the point is at the origin, *rotate*, and then *translate back*.

That is, `translate(-px, -py) * rotate(theta) * translate(px, py)`, where p is the point.

# Answer
> 2 votes
You can find an example at installation of android sdk

```
android-sdks/add-ons/addon-google_apis-google_inc_-8/samples/MapDemo

```

But maybe you have to change a bit two method to get right orientation on touch event.

```
private class RotateView extends ViewGroup implements SensorListener {

/* ...  */

    private Matrix invertedMatrix = new Matrix();
    private float[] tempLocation = new float[2];

    @Override
    protected void dispatchDraw(Canvas canvas) {
        canvas.save(Canvas.MATRIX_SAVE_FLAG);
        canvas.rotate(mHeading, getWidth() * 0.5f, getHeight() * 0.5f);
        canvas.getMatrix().invert(invertedMatrix);
        mCanvas.delegate = canvas;
        super.dispatchDraw(mCanvas);
        canvas.restore();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        centeringAllowed = false;

        float[] location = tempLocation;
        location[0] = ev.getX();
        location[1] = ev.getY();
        invertedMatrix.mapPoints(location);
        ev.setLocation(location[0], location[1]);
        return super.dispatchTouchEvent(ev);
    }
}

```

This class is part of MapDemo project

---
Tags: android, rotation, html-canvas
---


title: Acceleration Based Player Movement

text:
# Question
Title: Acceleration Based Player Movement
Ok, so I am making a first person shooter game and I am currently working on movement that looks and feels good. I want to incorporate acceleration based movement for the player so that he has to accelerate to max speed and decelerate to minimum speed. Acceleration will happen when you have the key pressed and deceleration will happen when you let go of that key. The problem is that there are some instances where you switch from moving forward to moving backward where no deceleration is needed because you could potentially be moving at double speed in the reverse if you did. Does anyone have a good implementation of how to accomplish acceleration based movement that works well?

# Answer
> 5 votes
There's something weird about your concept of the issue since you say, "could potentially be moving at double speed in the reverse." This should not be the case with an acceleration-based solution.

You will have a `double playerVelocity` value in your Player class. To keep it simple for now, imagine just forward/backward velocity. Every frame, you add your acceleration value (`PLAYER_ACCELERATION`) to the player's velocity *until it reaches a maximum* \- the speed at which you generally want the player to run (`PLAYER_MAX_SPEED`). This should only take a handful of frames unless you *want* the controls to feel very "floaty". (You don't for a modern FPS.)

If the player reverses direction, you add negative acceleration. If they are moving forward at full speed and reverse direction, it will take them twice as long to get to "full speed reverse" than it does from standing still.

If the player releases all buttons, you add acceleration towards zero. The player will slow down until they stop.

An implementation:

```
final PLAYER_MAX_SPEED = 1.0f;
final PLAYER_ACCELERATION = 0.2f;
double playerVelocity = 0.0f;

public void update() {        // Called every frame, and assuming constant fps

    if (forward_button_down) {

        // The player is holding the "move forward" button
        playerVelocity += PLAYER_ACCELERATION;
        if (playerVelocity > PLAYER_MAX_SPEED) {
            playerVelocity = PLAYER_MAX_SPEED;
        }

    } else if (backward_button_down) {

        // The player is holding the "move backward" button
        playerVelocity -= PLAYER_ACCELERATION;
        if (playerVelocity < -PLAYER_MAX_SPEED) {
            playerVelocity = -PLAYER_MAX_SPEED;
        }

    } else {

        // Neither forward nor backward pressed
        if (playerVelocity < 0) {
            playerVelocity += PLAYER_ACCELERATION;
            if (playerVelocity >= 0) {
                playerVelocity = 0.0f;
            }
        } else {
            playerVelocity -= PLAYER_ACCELERATION;
            if (playerVelocity <= 0) {
                playerVelocity = 0.0f;
        }
    }
}

```

Another thing you'll probably want to do is make the player accelerate much more quickly toward zero than they accelerate beyond zero, otherwise your character will feel unresponsive.

If you use something like this for forward/backward, and another variable for left/right, you'll have to limit the combined speed (bust out your geometry), otherwise your character will move diagonally-forward faster than they move only-forward.

---
Tags: physics, game-mechanics, movement
---


# Question
Title: Making retro games: Any good known game architectures?
I'm trying to do a remake of Snowbros . I'm doing it using libgdx but at each time i must try to thought how things got done .

For example the physics of the jump and collisions . It seams to be time perfect , but i use the deltaTime to try to aproximate the value in game . I think in this case maybe its using some calcs with processor Hz , but i don't know.

Then the simple question , is there any resources of how did they programm this games? Or any idea of the simple ideas repeated each game to game in the old style retro games.

# Answer
> 0 votes
First, the question is a bit on the open-ended side. "...any idea of the simple ideas repeated each game to game in the old style retro games." It's too wide a discussion to pick any specific answer. If you had a more specific problem set, you might get better responses from others.

Specifically to your case, as mentioned in the comments you should not be trying to copy Snowbros. class framework and code design in your project. (Snow Bros. wouldn't even have had "classes" anyway.) Libgdx is a perfectly fine framework to recreate a Snowbros. clone. For each task you want to get done, think of how you want to do it for the platform you're currently working on, and implement it that way.

Now, that's not to say you shouldn't try to emulate "retro" effects in your new platform. For example many old games have slowdown when many objects are on the screen. Depending on your code and your Android platform, this will likely never happen with your simple game, but you may want to recreate the effect in same manner, most likely artificially. You should NOT, however, try and recreate this with bad code. It won't even come out the same way as a "retro" game anyway.

---

Besides all this, judging by the formatting of your question, you're getting way ahead of yourself. Just try and get your game done and working in the first place. Once you have basic things moving around, maybe then think about emulating a "perfect" retro feel. The most important thing first is to even get a project done.

It's good to think about the "right" way to do things, but especially for game development, at the end of the day/week/sprint you should just get something done. Don't let "right" *prevent* you from getting a finished product.

---

Lastly, deltaTime is a perfectly fine value to use for your update loops. Snowbros. probably would have had a constant framerate - if you want to copy this, set `deltaTime` to your desired framerate before you make the `.update(deltaTime)` calls in `AndroidFastRenderView.java`:

```
deltaTime = 1.0f / 30.0f;        // "30 frames per second" and don't care about slowdown

```

for example. Then maybe later you can implement some kind of fake slowdown later if you get that far.

---
Tags: arcade
---


# Question
Title: Which one have to use Canvas or Open GL for 2D game in Android
I am compleatly new to android gaming.
I want to develop a 2D game with some physics in it.
I want to know which one i have to use **Open GL** or **Canvas** and the **reason for selection**
I **want to include a physics engine** i dont know anything about that too
It will be very help full if anyone can share **any idea's and suggections**.
Advanced thanks to all ...

# Answer
> 3 votes
You may be confusing "Surface View" with drawing via `Canvas`.

OpenGL allows hardware rendering (makes use of the GPU), even of 2D sprites (which you render to a polygon). This also gives your sprites additional features, such as rotation, hardware scaling, or setting them up in a 3D "perspective" to do things with that (like fake parallax scrolling).

Basically if you want any of the following, you probably have to use OpenGL:

* Intensive computation - basically anything where you want as much CPU as possible, so you want to push as much to the GPU as possible. Simple physics won't count for this.
* LOTS of sprites - In the dozens or hundreds.
* LOTS of scaling or some rotating of sprites - It's (relatively) expensive to scale sprites onto the Canvas, and very expensive/troublesome to rotate sprites on your own.

Drawing bitmaps with the `Canvas` object is arguably much simpler than implementing OpenGL. However for anything intensive, you may find later the class won't cut it. Basically if you don't need to do any of the above, you should be able to get away with just using `Canvas`.

# Answer
> 1 votes
It seems you are mixing things... On Android you have to use SurfaceView to display OpenGL.OpenGL is a library and SurfaceView is the viewable part of OpenGL.

OpenGL is not a physic engine as you think,you can't handle speed,acceleration, gravity etc..this is the job of library like andengine,box 2d and many others

I recommand you to read this: http://developer.android.com/guide/topics/graphics/opengl.html

---
Tags: opengl, android
---


# Question
Title: How to export deform modifier animation into a game engine?
Hi we animated a simple plane with deform modifier to give a folding cloth like effect. How do we export it from maya so that we are able to import into our game engine.

Can we export them as a single animated file with vertex info different for each frame ?

# Answer
> 1 votes
You can export it in whatever way you want by writing your own exporter plugin for Maya.

You could also try going via FBX or another well supported format, and convert to your own format from that.

# Answer
> 0 votes
You could export it as MDD, or another baked format.

---
Tags: 3d, opengl-es, maya
---


# Question
Title: How do I repeatedly move an image by 1 pixel?
I have a method that is moving a UIImageView called `shootImg` across the screen:

```
-(IBAction)shoot{
if (appDelegate.shootInt > 0) {
    if (direction == 1) {
            shootImg.center = CGPointMake(shootImg.center.x+1, shootImg.center.y);
            appDelegate.shootInt = appDelegate.shootInt - 1;
            shootLabel.text = [NSString stringWithFormat:@"%d", appDelegate.shootInt];
                }

```

This does seem to work. But it only moves `shootImage` 1 pixel. What I want to do is make it repeatedly move 1 pixel. I tried a while loop but that didn't seem to work. I'm not using cocos2d or anything like that and if you need to see more code just ask.

Thanks :)

# Answer
```
[UIView beginAnimations:nil context:nil];
shootImg.center = CGPointMake(shootImg.center.x+appDelegate.shootInt, shootImg.center.y);
[UIView commitAnimations];

```

you can use this to animate the motion of ur image over 0.25 secs. But if you want to change the duration or any other animation properties then refer the doc.

http://developer.apple.com/library/ios/#documentation/uikit/reference/uiview\_class/uiview/uiview.html
> 2 votes

# Answer
How about making your own method in moving your object.. and inside your if statement:

a loop the calls this method: \[self performSelector:@selector(methodname) withObject:nil afterDelay:1\]; *//this calls the method that moves your object every after 1 second..* as many times as you want..
> -1 votes

---
Tags: iphone, objective-c
---


title: Creating a 3D text mesh from a 2D glyph

text:
# Question
Title: Creating a 3D text mesh from a 2D glyph
I have thought of three steps for doing this:

1. Acquire the vertex coordinates which will represent the glyph's form
2. Extrude them
3. Render

Can you suggest a better method? Can you give me an insight on how to do the first and the second step?

I use FreeType 2.4.10 for text managment.

# Answer
> 4 votes
I think, without a library, this would require quite a few steps, but it is certainly possibly.

First convert the letter to a polygon (look at the bitmap to polygon algorithms) and then that polygon to a set of triangles using a technique that supports holes in the polygon, see this wiki page. You now have a flat model built out of triangles.

Now draw the models two times. Once at (0,0,0) and once at (1,0,1) (for an effect with a shear to far away-right).

You should now have something like the picture below, but you're still missing the triangles that connect the two models and make it look 3D.

Vertices A and C are parts of the triangles of the black (front) model. Vertices B and D are parts of triangles of the white (back) model. You now have to draw triangles between them for the 3D effect. Just draw a triangle from A,B,D and from A,C,D. You have now achieved the 3D-shear effect you're looking for.

**Optimizations**

You are going to draw more triangles then you need. You don't need to draw triangles between vertices which, when connected, would cut the model. You should number/sort vertices on the edge loop and only draw triangles between (M1\[x\], M1\[x+1\], M2\[y\]) and alternate (M2\[x\],M2\[x+1\],M1\[y\]). I don't know of a readily available algorithm to detect and sort these edge loops, but take a look at how you generate vertices when triangulizing your polygon, there might be a hint/implicit sorting there. It would be even better if you can sort some sort of index buffer so that you can use a trianglestrip.

---
Tags: opengl, text
---


title: Game Development using C#.Net

text:
# Question
Title: Game Development using C#.Net
I'm a ASP as well as C#.Net Developer. I love playing Games and willing to Create one. I'm a new bi in this Arena. So can you Help me on How to Create a Game using C#.Net?? Or is there any course or a platform using which I can Develop one? Can you suggest me different platforms using which we Develop Games!

# Answer
> 3 votes
XNA would be the obvious choice for a C# beginner. I suggest installing the XNA GameStudio and getting a copy of the book XNA Game Development by Example: Beginner's Guide. It introduces you to all the important basics and concepts and leaves you well equipped to become a game developer.

If you want, you can also use Unity. It's a 3D engine, but allows for 2D development as well, and the scripts your game uses can be written in C#.

# Answer
> 1 votes
I would suggest 'Mogre', currently for windows (c# port of Ogre3d). (it does not support Monodevelop at this time). there are many tutorials and samples for Mogre.

http://www.ogre3d.org/tikiwiki/MOGRE

---
Tags: c#, software-engineering, .net, platform
---


# Question
Title: Physics System ignores collision in some rare cases
I've been developing a simple physics engine for my game. since the game physics is very simple I've decided to increase accuracy a little bit. Instead of formal integration methods like fourier or RK4, I'm directly computing the results after delta time "dt". based on the very first laws of physics :

```
dx = 0.5 * a * dt^2 + v0 * dt
dv = a * dt

```

where `a` is acceleration and `v0` is object's previous velocity. Also to handle collisions I've used a method which is somehow different from those I've seen so far. I'm detecting all the collision in the given time frame, stepping the world forward to the nearest collision, resolving it and again check for possible collisions. As I said the world consist of very simple objects, so I'm not loosing any performance due to multiple collision checking. First I'm checking if the ball collides with any walls around it (which is working perfectly) and then I'm checking if it collides with the edges of the walls (yellow points in the picture).

the algorithm seems to work without any problem except some rare cases, in which the collision with points are ignored. I've tested everything and all the variables seem to be what they should but after leaving the system work for a minute or two the system the ball passes through one of those points. Here is collision portion of my code, hopefully one of you guys can give me a hint where to look for a potential bug!

```
void PhysicalWorld::checkForPointCollision(Vec2 acceleration, PhysicsComponent& ball, Vec2& collisionNormal, float& collisionTime, Vec2 target)
{
    // this function checks if there will be any collision between a circle and a point
    // ball contains informations about the circle (it's current velocity, position and radius)
    // collisionNormal is an output variable
    // collisionTime is also an output varialbe
    // target is the point I want to check for collisions

    Vec2 V = ball.mVelocity;
    Vec2 A = acceleration;
    Vec2 P = ball.mPosition - target;

    float wallWidth = mMap->getWallWidth() / (mMap->getWallWidth() + mMap->getHallWidth()) / 2;
    float r = ball.mRadius / (mMap->getWallWidth() + mMap->getHallWidth());

    // r is ball radius scaled to match actual rendered object.

    if (A.any()) // todo : I need to first correctly solve the collisions in case there is no acceleration
        return;
    if (V.any()) // if object is not moving there will be no collisions!
    {
        float D = P.x * V.y - P.y * V.x;
        float Delta = r*r*V.length2() - D*D;
        if(Delta < eps)
            return;
        Delta = sqrt(Delta);
        float sgnvy = V.y > 0 ? 1: (V.y < 0?-1:0);
        Vec2 c1(( D*V.y+sgnvy*V.x*Delta) / V.length2(),
               (-D*V.x+fabs(V.y)*Delta) / V.length2());
        Vec2 c2(( D*V.y-sgnvy*V.x*Delta) / V.length2(),
               (-D*V.x-fabs(V.y)*Delta) / V.length2());
        float t1 = (c1.x - P.x) / V.x;
        float t2 = (c2.x - P.x) / V.x;
        if(t1 > eps && t1 <= collisionTime)
        {
            collisionTime = t1;
            collisionNormal = c1;
        }
        if(t2 > eps && t2 <= collisionTime)
        {
            collisionTime = t2;
            collisionNormal = c2;
        }
    }
}

// this function should step the world forward by dt. it doesn't check for collision of any two balls (components)
// it just checks if there is a collision between the current component and 4 points forming a rectangle around it.
void PhysicalWorld::step(float dt)
{
    for (unsigned i=0;i<mObjects.size();i++)
    {
        PhysicsComponent &current = *mObjects[i];
        Vec2 acceleration = current.mForces * current.mInvMass;
        float rt=dt;
        // stores how much more the world should advance
        while(rt > eps)
        {
            float collisionTime = rt;
            Vec2 collisionNormal = Vec2(0,0);
            float halfWallWidth = mMap->getWallWidth() / (mMap->getWallWidth() + mMap->getHallWidth()) / 2;

            // we check if there is any collision with any of those 4 points around the ball
            // if there is a collision both collisionNormal and collisionTime variables will change
            // after these functions collisionTime will be exactly the value of nearest collision (if any)
            // and if there was, collisionNormal will report in which direction the ball should return.
            checkForPointCollision(acceleration,current,collisionNormal,collisionTime,Vec2(floor(current.mPosition.x) + halfWallWidth,floor(current.mPosition.y) + halfWallWidth));
            checkForPointCollision(acceleration,current,collisionNormal,collisionTime,Vec2(floor(current.mPosition.x) + halfWallWidth, ceil(current.mPosition.y) - halfWallWidth));
            checkForPointCollision(acceleration,current,collisionNormal,collisionTime,Vec2( ceil(current.mPosition.x) - halfWallWidth,floor(current.mPosition.y) + halfWallWidth));
            checkForPointCollision(acceleration,current,collisionNormal,collisionTime,Vec2( ceil(current.mPosition.x) - halfWallWidth, ceil(current.mPosition.y) - halfWallWidth));
            // either if there is a collision or if there is not we step the forward since we are sure there will be no collision before collisionTime

            current.mPosition += collisionTime * (collisionTime * acceleration * 0.5 + current.mVelocity);
            current.mVelocity += collisionTime * acceleration;
            // if the ball collided with anything collisionNormal should be at least none zero in one of it's axis
            if (collisionNormal.any())
            {
                collisionNormal *= Dot(collisionNormal, current.mVelocity) / collisionNormal.length2();
                current.mVelocity -= 2 * collisionNormal;
                // simply reverse velocity along collision normal direction
            }
            rt -= collisionTime;
        }
        // reset all forces for current object so it'll be ready for later game event
        current.mForces.zero();
    }
}

```

# Answer
> 4 votes
This looks very similar to a problem I once had when making my own physics hack, although I can't really see from your code if this is the case here. My problem was that when an object collided at a slow speed my collision handling didn't move it enough away from the collision (so it didn't solve interpenetration). That mean that a second collision would be reported, resulting in the exact opposite contact normal to the first one, making the object just keep moving. In my case it only occurred when an object moved slowly enough making it very hard to detect. If you think this might be the case here, just use one object and set debug breakpoint to hit if you have two collisions with a very short interval.

# Answer
> 1 votes
This is probably a rounding error. They can cause both (1) missing collisions and (2) items 'sticking' together for a time.

This site explains a solution (search for '**due to rounding**' on the page):

Computer Science Canada - Perfect Circle-Circle Collision Detection

# Answer
> 0 votes
In the case of any sort of collision detection, I always check for floating point number comparisons. They are inaccurate, and often a result is not what you expect it to be when you compare them. Try truncating them to 4 digits or so.

Looking at your code however, you haven't given us much context, and the above is only a suggestion to try/check. Perhaps you could give us a more complete example?

---
Tags: collision-detection, physics, physics-engine
---


# Question
Title: Viewport.Unproject - Checking if a model intersects a large sprite
Let's say I have a sprite, drawn like this:

```
spriteBatch.Draw(levelCannons[i].texture, levelCannons[i].position, null, alpha, levelCannons[i].rotation, Vector2.Zero, scale, SpriteEffects.None, 0);

```

Picture levelCannon as being a laser beam that goes across the entire screen. I need to see if my 3d model intersects with the screen space inhabited by the sprite. I managed to dig up Viewport.Unproject, but that seems to only be useful when dealing with a single point in 2d space, rather than an area. What can I do in my case?

# Answer
Did you mean `Viewport.Unproject`? This method is used to covert a point from screen space into world space. You can follow the instructions on the MSDN page on how to convert a 2D screen space point into two separate 3D points that form a ray going into the screen.

From what I understand, you have a 2D line going across the screen and want to see what 3D objects are intersected by that line, like this?

I think what you can do is use `Viewport.Unproject` four times: on the left side of the screen for the far and near plane, then the right side of the screen for the far and near plane (really you only need three of these points). With these points you can create a `Plane` which you should use with your collision detection to see which objects fall on that plane.
> 2 votes

---
Tags: xna, 2d, 3d, collision-detection, vector
---


# Question
Title: A Quick HLSL Question (How to modify some HLSL code)
Thanks for wanting to help!

I'm trying to create a circular, repeating ring (that moves outward) on a texture. I've achieved this, to a degree, with the following code:

```
float distance = length(inTex - in_ShipCenter);
float time = in_Time;

///* Simple distance/time combination */
float2 colorIndex = float2(distance - time, .3);

float4 shipColor = tex2D(BaseTexture, inTex);
float4 ringColor = tex2D(ringTexture, colorIndex);

float4 finalColor;
finalColor.rgb = (shipColor.rgb) + (ringColor.rgb);
finalColor.a = shipColor.a; // Use the base texture's alpha (transparency).

return finalColor;

```

This works, and works how I want it to. The ring moves outward from the center of the texture at a steady rate, and is constrained to the edges of the base texture (i.e. it won't continue past an edge). However, there are a few issues with it that I would like some help on, though. They are:

1. By combining the color additively (when I set finalColor.rgb), it makes the resulting ring color much lighter than I want (which, is pretty much the definition of additive blending, but I don't really *want* additive blending in this case).
2. I would really like to be able to pass in the color that I want the ring to be. Currently, I have to pass in a texture that contains the color of the ring, but I think that doing it that way is kind of wasteful and overly-cumbersome.

I know that I'm probably being an idiot over this, so I greatly appreciate the help.

Some other (possibly relevant) information:

* I'm using XNA.
* I'm applying this by providing it to a SpriteBatch (as an Effect).
* The SpriteBatch is using BlendState.NonPremultiplied.

Thanks in advance!

EDIT: Thanks for the answers thus far, as they've helped me get a better grasp of the color issue. However, I'm still unsure of how to pass a color in and not use a texture. i.e. Can I create a tex2D by using a float4 instead of a texture? Or can I make a texture from a float4 and pass the texture in to the tex2D?

DOUBLE EDIT: Here's some example pictures:

With the effect off:

With the effect on:

With the effect on, but with the color weighting set to full:

As you can see, the color weighting makes the base texture completely black (The background is black, so it looks transparent). You can also see the red it's supposed to be, and then the white-ish it really is when blended additively.

# Answer
You might want to set weights to the colors of the ring and the ship's texture so that they can cancel each other out and don't blend additively.

Make a white ring for the ring texture which would serve as a color mask, and use a float3 uniform variable to change it's color.

```
float3 newColor;

float4 ringColorMask = tex2D(ringTexture, colorIndex);
float4 ringColor = ringColorMask * newColor;

// All rgb channels have the same values for the max texture,
// so just sample the first one
float ringWeight = ringColorMask.r;
finalColor.rgb = (shipColor.rgb * (1 - ringWeight) + ringColor.rgb * ringWeight);

```

It's hard to visualize whether the ring is supposed to just expand, or both move away and expand, but it seems like you would want to set ringWeight according to the color mask
> 2 votes

---
Tags: xna, hlsl
---


# Question
Title: android game performance regarding timers
Im new to the game-dev world and I have a tendancy to over-simplify my code, and sometimes this costs me alot fo memory.

Im using a custom TimerTask that looks like this:

```
    public class Task extends TimerTask {

    private MainGamePanel panel;
    public Task(MainGamePanel panel) {
    this.panel=panel;
    }

    /**
    * When the timer executes, this code is run.
    */
    public void run() {
    panel.createEnemies();
    }
    }

```

this task calls this method from my view:

```
    public void createEnemies() {
    Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.female);
    if(enemyCounter < 24){
        enemies.add(new Enemy(bmp, this));
    }
    enemyCounter++;
      }

```

Since I call this in the onCreate-method instead of in my views contructor (because My enemies need to get width and height of view). Im wondering if this will work when I have multiple levels in game (start a new intent). And if this kind of timer really is the best way to add a delay between the spawning-time of my enemies performance-wise.

adding code for my timer if any1 came here cus they dont understand timers:

```
    private Timer timer1 = new Timer();
    private long delay1 = 5*1000; // 5 sec delay

    public void surfaceCreated(SurfaceHolder holder) {
    timer1.schedule(new Task(this), 0, delay1); //I call my timer and add the delay
    thread.setRunning(true);
    thread.start();
}

```

# Answer
> 3 votes
TimerTask is not really the best *or* "right" way to do this. You need to update your game each frame as the execution proceeds. That way you can:

1. Account for pausing the game.
2. Adjust the gameplay if the framerate slows down.

(Though the second one is certainly not an issue for your mini-game.)

---

First, you want to figure out `deltaTime`, which is the amount of time that's passed since you last checked the system clock. I'm calling your main program loop `run()`:

```
volatile boolean running = true;

public void run() {
    long startTime = System.nanoTime();

    while (running) {
        float deltaTime = (System.nanoTime() - startTime) / 1000000000.0f;        // Makes deltaTime into fractions of seconds
        startTime = System.nanoTime();

        // Rest of game code, including your "onDraw" code.
        ...
    }
}

```

Now you want to keep a value or class, your `timer`, that you add the deltaTime to once per "frame" of your game (i.e. each time your game draws itself). Once the accumulated time reaches 5 seconds, you can call your enemy spawner.

```
volatile boolean running = true;

public void run() {
    long startTime = System.nanoTime();

    while (running) {
        float deltaTime = (System.nanoTime() - startTime) / 1000000000.0f;        // Makes deltaTime a more reasonable-looking size of time
        startTime = System.nanoTime();

        spawnEnemyTimer += deltaTime;
        if (spawnEnemyTimer >= 5.0f) {        // 5.0f == 5 seconds
            createEnemies();                  // The method you listed in your question
            spawnEnemyTimer -= 5.0f;
        }

        // Rest of game code, including your "onDraw" code.
        ...
    }
}

```

Now, to pause, you simply stop `running`, and start running when you 'resume':

```
public void onPause() {
    running = false;
    ...
}

...

public void onResume() {
    running = true;
    ...
}

```

When the system enters your `run()` code again, your `startTime` is reset, so any system time spent while your app was paused is automatically accounted for.

---

You should make as many other elements rely on the deltaTime value as possible. This means, however, you can no longer assume frames of your game as a "fixed" time. Your enemies and bullets should have like a "speedPerSecond" value and each frame they move deltaTime's percentage of that distance.

```
distanceMoved = speedPerSecond * deltaTime;

```

If your game was just incrementing everything each frame before (like enemies moved X amount every time you drew), you should have a timer that's counting frames, instead of counting real time.

---
Tags: android, performance, timer
---