# Question
Title: Slick2D ComponentListener added to MouseOverArea not responding to right mouse clicks
I am developing a UI using Slick2D and experimenting with MouseOverArea. I have noticed that if I add a ComponentListener to my Button (which extends MouseOverArea) it only responds to left-clicks on my mouse, but not right-clicks. The MouseOverArea itself responds to both. If I call notifylisteners() in my Button subclass then ComponentListener does respond to right-clicks, but it gets called twice for left-clicks.

Does anyone have any idea why this is happening and how to fix it? Code included below:

```
package slick2dbutton;

import java.util.logging.Level;
import java.util.logging.Logger;
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.gui.AbstractComponent;
import org.newdawn.slick.gui.ComponentListener;
import org.newdawn.slick.gui.GUIContext;
import org.newdawn.slick.gui.MouseOverArea;

public class Slick2DButton extends BasicGame {

    Button button;

    public Slick2DButton(String title) {
        super(title);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        AppGameContainer game;
        try {
            game = new AppGameContainer(new Slick2DButton("Slick2DButton Test"));
            game.setMaximumLogicUpdateInterval(60);
            game.setDisplayMode(640, 480, false);
            game.setTargetFrameRate(60);
            game.setAlwaysRender(true);
            game.setVSync(true);
            game.setShowFPS(false);
            game.start();
        } catch (SlickException ex) {
            Logger.getLogger(Slick2DButton.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void init(GameContainer container) throws SlickException {
        button = new Button(container, new Image("res/bunsen burner #1.png"), 50, 50, new Slick2DButton.Listener());
        button.setMouseOverImage(new Image("res/bunsen burner #2.png"));
        button.inputStarted();
    }

    @Override
    public void update(GameContainer container, int delta) throws SlickException {
    }

    @Override
    public void render(GameContainer container, Graphics g) throws SlickException {
        button.render(container, g);
    }

    public class Listener implements ComponentListener {

        @Override
        public void componentActivated(AbstractComponent source) {
            System.out.println("Source: " + source);
        }
    }

    public class Button extends MouseOverArea {

        public Button(GUIContext container, Image im, int x, int y, ComponentListener listener) {
            super(container, im, x, y, listener);
        }

        @Override
        public void mousePressed(int button, int mx, int my) {
            super.mousePressed(button, mx, my);
//            this.notifyListeners();
            System.out.println("Button: " + button);
            System.out.println("");
        }
    }
}

```

# Answer
I got around my problem by re-writing my code to remove ComponentListener. Doing this I got a single response to a left-click (or right-click). This doesn't differentiate between left or right-clicks - it just picks up clicks, but that works for me. My test code is posted below.

```
package testslick2dbutton;

import java.util.logging.Level;
import java.util.logging.Logger;
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.gui.GUIContext;
import org.newdawn.slick.gui.MouseOverArea;

public class Slick2DButton extends BasicGame {

    Button button1;
    Button button2;

    public Slick2DButton(String title) {
        super(title);
    }

    public static void main(String[] args) {
        AppGameContainer game;
        try {
            game = new AppGameContainer(new Slick2DButton("Slick2DButton Test"));
            game.setMaximumLogicUpdateInterval(60);
            game.setDisplayMode(640, 480, false);
            game.setTargetFrameRate(60);
            game.setAlwaysRender(true);
            game.setVSync(true);
            game.setShowFPS(false);
            game.start();
        } catch (SlickException ex) {
            Logger.getLogger(Slick2DButton.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    @Override
    public void init(GameContainer container) throws SlickException {
        button1 = new Button(container, new Image("res/Launch Normal.png"), 50, 50);
        button1.setMouseDownImage(new Image("res/Launch Press.png"));
        button1.setMouseOverImage(new Image("res/Launch Over.png"));
        button1.inputStarted();

        button2 = new Button(container, new Image("res/Launch Normal.png"), 200, 50);
        button2.setMouseDownImage(new Image("res/Launch Press.png"));
        button2.setMouseOverImage(new Image("res/Launch Over.png"));
        button2.inputStarted();
    }

    @Override
    public void update(GameContainer container, int delta) throws SlickException {
    }

    @Override
    public void render(GameContainer container, Graphics g) throws SlickException {
        button1.render(container, g);
        button2.render(container, g);
    }

    public class Button extends MouseOverArea {

        public Button(GUIContext container, Image im, int x, int y) {
            super(container, im, x, y);
        }

        @Override
        public void mousePressed(int button, int mx, int my) {
            super.mousePressed(button, mx, my);
            if (this.isMouseOver()) {
                if (this == button1) {
                    System.out.println("Screen Button 1 Pressed!");
                }
                if (this == button2) {
                    System.out.println("Screen Button 2 Pressed!");
                }
            }
        }
    }
}

```
> 0 votes

# Answer
In my experience the AbstractComponent section of slick has some problems. I am quite sure there are some bugs and so I stopped using it. The rest of the slick framework seems to work fine though.

Try alternatives like Nifty GUI which is compatible with slick
> 0 votes

---
Tags: java, slick
---


title: particle - interpolate

text:
# Question
Title: particle - interpolate
I want to make a particle that interpolates in Alpha and velocity.

```
public class Particle extends GameObject implements Updateable
{

    int time;

    int lifetime;

    int Alpha;

    double dx;

    double dy;

    int[][] alphaEnvelope;

    double[][] speedEnvelope;

    @Override
    public void update()
    {
        time++;

    }

}

```

this is my particle class.

alphaEnvelope\[x\]\[y\] changes the Alpha over time where X is the time and Y is the Alpha Value.

For example:

\[1\]\[100\]

\[60\]\[70\]

\[70\]\[0\]

the Alpha is 100 at lifetime 1, 70 at lifetime 60 and 0 at lifetime 70.

How do I interpolate between these values fluently?

# Answer
Linear interpolation you can do with following code:

```
int l = 0;
for(int i = 0; i < keys.Length; i++)
{
if(time > keys[i]) l = i;
}
double interval_len = keys[l + 1] - keys[l]; //r = l + 1
double k2_a = (time - keys[l]) / interval_len; //k1_a = 1 - k2_a
return k2_a * values[l+1] + (1 - k2_a) * values[l];

```

It is very similar to your code - you were on the right track. Code explanation: first we find between which keys the time lies, then we find the interval length, after that we subtract left value from time to get "local time on interval". And lastly we find "how much close" it is to right boundary by dividing local time by interval length. We multiply right value by the result and finally we multiply the left value by complement and sum it for desired result.
If you wanted more smooth values you could for example interpolate by cubic spline solving system of linear equations (not hard to find, you will be likely looking for chord parameterization and natural spline bounding conditions).
> 1 votes

# Answer
You can try some polinomial interpolation : i.e lagrangian interpolation

In your example it becomes (if I calculated it right ):

```
L(x) = 100 * ((x-60)/(1-60)) * ((x-70)/(1-70)) +
       70 * ((x-1)/(60-1)) * ((x-70)/(60-70)) +
       0 * ((x-1)/(70-1)) * ((x-60)/(70-60)) +

```
> 1 votes

---
Tags: interpolation
---


# Question
Title: How do I create a simple RPG game server?
I'm working on a Sprite Kit game. I'd like to make it a true multiplayer game, by which I mean that each person joining the game has their own camera. I've seen tutorials on multiplayer games where the players share the same game screen, but that's not what I want.

I understand there needs to be a server that players connect to, which means the "world" that players connect to should be running on the server. Is this correct?

How do I have a server running the 'world' for this game? Does it have to be a specific type of server, or can I use Node.js or whatever else I want?

# Answer
You're on the right track.

The gist of the client-server networking model is that a *server* is that it's a central point of knowledge that *clients* connect to. A game server typically contains

* an in-memory **world representation**,
* a list of **connected players**,
* a **game loop** (with e.g. player control handler, a physics engine & AI).

You'll also need a communication channel between your server and clients, so clients can transmit the player's actions, and the server can transmit the game state.

More advanced client-server configurations might involve

Start simple. It's best to add complexity only as necessary. This rabbit hole is deep.

---

You mentioned Node.js: I've written a few servers for small games in that and it's been good. But you can write a server and clients in anything you like. *Eve Online*'s is largely in Erlang, Minecraft's in Java, pretty much everything by Valve is in C++, et cetera.
> 17 votes

---
Tags: ios, multiplayer, rpg, client-server, spritekit
---


# Question
Title: How can I move a created Image in Slick2D?
I want a image to follow the mouse, and I use Image class of Slick 2D:

```
public void init(GameContainer gameContainer, StateBasedGame stateBasedGame) throws SlickException {
    mouseImage = new Image("res/mouse.png");
}
public void render(GameContainer gameContainer, StateBasedGame stateBasedGame, Graphics  graphics) throws SlickException {
    mouseImage.draw(0,0,0.1f);
}

```

But it seems that it does not have method for re-positioning a Image object. So how can I implement it (in `update` method)? Thanks.

# Answer
You need to create variables that determine the position of your image, make your render function use those variables as the position, and change those variables when you want to move your object.

Here's how you can do it:

```
private float x = 0;
private float y = 0;

public void init(GameContainer gameContainer, StateBasedGame stateBasedGame) throws SlickException {
    mouseImage = new Image("res/mouse.png");
}

public void render(GameContainer gameContainer, StateBasedGame stateBasedGame, Graphics  graphics) throws SlickException {
    mouseImage.draw(x,y,0.1f);
}

public void moveDown(float amount) {
    y += amount;
}

public void moveRight(float amount) {
    x += amount;
}

```
> 0 votes

# Answer
Haven't used Slick2D, but I guess you should just change the coordinates, maybe when rendering?
> 0 votes

# Answer
If you want it to be in update, you can use the `setCenterX` and `setCenterY` methods.

```
mouseImage.setCenterX(Mouse.getX());
mouseImage.setCenterY(Mouse.getY());

```

However `Y` coordinates are going to be reversed. If you want them to correspond to proper ones you can do:

```
mouseImage.setCenter(container.getInput().getMouseY());

```
> 0 votes

---
Tags: java, lwjgl, slick
---


# Question
Title: Why would this scaling matrix have no effect?
To draw a simple model using the DirectXTk, I'm doing the following. It all works perfectly, draws correct, and so on. Except changing the scaling factor makes NO difference, and I can't figure out why.

```
_MissileScale = 5.0f;
XMMATRIX GetWorldMatrix()
{
    XMMATRIX translation = XMMatrixTranslationFromVector(XMLoadFloat4(&_Position));
    XMMATRIX rotation    = XMMatrixRotationRollPitchYaw(_RotationX, _RotationY, _RotationZ);
    XMMATRIX scaling     = XMMatrixScaling(_MissileScale, _MissileScale, _MissileScale);

    return scaling * rotation * translation;
}

```

Then when I draw it, I ask for that matrix. The rotation and translation work, but not the scaling.

```
        XMMATRIX mView = pCamera->GetViewMatrix();
        XMMATRIX mProj = pCamera->GetProjMatrix();
        XMMATRIX mWorld = pMissile->GetWorldMatrix();

        _ptrMissileModel->UpdateEffects([pCamera](IEffect* effect)
        {
            XMFLOAT3 ambientLightColor(0.5f, 0.5f, 0.5f);
            auto lights = dynamic_cast<IEffectLights*>(effect);
            if (lights)
            {
                lights->SetLightingEnabled(true);
                lights->SetPerPixelLighting(true);
                lights->SetLightEnabled(0, true);
                lights->SetAmbientLightColor(XMLoadFloat3(&ambientLightColor));
                lights->SetLightDiffuseColor(0, Colors::White);
                lights->SetLightDirection(0, pCamera->GetWorldAhead());
                lights->SetLightEnabled(1, true);
                lights->SetLightEnabled(2, true);
            }
        });

```

Any thoughts? Of all the linear transformations you'd think scaling would be the hardest to get wrong! I've tried the two "flailing" attempts of reversing my order of multiplication and of transposing the matrix before handing it off to the shader, neither helped (both broke the rendering as you'd expect).

# Answer
It turns out that the scaling was being corrupted/altered elsewhere, so it was unrelated to the problem I believed it to be. The code above is, for all intents and purposes, correct.
> 1 votes

---
Tags: c++, directx, matrix, scale
---


# Question
Title: Implementing a modal dialog from scratch with C++
Right now I'm implementing my modal dialogs in windows with a separate message loop after popping up the dialog.

This straightforward an approach won't work with other systems that don't have message loops.

Obviously if I'd designed from scratch assuming one message loop I wouldn't have this problem.

In Unity3D (C#) I believe I could use a coroutine for this.

Aside from manually unrolling the code after the message loop so I can put it into a separate state or lambda to be called on close of the dialog, does anyone have any brilliant ideas on ways to make the code work with only one message loop?

I've tried googling but nothing obvious comes up.

EDIT: I know how to write modal dialogs from scratch, the question is whether there's a simpler way to update older code to remove the message loops.

Let me see if I can write a better example of the pseudcode. This is the best I've come up with.

```
//DoAlert has a while doAlert is up processmessage loop in it
int i = doAlert("title", "Choice1", Choice2", "Choice3")
switch (i) {
  Case 1 : do something;
}

```

do something else and return to the routine that called you which does something else before returning, etc.

would become

```
auto alert = doAlert("title", "Choice1", Choice2", "Choice3");
alert.addChoice(1, [](){ do something; });
alert.addChoice(2, [](){ do something; });
alert.addPostProcess([](){});
... return from routine
alert.addPostProcess([](){});
... when finally at message pump...
alert.process();

```

...

Clumsy but at least it's simple to read and understand.

If I were writing from scratch, I would not have written it this way for new code.

I'd rather not decipher all these in order to get rid of the multiple message loops. The only way seems to be to trace what happens when the message loop exits, and put that into a lambda or possibly put the whole mess into a state machine. The lambda seems to be the simplest but it still means tracing through all of them and creating a stack of onexit routines from doAlert.

Thanks, Ralph

# Answer
Just have one message loop with a state or stack of modal dialogs that override your usual control flow:

```
handle message():
  if is input message:
    if has modal dialog:
      handle modal input message
    else:
      handle main input message

```

If you have a window stack, this might be made a bit simple:

```
handle message():
  get top of window stack
  dispatch message to window

```

When you open a modal dialog, just add it to the GUI/Window manager. Now the system that processes input knows where the input goes.

If you're using polling input systems somewhere, also add a flag or check in those, e.g.

```
is button down():
  if has modal dialog:
    return false
  else:
    return is_down[button]

```

That will make it so any polling systems like gameplay just stop responding to input when the modal dialog pops up. You should probably just pause all those systems when said dialog is up, though:

```
update game:
  update graphics
  if no modal dialog is open:
    update physics
    update AI
    update other gameplay

```

that way you won't keep falling or getting attacked or anything while a modal dialog is open.

So far as code organization, you likely either have a `WindowManager` of some sort that you pass around everywhere or you just use a global/singleton and carry on.
> 1 votes

---
Tags: c++, game-loop, windows
---


# Question
Title: Stitching terrain tiles made in Blender at runtime
## Background

I'm making several individual terrain tiles inside of blender for use within a Unity 3D 5 game. Each tile is square and is made to represent a segment of a world. In game the tiles are randomly\* chosen and placed between each other. However these tiles do not always have matching sides.

## Why the tiles

To allow for greater terrain sculpting possibilities such as caves, precision-placed landmarks e.t.c. but still allow for a procedurally generated feeling; randomly placed static tiles are used.

There are mountain tiles and there are plane tiles. Mountain tiles have a more extreme terrain and are mostly next to other mountain tiles so that bigger mountains can be formed. Plane tiles are similarity placed next to other plane tiles.

The game is "low poly" and so is the terrain. This makes it hard to have flat sides on every tile at the same height for easy "stitching".

## Concrete question

How can I match these edges runtime to ensure that there are no visible tile edges?

# Answer
> 3 votes
You might consider something like Wang Tiles. The idea is that you have a predetermined set of edges for your tiles. You can randomly generate tiles, still, so long as the edges match.

For example, you might have 4 possible sides:

* A: Low terrain
* B: Mid terrain
* C: High terrain
* D: Water

You can generate the first tile by randomly choosing the 4 sides. The tile to the right has to have the same edge on the left as the first tile, but the other 3 sides can be randomly chosen. On the next row, you have to match 2 sides, but the other 2 can be randomly chosen, etc.

You can use more than 4 types of edges. That's just an example.

# Answer
> 1 votes
You can do some cool things if you allow the tiles to overlap a little and then interpolate bits that overlap. For the parts that overlap you need to calculate each tile's contribution (weight) to the overall height which I'll refer to as H(x,y). Then when you sample H(x,y) you find each tile that overlaps that point and sum the weighted local heights of those tiles. I've made a quick diagram that I hope explains this in more detail, each of the colored H(x,y)'s represents the heightmap of a specific tile, with x and y still being in absolute world coordinates.

---
Tags: blender, 3d-meshes, mesh, unity
---


# Question
Title: How should I set camera in Blender for example to render a sprite which can be used in an isometric map?
I am trying to render some 3D model in blender and use them as a texture sprite in a game which uses Apple’s SpriteKit. I have an isometric map with tiles size : 32 as width and 24 as height, Since I use same size tile whole over the map (isometric) I need to use an orthographic projection I think! please tell me if I am wrong but I was pretty sure! anyway...

I am using Blender to render my sprites (3D models) but I can not set the camera direction to have the rendered image really fit with the map. The attached picture shows the problem, take a look at the building.

I have also attached the geometric math that I have used to create my render script in Blender.

I found out that if I use a 32,24 tile I need to look at from 29Deg 29Min 28Sec but it seems not alright as the iOS simulator shows!

Can anyone help me on this? How do I have to prepare my sprite to fit well on my isometric map?

Those who have experience with isometric map games are welcome to answer and I really appreciate it.

Here is the code I wrote in python to render the 3D Model, I have also set the camera to Orthographic manually.

```
import bpy
cam = bpy.data.objects["Camera"]
def look_at(cam, point):
    loc_camera = cam.matrix_world.to_translation()
    direction = point - loc_camera
    # point the cameras '-Z' and use its 'Y' as up
    rot_quat = direction.to_track_quat('-Z', 'Y')
    # assume we're using euler rotation
    cam.rotation_euler = rot_quat.to_euler()
meshObj = bpy.data.objects["plate"]
meshObj.rotation_mode = 'XYZ'
#meshObj.rotation_euler = (0,0,0)
d = meshObj.dimensions
# Finding maximum dim of the object
objectScale = 1
if d[1] >= d[2]:
    objectScale = d[1] / 16
elif d[2] >= d[1]:
    objectScale = d[2] / 16
cam.rotation_mode = 'XYZ'
cam.location = (20.416*objectScale,20.416*objectScale,20.416*objectScale)
#cam.rotation_euler = (0.7853,0.7853,0.5147)
cam.rotation_euler = (0.7853,0.7853,0)
look_at(cam, meshObj.matrix_world.to_translation())
alamp = bpy.data.objects["Lamp"]
alamp.location = (17.416*objectScale/4,17.416*objectScale/4,20*objectScale/4)
print("Scaling ",objectScale)
bpy.context.scene.render.filepath = "/Users/iman/Documents/Render/ISOBUILDING.png"
bpy.ops.render.render(write_still=True, use_viewport=True, scene="Camera”)

```

# Answer
Well, the problem was that my sprites size weren’t a multiple of 32 so the scale and the geometric calculation were not as accurate as I expected to be. Theoretically it had to work! But it didn’t.

I used someones advises and it works fine now. here is the answer that I found for my question

http://flarerpg.org/tutorials/isometric\_tiles/

And this is the result:

Hope it helps someone, and save some time for him/her.
> 2 votes

---
Tags: rendering, isometric, spritekit
---


# Question
Title: Dynamically applied texture to GameObject using GUI button
In a scene I have multiple different GameObjects (almost 30 kinds) with parent child relationships. At run time (by using a GUI button) I want to change the texture of each clicked GameObject. As the user clicks specific GameObjects, a GUI with a multiple texture button will appear. By clicking on the button, that specific texture will be applied.

Is there a smarter way to do this?

Do I need to apply a script to every object?

I have tried to apply a script with some specific code; it's working but not regularly and correctly. Additionally, I want different texture options for each kind of GameObject.

# Answer
If this should be a general possibility to change textures of objects dynamically, then I don't suggest to use a script on each object.

Consider building your own component, which loads a texture and checks every draw to see if it has to change the texture.

If you only have a few objects, about 1-10 in your scene, it's totally ok if you want a quick and dirty solution to apply a script to every object.

Having a script on each object will not affect performance dramatically. But it is not the a very practical use of a script. A script is supposed to define features, skills and movement which you want to apply to few objects, so that behave differently from the others. For general purposes you should use components or even hard code it in your routines, and for special cases you use a script.
> 0 votes

---
Tags: unity, textures, materials
---


title: Collsion on place without collider

text:
# Question
Title: Collsion on place without collider
I'm creating a simple endless runner game, I'm dynamically generating the terrain, I'm placing obstacles at runtime at pseudo-random position. Here is the script that generates the terrain and places the obstacles:

```
public class Builder : MonoBehaviour {
    //Private vars
    private GameObject plane1;
    private GameObject plane2;
    private GameObject plane3;
    public GameObject obstacle;
    public GameObject coin;
    //Generates random vector3 within given range
    public Vector3 generateRandomVector(float xMin, float xMax, float zMin, float zMax){
        return new Vector3 (Random.Range (xMin,xMax),0,Random.Range (zMin,zMax)) ;
    }
    // Use this for initialization
    void Start () {
        plane1 = Resources.Load ("Plane1") as GameObject;
        plane2 = Resources.Load ("Plane2") as GameObject;
        plane3 = Resources.Load ("Plane3") as GameObject;
    }
    //Updates the position of the gameObject, this is the location where the next plane will be spawned
    public void updatePosition(){
        Vector3 newPosition = new Vector3 (gameObject.transform.position.x, gameObject.transform.position.y, gameObject.transform.position.z + 10);
        gameObject.transform.position = newPosition;
    }
    // This will pick up random plate and add the corresponding nnumber of other objects(coins, obstacles and powerups)
    public void generateTerrain(){
        if (Random.Range (0, 6) > 3) {
            //Clone the plane
            GameObject newPlate = Instantiate (plane3, transform.position, transform.rotation) as GameObject;
            //Generate objects
            generateObjects(newPlate, 7);

        } else if (Random.Range (0, 4) > 2) {
            //Clone the plane
            GameObject newPlate = Instantiate (plane2, transform.position, transform.rotation) as GameObject;
            //Generate objects
            generateObjects(newPlate, 5);
        } else {
            //Clone the plane
            GameObject newPlate = Instantiate (plane1, transform.position, transform.rotation) as GameObject;
            //Generate objects
            generateObjects(newPlate, 3);
        }
        //Updating the position so that the next element won't be on the same position as this one
        updatePosition();
    }
    //Generates obstales, coins and powerups
    public void generateObjects(GameObject parent, int numOfObjects){
        for(int i = 0; i < numOfObjects; i++){
            // Generate what kind of object will be spawned
            int rand = Random.Range (0, 10);
            //Generate random location within the parent
            float xMin, xMax,zMin,zMax;
            Renderer parentRenderer = parent.GetComponent<Renderer>();
            xMin = parentRenderer.bounds.min.x;
            zMin = parentRenderer.bounds.min.z;
            xMax =  parentRenderer.bounds.max.x;
            zMax =  parentRenderer.bounds.max.z;
            Vector3 pos = generateRandomVector(xMin, xMax, zMin, zMax);
            //TODO add powerups
            if(rand < 6){
                //Instantiate obstacle
                GameObject newObstale = Instantiate(obstacle, pos, parent.transform.rotation) as GameObject;
                newObstale.transform.parent = parent.transform;
            }else{
                //Instantiate coin
                GameObject newObstale = Instantiate(coin, pos, parent.transform.rotation) as GameObject;
                newObstale.transform.parent = parent.transform;
            }
        }
    }
}

```

The obstacles have tag "Obstacle" and collider, and isTrigger is checked. The problem is that when the player moves there are places where there isn't any obstacle but the OnTriggerEnter method detect a collision. Here is my class which is handling the OntriggerEnter method

```
public class PlayerTrigger : MonoBehaviour {
    private gameData gameDataInstance = new gameData();
    void OnTriggerEnter(Collider collider){
        if (collider.gameObject.tag == "Coin") {
            gameDataInstance.addCoins(1);
        }
        if (collider.gameObject.tag == "Obstacle") {
            Debug.Log ("Obstacle");
            //StorePersisten.storePersistenInstance.Save(gameDataInstance);
        }
        if (collider.gameObject.tag == "PowerUp") {
            // powerup
            Debug.Log("powerUp");
        }
    }
}

```

Accrding to my observations the collision happens when I call generateTerrain(Builder class) from another class called Destroyer which is destroying the objects which are behind the player. Here is the Destroyer class:

```
public class Destroyer : MonoBehaviour {
    private Builder builder;
    private bool isColliding;
    void Start() {
        builder = (Builder)FindObjectOfType(typeof(Builder));
        Debug.Log("Destroyer");
    }
    void Update(){
        isColliding = false;
    }
    void OnTriggerEnter(Collider collider){
        if (isColliding)
            return;
        isColliding = true;
        if (collider.gameObject.transform.parent != null) {
            Destroy (collider.gameObject.transform.parent.gameObject);
            Debug.Log ("Destroyed parent");
        } else {
            Destroy(collider.gameObject);
        }
        if (builder) {
            builder.generateTerrain ();
        }
    }
}

```

In short: There are collisions between the player object and object with tag "obstacle" without any visiable object around the player. Any ideas what may cause the problem?

EDIT:Forgot to mention that there's a game object "builder" which is a few units away from the player

# Answer
I cannot add just a comment because of missing reputation so I write it as answer but be aware this is not a tested answer.

You apply the transform of ur obstacles parent after initiate. So maybe it's because after the initiate of the obstacle the player collider trigger fires up, because the actual position of the collider is at the players position at initiate.
> 0 votes

---
Tags: unity
---


# Question
Title: Rotating A 2D Cannon Based On Mouse Position
I'm creating a game like bubble shooter, I have a cannon which is in the image bellow:

I want to rotate the cannon based on mouse position.

So far I tried various solutions I found over the web but non of them are working, I know that I only need to rotate the cannon on the Z axis because this is a 2D game, so I don't touch X and Y axis.

Does anybody know how can I rotate the cannon based on mouse position?

Or at least provide me a sample script on where to start.

Thank You.

# Answer
> 1 votes
You need to create a vector pointing towards the mouse -\> Subtract the position of your cannon from the position of your mouse.

```
vector2 dir = mouse.position-cannon.position

```

Then you get the angle from this vector by using this formula if y is up and x is right

```
angle = arctan(dir.y/dir.x) // or use atan2(y,x)

```

Now you have the total angle that you need to use for you cannon.

Keep in mind that you may need to translate from radians to degrees. You may also need to offset the angle by 90 degrees or so depending on where 0 degrees are in your coordinate system.

---
Tags: unity, 2d, rotation, shooter
---


# Question
Title: Simple voxel-block melee removing script
I'm trying to create a voxel based game, now I want my character to remove blocks with a melee weapon, but I'm not sure which way to go.

I mean is it the only way to get the Block with a raycast? I don't really want a rigibody weapon and the blocks with a trigger btw. . So if the raycast is the solution, how is it done? I don't get my code running, I just want to shoot a ray for a short distance in the facing direction, or better in the mousedirection. I've found a lot of code to do that but none is working for me :( here is my code so far.

```
        if (Input.GetButtonDown ("Fire1")) {
        RaycastHit hit;
        var v3 = Input.mousePosition;
        v3.z = 16.0f;
        v3 = Camera.main.ScreenToWorldPoint (v3);

        Vector3 worldMousePosition = Camera.main.ScreenToWorldPoint (v3);

        var direction = worldMousePosition - transform.position;
        direction.Normalize ();

        if (Physics.Raycast (transform.position, direction, out hit, 100)) {
            print ("There is something in front of the object!");
        }

    }

```

So my world looks like follows: I got a 3d Sidescrolling game, so the character is moving on x and y axis, the z axis of the world is on -16 btw. thats because i change the z value of the raycast. It doesnt work with 16 nor -16. I think this direction part is not fine, because the values are kinda odd.

# Answer
The problem is that you are running your mouse coordinates through `Camera.main.ScreenToWorldPoint` twice.

```
    var v3 = Input.mousePosition;
    v3.z = 16.0f;
    v3 = Camera.main.ScreenToWorldPoint (v3);
    Vector3 worldMousePosition = Camera.main.ScreenToWorldPoint (v3);

```

Deleting the 3rd line will help.

When you also have the problem that you are shooting in the opposite direction, it will help to replace:

```
var direction = worldMousePosition - transform.position;

```

with

```
var direction = transform.position - worldMousePosition;

```
> 1 votes

---
Tags: c#, voxels, raycasting, unity
---


title: Strange depth map projection

text:
# Question
Title: Strange depth map projection
I'm trying to implement depth-only SSAO and for that, I render a depth map into a texture and pass it to my SSAO shader which then uses it.

The problem is that when I try to output the depth map values from SSAO fragment shader (for testing purpose), I get something really weird.

Here is the result :

And, here is how it normally looks rendered before giving it to the SSAO shader :

The depth buffer seems OK, so I guess it comes from a transformation done in the SSAO shader.

Here are the shaders (I'm using the bgfx library, but the shader language is very similar to GLSL):

Here is the way I output the depth from my SSAO for testing :

```
//Vertex Shader
$input a_position, a_texcoord0
$output v_texcoord0

#include "../common/common.sh"

void main()
{
    gl_Position = mul(u_modelViewProj, vec4(a_position, 1.0) );
    v_texcoord0 = a_texcoord0;
}

//Fragment Shader
$input v_texcoord0

#include "../common/common.sh"

SAMPLER2D(s_depth, 0);

float readDepth( in vec2 coord )
{
#if BGFX_SHADER_LANGUAGE_HLSL
    float z = texture2D( s_depth, coord );
#else
    float z = texture2D( s_depth, coord ) * 2.0 - 1.0;
#endif // BGFX_SHADER_LANGUAGE_HLSL

    return z;
}

void main()
{
    float depth = readDepth( v_texcoord0 );
    ...
    //Some computation
    ...
    gl_FragColor = vec4(vec3_splat(depth), 1);
}

```

And here the shader for storing the depth into a texture :

```
//Vertex Shader
$input a_position
#include "../common/common.sh"

void main()
{
    gl_Position = mul(u_modelViewProj, vec4(a_position, 1.0) );
}

//Fragment Shader

void main()
{
    gl_FragColor = gl_FragCoord.z/gl_FragCoord.w;
}

```

My guess is that I may be projecting the depth texture in a wrong way.

Thanks in advance for any help.

# Answer
> 2 votes
I found that replacing `v_texcoord0` with `gl_FragCoord.xy / vec2(screen_width, screen_height)` in the SSAO shader, solved this issue.

---
Tags: shaders, glsl, depth-buffer, depth, ssao
---


# Question
Title: What is a good method for collision detection, where I check a collision, instead of all collisions
The collision system for my game currently works fine; it lets me test a collision with an entity or specified rectangle, but that's not enough. I use to use Game Maker, and it had collision events that were simple. What I want to do is not check collision with everything, but check for *a* collision with everything.

Using the former method would probably be really expensive, checking all other objects, per object, per frame. What is a good method for collision detection, where if I am colliding with something, I get it's class, and can decide what to do with it?

# Answer
Read Real-time Collision Detection. By far the best on the subject imho.

* Implement Spacial Partitioning of the objects in your scene. (kd-tree or octree or etc...) This is by far one of your most important components (when it comes to simulation \[like col. det.\] or rendering)
* Implement a Bounding Volume Hierarchy (BVH) for your objects - grouping the objects in the scene in clusters depending on their proximity one to another.

Using those two together has already increased your performance by a few orders of magnitude (more or less).

Then there are *many* collision detection optimisation tricks which you can further implement, here are just a few that come to mind:

* Object hierarchy - is very similar to the BVH described above, however depending on your implementation of BVH it could/could not be included. It is basically BVH on an object level. So if you have complex objects in your scene... obviously you don't want to check all their triangles against all the triangles of the other object being checked... You have a bounding box for the object, then a bounding box for each of it's components, etc... thus you will only check the triangles in the two colliding bboxes (b/n the 2 objects) of the lowest level, too see if there actually is a collision.
* The Raycasting check. Casting a ray from the centre/corners of an object in its direction of travel, to see if they hit any other object... Thus you can easily discard further collision detection of that object for that frame if nothing was hit, or if object hit is too far away (you'll have to check their velocities for that one)
* Start your crude checks with simpler containers. eg Use bounding spheres rather than bboxes for crude checking then fall into more detailed containers.

**Sphere -\> Box -\> Convex hull -\> Concave hull -\> ...**

*Those principles are completely language independent.*
> 0 votes

# Answer
If I understand your intention correctly, you are trying to figure out how to reduce the number of collisions to check for, which is basically in the realm of 'potentially collidable set reduction'. If so, you'd do well to research spatial subdivision and/or nearest-neighbour search algorithms (such as octrees, KD trees, BSP and the like). One (or more in concert) of these should allow to to figure out which collisions are likely to have occurred before doing the full collision step.
> 0 votes

# Answer
What you're looking for is "spatial partitioning". You want to break up your world space into smaller chunks to cut down on how many objects you detect collision against. Since you're just doing 2D you'll probably want to use a "quad tree". There are other options including BSP trees but in my experiences quad trees are the best all around solution.

As for determining which class you're colliding with C++ doesn't handle that as nicely as C# or Java do. You can either use a "dynamic cast" to cast a generic collider class to a more specific collider class or you can store a hash of the specific type id in the generic collider to know which class to statically cast to.
> 0 votes

# Answer
Spatial partitioning is most definitely the way to go. The book 'Game Programming Patterns' has a very accessible chapter on the subject (http://gameprogrammingpatterns.com/spatial-partition.html) so I'd highly suggest reading that, as well his chapters on the game loop and update method.

Also, if I understand your comment correctly, each different type of object has an id (so all powerups have id=1). I'd suggest instead to let each individual object have an id, and then keep an array (or map) between an id and the instance of its class. Along with that, put in one common function (I use 'update') for each entity type so that when you detect a collision you can simply call

```
id=collision_result();
id2class(id).update();

```

and then update() different classes can respond accordingly.
> 0 votes

---
Tags: c++, collision-detection, platformer
---


title: 3d projection help?

text:
# Question
Title: 3d projection help?
I've been wanting to know how to do 3d projections.

Can someone explain how i can use this to find the position for x and y on the 2d plane that is 600 * 600 pixels.

# Answer
Assuming that you want to compute the position that an arbitrary 3D vertex (x,y,z,1) has on the view plane after the projection: You can use the given parameters to compute a projection matrix:

where `f = cotangent(fovy * 0.5)`

This is also the matrix that will be set by a call to gluPerspective. Then, you can multiply this matrix with your vertex to obtain the projected vertex position.
> 1 votes

# Answer
Generally, you have to use a bunch of matrices. With the traditional OpenGL pipeline, you'd have to mutiply these matrices:

```
finalMatrix = modelMatrix
  *
  viewMatrix
  *
  projectionMatrix
  *
  viewport.windowMatrix;

```

To find the position of the vertex on your viewport, just multiply the vertex by the matrix:

```
onViewportVertex = in3dVertex * finalMatrix;

```

Of course, this implies that no shader modifies the vertex or the pixel.
> 0 votes

---
Tags: 3d, projection
---


# Question
Title: Why does my MonoGame mesh throw an unhandled exception when trying to draw?
I am using the '3D Models' chapter of Learning XNA 4.0 to further understand 3D implementation in XNA, but I am running into an unhandled exception, when I try to draw each mesh.

Here is my basic Draw() function. It determines the amount of mesh transforms inside my model, and proceeds to draw each one, using a default BasicEffect.

```
public virtual void Draw(Camera camera)
{
    Matrix[] transforms = new Matrix[model.Bones.Count];
    model.CopyAbsoluteBoneTransformsTo(transforms);

    foreach (ModelMesh mesh in model.Meshes)
    {
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.EnableDefaultLighting();
            effect.Projection = camera.projectionMatrix;
            effect.View = camera.viewMatrix;
            effect.World = GetWorld() * mesh.ParentBone.Transform;
        }

        mesh.Draw();
    }
}

```

When I attempt to run, I get stopped at *mesh.Draw();*, with the error

> An unhandled exception of type 'System.InvalidOperationException' occurred in MonoGame.Framework.dll
>
> Additional information: An error occurred while preparing to draw. This is probably because the current vertex declaration does not include all the elements required by the current vertex shader. The current vertex declaration includes these elements: SV\_Position0, TEXCOORD0, COLOR0.

The model was provided by our lecturer. I have confirmed that the model shouldn't have any problems drawing. I have also found a similar issue to the one I am having, on the MonoGame forums, however the user reported having a current vertex declaration that includes "SVPOSITION0, TEXCOORD0, COLOR0", and the solution appeared to be changing "SVPOSITION0" to "SV\_Position0".

While I am unsure how to directly change the vertex declaration, it appears I should already have the correct vertex declaration.

**Why won't my mesh draw?**

If I remove the `effect.EnableDefaultLighting()` line, it works, no problem. However, I then do not have light, and everything comes up as black. If I replace my ground.x model with the spaceship.x model supplied by Microsoft, it works with lighting. I presume my issue is with my model, however, I can not access spaceship.x to read in plain english, as I can with my ground.x.

***Ground.x***

```
xof 0303txt 0032
template Vector
{
    <3d82ab5e-62da-11cf-ab39-0020af71e433>
    FLOAT x;
    FLOAT y;
    FLOAT z;
}

template MeshFace
{
    <3d82ab5f-62da-11cf-ab39-0020af71e433>
    DWORD nFaceVertexIndices;
    array DWORD faceVertexIndices[nFaceVertexIndices];
}

template Mesh
{
    <3d82ab44-62da-11cf-ab39-0020af71e433>
    DWORD nVertices;
    array Vector vertices[nVertices];
    DWORD nFaces;
    array MeshFace faces[nFaces];
    [...]
}

template Coords2d
{
    <f6f23f44-7686-11cf-8f52-0040333594a3>
    FLOAT u;
    FLOAT v;
}

template MeshTextureCoords
{
    <f6f23f40-7686-11cf-8f52-0040333594a3>
    DWORD nTextureCoords;
    array Coords2d;
    textureCoords[nTextureCoords];
}

Mesh
{
     4;
     65536.00000;0.000000;-65536.00000;,
     -65536.00000;0.000000;-65536.00000;,
     -65536.00000;0.000000;65536.00000;,
     65536.00000;0.000000;65536.00000;;
     2;
     3;0,1,2;,
     3;0,2,3;;

    MeshTextureCoords
    {
         4;
         0.000000;0.000000;,
         0.000000;1024.000000;,
         1024.000000;1024.000000;,
         1024.000000;0.000000;;
    }

    MeshMaterialList
    {
        1;
        2;
        0,
        0;

        Material
        {
            0.800000;0.800000;0.800000;1.000000;;
            0.000000;
            0.000000;0.000000;0.000000;;
            0.000000;0.000000;0.000000;;

            TextureFilename{"sanddf.png";}
        }
    }
}

```

# Answer
> 1 votes
```
// effect.EnableDefaultLighting();

```

Disabling this line fixed the problem.

Remembering that in previous graphics applications, vectors also need normal co-ordinates in order to allow lighting, I turned off "EnableDefaultLighting". I had noticed there was only position, color and texture inputs being reported in the vertex declaration.

Whether this is the correct reasoning behind it, it solved the problem, immediately.

# Answer
> 1 votes
I don't know how deep u actually get into 3D development, but the error message is quite clear, at this spot, if u understand what is written.

To draw something on a graphics card, u need Shaders to define how sth is interpreted on the graphics card to draw it.

There is allways a definition for structures u share between ur code and the graphcis card.

In this case, the defined Structure for a vertex define in one of ur shaders seems to have less fields then u try to hand to the draw method.

So to solve this u will have to upload ur shaders, so we can have a look at and the structure of ur Vertex Struct in ur code.

Or u do it by urself, as for now, I'm sure. u know what's going on, u will be able to fix it.

---
Tags: c#, monogame, models, pipeline, exceptions
---


# Question
Title: How to load sprites manually from a file in unity?
We're making a game, in which the User can apply their own textures to the game in order to make their own rooms. Is there a way to make a prefab with sprites, scripts, colliders, etc during runtime? With a script or something?

# Answer
As far as I know, no. Prefabs are editor side only. By the way there is no need to make a prefab since you can build a generic GameObject and customize via script adding components and loading resources like sprites from file.

For Example

```
void Start(){
Sprite loadedSprite = Resources.Load("your_sprite_path", typeOf(Sprite));
GameObject go = new GameObject();

go.AddComponent<BoxCollider2D>();
go.AddComponent<SpriteRender>();
go.GetComponent<SpriteRenderer>().sprite = loadedSprite;
go.AddComponent<YourScript>();
...
}

```

Then if you need to store it you can save it to a file or inside a dataase.
> 1 votes

---
Tags: unity, sprites, spritesheet
---


# Question
Title: A* pathfinding for dynamic obstacles and player made blockages?
Hi I'm creating a TD in Unity 5 and need some help with my Pathfinding.

I'm going to use Arons A\* pathfinding for my AI which enables me to use dynamic objects and update the path during run-time. However in my game I want the player to be able to block the minions with special turrets which will force the minions to attack the "block tower" instead to get past to their destination.

How could I accomplish something like this?

Image for more clarity:

# Answer
I haven't looked at specific implementation of A\* by Aaron but with a normal A\* you could include the 'block tower' as passable terrain but update the heuristic so that the 'cost' is much higher than a normal tile (so that AI will evaluate whether it is easier to destroy the block and continue or simple go around via the path that is not blocked).

Then you would need to update your AI so that when an enemy tries to move from a normal tile to a 'block tower tile' it automatically attacks until destroyed.
> 21 votes

# Answer
If what you are looking for is a sort of taunting tower you can add a collider to it set as is trigger and when the minions enter the trigger they are just scripted to attack the tower.

If you want the minions to attack the towers only when there aren't alternative paths, then when the path is blocked and the A\* is called to calculate another path if it returns null then you can script the enemies to find all taunting towers and target them.
> 0 votes

---
Tags: unity, c#, 2d, ai, path-finding
---


# Question
Title: How do I update individual sprites within a spritegroup in pygame?
I have a for loop that takes values from a text file, and then creates and adds a bunch of sprites to a group platformlist\_list. The for loop will continue until every line of the text file is read.

```
self.object = Wall(firstarray[0] , int(firstarray[1]), int(firstarray[2]))

print int(firstarray[3]), ' x ', int(firstarray[4]), ' y'

self.object.rect.x = int(firstarray[3])
self.object.rect.y = int(firstarray[4])

initialization.platform_list.add(self.object)

```

What I want to be able to do is access these created sprites and move them, but if I use this code to try and move all of the sprites in the platform\_list group:

```
if (loadterrain.character.direction == self.left):
    loadterrain.wall.rect.x += self.movementspeed
    loadterrain.object.rect.x += self.movementspeed
if (loadterrain.character.direction == self.right):
    loadterrain.wall.rect.x -= self.movementspeed
    loadterrain.object.rect.x -= self.movementspeed
    loadterrain.floor.rect.x -= self.movementspeed

```

The only object on screen that will move is the last object that my for loop has created.

I want to be able to access and modify the x and y positions for every sprite inside of the platform\_list but have no idea how to do so because from the research I have done indexing the platform\_list is unreliable as it is not ordered.

What is the best way for me to access and modify the positions of all the sprites in that group?

# Answer
So it looks to me like you want to move all of the sprites in the pygame.sprite.Group initialization.platform\_list by the same amount. It should not matter that the sprites in the group are not ordered or indexed.

```
delta_x, delta_y = 0, 0
if (loadterrain.character.direction == self.left):
   delta_x += self.movementspeed
#...
for sprite in initialization.platform_list:
    sprite.rect.move_ip(delta_x, delta_y)

```

You can get a plain old python list of the sprites with the sprites() method, if you need it sorted for some reason before iterating through it. For example here's some basic y sorting.

```
sprites = sorted(initialization.platform_list,
                 key= lambda sprite: -sprite.rect.y)
for sprite in sprites:
    # ...

```

Just leave a comment if you need any further help.
> 1 votes

---
Tags: software-engineering, python, pygame
---


title: Zooming In SDL 2.0

text:
# Question
Title: Zooming In SDL 2.0
I'm currently working on a project in which I render pictures raw. That is I use simple IMG\_LoadTexture(), SDL\_RenderCopy(). I want the program to be able to zoom in/out and textures to be scaled to screenwidth/height. I googled it but most of the answers for this question was outdated. Can I achieve this in SDL2. If not what's the way of doing this.

# Answer
By using SDL\_RenderCopy you can do all the zoom in/out or scaling stuff, by using non `null` values for the `srcrect` and `dstrect` parameters.

Here is the prototype of the function :

```
int SDL_RenderCopy(SDL_Renderer*   renderer,
                   SDL_Texture*    texture,
                   const SDL_Rect* srcrect,
                   const SDL_Rect* dstrect)

```

So you just need to create two `SDL_Rect` and setup them accordingly.
> 2 votes

---
Tags: c++, sdl, windows
---


# Question
Title: In Box2D, what exactly does a fixture represent?
In Box2dWeb, when we create a body we attach a fixture to the body object. We make the shape, friction, restitution and so on by tinkering with the fixture object.

So from this can we conclude that the fixture is what we really need to tinker with to get the body we want, and the body object we create just an abstract entity? Abstract in the sense that by itself, it is invisible in the canvas after we draw and animate the canvas? The body is just the abstract, formless object that becomes physical once we attach the fixture. Is this right to conclude?

# Answer
Yep, sounds right.

A *body* abstractly represents a physical entity. A *fixture* defines its shape, physical properties and which other fixtures it collides with. Technical details in the Box2D manual, Chapter 7: Fixtures.

Some reasons they are separate:

* This separates concerns by allowing the same fixtures to be used for all types of bodies (dynamic, static, kinematic).
* It allows you to create a *compound body* that has multiple fixtures. Fixtures in the same body are stationary relative to each other. (This is superior to a weld joint, which can flex slightly due to Box2D being an iterative solver.)
> 5 votes

---
Tags: box2d, terminology
---


title: Create a WebGL native plugin

text:
# Question
Title: Create a WebGL native plugin
I am trying to create a WebGL plugin and I read in the docs here: http://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html

But I'm not sure I understand.

I created a file in Assets/Plugins/WebGL called DomPlugin.jslib:

```
var DomPlugin = {
    ReadFromDom: function()
    {
        var mapStr = document.getElementById('my-elm').innerText;
        var buffer = _malloc(mapStr.length + 1);
        writeStringToMemory(mapStr, buffer);
        return buffer;
    }
};
mergeInto(LibraryManager.library, DomPlugin);

```

Within one of my C# scripts, I created a method declaration like so:

```
[System.Runtime.InteropServices.DllImport("__Internal")]
private static extern string ReadFromDom();

```

Then I call this external method like so:

```
private string ReadData()
{
    if (Application.platform != RuntimePlatform.WebGLPlayer)
        return testData.text;

    return ReadFromDom();
}

```

My WebGL Template page has an element with ID my-elm defined above `%UNITY_WEBGL_LOADER_GLUE%`

When I deploy I find this error:

Invalid function pointer called with signature 'ii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)

# Answer
> 2 votes
Fixed by changing my C# script:

```
private delegate string ReadData();
private ReadData dataReader;

#if UNITY_WEBGL && !UNITY_EDITOR

[System.Runtime.InteropServices.DllImport("__Internal")]
private static extern string ReadFromDom();

#else

public TextAsset testData;
private string ReadTestData()
{
    return testData.text;
}

#endif

void Awake()
{
#if UNITY_WEBGL && !UNITY_EDITOR
    dataReader = ReadFromDom;
#else
    dataReader = ReadTestData;
#endif
}

```

---
Tags: unity, javascript, webgl, plugin
---


# Question
Title: Approximating strength and hardness of alloys
I do not have any formal education in metallurgy, but I am trying to make a game mechanic based on it. I need to be able to alloy together different metals and alloyable materials such as carbon in different percentages, and get an approximation of the strength and hardness of the resulting alloy. If anyone has any ideas how what I would need to do to calculate such a thing I would be very appreciative, thanks!

# Answer
You could take cues from bit fields. Bit fields have the special quality that adding up previous bits is always one less than the next one. So I'd order the metals by hardness, then assign a bit to each one. E.g.:

Quicksilver = 1 Lead = 2 Iron = 4

Then you can add up the metals and get a certain hardness. E.g. adding Quicksilver and Lead would give a harder metal, but still not as hard as Iron.

Of course, this assumes that adding Quicksilver and Lead makes a stronger metal, if Quicksilver actually weakens the lead, you may have to pick the numbers 1 less than each power of 2, and then subtract the smaller from the larger:

Quicksilver = 1 Lead = 3 Iron = 7

and then mixing quicksilver with lead gives 2, which is \< Lead but \> Quicksilver. Mixing Lead with Iron gives 4, which is still better than Lead. And Quicksilver with Iron wouldn't dilute it as much, but would weaken iron. Would that work for you? Or is that too simplistic?

I guess you would want to draw a curve and then find an equation that expresses it, mathematically spoken.

If you have a limited number of combinations (91 metals is too much, but if you only need 8, there's only 64 combinations), you could just list them all in order, and their combinations, and then give each one a number that represents its hardness. You could put those in a dictionary/map with which metals are involved as the key (in alphabetic order or whatever) to look up the resulting hardness.

Of course, if you want to model flexibility as well, or different ratios of metals, you'd probably find someone well-versed in metallurgy and ask them how it *really* works. But in most games the combinations are so few that you can just manually generate them.
> 1 votes

---
Tags: game-mechanics
---


# Question
Title: TypeError: R[o5R.F6s] is not a function in changing states in phaser box2d
i build my game using `phaser.2.4.3.min.js` and `phaser.2.2.2.box2d.min.js` When trying to change states this error is being raised `TypeError: R[o5R.F6s] is not a function` and i can't seem to figure out the problem

PS : i took The source code of box2d plugin from the example folder in phaser , and i did not purchase the full plugin yet i was just testing it .

is there anyway to fix this issue ?

here is the game code : http://jsfiddle.net/fbdtq1tg/5/

and here where the error is raised :

```
SetGameOver: function () {
            this.game.state.start("TheGame");
        }

```

# Answer
> 0 votes
This was apparently a known issue in the Box2D plugin. As much as I hate suggesting buying a library like this, they *claim* to have fixed this bug in the currently distributed version. If you're dead set on Phaser and this Box2D plugin, I would consider buying it but my honest advice would be to stay away from such libraries.

---
Tags: javascript, box2d, phaser
---


# Question
Title: Move an enemy towards the player in pygame
I set variables for the distance between the enemy and the player along the x-axis and y-axis. My plan is to move the enemy along the hypotenuse formed by y and x-axis line at a constant speed. The thing is I'm not sure how to set x and y speed of the enemy so that it will adjust dynamically to the changing position of the player and still maintain a constant speed. I thought that maybe I could find the angle at which enemy approaches the player and do something with that, but I couldn't think of anything.

# Answer
> 1 votes
You should take a look at some vector math stuff, here's an example of a Vector class that will help you quite a bit in implementing this sort of logic. I think this is without bugs, but who knows.

```
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __sub__(self, other):
        return Vector(self.x - other.x, self.y - other.y)

    def __mul__(self, scalar):
        return Vector(self.x * scalar, self.y * scalar)

    def __div__(self, scalar):
        return Vector(self.x / scalar, self.y / scalar)

    def length(self):
        return ((self.x ** 2) + (self.y ** 2)) ** 0.5

    def normal(self):
        return self / self.length()

```

You can use it in place of every position, distance, velocity and so on.

```
player.position = Vector(5, 5)
enemy.position = Vector(7, 8)

```

It makes logic like you're case very simple! Just subtract the enemy's position from the player's to get the direction the enemy should move towards the player. Make sure you normalize that (create a vector with length 1) and then you can multiple it by some speed value and add it back to the enemy's position to have him move.

```
enemy_speed = 0.1

for _ in range(10):
    enemy_position += (player_position - enemy_position).normal() * enemy_speed
    print enemy_position

```

As a quick side note, you pretty much never need to use angles. Vectors are great at specifying **directions**, whereas angles are used (but not even that great at) specifying **rotations**. A rotation being like a transformation, taking an object in some orientation and then applying a rotation to it. That is pretty much the only place where angles ought to be used, vectors are super handy otherwise.

---
Tags: mathematics, ai, pygame
---


# Question
Title: What causes SDL2 error 0xc00007b when running my game on other people's computers?
I made a game using SDL2 and made it available for download. However, I first tried to install and play it on a different computer, to no avail. I made sure to copy all the .dlls and install all the runtimes, yet I still get error `0xc00007b`.

Am I doing something wrong?

# Answer
A quick search returns:

```
0xc00007b – the application could not start correctly. This may be because you are mixing up a 32bit environment with a 64bit one

```

Ensure the SDL you have is correct for your program, and that the program targets the correct Windows version (i.e. set Visual Studio to build for x86 if the computer runs 32 bit versions of Windows).
> 2 votes

---
Tags: c++, sdl2, distribution
---


# Question
Title: Can I use physics in Isometric map based games?
I am trying to use physics in my game which is an isometric map based strategy game that the player deals with a city full of buildings, roads and people in it. I am writing the game with Swift and SpriteKit technology.

(the following picture shows a snapshot of my game)

*MY GAME*

I like to use Spritekit's physics library so I would be able to simulate car accidents and preventing them to go throw the buildings and other kind of stuff that physics could provide.

I am familiar with Physics and I have enough experience with Bullet and I can write a 3D game using OpenGL ES and physics, but I haven't really used physics in 2D isometric map games.

I have also wrote a 2d physic game that was really 2d (an endless runner) which was actually a sample of a book but as you can see in the following picture the gravity vector is the Y axis and every thing is pretty easy.

Here is the gravity vector that is used to create the game at the following picture.

```
self.physicsWorld.gravity = CGVectorMake(0, -9.8)

```

*Someone Elses Game, Book Sample*

Book Name : iOS 7 Game Development

Author : Dmitry Volevodz

You may find the book Here

However, in an isometric map game you can't just set and assign the Y axis as a gravity vector. since the method which sets the gravity vector accepts two arguments it is a big hope that I can use physics in my isometric map games. For example something like this

> I Say!!! :

As I am still using a cartesian coordinate system (perpendicular axis) X and Y axis make a 90 degree angle and if I need to project the gravity quantity over the X and Y axis it would be g*Cos(45),g*Sin(45) I haven't tested it yet.

```
self.physicsWorld.gravity = CGVectorMake(-9.8*0.707, -9.8*0.707)

```

May you please help me on setting the gravity vector and how should I define the moving objects like cars and humans and the static ones like buildings any other tips on modelling physics in isometric map are also welcome and appreciated.

The main question is: is it really possible to use physics in an isometric map based games?

# Answer
The answer is *YES*,

You may set the gravity vector to (0, -some number) for this purpose, your code which multiplies the g scalar with sin and cos of 45 degree will be true if the Sprite Kit physics coordinate system could be changed to your isometric coordinate system.

I mean the direction of the gravity vector is still the Y axis, look at your Z axis (screen's Y axis), though reducing the quantity of g will make the project much more natural, so it is better to set (0,9.8\*0.707).

Try to define different groups of objects with different category bit so you may manage the collisions better and faster.

I don't know exactly what are you doing but using physics in your project will be a great asset in order to manage some of the jobs.

I strongly recommend you to let physics control some of the tasks and logics and define each sprite in a pre-planned category (bits).
> 3 votes

---
Tags: physics, isometric, spritekit
---


title: Underwater Shader Animation Help

text:
# Question
Title: Underwater Shader Animation Help
I found an underwater (distort) effect and I got it to work but somehow I cannot make it animate given the offset here:

Fragment Shader code:

```
uniform sampler2D fbo_texture;
uniform float offset;
varying vec2 f_texcoord;

void main(void) {
  vec2 texcoord = f_texcoord;
  texcoord.x += sin(texcoord.y * 4*2*3.14159 + offset) / 100;
  gl_FragColor = texture2D(fbo_texture, texcoord);
}

```

Original Source here

# Answer
Figured it out by looking other shader examples and hopefully it will benefit others. elapsedTime can be added to the computation or offset and will animate the effect, some use sin/cos as well..

```
uniform float elapsedTime;

```
> 2 votes

---
Tags: opengl, shaders, glsl, fragment-shader
---


# Question
Title: How to transform a matrix's local space position into another's local space
When looking at an example to learn how to do per pixel collision, I came across this:

```
// Calculate a matrix which transforms from A's local space into
// world space and then into B's local space
Matrix transformAToB = transformA * Matrix.Invert(transformB);

```

I have a (very) basic understanding of matrices, so I'm not too sure how this works, how can you convert the local space of one matrix to another by multiplying by the others inverted?

# Answer
> 2 votes
A transformation matrix has two functions: It can move and rotate a vector. We need one vector that we transform a little. Let's call it *positionRelativeToA*. We can transform this vector to the global world coordinates as follows:

```
Vector positionAbsolute = positionRelativeToA * transformA;

```

Of course, we can do the same with B:

```
Vector positionAbsolute = positionRelativeToB * transformB;

```

If we want to transform from the local space of B to A, we are interested in positionRelativeToB, so we change the above equation system a little:

```
//positionRelativeToB * transformB = positionRelativeToA * transformA;
//multiply with Matrix.inverse(transformB) on both sides
positionRelativeToB = positionRelativeToA * transformA * Matrix.inverse(transformB);

```

If you have to use that operation very often it makes sense to pre-calculate the Matrix * Matrix operation:

```
Matrix transformAToB = transformA * Matrix.inverse(transformB);
// ...
Vector positionRelativeToB = positionRelativeToA * transformAToB;

```

---
Tags: xna, matrix
---


# Question
Title: How to write a custom map canvas and project coordinates on it?
I am writing a game with Objective C ( xcode ) and I need to use the users location service to mark their position on a map but since I need to create my own map component, I am not able to use the Map framework.

Doing this I think I need to project latitude and longitude which I receive from location framework on my custom planar canvas, this is a small part of my game but the other parts are pretty easy or could be done if I could manage to implement this part, however I dont know where to start.

did anybody does it before? is it easy to create a map canvas?

Any kind of hint and help or sympathy are welcome.

Thanks

# Answer
First you need to know what is an ellipsoid and why we use them. The earth is spherical and to be exact it can be approximated using an ellipsoid. Location Service and all GPS system that work world wide, must use an ellipsoid that fits the best way the earth, Why we need an ellipsoid? because we need a mathematical model to do the computations. for example, suppose you need to know the distance from a specific point on the earth surface to the earth center. How could you do this? you must have the 3D model of the earth and measure the radius at that point. but in the real world we don’t have such a model and we are unable to measure all the points at the surface of the planet but we can only select a countable number of point on surface and using a 3D regression we find a best fitted ellipsoid. since you have a,b and c (diameters) of that ellipsoid, you may calculated each radius for every given latitude and longitude.

So, forget the irregular shape of the earth and assume that the earth is like an ellipsoid and there is no mountain on surface.All GPS and Location Service use a well known ellipsoid called WGS84. sometimes they call ellipsoid, datum. so do not panic if somewhere you saw this word.

Implementation : You need to google the parameter of WGS84 and find its a,b and c. and then you need to manage the map scroll and draw it yourself, to do it, you need to do a transformation from an ellipsoidal coordinates which is a pair of latitude and longitude to a planar cartesian coordinate system I mean the X and Y of the screen of your phone. you need to do the transformation from Lat,Long to X,Y and vice versa (X,Y to Lat,Long). There are different algorithms that do the transformation for you, some use iteration and some are direct method. But I don’t remember the details take a look at the following link

http://kartoweb.itc.nl/geometrics/Map%20projections/Understanding%20Map%20Projections.pdf

In order to model a world wide map, you need to use streaming technology to feed the canvas.

You may also create a new custom canvas class and inherits from CoreGraphics canvas.

If you really like and need to re-invent the wheel and re-write all of the CoreLocation framework and MapKit from sketch, you should consider that it demands a lot of time and cost you a lot. there is many precautions that you may take into consideration while using the data at this scale for Example If you use OpenGL to draw your map elements on your canvas, you need to define a local coordinate system by subtracting a big x and y from all coordinates to make them small enough so they will fit into float the numbers and increase the float accuracy in OpenGL varying and uniform variables. It is very challanging and needs a wide range of knowledge in many fields.

But Hey, I wish you luck.
> 2 votes

---
Tags: maps, objective-c, geolocation
---


# Question
Title: dynamic body jumping out of water object
In my game I have my main object, a jetski, which will dive down into water, when the screen is touched. I managed to code the jetski diving down, with Box2d and some buoyancy forces. But when the jetski is under water, it just rises to the water surface and stays there. Short: the jetski isn't jumping. I thought about applying forces as soon, as the jetski is on the surface. The problem with it is that the force would be a constant force ignoring how deep the jetski was (the deeper the jetski was, the faster it should rise and jump out). Is there any other way of doing this? This is the kind of thing I want: https://www.youtube.com/watch?v=b2t\_zMOy5SM

# Answer
> 2 votes
I've never tried to get this to work myself, but it seems like you would just need to increase the upward force applied to the jet ski's body as a function of the depth of the jet ski below the "surface" of the water object. The easiest way to get the distance below the surface might be to make a constant variable that describes the height of the water's surface, and then find the distance on the y axis between the jet ski's body and that height. Ex: float upwardForce = someConstantCoefficient * depth.

If a linear formula doesn't get the look that you want, something like float upwardForce = someConstantCoefficient * depth * depth, might.

Altogether it might look something like this:

```
@Override
public void render(float delta){
    //... other code you may have
    float upwardForce = constantCoefficient * depth * depth;
    //....
}

```

and in some code where you handle your inputs...

```
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
    yourBody.applyForceToCenter(0, upwardForce, true);

}

```

If I were you I would use

```
Gdx.app.log("", "Upward Force: " + upwardForce);

```

to figure out what the amount of force is that is being calculated, and adjust the "constantCoefficient" to make the force smaller if that is what is needed. For example if the depth * depth on its own is, say 1000 Newtons, you might want to make the coefficient as 0.1f, so that the force is only 100 Newtons and the jet ski isn't shot upward so fast. Another consideration might be to apply fractions of the upward force for some frames after the button is released, by multiplying the upward force by 1/60, or perhaps even 1/30, or some other fraction that gets the look you want, like this:

```
float upwardForce = constantCoefficient * depth * depth * 1 / 60;

```

But a better idea would be to multiply it by the delta between frames so that it isn't buggy in case the frame rate isn't 60 fps, like so:

```
...depth * depth * delta;

```

Also be sure to make sure that once the jet ski is no longer touching the water that the force is no longer being applied, other you could get some strange things happening...

I hope that makes sense. If in need for further clarification I might be able to help more :)

---
Tags: java, android, libgdx, box2d, jumping
---


# Question
Title: Correct level of abstraction for a 3d rendering component?
I've seen lots of questions around this area but not this exact question so apologies if this is a duplicate.

I'm making a small 3d game. Well to be honest, it's just a little hobby project and likely won't turn out to be an actual game, I'll be happy to make a nice graphics demo and learn about 3d rendering and c++ design.

My intent is to use *direct3d9* for rendering as I have some little experience of it, and it seems to meet my requirements. However if I've learned one thing as a programmer it's to ask "*is there any conceivable reason that this component might be replaced by a different implmentation*" and if the answer is yes then I need to design a proper abstraction and interface to that component. So even though I intend to implment d3d9 I need to design a 3d interface that could be implemented for d3d11, opengl...

My question then is what level is it best to do this at? I'm thinking that an interface capable of creating and later drawing

* Vertex buffers and index buffers
* Textures
* Vertex and Pixel "shaders"
* Some representation of drawing state (blending modes etc...)

In other words a fairly low level interface where my code to draw for example an animated model would use the interface to obtain abstract vertex buffers etc. I worry though that it's too low level to abstract out all the functionallity I need efficiently.

The alternative is to do this at a higher level where the interface can draw objects, animations, landscapes etc, and implement them for each system. This seems like more work, but it more flexible I guess.

So that's my question really, when abstracting out the drawing system, what level of interface works best?

# Answer
Apologies for the length of this response!

> "is there any conceivable reason that this component might be replaced by a different implmentation" and if the answer is yes then I need to design a proper abstraction and interface to that component.

"Any conceivable reason" is far too extreme a stance to take. Almost every function could be parameterised in some way, every module given some different strategy or policy, and every constant tweaked. If you provide an extra level of abstraction for each of these then you end up writing 2x as much code for no immediate gain, just a potential gain later if you ever require that flexibility.

If you go down the route of providing interfaces so that each of these things can be a facade for one of several different options, you then have to decide how you supply these different options, including defaults, and when you try and make that as simple as the original object was you often end up with a whole extra layer on top. This can (and does) get absurd in a lot of real world 'enterprise' software - may I humbly suggest reading this satire piece which sadly hits too close to home in many cases: Why I Hate Frameworks.

The biggest argument against this is complexity. Let's make the (probably incorrect) assumption that a good interface exists that could apply equally well to two 3D rendering APIs, and that someone is able to describe this to you in an answer here. You would then be working to this interface, which would, due to its multi-purpose nature, undoubtedly cover elements that DX9 does not use - for example, the plethora of API extensions that are available in OpenGL but not in DirectX 9. This is an added complication that will make your code harder to understand and maintain, and slow your learning process. It's bad enough when using an existing multi-platform library such as SDL, because people are forever coming across odd functions and restrictions that exist purely to fix something on one platform, but you'd not only have to learn why that part of the interface is there but also how it may or may not interact with the parts that you are currently about to write. eg. You'd end up writing abstract objects that encapsulate aspects of OpenGL extensions that are necessary in your core rendering code, even though you have no way of using them yet.

However, in future, once you are competent with how the DX9 system works, you can look into how the OpenGL system operates. You will then see how you need to adapt your existing system to make both parts work, and will do so, with the handy existence of your existing DX9 code path as an effective unit test to ensure your refactoring is correct.

You are lucky in that you are working with one of the most fluid and malleable materials known to engineering - source code stored as computer data. Embrace that blessing by making changes to it when you know you need them, rather than doing them months in advance and burdening yourself in the meantime by having to write to an abstraction you aren't gaining from yet.
> 8 votes

# Answer
> However if I've learned one thing as a programmer it's to ask "is there any conceivable reason that this component might be replaced by a different implmentation" and if the answer is yes then I need to design a proper abstraction and interface to that component.

This isn't really answering your question, but from *my* experience as a programmer, premature generalization is just as bad as premature optimization. You rarely gain anything and have to maintain it over the course of the project.

My advice is to straight up use D3D9 client code in your project, and when you determine that you need to switch interfaces, make an interface with all the things you're currently using. Programmers are *terrible* at predicting what they might need, doubly so in your case where you're not terribly familiar with the material, so this way you're doing the least amount of work.

See also: http://c2.com/xp/YouArentGonnaNeedIt.html
> 5 votes

# Answer
Hm, looks like I don't have enough reputation to post comments to responses.

Both Kylotan and Tetrad gave excellent answers. What I would add is to suggest you separate rendering code from the game logic -- this will serve several purposes:

* your code will be cleaner
* it will be easier for you to make changes to your renderer without rewriting half of the game logic each time
* eventually, providing completely different rendering modules is easier this way

As an added bonus, this way you will build your abstraction gradually as you work on your project. As you say, this is a learning project so take it easy and make it simple, adding complexity and abstractions as you go instead of making grand plans as you probably lack expertise to get it right initially (as Tetrad also suggested).
> 4 votes

# Answer
You can't write a low-level abstraction over this kind of thing, because the details of a shader are completely different between D3D9, 11, OGL, etc. It's simply impossible.

You could check out th abstractions implemented in, say, SFML, SDL, OGRE if you want to see what other people have chosen to do for rendering abstractions.
> 1 votes

# Answer
I've tried to write an API that wraps around both D3D and OGL neatly. It's a massive undertaking, I learned. Many of their differences *can* be reconciled. For instance, loading shaders. I effectively encapsulate D3D and OGL shader code in my own format. IE: In D3D, you need to specify the shader profile, so the file itself has the shader profile written in it. When the encapsulateed shader source is handed to my API, it calls the appropriate D3D shader creation method with the appropriate shader profile and such.

However, there are still plenty of differences that I haven't solved, nor might I ever, because I've decided that a higher-level abstraction is easier to design and satisfactory for my requirements. I'm currently working on something sort of similar to the D3DXEffect framework. Objects have a render-technique, which contains render passes, which have a set of render states, a set of shaders, and require certain inputs. This allows me to abstract more of the API away.
> 1 votes

# Answer
I don't know why people automatically jump to premature generalization/optimization when questions like these pop up. There is something to be said about being preemptive and realizing when a component in a system is likely to be swapped out. All of the answers about "don't worry and code away till you need to change it" generally get people into trouble in the real-world since they bring about bigger changes down the road, or leave behind code that should been designed differently to start with, but was left in because it "works". Doing some thinking ahead of time and knowing where to stop before you over-think is a skill in itself.

It would be much easier to refactor interfaces to accommodate differences between DX/OGL, than to introduce a whole new implementation (DX for example) into a system that is strictly coded to work with OGL. Code abstraction should happen at some level anyways as you wouldn't want to be mixing graphics code with game logic code all over the place, or repeating code. If I'm working on a game and starting out with OpenGL (because I have experience with it), but also know that I'd like to eventually get the game on Xbox/Windows (DX), it would be silly for me to not take that into consideration when designing my graphics API. The idea of refactoring something as complex as a game, and introducing new graphics APIs is tedious and error prone. I remember listening to an interview with Tommy Refenes (Super Meatboy) where he speaks about having to port the game to Mac after completion, and going through absolute hell because of lack of planning ahead of time.

You should consider how you're going to use your API, and build it up as your needs/knowledge change during the game's development process. You're not doing an abstraction over low-level OGL/DX, but rather creating an API for yourself to aid in loading geometry, loading/compiling shaders, loading textures, etc.
> 1 votes

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


title: Scene management

text:
# Question
Title: Scene management
I viewed sources of rendering engines (ogre, irrlicht, openscenegraph) but I can't really grasp the main ideas of their scene management systems.

I also read many articles (including Game Engine Architecture's "The Rendering Engine" part) but they all talk in abstract manners and never explain which classes are responsible to what etc. What should the SceneManager class do? SceneGraph too. Where do I store the caches (of Meshes, Textures etc) and what classes should "see" them?

How exactly should I manage the scene? I want to know everything starting from a simple `Node` design to the `render_frame()` function. If you have a good article on the subject that would be great.

I know I'm asking broad questions, but this is my last resort. I haven't found any good source for these.

Edit: here are some specific questions:

1. What is the task of the scene manager?
2. What is the task of the scene graph?
3. Where do I store all the caches, so that the user will be able to insert and query resources?

# Answer
It is difficult to answer these questions with much clarity because they are conceptual and the concept applied to each of these could be widely different depending on the engine and needs of any particular game. So I'm going to try to be fairly general.

---

### 1. Scene Manager

The scene manager keeps track of the scenes in a game, allowing to switch between them. At it's basic, it provides a centralized place to load and unload the scenes, keeping track of which one is loaded and handle unloading that scene when a new one is loaded.

See here for a basic example of a SceneManager.

It can get quite a bit more complicated, depending on the engine/game but primarily, its job is to provide a place to manage all the scenes so that each scene doesn't need to be uniquely referenced in the game code. Instead of the game having to deal with 10 or 20 (or 100) different scenes all over the code for example, by using a SceneManager and assigning all the scenes to it the game code can refer to the SceneManager and never need to know about any particular scene, how many scenes there are or if one is added/removed. In this way, to the rest of the code the number of scenes and specific names of the scenes does not need to matter.

This is a rather generic description. Some games or engines may use the scene manager a bit differently but the general concept will still apply. Usually the difference will come down to how a scene is defined. In most engines a scene is an entire level. In others a scene might be a subset of a level. In yet others, there may be no concept of a scene and instead they use screens but the same idea would still apply.

Really, this is just a software design pattern. In other areas of software development, we might call this a Facade or Mediator design pattern.

---

### 2. Scene Graph

I'm not going to get into explaining all the details of what a scene graph is since I think that this article does a better job of explaining it than I could and this answer would be too long otherwise. I will summarize though.

A scene graph is essentially a hierarchy of all the objects in a scene with parent-child relationships, such that manipulating one parent will implicitly affect the children. This is useful so that if you have a large number of objects, you can make one change to a node in a scene graph and that change will implicitly affect all the children of that node.

There are two key things that the scene graph helps with:

* spatial relationships
* behaviour relationships

The gamedev article I linked above uses a good example of a solar system to demonstrate how a scene graph is beneficial. Another example might be a squadron of ships, where they all act independently but also behave as a group, like a flock of birds.

---

### 3. Where to Store Caches

This is very subjective. You might have a ResourceManager to handle these things for your engine. You might have a manager for each type of resource or you might have both, where the ResourceManager coordinates all of the specific managers for each resource type. How much you need to break it down depends on the complexity of your game engine. Stick to the KISS principle and modify your design as you find that things are getting too messy and unmanageable.

---

**Note:** I'm no expert on these engine specifics. I'd rather leave these types of details to someone else to provide for me so I can focus on building games instead of implementing an engine that is likely going to be inferior to one that others have already spent a lot of time and effort to get right. I've learned enough to know why and how but explaining it is a little beyond my experience. Hopefully I'm not sharing incorrect information or missing any important details.
> 12 votes

---
Tags: architecture, rendering
---


# Question
Title: Cant sign in to MSDN/Visual Studio in Unity after trial
I've been using VS13 instead of Monodevelop for my Unity projects and my "30-day trial" has ended. Apparently all I have to do is sign in with my MSDN account and it *should* let me continue using VS without having to pay $6,000.00, but when I try to sign in I get "something went wrong, try again later"... this has been happening since yesterday. I have an active MSDN account that I am currently signed into and everything seems fine, should be a simple fix - hopefully. I reaaaaalllllyyy don't wanna go back to Monodevelop... any suggestions? It's only inside of Unity that I'm having this issue.

# Answer
> 0 votes
I had this problem too but im unsure now what the fix was. Are you using the community or the pro version? You may have to get the community edition, which is free and has no trial period.

You should first try disabling your firewall and antivirus though and do the update again. Your pc may be blocking the update process. This seems more likely to me.

Another possiblity is that you have to login to msdn and change the license for your copy of vs2013. Try this second.

Sorry i dont have a specific answer. Power is out right now so i cant check in my pc.

---
Tags: unity
---


title: How do I build Assimp with MinGW?

text:
# Question
Title: How do I build Assimp with MinGW?
How can I build Assimp with cMake and MinGW?

I tried, but I don't get a functioning library...

---

Details of my attempt:

I am trying to build the Open Asset Import Library (Assimp) but I have been running into problems. The assimp documentation is really poor and expects you to know exactly what you are doing. The developers haven't been particularly helpful either. I hope someone here has successfully built assimp and can let me know where I am going wrong. I suspect that I have several problems that are contributing to my failure. I am using 64 bit Windows 8.1 pro and using MinGW version 4.8.1.

The first thing I tried was downloading assimp 3.1.1 and boost 1.57. I extracted both folders and tried to use cMake to generate the makefile for MinGW. I haven't used cMake before and the assimp instructions are use cMake as you normally would, so I have no idea if I configured it right. I pointed `BOOST_ROOT` to the boost folder I extracted from the download, set it to build static libraries and generated the makefile.

I then tried running the makefile and got a number of errors. The first was

> ```
> IFCReaderGen.cpp.obj: too many sections and was too big.
>
> ```

After some googling, I found a workaround was to set `CMAKE_BUILD_TYPE` to `release`. That seemed to work and it finished the build but I only got the files `assimp32.dll` and `libassimp.dll.a`, which I thought was odd because I was expecting `lib/relese/libassimp.a` to be generated as per the details on the assimp website. Though the website might also be wrong or out of date.

I linked with `-lassimp.dll` and that allowed me to build my program. However it crashed upon start-up - the error that appeared immediately at start-up was

> Program has stopped working

(There was no additional info.) I guessed that this was a dll problem—which was odd because I had (tried) to build the static libraries through cMake. I copied `assimp32.dll` into my executable folder. This time, the program wouldn't crash but the screen would be blank. I'm guessing that there was something wrong with the library I build that was causing it to link incorrectly.

At this point, I deleted everything to try a fresh start. I tried to follow this article:

1. I downloaded assimp 3.1.1 and boost 1.57 and extracted them.
2. I opened `cmd`, changed to the boost root directory and ran

```
bootstrap.bat mingw

```
3. I then ran

```
b2 --build-dir="C:/Libraries/boost/" variant=release link=static address-model=32 toolset=gcc

```

The result of this was

```
598 targets updates, 3 targets skipped, 2 targets failed.

```

I now have a folder `C:\Libraries\boost\boost\bin.v2` with two folders `libs` and `standalone`, but I'm not certain what my `BOOST_ROOT` directory is anymore.
4. I opened cMake, selected the assimp folder I had extracted, and configured the following:

```
BOOST_ROOT = "C:/Libraries/boost/boost/"
ASSIMP_BUILD_STATIC_LIB = TRUE
ASSIMP_BUILD_TESTS = FALSE
ASSIMP_ENABLE_BOOST_WORKAROUND = FALSE
BUILD_SHARED_LIBS = FALSE

```
5. I then pressed `configure` and got the error that the boost libraries were not found.

I'm only guessing what these cMake settings do, as I can't find any documentation for assimp. I'd like to build some version of assimp that I can then link to and use in a simple test program. At some point I will go back and build the shared libraries, but first I just want to get something working and understand how to do it again.

Can someone see what has gone wrong?

# Answer
> 1 votes
I don't know how to exactly configure Assimp to build it with MinGW, but I have successfully build this library (as static lib) from source code of the OpenGL Tutorial's examples. You can use it as well. Just download the source code (I was using exactly this version) and do standard CMake build:

```
mkdir build
cd build
cmake -G "MinGW Makefiles" ../
# or
# cmake -G "MSYS Makefiles" ../
make

```

If compilation will succeed you will have generated:

> build/external/assimp-3.0.1270/code/libassimp.a

You could also inspect CMake files of the Assimp libarary to see how it is configured.

# Answer
> 1 votes
Try turning off Boost: http://assimp.sourceforge.net/FAQ.html

ENABLE\_BOOST\_WORKAROUND = ON

As explained there its not really required, and its big. When we build Boost for Qt3D 1.0 we didn't use Boost because of compile issues.

---
Tags: opengl, assimp, mingw
---


# Question
Title: applyForce as long as display is pressed
In my project I have my main character body. I want it to move down on the y-axis as long as the screen is pressed. I tried it with

```
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
        jetski.applyForce(new Vector2(0,-1000), jetski.getWorldCenter(), true);
        return true;
    }

```

but that does it only once.

# Answer
Well for one this is in the touchUp method, which is called once when the screen is no longer being touched. A good way to do it would be to create a boolean "touchDown" that is accessible to the whole class and turn it to true in the touchDown method, and false in the touchUp method. Then you would apply the force to your jet ski while touchDown is true.
> 1 votes

# Answer
Currently developing a mobile game myself, using Box2D, I have no libgdx experience but for touch input on Android you can acquire a tap, a persistent touch, and a release!

```
public void gameControls(final RelativeLayout gameBackground)
    {
        // Touch input.
        // Set up the touch listener for touch input on the screen.
        // Use the whatever background you are using for displaying the game.
        // In my case, I use Relative background.
        gameBackground.setOnTouchListener(new View.OnTouchListener()
        {
            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                int eventAction = event.getAction();

                switch (eventAction)
                {
                    // If the player touches the screen.
                    case MotionEvent.ACTION_DOWN:
                    {
                        //
                        // Whatever you want to happen on a TAP.
                        //

                        break;
                    }

                    // If the player holds down on the screen.
                    // The player can move the touch around while holding down.
                    case MotionEvent.ACTION_MOVE:
                    {
                        //
                        // Whatever you want to happen on a HOLD.
                        //

                        break;
                    }

                    // If the player releases the screen.
                    case MotionEvent.ACTION_UP:
                    {
                        //
                        // Whatever you want to happen on a RELEASE.
                        //

                        break;
                    }

                    // If none of the above cases are met.
                    default:
                    {
                        //
                        // Whatever you want to happen if none of the above are met, possibly nothing?
                        //

                        break;
                    }
                }
            }

```

Hope this helps! Don't hesitate to contact me/comment on this if you need any clarification or any more help.
> 0 votes

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


# Question
Title: Is it possible in Unity to Flip a 2D Sprite Without Flipping the Object it is Assigned to?
I 'built' (followed a tutorial) on a collision detection system, and when I flip the object to go left and right the collision messes up. So I have three options; find a way to modify the collision detection, have sprites for all animations for left and right or to flip the sprite but no the object.

if anyone has used RaycastHit2D, and has figured out a way to do it correctly, that would also be great.

# Answer
> 3 votes
You can attach the sprite to the child of the main game object which handles the collision detection logic. Whenever you want to flip the sprite just do it on the child object leaving the main object as it is. This way you can achieve your desired result :)

---
Tags: unity, 2d, collision-detection, sprites, raycasting
---


title: Using gl3w and Win32 api, without glut

text:
# Question
Title: Using gl3w and Win32 api, without glut
I'm still a beginner, the example on skaslev's site require us to use glut as an interface to create a window.

For some reason, I'm required to create a window purely with Win32 api, but I am not sure of how to integrate it together with gl3w.c

Is there a guide or tutorial on how to do that? I've been searching for hours, seems out of luck :(

# Answer
https://www.opengl.org/wiki/Creating\_an\_OpenGL\_Context\_(WGL)

After some research, this is where I learnt how to use gl3w without glut.
> 1 votes

---
Tags: opengl, win32
---