# Question
Title: How to run multiple Lua scripts within the same lua state without conflict
I've been working with Lua for sometime and there is a problem that I could never solve it. First, I'm using a single lua state to have a connection between my scripts so they could transfer data via global table `_G`.

My scripts have a template like this:

```
-- Vars
local somevar = 0

-- Update
function Update()
  -- stuff
end

```

I call `Update()` function from my application every game step, but since there are other scripts loaded in current lua state with the same template only the `Update()` function from the last chunk in lua is getting called and there is no way I can call all of `Update()` functions in my scripts.

If I load my scripts every time I want to call the functions, It'll work the way I want, but this way my local variables and every change that I have made to the scripts would get dumped because the chunk is replaced with a new one.

I've seen a message on Lua's site itself which talks about setting an environment for each chunk that is going to get loaded, but that's not what I want because it forces each script to reside in a unique table and there is no way to communicate with global table since we're going to override the global table for our unique tables.

I'd really appreciate if someone give me some advice because there isn't really much on the internet about these kinds of stuff.

**UPDATE**

I know the answer to first part of my question. Right now I'm using a table for each of my scripts, something like this:

*code1.lua*

```
code1 = {}

function code1.Update()
  -- Update
end

```

This makes every script accessible via the global table with their table name. The problem is if I load this script for another object in my game, then it'll conflict with the previously loaded script because they're both using the same source and therefore the same names and I can only access the last loaded. As you can see, I've stated this about environments in first part of my question.

# Answer
I had same problem and I solved it with event system

```
local __events = {}
function addEventListener(event, callback)
    local listeners = __events[event]
    if listeners ~= nil then
        listeners[#listeners + 1] = callback
    else
        __events[event] = {callback}
    end
end

function trigger(event, ...)
    local listeners = __events[event]
    if listeners ~= nil then
        for i = 1, #listeners do
            listeners[i](...)
        end
    end
end

```

Add event listener function saves callback function into table with array of functions for each event. Trigger function find array of functions for event and call all of them. For each event C code will call I create one function which just call trigger("EventName")

```
function event_update(elapsed)
    trigger("update", elapsed)
end

```

And all other scripts use

```
addEventListener("update", function(elapsed)

end)

```
> 1 votes

# Answer
You can use environments and communicate using the global table using metatables, which will allow the local environment to inherit the global one. With Lua 5.2:

```
function loadEnv(file)
    local newenv = {}
    setmetatable(newenv, { __index=_G })
    loadfile(file, "bt", newenv)()
    return newenv
end
globalVar = "Global"
newenv1 = loadEnv("update1.lua")
newenv2 = loadEnv("update2.lua")

newenv1.Update()
newenv2.Update()

```

With the scripts:

```
-- update1.lua
local somevar = 0
print(_ENV)
function Update()
    print("update1")
    print(somevar)
    print(globalVar)
    _G.globalVar = "global2" -- use this to create/modify a global variable
end

```

And

```
-- update2.lua
local somevar = 1
print(_ENV)
function Update()
    print("update2")
    print(somevar)
    print(globalVar)
end

```

You'll get:

```
table: 0044ED78
table: 009C9AC0
update1
0
Global
update2
1
global2

```
> 1 votes

---
Tags: lua
---


title: Batching and object's transformation

text:
# Question
Title: Batching and object's transformation
I'm trying to implement batching in my game (Sprite batching and 3D Mesh batching), I've read a lot of documentation about that but I don't understand something:

* When each object have is own transformation (rotation, position, scale), how can I merge it with others geometries?
* When each object use blending, how can I achieve depth with batching?

Thanks!

# Answer
> 1 votes
# Transformation In Batching

When the geometry your batching is simple enough - such as with sprites where only 4 vertices are used - you usually translate to a shared coordinate system before putting the vertices in a batch. Often this is camera space or screen space.

The simplicity of the geometry means that doing this operation CPU side is still a negligible process and is easily parallelised. As the geometry becomes more complex the cost/benefit ratio drops and suddenly separate draw calls looks more appealing.

One solution to this, which I haven't tried, is to supply your vertex shader with the worldview matrix for each mesh your batching and tag each vertex with an id so you know which one to use for each vertex.

# Alpha Blending

I'm not quite sure what you mean by "achieve depth". You can still leave depth testing and writing to the depth buffer turned on in this instance but this would cause transparent geometry to occlude other geometry unless the other geometry was drawn first. In other words a window might stop some things being drawn to the screen. For more information check out this article by Shawn Hargreaves.

So it's typical, when drawing transparent geometry, to disable writing to the depth buffer, but keep depth testing active. This means the transparent geometry can still be occluded by opaque geometry but will not occlude anything itself. You have to be careful though, if you draw the transparent geometry, without writing to the z-buffer, then draw opaque geometry, you might end up drawing over the top.

Imagine drawing a skybox and then a window. If you drew a tree behind the window later with no alpha blending it would be drawn over the top of the window.

As Shawn states;

> ```
> The most common approach:
>
>   1. Set DepthBufferEnable and DepthBufferWriteEnable to true
>   2. Draw all opaque geometry
>   3. Leave DepthBufferEnable set to true, but change DepthBufferWriteEnable to false
>   4. Sort alpha blended objects by distance from the camera, then draw them in order from back to front
>
> ```

---
Tags: opengl-es2, spritebatch
---


# Question
Title: Vertical alignment of a padded font generated by Hiero in libgdx
I've generated bitmap fonts for libgdx using Hiero. I've got several distance field fonts that require a lot of padding, unfortunately they don't seem to align correctly.

Below is a font with a bounding box drawn to the values returned from getBounds().

I've just changed to distance field fonts and all my logic that handles vertical positioning is broken because of this. If I use a font without any padding above or below then fonts are drawn aligned correctly.

My padding is 10 on all sides. Playing with a couple of characters, if I increase the y by 10 and decrease the height by 10 in the .fnt file I get the image below instead, which looks far more accurate.

If someone can tell me how I can resolve this issue, or a good way to work around it then that would be appreciated.

# Answer
> 2 votes
It has now been pointed out to me that on this page it says

> Note: If you're replacing a "regular" font by a distance field font, be aware that the font metrics are not the same. In particular, the extra padding causes the baseline to shift downwards, so you'll need to compensate by drawing your text higher.

So this is a known problem using the libgdx BitmapFont with padding and they're suggesting just working around it. IMO it's a bug and should have been fixed, but that'll now be difficult if people are already compensating for it.

To fix this you should create a wrapper for BitmapFont and then whenever you're drawing text you should do the following to compensate for the padding.

```
y += padding * font.getScaleY();

```

---
Tags: libgdx, fonts
---


# Question
Title: How do I mask graphics in Unity to create a searchlight effect?
I'm trying to make a searchlight-style punchout mask effect in Unity 2D. This is the effect I'm looking for:

That animation is made in Fireworks, using a white to black gradient circle masked on top of the map image below it. Here's a single frame for closer viewing.

How can I create this effect in Unity?

So far, I have a separate camera that only renders the white circle using a culling mask, but I'm not sure what to do from there.

# Answer
Why not use built in support for lighting in Unity? Spot light would do exactly the effect you need. Unity 2D "mode" is a bit tricky conserning the lighting:

> You'll need to add a material to your sprites for this which uses the Sprites Diffuse shader. As standard, sprites don't support lighting as we expect users to use them unlit and use lighting baked into the sprite design itself.
>
> Simply make a material, assign it to the sprite, and choose the Sprites Diffuse shader from the material.

and also, from the linked thread:

> Resurrecting this thread for anyone still looking for solutions for the binary lighting thing, just figured it out myself. Two important things to check:
>
> 1) Is the light's render mode set to "Important"? This should fix the issues with scaled stuff.
>
> 2) Are you using scaling or rotation to flip your sprites? Sprite renderers work like textured planes, they only receive light on one side. If you rotate the characters to mirror their direction then the renderer is suddenly facing away from the light, but if you just scale the object by -1 you can flip the character without flipping the renderer's normal.
> 2 votes

# Answer
The simplest way by far is this: create a transparent sprite with your circle "cut out", and opaque black along the sides. Then put in on top layer above everything else.

You might also want to attach 8 fully opaque black sprites to all sides of the circle, so that areas completely outside of it are masked too.

This would only work if you need to mask the entire screen (or entire screen except some layers such as UI). If you have some more complex configuration in mind, I'd look at a custom shader to render the mask. You only need to put a single quad over your masked area, and then in the shader change alpha to what you need, where you need it.
> 0 votes

---
Tags: 2d, unity, masking
---


title: Irregular oval collision detection

text:
# Question
Title: Irregular oval collision detection
I am using a physics library based on the Bullet physics engine. How do I create an egg shaped object or a cylinder where the width differs from the depth (i.e. with an oval shape)?

I'm not looking for code, but for a conceptual answer to help me understand this, or a useful approximation.

# Answer
If having your overall collision surface look something like this is acceptable, then yes, use a couplefew sphere colliders parented together somehow, since spheres are cheap (in fact I think the reason they're cheap in physics is because they're restricted to distance checks from a point, which is why you can't transform them):

Otherwise I would suggest making a convex hull out of e.g. a cylinder with a bulge in the middle if you need it fast. Here's one I hacked up in blender in a few mintues using an 8-sided cylinder and some loop cuts and scaling.
> 1 votes

---
Tags: physics, bullet-physics, physics-engine
---


title: Check which object was activated first

text:
# Question
Title: Check which object was activated first
How do I check which object was activated before the other? Let's say that there's door to open. To open the door you need to press firstly the second button and then the first button...but not the other way around.

I have these scripts for now:

Switch script (it's on 2 objects that are switches and both objects have colliders with IsTrigger checked):

```
public var IsPressed : boolean = false;
public var triggered : boolean = false;

function OnTriggerEnter() { triggered= true; }
function OnTriggerExit()  { triggered= false;}

function Update()
{
    if (triggered && Input.GetKeyDown(KeyCode.JoystickButton1))
        IsPressed = true;
}

```

SwitchCheck script (it's on door that should be opened)

```
public var Switch1 : Switch;
public var Switch2 : Switch;

function Update()
{
    if (Switch1.IsPressed && Switch2.IsPressed)
    {
        Destroy (gameObject);
    }
}

```

**EDIT:** Let me explain this in detail. If Button1/ Switch1 is pressed, door opens to World1.(no Button2 needs to be pressed.) If Button2 and then Button1 is pressed, door opens to the World2.

# Answer
To add a puzzle like quality to this you need to generate some sort of dependency on the switch values (the door shouldn't really know about this, the switches should notify the door it can open.) I would use a parent object much like indeed005 is suggesting but with some important changes:

```
//List references
import System.Collections.Generic; //Always a nice idea
import System.Linq;

//Unity3D
import UnityEngine;

public class Switch : MonoBehaviour
{
    public var IsPressed : boolean = false;
    public var Door : Door = null;
    public var DependantSwitches : List<Switch>;

    private var triggered : boolean = false;

    function OnTriggerEnter() { triggered= true; }
    function OnTriggerExit()  { triggered= false;}

    function Update()
    {
        if (
            triggered &&
            Input.GetKeyDown(KeyCode.JoystickButton1) &&
            DependantSwitches.All(function(o){ return o.IsPressed;})
           )
        {
            IsPressed = true;
        }

        if(IsPressed && Door != null)
        {
            Door.Open();
        }
    }
}

```

And the door class needs:

```
public class Doorextends MonoBehaviour
{
    function Open()
    {
        // Open your door
    }
}

```

This allows you to make a series of switches with any degree of dependance:

If you wanted you could make a series of switches in a linear formation:

```
SwitchA -> SwitchB -> SwitchC -> Door

```

Or even do a branched series of switches:

```
      SwitchA
       /   \
SwitchB     SwitchC
   |         /
SwitchD     /
       \   /
      SwitchE
         |
        Door

```

## Amending for Question Edit:

```
static var switchesList : List<Switch> = new List<Switch>();

public var switchNumber : int;

function Awake(){
    switchesList.Add(this);
}

function Update()
{
    if (
        triggered &&
        Input.GetKeyDown(KeyCode.JoystickButton1) &&
        DependantSwitches.All(function(o){ return o.IsPressed;})
       )
    {
        IsPressed = true;

        // Put to start of list.
        list.Remove(this);
        list.Insert(0, this);
    }

    if(IsPressed && Door != null)
    {
        Door.Open(switchesList);
    }

```

Door changes:

```
 function Open(switches : List.<Switch>)
 {
     // Check order of switches and open correct door/portal
     if( switches[0].switchNumber == 1  && switches[0].switchNumber == 2)
     {
          OpenPortalOne();
     } else if (switches[0].switchNumber == 2  && switches[0].switchNumber == 1)
     {
          OpenPortalTwo();
     }
 }

```
> 2 votes

# Answer
There are a number of ways. This is a really open ended problem, you can solve it however you want. Three options off the top of my head...

1. Store the game tick or timestamp that each switch was pressed on, and then compare ticks/timestamps to ensure Switch1 was pressed first.
2. Have Switch2 trigger an event on the door if it is pressed while Switch1 is down. That way Switch2 opens the door, instead of the door checking to see if it can open, a
3. Only set Switch2's IsPressed flag if Switch1 is already pressed, that way Switch1.IsPressed and Switch2.IsPressed can only both be true if they were pressed in the same order.

Option 1 requires adding some new information to the Switch class (a timestamp) whereas options 2 and 3 just require you to slightly reorganize the way your door is scripted. I personally would choose option 2 or 3.
> 0 votes

# Answer
Think about this: Should the second switch even be able to be flipped if the first switch is not already ON? If so, it may lead to some strange logic.

Assume door checks if switch1 was activated before switch 2

1. Player flips switch 2 to ON
2. Door does not open
3. Player flips switch 1 to ON
4. Door does not open
5. Player flips switch 2 to OFF
6. Door does not open
7. Player flips switch 2 back to ON
8. Door opens!
9. Door opens every time player sets switch2 to ON as long as they have turned on switch 1 once.

\*EDIT: This could cause the player confusion if they forget which order and when they turned the switches on/off. But if that is part of the puzzle, you'll have to set a timestamp for each switch and compare these

My advice is:

Add something like

```
public var ParentSwitch : Switch;

```

and

```
if (triggered && Input.GetKeyDown(KeyCode.JoystickButton1))
{
    if (ParentSwitch != null)
    {
        if (ParentSwitch.IsPressed) IsPressed = !IsPressed;
    }
    else
    {
        IsPressed = !IsPressed;
    }
}

```

to the switch script. That way the player can't flip the dependant switch until they flip the parent. This also means that if you decide to re-use the switch script later, you can just leave the reference empty if you don't want special logic.
> 0 votes

# Answer
How I'd do it would be the following:

(Sorry for the lack of code, on my lunch break!)

## First:

Create a new class.

A door controller, or something similar, give it a number of different (probably non-returning) update functions that correspond to the switches.

Give it variables to record the state of the object at the current time.

Each update function may cause a change in the state of the object, but only if the *current* state allows it.

When it enters a specific state, open the door.

Instance it.

## Second:

Each instance of the switch class is passed a function when it is created, corresponding to the in-level object it represents.

This function is called when the switch is triggered.

## State Machine

This is an example of a state machine, and they are quite a useful pattern for modelling this kind of behavior.
> 0 votes

---
Tags: unity, javascript
---


# Question
Title: Does a minor in math increase my hirability?
I've been pondering this question for some months now, and have been unable to get an answer from anyone in the industry (likely because I know no one in the industry).

**I am currently completing a B.S. in Computer Science, and I want to know if minoring in math will look good on my resume to gaming companies large and small.**

I am not set on becoming a game developer, but I certainly want to have that option available to me.

**UPDATE:** It's been a couple years since I asked this question, and have since graduated WITHOUT the minor. I was able to get a job at an amazing company, but not in game development. I am now personally of the opinion that minors are not really a major selling point for aspiring Software Engineers. The most important thing is building software and showing it off to potential employers.

# Answer
Hiring is kind of a black box. It really depends on the person who's looking at your resume/CV.

All I can say is that saying you have a minor in something is just another bullet point. Sometimes that helps. Maybe it shows you're more useful on the heavy math side of programming which some generalists programmers have trouble with. Maybe the person looking over your resume completely skips the education section because it generally isn't relevant.

I can't think of a reason it would hurt, though. At worse it should do nothing.
> 7 votes

# Answer
If I was looking at your resume, no. A math minor is probably the most common thing to accompany a CS major, and at most universities requires only one or two more classes - sometimes not even that, just a careful choice of electives. It won't hurt you at all, but all it tells me is that you're good at playing the college course picking game, not anything about your skills.

On the other hand, *knowing more math* can increase your hirability. If the best way for you to learn more math is to take more math classes, then definitely it will.

But if you know the math or would learn it on your own anyway, and don't particularly want to take the courses, I'd pick something else you enjoy. You'll stand out more, have more fun, and have something to talk about in interviews other than matrices.
> 7 votes

# Answer
As an engineer at a mid-size studio, if I'm reviewing your resume, then yes it certainly helps -- but it also means that I'd drill deeper into linear algebra and geometry during the interview. It also signals that you are more interested in the systems/engine side of programming.

A minor in the creative arts or language or so on can also be a positive signal, if you are interviewing for a gameplay programmer or hybrid code/design position.
> 4 votes

# Answer
Having more maths knowledge/ability is never a bad thing.

However don't take it as a bullet point for the CV - it's only going to be useful to you, and/or an employer, if you actually get something out of it. Which means actually learning stuff, and being able to demonstrate it in an interview and use it in the real world.

That can be tough, because IME maths is quite often a subject taught without much context. You may have to provide your own - look at what each topic can be used for and you'll probably absorb it a bit better.

I wish I had done this a bit more myself. There are topics in maths I *know* I covered at university, but didn't take in because I wasn't given any indication of what they were useful for. Now, 15-20 years later I'm coming across things where I need that knowledge... and it's not there ;)
> 3 votes

# Answer
I have a B.S. in Computer Science with a minor in math! What they told me in school was that they weren't so much teaching me all the things I had to know, but how to learn on my own. Unless you're at a game-programming school, what you're learning now is generalized and not specific to game development.

Having a minor in math lays the foundation for all the more specialized topics you'll have to learn about on the job. And hopefully, your future employer will see that you have experience with more difficult maths and know that you won't be scared away when they throw hard, boring problems at you ;)

Full disclosure: I'm not currently working in the game industry.
> 1 votes

# Answer
I started off as a B.S in CS and now I am a B.S. in Mathematics. I do not really have any experience with the resumes or the work world however I would say knowing math is very useful. I would further emphasize the fact that the gaming industry appears to be moving towards networked gaming or massively multiply gaming with trends in free-worlds and dynamic playing. A minor will not give you the depth to model much of that but it will give you the ability to understand and appreciate it.

Since it will cover calculus it will give you understanding of the mathematical tools necessary for optimizing situations. Since the math will be available to for the methods you wish to employ it will mainly be up to deciphering a way of implementing it both correctly and optimally.

Almost all games are pushing AI development and implementation into different facets, whether it is NPC or meta-level world and ontology generation and management. At this point computational power is prohibitive for many of the most powerful tools but with a planned career this does not matter so much.

The minor will probably require a statistics class and your knowledge of algorithms will most likely be sufficient. I am not sure if any current games include such computationally expensive simulation methods especially on massively multiplayer scales but I can foresee the use of Monte-Carlo methods.

In any case, perhaps it is merely my bias but I would get an M.S. as well. I imagine that would make you more marketable for a longer time and give you more freedom. Otherwise I imagine you will be just coding, and that seems liable to be outsourced.

Another option for a minor would be psychology, sociology or economics. The first two I imagine would emphasize your ability to appeal to and understand gamers while the third would give you a grasp of markets (many game developers struggle with generating realistic markets for trade) and present the possibility of the managerial route. I imagine a company could at some point (after showing promise) offer to pay for an MBA. I imagine would allow you enjoy both the gaming aspects and the freedom whether you are in a company or decide to manage your own studio and produce games, which increasingly is becoming an option due to digital downloads.

I initially was just going to push math all the way but I imagine the economics minor will give you the most freedom and happiness.

I hope that helps.
> 1 votes

# Answer
I know this is a pretty late reply but I just thought I should throw it out here for anyone with similar questions. I did econ major undergrad in UC Berkeley too. But after I finish, I wish I did a technical/science/math major because Economics is very general. You have to go to PhD to really make it worth it. Unless, you're planning on going to graduate school with your philosophy for Law or something like that, I really recommend you minor in Math. The decrease in GPA will be justifiable as math major average GPA will always tend to be lower, at Cal, it's like 2.7. From a recruiter perspective, I would take a person with 3.5 GPA with math minor over 3.8 Economics only. Skills vs just numbers. I had a friend who did economics and math and she got into investment banking.

Sources:

http://www.math.berkeley.edu/programs/undergraduate/minoring-mathematics

http://www.careerdean.com/c/2/incoming-freshmen-if-know-want-have-career-business-it-wise-major-computer-science-also-learn-the-technical-side-or-stick-more-traditional-major-like-economics
> 1 votes

---
Tags: mathematics, education, jobs
---


title: 2D collisions between 2 arrays

text:
# Question
Title: 2D collisions between 2 arrays
I'm trying to do collision detection between bullets and enemies in my game. But it's very unpredictable and sometimes it works, sometimes it doesn't (bullet goes straight through without doing anything) and sometimes it kills the script returning "Uncaught TypeError: Cannot read property 'x' of undefined".

The collision detection is just a trivial for loop like this:

```
if (enemies.length > 0 && bullets.length > 0) {
    for (a = 0; a < bullets.length; a++) {
        for (b = 0; b < bullets.length; b++) {
            if (bullets[a].x + 36 >= enemies[b].x && bullets[a].x <= enemies[b].x + 56 && bullets[a].y >= enemies[b].y && bullets[a].y + 6 <= enemies[b].y + 69) {
                bullets[a].Delete();
                enemies[b].Delete();
            }
        }
    }
}

```

The `.Delete()` function is just a reference to `arr.splice(index, 1)` in the objects. Of course I didn't expect this to be perfect, but I'm surprised by the random behaviour of it. What could cause this and how can I improve the collision detection?

# Answer
If I understand correctly, you have a bullet "object" of size 36x6 colliding with an enemy of size 56x69.

Let's take a look at each step of the collision:

```
bullets[a].x + 36 >= enemies[b].x

```

This will test if the bullet right side is to the right of the enemy's left side. Right after, you have this:

```
bullets[a].x <= enemy[b].x + 56

```

Here, you test that the left side of the bullet is to the left of the right side of the player. So far, the bullet must be fully contained horizontally.

Next, vertical collisions:

```
bullets[a].y >= enemies[b].y

```

This tests that the upper bound of the bullet is below or equal to the upper bound of the enemy. And then , you have:

```
bullets[a].y + 6 <= enemies[b].y + 69

```

Which does the same for the lower bound.

From what I can read, **the bullet must be totally contained within the enemy for the collision to occur**. So you will sometimes see the bullet "touch" the enemy, but not being totally inside, and the collision will not occur.

Worst than that, **if on one update tick the bullet is off on the left, and on the other is off on the right, the bullet will have passed through the enemy without killing it.**

Little ASCII arts to illustrate:

The bullet starts by being off on the left side:

```
  --------- // Tick 1 - Does not trigger collision
  |       |
-----     |
  |       |
  ---------

```

Then you increment the bullet's position:

```
  --------- // Tick 2 - Does not trigger collision
  |       |
  |     -----
  |       |
  ---------

```

The bullet will never have triggered the collision. But this, on the other hand, will:

```
  --------- // This triggers collision
  |       |
  | ----- |
  |       |
  ---------

```

If you want to have better collision management that does not require the bullet to be fully contained, but only to touch the enemy, have a look at AABB collisions:

For the crash side of things, Evan already found the problem, so refer to it's answer.
> 1 votes

# Answer
At first glance, I would say you're going to have a problem with splicing during the loop. Say you're at index 1 and you have a collision. You then remove that spot, and now everything moves up a space. But your loop counter still increments. So what used to be in the second index is in the first one, and you went from the first to the second, skipping it entirely. This explains why some collisions are never checked, and it would mean that if it happens in the last spot, you would go out of bounds.
> 3 votes

# Answer
You problem is in speed of checking for collisions.
there are two possible solutions:

1. Check several (*n*) times each frame (=move *1/n* speed *n* times)
2. Instead of point-rectangle intersection perform line segment - rectangle intersection

the first solution is fast and easily implemented, on the other hand it doesnt really solve anything, if your bullets are too fast, they will still miss.
At cost of more difficult to implement collision detection(and some performance) you can get perfect results even for rectangles with lim *size -\> 0*.
At the end the decision is up to you.
> 2 votes

---
Tags: collision-detection, javascript, html5
---


# Question
Title: How can I determine where to show a nameplate over a character?
I'm working on a naming system that displays the name of enemies above their heads.

The problem is that I have some enemies that are larger or smaller than others. So I'm trying to use a function that gets the height of the enemy, and then uses that as the modifier for the name's position.

Here's what I'm doing (I should mention that the `target` is the enemy that is currently being targeted):

```
public Vector3 offset = Vector3.up;
...
thisTransform.position = cam.WorldToViewportPoint(target.position + offset);

```

What I'd like to do:

```
public float enemyHeight;
...
enemyHeight = target.collider.bounds.size.y + .5f;
thisTransform.position = cam.WorldToViewportPoint(target.position + enemyHeight);

```

But obviously it is giving me an error that I can't add a float to a vector. How can I accomplish this?

# Answer
To compute the nameplate position (in world space), start with the character's origin (in world space). Hopefully your character origins are defined such that they represent the center of the character on the ground, since that's the meaning that makes the most sense in general. If your character origins are something else, you'll need to account for that.

Then, compute the character height plus some offset to allow for the padding between the top of the character and the nameplate. As you've noted, this is a floating point value. You can't add a float and a vector, but you can add two vectors, so if you simply construct a vector `(0, height + padding, 0)` and add that to the origin of the character, you'll have your nameplate origin.

This assumes, of course, Y is up in your world, but that is similarly easy to adjust for. If however "up" isn't always the same (for example if a character can stand on a 45-degree inline) you will instead want to construct the offset vector in a more general fashion. One way to do this is to take the normal vector of the plane the character is standing in (which should be normalizing it) and *scaling* that vector by the character height and offset. This also produces a vector you can add to the origin.

This gives you the nameplate position in world space, which you can use directly or project to screen space if you need to. In some cases it may be more desirable to instead project the bounding box of the character to screen space, find it's highest Y position and use that (plus some offset) as the basis for the nameplate. Both methods (and many others) are valid, it depends primarily on what sort of effect and behavior you want out of the nameplate.
> 2 votes

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


# Question
Title: Loading non-square textures, from a 256x256 spritesheet in lwjgl(JAVA)
so I'm doing lwjgl, so far I have the loading of 16x16 textures from a 256x256 spritesheet all working, using this code to get the location of the textures:

```
 public  Vector2f[] calculateUVMapping(int texture, int atlasWidth, int atlasHeight) {
    int textureIndex = texture;

    int u = textureIndex % atlasWidth;
    int v = textureIndex / atlasHeight;

    float xOffset = 1f / atlasWidth;
    float yOffset = 1f / atlasHeight;

    float uOffset = (u * xOffset);
    float vOffset = (v * yOffset);

    Vector2f[] UVList = new Vector2f[4];

    UVList[0] = new Vector2f(uOffset, vOffset); // 0,0
    UVList[1] = new Vector2f(uOffset, vOffset + yOffset); // 0,1
    UVList[2] = new Vector2f(uOffset + xOffset, vOffset + yOffset); // 1,1
    UVList[3] = new Vector2f(uOffset + xOffset, vOffset); // 1,0

    return UVList;
}

```

This takes the texture ID from left to right, top to bottom in the atlas, starting from 0 and the amount of textures the atlas holds, so to get the first texture in a 256x256 sheet (holds 16 textures in each row and column) I'd do `calculateUVMapping(0,16,16)`, along with he corresponding endings for the vector and variable.

Now, say I want to have a 200x20 texture in another 256x256 sheet, or any nonsquare texture, actually, and I want to apply that to a quad- could this code work for getting the co-ords for it, or what code should I use for those?

# Answer
> 0 votes
Simply calculate UVs (0,0 point is left bottom, 1,1 point is right top) assuming you v got sprite texture dimensions *sp* in pixels just divide it by texture size:

```
SpriteDimensions sp; //that you must know

Vector2f[] UVList = new Vector2f[4];

UVList[0] = new Vector2f(sp.x / tex_width, sp.y / tex_height); // 0,0
UVList[1] = new Vector2f(sp.x / tex_width, (sp.y + sp.height) / tex_height); // 0,1
UVList[2] = new Vector2f((sp.x + sp.width) / tex_width, (sp.y + sp.height) / tex_height); // 1,1
UVList[3] = new Vector2f((sp.x + sp.width) / tex_width, sp.y / tex_height); // 1,0

```

---
Tags: opengl, java, vector, lwjgl, uv-mapping
---


# Question
Title: GameLogic Model as Property or Constants with lookup in other Models?
Basically imagine a game where the Player has a Weapon which has a BulletType/type of Bullet.

Now Player, Weapon and Bullet are Models having properties and they would represent Instances in the game.

I want to Instantiate a Bullet when the Player fires and I have to check what BulletType the Weapon currently has, but I don't understand what kind of Property Weapon should have to represent the current type of Bullet.

Should in the Weapon class the BulletType be an Instance of Bullet or should I use some kind of Constant as BulletType that would map to the Bullet Model?

```
class Weapon{
    IBullet currentBulletType //<-- a Bullet Model with Position and everything
}

```

or

```
class Weapon{
    BulletTypeConstant currentBulletType // a Constant that is mapped to a specific Model
}

```

The first approach is using a whole Model to represent the BulletType currently equipped. The Second uses some kind of Constant that must then be mapped to a specific Model of Bullet on firing.

I always find myself troubled as to which approach would be better. Or perhaps you have an even better Idea. Thanks

# Answer
I think that any good OOP source you check will advise you to program against interfaces, which is one of the pillars of OOP, so your first option would be better.

However the problem here is conceptual. If you think about it, your weapons doesn't have a bullet, as your model suggest, but it produces bullets. In that sense, what your really need is to use a creational design pattern.

For my game, I use the Prototype pattern, which would make the code look similar to your first option (include an Interface variable, and make clones of it). However, depending on your needs, I think Factory Method can work as well.
> 0 votes

# Answer
Whether or not a "Weapon", a "Character", or the "World" (or some other more global concept) should contain a collection of bullets fired depends largely on how you want the bullets (or, generally, any object/concept) to be considered in your game.

Questions to ask:

* **Weapon**: Does the bullet exist as tied directly to the weapon? If the weapon changes or switches in some way during the bullets lifetime, will the bullet need to change as well? If so, a Weapon containing a list of bullets fired would make sense to ease the process of a Weapon change affecting its "children"
* **Character**: Does the bullet exist independent of the weapon, but heavily dependent on the Character/Agent firing it? If the Firing Character gets a "powerup" or moves or in some way changes, will those changes flow down to the bullets as well? Is there a maximum number of bullets a single character is allowed to fire or some other character-specific consideration for all bullets produced from the character?
* **World/Global Container**: Does the bullet exist independently from everything in the world? After firing, does it simply travel until it collides or dissipates? Is it more akin to a particle effect occuring in the world than an object with some dependence on another object?

To be clear, answering "yes" to any of these questions doesn't necessitate choosing that option. However, a set of bullets heavily dependent on per-frame changes to the weapon or character would be simpler as a collection held by that object.

To be general to the architectural problem at hand, this is true for any similar problem of "Should it be contained in a related object or simply lightly referenced?" The question of architectural dependency can be answered by looking at the desired functional dependency. In general, if an object is heavily dependent on some "parent" object, it might be wise for that "parent" to be a container. If an object is simply "produced" or lightly linked to some other object, it makes less sense for that object to need to be the container.
> 0 votes

---
Tags: architecture, design-patterns, oop
---


# Question
Title: Collision detection doesn't register until player sprite jumps
I have implemented a shooting mechanic into my game, and the act of shooting works fine. The shooting work is done in my "game1" class. The issue that arises is when I incorporate collision detection with the bullets and my enemies(zombies). For some reason, I can press shoot all day but none of the zombies will recognize the bullet. It isn't until I press jump with my sprite, that the bullets begin to register and kill the zombies. And jumping is the only way that I can get it to work, moving left or right doesn't do anything. I am going to post the relevant code below.

Zombie Collision code:

```
public void checkBulletCollision(List<Bullet> bullets)
{
   foreach (Bullet b in bullets)
   {
       if (BoundingBox.Intersects(b.BoundingBox))
       {
           isAlive = false;
           b.isVisible = false;
           bullets.Remove(b);
           break;
       }
   }
}

```

Shooting code in main game file:

```
public void UpdateBullets()
{
    foreach (Bullet b in bullets)
    {
        b.position.X += 10;
        if (b.position.X > 1020)
            b.isVisible = false;
    }
    for (int i = 0; i < bullets.Count; i++)
    {
        if (!bullets[i].isVisible)
        {
            bullets.RemoveAt(i);
            i--;
        }
    }
}

public void Shoot()
{
    Bullet newB = new Bullet(this);
    newB.LoadContent();
    newB.position = player1.position;
    newB.position.Y -= 10;
    newB.position.X += 10;
    newB.isVisible = true;
    if (bullets.Count < 1000)
        bullets.Add(newB);
}

```

Update code in main game file:

```
 protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            Exit();

        // TODO: Add your update logic here
        float deltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
        controls.Update();
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            Exit();

        //update all blocks in array
        for (int i = 0; i < blocks.Length; i++)
        {
            blocks[i].Update();
        }

        //block1.Update();
        //block2.Update();
        //block3.Update();
        //CheckCollisions();
        player1.Update(controls, gameTime, blocks);

        foreach (Zombie z in zombies)
        {
            if (z.isAlive)
            {

                z.Update(gameTime, blocks);

                z.getPlayerPosition(player1);
                z.checkBulletCollision(bullets);
            }

        }
        if (Keyboard.GetState().IsKeyDown(Keys.Space) && pastKey.IsKeyUp(Keys.Space))
        {
            Shoot();

        }

        UpdateBullets();

        pastKey = Keyboard.GetState();

        base.Update(gameTime);
    }

```

What could be the reason for this?

# Answer
Thanks to @wondra, he told me to look at the initialization of the y variable.

But this fixed the issue-

removing the line: newB.position.Y -= 10; from Shoot()

I guess the bullet became initialized when I was up -10 pixels.
> 1 votes

---
Tags: c#, xna, collision-detection, collision-resolution
---


# Question
Title: Mesa: Howto enable OpenGL 3.x functionality via extensions?
How can I enable OpenGL 3.x functionality via extensions? I'm new to OpenGL development under Linux. Currently I have:

```
#define GL_GLEXT_PROTOTYPES
#include <GL/osmesa.h>
#include <GL/glu.h>

```

My problem with Mesa and OpenGL 2.x is that I get an OpenGL "invalid value" error here:

```
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA32F_ARB, width, height, 0, GL_RGBA, GL_FLOAT, NULL );

```

because of `GL_RGBA32F_ARB`, it seems.

Background: I need the texture for a framebuffer object, and `GL_RGBA32F_ARB` for float data without clamping. My program works well using OpenGL 3.0 if I create the context with GLX.

# Answer
> 1 votes
I think that it's better to use GLEW to export all the extensions functionality. It's cross platform and allows you to write conditional code for different configurations.

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


title: How do I create a sound manager?

text:
# Question
Title: How do I create a sound manager?
I have a basic entity system in place. Now I want to add audio. I want to make a database class that watches over entities, pulls data out of them, and creates audio streams whenever necessary.

I'm using C++ and SDL2. What is a simple approach to this?

# Answer
The simplest way, assuming you have a bare bones component/entity/system architecture, is to create a Audio system and an AudioComponent. The AudioComponent would contain a reference (maybe just a string) to some audio and a corresponding "state" flag. As with other systems, the Audio system would scan entities, extract those that have an audio component and deal with the audio based on the state.

As you would likely need more than one audio snippet to be attached to an entity you could log these as a list of pairs; where the pair is a state and audio reference, but the rest still applies. You could put them in a map as well so there is a simple key lookup.

If you have a signals/events system later you can update the status of audio based on events; such as a collision. Although it might be better for the audio system at that point to just listen for events itself and extract only the audio source reference from the component.

The other method I can think is to forget the audio component altogether. This is a straight to the point implementation. Create an audio system that reacts to changes in entity states. For example, play a "hurt" sound when the players health drops compared to the last state and a death sound when it's suddenly 0.
> 1 votes

# Answer
This is a very broad question. Honestly, I would need some idea of how you set it up so far and a more specific idea of what you hope to accomplish in order to answer.

My best idea at the moment is create a base sound component with some way to retrieve sound information (`virtual sound_data getSound() =0;` as an example method). The constructer would add it to a list in a system somewhere, and that system would iterate through the list and get the sound data that way.

This isn't quite what you had in mind, but using messages or events to send information to an entity that generates sounds is probably a better idea.
> 0 votes

---
Tags: c++, audio, resource-management, entities
---


# Question
Title: lwjgl and slick util text over textured quad
So, I load a TrueTypeFont like this:

```
   private TrueTypeFont trueTypeFont;
   try {
        InputStream inputStream = ResourceLoader.getResourceAsStream("assets/fonts/main.ttf");

        Font awtFont2 = Font.createFont(Font.TRUETYPE_FONT, inputStream);
        awtFont2 = awtFont2.deriveFont(24f); // set font size
        trueTypeFont = new TrueTypeFont(awtFont2, true);

    } catch (Exception e) {
        e.printStackTrace();
    }

```

After that, I draw a textured quad, as one usualyy would and then, draw `trueTypeFont.drawString(this.x, this.y, this.text, Color.white);`. What this gives, however is far from text, this is what it does, the black is supposed to be text...

How to fix?

# Answer
You get the black boxes because you have to enable blending in OpenGL:

```
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

```

This because the textures drawn by Slick have transparency.
> 1 votes

---
Tags: opengl, textures, lwjgl, slick, text
---


# Question
Title: How do I measure a string that will be drawn with SpriteBatch?
Is there a way to measure width and height of an ever-changing string (a player's score, specifically)?

# Answer
Given

```
SpriteFont font;

```

Do this:

```
Vector2 size = font.MeasureString("Your String Here");

```
> 8 votes

---
Tags: c#, monogame, text
---


# Question
Title: How does super.render() call this method?
Today I was experimenting with adding different screens with `Scene2d` in `libgdx` and while doing so I became confused how `super.render()` in my `render()` method from my starter class (`MyGdxGame`) called `render()` in my `PlayScreen()` class. Basically I understand you use `super` to call methods, fields, invoke a super class constructor etc... however I don't see how my `Main class` witch `extends Game` is a subclass/derived class of my `PlayScreen class` witch simply `implements Screen`. In short I don't see how those two classes are related so that `super.render()` in `MyGdxGame` class can call `render()` in my `PlayScreen` class.

Also I looked at the API and `Screen` implements `ScreenAdapter` and `Game` implements `ApplicationListener` but I still don't see how that connects.

Starter class:

```
public class MyGdxGame extends Game {
    Game game;

    @Override
    public void create() {
        game = this;
        setScreen(new MainMenu(game));
    }

    @Override
    public void render() {
        super.render();
    }

    public void dispose() {
        super.dispose();
    }

    public void pause() {
        super.pause();
    }
}

```

PlayScreen class:

```
public class PlayScreen implements Screen {
    private static Player player;
    SpriteBatch batch;
    GameControls x;
    CollisionManager collisionManager;
    ArrayList<Tree> trees;
    Iterator itr;
    Enemy enemy;
    Animations animation;
    Game game;
    MainMenu mainMenu;

    public PlayScreen(Game game, MainMenu mainMenu) {
        this.game = game;
        this.mainMenu = mainMenu;
    }
// more code ...
}

```

# Answer
Your IDE of choice should have a way for you to navigate to the source for a specified class. For IntelliJ IDEA try moving your cursor to the Game class name that MyGdxGame extends and pressing CTRL + B. That should take you to the source for Game. Take a look at the override for render() that Game implements.

```
@Override
public void render () {
    if (screen != null) screen.render(Gdx.graphics.getDeltaTime());
}

```

It calls into the active screen object (set previously by setScreen(Screen)). That's how they are linked. :)

You can always reference the git repository as well, if that's easier for you in the future: https://github.com/libgdx/libgdx/tree/master/gdx/src/com/badlogic/gdx
> 1 votes

---
Tags: java, libgdx, inheritance
---


# Question
Title: What should I use for the event name when logging metrics with Flurry?
I'm working on a multiplayer game and I want to use Flurry to record game events.

In the game you can build, grow and train troops. In Flurry you can log an event (optionally with parameters).

It would be great to be able to track the progress of a player depending upon what kinds of things they build, grow and so on and at what experience levels they do that at, but I don't know whether it's best to just have different sets of events for different types of actions... like this:

```
NSDictionary *buildParams =
   [NSDictionary dictionaryWithObjectsAndKeys:
      @"Build_Type", @"Castle",
      @"EXP", @"234523", // Capture user status
      nil];

[Flurry logEvent:@"Build_Action" withParameters:buildParams];

```

And so on... so another for growing something, another for training, et cetera.

Or is it better to have one global type of record of an event like this:

```
NSDictionary *actionParams =
   [NSDictionary dictionaryWithObjectsAndKeys:
      @"Action", @"Build",
      @"Type", @"Castle",
      @"EXP", @"44234",
      nil];

[Flurry logEvent:@"Game_Action" withParameters:actionParams];

```

In this method all the data is stored in the one event type. I'm not sure which will give me the best result when it comes to funneling, segmentation, and all that?

# Answer
It sounds like you are trying to decide between a system where the `event` parameter describes a specific kind of event (a build event, a destroy event, a purchase event, et cetera) and one where the kind of event is encoded in the parameters and all events are "game events."

You should choose the first one. The second option discards information and useful querying functionality: when everything is a "game action," there is no point to even having that field in the data, and since everything is a game action there's no way you can usefully query using that field.

Flurry exposes the event name field for a reason. By making it a first-class citizen, it can perform storage or query optimizations on it. It also uses the event name as a way to associate the start and end times of timed events; if you record all your events with the same name, this becomes less useful.

Flurry's own documentation and example event set for a game agree with the pattern of using the event name to actually name each kind of event, as well.
> 1 votes

---
Tags: iphone, analytics, flurry
---


# Question
Title: Can the Shuriken particle system create particles with random shapes and sizes?
I want to create differently sized (but small, relative to the characters) dust clouds for player movement that move away from the player and fade away by shrinking.

This animated GIF from *Samurai Gunn* demonstrates the desired effect (observe the brownish clouds that appear as the player attacks).

Can the Shuriken particle system do this? It should randomly create the dust cloud at various shapes and sizes. I'm assuming I'd need to supply the system with a sprite sheet to select from? Or is this just easier/better achieved by using an animated sprite in the scene?

# Answer
Yes, it can.

A simple way of doing so would be to just set the particle size to "Random Between Two Constants" as described here, choosing two constants that work for you, and using the texture sheet animation module to refer into a texture where each row represents the animation of a particle (and setting the "Random Row" checkbox).

You could also just use an animated sprite, as you noted. It would give you more fine-grained control at the cost of less random / dynamic behavior (and could require more up-front work to author and tweak the animation). It's up to you.
> 4 votes

---
Tags: 2d, unity, particles, graphic-effects, shuriken
---


# Question
Title: What can I safely do with the MonoGame GraphicsDevice on multiple threads?
I'm working on a UI system that does it's processing on a separate thread. However, the results of this processing must end up on the GPU eventually.

A simplified overview of the system boils down to this step happening in the 'rendering phase':

1. Start at root widget (a widget is an object that controls what is rendered to the screen, and most importantly defines the hierarchical relation between controls).
2. Render widget to screen.
3. Iterate over all widget's children.
4. For each child go back to step 2.

When a widget is determined to be static (render output not changing over a period of time) the system must be able to choose to cache it in a texture in GPU memory (`RenderTarget2D`).

There are some other things that can be cached such as `VertexBuffer`s and `IndexBuffer`s.

Because the UI system does all its compution on a separate thead (to avoid slowing down the other game processes) I'm concerned about what methods I can call on anything other than the game's rendering thread.

Concrete questions:

* What communication with the graphics device can be done from a separate thread?
* If the above depends on the card or drivers, how can I determine whether it supports those actions?

# Answer
> 3 votes
Very little.

MonoGame doesn't provide any explicit thread-safely guarantees about `GraphicsDevice` that I can see, and as such you should assume it is *not* thread-safe in any way.

For the most part, if you access the device from a single thread at a time (using your own synchronization primitives) you'll be "safe-ish" (although you may run into problems where running a different platforms gives you wildly different results due to different graphics APIs), but there are a handful of threading-related bugs in MonoGame's code (for example, while glancing through the code for this question I saw several instances where events are raised without caching local copies, which creates a potential threading bug).

You're better off adopting a model where you can do all your work in your background threads using your own data, and then setting a flag or putting the results of that work into a queue that the render thread consumes to do the actual graphics device work necessary.

---
Tags: xna, monogame
---


# Question
Title: HLSL - can't get texture to wrap or mirror
I'm currently converting an app from XNA to SharpDx and I'm therefore upgrading my shaders to version 4 (vs\_4\_0/ps\_4\_0).

When using this sampler:

```
SamplerState MySampler
{
    Filter = MIN_MAG_MIP_LINEAR;
    MinFilter = Anisotropic;
    MagFilter = Anisotropic;
    MipFilter = Linear;
    AddressU = Wrap;
    AddressV = Wrap;
};

```

Like this:

```
float3 color = DiffuseColor * Texture.Sample(MySampler, input.UV.x);

```

I get clamping instead of wrapping.

If I write the code like this:

```
    float3 color = DiffuseColor * Texture.Sample(MySampler,
        float2(frac(input.UV.x),frac(input.UV.y)));

```

Then I do get proper wrapping - but I'd like to declare that in the sampler insted, so what am I doing wrong?

Full source code:

```
float4x4 World;
float4x4 View;
float4x4 Projection;
float3 CameraPosition;
float4 ClipPlane;
float3 LightingDirection = float3(-10, 20, 5);

bool DoShadowMapping = false;
float4x4 ShadowViewProjection;
float ShadowMult = 0.3f;
float ShadowBias = 0.001f;
texture2D ShadowMap;
sampler2D shadowSampler = sampler_state {
    texture = <ShadowMap>;
    minfilter = point;
    magfilter = point;
    mipfilter = point;
};

Texture2D Texture;

SamplerState MySampler
{
    Filter = MIN_MAG_MIP_LINEAR;
    MinFilter = Anisotropic; // Minification Filter
    MagFilter = Anisotropic; // Magnification Filter
    MipFilter = Linear; // Mip-mapping
    AddressU = Wrap;
    AddressV = Wrap;
};

float3 DiffuseColor = float3(1, 1, 1);
float3 AmbientColor = float3(0.4, 0.4, 0.4);
float3 LightColor = float3(0.8, 0.8, 0.8);
float SpecularPower = 32;
float3 SpecularColor = float3(1, 1, 1);

struct VertexShaderInput
{
    float4 Position : SV_Position;
    float2 UV : TEXCOORD0;
    float3 Normal : NORMAL0;
};

struct VertexShaderOutput
{
    float4 Position : SV_Position;
    float2 UV : TEXCOORD0;
    float3 Normal : TEXCOORD1;
    float3 ViewDirection : TEXCOORD2;
    float3 WorldPosition : TEXCOORD3;
    float4 ShadowScreenPosition : TEXCOORD4;
    float4 PositionCopy  : TEXCOORD5;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output = (VertexShaderOutput)0;

    float4 worldPosition = mul(input.Position, World);
    float4x4 viewProjection = mul(View, Projection);

    output.WorldPosition = worldPosition;
    output.Position = output.PositionCopy = mul(worldPosition, viewProjection);

    output.UV = input.UV;
    output.Normal = mul(input.Normal, World);
    output.ViewDirection = worldPosition - CameraPosition;
    output.ShadowScreenPosition = mul(worldPosition, ShadowViewProjection);

    return output;
}

float2 sampleShadowMap(float2 UV)
{
    if (UV.x < 0 || UV.x > 1 || UV.y < 0 || UV.y > 1)
        return float2(1, 1);
    return ShadowMap.Sample(MySampler, UV).rg;
}

float4 PixelShaderFunction(VertexShaderOutput input) : SV_Target
{
    // Start with diffuse color
    float3 color = DiffuseColor * Texture.Sample(MySampler, float2(frac(input.UV.x),frac(input.UV.y)));

    // Start with ambient lighting
    float3 lighting = AmbientColor;

    float3 normal = normalize(input.Normal);

    // Add lambertian lighting
    lighting += saturate(dot(-LightingDirection, normal)) * LightColor;

    float3 refl = reflect(-LightingDirection, normal);
    float3 view = normalize(input.ViewDirection);

    // Add specular highlights
    lighting += pow(saturate(dot(refl, view)), SpecularPower) * SpecularColor;

    if (DoShadowMapping)
    {
        float realDepth = input.ShadowScreenPosition.z / input.ShadowScreenPosition.w - ShadowBias;

        if (realDepth < 1)
        {
            // Sample from depth texture
            float2 screenPos = input.ShadowScreenPosition.xy / input.ShadowScreenPosition.w;
            float2 shadowTexCoord = 0.5f * (float2(screenPos.x, -screenPos.y) + 1);

            float2 moments = sampleShadowMap(shadowTexCoord);

            // Check if we're in shadow
            float lit_factor = (realDepth <= moments.x);

            // Variance shadow mapping
            float E_x2 = moments.y;
            float Ex_2 = moments.x * moments.x;
            float variance = min(max(E_x2 - Ex_2, 0.0) + 1.0f / 10000.0f, 1.0);
            float m_d = (moments.x - realDepth);
            float p = variance / (variance + m_d * m_d);

            lighting *= clamp(max(lit_factor, p), ShadowMult, 1.0f);
        }
    }

    // Calculate final color
    float3 output = saturate(lighting) * color;

    return float4(output, 1);
}

float4 PixelShaderFunctionClipPlane(VertexShaderOutput input) : SV_Target
{
    clip(dot(float4(input.WorldPosition,1), ClipPlane));
    return PixelShaderFunction(input);
}

float4 PixelShaderFunctionDepthMap(VertexShaderOutput input) : SV_Target
{
    // Determine the depth of this vertex / by the far plane distance,
    // limited to [0, 1]
    float depth = clamp(input.PositionCopy.z / input.PositionCopy.w, 0, 1);

    // Return only the depth value
    return float4(depth, depth * depth, 0, 1);
}

technique TechStandard
{
    pass Pass1
    {
        SetGeometryShader(0);
        SetVertexShader(CompileShader(vs_4_0, VertexShaderFunction()));
        SetPixelShader(CompileShader(ps_4_0, PixelShaderFunction()));
    }
}

technique TechClipPlane
{
    pass Pass1
    {
        SetGeometryShader(0);
        SetVertexShader(CompileShader(vs_4_0, VertexShaderFunction()));
        SetPixelShader(CompileShader(ps_4_0, PixelShaderFunctionClipPlane()));
    }
}

technique TechDepthMap
{
    pass Pass1
    {
        SetGeometryShader(0);
        SetVertexShader(CompileShader(vs_4_0, VertexShaderFunction()));
        SetPixelShader(CompileShader(ps_4_0, PixelShaderFunctionDepthMap()));
    }
}

```

# Answer
Unfortunately, the toolkit doesn't support inline definition of sampler in the shader (as legacy fx does). In order to use a sampler, you need to:

1. Simply declare a plain sampler state in hlsl: `SamplerState MySampler;`
2. Pass a sampler state from C# available in `GraphicsDevice.BlendStates` (or create your own) and set it on the parameter `effect.Parameters["MySampler"]`

Try to master a Graphics Debugger (Visual Studio 2012/2013 is also coming an integrated Graphics Debugger, but if you have a NVidia card, prefer using NSight - or any other HW specialized debugger) as you will be able to see exactly what is going on on the GPU, which resource is bound, what is inside your constant buffers, what is on each render target/texture...etc. It is often helping a lot to quickly spot this kind of issues.
> 2 votes

---
Tags: hlsl, sharpdx
---


title: Multiple animations on flash timeline

text:
# Question
Title: Multiple animations on flash timeline
I am working on a game inside Flash with ActionScript 3.

I have a horse game object with different animations for Walk, Run and so on. I have never worked with different animation types with Flash timeline. I want to have all these animations setup on the timeline at different key frames with different labels for each animation.

After setting this up, how do I select a specific animation?

Currently what I have setup inside Flash does not seem to work. When the walk animation is about to end, I want it to loop and start from the beginning. Currently what it does is it plays all the animations set on the timeline and not just the walk animation.

```
horseOne.gotoAndPlay("startwalk");

if(horseOne.currentLabel == "endwalk"){
    horseOne.gotoAndPlay("startwalk");
}

```

Please refer to the image of my fla timeline.

# Answer
> 0 votes
Currently your script plays the animation and immediately checks if the currently label is "endwalk" only once.

What you need to do is use an onEnterFrame event and check what frame the animation is on.

That would fix your current issue.

You could also put simple actions on the frames themselves without having to use events.

---
Tags: flash, actionscript-3
---


title: XNA Veiwing cubes behind others

text:
# Question
Title: XNA Veiwing cubes behind others
I am learning 3D at the moment. It is going well but I am stuck on the viewing of the camera.

I have two cubes, one next to each other made up of vertices, all the faces/triangles in the cubes are clockwise vertics so that when you move around the box, only 1 or two sides are visible at once. But, here's the problem, if I look at the cubes from the right, I can see a face of the cube that is further away. Like pictured below,

What would be the best way to deal with this, and are there any tutorials that could help me please?

Thanks in advance

# Answer
> 1 votes
You can set up your graphics device to do a depth-test to compute which cube is in front of the other cube and to not show parts that should be obstructed.

To do this in XNA add this right before you draw the cubes.

`GraphicsDevice.DepthStensilState = DepthStensilState.Default`

Note that some XNA components, such as the SpriteBatch change your graphics device states. So you need to make sure your graphics device states are correct each frame before you draw something that depends on it.

Edit: for more info please see this excellent post by our all-time-XNA-god Shawn Hargreaves

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


title: Infinite Jumper Snow Effect

text:
# Question
Title: Infinite Jumper Snow Effect
I wish to achieve a snowing effect on my game. The game is made in LibGDX and im using ParticleEmitter. I created a snow effect in ParticleEditor which consists in a line which spawns snow flakes. The problem is:

First, and the most important, since the game movement is vertical (its a jumper), if i just place the line above the screen, the jumping makes it look unnatural since when im jumping up, and the camera follows me, the particle emitter also has to move up, and the snow flakes are spawned with a bigger vertical distance; And when Im going down from the jump, a section of closer snowflakes is spawned due to that occurence. That makes the snow visually inconsistent.

Second, i wanted the snow to show up filling the screen from the start, instead of it starting to follow when the emitter is started.

To try to fix the first problem, i made the snow screen static, but it looks horrible, i really want the feeling that the snow is falling and my character is going up against it.

Any ideas how to achieve such an effect?

# Answer
> 1 votes
Another option would be to spawn a fixed number of snow particles and make them teleport to the top when they reach the bottom of the screen. This is trivial but in your case it should work fine.

# Answer
> 2 votes
Does the screen have game interaction or impact? Is it necessary to draw it in the same pass as the rest of the world, or even with the same camera for that matter? If the snow is mostly acting as an aesthetic overlay then do your render in two passes:

1. Begin render. Render your world using the dynamic world camera. End render.
2. Begin snow render. Render your snow using a static camera. End render.

**EDIT**

I'd aim for something like this:

The black box represents the world for your jumper. The red box represents the small world-bound dynamic camera that follows your character. The blue box represents the snow camera which is larger than what the world camera will ever perceive at once, and which remains static.

I don't see any reason this kind of setup wouldn't give you the effect you're after, but I'm happy to discuss it with you! :)

**EDIT 2**

I forgot to address your jumping issue, sorry. You want a basic version of parallax scrolling there. What you could do is adjust the snow camera in the opposite direction of the jumper's velocity. So as he jumps up the snow will move down in tandem. Just make sure your snow camera size allows edge room for max jump distance.

# Answer
> 1 votes
Try not to think in screen position, but world position. Place the emitter above the camera position with some offset each frame and spawn particles from there.

# Answer
> 1 votes
Without being able to modify the position of the individual particles, I don't think you're going to be able to achieve what you're looking for.

Take a look at a live wallpaper that I made, source available here. What I do here is I track each particle individually, and I can move them according to the rules set by the appropriate system. If a particle hits the bottom, it gets spawned at the top.

A few edits and you could achieve what you're looking for:

* Add wind direction and a "sway" (could just be a sine wave with variable speed).
* Make it so that particles hitting the bottom spawn at the top.
* Make the spawn area have random y-position, so that the particle don't follow the exact pattern.
* Add a "speed" modifier, make it so that particles can go both ways at variable speed. Then plugin a negative speed as your character begins to fall, with speed being proportional to your character speed.

Do note that the libraries I use *may* be outdated. I'm also not certain if my entity-component structure would be compatible with your existing game structure.

# Answer
> 0 votes
Not familiar with LibGDX Particle Emitters especially, but according to this site one of the options for a particle is **attached**, which makes the

> particles stay the same distance away from the emitter regardless of movement

This is somewhat confirmed by the official github-wiki, though the documentation is not 100% clear too me regarding this point. The Options are described at the bottom of the page just before *loading Particle Effects in your game* and described as:

> **Attached:** Means existing particles will move when the emitter moves.

If I understoond you correctly, this is what you're asking for.

For your information: Can also be found as first result when googleling "LibGDX move particles with emitter".

---
Tags: libgdx, particles
---


# Question
Title: How to detect if a ball will collide with another, and the normal vector of the collision?
So I have a 2D game involving balls (circles) colliding. I want to be able to detect if two balls will collide before it happens, and the normal vector of the collision if a collision is going to happen. Take a look at the below picture:

Essentially a normalized vector represented by the red arrow is what I am interested in knowing. How can I figure that out any frame most efficiently, given I know the following:

* The blue ball has a current initial velocity
* The ball ball is pulled down by a constant gravity
* The green ball does not move
* The sizes and location of both balls

# Answer
**Chapter 1: Movement Prediction for Beginners**

If you know the point of contact and especially the positions of the balls at contact, you can simply normalize the vector

```
//pseudocode
normalize ( blue.position - green.position )

```

Now for the collision prediction itself:

In every update the gravity vector is applied to your current velocity. To get out mathematics this means

```
velocity(0) = initialVelocity
velocity(t+1) = velocity(t) + gravity

```

where t is the number of Updates that occured after the start of the calculation. Implementing this in code would look like this:

```
//pseudocode
function predict()
    //I cheat a bit. You have to think of a smart way to copy in your language
    var bluePredict = copy(blue)
    while true do
        //If blue is completly below green and moving downwards, we can't possible hit green anymore.
        if blue.position.y+blue.radius < green.position.y-green.radius and blue.velocity.y < 0 do
            break;
        end

        //We don't actually add the whole G-Vector, but only the one applied in the update-timeframe
        bluePredict.velocity = bluePredict.velocity + gravity*deltaTime;
        bluePredict.position = bluePredict.position + bluePredict.velocity;
        if detectCollision(bluePredict, green) do
            return normalize (bluePredict.position - green.position);
        end
    end
end

```

Call predict and get the normalized vector back.

**Warning** This method does not interpolate the point of contact. Your balls will most likely intersect on collision and blue can even pass through green if blue moves fast enough. This is however a common problem of Collision detection and not easily tackled. Specify a language and/or Developmentarea (like Unity for example) and I can give you more detailed help. If you have questions about the interpolation, please feel free to comment.

---

**Chapter 2: Interpolation for Beginners**

**Note:** The following chapter is partially based on this document and this document.

A common problem with collission detection is, that the blue disc "penetrates" the green disc without colliding with it. Take a look at the following picture:

The blue arrow denotes both the direction and speed of the blue disc, it is also often known as velocity-vector.

1. The disc moves slow enough to collide with the green disc. Normal vector and Position of the collission are known good enough (Inaccuracies come because of my bad Paint.NET-Skills).
2. The disc moves slow enough to collide with the disc, but too fast for the correct result. For the Programm, it looks like the blue disc collided on the other side of green and it computes a wrong normal vector.
3. Worst case. Blue moves so fast that within one updatestep it is behind green, without triggering a collission.

So is fast movement necessarily bad? **NO!** At least not with caution.

What we used in chapter 1 is known as **Periodic Interference Test (PIT)**. It has some great advantages (like speed), but also some great disadvantages (see picture).

The solution: **Predicted Instant of Collision (PIC)**

*Please take a look at this question at stackoverflow, which describes your problem in 3D-Space (but should be easily convertible, as nobody actually cares for the size of the vector in this case.*
> 3 votes

---
Tags: collision-detection
---


title: terrain not properly rendering

text:
# Question
Title: terrain not properly rendering
I'm extending the terrain quad with resources from various tutorials and have the following code:

```
public class WorldTerrain extends TerrainQuad {

    public static final String NAME = "terrain";
    public static final int PATCH_SIZE = 9;
    public static final int TOTAL_SIZE = 33;
    private static Vector3f spawnLocation = new Vector3f(13, 3, 16);
    private Material mat_terrain;

    private void loadText(AssetManager assetManager) {
        /**
         * 1. Create terrain material and load four textures into it.
         */
        mat_terrain = new Material(assetManager,
                "Common/MatDefs/Terrain/Terrain.j3md");

        /**
         * 1.1) Add ALPHA map (for red-blue-green coded splat textures)
         */
        mat_terrain.setTexture("Alpha", assetManager.loadTexture(
                "Textures/Terrain/splat/alphamap.png"));

        /**
         * 1.2) Add GRASS texture into the red layer (Tex1).
         */
        Texture grass = assetManager.loadTexture(
                "Textures/Terrain/splat/grass.jpg");
        grass.setWrap(WrapMode.Repeat);
        mat_terrain.setTexture("Tex1", grass);
        mat_terrain.setFloat("Tex1Scale", 64f);

        /**
         * 1.3) Add DIRT texture into the green layer (Tex2)
         */
        Texture dirt = assetManager.loadTexture(
                "Textures/GrassRocky.png");
        dirt.setWrap(WrapMode.Repeat);
        mat_terrain.setTexture("Tex2", dirt);
        mat_terrain.setFloat("Tex2Scale", 32f);

        /**
         * 1.4) Add ROAD texture into the blue layer (Tex3)
         */
        Texture rock = assetManager.loadTexture(
                "Textures/Terrain/splat/road.jpg");
        rock.setWrap(WrapMode.Repeat);
        mat_terrain.setTexture("Tex3", rock);
        mat_terrain.setFloat("Tex3Scale", 128f);
    }

    private static float[] generateHeightMap(AssetManager assetManager) {
        AbstractHeightMap heightmap = null;
        try {
            heightmap = new HillHeightMap(1024, 100, 2, 10, 1);
        } catch (Exception ex) {
            Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
        }
        return heightmap.getHeightMap();
    }

    public static Vector3f getSpawnLocation() {
        return spawnLocation;
    }

    public WorldTerrain(Interface app) {
        super(NAME, PATCH_SIZE, TOTAL_SIZE, generateHeightMap(app.getAssetManager()));
        loadText(app.getAssetManager());
        setMaterial(mat_terrain);

        setModelBound(new BoundingBox());
        setLocalTranslation(32f, 0f, 32f);

        List<Camera> cameras = new ArrayList<Camera>();
        cameras.add(app.getCamera());

        RigidBodyControl landscape = new RigidBodyControl(0.0f);
        addControl(landscape);

```

and the interface:

```
public class Interface extends SimpleApplication {

  private TerrainQuad terrain;
  Material mat_terrain;

  public static void main(String[] args) {
    Interface app = new Interface();
    app.start();
  }

  @Override
  public void simpleInitApp() {
    flyCam.setMoveSpeed(50);

    terrain = new WorldTerrain(this);
    rootNode.attachChild(terrain);
  }

```

This gives the following result: as you can see large parts of the terrain are not rendering (ignore the weird mountains those are only tests). If I move the camera around these holes move around suggesting it's a rendering problem in the terrain. Anybody who knows how to fix?

# Answer
Trying changing

```
setModelBound(new BoundingBox());

```

to

```
BoundingSphere bs = new BoundingSphere();
bs.setCenter(new Vector3f(32,0,32));
bs.setRadius(1000000);
setModelBound(bs);

```

Edit Larethian (short Version) (confirmed working on example code):

```
setModelBound( new BoundingSphere(1000000, new Vector3f(32f, 0f, 32f)) );

```

As pointed out in the comments below a bounding volume with this large of a radius shouldn't really be used...although the fact that it is working gives you an idea of what the original problem was. If you wish to use bounding spheres realistically what you can do is try setting the radius to be "PATCH\_SIZE".
> 3 votes

# Answer
Maybe they are being culled for being partly outside the view area? Might be worth looking at the code selecting what you render instead of the terrain code.

(Or setting near and far plane differently and/or moving the camera further away since it seems the engine is not a custom solution)
> 0 votes

---
Tags: java, rendering, terrain, terrain-rendering, jmonkeyengine
---


# Question
Title: Gamemaker vs Unity2d - Speed of Development
* I know coding, so programming is not a problem
* Money is not a problem at all, I can get both GameMaker Master Collection and Unity Pro

I want to make a 2d game.

So which one is better for speed of development? On which one would I be able to finish my project earlier?

# Answer
This fully depends on the developer at hand and how well the person knows the coding language. Assuming you can definitely do the art side of things, I'll go ahead and list some pros and cons of both engines.

Game Maker Studio:

Pros:

* Very, very fast prototyping.
* Very beginner-friendly coding language called GML.
* Extremely welcoming community.

Cons:

* The engine is by far more limited than Unity3D.
* You have to purchase all of the exports besides Windows.

Unity3D:

Pros:

* Incredibly large community. There are a crazy amount of tutorials to be seen/read.
* Very fast engine in terms of the language and in execution.
* Lots of staff support and an abundance of features.
* Many, MANY more platforms that you can release to without having to pay extra.

Cons:

* Overwhelming. Unity is very overwhelming for a lot of people.
* Takes a bit of time to get used to. The UI is difficult to get the hang of.
* The programming language is a little more difficult to get a grip on.

Game Maker Studio will get the job done sooner but Unity3D will get the job done better. Take your pick.
> 7 votes

---
Tags: unity, game-maker
---


# Question
Title: UDP Netcode Architecture for Fighting Game
I am programming a fighting game that uses a UDP client/server architecture for multiplayer. The server can handle multiple clients, two of which (or one being the server) are playing and the rest are watching and chatting. I would prefer to use UDP for everything, including: player input from client, player state from server, and chat going both ways.

My concern is keeping the order of the player inputs in sync from the client to the server. Since moves involve a specific sequence of inputs (e.g., Left,Left-down,Down,Light Punch), if the server processes them out of order then the game is ruined. What is a good approach for dealing with packet loss and packets arriving out of order in this case?

I have considered having a linked list of outgoing packets in the client and server. With each step the list is traversed and unsent packets are sent, and if an ack packet(one I program the receiver to send back) was received for a particular packet (which I can identify simply with an integral value) then the outgoing packet is removed from the list. However, this does not guarantee order of delivery. Perhaps the server could keep a queue of inputs and evaluate another integral value in the packet for each input, organizing them into the correct order.

I'm not entirely sure, if someone could point me in the right direction I would be very grateful. I have working client and server chat code but before I starting seriously designing the network architecture I wanted to see what others have to say.

# Answer
> 4 votes
One reason you might prefer UDP over TCP is to save bandwidth. The drawbacks are obvious: if data gets lost on the way neither the sender nor the recipient will notice. In addition, the order of packages may change if they take different routes in the network, which would result in clients seeing wrong "combos" (e.g. Left-Down-Punch instead of Down-Left-Punch). In certain cases a client might also receive a single package multiple times (Down-Down-Left-Punch).

In scenarios where these drawbacks are acceptable and large amounts of data are sent, (e.g. video/audio streaming) UDP is a valid choice. Here errors in the data transfer will only cause minor and short-lived artifacts in your media stream. It seems to me, however, that in your case a connectionless protocol like UDP ist not reasonable. What you are trying to do is deliberately not use the automated control mechanisms TCP brings along and then reimplement them yourself because you actually need them. Therefore I wonder what you are trying to achieve. Why not stick with TCP that takes care of everything: Monitored data transfer that ensures your data packets are delivered in the right order, with automatic resend requests in the event of data loss.

# Answer
> 1 votes
If I understand what you're trying to achieve, you want your two active clients to send key strokes to your server, and you want your server to process them in the right order.

If you have to encode a key code and possibly some timestamp to know exactly when the touch was pressed (timing may be important for combos), I guess it should fit in 4 bytes/key (4 bits for key number + 28 bits for whatever timestamp you're using).

Since a UDP trame can safely contains 512 bytes of payload (according to https://stackoverflow.com/questions/1098897/what-is-the-largest-safe-udp-packet-size-on-the-internet), it won't have any impact on your communication speed if you send 1 byte or 512 at a time.

So, the solution I would try to implement is:

On the client:

* Implement your own packet number; No need to be fancy here: just use a 4 bytes unsigned integer that you increment for each packet sent
* When you send a new keystroke, what you actually send is: The packet number, \[4 bytes\], the keycode/timestamp you want to send \[4 bytes\] and the 126 previous keycode/timestamps \[4\*126 bytes\].

On the server:

Whenever a packet is received:

* If its packet number is lower than the last processed packet number for the same client, you drop it
* If its packet number is greater than the last processed packet number for the same client, you process as many keycode/timestamps as needed (i.e., if you're receiving packet 8 and previous processed packet was 6, you process the two more recent key/time information; if the packet 7 arrives later, you drop it since its payload has already been processed).

As long as you don't lost 127 packets in a row, it should work; using timestamps should help you to conserve the continuity. (also, you may be able to use less than 4 bytes for each keycode/timestamp pair, and so have more redundancy).

---
Tags: networking, input, synchronization, udp, fighting-game
---


# Question
Title: Mandelbrot generation using custom HLSL shader in XNA
So I made a Mandelbrot generator in C# and I'm learning about HLSL and custom shaders in XNA (For a college course). I was hoping to do the mandelbrot calculations on the graphics card to make them faster. This is the code that I have so far (only part of my .fx file).

```
// sx, sy is the upper left corner of the mandelbrot coordinate area
// sw,sh is the width and height of the mandelbrot coordinate area.
float sx = -2.5, sy = -1, sw = 3.5, sh = 2;
float width, height; // Size of the quad I'm drawing this to

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    // TODO: add your pixel shader code here.
    float count = 500;
    // Convert from the drawing space to madelbrot space
    float tx = (input.UV.x / width) * sw + sx;
    float ty = (input.UV.y / height) * sh + sy;
    float tsx = tx, tsy = ty;

    // Find the divergence count
    for(float i = 0; i > 500; i++)
    {
        // Get the next location
        tx = tx * tx - ty * ty + tsx;
        ty = 2 * tx * ty + tsy;
        // This is the part I'm having trouble with
        count = (tx * tx + ty * ty <= 4 ? count : min(count, i));
    }
    // Calculate and return a color based on the count obtained
    float factor = count/500;
    return float4(1-factor, 1-factor, 1-factor, 1);
}

```

I think the issue has to do with having a ternary operation inside of a loop. The issue is that "factor" always results in having a value of 1, which means count obtains a value of 500. So my looping does nothing. I believe that my code is theoretically correct.

Maybe HLSL doesn't deal with the ternary operator very well? Does anyone have information about how they work or any limitations when using them?

Any comments are welcome.

# Answer
Your loop has a bad conditional. It is never true, so the loop is never entered. This:

```
for(float i = 0; i > 500; i++)

```

Should be

```
for(float i = 0; i < 500; i++)

```

(Change **`>`** to **`<`**.)

I haven't run your code, so I'm not sure if there are other issues.

---

I've compiled your code, and it seems to work with the above fix (I'm not sure if the maths is right, but it displays something nice).

If you're using `ps_2_0` you have to crank the number of iterations down ridiculously low (6 instead of 500) to fit in the instruction limit.

If you switch to `ps_3_0` (the highest shader model XNA supports), you can do a few more iterations thanks to the higher instruction limit. But shader model 3 also supports *real* looping, which allows for significantly more iterations (~250). Decorate (MSDN) your loop like so:

```
[loop] for(float i = 0; i < 250; i++)

```

To use shader model 3, you'll need to enable HiDef mode. If you do what I did and draw with `SpriteBatch`, you'll need to follow these instructions to supply a vertex shader.
> 3 votes

# Answer
```
#define Iterations 254
float2 Pan;
float Zoom;
float Aspect;
float4x4 MatrixTransform;

void SpriteVertexShader(inout float4 color    : COLOR0,
                    inout float2 texCoord : TEXCOORD0,
                    inout float4 position : SV_Position)
{    position = mul(position, MatrixTransform);    }

float4 Pixel_Shader(float2 texCoord : TEXCOORD0) : COLOR0
{
    float2 c = (texCoord - 0.5) * Zoom * float2(1, Aspect) - Pan;
    float2 v = 0;

[loop] for (int n = 0; n < Iterations; n++)
    { v = float2(v.x * v.x - v.y * v.y, v.x * v.y * 2) + c;   }

    return (dot(v, v) > 1) ? 1 : 0;
}

technique
{
    pass
    {
    VertexShader = compile vs_3_0 SpriteVertexShader();
    PixelShader = compile ps_3_0 Pixel_Shader();

    }
}

```

Does a very decent monochrome pass using the 255 loops. Props to Shawn Hargreaves, XNA4.0 (PS\_3\_0) ready version mangled by me.
> 0 votes

---
Tags: xna, c#, hlsl
---


# Question
Title: Not able to change the background of the scene in cocos2dx android
I have started Game Development using Cocos2d-x. And started with HelloWorld sample game. I am able to run this sample game. But when I try to change the Background Color, I am getting error in

```
 HelloWorldScene.h
    The type 'HelloWorld' must implement the inherited pure virtual method 'cocos2d::CCRGBAProtocol::setOpacity'

Changes:
class HelloWorld : public cocos2d::CCLayerColor

```

and also in

```
 **HelloWorldScene.cpp**

    Invalid arguments '
    Candidates are:
    bool initWithColor(const cocos2d::_ccColor4B &, ?, ?)
    bool initWithColor(const cocos2d::_ccColor4B &)
    '
   **Changes:**
   CC_BREAK_IF(!CCLayerColor::initWithColor(ccc4(255,255,255,255)));

```

I am new for Cocos2d-x and also for C++. Is there any thing left to include or what?

# Answer
> -1 votes
in my case my problem was solved after writing this for background color change to white glClearColor(1.0,1.0,1.0,1.0);

---
Tags: c++, android, cocos2d-x
---


# Question
Title: How do I access the "product name" in Unity 4?
I would like to access my app name in a Unity C# script; I've found `PlayerSettings.productName`, however it requires `UnityEditor`, which is only available in the editor.

So, in a normal application, how am I supposed to access its name, as it appears in the "product name" field of the player settings?

* It must be cross-platform
* retrieving **the executable name** (or directory) **does not count**
* **duplicating data does not count** (obviously I can create a `const` with the same name, the whole point of this question is to avoid doing that)

(since the goal is to avoid duplicating data, backwards techniques such as having a `const`, and using that `const` to update `PlayerSettings.productName` **is ok**, as long as they require no extra step, i.e. they can be made to "run" automatically at compile time)

# Answer
> 2 votes
I don't believe it's possible simply, i.e. there's not an API in some UnityEngine class that will let you get it at runtime that you simply haven't found.

There are two ways of going about this really. The first is to slave the productName variable to a static constant in your scripts that you can also access at runtime. I.e. add a static readonly string to a game class/script. Then add a step to your build process (which exists in the context of the Editor) that forcibly sets PlayerSettings.productName to be the same as your own value.

The second way would be to save a data file in Resources with your product name in it as part of your build process. As in, as a pre-build step, look up what PlayerSettings.productName is and save it out into a text file in an Assets/Resources sub-folder called 'productName.txt'. Then at runtime, call `Resources.Load("productName") as TextAsset`, and parse the productName out of the text asset.

Personally I'd say that both approaches are more work than they're worth, and you should simply have two copies of the name. Maybe add an Editor verification function that you can habitually call to double check that they're still in-sync during development and prior to making a release.

# Answer
> 0 votes
```
//Save bundleVersion in PlayerPrefs and access it from anywhere
//This class must be in "Editor" folder to work

using UnityEngine;
using UnityEditor;
using System.IO;

[InitializeOnLoad]
public class BundleVersionChecker
{

    static BundleVersionChecker ()
    {
        string bundleVersion = PlayerSettings.bundleVersion;
        PlayerPrefs.SetString("Key_AppBundleVersion", bundleVersion);
    }

}

```

# Answer
> -1 votes
I thought you were looking for:

```
UnityEditor.PlayerSettings.productName

```

But I then realized you want this at runtime. Because the project needs to keep the same name as the folder its in, you can use something like this.

```
public string GetProjectName() {
    string[] s = Application.dataPath.Split('/');
    string projectName = s[s.Length - 2];
    return projectName;
}

```

---
Tags: unity
---


# Question
Title: How can I trigger an event each time the rotation of my rigidbody2D is at a given value?
I would like to trigger an event each time my rigidbody2D is at a particular value.

The event should only be triggered once for each given value per complete object revolution.

Initial attempts at achieving this have resulted in the following method which checks against an array of values, logging an event and incrementing an index when the value has been passed.

```
static readonly float[] angles = new float[] { 90f, 180f };
int angleIndex = 0;

void CheckForTrigger()
{
    if (rigidbody2D.IsSleeping())
        return;

    var rotation = Mathf.Abs(rigidbody2D.rotation);

    if (rotation % 360f >= angles[angleIndex])
    {
        Debug.Log("Fire");

        angleIndex++;

        if (angleIndex== angles.Length)
            angleIndex= 0;
    }
}

```

This suffers from a couple of issues:

* Floating point inaccuracy means that values close to 360f will often be missed (e.g. 359f)
* Fire will be logged each frame between the last and first value (i.e. between 180f and 90f)

Does anyone have any advice for approaching this problem and improving the above method?

# Answer
This is somewhat long and might not work well if they are rotating faster than the deadzone value, but then you can just increase the deadzone. I've commented the below code: //declare new array of the dataclass we made below

```
static AngleData[] angleDatas = new AngleData[] { new AngleData(90f), new AngleData(180f) };
int angleIndex = 0;
//the deadzone is how close it has to be to the target angle to fire, and how far it needs to be to 'reset itself'
float deadzone = 15f;
void CheckForTrigger()
{
    if (rigidbody2D.IsSleeping())
        return;

    var rotation = Mathf.Abs(rigidbody2D.rotation) % 360f;
    //we get the current AngleData
    AngleData currentAngle = angleDatas[angleIndex];
    //find the absolute difference from the target to the current rotation
    float difference = Mathf.Abs(rotation - currentAngle.angle);
    //if we haven't 'used up' this angle for this revolution
    if (currentAngle.available)
    {
        //if it's within the deadzone
        if (difference < deadzone)
        {
            Debug.Log("Fire:" + currentAngle.angle);
            currentAngle.available = false;
        }
    }
    else
    {
        //if it's outside the deadzone
        if (difference > deadzone)
        {
            currentAngle.available = true;
            //move on to next angle in list
            angleIndex = (angleIndex + 1) % angleDatas.Length;
        }
    }
}
public class AngleData
{
    public float angle;
    public bool available = true;
    //could have an event declared here if you want specific event methods to be fired for every different angle
    public AngleData(float angle) { this.angle = angle; }
}

```

Let me know if you have any questions or if it doesn't work as intended.
> 1 votes

---
Tags: unity, rotation, rigid-body-dynamics
---


# Question
Title: How do you replace a tile in a Tileset in TILED without destroying entire map?
I want to make an early version of a map for my game but then I want to be able to change some of the tiles for new and improved ones without destroying my entire map...is this possible?

# Answer
> 5 votes
The .tmx data format stores each tile in the map as a reference to a specific tile on the provided tileset, whose information in the .tmx file is found at

```
<tileset ...>
    <image source="path/to/image/tileset.png" width="194" height="129"/>
</tileset>

```

The tile data itself can be found in the .tmx file if you set the layer format to XML and view the .tmx file.

```
<data>
   <tile gid="1"/>
   <tile gid="1"/>
   <tile gid="2"/>
   <tile gid="2"/>
  . . .
   <tile gid="1"/>
</data>

```

The `gid` property represents the tile in the tileset that is referred to. The mapping of id to tileset tile begins at 1 at the topleft corner of the tileset and increases moving to the right. The breakdown of the tileset image into tiles (i.e. the width and height of each tile) will depend on your tileset settings.

Because of the .tmx use of references to refer to data, as opposed to storing the entire image itself, **you can edit the tileset image file and any changes you save to it will immediately be seen on the map.**

---
Tags: tiles, tilemap
---


# Question
Title: Timer.schedule(task, 0, 100) never fires
I added some code using `java.util.Timer` to execute my `spawnMonster` function every 100ms. It worked, until I tried instantiating images in it -- since it doesn't run on the libGDX core thread, there's no OpenGL context, so it can't do stuff with images.

I figured using the libGDX `Timer` class, which the javadocs say `runs on the core thread`, would solve this problem; but unfortunately, the timer code just doesn't execute.

I tried:

`- new Timer().scheduleTask(task, 0, 100)
- new Timer().scheduleTask(task, 0, 100, 99999)
- Timer.schedule(task, 0, 100)
- Timer.schedule(task, 0, 999999)
- Timer.start()
- t = new Timer(); t.scheduleTask(...); t.start();`

`task` appears to execute once, and only once; it never executes again. (It prints a date-time diff from a target time, so I can tell it's not running.)

# Answer
The `scheduleTask` function's source suggests that it expects the input in terms of **seconds** instead of milliseconds.

```
public void scheduleTask (Task task, float delaySeconds, float intervalSeconds, int repeatCount) {
    if (task.repeatCount != CANCELLED) throw new IllegalArgumentException("The same task may not be scheduled twice.");
    task.executeTimeMillis = TimeUtils.nanoTime() / 1000000 + (long)(delaySeconds * 1000);
    task.intervalMillis = (long)(intervalSeconds * 1000);
    task.repeatCount = repeatCount;
    synchronized (tasks) {
        tasks.add(task);
    }
    wake();
}

```

The function converts `intervalSeconds` to milliseconds and sets the task's interval time to this value.

Therefore to have it execute every 100 ms, you should input `0.1` instead of `100`.
> 2 votes

---
Tags: libgdx, timer
---