# Question
Title: Does it make the game more fun when the user is forced to progress through the levels sequentially rather than letting them pick and play?
For the first time in my game, I'm stuck with a real design dilemma. I guess that's a good thing ;) I'm building a word puzzle game that has five levels, each with 30 puzzles. Currently, the user has to solve one puzzle at a time before moving to the next. However, I'm finding the user occasionally gets stuck on a puzzle, at which point they can no longer play until they solve it. This is obviously bad because many people will probably just quit playing the game and delete the app.

The only elegant solution I can find to helping the player get unstuck is changing the design of the game to allow the users to pick any puzzle to play at any time. This way, if they get stuck, they can come back to it later and at least they have other puzzles to play in the meantime. It's my opinion, however, that this new flow design doesn't make the game as fun as the original flow design where the player has to complete a puzzle before moving to the next. To me, it's like anything else, when you only have one of something, it's more enjoyable, but when you have 30 of something, it's far less enjoyable. In fact, when I present the user with 30 puzzles to choose from, I'm concerned I might be making them feel like it's a lot of work they have to do and that's bad. I even had a tester voluntarily tell me that being forced to complete a puzzle before moving to the next is actually motivating.

My questions are...

1. Do you agree/disagree?
2. Do you have any suggestions for how I can help the player get unstuck?

Thanks so much in advance for your thoughts!

EDIT: I should mention that I've already considered a few other solutions to helping the user get unstuck, but none of them seem like good ideas. They are...

1. Add more hints: Currently, the user gets two hints per puzzle. If I increase the hint count, it only makes the game more easy and still leaves the possibility of the user getting stuck.
2. Add a "Show Solution" button: This seems like a bad idea because it's my opinion this takes the fun out of the game for many people who would probably otherwise solve the puzzle if they didn't have the quick option to see the solution.

# Answer
Lots of solutions:

**Limited Skips**

Players can skip up to X times, and clearing a previous level gets the skip back

**Skip after repeated failure**

If your puzzle can be failed then after a certain number of failures instead of just a retry button there is a skip button as well.

**Multiple Levels of Success**

For example, beating a level rewards 1, 2, or 3 stars. Then levels unlock based on stars not order. So if you are having trouble with one level you can go back and do a better job on previous ones.

**Micro-transaction Skips**

Depends on your platform, but you can charge for level skipping.
> 33 votes

# Answer
wkerslake has some good answers - multiple levels of success has been used to great effect in games like Cut the Rope and Angry Birds, among many others.

But I'm surprised not to see any answers recommending the solution used by Guitar Hero, Super Meat Boy, and many other games, which I'll call "gating."

Divide your levels up into chunks, say "Easy, Medium, Hard, Expert" chunks; each chunk might contain, say, 7 levels. The player starts with only access to the Easy chunk, but once they beat, say, 5 of the 7 Easy levels, the Medium chunk becomes available. Once they beat 5 of the 7 Medium levels, the Hard chunk becomes available; etc.

A variation is to make it so that beating 5 of the 7 available levels opens up a "boss" level, which must be played, after which the Medium chunk appears. This ensures that the "boss" levels must always be played in any possible progression through your game.

This allows players to quit certain levels they get stuck on and either return to them later, or not return to them at all. Meanwhile players who wish to do so can still play through every single level sequentially (and should probably be given a peripheral award such as an achievement for doing so). This also preserves a progression in your game - they can't immediately skip to the last level if they want. And the "boss" system ensures that if you have a level which teaches a skill which is absolutely required for the player to learn before moving on, that the player will always have to play that level (though if that one level turns out to be the one your players get stuck on, then you're right back to the problem you started with).

Another solution is the one used by Braid, which allowed the player to simply go right on past the puzzles without solving them. They could instantly return to them later after beating them, and there was still "gating" in that they couldn't open up new areas until the puzzles were actually paused. But think about having the ability to simply "move on" to the next puzzle and return to it later - often players will return to a puzzle refreshed, and with new skills acquired from the other puzzles they solved, and will be able to defeat that puzzle they were stuck on quickly.
> 8 votes

# Answer
I have two suggestions.

The first is to **limit the amount of direct skips they get**, and allow them to regain used skips if they go back and complete a puzzle they skipped previously.

This will ensure that the user remains motivated. They no-longer have unlimited potential for an easy ride, and it will add another motivating factor. Not using their skips because there is 'potentially' a far harder puzzle down the line. Also, as puzzles tend to effect the way that people approach a general set of problems they may get inspiration for a puzzle they play down the line. The act of returning and finishing a puzzle that had once defeated them will equal an immense amount of gratification (Consider finally one-upping someone who was better than you in ever class). For example of this, see World of Goo, although I don't know if they return skips.

The second suggestion is to **give them unlimited hints**, from the early casual hints to helping them step by step. There are any number of factors you could use to give out hints to players, time, failed attempts but casually release more information that would make solving the particular puzzle easier for them. For you, this may seem as juvenile hand holding, but thanks to Hindsight Bias your players won't see it that way. Mentally they will say, "Oh it's that simple, I would have figured that out" and continue without feeling slighted in the slightest. (Or alternatively, they will go *"No one would have thought of that, I'm happy I cheated"* or *"I was over-thinking the puzzle, I'm to smart to have ever guessed that"* and actually feel pleased). For an example of this (in a form) see the monkey island 1/2 remakes. You can hold down a button to get a hint, and repeatedly clicking things (in general) in monkey island games (and many other adventure games) makes the character give subtle hints.

The trick with that one, is to do it casually and without interrupting play. A simple visual tick could be the lowest hint levels, a sort of inconspicuous action to draw their eyes to something else (sparkles around something they should click, a change to a happier 'successful' tone when they are completing a proper chain of actions or touching the correct area)
> 4 votes

# Answer
One option that I've seen work well is to give the player, say, three available levels in the post-tutorial period, and then unlock an additional level when one is beaten. Thus, the player can initially do Level 1, 2, or 3; beating any one of these unlocks 4, and so on.

At any one time, the player has three different levels available. If she gets stuck on Level 2, she can do other levels all the way to the end of the game, but never has too many options to pick from.

Of course, if the player becomes stuck on three levels over the course of the game, say 2, 6, and 13, she must beat one of them to unlock a new level. Still, this gives more leeway than the beat-each-level method.
> 3 votes

# Answer
The player should be given "money" for each puzzle they solve. The amount of money earned depends on the difficulty and time taken.

```
money_earned = max - time_taken / difficulty;

```

With this money, they can buy the solution to puzzles:

```
#define TIME_TAKE 60 // (seconds) The average time it should take to solve a puzzle on level 1 difficulty; multiply by difficulty level to get time taken on that difficulty
cost_of_puzzle = TIME_TAKE * (*puzzle).difficulty;
if(buy)
    money_earned -= cost_of_puzzle;

```

If they have the solution to a puzzle, give them the option to skip it.

This method has a few benefits:

* If the player is good, they can skip some of the easy levels - the faster they are, the more money they earn
* You can force the player to go in order
* Money makes everything all right!
> 2 votes

# Answer
Having to progress through levels is probably more fun for a puzzle game. That said, you have 5 level-sets, so you could force sequential progression on those 5, while allowing the player to go through the sub-levels (of the current set) in any order.

Too many hints and cheats allow the player to bypass the challenge. Games are about challenge, so letting players out of the challenge can be harmful if overdone. It will make the game less fun. Give the player credit - s/he will rise to the level of the game (within reason... you can't require them to understand quantum physics to win). Make it too easy, and they will lose motivation.

I would try to make sure that **by the time they might get stuck**, they have enough **invested** in the game that they don't want to quit. So ramp up the difficulty gradually in those first 30 levels. Provide *enough* challenge, but make it unlikely to get stuck in the early stages. That way, the player starts having to really think on level 25 or 35 or 45, and by that time they have (we hope) formed goals and attachments within the game. Since they've already spent x hours mastering the gameplay, and assuming those hours were fun and rewarding, they won't want to waste that investment by quitting and uninstalling ;)
> 1 votes

# Answer
I would group 5-7 puzzles into one tier. The player has to complete a certain percentage of the puzzles for each tier to unlock the next tier e.g. 5 out of 7.

That way the player can progress and can try difficult puzzles at a later time. It would be a good idea to give some sort of incentive. Maybe making hints available if you complete all puzzles of one tier or bonus levels, different UI skins etc.
> 0 votes

# Answer
On the lines of what IQ said, some of the puzzle flash games I played and like implemented a star or coin type progression.

You need 1 star to unlock level 2, 5 stars to unlock level 3, 7 stars to unlock level 4, etc. etc.

You get a star for solving a puzzle, and also for completing secondary objectives for each puzzle. For example, if you beat a puzzle in under a minute, you get a star. If you beat the puzzle with 85% efficiency, you get a star. This way, you still have to go rather sequentially through each puzzle, but if you do well enough on the earlier ones, you can "skip" a puzzle that you get stuck on and go to the next.

Some of it depends on what kind of puzzle game it is, but I've always enjoyed these type of progressions because you can skip puzzles you get stuck on and it adds to replayability of earlier levels you've already beaten. Especially if you get rewards or bonus levels for getting all the stars on each level.
> 0 votes

# Answer
I just wanted to offer what I implemented for my own puzzle game I created. My game remains completely linear in that the player has to complete each level one by one to reach the ending. However, I also have the concept of bonus campaigns that come included with the game and can be accessed from the start. The player can start playing these bonus campaigns from any level they want (for instance, they could start the "Pro Campaign" at level 2-3). I included a copy of the main campaign here so the player can play and practice any of the later levels of the main campaign, they just wouldn't see the proper ending of the game.

There's also a level editor as well. The goal really was to give the player a sense that there's still plenty they can do in the game even if they get stuck on a particular level in the main campaign. Remains to be seen how effective this will turn out to be
> 0 votes

---
Tags: game-design, puzzle
---


# Question
Title: How do games go about designing weapon damage?
In Action-RPG games, I was wondering how weapon damage numbers and attack speeds are decided on. Do most games come up with their own or do they "steal" numbers from other games? How would I go about coming up with my own numbers?

# Answer
In any sort of design related field, its not 'stealing' unless it is a blatantly obvious copy. Rather more, its typically 'inspired by'.

As for coming up with your own numbers for weapon damage and attack speed, its not that hard. You don't even need to 'steal', or be 'inspired by' the numbers, although you can be 'inspired by' the range of valid values.

To come up with your own numbers, envision the type and typical use of the weapon, and assign stats accordingly. I'm going to give a few examples using various weapons.

* Good old dagger/shortsword. Short range, good for stabbing anything that gets to close, but short blade means little penetration, and therefore low damage. Lightweight and short range means short, fast attacks, suited for early game and/or horde type enemies.
Damage: Very Low/Low, Speed: Very High, Range: Short
* Hand Axe/Longsword. Bit more reach, good for hitting stuff a bit further away, more weight, larger blade/hit area and the larger swing means more impact, therefore more damage per hit, but takes longer to attack. Good for mid-late game and regular enemies.
Damage: Moderate, Speed: Moderate, Range: Short
* 2 Handed Axe/Sword/Maul: Bit more reach that the previous category, but a lot heavier with a much larger swing. Better hit area and impact, but slower as it takes even longer to wind up, swing and recover. Good for mid-late game and single, tanky enemies. May also have a small stun or AoE.
Damage: High, Speed: Low, Range: Short
* Bows/Cross bows: Ranged weapon with fast moving projectiles, but a very small impact area. You're relying on the impact speed to do most of the damage. Takes a bit of time to load, but has an advantage over melee weapons on allowing you to do damage from a safe distance, so lets drop its damage a bit.
Damage: Low, Speed: Moderate, Range: Long
* Firearms: Another ranged weapon with fast moving projectiles, but depending on the type of weapon, it may have high damage with slow attack speeds (muskets, sniper rifles) or low damage with higher attack speeds (ARs, SMGs, Handguns, etc). You could probably expand this out into multiple categories like the melee weapons above.

As for assigning some numbers, lets assume weapon speed is between 1 (snails pace) and 10 (roadrunner) where 5=1 attack per second and 10=2. Damage ranges from 1 to 200 (because we have 'drop large rocks on head' traps), and range is between 0 and 100 (cause our maps aren't that big). Now, lets make up some numbers.

* Daggers/Shortswords: Damage 5-20, Speed 8-10, Range 1
* Hand Axes/Longswords: Damage 50-80, Speed 5-6, Range 2
* 2 Handed Axe/Sword/Maul: Damage 100-140, Speed 2-4, Range 3
* Bows/Cross bows: Damage 20-40, Speed 4-5, Range 1-50
* Firearms (I'm going to go with a musket type weapon here): Damage 35-60, Speed 1-3, Range 2-80

However, play testing and other feedback reveals some problems (looking at the numbers it should be rather obvious).
Daggers/swordshorts are too weak to be used effectively, and your average medium melee weapon actually out damages your average heavy weapon, and muskets aren't being used because they don't kill stuff fast enough compared to bows.

Next challenge is how to solve this. Maybe increase/decrease some weapon stats, or introduce greater variance in the damage range for the weapon so that some attacks graze or deal large amounts of damage. Maybe increase the critical chance for some weapons to improve its average dps.

After a a random amount of rebalancing iterations the numbers may be declared final and that's that.

Until someone decides there aren't enough weapons and we need flails and maces.
> 8 votes

---
Tags: game-design, balance, combat
---


# Question
Title: Orthographic Camera settings for a 2D game
I'm starting out a 2D wrestling game in Unity 5 and i need some help. The default resolution of game needs to be 320x240. The background sprite that i would be using is 640x480. The camera would move over the background to give it a hovering look. I want the Camera to cover exactly 320x240 resolution. I tried setting the Camera size to 1.2 and it looks approximate but i wanna be sure that the camera is exactly 320x240. By default all the images are set to 100 Pixels per Unit.

So my question is:

* How to set the camera to cover exactly 320x240

# Answer
Your orthographic camera size depends on the pixels per unit of your sprites.

Orthographic camera size is equal to 1/2 of the vertical units (meters if you use built in physics) you will see on the screen. Say size 6 means that your screen height will be 12 units.

The formula is: screen resolution / 2\*orthographic size = pixels per unit on sprites
> 1 votes

# Answer
I had the very same question while while starting out. Do take a look at the detailed answer I later posted. How does Unity size graphics

> When we set camera size, there's a certain screen height. This height is fixed irrespective of the device screen. On larger devices, greater detail, on smaller devices, lesser detail. So, if I chose 760px as height of my background image, I calculate camera size as follows: cameraSize= (Height/2)/PixelsPerUnit which in my case is, (760/2)/100=3.8
>
> Next, I need to make sure skybox doesn't show irrespective of the device's screen size. This means, design background for the widest aspect ratio which is 16:9. So, I calculated the width as
>
> width=AspectRatio X height. Which in my case is (16/9) X 760=1352 px.
>
> So my background is 1352 X 760 pixel. This fits 16:9 aspect ratio perfectly. On narrower ratios like 4:3, there is cropping towards the sides. But skybox never shows. Which was my main issue.
> 1 votes

# Answer
Set your Pixel per Unit to 1 and try witch this:

```
scale = Screen.height / nativeRes.y;
        pixelsToUnit *= scale;
        cam.orthographicSize = (Screen.height / 2.0f) / pixelsToUnit;

```

Where nativeRes is your default resolution. Attach it to MainCamera and now your orto size should fit automatically.
> 0 votes

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


title: Generate random position within object

text:
# Question
Title: Generate random position within object
I have a plate object which is generated somehow (I don't care how), now I want to put another object within this object on random position. Lets say that I want to put random trees on this plate. How can I achieve this in Unity. I had read for bounds but I don't know how to use it to generate position for the tree.

# Answer
> 3 votes
This way you would get a random position on your plane. To get the correct size of your plane you need to get the `MeshFilter` which gives you the right bounds of the object.

```
public Vector3 GetARandomTreePos(){

    Mesh planeMesh = gameObject.GetComponent<MeshFilter>().mesh;
    Bounds bounds = planeMesh.bounds;

    float minX = gameObject.transform.position.x - gameObject.transform.localScale.x * bounds.size.x * 0.5f;
    float minZ = gameObject.transform.position.z - gameObject.transform.localScale.z * bounds.size.z * 0.5f;

    Vector3 newVec = new Vector3(Random.Range (minX, -minX),
                                 gameObject.transform.position.y,
                                 Random.Range (minZ, -minZ));
    return newVec;
}

```

# Answer
> 0 votes
http://docs.unity3d.com/ScriptReference/Random-insideUnitSphere.html

If you need something more complicated than a sphere, or box, you will end up creating your own randomize logic by hand.

You could set values in the inspector for example, bound values.

You could set up possible colliders, then randomize the position, and test it against these colliders(if the position is inside one of these).

---
Tags: unity
---


# Question
Title: Moving vector shooting at other moving vector
The following code creates an accurate shot to be made at a moving target from a stationary position. (ie a tower or non-moving vector). It works GREAT, but I need it to consider the movement of the shooter. I believe I subtract the shooter's movement from the target's movement, but I don't know what part of the code this would apply to. Please help. I have an assignment due tomorrow and this is working perfectly except for calculating the shooters movement.

```
    Vector totarget =  target.position - tower.position;

    float a = Vector.Dot(target.velocity, target.velocity) - (bullet.velocity * bullet.velocity);
    float b = 2 * Vector.Dot(target.velocity, totarget);
    float c = Vector.Dot(totarget, totarget);

    float p = -b / (2 * a);
    float q = (float)Math.Sqrt((b * b) - 4 * a * c) / (2 * a);

    float t1 = p - q;
    float t2 = p + q;
    float t;

    if (t1 > t2 && t2 > 0)
    {
        t = t2;
    }
    else
    {
        t = t1;
    }

    Vector aimSpot = target.position + target.velocity * t;
    Vector bulletPath = aimSpot - tower.position;
    float timeToImpact = bulletPath.Length() / bullet.speed;//speed must be in units per second

```

# Answer
You'll want to do it right at the beginning. As you probably know, if the target is moving at the same velocity as the tower, it should aim as if neither are moving. If the tower is unmoving, it should be the same calculation you already have there. So, right at the beginning:

```
var velocityDiff = target.velocity - tower.velocity;

```

Then, replace all "target.velocity" with "velocityDiff".
> 0 votes

---
Tags: c#, vector
---


# Question
Title: SFML Trying to shoot bullets but it moves with the gun
I'm pretty new to SFML and C++ and I'm trying to figure out how to shoot bullets. I've done the shooting part and it's origin is from a moving shape controlled by the user called Player.

The problem is when I move, the origin moves as well which is why the bullets move with the origin. I feel like it's something really basic but I cannot for the life of me figure this out. Can anyone help?

This is the part of the code that creates and moves the shapes:

```
        //creates a new bullet when pressed
            else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) {
            rects.push_back(sf::RectangleShape(sf::Vector2f(40, 10)));

        }
    }

    // clear the window with black color
    window.clear(sf::Color::Black);

    sf::Vector2f pl = player.getPosition();

    //draw active shapes in the vector and move them to the right
    for (int x = 0; x < rects.size(); x++)
    {
        rects[x].setOrigin(-pl.x,-(pl.y + 10));
        window.draw(rects[x]);
        rects[x].move(10, 0);
    }

```

# Answer
> 1 votes
If everything works just fine, and the only problem is origin changing after the bullet was shot - just move setting the origin on the line where it was initialized so that it is set only once and the time where it was shot:

```
 else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) {
   sf::Vector2f pl = player.getPosition();
   sf::RectangleShape rect(sf::Vector2f(40, 10));
   rect.setOrigin(-pl.x,-(pl.y + 10));//not set pos?
   rects.push_back(rect);
 }
 // clear the window with black color
 window.clear(sf::Color::Black);

 //draw active shapes in the vector and move them to the right
 for (int x = 0; x < rects.size(); x++)
 {
   // Only move the rect here, don't set the origin.
   window.draw(rects[x]);
   rects[x].move(10, 0);
 }

```

---
Tags: c++, sfml
---


# Question
Title: GLSL uniforms are returning -1, but they are being used in output
I have looked this up, and found some answers and people said that if uniforms aren't important to the final output than they get thrown away by the compiler. However, in my case they are being used but still being returned -1. I have spent hours trying to figure this out, but each time it happens. It is weird because I have other uniforms used in the exact same context but don't get thrown away.

My problem is that my shader compiles and runs perfectly until I try to use the applyDirLight function in my fragment shader. The uniforms being used for the variables are always -1 when I use glGetUniformLocation. My uniforms for point lights are working fine. I don't get compile errors from it, but instead I get program linking errors. Every single uniform inside the struct DirLight always returns -1 in my Java code.

My Java integer array of uniforms is all -1 in the directional light array, but not the point light array.

```
    pointLights = new int[amtPointLights*6];
    for(int i = 0; i < amtPointLights; i++) {
        int index = i * 6;
        pointLights[index+0] = shader.getUniformLocation("PointLights["+(i)+"].position");
        pointLights[index+1] = shader.getUniformLocation("PointLights["+(i)+"].color");
        pointLights[index+2] = shader.getUniformLocation("PointLights["+(i)+"].ambient");
        pointLights[index+3] = shader.getUniformLocation("PointLights["+(i)+"].diffuse");
        pointLights[index+4] = shader.getUniformLocation("PointLights["+(i)+"].specular");
        pointLights[index+5] = shader.getUniformLocation("PointLights["+(i)+"].radius");
    }

    System.out.println(Arrays.toString(pointLights));

    dirLights = new int[amtDirLights*5];
    for(int i = 0; i < amtDirLights; i++) {
        int index = i * 5;
        dirLights[index+0] = shader.getUniformLocation("DirLights["+(i)+"].direction");
        dirLights[index+1] = shader.getUniformLocation("DirLights["+(i)+"].color");
        dirLights[index+2] = shader.getUniformLocation("DirLights["+(i)+"].ambient");
        dirLights[index+3] = shader.getUniformLocation("DirLights["+(i)+"].diffuse");
        dirLights[index+4] = shader.getUniformLocation("DirLights["+(i)+"].specular");
    }

    System.out.println(Arrays.toString(dirLights));

```

If you know why it is being return -1 it would help me a bunch.

```
#version 330 core

in vec3 new_normal;
in vec3 worldPos_out;
in vec2 pass_texCoords;

out vec4 outColor;
uniform vec3 viewPos;

#define MAX_LIGHTS 25

struct Material {
    sampler2D diffuseMap;
    sampler2D specularMap;
    sampler2D normalMap;
    vec3 specular;
    float shininess;
    int usingNormalMap;
};
uniform Material material;

struct PointLight {
    vec3 position;
    vec3 color;

    vec3 ambient;
    vec3 diffuse;
    vec3 specular;

    float radius;
};
uniform PointLight PointLights[MAX_LIGHTS];

struct DirLight {
    vec3 direction;
    vec3 color;

    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
};
uniform DirLight DirLights[MAX_LIGHTS];

uniform int amtPointLights;
uniform int amtDirLights;

vec3 applyPointLight(PointLight light, vec3 normal, vec3 fragPos, vec3 viewDir, vec3 surfaceColor, vec3 surfaceSpecular) {
    vec3 lightDir = normalize(light.position - fragPos);
    //Diffuse shading
    float diff = max(dot(normal, lightDir), 0.0);
    //Specular shading
    vec3 reflectDir = reflect(-lightDir, normal);
    float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
    //Attenuation
    float distance = length(light.position - fragPos);
    float attenuation = 1.0 / (1.0 + light.radius * pow(distance, 2));

    vec3 ambient = light.ambient * surfaceColor;
    vec3 diffuse = light.diffuse * diff * surfaceColor;
    vec3 specular = light.specular * spec * surfaceSpecular;

    return light.color * (attenuation * (ambient + diffuse + specular));
}

vec3 applyDirLight(DirLight light, vec3 normal, vec3 viewDir, vec3 surfaceColor, vec3 surfaceSpecular) {
    vec3 lightDir = normalize(-light.direction);
    //Diffuse shading
    float diff = max(dot(normal, lightDir), 0.0);
    //Specular shading
    vec3 reflectDir = reflect(-lightDir,normal);
    float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);

    vec3 ambient = light.ambient * surfaceColor;
    vec3 diffuse = light.diffuse * diff * surfaceColor;
    vec3 specular = light.specular * spec * surfaceSpecular;

    return light.color * (ambient + diffuse + specular);
}

void main(void)  {
    vec4 surfaceColor = texture(material.diffuseMap, pass_texCoords);
    vec3 surfaceSpecular = vec3(texture(material.specularMap, pass_texCoords));
    float alpha = surfaceColor.a;

    vec3 unitNormal;
    if(material.usingNormalMap == 1) {
        unitNormal = normalize(texture(material.normalMap, pass_texCoords).rgb);
    } else {
        unitNormal = normalize(new_normal);
    }
    vec3 viewDir = normalize(viewPos - worldPos_out);

    vec3 linearColor = vec3(0,0,0);
    for(int i = 0; i < amtPointLights; i++) {
        linearColor += applyPointLight(PointLights[i], unitNormal, worldPos_out, viewDir, surfaceColor.rgb, surfaceSpecular);
    }
    for(int i = 0; i < amtDirLights; i++) {
        linearColor += applyDirLight(DirLights[i], unitNormal, viewDir, surfaceColor.rgb, surfaceSpecular);
    }

    if(amtPointLights == 0 && amtDirLights == 0)
        linearColor = surfaceColor.rgb;

    float gamma = 2.2;
    vec3 fragColor = pow(linearColor, vec3(1.0/gamma));

    outColor = vec4(fragColor, alpha);
}

```

# Answer
> 1 votes
My assumption is that when you add the `applyDirLight` you are exceeding the limit of the accepted number of uniform components per shader stage which is implementation dependent. Once you activate `applyDirLight` you are adding more than 25 uniform variables, that said `vec4` is 4 components, `vec3` is 3 components, so in your case you are adding around `25*3*5` components. I highly suspect this is the reason.

---
Tags: opengl, java, glsl, lwjgl
---


# Question
Title: Proper and easier way to make isometric animated art
Assuming I don't want to use 3D engine/models (no 3D *in* the game, I can use 3D offline), only 2D, in order to make for a game, for example, a single character, this would be the workflow I already got in mind:

1. Model in 3D
2. Texture it
3. Rig it
4. Animate it
5. Render it

* For each part of the body/items -in order to sort gearing-
    * For each type of animation (attack, move, idle, die, dodge, hurt)
    * For each angle (I'd like 16 angles, or 8 as minimum)
    * For each frame (let's say 15 frames/sec)

This is a ridiculous amount of sprites. 400 sprites for 1 item. (Could it be too much?)

And then

6. Get the animation controller with extra work: sort the sprites properly depending on animation frames and angles (example at p. 11 of Paul Siramy extracting animations of Diablo II)

All this seems to me, for a bad designer, and a person who aims to make a game for the moment alone, too much work. Are there alternatives to get **similar results, without 3D engine?** I've heard about something called 3D bitmaps or "Vortex" (used in don't remember which strategy game for vehicles), but I could not find any information about it.

# Answer
> 3 votes
I believe the approach you're referring to as "3D bitmaps" or "voxel"(?) is found in some of the C&C series of games, specifically C&C Tiberian Sun.

What they do is is make the units up out of a reasonably small 3D array with each voxel represented as a colour, and I think they then have a set number of frames (pre?-)rendered from that via part of their own engine's functionality rather than some external tool like Max.

It could be very cheap to do, even without the pre-rendering: given the orthogonal perspective in these games, rendering them is an embarassingly parallel set of raycasts with very few steps per ray (in fact, you can terminate the ray once you hit a voxel per se, after starting the ray on the boundaries of the sprite). For 3D raymarching, see 3D DDA.

# Answer
> 2 votes
What you're trying to accomplish is called "Prerendered 3D sprites". In this process, you create 3D character with textures and animaions. Then, you take snapshots of the character in animation. Several games like Clash of Clans work this way.

Any experienced 3D artist can help with the exact process. Here's some detail on doing it with blender. That discussion has steps to create sprites from models in Blender. I'm not an artist myself, so can't provide more details. Sorry

---
Tags: art, 2.5d
---


# Question
Title: Create sprites from 3D models at runtime in Unity
From my previous post where I search solutions to have animated characters in an isometric world (using 2D engine as base) arised this question.

I'd like to create and instantiate 2D sprites from 3D models, using Unity, at runtime, in order to use them as they were sprites, ordering them by depth, etc.

There are already unity scripts (maybe using 3d party software) that make this, like Sprite Maker. How is this done? (You have to pay to get the Sprite Maker). Anyway, I need to do it at runtime, instead of baking a spritesheet.

How do I do it? Is it posible?

Other solution, instead of converting it to sprite, is being able to sort the 3D model as it were a sprite. But how?

# Answer
> 1 votes
Finally I found a solution. It is posible to order in the same layer 3D and 2D objects!

Old answer:

*To do it there are two simple steps \- Add a sprite shader (diffuse or not) to the 3D model mesh object \- Sort in layer via script: GetComponent().sortingOrder = z; Found information here*

No. That finally did not work properly. But I found an other solution: as the objects are displayed always, no matter if they are 2D or 3D, depending on Z in ortographic perspective (minor Z means more above), my solution was to put my 3D model into a container (empty object). I gave to this container a very small Z scale: 0.0001f. So it really seems to be 2D, while I still can rotate the model as it is a child object with no troubles. After that, to order my objects depending on the diagonals of my isometric world, I just decreased, for each consecutive diagonal, the Z component by -0.0001f\*diagonal. That worked like a charm.

Decreasing by a small number allows to use lights as child objects of 2D sprite-diffuse shadered objects, as the sprites/models don't move too much far away from the background to notice it.

---
Tags: unity, 2.5d
---


# Question
Title: Unity Inspector - Turn off script for a group?
I have a large group of objects in Unity that can be grouped and for one instance I want to turn off a script on each one, for over 100 this can be tedious, can this be done group wise within the inspector? Instead of me going into each one and manually turning a script off?

I have tried doing this within a script but it will not work for this situation.

# Answer
> 1 votes
As far as I know, selecting multiple gameobjects with each of them having a common (of the same type) component allows you to edit the properties of that component with the changes being applied to all of the gameobjects in the group.

Although multi-editing is disabled for several types of components, this should still work with Scripts.

You can select multiple gameobjects in the editor by `CTRL+click`-ing them. To select a group at once you'd need to click the first gameobject in the group and then `SHIFT+click` the last one.

# Answer
> 2 votes
You can just add script onto parent with nothing else but bool flag `isEnabled`:

```
public ChildrenEnabler {
 public bool IsEnabled;
}

```

and edit the target script so it checks parent for the flag:

```
private bool IsThisEnabled = false;
void Start() {
 var e = transform.parent.gameObject.GetComponent<ChildrenEnabler >();
 if(e != null && e.IsEnabled) //enable logic here, e.g.:
   IsThisEnabled = true;
}

void Update() {
  if(IsThisEnabled) {
  // original logic here, same check in every other implemented method
  }
}

```

alternatively, you can use Actions:

```
private Action UpdateAction;
void Start() {
  var e = transform.parent.gameObject.GetComponent<ChildrenEnabler >();
  if(e != null && e.IsEnabled)
    UpdateAction = new Action(()=> { doUpdate(); });
  else
    UpdateAction = new Action(()=> { /*literally do nothing*/ });

}

void doUpdate() {
  // original logic here, similar for each other implemented method in script
}

void Update() {
   UpdateAction.Invoke();
}

```

To enable/disable script, just change the `IsEnabled` on parent to true/false. This turns off its logic - it does not, however, completely remove the script form the object - the script will remain on the object but will do nothing.
If you need to turn off multiple different scripts separately, just change the flag to List of Type and in the scripts `Start()` method check if the parent list `.Contains(this.Type)`.

---
Tags: unity
---


# Question
Title: How to orbit an object at certain speed in Unity?
I want to move an object around a circle. So I have this code below:

```
    static public int theta = 0;

void Update(){

    Vector3 position = this.transform.position;

    position.x = 0 + 50 * Mathf.Cos (theta) * Time.deltaTime;
    position.y = 0 + 50 * Mathf.Sin (theta) * Time.deltaTime;
    this.transform.position = position;
    theta += 1;
}

```

The object orbits, but it orbits so fast!!! I want the object to rotate like 1 orbit per second only. How to do that?

ANSWER TO THIS PROBLEM, THANKS!

```
static public int theta = 0;

void Update(){

    Vector3 position = this.transform.position;

    position.x = 0 + 50 * Mathf.Cos (theta) * Time.deltaTime;
    position.y = 0 + 50 * Mathf.Sin (theta) * Time.deltaTime;
    this.transform.position = position;
    theta += 1 * Time.deltaTime;
}

```

# Answer
> 0 votes
I'd do something like this...

```
public float orbitsPerSecond = 1f;
public float orbitRadius = 1f;

// Current angle in radians.
float orbitAngle;

void Update(){
    orbitAngle += Time.deltaTime * Mathf.PI * 2f * orbitsPerSecond;

    Vector3 position = this.transform.position;

    position.x = 0 + orbitRadius * Mathf.Cos (orbitAngle);
    position.y = 0 + orbitRadius * Mathf.Sin (orbitAngle);
    this.transform.position = position;
}

```

What I changed:

* I added public parameters so you can change the radius and speed of the orbit in the Inspector.
* I renamed your theta variable orbitAngle and made it an instance member float, so it can hold fractional values and isn't shared across all copies of this script (Even if you need them to sync, you'll want to make sure they're not all increasing this value!)
* I moved the update of orbitAngle to the top of update, and included orbitsPerSecond and Time.deltaTime so it advances at a controlled rate each frame.
* I removed Time.deltaTime from the equations for x and y. Putting it there, it would have caused your orbit radius to shrink when at a high framerate, and grow or jitter when your framerate drops, which isn't a behaviour you'd said you wanted.

---
Tags: unity
---


title: How to handle complex input

text:
# Question
Title: How to handle complex input
In my Libgdx project i need to handle several types of inputs.

In particular these input events are needed in order to interact with the Actors that the user puts in the Stage.

The possible interactions are:

1) Drag And Drop with DragAndDrop class.

2) Rotate the Actor (90 degrees clockwise each time)

3) Remove the Actor

I thought that i could rotate the Actor with a simple click (touchDown), and remove the Actor with double tap, but this strategy gives rise to some issues.

1) When the user does double tap on the Actor, before the Actors gets removed it rotates 2 times.

2) If the user wants to drag and drop the Actor, when he clicks on the Actor it rotates.

Then, i thought that i could rotate the Actor in the touchUp method, only if the current position of the Actor is the same as before in order to avoid to rotate the Actor when the user just want to move it.

This gives rise to another problem. In order to detect the double tap, i need to implement GestureListener interface that does not have the touchUp method!

I could remove the actor when the user does long press on it, but this will be a game that will require fast interaction.

So.. i need your help, any kind of help, thank you very much!

# Answer
> 3 votes
The base idea here is that you have to separate the concepts:

* Input
* Command
* Behaviour

So basically, instead of linking the `onTouchDown` event to `actor.rotate(90)`, you need an input manager that interprets the movements of the user:

* `click`
* `doubleClick`
* `drag`

This input manager will generates these events from what you get from the base layers of your system. Some libraries can do that for you, but some don't and you have to manage it yourself; I don't know how `libgdx` does it.

But the thing is, if you get a `click`, you have to wait a bit to make sure that you don't get a `double click`, and when you get a `double click` you have to make sure you don't get *two* `click`s. This is the main task of the input manager.

Then you need to translate these events into commands.

The command manager receives Input events, and translates them into "what do I do with that". So for instance, the command managers knows that in a specific context, the `click` is associated with a `actor.rotate(90)` action.

This allows you to

* easily test your inputs in an isolated way
* split your input from the behaviour of the game (no "is the user tapping, double-taping or dragging" in the game code (actors), only commands (you'll still need to handle dragging in a more complex way, like `startDragging` and `stopDragging` and `moveWhileDragging`, though ))
* change the commands associated with the input easily
    + allow the user to customize the inputs
    + allow for a much easier change of context

---
Tags: libgdx, input
---


# Question
Title: How do I expose a variable from a class in Unreal Engine 4 to blueprints?
I would like to expose to blueprints the variable CurrentTouchInterface in the class APlayerController, just like the method APlayerController::ActivateTouchInterface.

So, I'm guessing I have to change the header file **PlayerController.h** from this

```
/** The currently set touch interface */
UPROPERTY()
class UTouchInterface* CurrentTouchInterface;

```

To something like this

```
/** The currently set touch interface */
UPROPERTY(BlueprintReadOnly, Category="Game|Player")
class UTouchInterface* CurrentTouchInterface;

```

The point is, what do I need to do for the engine's editor to start showing the exposed variable `CurrentTouchInterface` in blueprints?

I'm working with UE 4.9 downloaded from the Epic Games Launcher application.

# Answer
> 1 votes
Since you are not compiling the Unreal Engine source code, any changes you make in the `PlayerController.h` file will be ignored. If you are prepared to modify the source, you can do the step you outlined in your question and compile the editor. You can read more about compiling the editor on the Unreal website.

However, it would be easier (and probably cleaner as you won't be running a custom version of Unreal), to create a helper function that takes a player controller and gets the current touch interface. Something like this (inside any class will do, but I like to have a class just for static blueprint functions):

```
UFUNCTION(BlueprintPure, Category = "Game|Player")
static class UTouchInterface* GetPlayerCurrentTouchInterface(APlayerController* Controller);

```

Then the implementation would just be:

```
return Controller->CurrentTouchInterface;

```

In the blueprint editor, you will be able to drag out from a player controller variable and get this node.

---
Tags: unreal-4
---


# Question
Title: Shader and Texture Scrolling depending on Direction
I am trying to scroll a texture using its uv in Unity but I don't get the result I need.

The aim is to have two components, the speed and the direction. I would like to define the direction in normalized values and the speed should influence the velocity of the scrolling according to the direction.

If I change the speed at runtime, I don't want to have some hiccups but maybe this should not be handled but the GPU.

How can I do that in a better way, maybe using matrix ?

Here is an example but the result is not as good as expected.

```
uv.xy = uv.xy + frac(_Time.y * float2(_Direction.x, _Direction.y));

```

# Answer
> 2 votes
You can control texture UV with external code. Define `uniform float4 _Diffuse_ST;` in your shader and then in your script call it every Update():

```
public float rollSpeed = 0.1f;

void Update()
{
    offset += Time.deltaTime * rollSpeed;
    renderer.material.SetTextureOffset("_Diffuse", new Vector2(offset, 0));
}

```

Then your shader will look like this (it also rotates the texture, but you can remove this code):

```
Shader "Custom/TextureRotation"
{
    Properties
    {
        _Diffuse("_Diffuse", 2D) = "black" {}
    }

    SubShader
    {
        Pass
        {
            CGPROGRAM

            #pragma vertex vert
            #pragma fragment frag
            #pragma target 2.0

            sampler2D _Diffuse;
            float4x4 _Rotation;
            uniform float4 _Diffuse_ST;

            struct vertexInput
            {
                float4 vertex : POSITION;
                float4 texcoord : TEXCOORD0;
            };

            struct vertexOutput
            {
                float4 pos : SV_POSITION;
                half2 col : TEXCOORD0;
            };

            struct Input
            {
                float2 uv_Diffuse;
            };

            vertexOutput vert(vertexInput input)
            {
                vertexOutput output;

                output.pos =  mul(UNITY_MATRIX_MVP, input.vertex);
                output.col =  input.texcoord.xy *_Diffuse_ST.xy + _Diffuse_ST.zw;
                return output;
            }

            float4 frag (vertexOutput IN) : COLOR
            {
                float4 MxV0=mul( _Rotation, (IN.col.xyxy) );
                return tex2D(_Diffuse,MxV0.xy);
            }
            ENDCG
        }
    }
}

```

---
Tags: unity, shaders, glsl, hlsl, cg
---


# Question
Title: Make Camera follow object only on Y axis?
Can someone give me a script that makes the camera follow a specific gameObject only on Y axis without changing the camera's X axis position, in C#?

# Answer
> 3 votes
```
public class CameraFollow : MonoBehaviour {
    public Transform target;

    void Update () {
        transform.position = new Vector3(transform.position.x, target.position.y, -10);
    }
}

```

Attach it to the camera and set `target` to desired gameObject.

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


# Question
Title: Unity Additive particle effect blends with background
I created a fire particle effect with the Particles/Additive (Soft) shader in Unity 5.2.2, and it looks fine against a dark background, like the editor background:

However, when I move it in front of a lighter background, it looks like this:

I think the additive property is blending with the background, is there a workaround to make the effect look like how it looks on a dark background, without using a different shader?

I've looked at this question: How can I achieve a good fire effect with alpha blending and particles? but I'm not sure how I would execute that in Unity.

# Answer
There are 2 hacks I can think of with which you can acheive this.

1. You can create an alpha-blended 'mask particle system' for every additive particle system you create. Render the mask particle system first and then on top of it, render the actual one. This way all the particles in the paricle system will be 'guarded' by the consistent underlying alpha blended particle from the variable backgorund.

If you use unity's built-in particle system to create particles then you'll have to make sure that there isn't much randomness in the particle. Otherwise the mask will not be much identical to the real one and will create some 'unguarded' areas.

If you are using your own particle system then for every particle in the system you'll have to create an identical particle in the 'mask-particle-system' which will follow the exact path of its corresponding real-particle. Then, render the mask-system and then the real one.

The mask-particle-system should preferably use the full-black version of the particle texture.

**Fire particle**

**Fire particle mask**

You'll have to adjust the sorting layer order of the particle objects. This can done attaching the following script to all the particle systems. Set the `layerOrder` of mask system as 1 and that of real one as 2.

```
  `public int layerOrder;
    void Start () {
        ParticleSystem particleSys = GetComponent<ParticleSystem>();
        Renderer renderer = particleSys.GetComponent<Renderer>();
        renderer.sortingOrder = layerOrder;
    }`

```

This is what I acheived this way.

**No mask**

**With mask**

2. The second method is to use a separate camera for rendering the particle systems. Anything that needs to be drawn over the fire particles also need to be rendered by this new camera. Things might get tricky this way. You might not be able to easily and properly position stuff rendered by the new camera in respective to the ones rendered by the older one.

Both of these methods will have their impact on performance. You'll have to choose the one which best suits your needs
> 3 votes

---
Tags: unity, particles
---


# Question
Title: Is there a good way to get pixel-perfect collision detection in XNA?
Is there a well-known way (or perhaps reusable bit of code) for pixel-perfect collision detection in XNA?

I assume this would also use polygons (boxes/triangles/circles) for a first-pass, quick-test for collisions, and if that test indicated a collision, it would then search for a per-pixel collision.

This can be complicated, because we have to account for scale, rotation, and transparency.

**WARNING:** If you're using the sample code from the link from the answer below, be aware that **the scaling of the matrix is commented out for good reason.** You don't need to uncomment it out to get scaling to work.

# Answer
I see that you tagged the question as 2d, so I'll go ahead and dump my code:

```
class Sprite {

    [...]

    public bool CollidesWith(Sprite other)
    {
        // Default behavior uses per-pixel collision detection
        return CollidesWith(other, true);
    }

    public bool CollidesWith(Sprite other, bool calcPerPixel)
    {
        // Get dimensions of texture
        int widthOther = other.Texture.Width;
        int heightOther = other.Texture.Height;
        int widthMe = Texture.Width;
        int heightMe = Texture.Height;

        if ( calcPerPixel &&                                // if we need per pixel
            (( Math.Min(widthOther, heightOther) > 100) ||  // at least avoid doing it
            ( Math.Min(widthMe, heightMe) > 100)))          // for small sizes (nobody will notice :P)
        {
            return Bounds.Intersects(other.Bounds) // If simple intersection fails, don't even bother with per-pixel
                && PerPixelCollision(this, other);
        }

        return Bounds.Intersects(other.Bounds);
    }

    static bool PerPixelCollision(Sprite a, Sprite b)
    {
        // Get Color data of each Texture
        Color[] bitsA = new Color[a.Texture.Width * a.Texture.Height];
        a.Texture.GetData(bitsA);
        Color[] bitsB = new Color[b.Texture.Width * b.Texture.Height];
        b.Texture.GetData(bitsB);

        // Calculate the intersecting rectangle
        int x1 = Math.Max(a.Bounds.X, b.Bounds.X);
        int x2 = Math.Min(a.Bounds.X + a.Bounds.Width, b.Bounds.X + b.Bounds.Width);

        int y1 = Math.Max(a.Bounds.Y, b.Bounds.Y);
        int y2 = Math.Min(a.Bounds.Y + a.Bounds.Height, b.Bounds.Y + b.Bounds.Height);

         // For each single pixel in the intersecting rectangle
         for (int y = y1; y < y2; ++y)
         {
             for (int x = x1; x < x2; ++x)
             {
                 // Get the color from each texture
                 Color a = bitsA[(x - a.Bounds.X) + (y - a.Bounds.Y)*a.Texture.Width];
                 Color b = bitsB[(x - b.Bounds.X) + (y - b.Bounds.Y)*b.Texture.Width];

                 if (a.A != 0 && b.A != 0) // If both colors are not transparent (the alpha channel is not 0), then there is a collision
                 {
                     return true;
                 }
             }
         }
        // If no collision occurred by now, we're clear.
        return false;
    }

    private Rectangle bounds = Rectangle.Empty;
    public virtual Rectangle Bounds
    {
        get
        {
            return new Rectangle(
                (int)Position.X - Texture.Width,
                (int)Position.Y - Texture.Height,
                Texture.Width,
                Texture.Height);
        }

    }

```

**Edit**: While this code is almost self explanatory, I did feel bad for not having comments, so I added some ;) I also got rid of the bitwise operations since it was doing basically what the Color.A property does in a more complicated way ;)
> 22 votes

# Answer
On the App Hub, there is a very old sample that walks you through 2D collision detection from simple bounding boxes to pixel-tested on rotated and scaled sprites. It has been fully updated to 4.0. The whole series is worth a read if you are new to the topic.

http://xbox.create.msdn.com/en-US/education/catalog/tutorial/collision\_2d\_perpixel\_transformed

I also found Riemer Grootjans approach interesting in his 2D shooters game. http://www.riemers.net/eng/Tutorials/XNA/Csharp/series2d.php

(It takes him a little while to get to it... http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series2D/Coll\_Detection\_Overview.php ... but you may want to follow along to see the problem he's solving)

But I caution you that Riemers sample is not XNA 4.0 and you may have to do a little work to get it running. It's not difficult or mysterious work, however.
> 4 votes

# Answer
I recommend creating a black and white collision map. Program it so the black pixels are collision points. Give the character a collision map too; When processing maps, use a algorithm that will turn big squares of black pixels into collision rectangles. Save this rectangle data in an array. You can the use the Rectangle intersects function to look for collisions. You can also transform the collision map with the texture.

This is a lot like using a collision matrix but more advanced and you can transform it! consider building a collision map generator tool if you need it. If you make it work, please share the code with others!
> 0 votes

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


# Question
Title: How can I test my game for epilepsy-safety?
I've been developing a game which is *rather blinky* in terms of color and brightness contrasts. It's an iPhone game, so the screen will be quite small, but I've heard about *Wipeout XL* failing the epilepsy test.

How does one ensure that a game won't cause epileptic seizures for users?

I am an indie developer, so a low-budget solution would be ideal.

# Answer
> 16 votes
There is software available to perform epilepsy testing as defined by OFCOM, known as the Harding Test.

Unfortunately, the software seems to be commercial only and requires a data capture card for it to run, so it's not the most financially feasible solution for an indie dev. This can be found here: http://www.hardingfpa.tv/

However, there is an alternative for smaller companies at http://www.hardingtest.com which has reasonable rates without needing a dedicated machine to carry out the testing for you (you just upload a video of gameplay) - £75 for under 30 minutes, which isn't too bad.

A warning should be more than sufficient and covers your back should anything unfortunate arise from a user playing your game, but if you do want to get it tested, the option is there.

# Answer
> 9 votes
A group that studied the Pokemon epilepsy phenomenon came up with the following recommendations:

* Flashing images, especially those with red, should not flicker faster than three times per second. If the image does not have red, it still should not flicker faster than five times per second.
* Flashing images should not be displayed for a total duration of more than two seconds.
* Stripes, whirls and concentric circles should not take up a large part of the television screen.

Note that these are just recommendations, not cut-and-dry human thresholds for epileptic triggers. If your game violates any of these guiding principles, there is a good chance it may be dangerous; however, if it doesn't, that's still no guarantee that it is safe.

Sources: http://en.wikipedia.org/wiki/Denn%C5%8D\_Senshi\_Porygon http://onlinelibrary.wiley.com/doi/10.1111/j.0013-9580.2004.18903.x/abstract

# Answer
> 6 votes
You *cannot* make sure that your game will not trigger seizures, ever, since the thresholds differ by orders of magnitudes between individuals and beetween the same person on different days and under influence of a hundred other factors which you cannot know about (lighting conditions, distance to the display, sleep deprivation, stress level, background noise, alcohol intake, etc).

If you can, that is if it doesn't disturb the game's look and feel, you may try as jokoon said, reduce the flashing a bit. If that would "destroy" the game's look and feel, scratch the idea.

Regardless, if you see a reasonable possibility that your game might trigger epileptic fits, you should add a (loosely worded) warning somewhere on the download page or on the package.
Something like "Note: This game contains vivid graphics. Video games (in general) may cause...". This will give people who have a known seizure disorder a valuable hint, and that is as much as you can do -- for them, and for yourself.
You cannot prevent people from having seizures, but you can prevent them from filing a lawsuit against you claiming that you didn't warn them.

I would however avoid saying "*This* video game may cause..." because that would be
a) massively negative marketing and
b) possibly the opposite effect of what a disclaimer should achieve (one could argue: "Hey wait, you *knew* this game was designed in a dangerous way and you still sold it?")

# Answer
> 2 votes
I wouldn't trust internet on that. I'd prefer asking a doctor, an ophthalmologist or a neurologist. The only thing I think I'm sure I know (and shouldn't be trusted), is that epileptic reactions are caused by blinking colors, meaning: very different colors (mainly meaning the hue component of the color) alternating at some kind of some particular threshold frequency; this may be linked to the fact the human eye cannot perceive animation beyond 60Hz.

This is tightly linked to how the brain computes back and perceive images, but maybe and especially motion.

To be sure you won't trigger crisis in anybody, document yourself or ask somebody who has a speciality: epilepsy is not well known because it's part or neurology.

Try to make your game somewhat less blinky, blinking less rapidly or just fade; it will be more quiet for the eye/brain. Remember our brains aren't supposed to be used to artificial images and motion, so the more the thing you render compares to reality the more the better.

# Answer
> 0 votes
Here is some guidance: http://gameaccessibilityguidelines.com/avoid-flickering-images-and-repetitive-patterns

Bottom line is that you cannot test for epilepsy. Any game can cause a seizure. All you can do is test for common triggers.

If in doubt and if the effects can't be avoided, give people advance warning, and ideally an option to disable the effect. But don't say things like 'epilepsy safe mode', you're opening yourself up to a world of legal pain then. Just talk about the effect, e.g.

"this game contains flickering effects. They can be turned off in the settings menu"

---
Tags: graphics, testing, accessibility
---


# Question
Title: Sprites are rendered as black rectangles in android 4.0.x only
I have some problems rendering sprites correctly on a LG optimus vu (android version 4.0) with libgdx. Basically sprites are black rectangles, while other images that i declare as Texture are correct. I've tested my game with android 4.2 4.3 and 5.0 and I have no problems...

Is there some difference between 4.0 and 4.2 in graphics rendering? Maybe it's Gl10 and not Gl20?

# Answer
SOLVED by changing the atlas dimensions from 4096x4096 to 2048x2048. The atlas was generated using GDX Texture Packer.

Apparently, there is a problem on Android \< 4.0.3 in loading big images from the assets folder.
> 1 votes

---
Tags: android, libgdx, graphics
---


# Question
Title: How can I calculate current level from total XP, when each level requires proportionally more XP?
In my game, XP needed to reach the next level is *Current Level × Level Threshold*. Given that, how can I get my *current level* from the *total XP* ever earned?

---

For example:

```
Level Threshold = 50
Current Level = 1

```

Starting at level 1, I would need *(1 × 50) = 50* XP to get to level 2, and so on.

```
Level 1: 50 XP needed to reach level 2
Level 2: 100 more XP needed to reach level 3
Level 3: 150 more XP needed to reach level 4

```

In other words, the progression table is as follows:

```
Level 1: 0 XP to 49 XP
Level 2: 50 XP to 149 XP
Level 3: 150 XP to 299 XP
Level 4: 300 XP to 499 XP

```

If I have 300 XP, I'll just reached level 4. How can I calculate that generally?

# Answer
> 35 votes
When working out the maths and solving for the `Level` conditional on experience `XP`, we obtain:

$$Level = \frac{1 + \sqrt{1 + 8 \times XP \div 50}}{2}$$

For example, what is the player's level for \\$XP = 300\\$?

$$ \frac{1 + \sqrt{1 + 8 \times 300 \div 50}}{2} = 4 $$

As requested.

Or, what is the level for `XP = 100000`?

$$ \frac{1 + \sqrt{1 + 8 \times 100000 \div 50}}{2} = 63 $$

More generally expressed, for an *arbitrary starting threshold* at Level 1:

$$ Level = \frac{1 + \sqrt{1 + 8 \times threshold \div 50}}{2} $$

You can also do the reverse and calculate the `XP` needed for any given level by solving the above formula for XP.

$$ XP = \frac{(Level^2-Level) \times threshold}{2} $$

Note that the above formula works with fractions but you need to round down to the next integer value. For example in C++/C# you could use (int)Level.

To obtained the above closed form formula, I used difference equations, Gauss summation and a quadratic formula.

*If you are interested in the solution of this formula step by step...*

We do an recursive algorithm by starting our considerations that ultimately `Experience(next_level) = Experience(current_level) + current_level*50`.

For example, to obtain \\$XP\_{Level3}\\$ we have:

$$ XP\_{Level3} = XP\_{Level2} + 2 \times 50 $$

Where, `2*50` comes from the OP's request that experience needed to reach the next level is current level\*50.

Now, we substitute \\$Xp\_{Level2}\\$ with the same logic into the formula. That is:

Substitute \\$XP\_{Level2} = XP\_{Level1} + 2 \times 50\\$ into the above formula:

$$ Xp\_{Level3} = Xp\_{Level1} + 1 \times 50 + 2 \times 50 $$

and \\$ Xp\_{Level1} \\$ is just 50, which is our starting point. Hence

$$ Xp\_{Level3} = 50 + 2 \times 50 = 150 $$

We can recognize a pattern for recursively calculating higher levels and a finite chain of summations.

$$ Xp\_{LevelN} = 50 + 2 \times 50 + 3 \times 50 + ... + (N-1) \times 50 = \sum\_{i=0}^{n-1} i \times 50$$

Where N is the level to be achieved. To get the XP for the level N, we need to solve for N.

$$ Xp\_{LevelN} \div 50 = \sum\_{i=0}^{n-1} i $$

Now the right hand side is simply a summation from 1 to N-1, which can be expressed by the famous Gaussian summation \\$ N \times (N+1)\div2-N \\$. Hence

$$ Xp\_{LevelN} \div 50 = N(N+1) \div 2-N $$

or just

$$ 2\*(Xp\_{LevelN} - 50) \div 50 = N(N+1)-2N $$

Finally, putting everything on one side:

$$ 0 = N^2-N-2 \times Xp\_{LevelN} \div 50 $$

This is now a quadratic formula yielding a negative and positive solution, of which only the positive is relevant as there are no negative levels. We now obtain:

$$ N = \frac{1 + \sqrt{\frac{1+4 \times 2 \times Xp\_{LevelN}}{50}}}{2} $$

The current level conditional on XP and linear threshold is therefore:

$$ Level = \frac{1 + \sqrt{1+8\times XP \div threshold}}{2} $$

**Note** Knowing these steps can be useful to solve for even more complex progressions. In the RPG realm you will see besides a linear progression as here, the actually more common fractional power or square relationship, e.g. \\$Level = \frac{\sqrt{XP}}{5.0}\\$. However, for game implementation itself, I believe this solution to be less optimal as ideally you should know all your level progressions beforehand instead of calculating them at runtime. For my own engine, I use therefore pre-processed experience tables, which are more flexible and often faster. However, to write those tables first, or, to just merely ask yourself what `XP` is needed to, let's say, obtain `Level 100`, this formula provides the quickest way aimed at answering the OP's specific question.

**Edit**: This formula is fully working as it should and it outputs correctly the current `level` conditional on `XP` *with a linear threshold progression* as requested by the OP. (The previous formula outputted "level+1" by assuming the player started from Level 0, which was my erring--I had solved it on my lunch break by writing on a small tissue! :)

# Answer
> 26 votes
The *simple and generic* solution, if you don't need to repeat this calculation millions of times per second (and if you do, you're *probably* doing something wrong), is just to use a loop:

```
expLeft = playerExp
level = 1
while level < levelCap and expLeft >= 0:
    expLeft = expLeft - expToAdvanceFrom(level)
    level = level + 1

if expLeft < 0: level = level - 1     # correct overshoot

```

The big advantage of this method, besides requiring no complicated mathematics, is that it works for *any* arbitrary exp-per-level function. If you like, you can even just make up arbitrary exp values per level, and store them in a table.

If you do (for some strange reason) need an even faster solution, you can also precalculate the *total* amount of exp needed to reach each level, store this in a table, and use a binary search to find the player's level. The precalculation still takes time proportional to the total number of levels, but the lookup then requires only time proportional to the *logarithm* of the number of levels.

# Answer
> 11 votes
The question has been answered with code, but I think it should be answered with math. Someone might want to *understand* instead of just copy and paste.

Your system is easily described by a recurrence relation: $$ \text{XP}\_{\text{Level}+1} = \text{XP}\_{\text{Level}} + \text{Level} \cdot \text{Threshold} $$

Which offers a nice simple closed form solution for \\$\text{XP}\\$:

$$\text{XP}\_{\text{Level}} = \frac{(\text{Level}-1) \cdot \text{Level} \cdot \text{Threshold}}{2}$$

Which we can solve for \\$\text{Level}\\$:

$$\text{Level} = \left\lfloor \frac{\sqrt{\text{Threshold}^2 + 8 \cdot \text{XP} \cdot \text{Threshold}}}{2 \cdot \text{Threshold}}+\frac{1}{2} \right\rfloor$$

(truncate to integer, because the player needs **all** the required XP to get **any** of the level-up bonus)

# Answer
> 10 votes
Here's one approach to solving the problem using basic algebra. If you don't care about the steps, skip to the bottom.

An easy thing to come up with is, given a level `n`, the total experience `e` needed to obtain that level:

```
e = sum from k=1 to n of (t(k-1))

```

The `t` term stands for the increase in XP needed per level - 50, in the example.

We can solve the above using the formula for arithmetic sequences (sum identity):

```
e = t/2 * n(n-1)

```

However, we want the opposite formula - the player's level given their total experience. What we really want to do is solve for the level, `n`. First, let's group the terms:

```
n^2 - n - 2e/t = 0

```

Now we can use the quadratic formula:

```
n = (1 + sqrt(1+8e/t))/2

```

---

Final equation:

```
level = 0.5 + sqrt(1 + 8*(total experience)/(threshold)) / 2

```

# Answer
> 3 votes
All the math involved here is *very important* to know for all sorts of reasons, some of them applicable to game development.

**BUT**

This is a game development site, not a math site. So let's discuss how these things work not as algorithmic series, but as *sets*, because that is the sort of math that applies to leveling in games you might actually develop to sell, and this is the system that underlies most (but not all) leveling systems (at least historically).

Players tend to prefer nice, round numbers that are easy to remember and visualize, and nowhere is this more important than in a level-based game system where the player need X amounts of xp to advance to level Y.

There are two good reasons for picking round numbers:

* The level experience itself is a nice, round number "100; 200; 1,000,000; etc."
* The delta between levels tends to be *another* nice, round number the player can glance at and calculate in his head.

Round numbers are enjoyable. The purpose of games is to be enjoyable. Pleasantness is important, especially since the game dilemmas will often be anything but pleasant by design.

Why is this important to keep in mind?

**Most compound series algorithms do not produce nice, round numbers**

Most series do not stop at a pretty point (every answer I've seen here so far just goes on forever). So, what do we do? We approximate, and then we *determine what set of levels should apply to the game system*.

How do we know what approximations are appropriate? We consider what the point of leveling is within the game system.

Most games have level caps that kick in at some point. There are a few ways this can play out:

* The cap is encountered relatively early, where the level system only exists to help players get through the first phase of the game in a focused way to force them to learn the complete game system. Once they are "fully grown" the long-game begins.
* XP gain VS the difficulty level has a certain economy to it where yes, there is a level cap, but it is so far away that we expect players to complete the game about halfway through the leveling chart. In DQ/FF-style RPGs with multiple characters/classes it is more common to have different characters/classes be made to level easier by *gaining experience* at different rates than *changing the required XP for each level per character class*. That way players can easily remember the cute little round numbers as universal goals, and know that each character progresses toward them at some arbitrary rate set by the game system (`XP + (XP * Modifier)` or whatever).
* Level caps are based on external character category. That is, some factor outside the game system proper dictates what the level system looks like. This is becoming more common as many games are pay-to-win but free-to-play. A free player may be capped at lvl 70, a subscriber may be capped at lvl 80, a one-time purchase may advance someone a level beyond some universal cap, etc.
* Level caps are universal and tied to the game world in some way. This system has been popularized by WoW.
* Any other level cap system you might dream up that enhances gameplay in a smarter way than simply rewarding players for wasting more minutes of their life in your made-up world than the other players.

There *are* some game systems where there is no level cap and the system is algorithmically determined. Usually systems like this use some X-powers-of-Y system to make the numbers explode quickly. This makes it very easy to get to level L-1, reasonably expected that most players will get to level L, inordinately difficult to get to level L+1, and players will grow old and die before reaching L+2. In this case "L" is a level you have decided is the target level appropriate for play and at which normally would have capped the system but leave the option open for people to delude themselves into thinking its a good idea to XP forever. (Sinister!) In this sort of system the math found here makes perfect sense. But it is a very narrow, and rarely encountered case in actual games.

**So what do we do?**

*Calculate* the levels and XP? No. *Determine* the levels and XP? Yes.

You determine what levels mean, then decide what the available set of levels should be available. This decision comes down to either granularity within the game system (Is there a *huge* difference in power between levels? Does each level confer a new ability? etc.) and whether or not levels are used themselves as a gating system ("Can't go to the next town until you're lvl 10, kid.", or a competitive ladder system enforces level-based tiers, etc.).

The code for this is pretty straightforward, and is just range determination:

```
level(XP) when XP < 100  -> 1;
level(XP) when XP < 200  -> 2;
level(XP) when XP < 500  -> 3;
level(XP) when XP < 1000 -> 4;
% ...more levels...
level(XP) when XP > 1000000 -> 70. % level cap

```

Or with an if statement, or a case, or a chain of if/elif, or whatever the language you happen to be using supports (This part is the least interesting element of any game system, I just provide two ways because I happen to be in Erlang mode right now, and the above syntax may not be obvious to everyone.):

```
level(XP) ->
    if
        XP < 100  -> 1;
        XP < 200  -> 2;
        XP < 500  -> 3;
        XP < 1000 -> 4;
        % ...more levels...
        XP > 1000000 -> 70 % level cap
    end.

```

Is it amazing math? No. Not at all. Is it manual implementation of set element determination? Yep. That's all it is, and this is pretty much the way I've seen it *actually* done in most games throughout the years.

As a side note, this *should not* be done every time the player gains experience. Usually you keep track of "XP to go" as one value, and once the player either exhausts or surpasses the "to go" value (whichever way you're doing it) then you calculate this once to figure out where the player is really at, store that, calculate the next "to go" minus the leftover (if carrying XP forward is allowed) and repeat.

---
Tags: mathematics, progression
---


# Question
Title: How to change the speed of the gameobject moving on the itween path
I have set an itween path for an object to move.And I have written the code as

```
iTween.MoveTo(gameObject,iTween.Hash ("path",iTweenPath.GetPath("train"),"time",300));

```

The above code is working for me.

Now I need to apply the change in speed that mean,when i press "S" the object should move Slow,when I press "F" the object should move Fast,When I press "M" the object should move with a medium speed on the itween path.I have written a code for.Below is the code

```
void Update () {

    if(Input.GetKey(KeyCode.S))
    {
        iTween.MoveTo(gameObject,iTween.Hash ("path",iTweenPath.GetPath("train"),"time",300));

    }
    if(Input.GetKey(KeyCode.M))
    {
        iTween.MoveTo(gameObject,iTween.Hash ("path",iTweenPath.GetPath("train"),"time",100));

    }
    if(Input.GetKey(KeyCode.F))
    {
        iTween.MoveTo(gameObject,iTween.Hash ("path",iTweenPath.GetPath("train"),"time",50));

    }
}

```

When I runned my above code,and when I press "S" key its moving slowly,next when I press "F" the object is going back to the original position where it was and then it starts moving fast ,same as for the medium "M" also.

I need to change the speed of the object moving on the itween path specified by pressing the keys.Can anybody please help me out.

# Answer
According to the documentation, you can pass a speed argument.
> -1 votes

# Answer
This will set the speed to `8`:

```
Hashtable props = new Hashtable();
props.Add("path", iTweenPath.GetPath("train"));
props.Add("speed", 8f);

iTween.MoveTo(gameObject, props)

```

I like to create a hashtable with all the properties I want to set, then pass it in at a later date. It is of course a matter of preference; I just think it makes things look clearer.
> -1 votes

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


# Question
Title: Could not load dynamic library .\RenderSystem_GL_d. System Error: %1 is not a valid Win32 application
I am using OGRE 1.8.1 SDK for Visual C++ 2010 (32-bit) from ogre3d.org/download/sdk and Ogre\_VC10\_Express\_AppWizard\_1.8.0.exe downloaded from https://bitbucket.org/ogreaddons/ogreappwizards/downloads. After a successful build when i am runnin application i am getting following error:

OGRE EXCEPTION(7:InternalErrorException): Could not load dynamic library .\RenderSystem\_GL\_d. System Error: %1 is not a valid Win32 application.

in DynLib::load at ........\OgreMain\src\OgreDynLib.cpp (line 93)

Seems to me that there is a mismatch of some 32bit/64bit dlls but reinstalling directx didn't solved the problem. I am new to OGRE, kindly guide me on this and i am using windows 8(64bit) and Microsoft visual C++ 2010 Express.

Edit: I tried installing SDK and directly run SampleBrowser (Without using AppWizard) but same error occurred again(build was successful).

# Answer
> 0 votes
Try to use the 64-bit version of Ogre. I guess this is cause by different ABI of your application build with a 64-bit compiler and a 32-bit dll coming from the SDK which you installed. So when the lib-loader tries to load the rendersystem dll this will fail and you get the error.

When no 64-version is available try to compile Ogre on your own with your 64-bit compiler.

---
Tags: c++, ogre
---


title: libgdx automove Actor does not work

text:
# Question
Title: libgdx automove Actor does not work
I am trying to make my sprite start moving from the moment it is created and do its animation. It draws on the screen right and animates but doesn't move. It should start moving towards the direction it is facin this means right and if collision detected to stop the animation do whatever and continue the animation. Here is my code:

```
public class grt extends ApplicationAdapter {
 Misheva mshv;

@Override
public void create () {
    mshv = new Misheva();
    mshv.init();

}

@Override
public void render () {
    mshv.drawIt();
    mshv.act(Gdx.graphics.getDeltaTime());

}

@Override
public void dispose() {
    mshv.disposer();

     }

 }

```

Misheva.java

```
public class Misheva extends Actor {
int state;
TextureAtlas atl;
TextureRegion [] walk;
SpriteBatch batch;
Animation anim;
float stateTime;
float elapsed = 0;
int horizontalspeed = 10;

public void reset (){
    state = 0;
    stateTime = 0;
}

@Override
public void act(float delta) {
    super.act(delta);
    stateTime += delta;
    switch(state){
    case 0: setX(getX()-horizontalspeed*delta);

    }
}

public void drawIt(){
    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    batch.begin();
    elapsed += Gdx.graphics.getDeltaTime();
    batch.draw(anim.getKeyFrame(elapsed,true), 0, 0);
    batch.end();

}

public void init (){
    atl = new TextureAtlas(Gdx.files.internal("data/tomaton.atlas"));
    batch = new SpriteBatch();
    walk = new TextureRegion[3];
    walk[0]=atl.findRegion("tomato");
    walk[1]=atl.findRegion("t_walk2");
    walk[2]=atl.findRegion("t_walk1");
    anim = new Animation(1/10f,walk);
}

protected void disposer(){
    batch.dispose();
    atl.dispose();
    }

 }

```

# Answer
> 0 votes
You are always drawing the texture region at `0,0`. So you don't use the position of the actor at all.

To fix this use:

```
batch.draw(anim.getKeyFrame(elapsed,true), getX(), getY());

```

Depending on the coordinate system you use (y up/down) you need to adapt the value from `getY()`.

---

---

As a side note, the code you try to run is quite inefficient and even wrong if you draw more than one element.

```
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

```

This should only be called once in your render method (so best call it at the beginning of your `grt` class render method), since it clears the complete screen, so if you draw more than one element, you would only see the last one, since you clear it before you draw the next.

```
batch.begin();
batch.end();

```

Should only be called once too, for example when you start to draw your sprites.

Then you should take a look at the `Actions` class, as it provides methods to move actors (there are predefined actions).

---
Tags: libgdx, animation, movement, automation
---


# Question
Title: Switch beetween Screen on LibGdx application
i have set main class like this:

```
public class MyClass extends Game {
    MenuClass menuClass;
    ActionGame actionGame;

@Override
public void create() {
         menuClass = new MenuClass(this);
         actionGame = new ActionGame(this);
         setScreen(actionGame);
    }
}

```

and method of ActionGame class like this:

```
....
@Override
public void pause() {
    game.setScreen(game.menuClass);
}

@Override
public void resume() {
    this.show();
    this.render(Gdx.graphics.getDeltaTime());
}
....

```

and method of menuClass.java like this, when touch Play button:

```
....
@Override
public void resume() {
    game.actionGame.resume();
}
....

```

When i touch play button i wish that actionGame class return in action render, but the render don't start. I have try with setScreen, but this restart my screen, this not good. Help

Thanks

# Answer
> 1 votes
The method `pause` is called, when your app looses focus. On Android this happens, if you press the home button or a call is incoming. When you return to the app, `resume` gets called.
So if you switch from `GameScreen` to `MenuScreen` inside the `pause` method, and switch from `MenuScreen` to `Gamescreen` inside the `resum`, the `MenuScreen` will never show, as it is active only when your app is in background.
What you might want to do is to switch to `MenuScreen` on `pause`, but on `resume` don't switch back. Instead you should wait till the user presses a button `Continue` and then go back to the `GameScreen`.
Also, you should not call `pause` or `resume` yourself, those are methods called by the framework in specific situations.

**EDIT:**
I also noticed, that you call `show` method inside the `resume` method. The method `show` is another method, used by the framework. It is usually called, when you switch `Screen` (`setScreen` in the `Game` class calls `hide` for the current `Screnn` and `show` for the new `Screen`).
Also the `render` method should generally not be called by you. The `Game` class automatically calls the `render` of the current `Screen` in it's own `render`. So if you set the right `Screen`, the right `render` method will be called.

**EDIT 2:**
A possible approach for you might be the following:
Inside the `pause` method, save the game data, as it is possible, that the user closes the app (or Dalvik decides to close it cuase the system needs the ressources). You can also call `setScreen(menuScreen)` here. This call will result in a call to `actionGame.hide()`, where you might release some of the ressources used by the `GameScreen`. Then it will call `menuScreen.show()` where you might load ressources needed by the `MenuScreen`.
When you return to the app `menuScreen.resume()` will be called. You don't need to do anything here. Instead you should waint, till the menu button `Continue` is pressed. Here you can load the saved data and the `setScreen(gameScreen)`.

---
Tags: java, android, libgdx, screen
---


title: Bilinear Interpolation

text:
# Question
Title: Bilinear Interpolation
In the context of *bilinear interpolation*, if we look at the image below:

I'm confused about what `P` is exactly. I'm not sure if it's a point (as in (x, y)) or if it's a single value.

# Answer
You seem to have taken the image on Wikipedia, on the bilinear interpolation page. The legend of that image says

> \[...\] the green dot is the point at which we want to interpolate.

So the `P` is at first a `point` from which we want to find the `value`.

You submit a set of coordinates to the interpolation function (x, y), and it spits you a scalar (a single value).
> 2 votes

# Answer
the page where you probably get that image states : "The four red dots show the data points and the green dot is the point at which we want to interpolate."

So, you know the values at Q12,Q22,Q11,Q21 , and yoi want interpolate the value at point P
> 1 votes

---
Tags: mathematics
---


# Question
Title: Finding relative x and y value on a sprite [Gamemaker]
I'm having a little conundrum that may just result from a lack of knowledge of Gamemaker's functionality. I've attached two images to aid explanation.

I have a sprite of a turret (with a gun barrel), attached to a turret object, and at certain points in gameplay this object will spawn another object on top of it (let's call it the 'bullet object').

I would like the bullet object to spawn at the x and y coordinates at the end of the gun barrel. This would be easy to find as a pair of coordinates if the sprite was always stationary, in this configuration. Alas, it is not. It rotates like billy-oh. This means that the x and y coordinates at the end of the gun barrel are constantly different.

How do I find this constantly changing x and y coordinate? I imagine (though am most likely wrong) that there the initial x and y coordinates of the sprite are saved and can be found even if rotated; is there a function that does this? Or do I need to write a script and then call it every time I want to spawn the bullet object?

Thanks for your help.

# Answer
> 1 votes
Thanks, @Dmi7ry, for posting the answer to this question above in the comments. The functions to use here are `lengthdir_x` and `lengthdir_y`, as explained in the link to the other question.

For my purposes, I knew that the point on the turret that I want my bullet to appear at was 62 pixels out from the origin. The functions `lengthdir_x` and `lengthdir_y`allow you to find a set of coordinates out from an object's x/y origin by specifying how many pixels out from source you want, and in which direction. I knew that I needed to find a point 62 pixels out from origin, and that that point would need to be in whichever direction the turret object (and thus its barrel) was pointing, determined by the `image_angle`. Therefore:

```
instance_create(x + lengthdir_x(62, image_angle), y + lengthdir_y(62, image_angle), oBullet)

```

---
Tags: sprites, coordinates, game-maker, orientation
---


title: I can't create a "trap" block

text:
# Question
Title: I can't create a "trap" block
So, I am trying to make a "trap" block. It should kill the entity that will stand on it(or walk as in the code, if somebody knows how to make that it will do something while an entity stands on it, it will be helpful). Here's the code for the block:

```
package com.daniel_sl.blocks;

import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;

public class Trap extends Block{

  public boolean isDead;

  protected Trap(Material material) {
    super(material);
  }

  public void setDead()
  {
    this.isDead = true;
  }

  public void onEntityWalking(Entity Entity){
    if(Entity instanceof EntityLiving){

      Entity.setDead();
    }
  }
}

```

When I stand on the block it doesn't do anything.

# Answer
You might have a typing error. I would write the method of the method as follows:

```
public void onEntityWalking(Entity entity){
  if(entity instanceof EntityLiving){
      entity.setDead();
  }
}

```
> 1 votes

---
Tags: java, minecraft-modding
---


# Question
Title: Minecraft modding: onLanded and item type/positioning?
My question is about programming Minecraft mods. So i added a block to my Mod. Now I want, that when you drop a sugar on it, that it waits some time and then, if the sugar is still there, it will consume the sugar and spawn an item that i made for my mod. But I don't know how to test wether the item is sugar. I use the event onLanded with an

```
@Override
public void onLanded(World worldIn, Entity entityIn)
{
    if(entityIn instanceof EntityItem && !worldIn.isRemote)
    {

    }
}                                                                                }

```

but I don't know where to specify the item and where to get the position of the block.

I hope anyone can help me and sorry for my bad english I'm not a native speaker. Thank you in advance Nova

# Answer
> 0 votes
I have not tried it but to be more precise you could write:

```
//specialBlock is the
//block on which the sugar is supposed to react on
if(specialBlock.getLocation().getBlock().getRelative(BlockFace.UP) != null &&
   entityIn instance of Item.sugar) {

}

```

I called your block here **specialBlock**. Now you check if there is something on your block and if it is sugar..

---
Tags: java, minecraft-modding, modding
---


# Question
Title: Efficient datastructure to store a galaxy map
I'm working on a project for an intro level Ai class, and the project I've closen is to create a simulated universe in which Ai actors play against each other economically and militarily. I have the actual Ai fundamentals planned out, but I've hit a bit of a snag in trying to properly store the randomly generated game world.

The solar system objects are generated and populated randomly and the aim I'm going for is to place them in a 3d world, with x,y,z positions relative to a galactic center.

Each system should be reachable from any other system, limited only by the jump range of a given ship. Which I assume would mean that id need a 3d bounding algorithm to determine what other systems are in range.

For storing them, would a weighted edge graph be best, although the number of edges would be huge as in theory each system is reachable from any other. Or would an octree be better. And if so how would I calculate a list of reachable systems from the current system with an octree.

# Answer
> 2 votes
This is naturally modelled as a graph structure, as you knew when you posed the question. So let's look at how we can take a graph and make it more efficient.

Let's look at topological methods. Making N^2 checks at runtime is ridiculous as you suggest, so we rule that out. Now there are two ways we can proceed - order nodes in such a way that we are likely to find locals quickly (e.g. hilbert curves which still aren't going to be effective), or pre-cache everything as the complete graph in N nodes; if N^2 is *large*, memory use may be prohibitive. So we may as well forego topological / classic graph style storage altogether.

Okay, so let's look at geometric methods. This is where I can see why wondra suggested octrees, however I don't think it is necessary to go that far. All you need is a single-level/depth 3D grid with reasonably cell granularity. Pre-process: If there's at least one star system anywhere in a cell, mark it occupied... assume e.g. that cells are 1 AU wide/deep/high. Now snap a sphere of the appropriate radius to this grid, roughly centring around player's position, and iterate cells within that \[xyz\] cubic range (that neatly surrounds your sphere) to see where you have candidates for travel.

This works well because in reality, physics tend to cause systems to cluster, so you often have systems grouped within the same cell/bucket so that you could rapidly run through only what is local. Again to return to the octree suggestion, I would only suggest implementing this if you really have a very matter-heavy galaxy. Octrees / quadtrees introduce cost due to multi-level traversal that can easily make them slower than "flat" approaches, though that is always mitigated as size grows geometrically. If you like octrees? Then by all means.

Conceptually I'd say this is simplest though and allows you to get on with other things. I guess the granularity of the grid is something you're going to have to play with - depends on your dispersion.

**EDIT** k-means clustering is one way you could classify various star-clusters from your starting collection of star systems; you could then create routes between them - this would allow a more traditional graph structure but with the "buckets" necessary to do fast local searches.

---
Tags: java, collision-detection, maps, data-structure, world-design
---


title: Java heart based health mechanic

text:
# Question
Title: Java heart based health mechanic
so I've made a basic game in java w/ LWJGL 2 and Slick. Right now Im working on the hud and health system. I'm kindof trying to get a minecraft like health system, 15 hearts for health,but I want the health to change from level to level. Right now Ive got this:

```
    int z = (int) (Math.floor(hp/15)); // this is how many hearts are being drawn
    for(int k = 0; k < z; k++){
        if(z >= 15){
            z = 15; // here it says that it can't draw more than 15 hearts
        }
        g.drawImage(heart, x + k * 32, y); // it draws the hearts with some distance inbetween each heart
    }

```

I'd be happy if I get some suggestions on how could I add half a heart "mechanic", like if I have 30 max health and 15 hearts (allthought rightnow I have 200 hp, I wanna work with bigger numbers :P) that would mean that If I had 15 health it should draw 7 full hearts and 1 half heart. I don't exactly know how to do that. If you can please do help :D. Thank you

# Answer
You could try something like this

```
    int hp = 15;

    for(int i = 0; i < hp/2; i++)
         System.out.println("Heart");
    if(hp % 2 == 1)
        System.out.println("Half Heart");

```

Just replace the print calls with your graphics calls.
> 1 votes

---
Tags: java, mathematics, lwjgl, slick, hud
---


title: Draw 3D ellipse in monogame/xna

text:
# Question
Title: Draw 3D ellipse in monogame/xna
I am programming a 3d solar system (simulator). To describe the path of a planet I wanted to add 3D rectangles.. and draw them. But to no surprise it decreased the frame rate extremely. Also it does not look nice:

Do You know how to handle this problem? Is there another way to solve this? Didn't found anything on 3D HLSL Circle Plotting.

# Answer
> 1 votes
I got it. I used a strip of lines instead.

```
  private void CalculateEllipsoid()
    {
        Path = new VertexPositionColor[64];
        List<VertexPositionColor> Vertices = new List<VertexPositionColor>();

        for (double i = 0; i < 2 * Math.PI; i += 0.001(variable))
        {
            var x = (float)(this.CenterX + (this.MajorAxisA * GLOBALSCALE) * (float)(Math.Cos(i)));
            var y = (float)(this.CenterY + (this.MinorAxisB * GLOBALSCALE) * (float)(Math.Sin(i)));
            Vertices.Add(new VertexPositionColor(new Vector3(x, 0, y), Color.DarkGray));
        }

        Vertices.Add(new VertexPositionColor(
            new Vector3((float)(this.CenterX + (this.MajorAxisA * GLOBALSCALE) *
                (float)(Math.Cos(0))), 0,
                (float)(this.CenterY + (this.MinorAxisB * GLOBALSCALE) * (float)(Math.Sin(0)))), Color.DarkGray));

        Path = Vertices.ToArray();
    }

```

The method to calculate an ellipse:

```
    var x = (float)(this.CenterX + (this.MajorAxisA * GLOBALSCALE) * (float)(Math.Cos(i)));
    var y = (float)(this.CenterY + (this.MinorAxisB * GLOBALSCALE) * (float)(Math.Sin(i)));

```

is from here

https://stackoverflow.com/questions/9155750/rotate-some-elements-in-an-ellipse-path

To draw it

```
   public void DrawEllipsoid()
    {
        BasicEffect effect = new BasicEffect(Device);
        effect.World = Matrix.CreateTranslation(new Vector3(CelestialBody.GLOBALX, CelestialBody.GLOBALY, CelestialBody.GLOBALZ));
        effect.View = Camera.ViewMatrix;
        effect.Projection = Camera.ProjectionsMatrix;
        effect.LightingEnabled = false;
        effect.TextureEnabled = false;
        effect.VertexColorEnabled = true;
        effect.CurrentTechnique.Passes[0].Apply();
        Device.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.LineStrip, Path, 0, Path.Length - 1);
    }

```

The result:  ( =

# Answer
> 0 votes
An possible approach:

Each planet's orbital ellipse can be drawn using 4 vertices to form a quad. The quad is drawn with a texture on it that is transparent except for the outline of a perfect circle.

The quad is 1 unit by 1 unit. It uses a world matrix that locates it's center on the orbital center and rotates it's orientation so it is coplanar with the orbital plane.

The world matrix is then scaled in length and width (on 2 of it's 3 axes) as necessary to cause the circle to become elliptical (the quad will change from a square to a rectangle and enlarge) and its circle will lay on the same path as the planet.

You can create a new instance of the quad for each planet and the only thing that is different between the various instances of the quad is the world matrix.

---
Tags: xna, monogame, hlsl
---


title: Game over when both players die

text:
# Question
Title: Game over when both players die
I watched the Unity Space Shooter video tutorials and then I have added a second player. I can not seem to get the 'Game Over' when they both die. It will happen when one player dies but not both. Below is my code.

```
using System.Collections;

public class DestroyByContact : MonoBehaviour
{
  public GameObject explosion;
  public GameObject playerExplosion;
  public GameObject player2Explosion;
  public int scoreValue;

  private bool P1Dead;
  private bool P2Dead;
  private GameController gameController;

  void Start ()
  {
    P1Dead = false;
    P2Dead = false;
    GameObject gameControllerObject = GameObject.FindWithTag ("GameController");

    if (gameControllerObject != null)
      gameController = gameControllerObject.GetComponent < GameController> ();

    if (gameController == null)
      Debug.Log ("Cannot find 'GameController' script");
  }

  void OnTriggerEnter(Collider other)
  {
    if (other.CompareTag ("Boundary") || other.CompareTag ("Enemy"))
      return;

    if (explosion != null)
      Instantiate (explosion, transform.position, transform.rotation);

    if (other.CompareTag ("Player"))
    {
      Instantiate (playerExplosion, other.transform.position, other.transform.rotation);
      P1Dead = true;
    }

    if (other.CompareTag ("Player2"))
    {
      P2Dead = true;
      Instantiate (player2Explosion, other.transform.position, other.transform.rotation);
    }

    if (P1Dead == true & P2Dead == true)
      gameController.GameOver ();

    gameController.AddScore (scoreValue);
    Destroy(gameObject);
    Destroy(other.gameObject);
  }
}

```

# Answer
> 4 votes
`if (P1Dead == true & P2Dead == true)`

That looks like a typo. Performing bitwise "and" instead of logic &.

Try this:

`if (P1Dead == true && P2Dead == true)`

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