title: How to generate an explosion?

text:
# Question
Title: How to generate an explosion?
I'm currently working in an Angry Bird-esque game, where the user flings a bomb at buildings and the bomb explodes.

How do I create explosions in Corona? Essentially some sort of area of effect explosion should occur on collision, which pushes all the elements within the area out of the way (this could probably be done with applyForce)

I've tried the following, but left me with lackluster results:

```
function setExplosion(self, event)
    event.other:applyForce(300, 300, circle.x + (circle.width/2), circle.y + (circle.height/2))
end

```

Note that the circle is the explosion radius.

Anybody have any tips on creating explosions?

EDIT:

```
function setExplosion(self, event)
    event.other:applyForce(500, 500, circle.x + (circle.width/2), circle.y + (circle.height/2))
end

function drawExplosion(eventX, eventY)
    return function()
        circle = display.newCircle( eventX +20, eventY +20, 150 )
            circle.myName = "circle"
            game:insert(circle)
       circle:setFillColor(100,100,100, 100)
     physics.addBody( circle, "static", {isSensor = true} )
        circle.collision = setExplosion
        circle:addEventListener( "collision", circle )
end
end

```

# Answer
From my limited knowledge and research, you seem to be incorrect in application of the force from the explosion. My above comments discuss this further, but put simply, you should not be applying a uniform force of {300, 300} to all bodies, unless you want to hurl them at a 45-degree angle with the same amount of force. If you want a realistic explosion, you should be applying a somewhat normalized force outwards from the center of your explosion to each body, and scale it down based on distance from the explosion's center.

The general procedure I follow for processing explosions is this:

* Locate the area of influence, and enumerate all bodies within it. (This is the part you seem to have down already.)
* For each body, calculate two points:

+ The "target point", which is a point (or multiple points; you can get creative here) on the body at which the force is applied.
    + The center of the explosion (which you have already done).
* Get the direction of the explosion's force upon the body, by subtracting the center point from the target point.
* Normalize the vector to get the core directional vector.
* Based on the original (non-normalized) vector's magnitude, apply some distance scaling function to the normalized vector to get your resultant force vector.

+ One possible way would be to multiply the normalized vector by some large "explosion power" value, then divide it by the squared magnitude of the original vector to scale it down.
* Use the resultant force vector's X and Y components as the first two arguments to `applyForce`, and the target point's X and Y components as the last two.
> 2 votes

---
Tags: lua, corona-sdk
---


title: collision test between ball and rect

text:
# Question
Title: collision test between ball and rect
need help with collision between ball and rect. i dont know how to test if ball hit the rec from top, bottom, right or left.

```
x = ball x
y = ball y
radius = ball width and height
rx = rect x
ry = rect y
rheight = rect height
rwidth = rect width

main game loop:

x += dx;   //keep the ball moving so i can test the collision
y += dy;

//collsion between ball and box
if(x+radius > rx && x < rx+rwidth)
 {
if(y+radius > ry && y < ry+rheight)
{
  if(y+radius == ry)
    {
    System.out.println("top");
    }
   else  if(y == ry+rheight)
    {
     System.out.println("bottom");
    }
   else if(x+radius == rx)
        {
    System.out.println("left");
        }
     else if(x == rx+rwidth)
    {
     System.out.println("right");
    }
   }
}

```

# Answer
The code that you are using does not check for the collisions from right and bottom side, it only checks when the ball collides from top left side.
For this case the above code fails to check for a collision

take a look at this code its just basic detection not very accurate but you should get the point. Hope this helps.

```
if (ballLocation.Center.Y > BrickLocation.Y && ballLocation.Center.Y < (BrickLocation.Y + BrickLocation.Height))
            {
                if (BrickLocation.Center.X > ballLocation.Center.X)
                {
                    velocity.X = mod(velocity.X) * -1;
                }
                else if (BrickLocation.Center.X < ballLocation.Center.X)
                {
                    velocity.X = mod(velocity.X);
                }
            }
            else if (ballLocation.Center.X > BrickLocation.X && ballLocation.Center.X < (BrickLocation.X + BrickLocation.Width))
            {
                if (BrickLocation.Center.Y < ballLocation.Center.Y)
                {
                    velocity.Y = mod(velocity.Y);
                }
                else if (BrickLocation.Center.Y > ballLocation.Center.Y)
                {
                    velocity.Y = mod(velocity.Y) * -1;
                }
            }

```
> 1 votes

---
Tags: collision-resolution
---


title: AAA quality game UI kit

text:
# Question
Title: AAA quality game UI kit
I have often come across many websites which provide free/ paid PSD layouts of website UIs for use by web/ graphics developers. Are there any such sites where one can find PSD layouts of UI kits for games?

Actually I am looking for some AAA quality game UI and menu screen kits - I have something like the ones in Crysis 2 and Crysis 3 in mind.

# Answer
> 2 votes
Ok, this only required Google-fu but I'll answer it

---
Tags: gui
---


# Question
Title: Component based game engine and dependencies - singletons
I am thinking about how to create component based game engine. I understand that all things should be very similar as in Data Oriented Design (each object is a collection of various structures as Position, 3D Model, Health, Damage etc.), but I don't understand how should I handle the very big project.

I made one game in XNA a while ago and when I tried to create such component based game engine - I ended up having many singletons. Many systems depend on each other and I had to use for example Terrain subsystem to handle AI - so I had to make singletons.

How should I organise the game engine so that I wouldn't have singletons? Is it even possible when I have many dependencies?

Also when I created many Entities I found the problem or repetition of code. If I want to for example make AI for few kinds of enemies - some code can be the same for various enemies (Initializing AI, beginning of AIUpdate function) - it appears that inheritance would be best for such case, but then it isn't component based architecture (or Data Oriented Design) anymore...

# Answer
Some month ago I asked myself the same question. Since my data orientated engine makes good progress, I can give you some advice.

Generally speaking, the key is to separate data and function. This way components can be connected only by the data they modify instead of being connected directly with each other.

Each component inherits a `Init()` and a `Update()` function from an abstract base class and that's it. The components neither know of each other nor do they call other's functions. Moreover component don't store data as class members but in global storages. This results in nearly stateless components, the state is given by the global data.

As I said, data is stored globally so that every component can fetch and modify the same data. Therefore I use a global data manager. It allows to create entities, which are nothing but an global number, and assign properties to them. There properties can be position data, buffers, health points, and so on. One important thing is here for the data manager to provide a function to fetch all properties of the same type. This allows a component to process all properties related to itself. For example the physics component fetches all position properties, loops over them, performs collision checks and updates the coordinates. The renderer component fetches the same data along with other properties like mesh buffers and materials to draw each form at the right place.

As a developer you are very flexible in such a architecture. Since there are no direct dependencies between components, you could for example just remove the physics component. The code would compile successfully and all other modules would still work as expected. Only the global position data won't be updated anymore and the scene stands still. As you might see this also allows you to change component, that means separate functionalities, with easy. The new component just have to modify the same data storages than the one before.

It might sound elaborate to developers who prefer object oriented design to get rid of all dependencies between components. But indeed it results in very encapsulated, easy to maintain and fast code. I told you that my own little game engine is based on this architecture. If you are interested, feel free to visit the Github repository take a look around.

As a side note, this architecture isn't guaranteed to be data oriented in the narrow sense of the word. It definitely uses that paradigm, that means data is stored in long lists by property and not by object. But it depends on the implementation whether the structure of your global data storages actually fit the CPU cache or not.

You might also want to read this question about data driven design in game engines.
> 4 votes

# Answer
First of all there is no absolutely right way of creating a component based engine. It depends on a concrete game. I can show how I do it developing a usual platformer.

```
//BaseEntity for platformer contains typical components for world entity, i.e. coordinates in world and hp amount
public class BaseEntity{

    protected LiveComponent liveComponent;
    protected PositionComponent positionComponent;

    public BaseEntity(LiveComponent liveComponent, PositionComponent positionComponent){
        this.liveComponent = liveComponent;
        //LiveComponent is interface and it could be just a container for data about current HP,
        //or implementation for immortal entity, or implementation of complex HP behaviour(increasing of HP depending on time for example).
        this.positionComponent = positionComponent;
        //PositionComponent is also interface and it could be implementation with Box2D body or just static rectangle witch constant position.
        //Moreover, it could contain 2D position or 3D position in the world.
        addComponent(liveComponent);
        addComponent(positionComponent);
    }

    public BaseEntity(){
        //constructor for more flexible entity creation.
    }

    public void reset(ResetData resetData){
        //method for reusing your entity. For example when entity dies you put in some pool.
        //When you need to create a new one you just take it from pool and call this method.
        //ResetData could contain new position or some new state.
    }

    public float getHP(){
        return liveComponent.getHP();
    }

    public Position getPosition(){
        positionComponent.getPosition();
    }

    public void setPosition(Position position){
        positionComponent.setPosition(position);
    }

    public void setDamage(float damage, DamageType type){
        liveComponent.setDamage(damage, type);//type is magic or melee, for example
    }

    public void update(float deltaTime){
        //iterate and update all components
    }

    public void destroy(){
        //destroy all components and clean references
    }

    protected void addComponent(Component component){
    //protected for inherited classes
    }

    protected BaseComponent getComponent(){
        //You can't avoid interaction of components.
        //But you must understand that the more your components interact with each other the harder it will be to use them.
    }
}

//Base enemy class
public class Enemy extends BaseEntity{

    protected ViewComponent viewComponent;

    public Enemy(ViewComponent viewComponent, LiveComponent liveComponent, PositionComponent positionComponent){
        super(liveComponent, positionComponent);
        this.viewComponent = viewComponent;
        super.addComponent(viewComponent);
        //ViewComponent is something which displays your entity.
        //It could be just frame switcher. Also it contains methods to control what it should show.
    }
}

//Concrete enemy
public class SimpleZombie(){

    private const String ATLAS_ID = "NormalZombieAtlasId";//path or id of visual data of your entity. You can leave these data inside every new entity or somewhere else
    private const int MAX_HP = 10;//Max HP

    private MoveAndAttackAI moveAndAttackAI;

    public SimpleZombie(float x, float y){
        super(new ViewComponent(ATLAS_ID),
              new LiveComponent(MAX_HP),
              new PositionComponent(x, y)
        );

        moveAndAttackAI = new MoveAndAttackAI(super.postionComponent, super.viewComponent, new MeleeWeapon(3)));
        super.addComponent(moveAndAttackAI);
        //first interaction of components and it is ok.
        //MoveAndAttackAI controls position of zombie(through setting concrete coordinates or application of forces if it is box2d body).
        //If zombie goes left it tells to viewComponent to show move animation directed to the left
        //MeleeWeapon is a weapon with max damage of 3 points
    }

    override public void reset(ResetData resetData){
        super.positionComponent.setPostion(resetData.position);
        super.liveComponent.reset(MAX_HP);
        moveAndAttackAI.reset();
    }

}

```

And some advice:

* One task implies one component. Component should be simple and do one exact work.
* It's ok if you have some interaction of components.
* It's ok if a component contains state, but stateless components are more preferable.
* Don't try to create super universal components.

PS Interaction of entities is a game dependent topic. For example, box2d has it's own system of colliding.
> 0 votes

---
Tags: architecture, component-based, design-patterns
---


title: collision between two objects

text:
# Question
Title: collision between two objects
to test collision i am using intersect function.

```
if(this.getBounds_ball().intersects(this.getBounds_rect()))
{

```

but the problem is i dont know how to test where the ball is collision from. i was thinking it will have a if statment inside to check if ball is collsion from left. another for right, top and bottom. so 4 if statments? but i dont know how to code it. any ideas? any ideas?

# Answer
I don't know if it's the best solution but I've used something similar. I found how much one object is overlapping the other and adjust accordingly.

```
xOverlap = boundsA.X - boundsB.X;
yOverlap = boundsA.Y - boundsB.Y;

```

then just watch those variables and you should be able to see where you stand. There's probably a better way though I'm still new.
> 0 votes

---
Tags: collision-resolution
---


title: Resynchronize game state on reconnect

text:
# Question
Title: Resynchronize game state on reconnect
Suppose in a multiplayer first person shooter game that a player loses their connection. On reconnect they need to synchronize with the current game state. But while they are getting a snapshot of the game state from the server the state is changing in realtime and these need to be sent as well.

This seems like a common problem. Is there a tutorial on how to architect this in a bug free manner, and explain the gritty details of the design patterns used?

# Answer
> 3 votes
Don't make your game state so complex that sending it takes so long that the normal update stream is no longer valid. If your network layer can deal with lag of up to 3s, for instance, you need to be able to send the necessary state in under 3s.

There's no specific architecture to this. Since sending the initial state is almost identical to just sending an update for every object in the client's area of interest (plus a relatively minor set of additional data), and since you're already hopefully working hard to handle the case where you must update every object in the client's area of interest, there's not much more to do.

The only really big architecture thing to consider is that area of interest bit. Don't try to literally send the *whole* game state. The client doesn't need information about far-away objects, nor does it need to know the value of every single property of nearby objects; it just needs the data to do reasonable prediction and simulation to make gameplay smooth. This has nothing to do with desync directly; this is just good network programming for games.

To handle area of interest properly, you need a NewObject message type (or set of messages) that you have to be prepared to send to the client as the player moves or objects around the player move. Joining a game just means sending a bunch of those for all objects near the area the player is entering the game (same as when a player teleports or respawns, really), and then a few messages about some other global state (team scores, player inventory, which skins/models/names the other players are using, etc.) but nothing that should take an exorbitant amount of time to send.

You can try to multiplex update and setup messages. Don't actually make the player "in the game" until it has all the necessary data. That way you can intermix update messages with "team score" messages if there is a problem with bandwidth or dropped packets, but again, this should not be necessary. Implementing message priorities help with them; keep the initial setup messages at very low priority so that they can't use up all the bandwidth if update messages are being generated. Once the client has enough initial state to play, the player's avatar can be spawned in-game on the server and he can start playing.

One case where this technique is handy is in low-importance but large-size data, like a team's custom logo or a player's custom skin. You don't *need* this data to play. You can stream it after the player actually joins. If priorities and bandwidth limits means it takes 5s for that purely-visual data to come across, no problem. The game plays just fine without it.

If you're having trouble getting game state across, you're either just sending too much irrelevant data or there's a serious connection problem and reconnecting should just fail; no reason to join a game that'll just desync again shortly because the connection is bad. If the client can't even reconnect and join properly without problem, it should *stop* trying to reconnect to help try to reduce server load in the event that the problem is an overloaded server.

---
Tags: architecture, state, synchronization
---


# Question
Title: How to calculate the distance between a Vector3 and a (3D polygon triangle)?
How to calculate the distance between a Vector3 and a (3D polygon triangle)?

for example : " float DistanceToTrianale( Vector3 pos, Vector3 Edges1, Vector3 Edges2, Vector3 Edges3)

thanks in advance

# Answer
Here is a nice guide to the problem, with implementation:

http://www.geometrictools.com/Documentation/DistancePoint3Triangle3.pdf
> 1 votes

---
Tags: 3d
---


title: Camera not strafing (GLSL)

text:
# Question
Title: Camera not strafing (GLSL)
I use this code in my GLSL vertex shader, where `v_position` is the vertex position:

```
gl_Position = v_position * u_camera;

```

and set `u_camera` as follows:

```
meshShader.setUniformMatrix("u_camera",
camera.view.mul(camera.projection).inv());

```

With the camera being an `PerspectiveCamera` of fov 45, width = aspect ratio and height = 1

This code is working when translating the camera over the z axis:

```
if (Gdx.input.isKeyPressed(Keys.W)) {
        camera.translate(0, 0, CAMERA_SPEED * Gdx.graphics.getDeltaTime());
} else if (Gdx.input.isKeyPressed(Keys.S)) {
        camera.translate(0, 0, -CAMERA_SPEED * Gdx.graphics.getDeltaTime());
}

```

But not when doing the same thing as above on the x axis, with the `A` or `D` keys.

The mesh (a triangle) looks like this before i press `A` or `D` (Translating with `W` and `S` is fine)

But when translating over the X axis it it looks like this:

I don't know anything of matrix math, and I made this code experimenting with the various matrices of the `Camera` class

EDIT : This code  `camera.projection.mul(camera.view.inv())` does a similiar thing

# Answer
```
meshShader.setUniformMatrix("u_camera",
camera.view.mul(camera.projection).inv());

```

Well first of all, you're (probably, judging by the notation) inverting the view AND projection matrices. This isn't correct. The inversion is only a part of the creation of a view matrix.

Also, an orthographic camera doesn't have a FOV, so i'm not sure if you haven't gotten some things mixed up because of that as well.
> 1 votes

---
Tags: opengl, java, camera, libgdx, matrix
---


# Question
Title: Get back or delete an existing OpenGL object, then change it and draw at new. How?
With OpenGL i'm drawing for example a circle.

Can i take this drawn circle back out of the window and change something and then draw it back on the window?

Or can i /have to delete it and then draw it new with other properties?

Do someone have me a link etc how to do something like this?

**edit** it is just about 2D objects

# Answer
Usually, you have a list of objects. Each frame, you iterate over the list and call the current objects draw function. When you skip objects or remove them from the list, they don't get drawn.

So, either, in onSurfaceCreated, you would create the list of objects to draw and where you call

```
body.draw(gl);
eyes.draw(gl);
mouth.draw(gl);

```

in onDrawFrame you'd have to iterate over this list.

Then, outside the onDrawFrame Method, you could add/remove objects to/from the list to have them render or not.

Also, I'd recommend you to read 'Java ist auch eine Insel' from Gallileo Computing, freely available here: http://openbook.galileocomputing.de/javainsel/

Edit:

You might want to read up on matrix transforms and the opengl matrix stack.

Use one ViewMatrix to set your camera (like you're doing currently with GLUlookat), then use one modelmatrix per model to draw your objects in the right position.

Although it is for delphi and not for java, http://wiki.delphigl.com/index.php/Hauptseite is one of the best german opengl references.

http://wiki.delphigl.com/index.php/Hintergrundwissen has explanations for the background knowledge and http://wiki.delphigl.com/index.php/Tutorial is a series of tutorials.
> 2 votes

---
Tags: java, android, opengl-es, opengl-es2
---


# Question
Title: Inputting Only Alphabetical Input - Slick2D
I'm trying to obtain the user input for when they enter their own name. However I would prefer to have it Alphabetically.

This is what I'm doing at the moment:

```
    if (input.isKeyDown(Input.KEY_A)) {

    }
    if (input.isKeyDown(Input.KEY_B)) {

    }
    if (input.isKeyDown(Input.KEY_C)) {

    }
    //continued for each letter.

```

Is there an easier way to obtain the input? An hopefully make sure its only alphabetical?

# Answer
> 1 votes
The Java `Character` class has a simple `isLetter` function.

The easiest way to handle key presses is to create a class that implements the `KeyListener` class. A little example would be:

```
public class MyKeyListener implements KeyListener {

     @Override
     public void keyPressed(int key, char c) {
         if(Character.isLetter(c)) {
             //do letter stuff

         } else {
             //do other stuff
         }
     }

     @Override
     public void keyReleased(int key, char c) {
         //do released key stuff
     }
}

```

Create an instance of `MyKeyListener` and then use `input.addKeyListener(myKeyListenerInstance)` to add the listener to your input.

# Answer
> 0 votes
Make an input handler class which stores the result of your key strokes then filter what you need using a regex.

A simple `[a-zA-Z]` will do the job.

Edit: You make a method which you call each tick that stores the current keys as an array

```
public List<char> pollInput() {
    List<char> keys = new ArrayList<char>;
    while (Keyboard.next()) {
        keys.add((char)Keyboard.getEventKey());
    }
    return keys;
}

```

Then you convert the list to an array and to a string which you pass through a regex. (Sorry i'm typing on a phone so i'm doing this all from memory).

---
Tags: java, slick
---


title: changing coordinate system

text:
# Question
Title: changing coordinate system
I'm currently trying to transform a system by scaling it on `x` and `y` axis and have some uncertainty. I have the general concept that scaling works as such:

My original box has corners at `(0, 0)` and `(3, 2)` and I'm asked to scale the `x` axis by `3` and the `y` axis by `-2`.

Is this what the correct solution would look like (with corners at `(0,2)` and `(6,-2)`)?

# Answer
> 2 votes
Given the points you have, no. The new rectangle will be defined by the points (0, 0) and (6, -4). The point on the origin will not scale to a new position where are the other point you have will. Scaling by -2 in the y will flip the rectangle so instead of having a point in the bottom left and top right it will now be in the top left and bottom right.

---
Tags: 2d, transformation
---


# Question
Title: Different types of smooth object movement
In a game I have a specific object and two positions the object will move from and to. I already have the function for calculating current position in specific time.

It works like this:

Inputting 0 will move the object to Position 1.

Inputting 1 will move the object to Position 2.

Inputting 0.5 will move the object in the middle of the two positions.

etc...

(In the examples below, time is varying from 0 to 1) When I want to start the object slowly and stop it when it is moving fast, I use:

```
MoveObject(sin(time * 90))

```

When I want to start the object fast and stop it as it is getting slower, I use:

```
MoveObject(1 - cos(time * 90))

```

Without the effects, it's:

```
MoveObject(time)

```

How do I make the object start moving slowly, move fast in the center of two positions and then get slower while reaching the second position?

# Answer
> 2 votes
You are looking for easing functions...

Here you have some desription: http://www.gizma.com/easing/#expo1

I wrote a reply about them here with my own implemntation in C#

https://gamedev.stackexchange.com/a/26872/8390

---
Tags: mathematics
---


title: Can't call method out of a timer. Why?

text:
# Question
Title: Can't call method out of a timer. Why?
I have another problem i can't solve by myselve.

My situation: I have four FrameLayouts in LinearLayouts.

I color them, set Layout hight and width at wrap content and just change the minwidth to use them as a status or progress bar.

To adjust the bars i have a method:

```
public void update_bars(){

    FrameLayout bar_eat = (FrameLayout)findViewById(R.id.bar_eat);
    FrameLayout bar_drink = (FrameLayout)findViewById(R.id.bar_drink);
    FrameLayout bar_wash = (FrameLayout)findViewById(R.id.bar_wash);
    FrameLayout bar_care = (FrameLayout)findViewById(R.id.bar_care);

    bar_eat.setMinimumWidth((int)(((float)screen_part/1000)*eat));
    bar_drink.setMinimumWidth((int)(((float)screen_part/1000)*drink));
    bar_wash.setMinimumWidth((int)(((float)screen_part/1000)*wash));
    bar_care.setMinimumWidth((int)(((float)screen_part/1000)*care));
}

```

This method works fine from everywhere in my activity. But i also want to call this update\_bars() method every second so i made a timer for it.

```
private void update(){

    Timer timer = new Timer();
    timer.schedule(new TimerTask(){

        @Override
        public void run() {
            update_bars()

        }

    },0,(1000* getResources().getInteger(R.integer.remove_speed_inSecond)));

```

But at this point it crashes....

The debugger says this:

> Thread \[\<12\> Timer-0\] (ViewRootImpl$CalledFromWrongThreadException)
> Timer$TimerImpl.run() Zeile: 290

So where it the problem? And what can i do? I woud be very happy if someone have an idear because i'm going crazy^^

# Answer
> 1 votes
Timer creates new thread. You can't update UI from non UI thread. Use Handler, AsyncTask or runOnUiThread method.

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


title: Can Cruncher crunch Daz models?

text:
# Question
Title: Can Cruncher crunch Daz models?
I have a number of Daz 3D models that I would like to use in my Unity shooter game. The only problem seemed to be the high poly count of the Daz models.

However, I just came across the Cruncher Polyreduction tool (http://assetstore.unity3d.com/#/content/4294). Is it possible to use this plugin to incorporate Daz models in my game?

# Answer
> 1 votes
As long as the file extension will be compatible with unity itself, the cruncher should work with no problems. Export it as one of unity-compatible extensions .FBX .OBJ etc. :)

Here is the list of all supported file extensions. http://unity3d.com/unity/workflow/asset-workflow

The only problem you may encounter is that if the ammount of vertices is beyond 64k~ then the unity will not let you import that asset. You will have to split it into a few models so that it has less vertices than aprox. 64,000. Of course, unless the cap has been made higher.

---
Tags: unity
---


# Question
Title: Type Error for hit testing two objects created with actionscript
I am making a zombie shooter game where I get an error when I try to hit test two objects created with actionscript. Could someone post a possible fix please.

Here is the Error Code;

```
TypeError: Error #2007: Parameter hitTestObject must be non-null.
    at flash.display::DisplayObject/_hitTest()
    at flash.display::DisplayObject/hitTestObject()
    at game3_fla::MainTimeline/zombiemove()

```

and here is my game code;

```
import flash.events.Event;
var zombiehits:Number = 2;
var numzombies1:Number = GenerateRandomNumber(10);
var zombie : Z = new Z();
var objz;
var objb;
stop();
//Change mouse
crosshair_mc.mouseEnabled = false;
crosshair_mc.addEventListener(Event.ENTER_FRAME, fl_CustomMouseCursor);
Mouse.hide();
//EventListners;
stage.addEventListener(Event.ENTER_FRAME, alwayson);
stage.addEventListener(MouseEvent.MOUSE_MOVE,facecursor);
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
//Code;
var startcountdown:Number = 5;
var fl_CountDownTimerInstance:Timer = new Timer(1000,startcountdown);
fl_CountDownTimerInstance.addEventListener(TimerEvent.TIMER_COMPLETE, startgame);
fl_CountDownTimerInstance.start();

function createZombie():void
{
    zombie.rotation = 90;
    zombie.height = 85.35;
    zombie.width = 55.9;
    zombie.x = 403.25;
    zombie.y = -86.9;
    addChild(zombie);
    trace("spawned the zombie");
    zombie.addEventListener(Event.ENTER_FRAME,zombiemove);
}

function zombiemove(event:Event)
{
    var zombie = event.currentTarget;
    objz = zombie;
    zombie.y +=  1;
    if (zombie.hitTestObject(objb) == true)
    {
        dead -=  1;
    }
    if (dead == 0)
    {
        removeChild(zombie);
        zombie.removeEventListener(Event.ENTER_FRAME,zombiemove);
    }

}

function alwayson(event:Event)
{
    if (character_mc.hitTestObject(wallleft) == true)
    {
        character_mc.x +=  speedchar;
    }
    if (character_mc.hitTestObject(wallright) == true)
    {
        character_mc.x -=  speedchar;
    }
    if (character_mc.hitTestObject(walltop) == true)
    {
        character_mc.y +=  speedchar;
    }
    if (character_mc.hitTestObject(wallbottom) == true)
    {
        character_mc.y -=  speedchar;
    }
}

function fl_CustomMouseCursor(event:Event)
{
    crosshair_mc.x = stage.mouseX;
    crosshair_mc.y = stage.mouseY;
}

function facecursor(event):void
{
    character_mc.rotation = (180 * Math.atan2(mouseY - character_mc.y,mouseX - character_mc.x))/Math.PI;

}

function mouseDown(event)
{
    var b = new Bullet();
    b.x = character_mc.x;
    b.y = character_mc.y;
    b.angleRadian = Math.atan2(mouseY - character_mc.y,mouseX -character_mc.x);
    b.addEventListener(Event.ENTER_FRAME, bulletEnterFrame);
    addChild(b);
}

function bulletEnterFrame(event)
{
    var b = event.currentTarget;
    objb = event.currentTarget;
    b.x +=  Math.cos(b.angleRadian) * speedb;
    b.y +=  Math.sin(b.angleRadian) * speedb;
    b.rotation = b.angleRadian * 180 / Math.PI;
    if (b.hitTestObject(objz) == true)
    {
        removeChild(b);
        b.removeEventListener(Event.ENTER_FRAME, bulletEnterFrame);
    }
    if (b.x < 50 || b.x > 675 || b.y < 50 || b.y > 500)
    {
        removeChild(b);
        b.removeEventListener(Event.ENTER_FRAME, bulletEnterFrame);
    }
}
character_mc.addEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);

function fl_MoveInDirectionOfKey(event:Event)
{
    if (upPressed)
    {
        character_mc.y -=  speedchar;
    }
    if (downPressed)
    {
        character_mc.y +=  speedchar;
    }
    if (leftPressed)
    {
        character_mc.x -=  speedchar;
    }
    if (rightPressed)
    {
        character_mc.x +=  speedchar;
    }
}

function fl_SetKeyPressed(event:KeyboardEvent):void
{
    switch (event.keyCode)
    {
        case Keyboard.UP :
            {
                upPressed = true;
                break;

            };
        case Keyboard.DOWN :
            {
                downPressed = true;
                break;

            };
        case Keyboard.LEFT :
            {
                leftPressed = true;
                break;

            };
        case Keyboard.RIGHT :
            {
                rightPressed = true;
                break;

        }
    }
};

function fl_UnsetKeyPressed(event:KeyboardEvent):void
{

    switch (event.keyCode)
    {
        case Keyboard.UP :
            {
                upPressed = false;
                break;

            };
        case Keyboard.DOWN :
            {
                downPressed = false;
                break;

            };
        case Keyboard.LEFT :
            {
                leftPressed = false;
                break;

            };
        case Keyboard.RIGHT :
            {
                rightPressed = false;
                break;

        }
    }
};

function GenerateRandomNumber(limit:Number):Number
{
    var randomNumber:Number = Math.floor(Math.random() * (limit + 1));
    return randomNumber;
}

function startgame(event:Event)
{
    createZombie();
    trace("complete");
}

```

# Answer
objb is likely null because you haven't fired a bullet yet, but your zombiemove function is testing with that variable.

try this :

```
function zombiemove(event:Event)
{
    var zombie = event.currentTarget;
    objz = zombie;
    zombie.y +=  1;
    if (objb != null)
    {
         if (zombie.hitTestObject(objb) == true)
         {
              dead -=  1;
         }
    }
    if (dead == 0)
    {
        removeChild(zombie);
        zombie.removeEventListener(Event.ENTER_FRAME,zombiemove);
    }

}

```
> 0 votes

---
Tags: actionscript-3
---


title: Setting up openGL on Linux

text:
# Question
Title: Setting up openGL on Linux
I am trying to figure out how to set up openGL on Linux based operating systems (Ubuntu 12.10) without using any \*GLUT libraries. I don't have much experience with developing on Linux distributions.

To be more precise I'm trying to make a statically linked library that compiles on the three major OS flavours (using some preprocessor macros to figure out the os its being compiled on and switch up renderer code, window creation code etc).

On windows I have successfully created a openGL 4.0 rendering context using `wglCreateContextAttribsARB` and the `GL/gl.h` provided by mingw.

On Ubuntu I have managed to create a openGL 2.2 rendering context using `glXCreateContextAttribsARB` and the `GL/gl.h` provided by mesa3d. This was however in a VMware Ubuntu VM and so mesa(9.0.2 I believe) would only manage to go that far with a virtual graphics card.

So I decided to go ahead and install Ubuntu on a external HDD to take advantage of the graphics card only to later find out that mesa(9.1) can only go up to openGL 3.1. After a little bit of research I figured out that the AMD and Nvidia drivers have support for openGL 4.3. So I installed the AMD 13.1 drivers (I have a *Sapphire 7970 vapor-x 6GB*) but then the openGL header files that come with it are really strange, `GL/glATI.h` tries to include `windows.h`, it doesn't define `APIENTRY` etc.

The question is whats the proper way of setting up openGL (with 4.3 support) for Linux? And even if the `GL/glATI.h` files were proper, wouldn't they fail if ran on a Nvidia card?

---

I'm manually creating the window with `XCreateWindow` and then I'm loading the extensions with `glXGetProcAddressARB` so I'm not going to use GLUT or any GLUT-like library.

# Answer
The OpenGL setup is rather straightforward under linux, in comparison to windows. If you link to -lGL you will dynamically link to whatever OpenGL library is installed and should be used, so under a X11-Environment with nvidia driver it will link to the NVidia specific libgl, with a ATI driver to the ATI specific libgl, the OpenGL libs of the different vendors have all a compatible ABI, so nothing is needed to be done from your side there.

For the headers you can use the Mesa headers, or any other generic OpenGL header, as said the ABI of the different libraries is compatible so you can use any headers with them.

You don't need to load the pointers to the functions either, though it could be useful so that your application works on both Windows and Linux the same. Generally you just need to make sure that the header you use defines the needed functions. (They can be linked directly under Linux.) If you want to link the newest version of OpenGL instead of getting the function pointers you'll find the newest headers on the OpenGL website: http://www.opengl.org/registry/

About the context creation I have no clue but I would recommend to use GLFW for it, it is really not necessary to communicate with the native platform directly. That way you can even use the same code for both Windows and Linux.
> 5 votes

# Answer
It's pretty straightforward on Linux. Just get a buildsystem setup so it can find OpenGL, SDL and GLEW. And use all 3 of those things, SDL for context creation and GLEW for creating the function pointers.

Also, unfortunately for now, I should recommend that you not use mesa. For example, eveerything I'm doing is gl 3.2, and Mesa only has..what? 3.0?
> 1 votes

---
Tags: opengl, linux
---


title: Proper opengl learning curve + tools

text:
# Question
Title: Proper opengl learning curve + tools
My first post here, so at first i would like to say HI to everyone!

Had a course of computer graphics at my uni and got interested with opengl. Unfortunatelly we used it with java + jogl + some funky frameworks from our lecturers which provided us with all texturing etc. Now i want to switch to c++, because as i noticed all the tutorials are written in it.

My question is about additional libraries. Google told me that "OpenGL SuperBible V Comprehensive Tutorial and Reference" by Richard S. Wright will be helpful for the learning process and in the book they use GLEW + GLtools. Are those proper tools or should i start with something else? Maybe some other books? \[yes i used search for online courses and books here, but maybe you have some tested and up to date positions\]

# Answer
> Are those proper tools or should i start with something else?

If you want to take a deeper look into what the frameworks from your lecturers do, the SuperBible does a very good job explaining all those basic things. There are also some good tutorials and references to useful libraries (like glm) if you want to start experimenting by yourself at opengl.org. So to answer your questions, yes the SuperBible is definitely one of the things you might want to read, although GLTools is probably something you will quickly get ahead off.

As for other references: use the search functions, there are a lot of these questions with good answers around already.
> 0 votes

# Answer
My favourite toolkit so far is GLFW. It's simple to use while fully featured and integrates well with OpenGL. GLEW is a must for anything complex, as it will allow you to easily use extensions.

I'm not sure if this is a proper question, but I'll answer it anyways :)
> 0 votes

---
Tags: c++, opengl
---


# Question
Title: How do I implement a Bullet Physics CollisionObject that represents my cube like terrain?
I've successfully integrated the Bullet Physics library into my entity/component system. Entities can collide with each other. Now I need to enable them to collide with the terrain, which is finite and cube-like (think InfiniMiner or it's clone Minecraft). I only started using the Bullet Physics library yesterday, so perhaps I'm missing something obvious.

So far I've extended the `RigidBody` class to override the `checkCollisionWith(CollisionObject co)` function. At the moment it's just a simple check of the origin, not using the other shape. I'll iterate on that later. For now it looks like this:

```
@Override
public boolean checkCollideWith(CollisionObject co) {
    Transform t = new Transform();
    co.getWorldTransform(t);
    if(COLONY.SolidAtPoint(t.origin.x, t.origin.y,t.origin.z)){
        return true;
    }
    return false;
}

```

This works great, as far as detecting when collisions happen. However, this doesn't handle the collision response. It seems that the default collision response is to move the colliding objects outside of each others shapes, possibly their AABBs.

At the moment the shape of the terrain is just a box the size of the world. This means the entities that collide with the terrain just shoot away to outside that world size box. So it's clear that I either need to modify the collision response or I need to create a shape that conforms directly to the shape of the terrain. So which option is best and how do I go about implementing it? Perhaps there's an option I'm not thinking of?

It should be noted that the terrain is dynamic and frequently modified by the player.

# Answer
> 3 votes
I was having some troubles with the strategy implemented in my other answer. Contact points would sometimes stick around, it was kind of hacky to do shapes other than cubes and it would sometimes allow objects to slip through the terrain.

So instead of modifying or overriding any of the Bullet classes, there is an alternative option of using a built in Bullet collision object that will represent the terrain. The `BvhTriangleMeshShape`(doc) is a built in shape that is represented by a triangle mesh.

This mesh can be generated at the same time as the mesh for visualizing the world. This means that the physics object can match the rendered object exactly.

I create a `RigidBody` for each chunk in my terrain. That body has its shape set to a `BvhTriangleMeshShape`. When the terrain is modified, at the same time I'm rebuilding the visual representation of the chunk, I'm also rebuilding the physics shape. Then, when it comes time to buffer the visual shape, I also swap out the physics shapes like so:

```
dynamicsWorld.removeRigidBody(chunk.getRigidBody());
chunk.getRigidBody().setCollisionShape(newShape);
dynamicsWorld.addRigidBody(chunk.getRigidBody());

```

This ensures that the body is properly removed, cleaning up the contact points. Then it's shape is changed and it's re-added.

In order to generate the `BvhTriangleMeshShape` each chunk must maintain a `TriangleIndexVertexArray`(doc). This is essentially two byte buffers. One with the positions of the triangle vertices and the other with the indices for constructing those triangles. This vertex array must be maintained as the `BvhTriangleMeshShape` does not make a copy of the data.

Using all the built in Bullet physics classes is likely faster than anything I could write, and it does indeed run very fast. I haven't see any slow downs after implementing this new strategy.

# Answer
> 8 votes
While I appreciate Kevin Reid's answer, it was at a level that was higher than what my question was asking. Understandably with out knowledge of Bullet Physics, it'd be hard to answer this question. I got this working and have an answer that is specific to Bullet Physics.

Along with extending the `RigidBody` class like I mentioned in my question. I also needed to extend the `CollisionAlgorithm` class. This is mostly to override the `processCollision()` function. Inside the `processCollision()` function (which takes the two colliding bodies as arguments), I was able to create a cube shape and appropriate `Transform` for the cube that my entity was currently colliding with. Then just let the default collision happen based on the entity and the specific cube/cubes it's colliding with. In order to use the newly extended `CollisionAlgorithm`, I needed to register the algorithm to deal with the shapes I want it to handle. In this case that's pretty much the terrain type against everything else. For that I used `registerCollisionCreateFunc()` with my `CollisionDispatcher`.

So for those following along in the future:

1. Extend `RigidBody` to have a basic collision check with your terrain.
2. Create a instance of your `RigidBody` class and add it to your `DynamicsWorld` or whatever `PhysicsProccesor` you're using.
3. Extend `CollisionAlgorithm`, specifically `processCollision()` to create Bullet Physics shapes and Transforms that match with your collision location.
4. Register your version of `CollisionAlgorithm` with your `CollisionDispatcher` using `registerCollisionCreateFunc()`. (This registration is done multiple times, once for each pair of shapes you want to collide.)

**EDIT**

Here's a video of it in action if anyone is interested.

**Detecting the initial collision**

For my initial collision checks, my extended `rigidBody` overrides the `checkCollideWith` function described in my question. I have a function for my terrain that can check if the world is solid at a specific point. Basically, I test my terrain against the object being passed in by the `checkCollideWith` function, seeing if my terrain is solid anywhere within the bounds of that object.

Now, there's also the next step in Bullet, finding the contact points. This takes place in the `processCollision()` function I mentioned above. Here, I've made a boxShape the size of a terrain cube, then when I detect a collision in the `checkCollideWith` function, I place that terrain cube sized boxShape at the collision location, and let Bullet use all it's default algorithms for detecting collision points there.

So basically, if a physics objects bounds touch solid material. I'll place my temporary physics body to that location and tell Bullet to check collisions against that temporary cube, as if it were always there. This is sort of like super optimizing placing a boxShape for every cube in my terrain. Instead of millions of boxShapes, I only need to have one that teleports around when a collision is detected.

# Answer
> 2 votes
I'm not familiar with Bullet Physics, but I've used ODE. There, after the yes-or-no collision test, there is a more detailed shape-shape collision test which generates a set of contact points.

In your case, your world is a collection of boxes, so you could do this:

1. Take the AABB of the moving entity.
2. Iterate over the terrain voxels in the volume that intersects it.
3. For each voxel of the terrain which is solid, construct a matching box and compute (preferably using the physics engine's provided routines) the collision of that box with the moving entity.
4. Return the collection of all of the resulting contact points.

This is *not* redefining the *collision response*; this is a layer before that. The collision response is determined fully by the contact points calculated from the collision.

As I said, I'm not familiar with Bullet Physics, so I don't know whether its architecture is amenable to this.

---
Tags: bullet-physics, voxels
---


# Question
Title: How to Animate a Mechanical Model to work with Unity's Mechanim?
I made a relatively simple model in 3D Studio Max to be used in a game. It's a simple stationary laser turret with an openable maintenance hatch. I want to use Mechanim to handle the animation states. The parts of the model are parented in a way that it's easy to just make it move from code but I rather have it use Mechanim and animation files to make it easier to add details like idle animations. I tried animating it with Unity's build in animation editor which looked nice enough but I couldn't get the animation created with that in Mechanim for some reason. If I have to use an external editor to add animations, I can't seem to find any. Google only gives results on how to animate character models or how to make an animation just to be exported to video. How would I animate this model to work with mechanim, what programs should I use and what should I pay attention to?

# Answer
You would usually animate your 3d model from 3d Studio Max itself. You'd have to create bones for your turret. Rig it, then skin it. Then add animations to that. Then in Unity, in the import settings for your turret, under the "Rig" tab set Animation Type to use Generic.

I don't think there's any other way to integrate your model to Mecanim, as of yet.
> 2 votes

---
Tags: unity, animation
---


title: What alternatives to GLUT exist?

text:
# Question
Title: What alternatives to GLUT exist?
I am trying to learn OpenGL, and I just found out that GLUT is obsolete. I already know SDL, and it seems it is a good alternative. Should I use SDL to develop games with OpenGL, or are there any better alternatives. I am new to game development, so I don't know much about the state of the art.

# Answer
> I just found out that GLUT is obsolete.

That's what happens when you accept the first answer you come across; you get bad information. GLUT 3.7 shouldn't be used, but FreeGLUT is completely backwards compatible with it.

However, your question goes elsewhere. For making an actual game, GLUT of * form is inappropriate. It doesn't give you control of the main loop, and you really need that in a game (FreeGLUT does have a way to control the main loop, but it's still odd). GLUT is for writing graphics demos. That's very important when testing new graphical effects, so it should be there in your toolbox when needed. But your main game code should never use it.

GLFW is a game-centric lightweight alternative to GLUT. It provides basic support for things beyond creating an OpenGL window. It lets you get input, load images as textures, and a couple of other things.

SDL, SFML, and Allegro 5 are all multimedia toolkits. They can create OpenGL windows, but they do a *lot* more than that. They provide full support for input, audio, and various other stuff you need to make a game. If you're making a game, any of these are a good starting point. I personally like Allegro 5, but that's just my bias towards good documentation and a clean API.
> 28 votes

# Answer
You can find alternative to GLUT on this page:

http://www.opengl.org/resources/libraries/windowtoolkits/

To that i would also add SFML:

http://www.sfml-dev.org/index.php
> 4 votes

# Answer
### If your goal is to develop a game,

It depends on whether you want your game to be cross-platform or not. For portable (Windows, Mac, Linux) games SDL seems to be the only choice.

If you only target Windows and/or XBox, there are much better alternatives, e. g. XNA which frees you from writing *a lot* of code manually.

### If your goal is to learn OpenGL,

Just program in raw OpenGL, but be prepared to face a lot of unintuitive concepts, math and huge manuals.
> 2 votes

# Answer
GLUT is an API as well as a library. The original library is indeed obsolete. The API is a different thing, it was pretty good to begin, it just needs revisions for overcoming limitations and addressing new needs. The primary current implementation is FreeGLUT, which is supported and not obsolete. That means that a good alternative to GLUT (as in the library GLUT) is GLUT (as in FreeGLUT).

The problem noted above with "control of the main loop" is incorrect. With newer GLUT versions you can have better control over your game loop (if that is important to you). The limitation was fixed by glutMainLoopEvent(). This and other limitations are addressed here:

http://en.wikipedia.org/wiki/OpenGL\_Utility\_Toolkit
> 2 votes

# Answer
Qt does support OpenGL. Take a look to Open Inventor and consider if make it sense for you to go straight to an higher level 3D API.
> 0 votes

---
Tags: opengl
---


# Question
Title: Why game engines usually don't offer a vector3.rotate method?
Game engines like Three.js, Ogre3d and Unity3d often don't provide a default rotate method on their vector class. You usually have to do something like:

```
rotated = vector.applyQuaternion(
    new Quaternion().setFromEuler(
        new THREE.Vector3(0,0,Math.PI)));

```

This is a little confusing for me, so I just define a rotate method. Is there a special reason for this?

# Answer
It seems that most engines do have those rotation methods.

XNA has one in it's `Vector3` struct.

```
// Returns a new Vector3 that results from the rotation.
public static Vector3 Transform (
     Vector3 value,
     Quaternion rotation
)

```

three.js has the function exactly as you wrote it.

In Unity's case, their `Vector3.Rotate()` method might be internally implemented as a quaternion rotation. It accepts an arbitrary axis and angle, which is all that is required.

```
//a quaternion is...
[sin(angle / 2) * [axis], cos(angle/ 2)]

//which expands to a 4-vector like...
[sin( angle / 2 ) * axis_x,
 sin( angle / 2 ) * axis_y,
 sin( angle / 2 ) * axis_z,
 cos( angle / 2 )
]

```

Regardless, there's no reason the function can't be implemented manually, as you said. You can wrap it in a helper if you want to. Game Engine Architecture by Jason Gregory has a thorough enough explanation of its implementation, but it does not attempt to prove the 4-dimensional math. It *does* prove that they are equivalent to Matrix rotations, while requiring fewer total multiplications.
> 7 votes

---
Tags: unity, vector, ogre, quaternion, three.js
---


title: Interstellar Economic Simulation

text:
# Question
Title: Interstellar Economic Simulation
I'm designing a game reminiscent of Elite or Escape Velocity, those old space trading games, where you play a traveling merchant in space.

I'd like to have the game's economy at least resemble a real one. What resources are available that I could look at to get an understanding of the algorithms I'll need to perform the simulation?

One big hurdle is that I'm pretty horrible at math; so a simplistic explanation would be ideal.

I figure an interstellar economy wouldn't be all that different from a global one; certain things can only be manufactured in certain places (due to resources and technology levels), shipping things takes time and money, people in different places need different things... just instead of cities, they'd be planets.

A Google search of "economics simulation algorithm" and similar terms turns up little of use, and nothing I've got the background to understand.

Anyone know of any useful resources I could look into?

# Answer
> 6 votes
Modelling something that is near impossible to do "right" but you can give a reasonable model of the economy (eve online is the most successful close match I can see that matches what you're trying to do)

For example:

Product A in Region A might be of low value because there is lots of it and getting it to this region is cheap. Product A in Region B might carry a higher value because it's not so abundant in that region and thus has the cost of being transported to that region.

Now depending on how your game works, if a player can buy a product from a far away region from anywhere in the galaxy then price displayed should be offset by your transportation cost.

Key things to note:

* This is a very simplified starting point.
* Transport costs may vary (think about risk, cost of other commodities like fuel, ships or ship parts).
* Tax ... are you planning on having that in your model?
* Abundance, any resource a user can just go and make / mine for easily should be worth virtually nothing as it would be simple to flood the market with such a commodity but with that said if no user is doing so and the demand rises then the price should rise.

What I find works best when im playing a game is models that shift by themselves. Each and every transaction that takes place in your market will have a knock on effect not just on the thing that was being traded but to the market as a whole. Links to products on a market can effectively be traced to virtually every other product on that market ...

Look at the real world, a barrel of oil makes more than 1 product, from fuel, to plastics.

any industry that depends on any of those products would be affected by the price of oil. but the oil drilling industry needs things like drill bits so will be affected by the price of say diamonds, metals, ect.

But metals need to be proccessed before they can be used and then manufactured in to drills so the metal workers need oil.

And that's a very basic example, when you consider something as complex as your mobile phone it goes completely bonkers.

How I would go about this:

Start with a table that contains all your products and give them an arbitrary value (don't worry if your model is any good this should sort itself out later).

Now set a load of rules and implement a method / function to implement them.

* rule 1: a product on the market increases by X amount for each system you have to go through to get to the nearest location it can be found
* rule 2: the higher risk to move a product between 2 systems offset
* rule 3: value by X rule 3: offset value by available / demand

Now you can write some sort of GetPriceOf(Product product, Location system) type function that determines based on the output of a chain of rules what the price of the given product might be in the given system.

Then just keep building and building on it until the model feels real. It'll likely never be perfect, very few companies actually get it right and even when they get it right it's still not real like in the real world.

The other thing you could try is making money as hard to come by as in the real world then based prices on the real world stock market ... could be a bitch to wire up to your game though.

# Answer
> 3 votes
You can create a "flow of merchants" system which edits the routes' popularity based on the length of the journey and the income and adjusts the prices according to the amount of goods transported there. In other words, simulate other merchants(not individually, but via "popular routes") that influence the economics as much as you do.

# Answer
> 2 votes
Although this may seem like a bit of a cop-out, it is worthwhile to note that **no one can make a provably accurate model of space-faring economics** because we have **no examples of it in real-life**.

All examples of space-oriented trading simulations make their own science fiction assumptions about how their universe works, and most of them take the Planet of Hats approach to alien worlds, in that, despite planets being huge and diverse things, the worlds are culturally very small and limited and possess only one real identity. With this kind of view on planets, it is consistent for them to have only a single, simplified economy for each of them - however, this is certainly a *massive* simplification of what might occur in real-life.

In other words, if you want realism as your primary goal, then you should know that it is unlikely that there has ever been (at least that I'm aware of) an economic model that is even close to being both realistic and on the galactic scale. Although it may be useful to use real-world economic models as a starting point, there is no guarantee that it will be even close to accurate. There is a measure of fiction, imagination, and utter guesswork that is simply required to make this work.

# Answer
> 1 votes
I have played a mobile game called Galaxy on Fire, where you would be a space pilot. You were supposed to travel between solar systems each containing 6~ space stations orbiting planets. Each station had its own shop, with its specialities, beverages and whatever you might think of.

Here is the Galaxy on fire 2 Galaxy Map. Taken from the GOF Wikia

The market would be reset every few space travels. With various commodities added randomly. In the top left corner of the map. There has been the most remote station Talidor. Lets say, it has been the only place where you can buy the "Talidor Tonic", it's price would be approx 2k in that station. The approximation would be completely random (I think FishLabs made it +-7% of the initial item value) to give the player a feeling of reality. The Tonic's price is highest in the other corner of the galaxy on Ni'mrodd 9 solar systems away. Where the price would be much higher, Lets say, for instance 190% of the initial cost making you earn 1800 credits from each Tonic you sell. If I were to set up that system I would make one, or more "production" sites, and the further you travel the more +X percents you will get to the items value.

Talidor: 2000; Ginouya: 2200; Eanya: 2400; (...) Nimrodd/Meenkk: 3800

If you feel strong, you can also make more "production sites" which would change the items value using the simple arithmetic mean, using the same method as before "The more times you have to travel, the more the price will rise".

All the values, along with the % the item will rise every time you move up the map can be reset every few travels.

---
Tags: mathematics, algorithm, simulations, economy
---


# Question
Title: How should I structure my turn based engine to allow flexibility for players/AI and observation?
I've just started making a Turn Based Strategy engine in GameMaker's GML language... And I was cruising along nicely until it came time to handle the turn cycle, and determining who is controlling what player, and also how to handle the camera and what is displayed on screen.

Here's an outline of the main switch happening in my main game loop at the moment:

```
switch (GameState)
{
case BEGIN_TURN:
    // Start of turn operations/routines
break;
case MID_TURN:
    switch (PControlledBy[Turn])
    {
    case HUMAN:
        switch (MidTurnState)
        {
        case MT_SELECT:
            // No units selected, 'idle' UI state
        break;
        case MT_MOVE:
            // Unit selected and attempting to move
        break;
        case MT_ATTACK:
        break;
        }
    break;
    case COMPUTER:
        // AI ROUTINES GO HERE
    break;
    case OBSERVER:
        // OBSERVER ROUTINES GO HERE
    break;
    }
break;

case END_TURN:
    // End of turn routines/operations, and move Turn to next player
break;
}

```

Now, I can see a couple of problems with this set-up already... But I don't have any idea how to go about making it 'right'. Turn is a global variable that stores which player's turn it is, and the BEGIN\_TURN and END\_TURN states make perfect sense to me... But the MID\_TURN state is baffling me because of the things I want to happen here:

* If there are players controlled by humans, I want the AI to do it's thing on its turn here, but I want to be able to have the camera follow the AI as it makes moves in the human player's vision.
* If there are no human controlled player's, I'd like to be able to watch two or more AI's battle it out on the map with god-like 'observer' vision.

So basically I'm wondering if there are any resources for how to structure a Turn Based Strategy engine? I've found lots of writing about pathfinding and AI, and those are all great... But when it comes to handling the turn structure and the game states I am having trouble finding any resources at all. How should the states be divided to allow flexibility between the players and the controllers (HUMAN, COMPUTER, OBSERVER)?

Also, maybe if I'm on the right track I just need some reassurance before I lay down another few hundred lines of code...

# Answer
> 2 votes
You will have to decouple the "camera" from a player. Maybe GML has limitations here but I have no experience with that to speak of. There is no reason why the position and setup of the camera has to be locked to a single player. Normally a game consists of a world and sometimes several cameras to be rendered each frame for multiple players on the same screen, or "security camera" views," or render to texture views etc. The process of rendering a frame from a single camera view to a single screen space area need not be tied to a player at all.

# Answer
> 1 votes
While there are human players, you can make the camera center on the moving AI unit if it's in range of vision. Else, you can have camera controllable with mouse/keyboard independent of the moving units.

---
Tags: architecture, state, game-maker, turn-based-strategy
---


title: Google Play 3rd Party Payment Allowed?

text:
# Question
Title: Google Play 3rd Party Payment Allowed?
Does Google allow 3rd party payment solutions to be enabled in developers' apps (i.e., Paypal, carrier/SMS payment), especially in countries where Google Checkout isn't present? Or does this violate any policy of theirs?

Please reference the policy in your answer if you can, and thanks in advance to all who answer.

# Answer
From their help pages:

> You can make purchases through Google Wallet using a credit, debit, or gift card with the following logos:
>
> American Express(USD Only)
> Discover (USD Only)
> MasterCard
> Visa
> Visa Electron (Outside of US Only)

However, some customers may be able to set up payment through their mobile carrier and people can put money into their Google Wallet with gift cards purchased in store (or online).

---

My answer above is how users can get money into their Google Play account from 3rd party sources. I guess I misunderstood the question.

If you're selling a game on Google Play, you have to use Google Play for in-app purchases, as stated in the Google Play content policy:

> * **In-app purchases:** Developers offering additional content, services or functionality within an application downloaded from Google Play must use Google Play's payment system as the method of payment, except:
>     + where payment is primarily for physical goods or services (e.g. buying movie tickets; e.g. buying a publication where the price also includes a hard copy subscription);
>     + or where payment is for digital content or goods that may be consumed outside of the application itself (e.g. buying songs that can be played on other music players)
> 2 votes

---
Tags: android, legal, mobile, payment, google-play
---


# Question
Title: Proper way to maintain Vertex Buffer Objects
I've started learning WebGL, currently I'm building a 2D lighting system, but there is some confusion going on inside my head.

How the lighting works is based on this tutorial http://archive.gamedev.net/archive/reference/programming/features/2dsoftshadow/default.html (probably the most linked article of the genre).

My question is about the proper way to store/create/update the Vertex Buffer Objects of the polygons.

Currently I have something like:

```
//-- during initialization of each polygon
//build vertices from the provided points
//[...]
//create the VBO
this._VBO = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, this._VBO );
gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.DYNAMIC_DRAW );

//-- during rendering of each polygon
gl.bindBuffer( gl.ARRAY_BUFFER, this._VBO );
gl.enableVertexAttribArray( program.aVertexPosLoc );
gl.vertexAttribPointer( program.aVertexPosLoc, 3, gl.FLOAT, false, 0, 0 );

```

The vertices array is created only one time at the top of the file, and reused for each new polygon, the motive to do that is to avoid the creation of various Float32Arrays per object.

```
//top of file
var vertices = new Float32Array( 20 * 3 ); //maximum of 20 points

```

---

It's okay to have one VBO for each object? I was thinking about the possibility of a single VBO, but I don't understand how I can make it work with only one. The number of vertices can vary between one polygon and another, so how I'm going to store that?

Currently I'm not taking into consideration textures, however, answers that already take they into account are welcome.

# Answer
One VBO per polygon, and updating it at runtime as you seem to be doing, is going to perform horribly. You'd be better off with old-school client-side arrays or even (if you weren't using ES) immediate mode. VBOs just aren't designed for good performance with that kind of usage pattern.

If the data is absolutely static then stuff it all into a single big VBO, using the parameters of your glDrawArrays call to specify the range of the VBO to draw for each polygon. In this scenario the VBO is never updated, and yes, uses more memory - but memory isn't everything. This is a fair tradeoff of memory for performance.

If the data needs to be dynamic then look at a streaming buffer pattern. Unfortunately ES2 doesn't have glMapBufferRange so you can't do this reasonably; either stuff it all into a system memory copy, then glBufferSubData it (your render would be in two passes then - one to build the data, the other to draw it - making sure that you're using a single big glBufferSubData call to update the buffer rather than lots of small ones) or go back to client-side arrays and let the driver do the streaming for you.
> 2 votes

---
Tags: opengl, 2d, opengl-es2, webgl, vbo
---


# Question
Title: How Does Ultima 7 manage different floors in 2d
In U7, you can move among floors without the function "tranport" the player to another place, as for example the first ff ones.

How can it tell whenever the character is moving from floor z to floor z+1? (of course, it uses stairs, but what is the logic behind this?) How does pathfinding in those cases work?

# Answer
> 1 votes
The player location is stored using an array. Three variables are used as coordinates X,Y,Z.

The X,Y are the map coordinates, while the Z is the height.

In order for the game look 2.5d when its 2d the entire the lower floor (Z-1) map is moved and has the X and Y coordinates transformed (Y-1) && (X+1). Which creates a nice illusion of 3d background. It also makes changes to the general way the 2.5d coordinate system, I do not remember how did they.

> The entire process of the illusion used in 2.5d games is explained in this post, it works really similar to the U7: Perspective projection with 90 degrees between X-Y axis?.

When a player uses stairs he is simply transported, his coordinates are changed and he is transported/teleported to the ground tile the stairs lead to the right. Generally it would work the following way \[x+1\]\[y+0\]\[z+1\]

It actually isn't pathfinding. It just moves you around the tiles just like teleporting would do. There is no need for a method to avoid obstactles unless you are making a movement method to the stairs~ itself:)

# Answer
> 3 votes
As far as I remember it, U7 had a very discrete sense of height. Each *stair* was +1 to height. If you stack potions, you could climb anything. From a height of 1, you could move to a square that was +/-1 from it, but not something that was +/-2.

It lends itself pretty naturally to pathfinding then, you just consider any node more than +/-1 unit of height away as **blocked**.

---
Tags: 2d, collision-detection, path-finding, rpg
---


# Question
Title: How to go about front end UI to main Game Engine and then to Game Over Phase
I am about to complete my first ever game. I have used Qt for windowing and OpenGL for actual game logic. I am confused about .. things which are related to design so according to FAQ, these kinda questions are valid. So from the past experience, people who are more interested in deciding what others should ask here and what should not, are taken care of.

(1) With Qt, How to go about connecting pieces? The very first thing comes to my mind is ==\> create a screen having few images(carttons) on it, start some music loop, give few buttons; and upon button click event, create OpenGL context and handle the control to it.

But I doubt if this is the way it is done. I tried reading few forum posts but some were either not relevant and others were too complex

(2) And about exiting the game. Is it wise to have OpenGL context kept as it is; and upon reply, use that context to restart a game? Or will it be harmful in any way?

I understand that these questions would not have definite answers, but others suggestions, who have experienced and did these things, can definitely help me in going ahead.

# Answer
> 1 votes
You need to **get some more QT experience** and everything will all make sense. What you're trying to do is all very basic QT programming.

There's nothing different from a "regular" QT app pulling up a new window (or show()+raise()) and an OpenGL window is just another QMainWindow with a widget, or whatever you're using.

You don't "hand the control" to the new window, if it's the active window it has control when you raise() it. Your windows are running inside the QT framework, which is entirely event driven, you do not have a "main loop" of your own. Until you get some more QT experience, or you are experienced with other event-driven frameworks you're going to have a hard time designing your code.

The basic structure and flow of a full QT app is that you create a main window for the app itself, this runs the exec() which gets inputs via events from the GUI. Based on those events you then new MyNextWindow and show()+raise() to activate it. That window does its thing with inputs and events, and thus the circle of life is complete.

Since an OpenGL context is tied to a widget in a window you're not controlling that separately, whatever window has that widget controls the lifetime of the context. It's not harmful if you just hide() and show() that window, as far as I know. That's the extent of what QT does with OpenGL for you, everything else you are responsible for in the Paint method.

---
Tags: opengl, game-design, qt, ui-design
---


title: Puzzled about game mods

text:
# Question
Title: Puzzled about game mods
I'm new to game development. I was thinking of different ways to create a game. I discovered Unity3d as much preferred indie game engine and yet so powerful. Then I read about game mods, which I found pretty exciting too. So, I now have two questions.

1. Are Mod creation Software/SDKs developed by the same company which made the original game? Are there any custom made (recent) mod sdk? Is it even possible to make one like that?
2. Is it possible to port a model from one mod sdk (say, Halflife) to another mod sdk (say, Skyrim)?

# Answer
> 3 votes
Is Skyrim Nexus (mod SDK) custom made? - Yes. It was made specifically for TESV Skyrim And you are not allowed to take any models from there unless you are going to use it with the game itself, or give it into the official modding society. Otherwise it would be considered stealing intelectual property/breaking the EULA you accepted upon installation of the software.

Mods are MODIFICATIONS made to some kind of game. So 99% of times if there is a mod SDK it is created by the company, or by the game fans and they rely completely on the game content + are not allowed to distribute/resell anycontent they get their hands on.

Is it possible to use the models in your published game? - NO

Can a modding SDK be made? Yes, as long as you have a +-finished game, otherwise it wouldn't be a modding sdk. But just an SDK.

Porting 3d "models" between sdks: the models are compressed in the Data folder (almost all the time). And they are saved in some format for eg. .FBX or .OBJ once you can export those outside the model container you can convert them into a model that the MOD kit supports.

---
Tags: unity, modding
---


title: Lightgun game (Mouse not in the middle)

text:
# Question
Title: Lightgun game (Mouse not in the middle)
I'd like to do a small lightgun game. So the mouse should not always be in the middle like in most ego shooters. The player should be moved trough a world and then shoot some enemies at a more or less fixed screen (typical lightgun game style like in Crisis Zone and others).

It would be good if I can just mod a game like Counter Strike, so I can use the models, animations, leveleditor and so on. I did some maps for CS a few years ago and coded a little bit with delphi and the genesis engine a long time ago, so I don't really have that much experience.

Is it possible to mod a existing game the way I described?

Which platform could be used (if possible predifined models and animations and so on)?

# Answer
If you want to make a high quality shooter. Use the Unreal engine.

> http://www.unrealengine.com/unreal\_engine\_4/

All the assets from the Unreal Tournaments are avaiable to you, for learning purposes. All you have to do is download the Unreal Develoment Kit, and install the Unreal Tournament Starter assets. Making any type of shooter won't be hard if you follow official tutorials. Gl on your light shooter :)
> 1 votes

---
Tags: modding
---


title: Flowfield density conversion

text:
# Question
Title: Flowfield density conversion
I'm trying to implement flowfield navigation, as described in http://grail.cs.washington.edu/projects/crowd-flows/ but I can't understand how the Density Function in Figure 4 of the paper is supposed to handle unit radius.

Has anyone ever implemented that and can provide more information?

This is the part in question:

Their algorithm seems to be using only 4 cells, pointing to the lower left of the unit, so is this some kind of kernel that needs to be applied multiple times?

Thanks.

# Answer
> 3 votes
No, it's not a "kernel that needs to be applied multiple times". You just apply the formulas as written, once.

It's kind of a weird rule, though, and not very clearly described. Let me try to clarify it a bit:

* First, find the four cells whose shared corner is closest to the unit. The unit will contribute a non-zero amount of density only to those cells. Call those cells A, B, C and D as in figure 4(b).
* Let Δx and Δy be the horizontal and vertical distance of the unit from the center of cell A, measured in units of one cell width/height.
* Let ρA = min(1−Δx, 1−Δy)λ, ρB = min(Δx, 1−Δy)λ, ρC = min(Δx, Δy)λ and ρD = min(1−Δx, Δy)λ, as described in the paper.
* Let the unit contribute ρA density to cell A, ρB density to cell B, ρC density to cell C and ρD density to cell D.

As I said, the rule is kind of weird, and I have no obvious geometric interpretation to offer for it. It does, however, satisfy the expected properties that:

* When the unit is exactly in the middle of any cell X, then (regardless of which of A, B, C or D we choose X to be) it contributes 1λ = 1 unit of density to cell X and 0 units of density to any other cell.
* When the unit is exactly at the corner of four cells, it contributes (1/2)λ units of density to each of the four cells (and nothing to any other cell, by definition).

However, note that, using this rule, the total amount of density contributed by a unit to all cells is *not* constant, not even if λ = 1. In particular, when the unit is exactly at the midpoint of the edge between two cells, it contributes (1/2)λ units of density to those *two* cells, and nothing to any other cell. Thus, calling the resulting value a "density" seems a bit misleading.

---

Edit: Another way of writing the formulas for ρA, ρB, ρC and ρD, which may make the symmetry of the definitions more apparent, is to define dX = max( |x − xX|, |y − yX| ) as the chessboard distance of the unit at (x, y) from the center of the cell X at (xX, yX), measured in cell widths/heights. Then, for any cell X,

* ρX = 0 if dX ≥ 1, and
* ρX = (1 − dX)λ otherwise.

---
Tags: algorithm, grid
---


# Question
Title: Approaching syncing between client and server, in a Tower Defense game
I am currently working on a Multiplayer TD, players can join games, and place towers on a map, so far so good.

This is how the game works as of today, when a new game is created, the server initialise a master game, basicly all logic happens here, it tell clients what to visualize. But this being my first MP game, i need some advice about how to keep players in sync with the server game, my questions could be. "What to do, if a player looses contact to the server for several seconds, therefore getting out of sync" "What to do, if a player plays with a poor internet connection, and having a latency jumping from 400ms to 3000ms"

I thought of sending data to each client 4 times every seconds, containing information for all entities on the board. This data i would then compare to the client data, and overrule entities that is out of sync, there would then be a tolerate value, so the users would't experience changes on the board, because of small game delays.

However i can imagine this would be a lot of work, and i wanted to ask if there was a smarter solution, i've looked at some post around the net, but could't find any which would apply for my game, feel free to throw links my way.

# Answer
> 1 votes
My suggestions are:

You are using the web, so you have to use TCP (websockets, I assume?). Therefore you do not need to worry about retransmission, TCP does this for you (this will probably create a bit of lag, then catch up though).

Run the game in ticks with a fixed and fairly low timestep (e.g. 200ms). The client can interpolate if you need smoother animation.

Each tick the server sends an "update everything" to all connected clients. A client sends any commands that the user may have made on the user interface, but DOES NOT ACT ON THEM LOCALLY!

If the client gets disconnected from the server, it can reconnect and tell the server the number of the last frame it's processed, to "continue from X". The server needs to keep some history of frames sent so that a client can "catch up".

If a client gets too far behind, it needs to resynchronise - reload the game world (this also happens initially). The server needs to keep timestamped old copies of the game world around for this purpose, or generate one on-the-fly. Each serialised copy of the game world needs to have a timestamp so that the client can "catch up" after download from the correct point in time.

This is broadly similar to the "1000 archers" technique (from Age of Empires and others)

---
Tags: html5, multiplayer, node.js, synchronization
---


# Question
Title: Whats an elegant implementation for 2D collision detection in a block based game?
to make things clear, i do not want to know HOW to implement collision detection mathematically. What i am looking for is an elegant way to check for collisions without having to manage seperate lists of objects, maybe for example implementing a ICollidable interface.

currently i have a simple gameloop

```
while(runGame){ handleInput(); update(); render(); }

```

So there are two possibilities which come straight to my mind. First, ill add an extra call to a method or class handling collisions.

`while(runGame){ handleInput(); update(); checkCollisions(); render(); }`

Second, every gameobject gets a list of nearby other objects in its update method. so it can do the collision on its own

```
while(runGame){ handleInput(); update(otherNearShapes); render(); }

```

i dont like both of these for two reasons.

in the first, i have to manage a seperate list of objects which implement an ICollidable interface.

in the second, the update method handles more logic than it should in my opinion.

so, is there an elegant way of integrating collision detection in my game (loop)? searching the net always only results in how to calculate stuff, but thats not what i want to know.

# Answer
> 2 votes
I can only comment in a answer because of rep but I wanted to say your question is a little vague.

I mean say your have 2 lists, one for all the static blocks that are not going anywhere and another for entitys in your game. You could give your collision class a hold on both lists and then check all of them based on where they are ect, but then your be checking everything in them lists all the time.

If before your level started, your collision class made its own list of static blocks and checked what blocks can be reached by entitys and put them in a list of its own then you don't have to check every block in a area agaist what ever entitys are near by and your render() and update() method can still run thorugh a complete list of all the stuff in you game.

Sometimes more is better and as for the update() method having to much logic, maby you can split up what is going on in there. Like moving all your user input code to another class so its no so crowded in there, more calls to other objects that handle this and that instead of many methods in one space.

Sorry for spelling and grammer, its very late and im very tired

# Answer
> 2 votes
Your "update();" call is itself a request to increment the state of the simulation. This generally involves physics.

Physics usually has some form of "broad phase," which roughly is in charge of figuring out those "other near shapes" and performing collision and physics resolution calculations appropriately. You shouldn't need to pass such a list in, since physics figures that out on its own, generally by using some form of spatial partitioning. In Minecraft-esque games, the "chunk" is a perfectly reasonable large-scale partition. Objects can at most interact with other object only in the same or (if on the very edge) adjacent chunks. You could break a chunk down into even small sub-chunks to make things smaller still.

The game state update steps asks the collision system to generate a list of contacting/colliding pairs of objects, then asks physics to resolve those collisions, then tells objects that need game logic updates to tick (generally just AI and the chunk object in this style of game, since individual blocks have no update logic to run, nor do items). Simpler games, including a Minecraft-ish game, could combine collision and physics, since "physics" in this case just means ensuring that objects don't move through blocks. A tile-based game usually breaks these down into two steps, one for object-tile collisions and one for object-object collisions (these are generally two totally different algorithms, and you often want the object-tile collisions to be checked for and resolved after object-object collision, so objects can't push other object into unpassable tiles).

There's no need for each object to have an individual update() method, nor do you want one. There's a step where you tick the AI for all relevant objects (because your AI system keeps a list of all AI objects and can iterate over just those in one pass), generally after all collision is done and other world-changing updates happen. For blocks, even in games like Minecraft where they can "grow" or otherwise change over time, you do this by ticking the whole chunk as a whole. The chunk iterates over all its blocks in one small, tight loop, using simple random chance to make things happen over time (do NOT store a timer for each block; this is massively wasteful). Items likewise can be despawned by keeping them in a queue; there's no reason to update() each object individually, rather just process the global (or per-chunk) item despawn pool in one pass.

Note that you never have need for interfaces like ICollidable, though you likely have some form of concrete component class for collidable objects. The collision system keeps track of all collidable objects itself and using that spatial partitioning can find all such objects which might be colliding with another. Really though you never need to ask "find all objects that might collide with the player." Instead, collision just does all collision for each object, which naturally includes the player and NPCs. Game logic can then respond to the collision messages, either as they're generated or in another pass (buffering up the collision messages).

Roughly speaking (since being exact here is impossible, as it depends on the specific game), update loops typically look something like:

```
while (running):
  pump system message queue
  send rendering commands for "last" frame to GPU with interpolation parameters
  integrate physics for "next" frame
  check collisions
  resolve physics
  update world state
  update player actions from input
  update AI
  GPU flush + swap buffers

```

Again, different games have different steps and ordering. Hobbyist/student games tend to do all rendering at the end of the loop since that's how the old pre-modern-GPU "textbook" game loop is taught. You'll notice that there is no discrete "update" step, though one could collapse almost all of the middle steps into such a step.

I find it useful to have a "tick\_simulation()" function as part of a fixed timestep loop. It also lets me turn off automatic simulation updates and then increment the whole state by one step on a keypress, which is a very, very handy debugging feature to have in game, especially for physics.

# Answer
> 0 votes
Well, here's the most elegant alternative I can offer, and it's in fact what I'm using in my games:

Supposing you have a mother-class Entity from which all your classes derive, you could have a static list of Entities called Collidable (preferrably a hash map, so that through a key you can delete the Entity from it when, say, the object dies in your game). In every class that you want to be able to interact through collision, be it a Player, Car or MonsterTree class, in its constructor you can add the instance to this list. As in, `Collidables.Add(this)`.

And in the Entity-based class, you override its Update() method in the following way:

```
override void Update() {
    // Do stuff

    foreach (Entity collidable in Collidables) {
        if collidable.CollidesWith(this) {
            // Handle the collision
        }
    }
}

```

It still uses lists, and I'd recommend using an interface for the collision-checking method. Nevertheless, I find it to be a much more flexible way of handling collisions than straight away checking it in your Main Game Loop - by leaving it to the objects themselves to deal with it -, as it easens tinkering with the Main Loop's architeture and prevents the unnecessary checking by Collidables that don't actively trigger collisions.

---

edit:

To adjust this design to what you want, you could use the following technique, then:

Let `BasicPack` be a basic, abstract data structure akin to `void*` of C and C++, if you're familiar with it, for it will have almost the same use of void\* in these languages.

From `BasicPack`, you can create various kinds of different Packs, each of which will store specific data. Now, instead of `Update()`, your update method will be `Update (BasicPack args)`. I'm going into details a little later.

Supposing you have a `CollidablePack` derived from `BasicPack`, which has a List of Collidable Entities, you can easily call the Update of each of your Entities in the group you separated as:

```
    CollidablePack collisionArg = new CollidablePack(YourListToPass);

    // ...
    selectedEntity.Update(collisionArg);

```

And now, I your update method would look like this:

```
    void Update (MyPack args) {
        // ...

        // Unwrap,
        CollisionPack collidablesPack = args as CollisionPack;
        List<Entity> myCollidables = collidablesPack.Content;

        // and use as you like!
        foreach (Entity collidable in myCollidables) {
            // ...
        }
    }

```

Now your instances are pretty much independent from global lists, and we just made things even more flexible.

---
Tags: collision-detection, game-loop, software-engineering
---


# Question
Title: How can I make it so that my player object doesn't penetrate world collision when I'm holding down movement keys in that direction?
Right now I have a player object and an obstacle, both with bounding box rectangles around them. The issue is that when my player runs into this obstacle, as long as I'm holding down the movement key, my player goes slightly inside the obstacle, then when I let go of the key my player is placed outside of it.

The movement code in the update function of my player class is as follows:

```
if (Input.isKeyDown(Keys.Left))
{
    velocityX += 5;
}
_position.X += velocityX;

```

The collision code in my SpriteManager game component is:

```
if(player.collisionRect.Intersects(platform.CollisionRect))
{
    if(player.position.X >= (platform.position.x - player.width))
    {
        player.velocityX = 0;
        player.position.X = platform.position.X - player.width;
    }
}

```

I have searched online for the past two days and have been unable to find any solution to this problem and I have been unable to figure out what I have been doing wrong. Even though this seems like a fairly simple problem. Any help would be greatly appreciated!

Edit: I can tell that my issue is that when I collide, my player is still moving into my object by the amount of `velocityX`. So what I need to do is check if there is about the be a collision with the box, however I am still unsure of how to do this.

# Answer
> 3 votes
I have drawed this to explain the behaviour when a collision with AABB boxes is present.

When you have choosen what dimension has to be fixed, you can change the position of the object that was moved accordingly.

Here is some code to accomplish the task, (it's not tested and will require tuning for sure)

```
var P = player.CollisionRect;
var Q = platform.CollisionRect;

int W, H;

W = H = int.Max;

if (P.Right < Q.Left) return;  // No Collision
if (P.Left > Q.Right) return;
if (P.Top > Q.Bottom) return;
if (P.Bottom < Q.Top) return;

W = (P.Left<Q.Left)
       ? P.Right - Q.Left
       : P.Left  - Q.Right;
H = (P.Top<Q.Top)
       ? P.Bottom - Q.Top
       : P.Top  - Q.Bottom;

if (Math.Abs(W)<=(Math.Abs(H))
{
   P.Location.X -= W;
} else {
   P.Location.Y -= H;
}

```

---
Tags: xna, collision-detection
---


# Question
Title: Develop a 2d isometric mobile game on Flash
I'm building a game on Flash that will run on web/Android/iOS. The game is 2d isometric.I heard that developing mobile apps on Flash sucks and the graphics looks just awful.It'd be quite uncomfortable to write code for every platfrom separately.What would you guys recommend-stay with Flash or some other platform? By the way,do i need to build the game specially on MAC so that i can later port it on iOS? Thanks

# Answer
> 1 votes
> graphics looks just awful

It depends on developer only.

> What would you guys recommend-stay with Flash or some other platform?

Again, it depends on many things, including your knowledge of other languages and platforms. There're several examples of cross-platform games but not so much to say that Flash is the one of the best platforms for game development.

I think that the main problem of Flash is performance. If you want decent FPS on mobile devices you have to use Stage3D. Fortunately there're several frameworks (Flare3D, Starling) which help to develop faster.

So, before choosing Flash you have to be insure in performance. How to be? Test on real devices.

> By the way,do i need to build the game specially on MAC so that i can later port it on iOS?

You can develop and test using an iOS device on Windows.

---
Tags: android, ios, flash, actionscript-3, web
---


# Question
Title: Simple 3D particle gravity in javascript?
I'm trying to do some simple gravity handling in my 3D environment (I'm using three.js). I've got some code, but it doesn't work. I'm hoping it's just a silly bug somewhere. **Note: This is a cross-question from stack overflow since I've got no responses**

```
function handleGravity() {
    for(var j = 0; j < spheres.length; j++) {

        for(var i = 0; i < spheres.length; i++) {

            var r1 = new Array( spheres[j].position.x, spheres[j].position.y, spheres[j].position.z);
            var r2 = new Array( spheres[i].position.x, spheres[i].position.y, spheres[i].position.z);
            var r12 = new Array(r2[0]-r1[0], r2[1]-r1[1], r2[2]-r1[2]);
            var r12UnitVector = new Array( r12[0]/Math.abs(r12[0]), r12[1]/Math.abs(r12[1]),r12[2]/Math.abs(r12[2]) );

            var m1 = masses[j];
            var m2 = masses[i];
            var r12Squared = r12[0]*r12[0] + r12[1]*r12[1] + r12[2]*r12[2];
            var a12 = new Array( -(gravConst*m2/r12Squared)*r12UnitVector[0], -(gravConst*m2/r12Squared)*r12UnitVector[1], -(gravConst*m2/r12Squared)*r12UnitVector[2]);

            velocities[j][0] += a12[0]*timePassed;
            velocities[j][1] += a12[1]*timePassed;
            velocities[j][2] += a12[2]*timePassed;
        }

    }
}

```

If you can see anything wrong with it, or give me any tips on using JavaScript to simulate many particles in a 3D environment most **efficiently** (I'm very new to physics + simulation), that would be awesome!

# Answer
> 1 votes
This seems to work. It's a little clunky though - it makes me think there's some sort of rogue rounding going on:

```
function handleGravity() {
    for(var j = 0; j < spheres.length; j++) {

        for(var i = 0; i < spheres.length; i++) {
            if(i != j) {
                var r1 = new Array( spheres[j].position.x, spheres[j].position.y, spheres[j].position.z);
                var r2 = new Array( spheres[i].position.x, spheres[i].position.y, spheres[i].position.z);
                var r12 = new Array(r2[0]-r1[0], r2[1]-r1[1], r2[2]-r1[2]);
                var r12UnitVector = new Array( r12[0]/Math.abs(r12[0] + r12[1] + r12[2])/3, r12[1]/Math.abs(r12[0] + r12[1] + r12[2])/3, r12[2]/Math.abs(r12[0] + r12[1] + r12[2])/3 );

                var m1 = masses[j];
                var m2 = masses[i];
                var r12Squared = r12[0]*r12[0] + r12[1]*r12[1] + r12[2]*r12[2];
                var a12 = new Array( -(gravConst*m2/r12Squared)*r12UnitVector[0], -(gravConst*m2/r12Squared)*r12UnitVector[1], -(gravConst*m2/r12Squared)*r12UnitVector[2]);

                velocities[j][0] -= a12[0]*timePassed;
                velocities[j][1] -= a12[1]*timePassed;
                velocities[j][2] -= a12[2]*timePassed;
            }
        }

    }
}

```

---
Tags: physics, javascript, simulations
---