# Question
Title: Scrolling background after firing projectile
I have a projectile which I fire using the mouse coords as the direction vector which I scale with a velocity vector and add a gravity vector to complete this simple simulation.

I want to scroll the background in some elegant way, so that I can keep the projectile centred in the red (viewport) whilst following it until I can no longer centre it.

*Edit:*

When the projectile starts it will be at the left edge so I cannot centre here as there's no room outside the scene, same if the projectile gets to the end of my scene.

How is this situation usually solved?

# Answer
Declare an x value for your camera, and then offset everything (projectile, scenery, etc.) by that camera's X. For example, If I want my camera to be 500 pixels to the right, but projectile is 600 pixels to the right, I draw the projectile on the screen at projectileX - cameraX = 600 - 500 = 100 pixels.

There are three possible states for your camera:

* The target of the camera (the projectile) is less that half the window width away from the left edge, where we want to lock the camera to the left edge
* The target is less that half the window width away from the right edge, where we want to lock the camera to the right edge.
* The target is somewhere in the middle, so it should be centered in the window

Now, lets say your game window is `camWidth` wide, your stage is `stageWidth` wide, and the projectiles x relative to the stage is `tarX`, and the camera's left edge x relative to the stage is `camX`. Your code will look something like this:

```
halfcamWidth = camWidth / 2
if tarX < halfcamWidth:
    camX = 0
else if tarX > stageWidth - halfcamWidth:
    camX = stageWidth - camWidth
else:
    camX = tarX - halfcamWidth

```

Then each drawing loop, draw the projectile at `tarX - camX`.
> 3 votes

# Answer
All you need to do is say that when the projectile is past halfway in the X direction, you should center the camera on the projectile until the camera cannot go any further.

edit: pseudo code as requested

`//Check that projectile is past half the screen width
if projectile.x > (screenwidth / 2)
 //get background to follow projectile
 background.xPos = -1 * (projectile.x - (screenwidth/2))
 # Draw the projectile in the middle of the screen
 projectile.drawposX = screenwidth / 2`
> 0 votes

---
Tags: vector, projectile-physics
---


# Question
Title: What colors to choose for colorblind people?
I'm creating a game. Color coding is its main gameplay feature. What colors should I choose so the game will be colorblind-friendly? (I need 4 colors)

# Answer
There are different kinds of color blindness which occur in different intensities.

The most frequent ones are red-green blindness and yellow-blue blindness (each indicating which two colors affected people can **not** tell apart).

Here are different forms of color blindness and how frequently they occur in the general population. Source of these numbers is the Wikipedia article on color blindness:

```
              men    women
red-green       9%     0.5%
blue-yellow   < 1%    <1%
all colors    (negligible)

```

As you can see, red-green blindness is by far the most common form of color blindness. However, it predominately affects men. For women, it is even less frequent than the next most frequent kind: blue-yellow blindness. So keep your target demographic in mind when you prioritize different kinds of color blindness.

The most flexible way to take care of any form of color-blindness is simply to make the colors used by your game configurable in the options menu. That way every player can set a color combination which works for them.

Or you can use this palette from the article *Color Universal Design (CUD) How to make figures and presentations that are friendly to Colorblind people* by Masataka Okabe and Kei Ito.

By the way: You might want to skim the whole article. While it focuses on scientific presentations in front of an audience, it also has plenty of advise which is transferable to game design.

Here's a copy paste friendly version of the above picture:

C,M,Y,K (%)

```
(0,0,0,100)
(0.50,100,0)
(80,0.0,0)
(97,0,75,0)
(10,5,90,0)
(100,50,0,0)
(0,80,100,0)
(10,70,0,0)

```

R,G,B (0-255)

```
(0,0,0)
(230,159,0)
(86,180,233)
(0,158,115)
(240,228,66)
(0,114,178)
(213,94,0)
(204,121,167)

```

R,G,B (%)

```
(0,0,0)
(90,60,0)
(35,70,90)
(0.60,50)
(95,90,25)
(0,45,70)
(80,40,0)
(80.60,70)

```

Hex codes

```
#000000
#E69F00
#56B4E9
#009E73
#F0E442
#0072B2
#D55E00
#CC79A7

```
> 14 votes

# Answer
I'm mainly red/green color blind. The colors I always choose when given a choice in situations like this, are:

* Red
* Blue
* Yellow
* Grey

Those I can always tell apart.

Color combinations I have problems with are mainly the following:

* Red/green
* Red/brown
* Green/brown
* Yellow/orange
* Red/orange
* Pink/grey
* Sky-blue/light grey
* Purple/dark blue

Hope it helps :-)
> 5 votes

# Answer
*The following is informed by my experience as someone with slight red/green colorblindness - specifically protanomaly.*

When choosing colors, think about differentiating colors by **brightness** in addition to just **hue**.

A naive approach in choosing colors is to say "Okay, I need four colors. Let's go with primaries: red, green, blue and yellow. So that's #FF0000, #00FF00, #0000FF, and #FFFF00. Done!"

The problem with this approach is that all your colors are sitting at maximum brightness. Someone who has difficulty with red/green colorblindness might not be able to tell the difference between maximally bright yellow (red+green) and maximally bright green (or red).

Instead, in addition to spacing the colors out by hue, you should also space them by *brightness*. For example, don't have *bright* green and *bright* yellow, but have a *dark* green versus a *bright* yellow, to help out those people who may have red/green colorblindness. Even if they can't distinguish the hue of the color, they can tell that the colors are different by their brightness.

This isn't a foolproof method, of course. There's a wide range of colorblindness types, and certain types are less about not being able to distinguish between different colors and more about not having the same sensitivity to particular wavelengths, so the perceived brightness for a colorblind person will be different than for a non-colorblind person. (This is what happens with my protanomaly. I'm less sensitive to red light than the average person, so reds are darker for me than for others: really dark red is easily confused with black, and I can pick up the green much better than the reds in fully saturated computer yellow, so it's easily confused with fully saturated computer green, as are dark blues with dark purples. - Though I can still pick up large differences in brightness.)

Adding a "colorblind mode" where something else besides color (e.g. shapes) is used to distinguish things is also a good idea. But keep in mind that there's a range of severity in colorblindness, and many "colorblind" people can still perceive colors. So your "colorblind mode" should *add* extra distinguishing factors, rather than *replacing* the color. (I've seen games which turn everything black & white in "colorblind mode".) Ideally you should be able to have your "colorblind" features on all the time.

But one thing you definitely want to do is to extensively play test you game with things "de-hued". Either through some colorblindness simulator (but remember the multiple types), or simply by converting everything to greyscale. I've experienced a few games whose "colorblind mode" was obviously an afterthought. For example, one game just added numeric labels to the colored balls. The problem with this was that the game was time-sensitive and distinguishing between a 2 and a 3 is harder (takes a fraction of a second longer) than distinguishing between colors. So levels that were comfortable for normal sighted persons using colors were unplayable to someone relying on the labels.
> 3 votes

# Answer
Whenever I need to pick a set of colours, I use colorbrewer. Even though it is technically for maps, you can it for everything, and they let you choose between different pallets based on your preferences (like colour blindness).
> 2 votes

# Answer
There are different types of colorblindness, so you may not be able to be friendly with all of them, but the two major types are red-green and blue-yellow colorblindness.

This means that these people have trouble differenciating red from green or yellow from blue. So for your game, try avoiding **red** AND **green** at the same time (same goes for yellow and blue).
> 1 votes

# Answer
To add to the other answers, you can use a colorblindness simulator such as Color Oracle to detect problems with your color scheme.

Also, while this may not be applicable to your game, Jon Blow of The Witness made sure that puzzles which depended on discerning different colors were optional.
> 1 votes

---
Tags: game-design, accessibility
---


# Question
Title: Why the layer must be created from my class and not from layer class
I am confused about something. I have the following example:

**mainMenu.h**

```
class mainMenu : public Node {
public:
    static Scene* createScene();
    virtual bool init();
    void GoToGameScene(Ref *pSender);
    CREATE_FUNC(mainMenu);

private:
    mainMenu() {};
    ~mainMenu() {};

};

```

**mainMenu.cpp**

```
Scene* mainScene::createScene(){
    auto scene = Scene::create();
    auto layer = mainScene::create();
    scene->addChild(layer);

    return scene;
}

```

Focus on this part.

```
auto scene = Scene::create();
auto layer = mainScene::create();

```

Why do we create layer from `mainScene` not from `Layer`

For example: Why we do this:

```
auto layer = mainScene::create();

```

If we can do it, like creating a scene

```
auto layer = Layer::create();

```

# Answer
First of all, it's very uncommon to start classnames with a lowercase letter. It makes the code harder to understand.

Second, I'm not sure if I got your question right, but it seems like you're asking: **Why call a `create()` method on the `mainScene` class instead of just using a simple `Layer::create()`?**

If that's the case then the answer is quite simply: Because in this way we can customize how the `mainScene` should be initialized. Perhaps it needs several layers, like a HUD layer, a game layer, a controls layer, etc. By calling its `create()` method we make sure the constructor of `mainScene` is called, but also it's created as a `Ref` object, meaning that it'll be reference counted and therefore the memory management will be done automagically (for the most part).

If that wasn't the question feel free to explain it to me a bit further.
> 1 votes

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


# Question
Title: Modifying UV's origin on shader (OpenGL)
Is there a way to change the UV's origin (bottom-left) on shader?

# Answer
Yes, you can use a texture matrix. In addition to your model, view, and projection matrices, you can pass a texture matrix to your shader. Before using the UV coordinates, you can multiply them by the matrix and use the result of the multiplication. For something as simple as just a translation, you could just pass a vector with the translation in it, and add that to the UV coords, but a matrix is more general if you change your mind later.
> 3 votes

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


# Question
Title: What is the best way to avoid colorblind issues?
About 5-10% of males have some form of colorblindness. What's the best way to ensure you are not turning away 5-10% of your male population from your game?

Just to note colorblindness does not mean people see in black and white. It usually means they see less green and get red/green confused easily. Colorblindness comes in degrees. Some forms are mild some are extreme.

# Answer
> 18 votes
Don't make game critical functions or gameplay based off of the colors that might confuse players.

Let's consider a game like Bejeweled. Let's say that a color blind person can not determine the difference in the red or green gems. They are going to have a lot trouble swapping gems if they can't determine what color a gem is.

You could fix a problem like this by including a second way to differentiate between the red and green gems. One example would be to give them different **shapes**, such that each color has its own unique shape.

# Answer
> 16 votes
Use things other than colours to different key games items.

Patterns and Shapes are very helpful.

Also this Vischeck website provides very good information, and a set of photoshop filters you can use to check your assest

# Answer
> 9 votes
The most basic answer is to use shapes, but that doesn't solve all the problems. What about colored text hovering over player's head to show their game name?

Here are all the fixes for colorblind issues I know of:

1. Use shapes instead of color
2. Use saturated colors (red and green are actually fine when saturated, but green and yellow never are)
3. Use Red/Blue instead of Red/Green (Counter-Strike used this Red for T and Blue for CT. This solves the problem for most people, but for less than 2% of people they have even more severe colorblind issues)
4. Use high contrast outlines around all important text (eg. Blue text with white outline stands out on anything)
5. For all important events in the game use a combination of color, shape, and sound.
6. Don't use thin colored shapes. The thicker the shape (eg. bigger text) the easier it is to tell colors
7. **Allow end user to change all colors in game** (the most important solution to them all)

# Answer
> 5 votes
This is an interesting topic, I often refer back to this page: http://wearecolorblind.com/articles/quick-tips/ and the resources linked above seem quite good too.

Some of the issues are not as severe as you might think: for example red and green gems in a matching game may be perfectly fine if one is brighter (usually that would be green).

I actually had the chance to test Audiosurf on a colourblind user for a class, and found there was only one issue. For those who don't know it, Audiosurf involves matching coloured blocks (red, yellow, green, blue and purple) in most modes, however the "mono" mode reduces them to coloured blocks that change colour and grey blocks. In mono mode the objective is to collect all the coloured blocks and avoid all grey ones, but at some points they looked identical to the colour blind user.

Audiosurf now includes the ability to change block colour settings. Valve games also often have a "colour blind" mode which may be worth looking at. So I'd say with so many colour blind people around, you may be able to find some test subjects of your own and check any gaps with the vischeck plugin linked above.

# Answer
> 4 votes
I'm mildly colour blind and always find that I get along best with games that use very contrasting colours. The best example I can think of is TF2 where everything was either red or blue with very little exceptions. You would have to be severely colour blind to have trouble with two very different colours like that.

# Answer
> 4 votes
My father has some mild color blindness, and my cousin has a severe red/green blindness (he see both as yellow... something that makes things worse, since when he see a colour it may be yellow, or red, or green...)

My family feared that I would be colour blind too (I DO confuse some colours, mostly blue and black and dark blue with dark green... but it is not colour blindness it seems), so we researched a lot...

Basically, 7% of the US population (seemly worldwide is 10% among caucasians and maybe asians... I have no data for black people) is colour blind in varying degrees but of the same type of my cousin (ie: see both red and green as yellow)

So, the solution is basically don't use red, green and yellow as important gameplay elements...

I for example made my current game based on colors, but you can still understand the game if you only see the difference between red and blue, and the majority of the population can see the difference between those two colours (they are on the opposite sides of the spectrum and have mostly no overlap in our "sensors", even if the person have only a single colour sensor in his retina, he will see one of these two colours and see the other as yellow or gray, but unless you have some bizarre brain problem, it is impossible to see red as blue, or blue as red)

A BAAAAD example is Bioshock 2, it has a minigame where the background is yellow, and you have to stop a pointer above either red or green... If you use some filters that simulate colour blindness you will see that almost all types colour blindness result in this minigame breaking, or the green and red become hard to distinguish, or one of the two colours blend in the yellow background, the only people that can play this minigame properly while having colour blindness are those that don't see the blue colour...

# Answer
> 3 votes
The obvious answer is don't make any gameplay that relies on the ability to differentiate colours - e.g. in a match-3 game, make sure each colour of jewel also has a different shape.

# Answer
> 3 votes
In addition to using additional differentiating features beyond color (such as shape or text), using a different amount of color saturation in different colors will make them look different, even if the colors themselves appear the same.

# Answer
> 3 votes
You can use this palette from the article *Color Universal Design (CUD) \- How to make figures and presentations that are friendly to Colorblind people -* by Masataka Okabe and Kei Ito.

Another option is to make the colors used by your game configurable in the options menu. That way everyone can figure out a set of colors which works for them.

# Answer
> 2 votes
The most common form of colorblindness you have to deal with is red/green. It effects ~7% of the male population in the US, not sure how well that holds up globally, as it's slightly more prevalent in Caucasians. The only other common form is also green oriented. The others are forms are often found in less than 1% of the population.

Unfortunately Red/Green are used pretty commonly to designate stop/go and bad/good culturally, at least in the US. The three best options as have been mentioned are to include shape differences as well as color, use different values/saturations, and most commonly avoid green as an identifier when possible. Hence the reason good guys & bad guys are often designated as Red vs. Blue in games.

# Answer
> 2 votes
All the information you need is here, together with examples:

http://gameaccessibilityguidelines.com/ensure-no-essential-information-is-conveyed-by-a-colour-alone

First port of call is to avoid relying on colour alone. Then test using a simulator for the most common types to pick up on contrast issues, e.g. red on black. If you're still unavoidably using colour, e.g team colors that need instant recognition, allow the colours of the relevant elements to be customised. Ideally free choice + presets for the most common types.

Colororacle.org has the most accurate simulator currently available.

Common mistakes to avoid -

1. Assuming CBness is about 'red-green' (which doesn't exist, it's two similar but separate things - red deficiency and green deficiency) or deuteranopia/protanopia/tritanopia, there are other and sometimes unique types, even different type in each eye, or whole ranges of colours swapped around.
2. Filters, the idea of a simple universal effect that will fix it all for you is a seductive one, but it isn't effective.
3. Validating with real people. This can't be done as CBness is so varied, and on top of that many people don't know what type or what severity they actually have. Instead, use simulators for validation, and real people as a way to pick up on extra issues you may have missed.

Again this is just a summary, the full info is at the above link.

---
Tags: color, accessibility
---


title: JavaScript Collision Detection bug

text:
# Question
Title: JavaScript Collision Detection bug
Hello to all who are reading this post In trying to make Mario type of game but I have some collision bug maybe someone can explain to me whats is incorrect and how to fix it

Collision part there while be hard coded value I can't jump on box correctly is hard to explain if it's not hard just cache js fiddle link!

controls on arrow's space jump the issues is with jumping

And here while be a full code to look at or play whit it on js fiddle

```
var hero = {
    X: 200,
    Y: 450,
    gravity: 0.05,
    gravitySpeed: 0,
    speed: 2,
    height: 50,
    width: 50

}

var box = {
    X: 300,
    Y: 450,
    height: 50,
    width: 50
}
var map = {
    gravity: 0.5,
    groundY: 350

}
var optiones = {
    crashWith: function () {
        var myleft = hero.X;
        var myright = hero.X + (50);
        var mytop = hero.Y;
        var mybottom = hero.Y + (50);

        var otherleft = box.X;
        var otherright = box.X + (50);
        var othertop = otherobj.y;
        var otherbottom = box.Y + (50);
        var crash = true;
//Hard coded values
        var Y = 450,
            X = 300,
            w = 50,
            h = 50
        // not tuching
        if ((mybottom < othertop) ||
            (mytop > otherbottom) ||
            (myright < otherleft) ||
            (myleft > otherright)) {
            crash = false;
            //            console.log("dont tuch")
            hero.Y += hero.gravitySpeed;
            hero.gravitySpeed += hero.gravity;
        } else {
            // collision rules
            if (mytop >= othertop && othertop < otherbottom) {
                if (hero.X <= X) {
                    hero.X = X - hero.width
                } else if (hero.X > X) {
                    hero.X = X + hero.width
                }
            } else if (hero.X >= X && hero.X <= X + w) {

                if (hero.Y <= Y) {

                    hero.Y = Y - hero.height
                } else if (hero.Y >= Y) {
                    hero.Y = Y + hero.height
                }
            }

        }
```

# Answer
> 2 votes
Do this on line 103

```
hero.jumping = false;

```

And change the conditional on line 100 to this:

```
hero.X + w >= X && hero.X <= X + w

```

There are many other things wrong with your code though...

# Answer
> 1 votes
```
(mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)

```

This will always be true, no matter what, because an object is alway either to the left from the right side of another, or to the right from the left side of the same object, etc.. You need to change the ORs to ANDs.

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


title: Ball collisions 'sticking' together

text:
# Question
Title: Ball collisions 'sticking' together
I have a program which simulates many bouncing balls. The balls can bounce off each other and off the sides of the container.

The problem I am having is that sometimes when two balls collide, they get stuck together, overlapping very slightly. They will not come apart on their own, but may disperse if another ball knocks into them.

Here is my collision detection and resolution code:

```
public void handleCollisions(){
        double xDist, yDist, distanceBetween;
        for(int i = 0; i < balls.size(); i++){
            Ball A = balls.get(i);
            for(int j = i+1; j < balls.size(); j++){
                Ball B = balls.get(j);
                xDist = Math.abs(A.getCenterX() - B.getCenterX());
                yDist = Math.abs(A.getCenterY() - B.getCenterY());
                distanceBetween = Math.sqrt(xDist*xDist + yDist*yDist);
                if(distanceBetween <= (A.radius + B.radius)){
                        double dx = A.getCenterX() - B.getCenterX();
                        double dy = A.getCenterY() - B.getCenterY();
                        double collisionAngle =  Math.atan2(dy, dx);
                        double magnitudeA =  Math.sqrt(A.xVel*A.xVel + A.yVel*A.yVel);
                        double magnitudeB =  Math.sqrt(B.xVel*B.xVel + B.yVel*B.yVel);
                        double directionA =  Math.atan2(A.yVel, A.xVel);
                        double directionB =  Math.atan2(B.yVel, B.xVel);
                        double xVelOnCollisionAxisA = magnitudeA*Math.cos(directionA - collisionAngle);
                        double yVelOnCollisionAxisA = magnitudeA*Math.sin(directionA - collisionAngle);
                        double xVelOnCollisionAxisB = magnitudeB*Math.cos(directionB - collisionAngle);
                        double yVelOnCollisionAxisB = magnitudeB*Math.sin(directionB - collisionAngle);
                        double postCollisionXVelA = ((A.mass - B.mass)*xVelOnCollisionAxisA + (B.mass*2)*xVelOnCollisionAxisB) /(A.mass + B.mass);
                        double postCollisionXVelB = ((A.mass*2) * xVelOnCollisionAxisA + (B.mass - A.mass)*xVelOnCollisionAxisB)/ (A.mass + B.mass);
                        A.xVel =  (Math.cos(collisionAngle)*postCollisionXVelA + Math.cos(collisionAngle+Math.PI/2)*yVelOnCollisionAxisA);
                        A.yVel =  (Math.sin(collisionAngle)*postCollisionXVelA + Math.sin(collisionAngle+Math.PI/2)*yVelOnCollisionAxisA);
                        B.xVel =  (Math.cos(collisionAngle)*postCollisionXVelB + Math.cos(collisionAngle+Math.PI/2)*yVelOnCollisionAxisB);
                        B.yVel =  (Math.sin(collisionAngle)*postCollisionXVelB + Math.sin(collisionAngle+Math.PI/2)*yVelOnCollisionAxisB);
                }
                }
            }
        }

```

So essentially, the method iterates through all possible combinations of two balls. If the distance between them is less than the sum of their radii then a collision is detected and the velocities of each ball are changed.

The next method to run will update the positions of the balls, before the above method is called again.

It appears that my problem occurs when a collision is detected, but on the next pass of the function, the ball is still seen as being inside the other ball and receives a collision whilst trying to get out.

I have tried adding this code when a collision is detected. I expected this to solve the problem by moving the balls to their last position before the collision, but the problem persists

```
                        A.posX -= A.xVel;
                        A.posY -= A.yVel;
                        B.posX -= B.xVel;
                        B.posY -= B.yVel;

```

Actually for multiple balls, I'm not sure the above snippet is a good idea anyway.

# Answer
**The very simple solution:**
Check whether the balls are moving towards or away from one another, perform the collision only if they are moving towards one another.

**The badly needed change:**
Your code is pretty much walking circles around the concept of vector maths, you do not need the trigonometric functions at all.

```
public void handleCollisions(){
    double xDist, yDist;
    for(int i = 0; i < balls.size(); i++){
        Ball A = balls.get(i);
        for(int j = i+1; j < balls.size(); j++){
            Ball B = balls.get(j);
            xDist = A.getCenterX() - B.getCenterX();
            yDist = A.getCenterY() - B.getCenterY();
            double distSquared = xDist*xDist + yDist*yDist;
            //Check the squared distances instead of the the distances, same result, but avoids a square root.
            if(distSquared <= (A.radius + B.radius)*(A.radius + B.radius)){
                double xVelocity = B.xVel - A.xVel;
                double yVelocity = B.yVel - A.yVel;
                double dotProduct = xDist*xVelocity + yDist*yVelocity;
                //Neat vector maths, used for checking if the objects moves towards one another.
                if(dotProduct > 0){
                    double collisionScale = dotProduct / distSquared;
                    double xCollision = xDist * collisionScale;
                    double yCollision = yDist * collisionScale;
                    //The Collision vector is the speed difference projected on the Dist vector,
                    //thus it is the component of the speed difference needed for the collision.
                    double combinedMass = A.mass + B.mass;
                    double collisionWeightA = 2 * B.mass / combinedMass;
                    double collisionWeightB = 2 * A.mass / combinedMass;
                    A.xVel += collisionWeightA * xCollision;
                    A.yVel += collisionWeightA * yCollision;
                    B.xVel -= collisionWeightB * xCollision;
                    B.yVel -= collisionWeightB * yCollision;
                }
            }
        }
    }
}

```

Since it is Java I haven't tested this code, so if it behaves strange, there is a bug somewhere.

Go and learn some vector maths, it is incredibly useful.
> 11 votes

# Answer
Handling simultaneous collisions between more than two balls (e.g. balls A and B simultaneously colliding with C) is *hard*. And yet it's bound to happen when you have a lot of balls in a small space. You want to think not just in terms of separating pairs of balls but in terms of conserving energy and momentum while respecting each collision's restitution.

I'm not sure whether SIGGRAPH has published anything more recent, but the paper which I used as a basis for multiple collision handling in my most physics-demanding game was

**Complementarity Based Multiple Point Collision Resolution**
Thanh Giang, Gareth Bradshaw and Carol O'Sullivan
*Eurographics Ireland Workshop, pp1 - 7 (2003)*
http://isg.cs.tcd.ie/cosulliv/Pubs/GiangEgirl03.pdf
> 2 votes

# Answer
I had a similar problem and just added a loop after updating the velocities that fixed it. The loop checks whether the two balls are colliding and moves both of them if they are, until they are no longer within each other's range.

Something like:

```
 while (distanceBetween <= (A.radius + B.radius)) {
 A.move();
 B.move();
 }

```

That should follow immediately after updating the velocities to make sure the balls move away from each other.
> 1 votes

# Answer
I would say you have to get the balls out of each others radius first. Let's say push the target ball 1pixel out of the second ball's radius so the collision detection won't happen in the next loop. Then you can reverse the velocities.
> 0 votes

---
Tags: java, collision-detection, collision-resolution
---


# Question
Title: Data overwritten in MapSubresource() method
I am trying to dynamically update the vertex buffer in a UWP project using SharpDX, once every time I call the following method, where context is the device context member.

```
public void UpdateVertexBuffer(ScatterVertex data)
            {
                DataBox dataBox =
                this.context.MapSubresource(
                    scatterPointVertexBuffer,
                    0,
                    D3D11.MapMode.WriteNoOverwrite,
                    D3D11.MapFlags.None
                    );
                var pointer = dataBox.DataPointer;
                pointer = Utilities.WriteAndPosition(pointer, ref data);

                this.context.UnmapSubresource(scatterPointVertexBuffer, 0);
            }

```

I am expecting to keep the old data during the update process. However each time I call this method, the previous data is overwritten. I checked the pointer of `dataBox.DataPointer` and it remains the same value in every call.

Using `DataStream` as output doesn't help either. In either cases if I check the vertex buffer I get only one vertex.

But shouldn't the `MapSubresource` method protect the old data if I choose the `WriteNoOverwrite` mode?

What should I do to keep the previous data during update?

# Answer
Yes u have the same buffer but each time you are writing to the same place, you need to keep track of your position in the buffer and increment it each update and also make sure you don't go out of bounds.

Maybe pull your pointer var out of that method and make it class scoped.

It should work just like writing to a memory stream.

The pointer that databox gives u is the start of the buffer.

```
private pointer;
private bool First = true;

public void UpdateVertexBuffer(ScatterVertex data)
        {
            DataBox dataBox;
           if (First )
           {

            dataBox =
            this.context.MapSubresource(
                scatterPointVertexBuffer,
                0,
                D3D11.MapMode.WriteDiscard,
                D3D11.MapFlags.None
                );
              pointer = dataBox.DataPointer;
              first = false;
           }
          else
          {
           dataBox =
            this.context.MapSubresource(
                scatterPointVertexBuffer,
                0,
                D3D11.MapMode.WriteNoOverwrite,
                D3D11.MapFlags.None
                );
          }

            pointer += Utilities.WriteAndPosition(pointer, ref data);

            this.context.UnmapSubresource(scatterPointVertexBuffer, 0);
        }

```

I don't normally write C# so sorry if this code is not right but something like that should work to update it now u just have to make sure you don't go out of bounds in the buffer, maybe set First to true and start at the beginning of the buffer again once u reach the end.... would end up like a ring buffer I think.
> 0 votes

---
Tags: directx11, windows, sharpdx, vertex-buffer
---


# Question
Title: Why can't I rotate anything to be "more than 360 degrees or less than 0 degrees"?
I've been trying to make an animation in Unity, but most assets already come bundled with everything facing at 0 degrees, not to say it's a bad thing.

However, the problem I'm facing is that the animation keyframes aren't playing out correctly.
When this is done with raw measurements (simply dragging the XYZ rotations), negative and greater than 360 degree angles are taken account. But then again - Unity could be simply remapping them, whcih is not the case.

For example, the `prop_robotArm` prefab, found within Unity's Robot Factory asset pack has a rotator script that simply rotates the whole thing along the Y axis.

```
void OnFixedUpdate()
{
    transform.Rotate (new Vector3(0, rotateSpeed*Time.deltaTime,0));
}

```

Meaning that after slightly more than a full revolution, the Y rotation value should be more than 360 degrees, which it does end up becoming... Eventually.

---

Thinking that was possible, I tried to mimic this behavior by making the arm rotate 720 degrees (twice) in an animation file (this is not using the `rotator.cs` script attached to the body in the example above).
Instead, all I ended up was the arm's body staying still as 720 is the same as... 0 degrees in rotation changes.

So, I tried a second experiment; trying to rotate from 359 degrees to 1 degree (or -1 to 1 degree).
Just like above, it didn't go to plan. When the animation is run, it simply runs from 359, through every angle in-between before reaching 1, instead of 359, 360 (0) and 361 (1).
*If you don't get what I mean, see the diagram below.*

## So, I was wondering, is there a way to allow for such rotation to be defined in an animation curve?

Every time I try doing it, any value greater than 360 (or lesser than 0) is replaced by its co-terminal counterpart that's between 0 and 359.999999...999.

# Answer
Unity supports two methods of animation interpolation:

* Quaternion interpolation (the default)
* Euler angle interpolation (what you're expecting)

Quaternion interpolation is smoother, but doesn't react gracefully to a single keyframe which rotates more than 180 degrees -- as you're seeing, it picks the shorter path, no matter what your intention was.

To quote from the Unity manual:

> Quaternion interpolation cannot represent rotations larger than 180 degrees, because it is then shorter to go the other way around.
>
> ...
>
> If rotations larger than 180 degrees are desired, additional keys must be placed in between.

You can either add more keyframes, or set each AnimationCurve to use Euler angle interpolation. Either option sounds a bit tedious, so it's up to you which is easier for your workflow.
> 8 votes

# Answer
In addition to what @rutter has mentioned, you can change animation view to "Curve" and adjust curves accordingly to achieve the smooth rotation
> 0 votes

# Answer
Probably I am little late, but I have the solution for this:

Add an offset of 360 to each Euler angle, now you do not want to apply it every time, so check if the rotation of the desired angle is lesser than 180 that is when you do not add an offset of 360, if it is not, add an offset of 360. @aytimothy
> 0 votes

---
Tags: unity, animation
---


# Question
Title: Unity3D 5.5b : C# WebGL open email client Win32 exception error
I want to send an email in a WebGL build using C#. My code is as below

```
try
{
   Uri myUri = new Uri("mailto:anemailaddress@example.com? Subject=Hello%20again&body=TEST");
   System.Diagnostics.Process.Start(myUri.AbsoluteUri);
}
catch (Win32Exception e)
{
  Debug.LogError(e.Message);
}
catch (Exception e)
{
   Debug.LogError(e.Message);
}

```

to open an email client. But I get the following error as well as a Win32Exception : Success error

(Filename: /Users/builduser/buildslave/unity/build/artifacts/generated/WebGL/runtime/DebugBindings.gen.cpp Line: 51)

a9b4b6fe-b629-4efc-bb29-821d1f0fcea2:9085:3 Not implemented icall: Process::ShellExecuteEx\_internalUnityLoader.js:3541:3 Success

(Filename: /Users/builduser/buildslave/unity/build/artifacts/generated/WebGL/runtime/DebugBindings.gen.cpp Line: 51)

# Answer
> 1 votes
The solution is to use Application.OpenURL instead of Process.Start

Example:

```
Application.OpenURL("mailto:someone@gmail.com?Subject=Hello%20again&body=TEST");

```

---
Tags: unity, c#, webgl, .net
---


# Question
Title: Detecting collisions between orbiting objects in 2D
I am currently in the process of creating a 2D space debris simulation. I have the orbital physics implemented, but I am currently struggling to find a suitable way of detecting collisions.

There are many objects, all of which are incredibly small and therefore very spread out, but they are travelling at very high speeds. It seems like using a grid would be a good way of detecting collisions between objects, although the objects are all constantly moving at high speeds so they will be moving between cells very often. I also have the issue of only having a limited rate at which I can update the object's positions because otherwise it runs slow, so I believe I need to implement some form of 'swept' collision detection.

Does anyone have any suggestions for a way in which I could efficiently check for collisions, but also make it so they don't miss?

# Answer
> 1 votes
I'll go with bpgeck's answer which is the standard collision detection method when you have a lot of colliders: separate'em in buckets.

However, the standard `xy` grid is ill suited for this problem as the entities will change of cell extremely often.

Instead I'd go with a coordinate system more natural to your game. The details depend on your implementation:

* Do you have a **gamey** simulation where the laws of physics are not followed and orbits of any radius can have any speed?
Then partition by `R, theta`
* You probably don't have a **constrained but realistic** simulation where orbits are all circular and only radius vary (so speed is fixed as a function of radius) because collisions would be impossible, except reverse orbits (!) and manoeuvres (unlikely, depends on scale)
* If you have a **full two-body simulation** (more likely for collisions) **and use xy coordinates with an integrator**, then at least use some cheap orbital elements like apoapsis, periapsis to segregate your objects into altitude buckets. If ship1 apoapsis \< ship2 periapsis, then no collision can occur. As long as you don't have hugely eccentric objects, you'll get good separation. As a bonus these are cheap *and constant*! You need only recalc and reorder the buckets when a ship is thrusting.
* If you implemented a **full two-body simulation using orbital elements**, then in addition to the apsises, the anomalies can be used to further cluster objects within a bucket before fine computations.
* If you have a multi-body simulation, back to point 2.

---

Feel free to mix-and-match: use x-separation, y-separation, radial separation and anomaly separation **in series or in parallel** (or not at all).

Simple example of what I mean by series or parallel, using a usual xy grid split like tic-tac-toe in 9 squares:

* **Series** partitioning is the typical way: by `x`, then by `y`, and getting 9 disjoint buckets as usual.
Both coordinates are required to define these buckets
* **Parallel** partitioning means you can split in rows and columns *separately* and get 3 `x`-buckets and 3 `y`-buckets.
The `x` coordinate alone defines the column buckets, the `y` coordinate alone defines the row buckets.
The advantage is if your ship moves fast in `x` direction but not much in `y`, you don't have to reorganise the `y` buckets often: this suits orbits nicely I think, because apoapsis and periapsis seldom change, but the anomalies, x and y often do.
To determine collidability, first compare radial ranges. If disjoint, no collision. If intersection, continue with next coordinate etc.
This is great with 1-to-many collisions as you can simply take the intersection of each bucket and check the remaining objects.
The disadvantage is when looking for many-to-many collisions, where the buckets are larger than in series.

---

Finally try grouping fleets under a single collider, etc.

# Answer
> 2 votes
In my experience, the best way to perform 2D collision detection is with a grid, preferably a uniform grid, as this is very easy to implement and works very well. Since your game is a space game, though, I am guessing that your game world is very large. In that case, I would partition the entire game world into a series of "tiles" and each tile contains a uniform grid this will make it faster to check collisions. Side note: you have the option to make it so only the asteroids in the tile that the player is currently looking at will move. This wil make movement of asteroids quicker.

Each cell of the grid represents an amount of area within the tile (i.e. the cell located at UnifGrid may represent x = 20 to x = 29 and y = 50 to y = 59) and each cell is some data structure representing all objects in that area.

Now you need to check collisions. On each iteration, for every asteroid that moved, check if it hit any of the other asteroids **within its same cell**. Please see my sketch below for a visual representation of what I mean.

Imagine this is one tile of your game world:

First make the grid,

Now let's say these asteroids move

Now, just check for collisions between the asteroids that moved and all other asteroids in that cell (AABB collision detection. Read about it elsewhere)

Our collision algorithm will show that only this pair of asteroids collided

---
Tags: java, collision-detection, orbit
---


# Question
Title: How do multiple expansions to a game typically should be implemented?
Let's say I have a game that's finished and shipped, what would be the approach that is typically taken in regards to future content such as expansions? I'm not talking about programmatic implementation. I'm talking about how to integrate it to the base game, especially for multiple expansions.

If I finished making **Expansion Pack 1** which adds new locations, new quests that tie in to the base vanilla game, etc, and then later down the line, I finish **Expansion Pack 2** as well, how do I handle if the player only bought **Expansion Pack 2** without making it feel disjointed in relation to the lack of **Expansion Pack 1**?

Or should I make all older expansions mandatory before being able to use the latest one?

In short, I'm trying to wrap my head around implementing multiple expansions without any of the expansions being mandatory but at the same time, I don't want them to feel "tacked on" to the base game as a side content (meaning, they should be integrated into the game's world). I want them to feel like an actual part of the world. Just that they're optional.

# Answer
There is two models possible ; both exists and work in the World. You have :

* the layer model, applied to every MMO out there, where every expansion is added on top of the previous one and all are required to move on ;
* or you can do parallel extensions that doesnt interlap, like the Skyrim / Fallout 3-4-NV ones, where each is a pack of new quests in new locations, with featurzs and item usable on the core game.

They sound quite opposite, and it is somewhat true. It is almost by definition that something not mandatory is, well, side content.

It really depends, in the end, of your game, and what is packaged in those extensions.
> 1 votes

---
Tags: game-design, game-mechanics
---


title: Calculating time until a ball fall

text:
# Question
Title: Calculating time until a ball fall
How exactly can I calculate time until a ball fall if I know initial and final `x` and `y` position of a ball, gravity, delta time, initial `dx` and `dy` of a ball and its speed calculated from the formula `sqrt(dx ** 2 + dy ** 2)`?

# Answer
Supposing a macroscopic ball falling without atmosphere resistance and where Relativist effect is negligible.

* **P0\[x,y,z\]** is the initial position of the ball, with y \>= r
* **P\[x,y,z\]** is the final position of the ball.
* **V0\[x,y,z\]** is the initial speed of the ball
* **g\[0,y,0\]** is the gravity, with y \< 0
* **r** is the radius of the ball, r \>= 0
* **ground** is defined as a plane at Y=0

The position of the ball at any moment is given by (1):

```
P = P0 + V0*t + g*t*t;

```

To found the time where the ball hit the ground (2):

```
P0.y + V0.y*t + g.y*t*t = r

```

Solving the equation (3):

```
t = ( -V0.y - sqrt(V0.y*V0.y - 4*g.y*(P0.y-r)) ) / (2 * g.y)

```

Final position can be calculated using (1)

Note: Considering that P0.y \>=r and g.y is negative, the internal of the root is always positive.
> 2 votes

# Answer
an unusual answer cause its mostly a link, but this is the way to calculate object falling according to X gravity following newton's law.

https://en.wikipedia.org/wiki/Equations\_for\_a\_falling\_body
> 0 votes

---
Tags: 2d
---


# Question
Title: Simplest way of skeletal animation in openGL
I am not interested in using easy libraries like assimp which will import collada files with ease to get skeleton animation done.

I wanna know what is the minimal requirement to get the animation done.

What I understand is that a bone is a 3\*3 rotation matrix which is associated with each group of vertex.

We have to augment it with the model matrix to animate anything

How would I play a sequential animation with my existing bone system.

What's the workflow to process the bones. Sending bones through Uniform block is slow but I would consider doing it.

What's the simplest file format to store rig and animation data. Collada is unnecessarily advanced and complex.

Or how would I write my own file format for animation.

I am using blender to model and rig. How would I even manage to get an exporter for my format in blender

# Answer
Those are 3 questions:

1. How to implement a simple skeletal animation in OpenGL
2. What is the simplest file format to store skeletal structure and animation data
3. How to import from Blender to OpenGL

I will focus on the main question and just add notes for the 2 others:

## How to implement a simple skeletal animation in OpenGL

An simple skeletal require:

* A simple bone could be a transformation matrix. Which apply a rotation and translation.
* A bone apply to a set of vertexes
* A bone effect on a specific vertex is weighted between 0 and 1. To avoid strange effect on articulations.

A very simple way to solve that in OpenGL is:

* Every frame, update and save in an uniform vector each bones transformation matrix, ordered so a leaf is always after a root.
* Each vertex in the VBO contain, not only its position and normal, but also a list of weights of the size of the bone vector.
* In the vertex shader, for each bone, weight the bone matrix and apply it. So unrelated bones will multiply by the identity matrix, and relevant will have a real effect.
* Several optimizations are possible

## Short answer about file formats:

There are plenty of file-formats which accept bones, and to suggest one or another depends mostly of your specific requirements. I suggest you to look for:

* Support bones, at the complexity you want.
* Is not over-complex neither missing important features.
* The format is documented and, ideally, standardized.

Blender native format is, however, generally not a good idea: the format is not formally defined, so it is difficult to implement an exporter (except by just copying the loading code).

Creating your own format is possible and quite easy: You may create a script in blender to export and load it in your application.

EDITED 1:

Requirement of data for a "correct" skeletal file format:

* Bone hierarchy
* Affected vertex per bone, or
* Bones influence range, or weight per vertex.
* Articulation axes, and angular limitations to every one
* Animation of bones:
    + Allows several animations (e.g. one for walking, another for jumping...)
    + Definition of bone movement per animation.
    + Timing for the animation.
> 5 votes

---
Tags: opengl, animation
---


# Question
Title: Skip processing individual triangles or vertices of the mesh
In my game I have a billiard table, and a floor below the table. In typical situation the table covers 80% of the screen, so only small amount of the floor is visible. And I render the table first, so invisible part of the floor is discarded by the depth buffer test.

But profiling with Nsight shows me drawing the floor takes significant amount of time, and it is spent in the rasterizer. It seems generating all those pixels of the floor and depth testing them takes a long time.

I'm wondering how to solve this problem and one thing I tried is to divide the floor (a rectangle with two triangles) to multiple rectangles, so some of them could be cancelled in an earlier stage. The problem is, this is still one model / mesh, just with more triangles and I don't know how to start.

What would be a way to achieve this in Monogame + HLSL? Somewhere in vertex shader? Or gemoetry shader (is it supported in monogame?)

Or is there any other way to optimize this?

UPDATE: the whole floor is needed and might be drawn depending on where the camera is, so I can't get rid of parts of it. In typical situations table top covers 80% of the screen because of perspective and looking down at an angle. The game is in 3D.

# Answer
Break the floor geometry such that invisible pieces are not there at all
> 2 votes

# Answer
You have these options:

* Render the table first, and the floor second and have depth testing on. This will cancel calling the pixel shader on the floor pixels where the table has already been drawn. (though the rasterizer will still do its work) (edit: Oh I see you are already doing that)
* Frustum culling: don't render anything that is not in the view frustum. Usually visibility is determined by checking the object's bounding box against the view frustum.
* Occlusion culling: Don't call the draw if it is occluded. I don't know if occlusion queries are available i XNA though. It is also doable by a software occlusion culling technique, but I doubt it would be fast enough if it is done in C#. This is a broad topic, I won't get into details here.
* Culling primitives in the geometry shader. This is not available in XNA, but in monogame it is when using a DirectX 11 renderer. For each primitive you can test it against the view frustum, and decide if you want to send it to the pixel shader. I don't know if adding this extra shader stage will help you or not though, it's just an idea.
> 1 votes

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


# Question
Title: Unity "Update" method with lots of objects with logic
In my game I'm working on in Unity, I want to have energy and machines (i.e ore processing machines, smelting (think Minecraft modded)), but I was thinking about performance. The player could have quite a few of these machines in their base, all of them could be doing something and could be off screen, so this could effect performance as each machine will have logic to handle whatever it needs to do, and lots of them could be running at the same time.

Machine example; Let's say we have a machine that crushes stone. Player puts it into the machine slot, machine then starts crushing it if it has enough energy, and after X seconds, it outputs the crushed stone. Player could keep the machine UI open and watch the progress (i.e progress bar), or be far away from it.

Should these machines be running constantly in Update, if not, what would be a better way to do this?

# Answer
> 1 votes
Some things will only need to be updated every once in a while, for instance an ore processing machine might only need to update once every second or so, you can achieve this by giving the objects you need to update a nextUpdate attribute, a time when they next need to be updated in order to run properly. You'd just set this to maybe the current time + 1 second or whatever is suitable for that particular object. You'd then need to loop through the list and call update on only the objects where their nextUpdate is less than the current time.

You could even make this more complex (but also better performance) by having machines change their update frequency based on player distance, whether they have stuff to do etc etc.

An even better (however more complex) solution would be to load and unload certain objects based on if they need to be updated or not, for instance a processing machine without any items in it doesn't need to update. You'd need to remove it from the update list while it was idle and then re-add it once you detected interaction with the machine.

# Answer
> 1 votes
You could record the time that the items were put into the machine, then when the player interacts with the machine to remove processed items, use the time difference between current time when the items were entered to determine how many items should have been processed in that time. If the number of items exceeds the fuel cost of producing, return the max for the amount of fuel you have.

This would mean that there is no processing at all until the player interacts with the machine.

# Answer
> 0 votes
As an idea, you could make the machines do so: If the player is not in that machines UI so he can't see the loading bar or what ever, which means you can just set a timer depending on the amount of the material eg. 10 seconds, and then it will finnish/output result (so nothing happens every frame). However if the player is in the UI of the machine than a script that is ON THE PLAYER will show the progress of the particular machine, thus the constant updating will only occur at the machine that a player interacts with at the time (only one at a time possible). I haven't tried this so somethings may not quite work as I assume they will.

---
Tags: unity, performance
---


title: Perlin Noise' gradient

text:
# Question
Title: Perlin Noise' gradient
I'm having some problem understanding the Perlin Noise algorithm and none of the explanation I found go into this (probably obvious)detail.

From what function is the gradient on it? Is it from the blending function?

# Answer
The gradient is between the dot products of vectors to corners and randomly chosen vectors.

The pre-computed table you are looking at is likely part of the hash-function. (used to generate random numbers in a way that stays constant between calls)
> 2 votes

---
Tags: mathematics, perlin-noise
---


# Question
Title: Issue with tangents/bitangents generation for normal maps
I'm generating tangents and bitangents for a normal mapping effect and while using the same method as several tutorials, I get tangents that are not very continuous.

Here, we can see on the sphere especially that the tangents are very weird.

Also, my normal are totally correct and don't have this issue.

And when using these tangents with my normal mapping shader they "work", but create a very harsh "break" in the surface.

Here is the code used to generate the tangents and bitangents :

```
for (size_t i = 0; i < out_vertices.size(); i += 3)
{
  const auto& v0 = out_vertices[i];
  const auto& v1 = out_vertices[i + 1];
  const auto& v2 = out_vertices[i + 2];

  const auto& uv0 = out_uvs[i];
  const auto& uv1 = out_uvs[i + 1];
  const auto& uv2 = out_uvs[i + 2];

  const auto& dd_v0 = v1 - v0;
  const auto& dd_v1 = v2 - v0;

  const auto& dd_uv0 = uv1 - uv0;
  const auto& dd_uv1 = uv2 - uv0;

  float r = 1.0f / (dd_uv0.x * dd_uv1.y - dd_uv0.y * dd_uv1.x);
  glm::vec3 tangent = glm::normalize((dd_v0 * dd_uv1.y - dd_v1 * dd_uv0.y) * r);
  glm::vec3 bitangent = glm::normalize((dd_v1 * dd_uv0.x - dd_v0 * dd_uv1.x) * r);

  out_tangents.push_back(tangent);
  out_tangents.push_back(tangent);
  out_tangents.push_back(tangent);

  out_bitangents.push_back(bitangent);
  out_bitangents.push_back(bitangent);
  out_bitangents.push_back(bitangent);
}

```

I'm not sure if I need to average the (bi)tangents that share the same vertices/uvs, but I'm also not sure how to do it.

Thanks for any help.

# Answer
You need to average tangents and binormals from the neighbor triangles to get a the correct result. I suggest you take a look at Martin Mittrings (Crytek) code:

http://www.shaderx4.com/TangentSpaceCalculation.h

Now that aside, I might suggest to make life even easier by calculating the tangent space directly in the pixel shader. This is way more robust compared to precalculating it:

http://www.thetenthplanet.de/archives/1180

Henning
> 3 votes

---
Tags: opengl, normal-mapping, normal-generation
---


# Question
Title: Simple state pattern and circular dependancies
I'm creating a game engine which utilizes a state machine following this GameDevGeek tutorial. My concern is the use of circular dependency which I've heard is bad. The game engine has the game state but the game state needs access to the game engine for a state to be able to transition to a new state. Is this a proper way of doing it? Namely my implementation, includes, and forward declarations. On another note, why does syntax highlighting randomly turn off after two files have `#include`d each other? Here's my code:

```
// Game.h
#ifndef GAME_H
#define GAME_H

#include "GameState.h"
#include "SFML\Graphics.hpp"

class GameState;

class Game
{
public:
    Game();
    ~Game();

    void setState(GameState* state);
    void handleEvents();
    void update();
    void render();

private:
    sf::RenderWindow window_;
    GameState* state_;
};

#endif

```

---

```
// Game.cpp
#include "Game.h"

Game::Game()
    : window_(sf::VideoMode(500, 500), "Test Game", sf::Style::Default) ,
{
    window_.setKeyRepeatEnabled(false);
    state_ = nullptr;
}

Game::~Game()
{
    if (state_ != nullptr)
    {
        state_->destroy();
        delete state_;
    }
}

void Game::setState(GameState* state)
{
    if (state_ != nullptr)
    {
        state_->destroy();
        delete state_;
    }
    state_ = state;
    if (state_ != nullptr)
    {
        state_->init();
    }
}

// more code...

```

---

```
// GameState.h

#ifndef GAME_STATE_H
#define GAME_STATE_H

#include "Game.h"
#include "SFML\Graphics.hpp"

class Game;

class GameState
{
public:
    virtual void init() = 0;
    virtual void update(Game* game) = 0;
    virtual void render(sf::RenderWindow &window) = 0;
    virtual void destroy() = 0;

    void changeState(Game* game, GameState* state);
};

#endif GAME_STATE_H

```

---

```
// GameState.cpp
#include "GameState.h"

void GameState::changeState(Game* game, GameState* state)
{
    game->setState(state);
}

```

# Answer
Your issue can be solved by moving some includes about. The inclusion of file containing the declaration of another class is only needed when specific details are required (which functions are publicly available, how much space should I reserve for a field of that type, etc.).

Since your `GameState` header only ever uses pointers (references might be better suited here so others don't mistake it for an array and whatnot) to a `Game` object, you can get away with a forward declaration there. This is because the size of a pointer and reference is independent of the size of the data they point to; the compiler only needs to know about the existance of the class/struct at this moment.

Down in the `GameState.cpp` source file you are invoking functions of `Game`, so you need the signature there. Simply add `#include "Game.h"` heere and you should be good to go.
> 1 votes

# Answer
I agree, it does seem a little gross for each state to hold a reference to the `Game` just so the state can request a state change. But, in a way it makes sense: the `Game` class is acting as the state manager -- it keeps track of the current state and it knows how to change states.

I can think of a couple ways to break the explicit dependency between these two classes, but I think this one is the least complex and still achieves good decoupling:

### Make and use an interface that defines the role of a state changer

Basically, this won't change your current code that much, except instead of the `GameState` referring to an object of type `Game`, it would refer to an interface/abstract class type that declares a function for changing state. So something like this:

* Create an abstract class/interface that declares the `changeState(GameState * state)` function; let's call it `IStateChanger`
* Have the `Game` class extend/implement `IStateChanger` (`Game` already has `setState` -- so after extending `IStateChanger`, you would just have to rename `setState` to `changeState`)
* Change `GameState::changeState`'s first argument from `Game *` to `IStateChanger *`.

Any `GameState::changeState` calls that used to pass an instance of `Game` will still work, since `Game` would be a sub-class of `IStateChanger`; so why is this any better if we're still passing the `Game` instance around?

* With your current code, `GameState::changeState` has the ability to call other functions in `Game` that have nothing to do with changing state (e.g. `render`) and could potentially mess up the program flow. By using `IStateChanger`, the only function that is available to `GameState::changeState` is exactly the one you intended to be used by passing this object.

If you're the only one working on this project, then you know not to call any function other than `Game::setState`; but if someone else contributes to your project, they might not know, and they might accidentally use what's available in ways that you didn't originally intend. This is one of the main reasons "good design" is important: good design makes intention clear and makes it hard to screw things up.
* In the future, you may decide that `Game` should not handle state management. Maybe you decide that you want to make a class that specifically handles this, say, `StateManager`. Then all you would have to do is make `StateManager` extend/implement `IStateChanger` and then you can just swap out `Game` for `StateManager` wherever `Game` is being assigned to an `IStateChanger` declaration. This is another major benefit of "good design": easy to make changes and swap out one implementation with another.

Hope this helps.
> 1 votes

# Answer
Add static members and methods to the class GameState to handle the responsibilities that you've forced into the main Game class.

Each instance of GameState will then have access to one, shared state environment like they do now, and Game doesn't have to carry around the baggage.

Bonus is that if you later change the state implementation, an example would be to add hierarchical states, then all the changes are internal to the state classes and not spread all over outside files.
> 0 votes

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


title: Problem with shooting

text:
# Question
Title: Problem with shooting
So what I am trying to achieve is have the player shoot toward the mouse positiion and I have that working but I want the player to have to charge their shot. So if the player just presses the button it only goes a certain distance but if the player holds the button down for a bit it goes farther.

I tried to make a video that kinda explains what I am going for.

This is the code that controls the shooting

```
public class BowController : MonoBehaviour {

    public GameObject arrow;
    public Transform shootLoc;

    public float force;
    public Camera cam;

    public float chargeMin;
    public float chargeAmount;
    public float chargeMax;

    public bool charging;

    void Start () {

    }

    void Update () {

        Ray cameraRay = cam.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        Vector3 pointToLook;

        if (Physics.Raycast(cameraRay, out hit, 50))
        {
            pointToLook = hit.point;
            Debug.DrawLine(cameraRay.origin, pointToLook, Color.blue);

        }
        else
        {
            pointToLook = cameraRay.origin + (cameraRay.direction * 50);
        }
        transform.LookAt(pointToLook);

        if(Input.GetMouseButtonDown(0))
        {
            charging = true;

        }
        if (charging)
        {
            Charging();
        }

        if (Input.GetMouseButtonUp(0))
        {
            GameObject tempArrow;
            tempArrow = Instantiate(arrow, shootLoc.position, shootLoc.rotation) as GameObject;

            tempArrow.transform.LookAt(pointToLook);

            Rigidbody tempBody;
            tempBody = tempArrow.GetComponent<Rigidbody>();

            tempBody.AddForce(transform.forward * force, ForceMode.Impulse);

            force = 100;
            charging = false;
        }
    }

    void Charging()
    {
        force += Time.deltaTime * chargeAmount;

        if (force >= 500)
        {
            force = 500;
        }
    }
}

```

And this is the code that is on the arrow

```
  public Rigidbody rBody;
  public float speed;

    void Awake () {
        flying = true;
    }

    void Update () {
        if (flying)
        {

            //rBody.velocity = rBody.velocity.normalized * speed;
            transform.LookAt(transform.position - GetComponent<Rigidbody>().velocity);
            transform.Rotate(0, 180, 0);
        }
    }

    void FixedUpdate()
    {

        /*
        if (flying)
        {
            transform.rotation = Quaternion.LookRotation(rBody.velocity);
        }
        */
    }

    void OnCollisionEnter(Collision collision)
    {
        flying = false;
    }
}

```

I am still pretty new to coding so any help is appreciated. Thank you all very much in advance for the help!

# Answer
> 1 votes
I'm unfamiliar with Unity, so this answer may not be specific enough, but the general way I'd do this is:

* when the player initially clicks, save the timestamp (chargeStart)
* When they release, take the current timestamp (chargeStop)
* Subtract the difference to determine the length of the charge (chargeLength = chargeStop - chargeStart)
* Based on a formula that has the desired effect (play around with this based on your desired end result), use chargeLength to increase the amount of force used on the projectile

# Answer
> -1 votes
I would say that darkside's answer is probably what I would do. Just to add a little, in Unity you would probably use Time.time at the point where you start and finish charging. Additionally, Its probably a good idea to use Mathf.clamp(or just an if statement) to stop the charge reaching absurdly high levels. Anyway, just my two cents.

Good luck with the programming :)

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


# Question
Title: libgdx scene2d DelayAction and SequenceAction
I'm trying to get the delay action in scene2d working correctly. I have multiple image objects which I store in an array and I have managed to get them all displaying, scaling and moving correctly. I can't however seem to get them moving independently using the delay action.

I have tried using the sequence action and that isn’t working either…

I’m trying to create transition effects using little squares that move off the screen.

I have included a sample of the code im using below:

```
for (i = 0; i < scaleActions.length; i++) {
    ScaleByAction scaleAction = new ScaleByAction();
    scaleAction.setAmount(-0.1f);
    scaleAction.setDuration(0.5f);

    scaleActions[i] = scaleAction;
}

float increase = 0;
for (i = 0; i < delayActions.length; i++) {
    DelayAction delayAction = new DelayAction();
    delayAction.setDuration(0.05f+increase);
    increase += 0.1;
    delayActions[i] = delayAction;

}

for (i = 0; i < boxArray.length; i++) {
    SequenceAction sequence = new SequenceAction(scaleActions[i],moveActions[i],delayActions[i]);
    boxArray[i].setOrigin(boxW / 2, boxH / 2);
    boxArray[i].addAction(sequence);

    //boxArray[i].addAction(sequenceActions[i]);
    //boxArray[i].addAction(scaleActions[i]);
    //boxArray[i].addAction(moveActions[i]);
    //boxArray[i].addAction(delayActions[i]);
}

public void addToStage() {

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

        stage.addActor(boxArray[i]);
    }
}

```

Everything seems to be moving and scaling at the same time, the delay doesn’t look like it is even working.

Hope you guys can help point out what I'm doing wrong.

# Answer
> 0 votes
When creating a SequenceAction, the order of parameters matters. Your code is telling it to scale, then move, then delay. Since delay is the last action, it doesn't really do anything.

---
Tags: libgdx, scene2d
---


# Question
Title: Best way to create a Chromadepth shader for unity?
I'm trying to create a chromadepth environment in unity3D. So the camera sees close objects colored as red, and then farthest objects as blue. And everything in between falls down the color spectrum (Red orange yellow green blue)

I've looked into a few things such as z depth or even using fog for this kind of thing. But I'm not sure what the best way to approach this is; or maybe it's already been done before but I couldn't find it in the asset store. I Thanks in advance for your thoughts and time, it is much appreciated.

# Answer
Here's a simple version which should work both as a fullscreen post effect or as an object in the world, like a magic lens you can look through.

```
Pass
{
    CGPROGRAM
    #pragma vertex vert
    #pragma fragment frag
    #pragma target 3.0
    #include "UnityCG.cginc"

    struct appdata
    {
        float4 vertex : POSITION;
    };

    sampler2D _MainTex;
    // Request camera depth buffer as a texture.
    // Incurs extra cost in forward rendering, "just there" in deferred.
    sampler2D _CameraDepthTexture;

    void vert (
        float4 vertex : POSITION,
        out float4 outpos : SV_POSITION)
    {
        outpos = UnityObjectToClipPos(vertex);
    }

    fixed4 frag (UNITY_VPOS_TYPE screenPos : VPOS) : SV_Target
    {
        // Convert pixel coordinates into screen UVs.
        float2 uv = screenPos.xy * (_ScreenParams.zw - 1.0f);
        // Depending on setup/platform, you may need to invert uv.y

        // Sample depth buffer, linearized into the 0...1 range.
        float depth = Linear01Depth(
              UNITY_SAMPLE_DEPTH(tex2D(_CameraDepthTexture, uv)));

        // Compressing the range, so we get more colour
        // variation close to the camera.
        depth = saturate(2.0f * depth);
        depth = 1.0f - depth;
        depth *= depth;
        depth = 1.0f - depth;

        // Use depth value as a lookup into a colour
        // ramp texture of your choosing.
        fixed4 colour = tex2D(_MainTex, depth);

        return colour;
    }
    ENDCG
}

```

Here I'm using the VPOS semantic to simplify calculating the position of the fragment on the screen. If you need to support shader models below 3 there are other ways to do this, they're just a little messier. ;)

Here's me playing around with this a bit more...
> 3 votes

# Answer
I use this in my tile based renderer to show how many lights hit a tile, I also use it for my volume ray casting to get like a heat map effect.

I work with sharpDX but its all done in HLSL so if u tweak it a bit it will work just how u want.

It takes an uint as the distance to camera and another uint as the max range and you can change the colors that match the different ranges.

```
static const float4 kRadarColors[14] =
{
{ 0, 0.9255, 0.9255, 1 }, // cyan
{ 0, 0.62745, 0.9647, 1 }, // light blue
{ 0, 0, 0.9647, 1 }, // blue
{ 0, 1, 0, 1 }, // bright green
{ 0, 0.7843, 0, 1 }, // green
{ 0, 0.5647, 0, 1 }, // dark green
{ 1, 1, 0, 1 }, // yellow
{ 0.90588, 0.75294, 0, 1 }, // yellow-orange
{ 1, 0.5647, 0, 1 }, // orange
{ 1, 0, 0, 1 }, // bright red
{ 0.8392, 0, 0, 1 }, // red
{ 0.75294, 0, 0, 1 }, // dark red
{ 1, 0, 1, 1 }, // magenta
{ 0.6, 0.3333, 0.7882, 1 }, // purple
};

float4 ConvertDistToColor(uint current, uint max)
{
// black for 0
if (current == 0)
    return float4(0, 0, 0, 1);
// light purple for reaching the max
else if (current == max)
    return float4(0.847, 0.745, 0.921, 1);
// white for going over the max
else if (current > max)
    return float4(1, 1, 1, 1);
// else use weather radar colors
else
{
    // use a log scale to provide more detail when the number of range is smaller

    // want to find the base b such that the logb of max is 14
    // (because we have 14 radar colors)
    float fLogBase = exp2(0.07142857f * log2((float) max));

    // change of base
    // logb(x) = log2(x) / log2(b)
    uint nColorIndex = floor(log2((float) current) / log2(fLogBase));

    return kRadarColors[nColorIndex];
}
}

```

then use it like this:

```
return  ConvertDistToColor(asuint(distance(WorldPos, WorldCam) / 255), asuint(farclip / 255));

```
> 0 votes

---
Tags: unity
---


# Question
Title: Scripts enable and disable on Random time unity?
In unity game I've put two scripts in single object i want to these scripts are enable and disable on random time so how can do?

# Answer
First, create empty object .
Then, attach this script to the object (and don't forget to modify it).

The following code is **untested**:

```
/*
the how-to-use is in multiple comment
To stop the script from running , set active false from outside the object using script
UNTESTED
*/

using UnityEngine;
using System.Collections;

public class /* script name */ : MonoBehaviour {
  public float RandomizedTime;
  public int ActiveOrDeactive;

  void StartTheRandom(int TheObjectId,GameObject TheObject,string HelloAf) {
    GameObject AttachObject = TheObject;
    /* Set The Random Time in second , 0 Is minimal random time , 10 is the max */
    RandomizedTime = Random.Range(0f,10f);
    /* 1 Is Active , 2 Is De-active */
    ActiveOrDeactive = Random.Range(1,2);
    StartCoroutine(startWaiting(RandomizedTime,TheObject,ActiveOrDeactive,HelloAf,TheObjectId));
  }

  IEnumerator startWaiting(float theTime,GameObject GameGameObject,int ActiveOrNot,string HelloAfff,int ObjectId) {
    yield return new WaitForSeconds(theTime);
    if( ActiveOrNot == 1 ) {
      GameGameObject.GetComponent<HelloAfff>().enabled = true;
    }
    if ( ActiveOrNot == 2 ) {
      GameGameObject.GetComponent<HelloAfff>().enabled = false;
    }
    StartTheRandom(ObjectId,GameGameObject,HelloAfff);
  }

  // Use this for initialization
  void Start () {
    /* change firstobjectname and secondobjectname to the object that have the script */
    GameObject gameobjectone = GameObject.Find("firstobjectname");
    GameObject gameobjecttwo = GameObject.Find("secondobjectname");
    /* change onehere and twohere with the name of the script in the object */
    public string FirstScriptName = "onehere";
    public string SecondScriptName = "twohere";
    StartTheRandom(1,gameobjectone,FirstScriptName);
    StartTheRandom(2,gameobjecttwo,SecondScriptName);
  }
}

```

I hope this works :)
> 1 votes

# Answer
Just call static function on any script you want to have this behavior.

Here is the tested code:

```
using UnityEngine;
using System.Collections;

public class SwitchScriptsAtRandom : MonoBehaviour {

public MonoBehaviour script;
public float minTime = 1f;
public float maxTime = 4f;

// Use this for initialization
void Start () {
    StartCoroutine(ConstantlySwitchScrtiptsState(minTime, maxTime, script));
}

/// <summary>
/// Enables or Disables scripts depending on it's current state. Refreshes by random time.
/// Don't turn off this the script itself if you don't want the switching to interrupt.
/// You won't be able to enable it with itself.
/// </summary>
/// <param name="minWaitTime">Mininal random amount of time to wait until script changes it's state</param>
/// <param name="maxWaitTime">Maximal random amount of time to wait until script changes it's state</param>
/// <param name="scriptToSwitch">Reference to instance of the script</param>
/// <returns>WaitForSeconds</returns>
public static IEnumerator ConstantlySwitchScrtiptsState(float minWaitTime, float maxWaitTime, MonoBehaviour scriptToSwitch)
{
    while (true)
    {
        /*
         * If you want to check if gameobject is enabled you can use - scriptToSwitch.gameObject.activeSelf;
         * Also you could check by scriptToSwitch.isActiveAndEnabled;
         * https://docs.unity3d.com/ScriptReference/Behaviour-isActiveAndEnabled.html
         */
        scriptToSwitch.enabled = !scriptToSwitch.enabled;

        // Make sure that values are correct. You can check with "if" and "throw" an exception if you have to be sure that values the developer enter are definitely correct.
        minWaitTime = Mathf.Clamp(minWaitTime, 0, maxWaitTime);
        maxWaitTime = Mathf.Clamp(maxWaitTime, 0, maxWaitTime);

        yield return new WaitForSeconds(Random.Range(minWaitTime, maxWaitTime));
    }
}

}

```
> 1 votes

# Answer
Your gameobject Go continast ScriptA and ScriptB. So make another script OnOffController and attached to your gameobject GO

```
ScriptA objScriptA
ScriptB objScriptB
public float minRandomTimeInSeconds = 10;
public float maxRandomTimeInSeconds = 10;
void Start(){
  objScriptA = gameObject<objScriptA>();
  objScriptB = gameObject<objScriptB>();
  StartCoroutine(OnOffRandomly(true));
  StartCoroutine(OnOffRandomly(false));
}

void OnOffRandomly(bool state){
    while(true){
    yield return new WaitForSeconds(Random.Range[minRandomTimeInSeconds,maxRandomTimeInSeconds]);
    objScriptA.enabled = state;
    objScriptA.enabled = state;
    }
}

```
> 0 votes

---
Tags: unity
---


title: How to calculate fps in GLFW?

text:
# Question
Title: How to calculate fps in GLFW?
Just letting you guys know before anything I'm a beginner at programming. I am just wondering how I should go about calculating the fps using GLFW?

# Answer
You can get the amount of milliseconds passed between 2 render calls by storing the time the last render happened and subtracting it from the current time. Then you can get the exact fps count by dividing 1000 with the time passed.
> 3 votes

# Answer
This is very straight-forward. The following code is a slightly modified version from the code I found from this link, which I came upon with a Google search of "GLFW get fps".

Anyways, here's the basic algorithm: you increment a frame counter each time you call the `update()` method in your game loop, and you display and clear that value once a second.

```
double previousTime = glfwGetTime();
int frameCount = 0;

while (isGameRunning)
{
    // Measure speed
    double currentTime = glfwGetTime();
    frameCount++;
    // If a second has passed.
    if ( currentTime - previousTime >= 1.0 )
    {
        // Display the frame count here any way you want.
        displayFPS(frameCount);

        frameCount = 0;
        previousTime = currentTime;
    }

    // Rest of your game loop...
 }

```

Please note that FPS is not a very great measurement of performance, but the code above should let you measure the FPS.
> 4 votes

---
Tags: frame-rate, glfw
---


# Question
Title: Having problems sending multiple lights to my shader
I have a lightstruct in C++ which holds the color and direction of the light.

```
    const int NUM_LIGHTS = 1;

struct lightStruct {
    XMFLOAT4 Color;
    XMFLOAT4 Direction;
};

```

And this is how I create my buffer and update it.

```
    void PBRMaterial::CreateLightBuffer(ID3D11Device* device, ID3D11Buffer** lightBuffer, std::vector<lightStruct*> lightStructs){

    D3D11_BUFFER_DESC cbDesc;
    cbDesc.ByteWidth = sizeof(lightStruct) * NUM_LIGHTS;
    cbDesc.Usage = D3D11_USAGE_DYNAMIC;
    cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    cbDesc.MiscFlags = 0;
    cbDesc.StructureByteStride = 0;

    D3D11_SUBRESOURCE_DATA InitData;
    InitData.pSysMem = &lightStructs[0];
    InitData.SysMemPitch = 0;
    InitData.SysMemSlicePitch = 0;

    if (FAILED(device->CreateBuffer(&cbDesc, &InitData, lightBuffer)))
    {
        throw GameException("ID3D11Device::CreateLightBuffer() failed.");
    }
}

void PBRMaterial::SetLightBuffer(ID3D11DeviceContext* deviceContext, ID3D11Buffer** lightBuffer){

    deviceContext->VSSetConstantBuffers(0, 1, lightBuffer);
}

```

On the shader side I declare my variables as such:

```
    #define NUM_LIGHTS 1

    struct DIRECTIONAL_LIGHT_DATA {
        float4 Color;
        float4 Direction;
    };

    cbuffer cbDirectionalLight : register(b0)
    {
        DIRECTIONAL_LIGHT_DATA directionalLights[NUM_LIGHTS];
    };

```

Now, I don't get any errors but my shader only outputs black. I have been stuck on this for two days now and I can't come up with a solution. For debug purposes I also tried outputting the light's color directly like this:

```
    OUT.rgb = directionalLights[0].Color.rgb;// ambient + diffuse + specular;
OUT.a = 1;

```

But that also just shows up black. Anyone have a thought on what the issue might be? Thanks!

EDIT: Complete shader code:

```
    #include "include\\Common.fxh"

    #define NUM_LIGHTS 1

    struct DIRECTIONAL_LIGHT_DATA {
float4 Color;
float4 Direction;
    };

    cbuffer cbDirectionalLight : register(b0)
    {
        DIRECTIONAL_LIGHT_DATA directionalLights[NUM_LIGHTS];
    };

    float4x4 WorldViewProjection : WORLDVIEWPROJECTION;
    float4x4 World : WORLD;

    float3 CameraPosition : CAMERAPOSITION;
    float4 AmbientColor : AMBIENTCOLOR = { 1.0f, 1.0f, 1.0f, 1.0f };

    Texture2D ColorTexture;
    Texture2D NormalMap;
    Texture2D SpecularMap;
    Texture2D GlossMap;

    RasterizerState DisableCulling { CullMode = NONE; };
    SamplerState ColorSampler { Filter = MIN_MAG_MIP_LINEAR; AddressU =                 WRAP; AddressV = WRAP;
    };

    struct VS_INPUT
    {
        float4 ObjectPosition: POSITION;
        float2 TextureCoordinate : TEXCOORD;
        float3 Normal : NORMAL;
        float3 Tangent: TANGENT;
    };

    struct VS_OUTPUT
    {
        float4 Pos: SV_Position;
        float3 Normal : NORMAL;
        float3 Tangent : TANGENT;
        float3 Binormal : BINORMAL;
        float2 TextureCoordinate : TEXCOORD;
        float3 LightDirection : TEXCOORD1;
        float3 ViewDirection : TEXCOORD2;
    };

    VS_OUTPUT vertex_shader(VS_INPUT IN)
    {
        VS_OUTPUT OUT = (VS_OUTPUT)0;

        OUT.Pos = mul(IN.ObjectPosition, WorldViewProjection);
        OUT.Normal = normalize(mul(float4(IN.Normal, 0), World).xyz);
        OUT.Tangent = normalize(mul(float4(IN.Tangent, 0), World).xyz);
        OUT.Binormal = cross(OUT.Normal, OUT.Tangent);
        OUT.TextureCoordinate = get_corrected_texture_coordinate(IN.TextureCoordinate);
        OUT.LightDirection = normalize(-directionalLights[0].Direction.xyz);

        float3 worldPosition = mul(IN.ObjectPosition, World).xyz;
        OUT.ViewDirection = normalize(CameraPosition - worldPosition);

        return OUT;
    }

    float4 pixel_shader(VS_OUTPUT IN) : SV_Target
    {
        float4 OUT = (float4)0;

        float3 sampledNormal = (2 * NormalMap.Sample(ColorSampler, IN.TextureCoordinate).xyz) - 1;
        float3x3 tbn = float3x3(IN.Tangent, IN.Binormal, IN.Normal);
        sampledNormal = mul(sampledNormal, tbn);
        float3 lightDirection = normalize(IN.LightDirection);
        float3 viewDirection = normalize(IN.ViewDirection);
        float n_dot_l = dot(lightDirection, sampledNormal);

        float4 color = ColorTexture.Sample(ColorSampler, IN.TextureCoordinate);

        float3 ambient = AmbientColor.rgb * AmbientColor.a * color.rgb;

        float3 diffuse = (float3)0;
        float3 specular = (float3)0;

        if (n_dot_l > 0)
        {
            diffuse = directionalLights[0].Color.rgb * directionalLights[0].Color.a *saturate(n_dot_l) * color.rgb;

            float4 sampledSpecular = SpecularMap.Sample(ColorSampler, IN.TextureCoordinate);
            half smoothness = GlossMap.Sample(ColorSampler, IN.TextureCoordinate);
            float SpecularPower = pow(2, 1 + smoothness * 10);

            float3 reflectionVector = normalize(2 * n_dot_l * sampledNormal - lightDirection);

            specular = sampledSpecular * min(pow(saturate(dot(reflectionVector, viewDirection)), SpecularPower), color.w);
        }

        OUT.rgb = ambient + diffuse + specular;
        OUT.a = color.a;
        return OUT;
    }

    technique11 main11
    {
        pass p0
        {
            SetVertexShader(CompileShader(vs_5_0, vertex_shader()));
            SetGeometryShader(NULL);
            SetPixelShader(CompileShader(ps_5_0, pixel_shader()));

            SetRasterizerState(DisableCulling);
        }
    }

```

# Answer
> 1 votes
Just change

`std::vector< lightStruct* >`

to

`std::vector< lightStruct >`

# Answer
> 0 votes
I dont know which editor you are using, but Visual Studio contains a HLSL shader debugger. So you can select a pixel/fragment and see which DXCalls influenced the pixels color.

Start your program from Debug -\> Graphics -\> Start Diagnostics (or hit Alt + F5), then press „Print“ to capture the last rendered frame.

Hope that helps! If not, can you show the pixel shader you are using?

---
Tags: c++, shaders, directx, graphics, hlsl
---


# Question
Title: Sending a players mouse movement to the server in an FPS
So I have a server-client model FPS set up. It uses udp to send data between the two with the server having a constant tick rate of 100 ticks per second (It updates movement 100 times a second) on the server with the client doing update of its key states etc 30 times a second and for keys the system works well. But now my question is how would I send the mouse movement to the server as this in not an on/off system is is constantly changing.

So my question is how do you send the movement of the mouse to the server. Do you send the direction and speed that the mouse is moving each update and interpolate it or something else. The problem I can see with interpolating something like a mouse is that in an FPS it is required to be very accurate and interpolating is literally guessing. Any advice would be appreciated.

The other problem that I see is that to get a direction vector of a mouse you would have to wait for enough movement to get the vector.

Another idea has come to me and that is just sending the direction that the client thinks its looking when it shoots.

Any advice would be much appreciated.

# Answer
> 3 votes
Translate mouse input to rotation on the client-side. Then send the new view direction to the server, not raw mouse input.

1. Usually there is more than one way to change the players view direction (keybindings, for example). When you just handle direction updates you don't have to handle this as a separate case on the server (not a particularly important reason, but a reason nevertheless).
2. Mouse position updates are changes, not absolute values. That means a single lost packet causes the view-direction on client and server to become asynchronous. You said you are using UDP, so you always need to keep the possibility of lost or out-of-order packets in mind.
3. ...unless you enforce server authority on view direction. Then your players will get annoying input lag (when you have no prediction) or unexplained mouse jumps (when you have prediction).
4. In most first-person games the player is allowed to turn as fast as their mouse allows. So there is no reason to handle this server-sided anyway.

When you are worried about too many direction updates using too much bandwidth, reduce the update rate in situations where it does not matter and increase it in situations where it does. When the player is just standing around, you only need very infrequent mouse updates because their view direction is mostly cosmetic for the other players. When the player is shooting, you want a mouse update on every tick so you can accurately represent their aiming.

# Answer
> 0 votes
First, mouse look doesn't require to be sent as the player direction is not affected. You need to send out your position (speed, momentum, whatever) and your actions (fire, duck whatever)

Quake does like this. Prediction could be useful but at an expense of some paradox to be resolved at client/server site

**EDIT**

Have a look at QuakeWorld and Quake3Arena source code

# Answer
> -1 votes
Would you happen to be using a socket server? Or what kind of networking system Do you use? Having a stream of floats going over the network should not cause an issue, if you use a setting on that rpc like transmission set to "reliable" (if you have this kind of system) that can cause the packet buffer to overflow on the server and cause overhead. if this can handle some list packets you should be just fine using a system like this.

---
Tags: client-server, mouse, first-person-shooter
---


# Question
Title: Deployed Android APK file size was more tha expected when developed in Unity
I developed a game, and build it as an Android APK file. I was not using any assets, only a UI panel and a UI Button. I thought the APK file woul be 3 MB, but it was 18MB.

On the Google Play store, there are many good games using good graphics that have a small size. Some are only 5MB or 6MB. I want to know why I am getting such a large APK file.

How do I reduce the size of my APK file?

# Answer
> 1 votes
When you build APK in Unity then the entire engine code is included as a library, the last time I've checked it was about 9-10MB, but I'm sure it changes between engine and/or Android versions. For this reason you can't get below this size and all your assets are just added on top of it.

Change the extension of your APK to zip and open the file as regular archive to see more details.

# Answer
> 0 votes
> **ProGuard**
>
> A tool for code shrinking, like ProGuard, will significantly reduce the static foot print. Note that it is very important to re-test all of the application after applying ProGuard since it may change the application behavior.
>
> As ProGuard replaces the application symbols, to make the code difficult to read, it is important that you retain the symbol mapping, so that you can translate a stack trace back to the original symbols if you have to investigate a crash in your application.
>
> \- Answer submitted by GrisHu to "Does including JAR in android projects affect the size of the APK" at Stack Overflow.

# Answer
> 0 votes
> Often textures take up most space in the build. The first to do is to use compressed texture formats (DXT(Desktop platforms) or PVRTC) where you can.
>
> Meshes and imported Animation Clips can be compressed so they take up less space in your game file. Compression can be turned on in the Mesh Import Settings.
>
> When building a player, you should avoid any dependencies on System.dll or System.Xml.dll. Unity does not include these in the built player by default but if you use their classes then they will get included. These DLLs will add about a megabyte to the player’s storage size.
>
>  \- Unity Manual: Reducing the File Size of a Build

# Answer
> 0 votes
I had a similar problem. Try reducing and compressing the size of the textures. I reduced the size of my assets while ensuring that their quality remains the same .

# Answer
> 0 votes
Unity 5 Android builds seem to be larger than previous versions. That being said, if you look in the build's player settings and use *ARMv7* instead of *FAT (Armv 7 + x86)* the size will be reduced some, but this will also make the app incompatible with mobile devices that use a full x86 processor. Such devices are far less common though.

---
Tags: unity, android
---


# Question
Title: Why does physics not behave consistently in Unity?
I'm making a game in which AI players throw a ball.

In the screenshot, you can see the arena which is separated by a net in the middle. Each side of the arena has 6 players belonging to one of 2 teams. Right now, one of the players on the right side has the ball (the top-right player). He is going to throw the ball to the left side.

According to my code, the ball should always land on the same place, because the player always applies the same force to the ball. However, I have noticed that the ball doesn't always land in the same place. I have marked where I've seen the ball land with several red circles.

Interestingly, on my main PC, the ball almost always lands on the right-most circle. It rarely lands on the other circles, although that *does* happen. On 3 other PCs I've tested this game on, however, the ball most often lands on the legs of the top-left player, sometimes on his head or behind him, but never on the right-most circle (in front of him).

My game relies heavily on physics. The AI is supposed to calculate how to throw the ball to get it to land on a very specific location, as well as guess where it'll land depending on the ball's position and movements. If the physics don't behave consistently on all machines all the time, how is the AI supposed to calculate all of this accurately?

Here is the code in charge of throwing:

```
private IEnumerator Serve()
{
    var ball = GameObject.Find("Ball").GetComponent<BallController>();
    if (ball.ServingPlayer != this)
        yield break;

    yield return new WaitForSeconds(3);

    Vector3 shootDirection = transform.forward.normalized;
    var q = Quaternion.AngleAxis(-45, transform.right);

    ball.RigidBody.AddForce(q * shootDirection * 20f, ForceMode.VelocityChange);
}

```

As you can see, the ball is always thrown "forward" (facing the net) at a 45° upward angle, using a normalized vector and a constant speed (`20f`).

Before each throw, the position of the players is reset to the exact same location (and rotation) they are seen on the screenshot.

```
player.transform.localEulerAngles = new Vector3(0, playerRotation, 0);
player.transform.position = startingposition + posOffset;

```

In this case, `playerRotation` is either `90f` or `-90f` depending on which side the player is on, `startingposition` is their "horizontal" position (relative to the net), and `posOffset` is their "vertical" position.

The ball has its velocity and angular velocity reset, but not its rotation (since it's a sphere, its rotation shouldn't influence anything). Its position is also set to a fixed location relative to whichever player has to serve the ball.

```
rb.velocity = Vector3.zero;
rb.angularVelocity = Vector3.zero;
transform.position = ServingPlayer.ServingPosition;

```

Here, `rb` is the ball's `RigidBody`.

Finally, I am not influencing the ball's movement in any way. I simply apply a force to it when serving, which happens only once. 3 seconds after the ball lands, the match is reset and everything repeats.

The flow is basically like this (pseudocode):

```
Start()

ResetCourt()
StartCoroutine(Players[0].Serve())
event BallLanded()
wait for 3 seconds

// repeat starting with ResetCourt()

```

---

I ***really*** need the ball's trajectory to be reproducible every single time on every possible machine. Obviously I'm doing something wrong here, but what?

# Answer
I don't think you are doing anything wrong, the reason the result is different is because the Unity physics engine is calling FixedUpdate at a different rate depending on hardware and system load. Many physics calculations use the time step on each call too smooth out the result. See the answer here: http://answers.unity3d.com/questions/11839/making-fixedupdate-fixed-timestep-independent.html
> 7 votes

---
Tags: unity, physics
---