title: 2D particles with a perspective camera?

text:
# Question
Title: 2D particles with a perspective camera?
I'm working on a 2D pixel art Unity game. I have multiple layers of scrolling so I need to use a perspective camera, the problem is though that it seems to mess up using particles as when the screen scrolls the particles move in perspective, when I need them to stay just in the x and y. Is there way to achieve this? I don't particularly want to go through every particle in real time and zero out their Z value, but maybe that's the only way?

# Answer
There are three main approaches you can try:

**1. Modify your particle emitter settings:**

**Ensure the particles are spawned at the same Z position**. In Unity, this will be in the Shape section of the particle system inspector. For a sphere, hemisphere, or cone, set the radius to zero. For a box, set the Z extent to zero. If using a mesh as the emission surface, choose a flat mesh.

**Ensure the particles do not stray from the Z plane they start in**. In Unity you can do this with the "Limit Velocity over Lifetime" section. Check the "Separate Axis" box, and set the Z velocity limit to 0 and the space to World. Set the X and Y limits generously high (greater than or equal to your maximum speed) so that you don't slow the particles in the directions you want preserved. Watch out when using forces or collisions with the particles, as these might bump them out of plane.

**2. Use a shader to flatten particles during rendering:**

**Write a custom vertex & fragment shader for your particles.** Create a material using this shader and assign it in the Renderer section of the particle system inspector. In the vertex shader, set the z-coordinate of each vertex to some fixed value (either a constant or a shader parameter) before multiplying it by the projection matrix. (There are plenty of sources that explain how to write vertex shaders for Unity, so I won't clutter this answer with every step)

Note that, as far as I can tell, Unity pre-transforms particle vertices into camera space before submitting them to the GPU, so the z-value you use is relative to the camera. This may be a platform-specific batching behaviour, or dependent on quality settings, so be sure to test in your intended output format to double-check that it behaves as expected.

**3. Render your particles (alone) with an orthographic camera.**

**Put your particles into their own layer. Set your main (perspective) camera to ignore this layer.** Create a second camera, parented to your main camera. This one should render after the main camera, see only the particles layer, perform no clearing, and be set to Orthographic. Adjust its size so that the particles line up correctly. If your camera ever gets closer or further from the scene, you'll need to adjust the orthographic camera's size to match. (This will only work if all your particle sources sit in a single plane - otherwise the particles may be offset from their source when the source parallaxes and the particles don't)

Of these options, number 1 (emitter settings) is quickest to set up, and 2 (custom shader) is the most robust/flexible. I'd only recommend 3 (separate camera) if you need more flexible emission options than 1 allows, but aren't comfortable writing shaders (or are targeting a platform that lacks programmable vertex shaders)
> 1 votes

---
Tags: unity
---


title: How To calculate camera boundaries

text:
# Question
Title: How To calculate camera boundaries
Is it possible to calculate the exact camera bounds? By this I mean the white lines that represent the camera area e.g the lines in the picture:

I'm using Camera.main.screenToWolrdCoordinates to convert screen coordinates to world coordinates because I want to position the player exactly on that white line that the camera represents:

But when I calculate the boundaries using Camera.main.screenToWolrdCoordinates I get this:

The players legs are outside of that lower camera bound on y axis, it will also happen on x axis when I strict the players movement by using the value that I got from Camera.main.screenToWolrdCoordinates , I also have bouncing balls in my game that I want to strict by the same boundaries. So my question is how can I calculate camera bounds exactly by this I mean again these white lines that represent the camera view, I hope that my question is clear enought. Just to make it more clear, when I calculate the bounds using Camera.main.screenToWolrdCoordinates I just assign the Y value that I got from that calculation to the Y position of the player.

# Answer
Getting the lower boundary of the Camera in world space is easy with this little extension method:

```
public static float LowerBound(this Camera parent)
{
    return parent.transform.position.y - parent.orthographicSize;
}

```

I could give some more flexible methods, but this is simple and does exactly what you need.
> 0 votes

---
Tags: unity, 2d, camera
---


# Question
Title: How to do monster AI movement and attacks server side?
I have my web based rpg game already created. Inventory management, equipment system, character stats, skill tree, and etc. It's almost complete.

For the game world, I am creating a top-down rpg character movement and combat. With point and click. You click on a part of the map (in this case, it's a image, and your character .png image transitions to that spot). It's with Javascript and PHP. I'm using a PHP Websocket server. I have it where players can only move up to 200 pixels per each click. Each click is essentially a packet being sent to my gameserver. Then the gameserver validates if it's a valid input (1235x1235) format, and spits it out to other players in that specific game. (So it's a consistent world/map). This works perfect.

My question is: If I want to incorporate a monster that has AI and starts to attack the character... I can do that with javascript easily with setInterval or setTimeout functions (to make the mob move and then attack the character). But how do I do that serverside? Because a user could just press F12 and edit the javascript to stop the mob from attacking. But, I need the mob to attack the player every xxx milliseconds serverside as well. How is this done with PHP? I feel like I need some type of heartbeat going on where it's a constant check between client and server every xxx seconds? I might be going off on the deep end and I'll stop talking lol. But I hope you get the jist of it. Any ideas are greatly appreciated.

Another thought: Think of Diablo 2 or Path of Exile, and using a hack that just stops mobs from moving towards your character and attacking it. Is that just an illusion? And the "auto attacking" is done serverside regardless if you've stopped that mob on the client, right? If so, how to accomplisgh this with a PHP Websocket server, and some JS? I'm not looking for code, just an application theory or design process would help! :)

P.S. It's either I go this route, or the game becomes a simple real time strategy pokemon style combat. Which I really, really don't want...

# Answer
check out http://browserquest.mozilla.org/ as a reference model. it uses node for the backend.

They use setTimeout on server side classes e.g character, mob, player. Messages are sent client-server (move, attack etc) and server-client (move,spawn,damage etc). There are client and server side versions of classes for major entities in the game world. Numeric constants are used to keep messages light.

Source: https://github.com/mozilla/BrowserQuest
> 1 votes

---
Tags: javascript, php, websocket
---


# Question
Title: How do I figure out if a point is infront or behind my vehicle?
I need to figure out whether a point is infront or behind my vehicle.

I have the vector of it's position, forward direction.

So far I have tried finding the vector perpendicular to its forward direction and then calculating what side of the line it is positioned on.

This works fine at first. But then I realised it is only calculating around the origin.

```
bool Car::isInfront(ngl::Vec2 _pos)
{
//http://stackoverflow.com/questions/1243614/how-do-i-calculate-the-normal-vector-of-a-line-segment

//if we define dx=x2-x1 and dy=y2-y1, then the normals are (-dy, dx) and (dy, -dx).

//create vector per to the direction of travel.
ngl::Vec2 fwdVec = m_carPhysics->getForwardVec2();
ngl::Vec2 pos = m_carPhysics->getPosVec2();

ngl::Vec2 dir = pos + fwdVec;

float dx = dir.m_x - pos.m_x;
float dy = dir.m_y - pos.m_y;

ngl::Vec2 v1(-dy, dx);
ngl::Vec2 v2(dy, -dx);

ngl::Vec2 perp = (v1) - (v2);

int turn = getLeftOrRight(_pos, perp);

if(turn == LEFT)
{
    return true;
}
else
{
    return false;
}

int Car::getLeftOrRight(ngl::Vec2 _dir, ngl::Vec2 _fwd)
{
//http://gamedev.stackexchange.com/questions/34536/calculating-angle-between-two-vectors-to-steer-towards-a-target
//cross product;
float val = (_dir.m_x * _fwd.m_y) - (_dir.m_y * _fwd.m_x);

if(val > 0)
{
    return LEFT;
}
else
{
    return RIGHT;
}

```

}

# Answer
The idea is right, the execution however is chaotic.
First of all "So far I have tried finding the vector perpendicular to its forward direction", you already seem to know the trick - swaping x,y and inverting one axis, but why you apply it to some random products of calculations?

```
bool Car::isInfront(ngl::Vec2 _pos)
{
ngl::Vec2 fwdVec = m_carPhysics->getForwardVec2();
ngl::Vec2 perp = vec2(-fwdVec.y, fwdVec.x);

```

Second: "But then I realised it is only calculating around the origin.", there is nothing easier than moving your problem to origin - by using relative position to your car(just substract its position).

```
return getLeftOrRight(_pos - m_carPhysics->getPosVec2(), perp);
}

```

...and that is all code you need. Judging from comments you originally wanted 45deg slice, and you were probably on the right track there too - just be aware it might require chcecking against both vectors `v1(-fwd.y,fwd.x)` and `v2(fwd.y,-fwd.x)` (if you think about it, point in 45 slice must be right of forward-left bound AND left of forward-right boundary).
> 0 votes

# Answer
If two vectors point in the same direction, then their dot product is positive. If the point in opposite directions, there dot product is negative. If they are perpendicular, the dot product is zero. All we need to do is compare a vector from the car to the point and the car's forward vector:

```
bool Car::isInfront(ngl::Vec2 _pos)
{
  ngl::Vec2 fwdVec = m_carPhysics->getForwardVec2();
  ngl::Vec2 pos = m_carPhysics->getPosVec2();
  ngl::Vec2 dir = _pos - pos;
  return (dir.x * fwdVec.x + dir.y * fwdVec.y) >= 0; // dot product
}

```
> 1 votes

# Answer
In simple terms, there are two steps you'll need to take:

1. Calculate the angle between the vehicle's position and the point's position.
2. Compare that angle to the angle the vehicle is facing (the angle of the vehicle's forward vector).

More specifically...

Step 1 is easy: subtract one vector from the other, and use a trig function (often called something like "atan" or "atan2" in most programming languages) to turn that new vector into an angle.

For step 2, there are a couple of ways to approach this. The simplest would just be to subtract one angle from the other, and take the absolute value of it (example: abs(60 degrees - 90 degrees) = 30 degrees), and then check whether it's under some threshold you define. A threshold of 45 degrees might be a good starting point. A higher threshold will be more generous, while a low threshold will require the vehicle to be facing directly toward the point.
> -1 votes

# Answer
I get a simple geometry trick that will solve you problem. You actually have the position and the direction of the vehicle. So, with that information you can construct a plane. If vector position

```
(Px,Py,Pz)

```

and forward direction is

```
(Dx,Dy,Dz)

```

and the object´s position to check is

```
(Ox,Oy,Oz)

```

well, you plane's formula is:

```
Dx*(Ox - Px) + Dy*(Oy - Py) + Dz*(Oz - Pz) = P

```

If P is positive, the object is in front. If P is equal to zero, your vehicle and the object are in the same position. If P is negative, the object is behind. So your code looks like:

```
bool Car::isInfront(ngl::Vec2 _pos)
{
    ngl::Vec2 fwd = m_carPhysics->getForwardVec2();
    ngl::Vec2 pos = m_carPhysics->getPosVec2();
    return fwd.x*(_pos.x - pos.x) + fwd.y*(_pos.y - pos.y) + fwd.z*(_pos.z - pos.z) > 0;
}

```
> -1 votes

---
Tags: physics, vector, vehicle
---


# Question
Title: Data model design using Core Data and Spritekit
I have a entity called Item, and every item can have two or three bonuses...

What would be a good model design in this situation. I can think of something like:

To have many optional attributes inside Item entity i.e.

(Item)

* fire\_rate\_bonus
* energy\_bonus
* damage\_bonus
* health\_bonus
* some\_other\_bonus

And then when creating an item, I would set the values for appropriate bonuses and rest of attributes will be set to null.

I find that this approach solving my problem, but is there some other/better/efficient way? If you need more info about this, I will update my question. Thanks in advance...

EDIT:

Doing like above in my case will do the job, because I don't have much possible bonuses. But let's say there is a lot of possible bonuses, and an item can have only few bonuses. Then I think this method could be overkill because:

Item entity will have too much unused attributes.

What I can think of (I know that Core Data is not relational database system, but I like to think in relational way) is to make new entity called Bonus with relationship between Item entity (one Item can have many bonuses) with attributes :

bonus\_name, bonus\_modifier or something like that.

And then when creating an Item just assign appropriate bonuses to it. I hope this make some sense.

# Answer
> 1 votes
I can see you going about this two ways without changing too much of your core data model.

Kind of a lazy way to do it if you know that there will be no more than 3 bonuses per item.

* bonus\_1\_type (NSInteger)
* bonus\_1\_amount (float)
* bonus\_2\_type
* bonus\_2\_amount
* bonus\_3\_type
* bonus\_3\_amount

This would give you the flexibility to use an Enum for type and float for amount.

The other way is to create a BonusEntity as you were talking about in your edit with a one to many relationship.

ItemEntity

* bonuses one to many BonusEntity

BonusEntity

* bonus\_type (NSInteger)
* bonus\_amount (float)

**EDIT**

Some additional thoughts. Keep in mind I am making some assumptions as to what a bonus actually is.

Lets say you have bonus types of FIRE\_RATE, ENERGY, DAMAGE, HEALTH.

So adding a bonus would be.

bonus\_type FIRE\_RATE bonus\_amount .25 (this would be an increase rate of .25)

bonus\_type HEALTH bonus\_amount 50 (this would give you 50 extra health)

Now keep in mind this is best if you are going to subtract from these values. Take HEALTH for example. You get hit and that item now only has a bonus of 25 left.

Now if these are more or less static you can do something like this.

Bonus types HEALTH\_LEVEL\_ONE, HEALTH\_LEVEL\_TWO, HEALTH\_LEVEL\_THREE.

Knowing that HEALTH\_LEVEL\_ONE will always give you 25 extra, HEALTH\_LEVEL\_TWO will give you 50 extra etc. Now you only need to manage bonus\_type in core data and code will determine the amount.

Hopefully that helps.

# Answer
> 1 votes
That is a fine way to do it. Alternatives would be

* A field on the item specifying which attribute the bonus applies to, with a modifier ie

\[{"fire\_rate", 5}, {"health", 10}\]
* Each item could have a pair of delegates so you can make changes programatically. One applies the item's attributes, and optionally, the other removes them (like for equipment)

However, these two options are probably overkill for what you're going. Keeping with the YAGNI principle I strongly suggest sticking with specific modifiers like you've stated.

---
Tags: architecture, ios, models, spritekit, entity
---


title: Compiled vs Scripting Plugin System

text:
# Question
Title: Compiled vs Scripting Plugin System
I'm making a very simple game that revolves mostly around user-created mods. So far I've seen most games using Lua or something like Lua to enable user scripting, but recently I've seen people using dynamically loaded, AOT'd libraries to increase performance. When would I use one over the other?

The only advantages I can find are that scripting languages are easier to approach by non-programmers (particularly Lua), or that dynamic loading will improve performance and will be more lightweight (no need for an embedded interpreter).

# Answer
Compiled: Code gets converted into a binary format that can run directly on hardware, or through a VM. (Virtual Machine) Executing the compiled code is specific to the binary format, and if it's not for a VM, then it can only run on specific hardware. (eg. a dll compiled for x86\_64 will not run on an ARM processor. You would have to recompile the code to do that, and possibly modify it.

Interpreted: Code that gets executed from text. This avoids binary conversion, so it is cross-architecture (not dependent on any hardware), offers many debugging features unavailable to compiled code, and can (with a little extra effort) be edited in real-time (the script can be edited while the code is running, and have the code-changes represented immediately.)

Compiled:

* Fast
* Hardware dependent (x86, x86\_64, Arm, PowerPC, etc)
* The avarage user will be lost entirely

VM (Virtual Machine):

* Faster than interpreted
* Slower than compiled
* Hard to implement
* Hardware independent (it can run anywhere your game can)
* Not commonly available. (Java and .net (C#) are the only common languages that I know of. And .net is only cross-platform because of Mono.)

Interpreted:

* Slow
* Easy to use
* Hardware independent (it can run anywhere your game can)

---

As pointed out by akaltar, none of these are particularly slow. If your application is really performance intensive, then it might come into play. That would be your primary reason for using a compiled plugin interface. For basically any other reason, especially if you want your game to easily go across many platforms, you would want a VM or scripting language. The choice between those being dependent on what features you need.

If you want to see some benchmarks, Debian.org allows you to compare every language mentioned here and then some. You can select your two languages at the top and scroll through data and measurements on how fast the equivalent programs executed in each language, along with how much memory they used, and how CPU intensive they where.

Other Notes: Creating your own scripting/VM language would not be ideal. If your aiming for something that many people will be using, you would have to create and maintain a specification for that language, and handling every user problem as they learned a language never before used. Something like Lua is well documented, and many people already know how to use it.
> 1 votes

---
Tags: scripting, plugin
---


# Question
Title: How to make a proper cache on user computer?
Currently when launching the client of the game, it connects to the server and loads all the cachedata **in a normal form (= folders, .txt files and .png files).** However I don't like that the players can edit the images very easily and read all the .txt files etc.

* How could I deny user access to the cache or hide it? (in java)
* Is there anyway to save .png images in a text form and load them into images using somekind of decrypt system?
* How's that kind of stuff normally done?

# Answer
> 0 votes
As the game executable has to be able to decode the data to use it, there is no protection from an user determining the decryption key and doing the same to read the data.

You can get limited protection from modifying files by encrypting them with a private key server-side, as the user will not be able to encrypt new data in a manner that is decryptable by the public key present in the executable. This of course does not protect against the user modifying the decryption key in the executable and re-encrypting all the data with a private key of their own.

If this is a multiplayer game, there's no end to the amount of attempted countermeasures you can do, and there's a whole industry around mitigating them.

If this is a single player game, let the user do what they want. Moddability tends to be a net win in publicity and is likely to extend game longevity way past what you intend it to.

# Answer
> 0 votes
What do you want to prevent? Editing or reading?

Preventing reading is impossible. Your client has to be able to read and display the images and text files to allow playing the game, so everything someone would need to crack any protection you add would *always* have to be included in your client software.

If you want to make it less tempting for a user to just go in the files and read the text or look at the images and get the solution to a riddle too easily, use a simple transformation on your text and images, like XORing each byte with a fixed number or Rot13. But since users can go online and read walkthroughs, why bother?

If you want to prevent editing (why? You'll prevent modders from modding your game, making it popular, and becoming already-educated future employees or collaborators), use a checksum or a signature. That will let you detect that a file has been modified and reject (or re-download) it. Checksums are not that hard to figure out. Signatures are pretty much impossible to figure out (OpenSSL will let you sign stuff). For signatures, there is a "private" key you use to sign the code, and a different "public" key your client uses to, but since a user can edit the client software on their hard disk, they could still replace the public key in the client with their own public key and sign their changed version that way.

So in the end, if it's on the user's computer, the user can edit it. The only way to avoid the client from editing the game to make it easier is to not transfer the data to the client's machine until they actually need it, and to cache as little as possible.

Also, if your game is a network game, you need to be even more paranoid and only send user actions to the server, not results of the actions, because anyone can hack the client to transmit "I just killed 1000 monsters", while it's harder to send messages that say "step forward, step forward, step forward, strike" to kill a monster.

---
Tags: java, data-structure, databases, loading, file-format
---


# Question
Title: Game mechanic player following path looks very roughly
I want my player entity to follow a path, which works, but it looks very roughly. Like it would stuck everytime.

```
    bool arrivedX = false;
    bool arrivedY = false;

    float speed = 0.06f;

    if(bestway.empty()) {
        //arrived
    } else {

        if(entity->x < bestway.front()->x * gridSize) {
            entity->x += speed * machine->getDeltaTime();
        } else if(entity->x > bestway.front()->x * gridSize) {
            entity->x -= speed * machine->getDeltaTime();
        } else {
            arrivedX = true;
        }

        if(entity->y < bestway.front()->y * gridSize) {
            entity->y += speed * machine->getDeltaTime();
        } else if(entity->y > bestway.front()->y * gridSize) {
            entity->y -= speed * machine->getDeltaTime();
        } else {
            arrivedY = true;
        }

        if(arrivedX && arrivedY) {
            bestway.pop_front();
        }
    }

```

the vector contains grid coords from 0 to WIDTH or HEIGHT / gridSize. And the entity has pixels coords. I have tried already:

```
entity->x / gridSize < bestway.front()->x

```

which runs smoothly, but when it goes up or right it will omit one grid tile. I think it is because of when the player is at pixel 19 and the gridSize is 20 it would calculate 0 . 19/20 = 0... I tried to ceil and floor it, but it didn't work out. Hope you guys can help me.

edit:

```
        int ix = int( x + 0.5f );
        int iy = int( y + 0.5f );

        if(ix < bestway.front()->x * gridSize) {
            x += speed * machine->getDeltaTime();
        } else if(ix > bestway.front()->x * gridSize) {
            x -= speed * machine->getDeltaTime();
        } else {
            arrivedX = true;
        }

```

Video

http://youtu.be/-DugHbMdODg

# Answer
> 1 votes
I believe your error arises from rounding errors.

I believe the problem could be solved by using `float` for pixel-coordinate storage. This way you will always get the exact increment needed for the given delta time, which is usually very small and thus the resulting per update increment is less than 1, and truncated to 0.

Don't forget to use proper rounding when converting back for rendering or comparison. For rendering I would use: `int ix = (int)( entity->x + 0.5 )` Which will yield 'proper' rounding: up from 0.5 and down with anything less.

---

Edit:

From the video it seems you are overshooting the position you are aiming for. There are three ways to solve this:

* After moving, check if you overshot and correct for it:

```
entity->x += speed * dt;
if( entity->x > movelocation->x * gridSize )
    entity->x = movelocation->x * gridSize;

```
* Lower the speed you are moving with.
* Use a higher update frequency.

The most solid option seems to be checking for overshoot and correcting. Note: The simple code I provided doesn't account for the movement speed lost when arriving at each tile.

---
Tags: c++, movement, game-mechanics, path-finding
---


title: Move vehicle towards the cursor

text:
# Question
Title: Move vehicle towards the cursor
I am making a game similar to Asteroids. The ship always points toward the mouse cursor. I want to know how to move towards the mouse so if I press `w` I will drive towards the mouse and if I press `s` I will move away from the mouse. How can I do this? Here is my code so far:

```
public class player {

    public int x,y;
    private Image img;

    float xDistance;
    float yDistance;
    double rotationAngle;

    public player(int x,int y){
        this.x = x;
        this.y = y;
    }

    public void tick(){
         xDistance = Comp.mx - x;
         yDistance = Comp.my - y;
         rotationAngle = Math.toDegrees(Math.atan2(yDistance, xDistance));
         handleinput();
    }

    public void render(Graphics g){
        Graphics2D g2 = (Graphics2D) g;

        RenderingHints rh = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
        g2.setRenderingHints(rh);

        ImageIcon i2 = new ImageIcon("res/player.png");
        img = i2.getImage();

        AffineTransform at = AffineTransform.getTranslateInstance(x, y);
        at.rotate(Math.toRadians(rotationAngle) ,20,20);

        g2.drawImage(img, at, null);

    }

    public void handleinput(){
        if(Keys.isPressed(Keys.w)){

        }
    }

}

```

# Answer
> 1 votes
There are a few steps that you need to follow to accomplish this goal, they are as follows:

* Get the distance that the player has moved (i.e. the amount of time the w key has been pressed times some sort of speed multiplier)
* Calculate the distance along the x- & y-axis that the ship should be displaced using the trigonometric functions sine and cosine
* Move the ship relative to these amounts

---

The diagram below shows how the vertical and horizontal displacements relate to the distance the player moved in the asteroids game.

Suppose that your cursor makes an angle that is 30 degrees, or π/6 radians, relative to the x-axis and the ship moves a total of 15 pixels toward its target. The horizontal displacement of the ship is then **`15×cos(π/6)=12.99≈13 pixels`** and the vertical displacement is **`15×sin(π/6)=7.5≈8 pixels`**.

Hope that helps, and sorry for the lack of code. I'm not that familiar with the native Java libraries for drawing graphics.

---
Tags: java, movement, mouse
---


# Question
Title: Store metadata for tile in Tiled Map Editor
In my tilemap-based game, I need to associate lights with light switches, buttons with doors etc. I am using the Tiled map editor (mapeditor.org), but I have yet to find a way to store these associaltion. My idea is to store a number with each tile, so I can have groups of tiles that interact with each other.

Is there a way to store custom data with each tile in the Tiled map editor? Just to be clear: I don't want to store custom data with each tile type, but with individual instances of one tile type.

# Answer
> 1 votes
You can do this by using an Object Layer:

* You can use Tile Objects to place your switches and doors, so that you can set custom properties on them to define which switch is connected to which door.
* If you still want to use a Tile Layer for placing the switches and doors, then you could place plain rectangular objects on the Object Layer and match them to the tiles by their location.

In both cases, you could use the recently added unique object IDs to refer to the other objects, or you can set names on them and use that as a reference, which could be easier to understand.

---
Tags: tilemap, tiled
---


# Question
Title: State Machine class vs function pointers
What do you guys recommend to use? A State Machine with function pointers or classes?

Or, in which case one would be better than the other one?

At work we use the state machine with function pointers only and I've never tried to use one with classes before.

# Answer
The main difference is that with classes you can store information that only applies to that state in the class itself, whereas with function pointers you need to store it "somewhere else", hopefully in a closure or possibly in the main object using an associative array/map/dictionary.

In a programming language with closure support the difference is much smaller and in the end your choice might come down to which looks more natural in your language of choice or which is more efficient during execution.

For instance in C++, Java and C# I would use classes, it is the natural fit. You should tag your question with which programming language you are talking about if you want more specific information.
> 1 votes

# Answer
Both are good approaches. If you are working on the logic of a simple NPC character, and have 2 states, Idle and OutOfScene. With a State Machine class that update a state enum, know the state of the character is too simple. And in the "Global Loop" of the character logic, your only task is checks the machine states. But if the character is a little more complex, for example, when we are close of them begins a animation. Now our logic have a new state called "speaking". So, It's very convenient listen when happens character change of state. So, If you store a function pointer to a function called "doSpeakAnimation", when the character change to the state "speaking", just call to "doSpeakAnimation" and your code will be more elegant. My conclusion is that. The right approach depends of your necessity.
> 0 votes

---
Tags: c++, state, fsm
---


# Question
Title: TTF fonts are being converted to image in CPU or GPU?
Once I use a TTF font, when they are being converted to images to be rendered? Does CPU or GPU do the conversion? How heavy is that operation?

# Answer
> 2 votes
In many game engines you would create a texture map for your fonts, rendering the TTF font into a character sheet that is used in the game itself, but it is quite possible to convert the TTF bezier curves into geometry that can be rendered directly on the GPU in a very efficient way.

In the end, the performance difference is minimal and unless you are planning on rendering your entire game with text (like in the scene towards the end of the first Matrix film) you won't be able to tell the difference in a real game.

---
Tags: gpu, fonts, ttf, cpu
---


# Question
Title: Calculating shadowmap coordinates for cubemap in shading pass?
I'm trying to implement shadow mapping with cube maps. I believe I've done the first stage by filling the cube map, but for the final shading pass I am unsure how to exactly calculate the cubemap coordinates. Any pointers?

# Answer
> 1 votes
To use a cube map for shadows you need to recreate the world position of the pixel you are rendering and from that get the normal that points at that world position from the light source, now you can calculate the distance of your pixel from the light source as well as check the cube map for the distance to the first shadow casting object.

Vertex shader needs to send along the z and w components of the vertices so you can perform the unprojection in the fragment shader

```
output.position = mul(input.position, worldViewProjMatrix);
output.depth.xy = output.position.zw;

```

Then you can combine these values with the inverse projection matrix in the pixel shader to recreate the world position of each pixel:

```
float4 projectedPos = float3(input.position.xy, input.depth.x / input.depth.y, 1);
float4 worldPos = mul(projectedPos, invProjectionMatrix);
float4 lightDir = worldPos - lightPos

float4 normal = normalize(light2pixel);
float dist = distance(worldPos, lightPos);

float shadow = texture(shadowCubeMap, normal);

if (shadow > dist)
  // Perform lighting...

```

I haven't tested this code so there may be bugs and errors in it, but it should be enough to demonstrate the idea I hope (the unprojection of the pixel coordinate is identical to other type of shadow maps, the main difference is using the normal with the cube map instead of calculating the texture coordinate with projection).

# Answer
> 0 votes
Cube maps are using direction as their texture coordinates. A quote from the OpenGL wiki:

> The texture coordinates for cubemaps are 3D vector directions. These are conceptually directions from within the cube defined by the cubemap, pointing in a particular direction. The vectors do not have to be normalized.

You have to calculate the direction of the fragment is pointing at to get a cube map direction. You could use the vertex normals for that, or some other mechanism. In your case of shadows, I'm guessing (I've not actually done that yet myself, I am a learner too) you could get the direction from the camera to the fragment to get the correct depth texel, or at least something similar to that.

Read a tutorial about cube maps.

---
Tags: opengl, c++, shadow-mapping
---


title: Storing a block world

text:
# Question
Title: Storing a block world
I've gotten a basic Minecraft clone working (thanks to gamedev.stackexchange's help! ^\_^), but know I have no idea how to save the file.

Minecraft itself uses a naive list of block ids as far as I can tell, but there are three problems with this:

* There appears to be a 4096 block limit.
* My game uses strings to represent block ids, not integers.
* Extra data for blocks, like washing machines holding their state and contents.

Of course, (b) can be easily solved with a map generated at runtime, but that sounds really dirty. And Minecraft's solution to (c), NBT data, looks really quirky too.

How would I avoid these three problems when saving a Minecraftian world?

# Answer
> 0 votes
Creating a save file/format is not so difficult, essentially what you are doing is saving your memory structure to disk so that you later can read it and recreate the same memory structure. The main issue you need to consider is how to make sure that a world saved with an earlier version can be loaded by a later version.

To that end it is a good idea to save a version at the start of the file so that you can detect the file your loading to be old and use an older version of the loading code.

Another issue is to use a format that is fast to both save and load, seeing as you will continuously be both saving and loading them as the player moves around the world. The best way to ensure this is to do the least amount of work to convert the memory structure to the file structure and vice versa.

So if you have a 3 dimensional array for an area (chunk) of blocks then you want to write your header (with version number) then spit out the data for each block in your array in a specific order (increasing index order in the array is a good bet). Using a table at the end to store a position of a block and then extra data that needs to be loaded means you don't have to check every block in the chunk to see if it has more data stored when loading, you simply load all blocks in one go and then at the end you go over the special blocks and load their extra data.

As for minecraft, the reason they are restricted to 4096 id's is because they split a 16 bit integer into a 12 and a 4 bit number, the first is the block id, the second is the orientation of the block. If you wish you can save your id's as 32 bit numbers (for a total of 4 294 967 296 different blocks), that way you could create a new block every second and you would have to continue that pace for a bit over 136 years before you run out of numbers.

Using integers might speed things up, but there is no reason to look into that unless you start having performance issues.

# Answer
> 0 votes
> * here appears to be a 4096 block limit.

Use a larger bit size like an int for 2 billion blocks, Notch severely underestimated several things when first creating minecraft and we (Mojang devs and modders) are still paying for a lot of those decision.

> * My game uses strings to represent block ids, not integers.

Create a map and save it along with the world, that way if you ever add/remove blocks the old IDs remain valid. This is what minecraft does starting from 1.7.

> * Extra data for blocks, like washing machines holding their state and contents.

Minecraft uses some fixed length data for all blocks, which includes the numeric ID, metadata, and light level. Having this fixed length help a lot when reading it in.

You don't *need* to use NBT (it is essentially a binary json with more types) but I do suggest putting it in a fast lookup structure (HashMap) to get the additional data related to a set of coordinates fast.

---
Tags: voxels, minecraft-modding, file-format, savegame, game-state
---


# Question
Title: The camera in a 2D tile based side scroller is moving slower than the player
In my 2D tile based side scroller, I want a camera that scrolls in the x direction, but not in the y direction. The world is separated into three zones; one on the left and one on the right where the camera doesn't move, and one in the middle where the camera should move left and right and centered on the player.

The world is a 2D int array where each tile has it's own ID (number). The player's position is in pixel coordinates.

My problem is that when the player moves outside the left zone (and into the middle), the camera always move slower than the player, which means the player disappears of the screen. Since I calculate the camera's position from the player position when the player is in the middle zone, I don't understand why the camera isn't always centered around the player.

My code for calculating the camera's position and drawing the background is as follows (in C#):

```
int worldWidth = world.GetLength(0) * _TILE_WIDTH;
int resX = camera.Width / TILE_WIDTH;
int resY = camera.Height / TILE_HEIGHT;

Bitmap screenBmp = new Bitmap(camera.Width, camera.Height);
Graphics g = Graphics.FromImage(screenBmp);

// upper left corner of the camera in the world
Vector2D pCamera = new Vector2D(p.X + (p.PlayerSize.Width / 2) - (screenBmp.Width / 2), 0);

int oneMoreX_tile = 0;  // draw one more tile off the screen?

if (p.X + (p.PlayerSize.Width / 2) < 0 + screenBmp.Width / 2) // past the left zone
{
    pCamera.X = 0;
}
else if (p.X + (p.PlayerSize.Width / 2) >= worldWidth - screenBmp.Width / 2) // past the right zone
{
    pCamera.X = worldWidth - screenBmp.Width;
}
else  // between the zones
{
    oneMoreX_tile = 1;
}

int xOffset = (int)pCamera.X % TILE_WIDTH;
int yOffset = (int)pCamera.Y % TILE_HEIGHT;

int startX_tile = (int)pCamera.X / TILE_WIDTH;
int startY_tile = (int)pCamera.Y / TILE_HEIGHT;

for (int i = 0; i < resX + oneMoreX_tile; i++)
{
    for (int j = 0; j < resY; j++)
    {
        int tileValue = world[startX_tile + i, startY_tile + j];

        // tile coord in tileset
        int x = tileValue % tilesetWidth_tile;
        int y = tileValue / tilesetWidth_tile;

        // pixel coord in tileset (top left)
        int x_px = x * TILE_WIDTH;
        int y_px = y * TILE_HEIGHT;

        g.DrawImage(tileset,
            new Rectangle(i * TILE_WIDTH - xOffset, j * TILE_HEIGHT - yOffset, TILE_WIDTH, TILE_HEIGHT),
            new Rectangle(x_px, y_px, TILE_WIDTH, TILE_HEIGHT),
            GraphicsUnit.Pixel);
    }
}

```

This code runs every time the graphics timer ticks. (I'm using Windows Forms..) I have two timers set at the same interval; one graphics timer and one physics timer. The physics timer just updates the player's position.

Regardless of world length, the player always disappears of the screen at 640 pixels (which is also the width of the screen), and the camera's position is 336 pixels from the left. I have also tried with lower speeds with no success.

Please ask if there's anything more you need to know. Any help would be appreciated.

# Answer
> 0 votes
I figured out what the problem was. It was not a problem with the camera calculation, but rather with drawing the player.

The player's coordinates is in pixels in the works ( between 0 and world.GetLength(0) * tile\_width). So when I drew the player, I forgot to subtract the camera position so the player world stay inside the camera view.

This is what my code to draw the player looks like now:

```
g.DrawImage(p.PlayerSpriteCharSet,
            new RectangleF(p.X - (float)pCamera.X, p.Y - (float)pCamera.Y,     p.PlayerSize.Width, p.PlayerSize.Height),
            new Rectangle(new Point(tilesetX_px, tilesetY_px), p.PlayerSpriteSize),
            GraphicsUnit.Pixel);

```

---
Tags: c#, camera, side-scroller, tiles
---


title: missiles skip in collision detection

text:
# Question
Title: missiles skip in collision detection
I'm trying to work on spaceinvader. I have problem that missiles or the bullets skip frames due to its fast speed. I tried to use the previous position of the bullet in the collision check, but still, the collision does not work. it's pretty working on bullets with slow speed. Kindly see the attached video. https://www.youtube.com/watch?v=jOVc-HGNI9Q&feature=youtu.be

```
  void Bullet::Update(float dt)
{
    Position.y -= 0.50 * dt;

    Vel = (Position - prevPosition).GetNormalised();

    if (Position.y < 0)
    {
        IsDestroyed = true;
    }
    else
        IsDestroyed = false;

    prevPosition = Position;

}

```

and for collision check:

```
// if there is intersection
        if (IntersectsWith((*it)->BoundingRect, barrierRect))
        {

            // subtract (*it) bullet position from barrrier's rect
            int normX = (*it)->prevPosition.x + (*it)->Vel.x - barrierRect.x;
            int normY = (*it)->prevPosition.y + (*it)->Vel.y - barrierRect.y;

            // barrier image pixels
            uint32* ptr = (uint32*)pixels;
            // height of the barrier

            int pixelOffset = normY*51 + normX;
            unsigned int color = ptr[pixelOffset];
            // look up the color if its not black, it should be green
            if (color != 0xFF000000)
            {
                // delete the bullet
                Bullet *bullet = *it;
                it = ship->Bullets->erase(it);
                delete bullet;
                ship->Canfire = true;
                isCollision = true;

                // blast a circle around that bullet hit position
                int radius = 9;
                for (int y = -radius; y <= radius; y++)
                {
                    for (int x = -radius; x <= radius; x++)
                    {
                        if (x*x + y*y <= radius*radius)
                        {
                            int j = x + normX;
                            int i = y + normY;
                            int pixelOffset = i*51  + j;
                            ptr[pixelOffset] = 0xff000000;
                        }
                    }
                }

            }

```

# Answer
> 0 votes
Issues like this often come from the fact that the bullet gets through the target; frame A it's before and frame B it's passed it, and neither in frame A nor frame B you had a bounding box intersection.

A way to solve this is: in frame B, you extend your bullet's bounding box from the position it was in in frame A. This would encompass 'all the infinite positions the bullet have been in' during the 'frame transition'.

**Edit**:

As per request, here is a pseudocode sample. Note that it is assumed that everything is axis-aligned, that the origin is bottom left, and that bullets are going from 0 to infinite in the y-axis.

```
// Stuff to add to your main update
update()
  // When you update your bullet posisiton
  bullet.previousPosition = bullet.position
  bullet.position  = blaBlaBlaUpdatePosition()
  bullet.mositionBoundingBox =
    makeMotionBoundingBox(
      bullet.previousPosition,
      bullet.position,
      bullet.size )

// Take into considration the traveled distance between this frame and the
// previous frame
makeMotionBoundingBox( positionLast, positionNow, itemSize )
  rect = new rectangleBoundingBox
  rect.position = positionLast
  rect.size.x = itemSize.x
  rect.size.y = positionNow.y - positionLast.y + itemSize.y

isInMotionCollision( bullet, target )

  if ( bullet.mositionBoundingBox.intersect( target.boundingBox )
    return true;

  return false

```

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


# Question
Title: Elegantly simulating NPC movement in inactive areas
My AI is utility-driven in a similar pattern to The Sims, where all unique behavior is coded into interactable objects, and the only thing an NPC does is decide which object they wish to use, path to it, and activate it. This is deceptively powerful, as I can extend nearly any desired behavior by creating a novel object and shaping constraints leading to its selection.

The challenge I'm having with this approach is giving the illusion that NPCs are moving around when the player isn't nearby. The game runs a 24/7 clock and seeks to have each NPC go through the motions of maintaining a regular schedule: going to work, going to bed, and randomly doing weird things in their free time to preserve the illusion of unpredictability. This is implemented with a dict(float time, Appointment appointment), which acts as a global behavior queue and is called every time the in-game clock changes to teleport each AI who has an appointment to use an object to that object's position. This works well enough for prototyping other systems, but it isn't very convincing: you never see NPCs moving through the world, and when you're familiar with a few specific characters it becomes very obvious that they're teleporting around when you can't see them.

Is there a better way to simulate movement around a world with a large number of NPCs, or am I better off keeping my current queue-oriented behavior system and writing an entirely different system to fake movement? My optimal endpoint would be a system that can order NPCs to be at any location, at any time, and trust them to move there in a convincing way, but I worry I'm putting too much detail into a simulation that could fake the same behavior more convincingly with a simpler solution.

# Answer
Make a list of things a character would do at certain hours and be sure to have multiple activities at every time. Say at 08:00 they eat breakfast or shower and at 09:00 they commute to work or work from home. Now you keep also note how long a NPC would take to finish the task. You keep track of the last time the player was able to see the NPC. If the player returns within the time it would take to do the task you would make the NPC do the current task, but if the player returns after a couple of ingame hours you would teleport them to their new task or if it's a traveling task you would calculate the percentage of distance they covered and teleport them to that location.

The multiple task possibilities at a certain time will reduce the pattern the player will be able to see. To reduce the randomness multiple lists would be created that feature different tasks which are logical follow ups of the previous task.

---

Example: At the start of the day choose either list 1, 2 or 3.

List 1

07:00 - Wake up

07:02 - Go to Toilet / Drink a glass of water

07:05 - Drink a glass of water / Go to toilet

---

List 2

07:30 - Wake up

07:40 - Make breakfast / Watch a cat video

---

I trust in your ability to make list 3 yourself.
> 2 votes

---
Tags: c++, ai, simulations
---


title: How to move an object to a position?

text:
# Question
Title: How to move an object to a position?
I'm trying to move an object to the coordinates `48.7, 51.07, 102.8`, but it does not move. I did some test to make sure that "OnMouseDown" works, and it does, I think it could not be finding the object "upgradeone".

```
public class click1 : MonoBehaviour {
    GameObject Upgradeone;
    GameObject cube;

    // Use this for initialization
    void Start () {
        Upgradeone = GameObject.Find("upgradeone");
        cube = GameObject.Find ("Cube");
    }

    void OnMouseDown(){
        Upgradeone.transform.localScale = new Vector3(48.7f,51.07f,102.8f);
    }
}

```

# Answer
I'm certainly seeing some issues in the way you're using Unity and with the script you have.

You script to move the object should be attached to the object you want to move. This means you won't need to use `Find` to statically locate the object you want to move, it'll be the object the script is attached to. That means you can simply use the `this` keyword to access the object to be moved.

Further, you're setting the local scale of the object, not the position. You'll want to modify `this.transform.position` to adjust the position of the object in the game world.

Finally, you're only taking action in `OnMouseDown` this only triggers once when the object is clicked. If you want to move the object over time, you'll have to use the `Update` method. You can still use `OnMouseDown` to trigger the start of the movement.

As an example, this script will move the object to the coordinates when clicked:

```
using UnityEngine;
using System.Collections;

public class click1 : MonoBehaviour {

    public float speed = 1;
    public Vector3 target = new Vector3(48.7f,51.07f,102.8f);
    private bool moving = false;

    // Update is called once per frame
    void Update () {
        if(moving) {
            float step = speed * Time.deltaTime;
            transform.position = Vector3.MoveTowards(transform.position, target, step);
        }
    }

    void OnMouseDown(){
        moving = true;
    }
}

```

Or if you wanted it to be instantaneous and activated from a different object:

```
using UnityEngine;
using System.Collections;

public class click1 : MonoBehaviour {

    public GameObject objectToMove;
    public Vector3 target = new Vector3(48.7f,51.07f,102.8f);

    void OnMouseDown(){
        if(objectToMove != null) {
            objectToMove.transform.position = target;
        }
    }
}

```

Then you set `objectToMove` by dragging the object from the hierarchy into the inspector for your trigger object, specifically the `objectToMove` field of the `click1` script.

Or, you can set in the `Start` method with the `Find` method, but I'd recommend against it. Setting the `objectToMove` in the editor is a cleaner way of dealing with this and doesn't hard code strings into your scripts.
> 3 votes

# Answer
There are a couple ways to move an object in Unity:

* `obj.transform.Translate(theTranslationVector)`
* `obj.transform.position = newPosition`

In the code you are using, you set the object's `localscale`, which obviously won't move the object.
> 1 votes

# Answer
Your code sets transform.localScale but you want transform.localPosition
> 0 votes

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


title: How should i manage intro animation

text:
# Question
Title: How should i manage intro animation
never realized how the animation intro of a game is done, I've thought that perhaps you have all the images of each frame of the animation, or have a video made and make the load.

anyway, if it is made of any of these ways, What is the best way to do this?

# Answer
It used to be quite common to play pre-rendered video files as cutscenes. But now that 3d engines became way more powerful, many games do their cutscenes with the game engine itself by replaying a scripted sequence. Playing cutscenes with the game engine has the advantage that it is less a break of immersion and also allows limited interactivity and character customization. It is also usually much cheaper to do. But when the game engine isn't designed for this, it can look quite awkward compared to a rendered video. Also, with rendered videos you can use a much higher level of detail, because you don't have to worry about the players machine being unable to render it in real-time with a proper framerate.

There was also a short phase in the late 90s where it became fashionable to film cutscenes with real actors. But this soon fell out of favor because the actors just looked too different from the 3d models representing the same characters during the actual gameplay.

There is never a *best* way to do something. There is only the best way for *you* and *your project*.
> 0 votes

---
Tags: animation
---


# Question
Title: Spawning moving text make it disappear overtime
I am trying to display a text when I click the letter 'R'. When the text appears, it should slowly slide down on the y axis only, slowly disappear over 4 seconds and get disabled.

I am not able to find any clear guidance on the new UI. Most are just telling how to insert and move them on the Unity Editor and not able to find anything on scripting and the documentation doesn't seem to have a clear description focused on UI scripting either (or maybe I am just that bad at reading it).

The following script makes the Text appear when I press the letter 'R'. It does disappear after 4 seconds. But it doesn't move down the y-axis and I am not able to assign the alpha value to the text incrementally to make it disappear over the 4 seconds.

Have commented the errors encountered below. I am testing this class separately on a separate Project altogether so no other interference. The Script is attached to an Empty Object on the scene.

```
    using UnityEngine;
    using System.Collections;
    using UnityEngine.UI;

    public class TextScript : MonoBehaviour
    {
        public Text Text1;
        private float count;
        private float scrollDown, alpha, duration;

        void Start()
        {
            count = 0;
            scrollDown = 660;
            alpha = 4;
            duration = 1.5f;
            StartCoroutine(WaitAndPrint(2.0F));
        }

        void Update()
        {
            TextSpawn();
            KeyCount();
        }

        //spawn the Text on the screen when count is higher than 1
        //text should slowly move down on the y axis
        //same time its Color alpha should go down too and making it disappear and when alpha is zero, disable the text.
        void TextSpawn()
        {
            if (count >= 1)
            {
                Text1.enabled = true;
                Text1.color = Color.black;
                Text1.text = "Text 1 !";
            }

            if (alpha > 0)
            {
                //if I use the variable scrollDown instead of 660, the Text will not appear on screen

                Text1.transform.position = new Vector3(748, scrollDown, transform.position.z);

                //this line of code will make the Text jump in the Y axis to 1620 even before I press 'R'
                //scrollDown += 10f;

                alpha -= Time.deltaTime / duration;

                //trying to set value to alpha which is not accepted.
                //Text1.material.color.a = alpha;
            }
            else
            {
                Text1.enabled = false;
            }
        }

        //Using this to increment count and enable the Text
        void KeyCount()
        {
            if (Input.GetKeyDown(KeyCode.R))
            {
                count++;
            }
        }

        //Using this to find out the position of the text for testing
        IEnumerator WaitAndPrint(float waitTime)
        {
            yield return new WaitForSeconds(waitTime);
            Debug.Log(Text1.transform.position);
        }
    }

```

# Answer
Get a reference to RectTransform component instead of transform position. Just attach this script to your gameObject.

```
using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class TextMoveFade : MonoBehaviour {

    public float Speed = 10;
    public float FadeOutSpeed = 0.1f;
    public Vector3 MoveToPosition = new Vector3 (0, -10);
    public float distanceOffset = 1;
    public RectTransform RectTransform;
    public Text CustomText;

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

    IEnumerator MoveAndFade()
    {
        while (true) {
            RectTransform.position -= Vector3.up * Time.deltaTime * Speed;
            CustomText.color -= new Color(0,0,0,FadeOutSpeed);

            if(Vector3.Distance(MoveToPosition, RectTransform.position) < distanceOffset)
                break;

            yield return null;
        }
    }
}

```
> 1 votes

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


title: Unity .3ds file is purple

text:
# Question
Title: Unity .3ds file is purple
I imported a .3ds file from skethup and in the preview it shows it with the texture, but when I put it in the scene it shows it without the texture.

http://puu.sh/gyYSU/a09541420c.png

# Answer
> 0 votes
Export the SketchUp model as .fbx and select "Export two-sided faces" in the menu.

---
Tags: unity
---


title: XNA Stop movement when arrived

text:
# Question
Title: XNA Stop movement when arrived
I'm trying to stop movement when sprite arrive target position. But i couldn't handle it. Sprite still move and pass target position.

Here's the code that runs every update to move it.

```
    public override void Update(GameTime gameTime)
    {
        if (!IsNasted)
        {
            //Find the delta time
            float delta = (float)gameTime.ElapsedGameTime.TotalSeconds * 300;
            //Find the direction
            Vector2 direction = ConvertUnits.ToDisplayUnits(targetPos) -
                 ConvertUnits.ToDisplayUnits(body.Position);
            if (direction.Length() < delta)
            {
                body.Position = targetPos;
                if (minx == movements.Count - 1) minx = 0;
                else minx++;
                targetPos = ConvertUnits.ToSimUnits(movements[minx]);
            }
            else
            {
                direction.Normalize();
                //Move towards it
                currentPos = direction * delta;
                body.Position += ConvertUnits.ToSimUnits(currentPos);
            }
        }
        base.Update(gameTime);
    }

```

# Answer
> 0 votes
This is how I would do it:

```
Vector2 targetPos = new Vector2(600,100);//target location
float speed = 0.5f;

public override void Update(GameTime gameTime)
{
    //if the distance between the current position and the target position
    //is less than 10, then move it straight to the target position
    if(Vector2.Distance(targetPos, ConvertUnits.ToDisplaUnits(body.Position) < 10)
        body.Position = ConvertUnits.ToSimUnits(targetPos);
    else
    {
        //calculate velocity and move the body towards the target position
        Vector2 velocity = (targetPos - ConvertUnits.ToDisplayUnits(body.Position)).Normalize()
            * speed * gameTime.ElapsedGameTime.TotalMilliseconds;
        //you can use: body.Position += ConvertUnits.ToSimUnits(velocity);
        //or better use the LinearVelocity property, so that the collisions
        //will be detected faster
        body.LinearVelocity = ConvertUnits.ToSimUnits(velocity);
    }
    base.Update(gameTime);
}

```

You need to set a number like `10` I have set, so that the moving object won't stutter and move back and forth while trying to reach the target position. So for example if the distance between the current position and the target position is less than `10` you will just directly move it to the target position.

You need a big enough number so that it doesn't stutter, but a small enough number so that it doesn't look like your object just magically teleported to the target position. That number should basically be `(1/60)*1000*speed` (where 60 is your fps), or if that doesn't work (object stutters and never stops moving) then try `(1/60)*1000*speed + 0.5f`. It is basically `velocity.Length * speed` **but not quite**, because in the example above we calculate velocity according to the current fps (current time elapsed), but we need the "max" fps (`16.66666 * speed`). So `velocity.Length * speed` **would not work**, because if the device runs in lower fps, then there will be bugs.

---
Tags: xna
---


# Question
Title: Is sidescroller movement just offsetting the background?, MonoGame/XNA
When I make a sidescroller game and what to move my character do I just offset the background, or is there another better way?

# Answer
A sidescroller involves you having 2 background images. When one's position crosses the screen it goes behind the other one and it keeps looping. This involves using the Rectangle struct. Here's a video I have for your problem exactly.

https://www.youtube.com/watch?v=NZEzD0GvImg
> 1 votes

---
Tags: xna, movement, monogame, side-scroller
---


# Question
Title: How can I efficiently represent territories and their borders on a map like if it was a Risk board game?
I am exploring the idea of programming a territory control based RTS. These territories would be in 3D and I would like their colors to change when captured to represent the faction's color. I would also like if my borders be embossed to separate them more easily. Which brings me to my question. Is there a way to efficiently represent these territories to make them easy to modify and where I could track the borders efficiently and with precision?

For instance, lets say I have a map divided like the classic Risk map (ignore the continental colors):

How can I represent each territory in a way where I could easily modify its properties (color, shape and possibly borders)? Should I engrave the borders in lists of coordinates and draw my territories according to these lists? Should I draw the map in an editor like Photoshop and analyse it pixel by pixel through a code execution to create the actual 3D map? Should I design each piece in a 3D modeling program (which seems insanely time consuming) and import the models when I load my map? Or is there a simpler answer right under my nose that I haven't explored yet?

I'm not sure yet if I'll be using Java or C++ to code, but I know it will be one of these two with OpenGL as my graphics library.

I understand that my question might be confusing, so please do ask for me to explain if it is the case and I'll try to clear any question you might have the best I can.

# Answer
> 4 votes
GIS systems actually use polygons for this kind of information, where each "ring" is a list of coordinates, so you can take the same approach.

Once your borders are defined in a list of points, you can triangulate them, assign vertex colors, or even apply UV values in order to apply a texture. Then the same mechanics apply as with a 3D model.

Polygons are sometimes produced from maps using the marching squares algorithm to produce a polygon, but if you can start with coordinate lists that would be less work.

---
Tags: opengl, game-mechanics, planning
---


# Question
Title: Cocos2D-JS Windows App in fullscreen mode (Win32)
I've been looking for a way to make my Cocos2D-JS app go into fullscreen mode, but there doesn't seem to be much documentation on Cocos2D-JS (or Cocos2D-x-js as some seem to call it.) This app is to be exported into a Windows Desktop platform (Win32), and so fullscreen mode should work there as well.

I checked the Cocos2D-JS Online API and found cc.screen, which has a method called `requestFullScreen`, so I tried this:

```
cc.screen.requestFullScreen(document.documentElement, function() { cc.log('Requesting full screen...'); } );

```

However, this didn't work on either of the platforms I tested it on (web browser and win32). Since `document` does not exist when you export the app into win32, I then tried changing it for `cc._canvas`:

```
cc.screen.requestFullScreen(cc._canvas, function() { cc.log('Requesting full screen...'); } );

```

But this did not work either. Is there a way to make the app run in fullscreen mode?

PD: My apologies for any wrong tags I may have included to this question. I added the ones I thought were related to this problem.

# Answer
I was able to make the deployed cocos2d-js Win32 app run in fullscreen mode by modifying the `AppDelegate.cpp` file (located in `frameworks/runtime-src/Classes/AppDelegate.cpp`).

1. Inside the `AppDelegate.cpp` find method `applicationDidFinishLoading`
2. Within method `applicationDidFinishLoading`, look for this line:

```
glview = cocos2d::GLViewImpl::createWithRect("MyAppName", Rect(0,0,900,640));

```
3. Call `createWithFullScreen` instead of `createWithRect`, and remove second argument (which sets the window size in window mode):

```
glview = cocos2d::GLViewImpl::createWithFullScreen("MyAppName");

```
4. Compile/Deploy the app using `cocos compile -p win32`, `cocos deploy -p win32 -m debug`, or `cocos run -p win32`.

And that's it. :)
> 1 votes

---
Tags: javascript, html-canvas, windows, cocos2d-x-js
---


# Question
Title: Unity - Proper use of threads with procedural generation
I have been working on a simple chunk based terrain generation system, with voxel octrees. The overall method works pretty well, but testing this system with large amounts of chunks completely freezes the game/main thread until the generation process is finished. Looking for a solution, I read about threads and coroutines and I implemented a simple thread class (based on this template) to call the "generate" function from it. The only advantage I had was a faster generation, with full CPU usage, but the game still freezes until the chunks are completely loaded. Am I doing something wrong? Here some parts of the code:

```
public class ChunkThread : ThreadedJob {
  public Chunk chunk;
  protected override void ThreadFunction(){
    chunk.root = chunk.root.BuildOctree (chunk.pos, Chunk.size, -1);
  }
  protected override void OnFinished(){
    chunk.RenderChunk ();
  }
}

```

This is the simple Thread class I use to call the Build function, and the Render function when finished. This piece of code below is the start\update method for every Chunk gameObject (I kept only the relevant part), that simply creates the Thread instance and calls Start() pressing the mouse button.

```
void Start () {
  t = new ChunkThread ();
  t.chunk = this;
}
void Update () {
  if (Input.GetButtonDown ("Fire1")) {
  t.Start ();
}

```

Now, coming to the questions, what should I do to generate the terrain while still being able to play? Is there something wrong in my thread? Should I use a thread pool, if so how?

# Answer
> 0 votes
I took a similar approach here:

https://github.com/TehWardy/ccoder-Voxels/tree/master/Assets/Tasks

My code basically does what the .Net 4 tasks stuff does (well some of it) in that I pass a lambda in and get a task back ....

```
var task = Task.Factory.StartNew(() => { return GenerateLotsOfData(); });

```

I then use update to handle when the task is complete ...

```
void update() {
  if(task.Complete) { var data = task.Result; }
}

```

Using my code I don't appear to get any locking problems.

The key difference I can see is that I limit the number of threads my tasking system can use, other than that it's pretty much the same approach.

---
Tags: c#, unity, procedural-generation, multithreading
---


# Question
Title: How to render a pseudo-3D view like in the game Biosys (1999)?
Biosys is a PC game released in 1999, where navigation through its environments is done by clicking an "exit" on a scene, taking the player to a new scene. The player can't move in a scene, and interaction is done by clicking a location in it. In some scenes the player can freely look around in 360 degrees by moving the mouse.

My question is, what technique could be used to render such a scene? I'm asking because that doesn't look like it's true 3D; it looks drawn as if a picture is wrapped around the player, but how would you produce and render a picture in such a way?

Here is a rare YouTube video of that game, beginning at 3:40 where the technique I'm curious about is shown.

And here's a picture of one of those environments:

# Answer
> 2 votes
Its a guess but ...

Maybe they just have a skybox behaviour where they track clicks to particular locations on each "quad" of the box.

This basically means each "scene" is no more than 1 cubes worth of verts and indexes.

Puts a lot of load on your artist though.

You could test this by rendering a normal cube inside out and putting the camera inside it, by turning off the z buffer you would basically remove those square edges you might expect from a normal cube.

---
Tags: 3d, rendering
---


title: How to draw arrows between bubbles

text:
# Question
Title: How to draw arrows between bubbles
I have 2 * 3 matrix of bubbles and i want to draw arrows between those bubbles. it should be done in way as in below Image:-

1 ----\>2---\>3

What is happening here, When i touch **1 bubble**, start point will set to 1 and if i drag my finger towards 2nd bubble, an arrow that is strechable should draw between these 2 points and if **i continue to drag my finger from 2 bubble to 3rd bubble**, **another arrow should draw between 2 and 3rd bubble** and continue untill i lift my finger.

# Answer
> 0 votes
This is the pseudo code for what my approach would be. This would go in your update function.

```
If touch location is on a bubble {
    start drawing new arrow
}

If drawing arrow {
    If player stops touching screen {
        stop drawing arrow
    }
    else {
        draw arrow from start touch location to current touch location
        If current touch location is another bubble {
            add completed arrow to draw list
            start drawing new arrow
        }
    }
}

```

---
Tags: unity
---


# Question
Title: SelectBox in LibGDX doesn't display and freezes the program after a click
I am currently trying to apply an overlay with LibGDX over my 3D ModelBatch. Everything works fine except for the SelectBox. Once instanciated, it shows up on my screen I can click on it once but then it freezes. The drop-down list is not displayed and the clicks are no longer registered by my application. However, if my second click is under the standard position of the list, that is where it should be drawn when it drops down, an item is selected but then any third click will just return the list to the original selected item and no click is registered by my application anymore. I am running the application on Desktop.

Using break points in the SelectBox.class I was able to notice that the third and other next clicks are registered by the SelectBox.class as part of the list in the Listener responsible for selecting an item.

```
selectBox = new SelectBox<Object>(skin);
selectBox.setItems(array);
selectBox.setSelected("Custom");
stage.addActor(selectBox);

```

array in this case is an instance of Object\[\] containing only Strings. This is the only part of code I have related to the selectBox.

I have tried using an array of String\[\] at first but then switched to Object as suggested on a LibGDX forum.

I am currently using the latest Nightly Build of 2014/04/11 as I also need TextArea which is not yet in the stable release. However, I have tried the stable release 0.9.9 and it doesn't work either.

Am I using the right code to declare my SelectBox, or what could I do to make the SelectBox behave properly that is display its list when clicked and return to a normal state after an item is selected?

# Answer
Just had a similar problem. The following code in the render method of the screen helped:

```
stage.act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 30f));

```
> -1 votes

---
Tags: libgdx
---


# Question
Title: Since Table.drawDebug is deprecated in libGDX, what should I use instead?
I am following the "Learning LibGDX Game Development" book to make a simple game. I am in the menu creation section where we create a stage and render it with debug borders.

The book says to use `Table.drawDebug(stage)` but this static method seems to have been removed from the frameworks `Table` class entirely.

I am importing `com.badlogic.gdx.scenes.scene2d.ui.Table`; below is my code:

```
@Override
public void render(float deltaTime) {
    Gdx.gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    if (debugEnabled) {
        debugRebuildStage -= deltaTime;
        if (debugRebuildStage <= 0) {
            debugRebuildStage = DEBUG_REBUILD_INTERVAL;
            rebuildStage();
        }
    }
    stage.act(deltaTime);
    stage.draw();

    Table.drawDebug(stage);
}

```

The last line, `Table.drawDebug(stage);` has the compilation error `"The method drawDebug(ShapeRenderer) in the type Table is not applicable for the arguments (Stage)"`

Is there a new way to draw the stage in debug mode?

# Answer
This has changed once again.

The correct code for the method is currently as follows, as `stage.setDebug()` has seemingly been removed (can't find what version that happened) and replaced with `stage.setDebugAll(true);`:

```
@Override
public void render(float deltaTime) {
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    if (debugEnabled) {
        debugRebuildStage -= deltaTime;
        if (debugRebuildStage <= 0) {
            debugRebuildStage = DEBUG_REBUILD_INTERVAL;
            rebuildStage();
        }
    }
    stage.act(deltaTime);
    stage.draw();
    stage.setDebugAll(true);
}

```

Scene2d API documentation for the Stage class.
> 12 votes

# Answer
Found the answer, instead of the static `Table.drawDebug(stage);` call there is an instance method called `stage.setDebug()`.
> 5 votes

---
Tags: libgdx
---


# Question
Title: Keep state in Unity editor without hitting serialization
In my game I have a MonoBehaviour `WorldView` that, when created at editor time, initializes a large dictionary. Later from a Editor `WorldViewEditor` I call `WorldView.SetBlock()` that tries to access this dictionary, but finds it empty.

If I understand correctly this is because my editor doesn't access the same WorldView instance, but rather a copy it received through serializing and de-serializing my original instance.
Pushing this dictionary through the serializing process is a performance nightmare and not supported by Unity out of the box.

This dictionary should never be shown in any editor, is private to the instance and initialization will be called every time the scene is loaded.
This sounds like a perfect case for keeping it somewhere outside the serialization process.

I could try to leverage ISerializationCallbackReceiver but this still requires me to pull the entire dictionary through some serialization process.
I'm looking into keeping everything state related in a separate library outside of unity, but this has it own downsides.

Is there a way to put this dictionary in a place where its state is kept?

# Answer
The problem with what you're trying to do is that Unity has to recompile your scripts and reload the DLLs every time you make a change, which wipes out all of your non-serialized values, including static fields. Serialization isn't just how they save your scenes and prefabs to disk, it's also how they restore the editor's state every time you compile.

Every time the little wheel in the bottom right hand corner spins, something like this happens:

1. Serialize every managed object in the Unity editor, including EditorWindows and MonoBehaviours. This is how Unity remembers the position and state of all your windows, GameObjects, etc. It's also how it restores the original game state after you exit play mode even if you didn't hit Save.
2. Unload all of your script DLLs. At this point your custom types are all gone. Nothing "exists" in managed land at this point because the runtime has no idea about any of your code.
3. Recompile your scripts and load the DLLs again.
4. Now that you have your types back, deserialize everything and recreate all your GameObjects, MonoBehaviours, EditorWindows, etc. Since you don't push your dictionary through the serialization pipeline, it's lost at this point and needs to be reloaded.

Basically without serializing it, there's no way to maintain the state. You would have to reload the dictionary every time your scripts compile, not just once at scene load.

It sounds like you're loading that dictionary from a file on disk, or somehow creating the dictionary programmatically every time. How often does this dictionary change? If it doesn't change often, instead of using an intermediate format like XML you could build it directly into a static readonly field so that it automatically builds itself every time scripts reload without having to squeeze through serialization. The only other option is to let the dictionary serialize. You said it's large, and Unity doesn't support Dictionary serialization right out of the box, so you'd like to avoid this route, which I understand. But there's really no way around the fact that the entire state of the managed application gets wiped every time you recompile.
> 2 votes

---
Tags: unity, serialization
---


# Question
Title: My Raycast will not detect collisions in my Unity 2D project. What am I doing wrong?
I appreciate any help you can offer me. I created a script for a character controller that casts two rays below the player's gameobject. The rays extend infinitely and should collide with another gameobject called terrain. The player is directly above the terrain, so the Raycast must return information about that collider (terrain has a BoxCollider2D). The code I'm using is below. Thank you so much for your time and your help.

Why won't my Raycast hit the BoxCollider2D that is directly in front of it?

```
 public int distanceFromCenter; // set to 1 in inspector
 private float rayDistance = Mathf.Infinity;

 void Update () {
     Vector3 transformUp = transform.up;
     Vector3 transformRight = transform.right;
     RaycastHit leftRayHitInfo;
     RaycastHit rightRayHitInfo;

     Vector3 leftRayOrigin = transform.position + distanceFromCenter * transformRight;
     Vector3 rightRayOrigin = transform.position - distanceFromCenter * transformRight;
     Ray leftRay = new Ray(leftRayOrigin,-transformUp);
     Ray rightRay = new Ray(rightRayOrigin,-transformUp);
     Debug.DrawRay (leftRayOrigin,-transformUp*5000,Color.white); // for visualization
     Debug.DrawRay (rightRayOrigin,-transformUp*5000,Color.white); // for visualization

     bool castLeftRay = Physics.Raycast (leftRay, out leftRayHitInfo, rayDistance);
     bool castRightRay = Physics.Raycast (rightRay, out rightRayHitInfo, rayDistance);
     if (castLeftRay) {
         Debug.Log ("leftray true");
     } else {
         Debug.Log ("leftray false"); // the console always prints this
     }
 }

```

# Answer
> 1 votes
I figured it out! Physics cannot be used with 2D colliders like BoxCollider2D. I switched to Physics2D and everything works fine.

Thanks!

---
Tags: unity, 2d, box2d, raycasting
---


title: Flipped model has wrong triangle order

text:
# Question
Title: Flipped model has wrong triangle order
I have list of models and transform matrix for each of them. Some of models are flipped along X or Y or Z axis. This meshes will be rendered wrong, back face is rendered instead of front.

I tried to use `glFrontFace(GL_CW)` and that makes wrong models fixed but previous correct models are wrong.

How can I fix this? Can I detect from transform matrix which models need glFrontFace switch?

Right cube and sphere are normal and left are flipped

# Answer
Yes you can detect this. If the determinant of the upper-left 3x3 part of the transformation matrix is negative, your model is flipped.

Quoting this wikipedia page http://en.wikipedia.org/wiki/Back-face\_culling:

> An odd number of reflections will leave triangle facing the other side, as if exactly after one reflection. Transformations containing an odd number of reflections always have negative scaling factor, likewise scaling factor is positive if there are no reflections or even number of them. Scaling factor of a transformation is computed by determinant of its matrix.
> 1 votes

---
Tags: opengl, transformation
---


# Question
Title: CGVectorMake to move SKNode at a certain speed towards the middle of screen?
I am trying to launch my ball sprite towards the middle of the screen at the same speed every time I launch it.

```
let vel: CGFloat = 1000

dx = size.width / 2 - ball.position.x
dy = vel - size.height / 2 - ball.position.y

ball.physicsBody?.velocity = CGVectorMake(dx, dy)

```

This works in that it does launch the ball towards the center of the screen but at differing speeds depending on where the ball starts from.

# Answer
> 1 votes
I was misunderstanding the way vectors in SpriteKit are represented. The solution I used was:

```
dx = (size.width / 2 - ball.position.x) * vel
dy = (size.height / 2 - ball.position.y) * vel

```

---
Tags: physics, ios, linear-algebra, spritekit
---


title: How to use phaser documention?

text:
# Question
Title: How to use phaser documention?
im new to game development and i began with phaser which seems to be a great framework but i can't understand it's documention very well. Lets talk about phaser groups docs examples

How you understand how to use groups based on the documention ? Examples are clearer but limited they dont cover everything.

---

PS: valueerror answered this question in html5gamedevs

link to answer

# Answer
> 4 votes
I have a basic understanding of Phaser as well, but I know how to use the docs. The classes will be the classes in the `Phaser.Game` module. You make an instance of that at the start of your game. This is an example from my Flappy Bird game:

```
var game = new Phaser.Game(790, 400, Phaser.AUTO, 'game', stateActions);

```

I access the classes by `game.class`. The documentation tells you what the class contains and the methods and what they do with their parameters. Hope this helps!

---
Tags: phaser, documentation
---


# Question
Title: Apk file installes two instances of a Unity game
I created an apk in Unity (4.6) and when I install that apk on the device it creates 2 instances of the game (2 icons are visible in the screen). Both icons start the same game, and when I uninstall the game it removes both icons.

In previous builds this didn't happen, so I'm assuming that the changes I made to the Android Manifest have something to do with it. I included the Game Analytics SDK and it caused some problems when I tried to build the game for Android (with the message that the incompatible manifests can't be merged). So I commented out the part of the manifest that was causing the problem and now I have the problem with multiple instances of the game. I did some research and found that this happens when there are multiple activities in the manifest that are marked as LAUNCHER - this is not the case in my app, only one activity has that property. Also, as far as I can see, there is only one AndroidManifest.xml file in the Unity project (only one appears when I type it in the search).

This is the part of the manifest that I needed to change:

```
 <activity android:name="com.unity3d.player.UnityPlayerActivity" android:label="@string/app_name" android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
</activity>
<!--<activity android:name="com.unity3d.player.UnityPlayerNativeActivity" android:label="@string/app_name" android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
  <meta-data android:name="android.app.lib_name" android:value="unity" />
  <meta-data android:name="unityplayer.ForwardNativeEventsToDalvik" android:value="false" />
</activity>-->

```

If the commented out part is included, Unity throws the "incompatible manifest merge" error in the building process:

```
Error: [Temp\StagingArea\AndroidManifest-main.xml:4, [MyGame]Temp\StagingArea\android-libraries\unityads\AndroidManifest.xml:19] Trying to merge incompatible /manifest/application/activity[@name=com.unity3d.player.UnityPlayerNativeActivity] element:

UnityEditor.HostView:OnGUI()

```

Did anyone have any similar problems and how did you fix it?

Thanks

# Answer
This solution worked - I excluded the following lines: `<intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter>` And that solved the problem.
> 0 votes

---
Tags: unity, android
---


# Question
Title: How can I achieve a pseudo-3D camera effect like this?
I am trying to achieve a pseudo-3D camera effect similar to this:

I have gotten the following results using a 3D camera and billboards:

I am now running into the following problems:

1. In the first billboard example, the size discrepancy between when the sprites are at the "front" and "back" is too great. I need to have them be more similar to the above.
2. The bottom y-coordinate of the sprites never seem to change in my example, but they do (slightly) in the example that I want.
3. I need to be able to control how close to the right and left edge of the screen the sprites go to.

In the first billboard example I setup my camera like so:

```
// (float fovxDegrees, float aspect, float znear, float zfar)
this.simpleCamera.Perspective(75f, 1.5f, 0.01f, 400);

// (Vector3 eye, Vector3 target, Vector3 up)
this.simpleCamera.LookAt(new Vector3(0, 5f, 10f), Vector3.Zero, Vector3.Up);

```

My sprites are positioned at the following locations:

```
new Vector3(-4f, 1f, 0f);
new Vector3(-4f, 1f, 1f);

```

Full CSharp code: http://pastebin.com/9G0FDNLs

Billboard HLSL: http://pastebin.com/uB8e3gXU

If you want the grid: http://pastebin.com/R5UCBNWt

# Answer
You can do this in two ways, both of which require 3D cameras and projection:

First, give all of your objects a 3D position in the world.

```
// XYZ
Vector3 Position;

```

Next, create a camera with a position and orientation:

```
class Camera
{
    // Position of the camera in the world
    Vector3 Position;
    // Place where the camera is looking
    Vector3 Target;
    // Matrices representing the camera's parameters
    Matrix ViewMatrix;
    Matrix ProjectionMatrix;
}

```

You can update the camera's parameters like this:

```
void UpdateCameraParams()
{
  // Creates a view matrix from where the camera is looking and its position.
  ViewMatrix = Matrix.CreateLookAt(Position, Target, Vector3.Up);
  // Creates a perspective matrix with 1.2 radian FOV, 16:9 aspect ratio,
  // near plane of 0.01 units, and far plane of 10 units.
  ProjectionMatrix =
        Matrix.CreatePerspectiveFOV(1.2f, 16.0f / 9.0f, 0.01f, 10.0f);
}

```

Now, the two ways of drawing.

# SpriteBatch, the Hacky Way

You're probably familiar with SpriteBatch already. It's a way of drawing sprites to the screen in screen space. One thing you can do is simply project all of your objects onto the screen, scale them by their distance to the camera, and then render them. This is a hacky way of doing things, because you have to fake perspective and the depth buffer.

Here's how to do it:

```
SpriteBatch.Begin();

// Draw each entity in the scene
foreach(Entity thing in Scene)
{
    // Project its position onto the screen using the camera.
    Vector3 screenPos
      = GraphicsDevice.Viewport.Project(thing.Position, camera.ProjectionMatrix,
                                        camera.ViewMatrix, Matrix.Identity);

    // Determine if its on the screen.
    bool isOnScreen = Viewport.Bounds.Contains((int)screenPos.X, (int)screenPos.Y);

    if(!isOnScreen) continue;

    // Compute the depth and scale of the object.
    float depth = screenPos.Z;
    float scale = 1.0f / depth;

    // Draw it at the appropriate depth and scale.
    SpriteBatch.Draw(thing.Image, new Vector2(screenPos.X, screenPos.Y),
                     thing.SourceRect, thing.Tint, thing.Rotation, thing.Origin,
                     new Vector2(scale, scale), thing.SpriteEffects, depth);

}

SpriteBatch.End();

```

# Textured Billboards, the Correct Way

You can also just create for each sprite a physical 3D model, just a 3D billboard, oriented to face the camera. Then, you can render it like any other XNA 3D geometry. The depth buffer will work flawlessly, you won't have to guess the scale, and perspective will be taken care of correctly. I suggest this tutorial to get you started.
> 3 votes

# Answer
I would agree that it would be best to go fully 3D billboard with this. You can do this without shaders (well, you would use the built in `BasicEffect` which is an already written shader for you).

1. Move the camera away from the scene and decrease the FOV. here's why:

When you move the camera close to the scene and widen the FOV, the close fighter (blue square) is taking up approx. 1/10 of the screen, but the farther fighter is only 1/15 to 1/20 of the screen which is drawn as a much smaller object. When moving back from the scene and narrowing the FOV, the close and far fighters appear about the same size with the farther one only slightly smaller instead of a lot smaller. Experiment to find the sweet spot.

2. Raise the position of the camera a bit and point it down to keep scene centered. Experiment to find the sweet spot.
3. Once the camera is looking at the center of the scene, the FOV and the camera distance from the scene will contribute to that.
> 1 votes

---
Tags: xna, 3d, camera, projection, perspective
---


title: FlxG.overlap() won't work

text:
# Question
Title: FlxG.overlap() won't work
I need a collision detection that has no physics and it's FlxG.overlap(), right? But why it doesn't work? FlxG.collide() works for me but.. how can I remove the physics when I hit the monster with a bullet?

# Answer
when FlxG.collide runs, it also moves the colliding bodies apart, so an overlap check right after, will return false. So make sure that the overlap check runs before the collide function kicks in
> 0 votes

# Answer
It is slightly difficult to understand exactly how you are trying to implement it, assuming it is a basic, if overlapping, then do A, this is how it should work.

you will need an object/group:

```
private var ObjectGroup:FlxGroup;
private var ObjectInGroup:FlxSprite;
private var Object2:FlxSprite;

```

In your update function or wherever you want to detect the overlap:

```
FlxG.overlap(Object2, ObjectsGroup, OverlappingObjects);

```

Then the function that is called:

```
   private function OverlappingObjects(FirstObject:FlxSprite, SecondObject:FlxSprite){

   }

```

Now you can do this with two sprites, or two groups, but this is basically how the it should turn out. I have not used the ProcessCallback yet, but I assume you would have a function with a return as a boolean, based upon the description. I could be wrong though.
> 0 votes

---
Tags: flixel
---


# Question
Title: How do I compile further libraries into my game?
This might be vague; I don't know how to search for this.

How do I link a GUI framework (in my case, CEGUI) to a graphics framework (in my case, SDL)?

I'm using a Mac. My mental model on how to add libraries is something like this in my head:

> There are `.framework` files. They go in `/Library/Framework/`. You then link them to Xcode in build settings, then they magically work. Then there are libraries you add to header path, and library path and something about include and lib folders, but I don't understand those.

A guide from the ground up would help, because I would like to get a better understanding of how it works. I also have no idea what `cmake` is, although I've been seeing it a lot.

# Answer
> 1 votes
You seem to be confused about the link process in general, so sorry if I go a bit on a tangent first.

You need to differentiate between object files, static libraries and dynamic libraries. Apple adds "Frameworks" to the mix in OSX. They are just one possible way of adding foreign code into your executable. Roughly speaking:

* Object files (\*.o, \*.obj) are the result of compiling your source code and become part of the executable (\*.exe, \*.so, \*.dll).
* Static libraries (\*.a, \*.lib) contain multiple object files and they again become part of your executable. Since the object files of the library are available to the compiler it can perform many optimizations (e.g. removal of unused object files).
* Dynamic libraries are executables without an entry point (main function). Other executables may reference their content at runtime, but that also means their content is not part of those executable files. They can be shared by multiple executables and even unloaded again (e.g. useful for plugins or hardware drivers which should be loaded on demand only).
* Frameworks (\*.framework) are just directories that bundle header files, libraries (possibly multiple versions) and other resources (images etc.) together. They're supposed to force a scheme of how the above should be organized to make installation, compilation and linking easier for the programmer. You may find system-wide Frameworks in system folders, but you will also find application-specific ones in App Bundles (\*.app).

In case of pre-installed, system-wide Frameworks (e.g. Cocoa) you may assume that they exist on the target machine and just link them, your user will also have them.

SDL and CEGUI are not part of the OS X base system, so it is unlikely that your user installed them system-wide. Therefore you should add such libraries/Frameworks to your App Bundle and link to those local copies, or the application will crash on your users' machines at runtime.

Even if the user installed those Frameworks (unlikely), then the version or configuration might not match. Many developers constantly break the ABI of their library during version updates (due to lack of knowledge, care or use of an ABI-unstable language such as C++). But even if that is not the case the configuration options used during compilation on your users' machines might bite you (e.g. you need GIF image support, but their SDL library was compiled without it). This is called "DLL Hell".

So what to use? People are very religious about static vs dynamic libraries/Frameworks, so you will see very heated debates about this question on forums. In a perfect world we would all use the same library versions and configurations, the dynamic library would only be loaded once and we could all share their memory. In reality this is not the case, and how many of your running applications are using SDL and CEGUI right now anyway? Static libraries also offer the aforementioned optimization possibilities.

So my rough suggestion to you would be:

* Pre-installed system libraries and frameworks (e.g. Cocoa, OpenGL) should be linked dynamically (\*.so, \*.dll, \*.framework). They benefit from system updates (especially security updates).
* Libraries that only your application will use should be put into static libraries and made part of your executable. Dynamic linking and Frameworks are of no advantage here, since you need to distribute them with your application and they will most likely not be shared with other applications.

TL;DR: SDL and CEGUI probably offer both Framework and static library versions. I suggest you use the static library for your application.

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