# Question
Title: Separating axis theorem with multiple polygons?
I am attempting to implement the separating axis theorem in C#. I have a function that can calculate the minimum translation vector between two polygons. However, I can't seem to create a function that calculates the minimum translation vector between one polygon and multiple other polygons. Honestly, I've been working on this for months and am no closer to a solution and have not been able to find a solution online. There's always a few edge cases that do not return the correct result, leading to high priority bugs in my game.

Here are common edge cases that do not work correctly:

Is there a well-known solution for this problem? All I can find is people saying "just perform the SAT on each polygon" but this rarely produces the *minimum* translation vector.

Any help would be highly appreciated.

# Answer
Ideally, you don't build your environment out of polygons. You build it out of *edges* (which perhaps you calculate from a set of polygons). In your first example, for instance, there is a single diagonal edge; in the last example, the box is resting on a single horizontal edge.

The fact that your editor or tools use smaller, individual shapes to build a level should not impact the runtime.

A slightly simpler approach would simply remove "inner" edges of the base shapes. For your last example, there are two edges between the "floor" boxes; ignore these during collision detection.

You can find some better pictures and some implementation ideas by reading section 4.5 (edges and edge chains) in the Box2D documentation.
> 2 votes

---
Tags: collision-detection, separating-axis-theorem
---


# Question
Title: Update Camera manually after Camera's target updates, bypassing the game loop. Is this a good or bad practice?
*This question may be suited better for codereview.stackexchange.com?*

I've been experimenting with a camera implementation / matrix `SpriteBatch` transformations and have run in to a bit of a snag.

The camera's `.Update()` method updates the transformation matrix and the camera's positioning.

My `Player` class depends upon the camera in order to work out where the mouse is in relation to the game world for a rotation calculation. This leads to the camera's information being one frame out of date when I need to be. This isn't noticeable when the player isn't moving as the camera's information is correct; even at low speeds I didn't personally notice the problem. However the speed was in excess of ~1000 pixels/sec (a few pixels per frame), it started to introduce a jittery-ness to the player's transformed position. Above and beyond these speeds resulted in very ugly drawing.

My thought process was "So I should update my camera immediately after the player's position has changed instead. Won't that introduce an unnecessary dependency? What happens if my camera isn't following the player or a player doesn't exist?"

My solution:

```
// in Camera2D.cs

public void ManualUpdate(GameTime gt)
{
    Update(gt);
    _hasAlreadyUpdated = true;
}

public void Update(GameTime gt)
{
    if (!_hasAlreadyUpdated)
    {
        DoUpdate(gt);
    }
    else
    {
        _hasAlreadyUpdated = false;
    }
}

private void DoUpdate(GameTime gt)
{
    ...
}

```

I can now manually call the camera's `.Update()` method early if I want to and it won't lead to multiple calls per frame. The jitter has been completely eliminated.

Would you consider this an adequate solution? Can you think of something more elegant?

# Answer
> 1 votes
It will depend a fair bit on the structure of your game.

One solution to this could be to convert all output-dependent inputs (ie: mouse inputs) into output-independent "commands" at the start of your update, before anything actually happens. This will completely solve any ordering problems. Kind of complicated, though.

A brute-force option might be to just keep two copies of the camera around. The current camera, and the one associated with the incoming input data (what the player saw when they clicked the mouse).

I think having the camera as an independent object that updates after everything else is probably the simplest solution - possibly the best. It is essentially the same as the "keep two copies" method - except you make everything update in the right order so you don't actually need two copies.

Having your camera update last does not seem to be an "unnecessary dependency". Although having the player responsible for updating the camera does seem to be a bad way to structure things. Make it an independent object and feed it a target position manually or give it a reference to its current target.

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


# Question
Title: character and camera not moving in the same speed
the two scripts below do the similar things,
get the key press and calculation the direction after the direction calculated, they multiple with the same speed, say 0.05f,
while the character and the camera, do not move at the same speed, and the character move faster than the camera.
if i rotate the camera a bit and move the character, the character move even faster than camera.
i believe there are something wrong in the variable direction, i would like to like how can i fix it so that both of them can move at the same speed in every direction.
Thank you.

character movement script:

```
    animation.CrossFade("moving");
        direction = Vector3.zero;
        myposition= transform.position;

    if(Input.GetKey("i")) {
        animation.CrossFade("moving");
        direction += Vector3.forward;
        currentkeydown=true;
    }
    if(Input.GetKey("k")){
        animation.CrossFade("moving");
        direction += Vector3.back;
        currentkeydown=true;
    }

if(Input.GetKey("j")){
       animation.CrossFade("moving");
       direction += Vector3.left;
       currentkeydown=true;
    }

if(Input.GetKey("l")){
    animation.CrossFade("moving");
    direction += Vector3.right;
    currentkeydown=true;
}

       //if two key press
if(Mathf.Abs(direction.x)+Mathf.Abs(direction.y)+Mathf.Abs(direction.z)>1){
          direction.x/=2;
          direction.y/=2;
          direction.z/=2;
         }

         //if direction change
         if (direction != Vector3.zero) {
             direction = Quaternion.Euler(0.0f, Camera.main.transform.localEulerAngles.y, 0.0f) * direction;
             transform.rotation = Quaternion.LookRotation(direction);
         }

         if(currentkeydown){
          transform.position+=direction*speed;
         }

```

and camera script

```
if(Input.GetKey("i")) {

         direction += Vector3.forward;
         currentkeydown=true;
       }

       if(Input.GetKey("k")){
         direction += Vector3.back;
         currentkeydown=true;
       }

       if(Input.GetKey("j")){
         direction += Vector3.left;
         currentkeydown=true;
       }

       if(Input.GetKey("l")){
         direction += Vector3.right;
         currentkeydown=true;
       }

       if(Input.GetKey("u")){
         transform.RotateAround(player.transform.position,Vector3.up,-2f);
       }
       if(Input.GetKey("o")){
         transform.RotateAround(player.transform.position,Vector3.up,2f);
       }

       direction = transform.TransformDirection(direction);
       direction.y = 0;
       if(currentkeydown){
         if(Mathf.Abs(direction.x)+Mathf.Abs(direction.y)+Mathf.Abs(direction.z)>1){
          direction.x/=2;
          direction.y/=2;
          direction.z/=2;
         }
       transform.position+=direction*speed;
       }

```

# Answer
> 1 votes
Normalize the direction component after you get your inputs and get rid of this nonsense:

```
direction.x/=2;
direction.y/=2;
direction.z/=2;

```

Then multiply the normalized direction value by `speed` to get the correct movement vector.

# Answer
> 0 votes
Maybe it is a point of view opinion but it seems you should use another approach :

1. If you have no plans on making your camera track another object then you should make it a child of your object (i do think it is not the good answer but i think it's still better than moving two objects separately when you want them to be synched)
2. If you need your camera to be versatile you should make it completely separated from input for it's position and input relative only for it's rotation.

Good tools for that is :

Making your cam position relative to a transform :

```
cam.position = object.position + localpos
//Calculate localpos using
cam.RotateAround(object.position,Vector3.Up,input.GetAxis("Horizontal"))
//or something similar

```

this should already make your code easyer to maintain and it could allow you to switch between targets painlessly

EDIT: And to stress it even more as Byte56 stated : Get rid of all the useless stuff

---
Tags: unity, movement
---


# Question
Title: Scaling textures with nearest neighbour without having to use seperate sprite batches
I'm interested in being to scale textures up via nearest neighbour. I can do this via a `SpriteBatch.Draw()` overload however this means that any other sprites drawn within that batch will also have the scaling.

What happens if I have 50 objects I want to to scale, and another 50 objects I don't want to be drawn using nearest neighbour. Assuming they alternate depths, that's 100 calls to to `spriteBatch.End()` in order to get depth drawn correctly. Now also let's say each object has it's own texture.

One way is to you use `Texture2D.SetData()` to manually scale up the textures but this could get messy, very quickly.

Any tips?

# Answer
> 3 votes
## FIRST OPTION (not advised) :

Looking at the documentation you can change the samplerState to choose texture interpolation.

Two references there

http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.samplerstate.pointclamp.aspx

https://stackoverflow.com/questions/9215027/nearest-neighbor-zoom

If changing the SamplerState of spriteBatch during the different .draw() calls does work because the texture are "initialized" at each operation you're good. But you'll have to temper a bit cause it's not public API (as you said very messy :D).

If they are processed when .end() is called then you would have to override .draw() calls to detect the state of the sampler in order to process them as you want on the last phase.

*Disadvantage* : tempering with inside magic is most of the time a wrong idea

## SECOND OPTION (advised) :

Your real concern is to enable depth-testing. So it will slightly more expensive but you can also do depth-testing with your own algorithm. For a low number of elements this would be very cheap even on a mobile phone.

You can still do packaged texture draws by an algorithm segmenting the calls.

For instance in order of depth : 10 linear interpolations, 2 pointClamp, 2 linear, 2 pointClamp. =\> 4 calls instead of 16.

You just have to specifiy the interploation for each texture and code something like

```
//pseudo-code
data //textures ordered by depth with field interpolation = samplerState
prev = data.next()
spriteBatch.begin(..., prev.interpolation, ...)
spriteBatch.draw(prev)

while(data.hasNext()) {
    next = data.next()
    if(next.interpolation != prev.interpolation){
      spriteBatch.end()
      spriteBatch.begin(..., next.interpolation, ...)
    }
    spriteBatch.draw(next)
    prev = next
}
spriteBatch.end()

```

*Advantage* : You have real control over each draw call (what if you suddenly want to add this special texture interpolation on your gunship or this other element) and this is O(n) (without ordering)

---
Tags: xna, c#, textures, scale
---


title: Additive "Sprites/Default" shader

text:
# Question
Title: Additive "Sprites/Default" shader
The `Sprites/Default` shader multiplies the color with the provided tint, while I need to add it instead. I fixed this copying the shader (taken from here) and simply changing the line

```
return tex2D(_MainTex, IN.texcoord) * IN.color;

```

to

```
return tex2D(_MainTex, IN.texcoord) + IN.color;

```

Is this the right approach, or there was a better one? (which uses something like inheritance, as opposite to copy-pasting)

Also, is this legal? I assume they allow you to use it at will, but technically there's no licence attached to the shader, so I'm not sure. Maybe that's covered somewhere in the Unity license?

# Answer
> 0 votes
According to this answer, you can either include common files, but this isn't the case, or use the `UsePass` command, but is not helpful here either.

Since apparently there isn't really inheritance like with normal object-oriented languages, I'd say there's no other way to do that.

---
Tags: unity, shaders
---


# Question
Title: Floating point precision issue with Box2D
I'm using Box2D and I am putting edge tiles as b2Bodies so that the tile world can have physics:

The problem is that there are 3 b2\_kinematic bodies under the player right beside each other.

Every so often, he gets stuck like in this image (as if there were a very very small slope) and the player box gets stuck. I have to move him back a little to overcome it.

The player has fixed rotation which is what also causes this.

I'm not sure how to fix this.

Any ideas?

Thanks

# Answer
> 3 votes
The problem you're having is that the player box is getting caught up on those 'side' edges of the tiled physics objects you're using.

The usual advice for this sort of situation is to not create your ground by making a lot of boxes which are placed next to each other. Instead, make just one wide rectangle which covers that whole ground section.

You really don't want your collision mesh to have any edges which the player shouldn't be able to bump against; all they'll do is cause this sort of problem.

# Answer
> 0 votes
Your box2d bodies are overlapping, which may cause this behavior. Try removing the overlap, by making your bodies a little smaller.

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


# Question
Title: Calculating 2D Physics Prediction of Shot Angle with Moving Velocity of both targets
I currently have the math right to hit a moving target with 99% accuracy as long as I don't move.
When I start moving the aim is nearly 80%, it should also be 99% accuracy because the target is moving with you at a constant speed.
You can't have 100% accuracy even if you are not a moving player because the other target can dodge your bullet when they see it flying near them, the bullet is shot into the future knowing where the target will end up if they keep moving at the same constant X,Y speeds.

I don't seem to understand how to calculate the new shot angle when I am moving with a moving target together.

Each player has 5 variables

1. X Coordinate in Pixels
2. Y Coordinate in Pixels
3. X Speed (can be negative) this is measured in pixels in 10 milliseconds
4. Y Speed (can be negative) this is measured in pixels in 10 milliseconds
5. Bullet Speed (-32768 to 32767) (negative bullet means how fast a shot is backwards) also measured using pixels, number of pixels traveled in 10 seconds.

The calculates are done using 10 milliseconds so all the X,Y's have to be scaled from 10 seconds to 10 milliseconds as well as Bullet Speed which uses the same 10 seconds pixels traveled system.

```
Weapon Speed of 1000 [Just a base speed for testing]
-----------------------------------------------------------
1000 pixels = 10 seconds                    1000/10 = 100
900 pixels = 9 seconds                      900/9 = 100
...
500 pixels = 5 seconds                      500/5 = 100
100 pixels = 1 second.                      100/1 = 100
50 pixels = 500 milliseconds.               50/500 = 0.1
25 pixels = 250 milliseconds.               25/250 = 0.1
12.5 pixels = 125 milliseconds.             12.5/125 = 0.1
6.25 pixels = 62.5 milliseconds.            6.25/62.5 = 0.1
3.125 pixels = 31.25 milliseconds.          3.125/31.25 = 0.1
1.5625 pixels = 15.625 milliseconds.        1.5625/15.625 = 0.1
0.78125 pixels = 7.8125 milliseconds.       0.78125/7.8125 = 0.1
1 pixel = 10 milliseconds. (seems correct). 1/10 = 0.1
-----------------------------------------------------------
Conclusion How much pixels to travel in time equation is
double PixelsTraveled = (WeaponSpeed / 10,000) * timeSpentInMilliSeconds;

```

The game does a update every 10 milliseconds to everything.
When the Bullet Speed is `1000` that means it travels `100` pixels per second. `(1000/10)=100`

Doubt I need to take into account that 10 milliseconds per game update, since when I don't move I never use 10 milliseconds and it works perfect.

**EDIT:** This thread (outside game loop) actually has a sleep time of 10 milliseconds which cancels out the effect even though it doesn't synchronize the time dot to dot.

Here is the nearly perfect code, 99% accuracy
For myPlayer attacking a moving target when you have `X Speed=0, Y Speed=0`

```
double xDelta = targetPlayer.XCoordinate - myPlayer.XCoordinate;
double yDelta = targetPlayer.YCoordinate - myPlayer.YCoordinate;
double targetDistance = sqrt((xDelta*xDelta)+(yDelta*yDelta));

// Prediction of shot.
double impactTime = targetDistance/targetPlayer.BulletSpeed;
xDelta += impactTime*targetPlayer.XSpeed;
yDelta += impactTime*targetPlayer.YSpeed;

// Gets new firing angle.
double radian = atan(yDelta/xDelta);
printf("new angle = %g\n", radian);

```

Here is the code I attempted to make it get a new firing angle when both targets are moving which I have to take into account both player's speeds and bullet speed.
Seems I have over complicated it with `sqrt` and it doesn't work right.

```
double xDelta = targetPlayer.XCoordinate - myPlayer.XCoordinate;
double yDelta = targetPlayer.YCoordinate - myPlayer.YCoordinate;
double targetDistance = sqrt((xDelta*xDelta)+(yDelta*yDelta));

// Prediction of shot.
double predictBulletSpeedX = myPlayer.BulletSpeed + myPlayer.XSpeed;
double predictBulletSpeedY = myPlayer.BulletSpeed + myPlayer.YSpeed;
double finalBulletSpeed = sqrt((predictBulletSpeedX*predictBulletSpeedX)+(predictBulletSpeedY*predictBulletSpeedY));
double impactTime = (targetDistance/finalBulletSpeed);

xDelta += impactTime*targetPlayer.XSpeed;
yDelta += impactTime*targetPlayer.YSpeed;

// Gets new firing angle.
double radian = atan(yDelta/xDelta);
printf("new angle = %g\n", radian);

```

# Answer
> 3 votes
After testing a few ideas, I'm focusing on this answer because it is the cleanest code. The algorithm is very similar to your approximation, except I've modified it to iterate to a given accuracy:

```
double max_error = 0.0000000001; // measured in radians
double dx=targetPlayer.XCoordinate - myPlayer.XCoordinate;
double dy=targetPlayer.YCoordinate - myPlayer.YCoordinate;
double targetDistance = sqrt(dx*dx+dy*dy);
double ImpactTime=targetDistance/myPlayer.BulletSpeed;
double radian=atan2(dy,dx);
int max_iterations = 100;
while (max_iterations--) {
    printf("Angle: %2.1fdeg, Collision At: (%f, %f)\n", radian*(180.0/M_PI), dx,dy);
    dx = targetPlayer.XCoordinate - myPlayer.XCoordinate +
        (targetPlayer.XSpeed - myPlayer.XSpeed)*ImpactTime;
    dy = targetPlayer.YCoordinate - myPlayer.YCoordinate +
        (targetPlayer.YSpeed - myPlayer.YSpeed)*ImpactTime;
    targetDistance = sqrt(dx*dx+dy*dy);
    ImpactTime = targetDistance/myPlayer.BulletSpeed;
    double newradian = atan2(dy,dx);

    double cur_error = fabs(newradian - radian);
    radian = newradian;
    if (cur_error <= max_error) break;
}

```

# Answer
> 2 votes
```
Doubt I need to take into account that 10 milliseconds per game update, since when I don't move I never use 10 milliseconds and it works perfect.

```

I think that's where you're mistaken.

The fact is you say you do still miss 1% of the time when not moving. This miss rate results from a combination of the incident angle, distance, speed of shot relative to the speed of target, and size of shot relative to size of target -- remember that you are working only with points (centroids) and lines for trajectories, so a larger profile relative to the velocities for each object means a greater chance to hit. Catapulting a car quickly at a slow moving bus is more likely to hit, than catapulting a tennis ball at the same speed, at a faster-moving bus, due to the reduced profile of the tennis ball and the increased speed of the target.

In other words, a lot of the time, the combination of these factors will save you from misses, but not always. Reduce the sizes of shot and target, and make the shot angle perpendicular to the motion of the target, and you will start to see consistent misses. you should always be taking into account your 10ms lead time in your calculations. Your 1% miss rate under ideal conditions is likely a result of your not doing this sort of extrapolation.

You should find that if you do calculate one frame ahead as the target position, your hit ratio for moving target and gunner should increase to near to 100%. If you further use the 2 radii of the objects (or at least radii of their bounding circles) then you should experience a 0% miss rate, provided they experience linear velocities. If non-linear, rather more fluffy calculus will be required.

# Answer
> 0 votes
Change your bullet speed with bullet velocity (make it a vector value and not a scalar) and for each frame calculate its relative x,y movement. Take into account the fact that it's initial velocity is the sum of its velocity plus the player's velocity. Using vector math will give you 100% accuracy under any conditions.

---
Tags: 2d, mathematics, ai, physics, aiming
---


# Question
Title: Shader which supports vertex colors and pixel lights?
From my question at Unity Answers:

Hello everyone, I'm facing a bit of a problem here: I need a shader which has the ability to colour individual vertices and be lit pixel by pixel. Until recently, I was planning to use just vertex shading, since I couldn't find any info about this. The thing, it looks like this: Bad shading 1 and Bad shading 2. As you can see, it is horrendously bizarre and even glitchy. Here is the shader I'm using right now (ShaderLab syntax):

```
Shader "Alpha/VertexLit Colored" {
    Properties {
        _Color ("Main Color", Color) = (1,1,1,1)
        _SpecColor ("Spec Color", Color) = (1,1,1,0)
        _Emission ("Emmisive Color", Color) = (0,0,0,0)
        _Shininess ("Shininess", Range (0.01, 1)) = 0.7
        _MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}
    }

    SubShader {
        //ZWrite Off
        Alphatest Greater 0
        Tags {Queue=Transparent}
        Blend SrcAlpha OneMinusSrcAlpha
        ColorMask RGB
        Pass {
            Material {
                Shininess [_Shininess]
                Specular [_SpecColor]
                Emission [_Emission]
            }
            ColorMaterial AmbientAndDiffuse
            Lighting On
            SeparateSpecular On
            SetTexture [_MainTex] {
                Combine texture * primary, texture * primary
            }
            SetTexture [_MainTex] {
                constantColor [_Color]
                Combine previous * constant DOUBLE, previous * constant
            }
        }
    }
    Fallback "Alpha/VertexLit", 1
}

```

I searched around on the Unity forums, wiki and also on Google, but I found no resources for this. I really need the vertex colours here, it's a crucial element of the graphic style of my game, and is the simplest way to do what I want. Any help is immensely appreciated. Does anyone know if such kind of shader exists?

# Answer
Why not do that with a surface shader? you could have Per Vertex coloring and on a same time keep multi-light shading (Which is "almost" default when using surface shaders)

Surface shaders doc :

According to those docs over here, you should be able to create a basic surface shader with diffuse and lighting. And by tricking the `vertex:disp` in doing no specific action except getting vertex position and converting it to color you want (using an `out` struct which could be a bit more evolved).

After doing that and getting back the color you got in `vertex:disp` inside your albedo infos, you just let surface shaders do their job and take care of the lighting (you can specify it there `#pragma surface surfaceFunction lightModel [optionalparams]`)

EDIT :

I think i'm starting to get what you mean by vertexColor, you mean Weight Shade : giving a vertex a 0-1 value and from this value get the color mix which correspond?

or you just need access to the `Color` property in your input data for `surf` :

```
        struct Input {
            float2 uv_MainTex;
            float4 color : COLOR; //get vertex color (blind shot not sure)
        };

        sampler2D _MainTex;
        sampler2D _NormalMap;
        fixed4 _Color;

        void surf (Input IN, inout SurfaceOutput o) {
            o.Albedo = IN.color.rgb;
            o.Specular = 0.2;
            o.Gloss = 1.0;
            o.Normal = UnpackNormal(tex2D(_NormalMap, IN.uv_MainTex));
        }

```

As stated in docs :

> float4 with COLOR semantic - will contain interpolated per-vertex color

That is definately what you should be looking for
> 3 votes

---
Tags: unity, shaders, fragment-shader, cg
---


title: How do I make time?

text:
# Question
Title: How do I make time?
I wanted to output a text for a certain amount of time. One way is to use threads. Are there any other ways? I can't use threads for slick2d. This is my code when I use threads for slick:

```
package javagame;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import java.util.Random;
import org.newdawn.slick.Input;
import org.newdawn.slick.*;
import org.newdawn.slick.state.*;
import org.lwjgl.input.Mouse;

public class thread1 implements Runnable {
    String showUp;
    int timeLeft;

    public thread1(String s)
    {
        s = showUp;
    }

    public void run(Graphics g)
    {
        try {
           g.drawString("%s is sleeping %d", 500, 500);
           Thread.sleep(timeLeft);
           g.drawString("%s is awake", 600,600);

        } catch(Exception e) { }
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        run();
    }
}

```

It auto generates a new `run()` And also when I call it to my main class it has stack overflow!

# Answer
> 1 votes
You can use the Timer class from LWJGL.

Somewhere in your code you would have:

```
Timer timer = new Timer();

```

Each frame you update this timer:

```
timer.tick();

```

And then when you need to retrieve the elapsed time:

```
float elapsed = timer.getTime() - lastframe;
lastframe = timer.getTime();

```

And do the processing you want:

```
if (elasped >= ACTION_DELAY)
    do();

```

This class also provides useful methods like pausing, resting etc.

Also you may want to check this.

# Answer
> -2 votes
You need a long timeLeft not int

long = time int = just a number

---
Tags: java, slick
---


# Question
Title: Using an image instead of a colored rectangle
I recently watched a video on how to do tilemaps in java. He has the tiles as colored rectangles. I want them to be images.

My code:

```
public void draw(Graphics g){
    for(int row = 0; row < mapheight; row++){
        for(int col = 0; col < mapwidth; col++){

             int rc = map[row][col];

             if(rc == 0){
                 g.setColor(Color.green);
             }

             if(rc == 1){
                 g.setColor(Color.yellow);
             }

             g.fillRect(x + col * tilesize, y + row * tilesize,tilesize,tilesize);

        }
    }
}

```

This is the tilemap class. It says if rc is = to 0 it sets the color to green. Is there any way I can change that to an image?

# Answer
> 1 votes
Without a fairly substantial change in your code, your options are limited.

If you take a look at the functions provided for you in the `Graphics` class, you'll find a `drawImage` function that will allow you to draw an image instead of using the existing `fillRect` function.

Even this simpler change is going to require more changes to your code than just one line. You'll need to add image loading, storage and selection.

I recommend you find a tutorial for tile maps using images, instead of attempting to modify this code to work for you.

---
Tags: java, tiles
---


# Question
Title: GLSL does weird things to my view matrix
```
uniform mat4 model;
uniform mat4 view;

varying vec4 vColor;

void main(){
    gl_TexCoord[0] = gl_MultiTexCoord0;
    gl_Position = view * model * gl_Vertex;

    vColor = gl_Color;

    if(view * model * gl_Vertex == model * gl_Vertex) vColor = vec4(0, 1, 0, 1);

}

```

Basically, if everything without the camera's view matrix applied is equal to everything WITH the camera's view matrix applied, make everything green.

Everything's green. Even when I change the view matrix (move the camera around).

Obviously, this means the view matrix is an identity one. I checked. It isn't. It's a perfectly simple 4x4 matrix, that has the 1's running diagonally and the x and y coordinates in the fourth column, first and second row respectively.

```
public void setMat4Uniform(Matrix4f value, String name){
    FloatBuffer buffer = BufferUtils.createFloatBuffer(4 * 4);
    value.store(buffer);
    buffer.flip();

    glUniformMatrix4(glGetUniformLocation(programId, name), false, buffer);
}

```

This is what I use to send uniforms to the GPU. I'm pretty sure it isn't faulty because it sends the model matrix without problems.

And here's the weird part (at least for me). If I set the gl\_Position variable to just model * gl\_Vertex (as opposed to view * model * gl\_Vertex), and then move the camera around, nothing's green. Somehow, gl\_Position = view * model * gl\_Vertex is affecting my view matrix.

Could anybody help?

EDIT: I figured out what the problem was. It was a silly mistake, completely different from what I thought it was at first. Thanks, everybody, for trying to help.

# Answer
> 3 votes
Well, GLSL isn't doing anything weird to your view matrix.

First of all you are comparing floating point using `==` in your shader. This is bad, and probably will never return true, that explains why when you move the camera you never see anything grean. You are basically assuming both terms (left and right of the `==`) will return the same exact value (bit by bit). Unfortunately floating point doesn't work like this, floats try to represent real world numbers (infinite) using finite precision so a lot of approximation comes into play. That's why we use error margine when comparing floats like this

```
if ( fabs( a - b) < 1e-12 ) // compares a and b
instead of doing this
if ( a == b ) // this won't work if a = 0.00000091 and b = 0.00000092
and you probably want them to be equal. (my example might not be real but you get the
idea.

```

I also answered a question about floating point error here

Second, using if statements in a shader is highly discouraged, this will highly affect performance. Unlikely in your case but just for the record. Check the discussion here for using conditionals in shaders.

---
Tags: opengl, glsl, camera, view
---


# Question
Title: How do I rotate a bounding box together with a sprite?
I have a game object with a sprite that can rotate. It's a rectangle. I need its bounding box to rotate with it. How do I make sure that they can both rotate, but they're always both at the same angle?

# Answer
> 2 votes
Each corner should be rotated around the center of the box.

Typically this would be done by translating the box back to the origin, rotating, then translating back to the starting position.

Imagine the points that make up the corners rotating around a circle:

For rotating each point, see this answer.

---
Tags: 2d, sprites, rotation, bounding-boxes
---


# Question
Title: Implementing `fling` logic without pan gesture recognizers
So I am trying to port over a simple game that I originally wrote to iphone into cocos2d-x. I've hit a minor bump however in implementing simple 'fling' logic I had in the iphone version that is difficult to port over to the c++. In iOS I could get the velocity of a pan gesture very easily:

```
CGPoint velocity = [recognizer velocityInView:recognizer.view];

```

However now I basically only know where the touch began, where the touch ended, and all the touches that are logged in between. For now I logged all the pts onto a stack then pulled the last point and the 6th to last point (seemed to work the best), find the difference between those pts multiply by a constant and use that as the velocity. It works relatively well, but I'm wondering if anyone else has any better algorithms, when given a bunch of touch pts, to figure out a new speed upon releasing an object that feels natural (Note speed in my game is just a constant x and y, there's no drag or spin or anything tricky like that).

Bonus points if anyone has figured out how to get pan gestures into the newest version (3.0 alpha) of cocos2d-x without losing ability to build cross platform.

# Answer
> 1 votes
I think using just the last points is a little risky. For example, if the user do a lot of harsh movements but the last 6 points are generated from a very calm movement your system will behave wrongly by discarding all the other points.

If you have performance limitations you could indeed fix the number of points to be seen but use a list instead of a stack so you can interpolate the indices of the points to be checked based on the size of the list and the number of values you want to consider. The main idea is:

```
const int MAX_POINTS_TO_CONSIDER = /*your constant value here*/;
const int finalPointsToConsider = min(pointVector.size(), MAX_POINTS_TO_CONSIDER);
const int step = pointVector.size(); / finalPointsToConsider;

for(int i = 0, i < finalPointsToConsider; ++i) {
    Point p = pointVector[i*step];

    // Do your computation here
}

pointVector.clear();

```

If you don't have performance problems, just use all points to be accurate.

# Answer
> 0 votes
the best is to look at the implementation of the recognizer. You can have a look at the open source project Chamelon that ports uikit to mac os.

in your case your can find the implementation of your recognizer here : https://github.com/BigZaphod/Chameleon/blob/master/UIKit/Classes/UIPanGestureRecognizer.m

it seems that it just takes the last two points.

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


title: On Demand Loading of MipMap Layers

text:
# Question
Title: On Demand Loading of MipMap Layers
I have heard that in OGL and in DX9 `D3DPOOL_MANAGED` mipmap layers are pulled to the GPU memory on demand. As in If I pull from layer 4 of a mipmap, that layer and all smaller layers are pulled into the GPU memory, but larger mipmap layers are not.

I have tried to test this by creating a scene which requires more textures than the GPU has room for, but never getting close enough to any object such that it's larger mipmaps are required.
In OGL I don't hit a performance cliff, and as best I can tell with gDebugger I don't fill the GPU memory.
In `D3DPOOL_DEFAULT` I actually get a DX9 error cause I run out of GPU memory space.

At such a high level of abstraction I can't conclusively say what's happening. But I was hoping someone here could confirm or deny the partial mipmap rumor I've heard, as that would make my tests make sense.

# Answer
If you want on-demand loading of "mipmap layers" there is actually a new hardware feature in DX 11.2 class hardware for this exact purpose. AMD introduced it first to OpenGL as sparse textures, it virtualizes the memory used by textures and allows individual LODs to be demand-paged the first time they are actually referenced in a fragment/pixel shader. D3D 11.2 standardizes this feature and calls it "tiled resources." This is honestly the only time you will ever (portably) have fine-grained knowledge of how the driver is managing your texture's memory at the LOD level.

Using this hardware-level feature, you can even tell inside your shader, whether an LOD is resident or not. This is very handy because demand-loading any resource introduces quite a bit of latency, and you want to be able to fallback to a lower LOD while you load the LOD into memory rather than suddenly increasing the time taken to render 1 frame by a factor of 10.
> 1 votes

---
Tags: resource-management, mipmaps
---


# Question
Title: libgdx default saving mechanism for box2d world
I want to save my game in **libgdx**, and I have no problem using **Kryo** to save everything, except the **box2d** Worlds and the RayHandlers from **box2dlights** \- these are not Serializable and do not have default constructor, ruling out most of the methods. I have no idea how to save them, but I'm aware the most used approach is **JSON** \- which I'm ok with. I even found this, but it seems to be specific for **jBox2D** alone, because I'd have to change all the names and packages in the code to match **libgdx**'s **box2d** version's. Also, it uses the famous original JSON lib for java, whereas libgdx has it's own internal **JSON** handler and parser. So, I could just convert everything, as I said, it's all opensource. But it is such an absolutely essential task (serializing), present in every single game, that I think **libgdx** might also have something to do this. I can't, however, find anything about it, anywhere. Can someone put a light on this?

Just some **background**: my game happens in a galaxy, and every single planet has it's own World for handling. But I only load one planet at a time in the memory: when the player leaves, I save it on a file. So my save consist of one main file with player data, galaxy structure, anyway, everything else, and a folder with one file for each Area (planet's map). This map contains some objects and data plus the World and RayHandler from box2d and box2dlights. I'm using JSON (libgdx's default) already for the Area class, but if the world and rayHandler fields are no transient, I get a StackOverflow, probably due to circular refences not supported by JSON writers. As I said, I can't use kryo due to the lack of private default constructors in most classes, and JSON does seem to be the standard approach for this. The lack of a solution built-in in libgdx, however, is really making me wonder what I'm not seeing in all this.

# Answer
> 1 votes
For most scenarios it's beneficial to wrap the objects you have no control over (box2d in your case) in your own objects with custom serialize methods.

That or build a custom serialize method in your world manager presumably you have a list of the bodies somewhere (for destroying later), which you could flatten down in a serialize method for the whole world instead of per-body.

But either way you'll need your own serialize method, decide which attributes you need to keep most times you just need position and angle, but if you have other non-constant properties like restitution, etc. Save those as well.

Here is some example on custom methods: https://github.com/EsotericSoftware/kryo#kryoserializable

Same goes for the Lights in box2dlights, and i don't think the rayhandler has any state to save, so long as you successfully re-add the lights once they are de-serialized the rayhandler should be fine.

---

Though as a side bar it seems that kryo may be able to serialize these private fields in Box2d via reflection: https://github.com/EsotericSoftware/kryo#fieldserializer

For your consideration, though i don't have much experience with kryo so i cannot comment.

---
Tags: box2d, libgdx, jbox2d, serialization
---


title: glGetUniformLocation Returns -1

text:
# Question
Title: glGetUniformLocation Returns -1
I've been trying to develop shaders that would allow me to easily display text on screen using a font texture. I've previously written shaders that simply drew the text on screen and I passed the exact coordinates for the vertices and UV coordinates to the shaders. With my new shaders, I'm trying to pass *just* a single point for each letter, representing the bottom left corner each letter, as well as a single point for the UV coordinate of the letter, representing its location on the font texture. I then use a geometry shader to generate the triangles and UV coordinates necessary to draw the letters. Here is my code for the shaders:

Vertex Shader:

```
#version 330
layout(location = 0) in vec2 vertexPosition;
layout(location = 1) in vec2 vertexUV;
layout(location = 2) in float textSize;
uniform unsigned int textureX;
uniform unsigned int textureY;
out VertexData
{
    vec2 uv;
    float textSize;
} outputData;
void main()
{
    // Represents the bottom left corner
    gl_Position = vec4(vertexPosition, 0.0f, 1.0f);
    // Convert the UV coordinates from [0, textureX - 1] to [0, 1]
    outputData.uv = vertexUV / vec2(textureX, textureY);
    outputData.textSize = textSize;
}

```

Geometry Shader:

```
#version 330
layout(points) in;
layout(triangle_strip, max_vertices = 6) out;
uniform unsigned int textureX;
uniform unsigned int textureY;
in VertexData
{
    vec2 uv;
    float textSize;
} inputData[];
out FragmentData
{
    vec2 uv;
} outputData;
void main()
{
    float textureWidth = 1.0f / textureX;
    float textureHeight = 1.0f / textureY;
    // Calculate the vertices
    vec2 brCorner = vec2(gl_in[0].gl_Position) + vec2(inputData[0].textSize, 0.0f);
    vec2 tlCorner = vec2(gl_in[0].gl_Position) + vec2(0.0f, inputData[0].textSize);
    vec2 trCorner = vec2(gl_in[0].gl_Position) + vec2(inputData[0].textSize, inputData[0].textSize);
    vec2 uvBR = inputData[0].uv + vec2(textureWidth, 0.0f);
    vec2 uvTL = inputData[0].uv + vec2(0.0f, textureHeight);
    vec2 uvTR = inputData[0].uv + vec2(textureWidth, textureHeight);
    gl_Position = vec4(tlCorner, 0.0f, 1.0f);
    outputData.uv = uvTL;
    EmitVertex();
    gl_Position = gl_in[0].gl_Position;
    outputData.uv = inputData[0].uv;
    EmitVertex();
    gl_Position = vec4(trCorner, 0.0f, 1.0f);
    outputData.uv = uvTR;
    EmitVertex();
    EndPrimitive();
    gl_Position = gl_in[0].gl_Position;
    outputData.uv = inputData[0].uv;
    EmitVertex();
    gl_Position = vec4(brCorner, 0.0f, 1.0f);
    outputData.uv = uvBR;
    EmitVertex();
    gl_Position = vec4(trCorner, 0.0f, 1.0f);
    outputData.uv = uvTR;
    EmitVertex();
    EndPrimitive();
}

```

Fragment Shader:

```
#version 330 core
in FragData
{
    vec2 uv;
} inputData;
out vec4 color;
uniform sampler2D textureSampler;
void main()
{
    color = texture2D(textureSampler, inputData.uv);
}

```

When I call glGetUniformLocation for the textureSampler uniform in my fragment shader, I get a valid uniform location back. However, when I call glGetUniformLocation for textureX and textureY, glGetUniformLocation returns -1. When I searched for what could cause this, the main cause of this issue is usually the compiler optimizing the variable out as it's not used. I don't believe this to be true in my case, but I have no idea what could be causing glGetUniformLocation to return -1 for this.

**Edit:** After reading Andon M. Coleman's excellent answer on how active uniforms are determined, I discovered the issue. The name of the struct the geometry shader outputs and the name of the struct the fragment shader accepts are different-

Geometry Shader:

```
out FragmentData
{
    vec2 uv;
} outputData;

```

Fragment Shader:

```
in FragData
{
    vec2 uv;
} inputData;

```

After changing the structs to share the same name, I am able to get a valid uniform location back.

# Answer
Since there was a little bit of confusion in the comments regarding what is required for a uniform to be ***active***, I will try to explain it here.

The first thing you need to understand is that in OpenGL, GLSL programs are built in two phases:

1. Compile
2. Link

These are analogous to compiling and linking in a language like C, except some implementations of GLSL (e.g. NVIDIA) actually "compile" your shader in both phases. The most important thing that happens in the ***Compile*** phase is that general parse / syntax errors are caught, and inputs and outputs are determined.

After the compile phase determines the set of inputs and outputs for each stage of the GLSL program, the ***Link*** phase then assigns data locations to things like generic vertex attribute locations, fragment bindings, uniform locations, etc. But there is a catch, it only assigns locations to uniforms that ***actively*** contribute to pipeline output.

---

Below are two overly-simplified shaders that exemplify what happens when a Vertex Shader outputs something that is not used by any other stage to produce an output.

### Hypothetical Vertex Shader (Active + Inactive Uniforms)

```
#version 330

uniform float UsedButNotActive;
uniform float Active;

in      vec4  ndc_vtx;

out     float UsedButNotOutput;
out     float Used;

void main (void)
{
  gl_Position = ndc_vtx;

  UsedButNotOutput = UsedButNotActive;
  Used             = Active;
}

```

### Hypothetical Fragment Shader

```
#version 330

in  float UsedButNotOutput;
in  float Used;

out vec4  color;

void main (void)
{
  // Inactive, because this does not produce any output
  float Pointless = sqrt (UsedButNotOutput);

  // Used, and any variable that was used to compute it, is part of an active code path
  color = vec4 (Used);
}

```

Because the variable `Used` is the only variable in the fragment shader stage that contributes to an output, it is the only active code path. This means the uniform `Active` is part of an active code path and will be assigned a uniform location.

`UsedButNotOuput`, on the other hand, is used to compute something in the fragment shader, but that something is never output. This variable effectively dies inside the fragment shader. If you trace its path back to the vertex shader, you will see that `UsedButNotActive` was used to set this value, but does not belong to an active code path. Thus, that uniform is not active and is ***not*** assigned a uniform location.

---

Remember how I mentioned that some GLSL implementations compile your shader twice? Well, after all this active vs. inactive codepath determination, some lines and variables will effectively be stripped from the shader the second time it is compiled.

### Hypothetical Link-Phase Vertex Shader (Active Uniforms)

```
#version 330

//uniform float UsedButNotActive; -- STRIPPED
uniform float Active;

in      vec4  ndc_vtx;

//out     float UsedButNotOutput; -- STRIPPED
out     float Used;

void main (void)
{
  gl_Position = ndc_vtx;

  //UsedButNotOutput = UsedButNotActive; -- STRIPPED
  Used   = Active;
}

```

### Hypothetical Link-Phase Fragment Shader

```
#version 330

//in  float UsedButNotOutput; -- STRIPPED
in  float Used;

out vec4  color;

void main (void)
{
  //float Pointless = sqrt (UsedButNotOutput); -- STRIPPED

  // Used, and any variable that was used to compute it, is part of an active code path
  color = vec4 (Used);
}

```

---

It is worth mentioning that some of this behavior is altered by new OpenGL features such as ***Separate Shader Objects***, which makes the concept of active vs. inactive uniforms almost meaningless / impossible to determine. Also, when transform feedback is used, it means that data does not have to be output from the fragment shader stage in order for a variable to be involved in an active codepath. However, this explanation should make it obvious why if you are missing the geometry shader stage of your GLSL program in your code, then the uniforms `textureX` and `textureY` do not belong to any active code paths.

Also note that any uniform used to calculate `gl_Position` is ***active*** simply because `gl_Position` is an important interpolated/used input for **every** shader stage following vertex. It is responsible for producing `gl_FragCoord`, which determines where the fragment is output in the fragment shader stage, for instance.
> 6 votes

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


# Question
Title: How to implement status-changing effects for attack class in turn based RPG?
I'm implementing "On Attack" and "On Receive Damage" within my game and from these two answers(Implementing flexible buff system,Implementing attack class in RPG ) I got that I will be implementing custom handlers which will modify the attack effects. I've included an example below.

My question is - **how to handle status changing special effects, such as knockdown, poison over time, petrify, etc?** Do I need include them in my attack/damage class and have defender's damage handlers adjust the attack parameters, or is there a better way to handle special effects?

```
@interface Attack : NSObject

-(id)initWithDamage:(int)damage type:(int)damageType;

@property (nonatomic)int type;
@property (nonatomic)int value;
@property (nonatomic)int penetration;
@property (nonatomic,strong)NSMutableArray* attackEffects;
@end

```

Here's the understanding that's starting to form in my head:

* **Attacker** records everything about the attack in an Attack class:
* Create Attack class for each attack
* Record **damage type**(physical/magical) and value
* Pass Attack to the attacker's (**onAttack**) handlers
* Each effect within attackers list of buffs **applies it's effects** to attack,(ex: poison over time, knockdown)
* Pass the attack over to **defender** for his (onReceiveDamage) buffs to handle
* Defender's list of buffs marked "**on receive damage**" modifies the attack (poison immunity removes poison over time)
* Pass attack over to the defender to **resolve**
* Check for special conditions (ex: can't poison undead), further adjust attack effects
* Each effect that has passed the check is applied to defender

Repeat for counter attack.

What I'm concerned about: the method mutates `attack` instance, meaning any time I ask a character for `attack`, I actually need to get a copy of the `attack`. My `attack` class has started as a tuple, and there's already some code around that expects that checking attack is a simple operation. If `attack` gets overloaded with effects, and starts to be passed around as copy, this may have implications on my other code.

# Answer
> 2 votes
You do not need nor what `attack` to be mutable. There's easy workarounds to avoid it.

The attack has a list of `AttackEffect`s (or whatever you want to name them). The recipient's `OnAttacked` method takes that list of effects as an immutable reference (no need to copy). The method then iterates over each effect and applies that effect to the target with e.g. an `OnAttackDamage` or `OnPoisoned` method which takes input relevant parameters (damage type, strength, time, etc.). This method then checks the list of buffs (or a more efficient set of cached data) and modifies the input values accordingly before applying them.

Your attack does *not* do damage over time. The attack causes the recipient to acquire a "debuff" that does poison over time. The attack is a once-off affair. There is simply a `PoisonAttackEffect` subclass that includes the poison damage and time. The recipient's `OnPoisoned` takes that damage and time and creates a new `PoisonDebuff` to add to the character with the given parameters, modified as appropriate by resistances and the like.

That's the crux of Benjamin's comment above. The attack is *always* instant. There is no part of the attack that is not instant. Lasting effects of the attack are handled by having the attack instantaneously insert a record into the target of the damage to be done over time.

In somewhat rather overly-typed pseudo-code, it might look something like:

```
// Effects that weapons can have

class AttackEffect:
  abstract Apply(target)

class DamageEffect:
  int amount
  override Apply(target):
    target.OnDamage(this.amount)

class PoisonEffect:
  int amount
  int seconds
  override Apply(target):
    target.OnPoison(this.amount, this.seconds)

class Weapon:
  AttackEffect effects[]
  void Attack(target):
    for effect in this.effects:
      effect.Apply(target)

class Character:
  Buff buffs[]

  OnDamage(amount):
    for buff in this.buffs:
      amount = buff.ModifyDamage(amount)

    hp -= amount
    CheckIfDead()

  OnPoison(amount, seconds):
    for buff in this.buffs:
      amount, seconds = buff.ModifyPoison(amount, seconds)

    this.buffs.append(new PoisonDebuff(amount, seconds))

  Update(dt):
    for buff in this.buffs:
      buff.ApplyUpdate(this, dt)

    RemoveExpiredBuffs(this.buffs)

```

You can take this a bit further by allowing the attacker to have buffs that grant additional `AttackEffect`s beyond those innate to the weapon or to have the attacker's buffs be allowed to modify the "outgoing" values (so e.g. the attacker could have a buff like "+50% to all poison damage").

---
Tags: architecture
---


# Question
Title: How set and count Angle of sprite (turret) object in portrait mode in cocos2d?
I am new in cocos2d.I follow Raywenderlich tutorial series. I wish to set turrets in below of the screen in portrait mode.when user touch that location fire bullet and turret fire position at the touch location. how can i do that. Below is my image of turret position.

# Answer
```
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    if (_nextProjectile != nil) return;

    // Choose one of the touches to work with
    UITouch *touch = [touches anyObject];
    CGPoint location = [self convertTouchToNodeSpace:touch];

    // Set up initial location of projectile
    CGSize winSize = [[CCDirector sharedDirector] winSize];
    _nextProjectile = [[CCSprite spriteWithFile:@"projectile2-Hd.png"] retain];

     _nextProjectile.position = ccp(winSize.width/2,20);

    // Determine offset of location to projectile
    CGPoint offset = ccpSub(location, _nextProjectile.position);
     NSLog(@"offset.x : %f",offset.x);
    NSLog(@"offset.x : %f",offset.y);

    // Bail out if you are shooting down or backwards
   if (offset.y <= 0) return;

    int realY = winSize.height - (_nextProjectile.contentSize.width/2);
     float ratio = (float) offset.x / (float) offset.y;
    int realX = (realY * ratio) + _nextProjectile.position.x;
    CGPoint realDest = ccp(realX, realY);

    // Determine the length of how far you're shooting
    int offRealX = realX - _nextProjectile.position.x;
    int offRealY = realY - _nextProjectile.position.y;
    float length = sqrtf((offRealX*offRealX)+(offRealY*offRealY));
    float velocity = 480/1; // 480pixels/1sec
    float realMoveDuration = length/velocity;

    // Determine angle to face
   // float angleRadians = atanf((float)offRealY / (float)offRealX);
    float angleRadians = atanf((float)offRealX / (float)offRealY);

    float angleDegrees = CC_RADIANS_TO_DEGREES(angleRadians);
   // float cocosAngle = -1 * angleDegrees;
     float cocosAngle = angleDegrees;
    float rotateDegreesPerSecond = 180 / 0.5; // Would take 0.5 seconds to rotate 180 degrees, or half a circle
    float degreesDiff = _player.rotation - cocosAngle;
    float rotateDuration = fabs(degreesDiff / rotateDegreesPerSecond);
    [_player runAction:
     [CCSequence actions:
      [CCRotateTo actionWithDuration:rotateDuration angle:cocosAngle],
      [CCCallBlock actionWithBlock:^{
         // OK to add now - rotation is finished!
         [self addChild:_nextProjectile];
         [_projectiles addObject:_nextProjectile];

         // Release
         [_nextProjectile release];
         _nextProjectile = nil;
     }],
      nil]];

    // Move projectile to actual endpoint
    [_nextProjectile runAction:
     [CCSequence actions:
      [CCMoveTo actionWithDuration:realMoveDuration position:realDest],
      [CCCallBlockN actionWithBlock:^(CCNode *node) {
         [_projectiles removeObject:node];
         [node removeFromParentAndCleanup:YES];
    }],
      nil]];

    _nextProjectile.tag = 2;

  // [[SimpleAudioEngine sharedEngine] playEffect:@"pew-pew-lei.caf"];
}

```
> 0 votes

---
Tags: ios, cocos2d-iphone, cocos2d
---


# Question
Title: Fast Forward Drawing using ACEdrawingView
i am using this : https://github.com/acerbetti/ACEDrawingView i want to implemented one Functionality in which i want Fast drawing by clicking on a Button. i am drawing points on screen. i have got success For drawing small amount of points But when i try to draw with more points & draw them with Zero Delay then my app crashes .How can i draw for more points or say more data .!!

```
-(void)playVideoForDict1:(NSMutableArray*)playvideo widMul:(float)widMul1 heimul:(float)heiMul1 whichValue:(int)thisValue
{

widMul = widMul1;
heiMul = heiMul1;

[NSObject cancelPreviousPerformRequestsWithTarget:self];

for(int i = 0; i<[playvideo count]; i++)
{

    NSDictionary *dict1 = [[NSDictionary alloc] init];
    dict1  = [playvideo objectAtIndex:i];

for(int i=0; i<[playvideo count]; i++)
{

    self.currentTool = nil;

    NSDictionary *dict1 = [[NSDictionary alloc] init];
    dict1  = [playvideo objectAtIndex:i];

    if ([dict1 count]==4)
    {

        self.drawTool = ACEDrawingToolTypePen;
        self.currentTool = [self toolWithCurrentSettings];
        [self.pathArray addObject:self.currentTool];
        NSDictionary *colorDic = [dict1 objectForKey:@"colore"];
        if ([[dict1 objectForKey:@"lineWidth"] floatValue]==1) {
            self.lineWidth = 5;
        }else if ([[dict1 objectForKey:@"lineWidth"] floatValue]==2) {
            self.lineWidth = 10;
        }else if ([[dict1 objectForKey:@"lineWidth"] floatValue]==3) {
            self.lineWidth = 15;
        }else if ([[dict1 objectForKey:@"lineWidth"] floatValue]==4) {
            self.lineWidth = 30;
        }

        if ([[CCDirector sharedDirector] winSize].width==768)
        {
            self.lineWidth *=2;
        }
        self.currentTool.lineWidth = self.lineWidth;

        self.currentTool.lineColor = [UIColor colorWithRed:[[colorDic objectForKey:@"r"] floatValue] green:[[colorDic objectForKey:@"g"] floatValue] blue:[[colorDic objectForKey:@"b"] floatValue] alpha:1];

        self.currentTool.lineAlpha = 1;

        [self.currentTool setInitialPoint:currentPoint];

        currentPointArray = [dict1 objectForKey:@"points"];

        for (int i = 2; i<[currentPointArray count]; i++)
        {
            currentPoint = CGPointMake([[[currentPointArray objectAtIndex:i] objectForKey:@"x"] floatValue]*widMul, [[[currentPointArray objectAtIndex:i] objectForKey:@"y"] floatValue]*heiMul);

            previousPoint2 = CGPointMake([[[currentPointArray objectAtIndex:i-2] objectForKey:@"x"] floatValue]*widMul, [[[currentPointArray objectAtIndex:i-2] objectForKey:@"y"] floatValue]*heiMul);
            previousPoint1 = CGPointMake([[[currentPointArray objectAtIndex:i-1] objectForKey:@"x"] floatValue]*widMul, [[[currentPointArray objectAtIndex:i-1] objectForKey:@"y"] floatValue]*heiMul);
            if ([self.currentTool isKindOfClass:[ACEDrawingPenTool class]]) {
                CGRect bounds = [(ACEDrawingPenTool*)self.currentTool addPathPreviousPreviousPoint:previousPoint2 withPreviousPoint:previousPoint1 withCurrentPoint:currentPoint];
                CGRect drawBox = bounds;
                drawBox.origin.x -= self.lineWidth * 1.0;
                drawBox.origin.y -= self.lineWidth * 1.0;
                drawBox.size.width += self.lineWidth * 2.0;
                drawBox.size.height += self.lineWidth * 2.0;
                [self setNeedsDisplayInRect:drawBox];
            }
            else
            {
                [self.currentTool moveFromPoint:previousPoint1 toPoint:currentPoint];
                [self setNeedsDisplay];
            }

        }

         [self updateCacheImage:false];
    }

    else
    {
        NSNumber *check = [dict1 objectForKey:@"undo"];
        if ([check intValue]==1)
        {
            [self.pathArray removeLastObject];
        }
        else
        {
            [self.pathArray removeAllObjects];
        }
    }
    [self updateCacheImage:true];

}

```

}

i am stuck with this . please Help on this .. How can i achieve this .

# Answer
it seems i was having memory Issue :

i Change my code like this :

In updateCacheImage method :

You need to put Your imageContext in AutoReleaspool to free up your memory.

@autoreleasepool {

```
// init a context

UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0.0);

//End Context

UIGraphicsEndImageContext();

```

}

i also have make my objects To nil for making memory Free like this way :

```
id object;
object = nil;

```

it works For me.
> 1 votes

---
Tags: ios, cocos2d-iphone
---


# Question
Title: Exists a dedicated non-O(n²) Algorithm for avoiding to have overlapping elements?
I am generating positions in a random fashion.

In the game world, instantiated elements have a radius, and shouldn't overlap.

The problem is that they will overlap because I use a usual random number generator combined with other fanciness. I can't use other random number generation algorithms where I can guarantee that the elements will never overlap.

A way to solve this is to use a spatial data structure and search for the nearest neighbors in that tree. When I insert an element into that tree, I update it accordingly.

This solution would do the work and it would be fast but my question is:

Is there a dedicated algorithm without that Tree implementation complexity which is faster than `O(n²)`?

# Answer
You already have the answer:

> A way to solve this is to use a spatial data structure and search for the nearest neighbors in that tree. When I insert an element into that tree, I update it accordingly.

You need a tree data structure to actually get a better worst case using scenario, this will give you an O(log N) for nearest neighbor searches.

Grids on the other hand will still give you a better average solution, so you only need to check the adjacent cells, but this will not be as good as the tree structure.

I can also think of spatial hashing but am not particularly sure that a nearest neighbor problem can be solved and give a better performance that trees since I didn't try it myself. You can also check this wikipedia page for the common nearest neighbor search algorithms.

Regarding your number generation I want to point out to this article, that says that using your RNG or grid sampling won't give you points that really look naturally random (will be either too messy or too regular) and why you should use a Poisson point disk sampling instead.

http://devmag.org.za/2009/05/03/poisson-disk-sampling/
> 4 votes

# Answer
option 1 divide your area up into a grid and assign each object to a cell according to there position, now you only have to check the cell it is in and the neighbouring cells (those only if the new object gets close enough)

option 2 sort the objects according to 1 axis and then you can easily find all objects that overlap a certain interval on that axis (this breaks down in dimensions higher than 2 though)
> 0 votes

---
Tags: algorithm
---


# Question
Title: Efficiently checking input and firing events
I'm writing an InputHandler class in XNA, and there are several different keys considered valid input (all of type `Microsoft.XNA.Framework.Input.Keys`). For each key, I have three events:

```
internal event InputEvent XYZPressed;
internal event InputEvent XYZHeld;
internal event InputEvent XYZReleased;

```

where `XYZ` is the name of the `Keys` object representing that key. To fire these events, I have the following for each key:

```
if (Keyboard.GetState().IsKeyDown(XYZ))
{
  if (PreviousKeyState.IsKeyDown(XYZ))
  {
    if (XYZHeld != null)
      XYZHeld();
  }
  else
  {
    if (XYZPressed != null)
      XYZPressed();
  }
}
else if (PreviousKeyState.IsKeyDown(XYZ))
{
  if (XYZReleased != null)
    XYZReleased();
}

```

However, this is a lot of repeated code (the above needs to be repeated for each input key). Aside from being a hassle to write, if any keys are added to/removed from the keys (if functionality is added/removed), a new section needs to be added (or an existing one removed).

Is there a cleaner way to do this? Perhaps something along the lines of

```
foreach key
  check which state it's in
  fire this key's event for that state

```

where the code does the foreach (automatically checking exactly those keys that "exist") rather than the coder?

# Answer
I would definitely avoid having an event for each key, and certainly not an event for each key and state change. Worse, a 'held' event is very ambiguous as to when it should fire: once a frame? Once every X seconds?

To keep full control of your input, it's better to poll at a specific point in your update loop. In that polling function (which I've called CheckForKeyPresses below), you check the current state against the previous state to watch for state changes.

When that function is called, iterate over the list of keys you are interested in, and check if any of them are pressed or released now. If you identify that a key that is pressed now that wasn't before, or a key that is released now when it was pressed before, then you have a state change for that key. Once you've identified that is the case, call a 'dispatcher' function to do some work. E.g.

```
List<Key> myKeys;
Dictionary<Key, bool> keyPressedState;

private void CheckForKeyPresses()
{
    foreach (Key key in myKeys)
    {
        if (Key.IsPressed(key) && !keyPressedState[key])
        {
            keyPressedState = true;
            HandleKeyPressed(key);
        }
        else if (!Key.IsPressed(key) && keyPressedState[key])
        {
            keyPressedState = false;
            HandleKeyReleased(key);
        }
    }
}

private void HandleKeyPressed(Key key)
{
    if (key == Keys.W)
    {
        GoForward();
    }
    //else if ...
}

```

Held keys you want to handle slightly differently: in your update loop, at some obvious point when you're checking inputs, call a function to see if any keys which were held are still held, and handle them there.

```
private void CheckForHeldKeys()
{
    foreach (Key key in myKeys)
    {
        //is it still pressed?
        if (keyPressedState[key] && Key.IsPressed(key))
        {
            HandleKeyHeld(key);
        }
    }
}

```

Now, the **dispatcher** logic is probably the thing you want to code as events. I.e. in HandleKeyPressed, if you detect a press of the W key, then you raise the 'go forward' event. That way multiple listeners can react to a single event. This dispatching through events forms your control mapping. The rest of your game doesn't have to know that it's the W key that maps to going forward, because it's bound to a *logical* control event instead of a *physical* one. That allows you to rebind W to some arbitrary key, and not have to change a bunch of code elsewhere that assumes that forward is always W.
> 3 votes

# Answer
There's a way if you don't mind using a bit of reflection, but I'm not sure I'd recommend it, especially since the title mentions efficiency. But I'll describe it anyway. I'll assume there's a subset of keys you want to cover, and not the entire `Keys` enumeration. If you want to cover *every* key, iterate directly over the enumeration values instead of using the array below:

1. Add every key you're interested in to an array:

```
public Keys[] keys = {Keys.A, Keys.B, Keys.C};

```
2. Create the events for these keys. I'll use a simple `Action` delegate which has no parameters and no return value (add other types of events).

```
public event Action APressed;
public event Action BPressed;
public event Action CPressed;

```
3. Next we need an utility method to call an event by name. This is where the reflection comes in. Once again I'll assume that there are no parameters to the events, and I'll place the method in the same class that stores the events:

```
private void RaiseEventByName(string eventName)
{
    var eventDelegate = (MulticastDelegate)GetType().GetField(eventName, BindingFlags.Instance | BindingFlags.NonPublic).GetValue(this);
    if (eventDelegate != null)
        foreach (var handler in eventDelegate.GetInvocationList())
            handler.Method.Invoke(handler.Target, null);
}

```
4. Finally our `Update` loop becomes something like (add logic for other states):

```
foreach(Keys key in keys)
    if (currentKeyboardState.IsKeyDown(key) && previousKeyboardState.IsKeyUp(key))
        RaiseEventByName(key.ToString() + "Pressed");

```
> 2 votes

# Answer
So I have been thinking about this a lot, and as this question is quite old, I decided to help future generations, even though XNA is discontinued it may be useful with other programming languages. The InputHelper that I wanted to design would be able to handle additions and modifications easily, therefore I don't want to program that the W key specifically is pressed, instead I'd like to state that the 'Forward' key has been pressed, or perhaps a list of keys. The way I wanted to accomplish this is having a class KeyBind. This class holds names (for internal use and for KeyBind modifications the player can relate to), a list of keys and certain events. The structure would be as follows:

```
class KeyHelper {
    public string Name;
    public string GraphicalName;
    public ICollection<Keys> Keys;

    public event EventHandler keyPressed;
    public event EventHandler keyReleased;

    public KeyHelper(string Name, string GraphicalName, ICollection<Keys> Keys)
    {
        this.Name = Name;
        this.GraphicalName = GraphicalName;
        this.Keys = Keys;
    }

    public void OnKeyPress(EventArgs e)
    {
        keyPressed(this, e);
    }

    public void OnKeyRelease(EventArgs e)
    {
        keyReleased(this, e);
    }
}

```

This way, you can just iterate over every keybind in the InputHelper, check if the key has been pressed for this keybind and fire the according event. I'm sure you can figure the details out though, as I just programmed this in the editor for this site.

Anyway, I have to be in the same line with MrCranky, because you want to check for held keys manually, by polling. Unless of course you state that, when you want the Held Key fire every 100 milliseconds. Then it can be done.
> 0 votes

---
Tags: xna, c#, input, events, keyboard
---


# Question
Title: How can I provide access cheat codes or diagnostics for a tap-only mobile game?
I'd like to build several cheat-like commands into my game, mainly for debugging problems that could only be reproduced on the end-user's side.

For most games this would be trivial: just listen to a keyboard shortcut or two, but my game is a 'tap-only' mobile game. How can I go about providing access to these sorts of diagnostic commands with such a limited user interface in a way that will remain accessible to end-users but that they'd be unlikely to trigger automatically?

# Answer
In the latest version of Android (4.3 and above), to access the developer options, you had to click the build number in the settings menu multiple times.

You could do something similar with a UI element that would normally be there and have a click counter to enable a "cheat" mode. Once in this mode, you could use more standard UI elements to expose cheat functionality.
> 4 votes

# Answer
Usually, cheat codes are like easter eggs. They are usually enabled when the user performs a series of unusual actions in a situation where the UI doesn't seem to expect *any* action from them. The typical examples from the console-area of games are:

* start screen
* loading screen
* when the game is paused

It is important to choose a situation where the user has no reason to perform any input, because otherwise they might enable the cheat-code by accident. In the context of a game where the only input is a touchscreen, you could have input elements which don't look like input elements (like decorative graphics or text labels) and have the user perform unusual actions on them (draw specific shapes, tab them in a specific order, etc.). You could also combine this with other input methods your game doesn't utilize in other ways. When your game runs on mobile phones equipped with accelerometers, and your game doesn't use them as an input method otherwise, you could for example enable a cheatcode by shaking the phone while holding a button (which doesn't look like a button).
> 2 votes

---
Tags: mobile, user-experience
---


# Question
Title: How can i Randomize Unique Numbers in Java
So i'm making a game where i have to randomize 52 numbers from 1 to 52 so the order has to change i use this

```
    class Deck
{
    Random r = new Random();
    int[] Card = new int[52];
}

```

# Answer
you fill in the array from 1 to 52

```
for(int i=0;i<52;i++)Card[i]=i+1;

```

and then you shuffle it:

```
for(int i=1;i<52;i++){
    int randIndex = r.nextInt(i+1);
    int tmp = Card[i];
    Card[i] = Card[randIndex];
    Card[randIndex]=tmp;
}

```
> 0 votes

# Answer
Since you are building and shuffling a deck of cards I will point you to the java 1.5 Enum tutorial. It uses `enum`s to build up a Collection of cards and then uses `Collections.shuffle()` to randomize the deck.

```
public class Card {
    public enum Rank { DEUCE, THREE, FOUR, FIVE, SIX,
        SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE }

    public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }

    private final Rank rank;
    private final Suit suit;
    private Card(Rank rank, Suit suit) {
        this.rank = rank;
        this.suit = suit;
    }

    public Rank rank() { return rank; }
    public Suit suit() { return suit; }
    public String toString() { return rank + " of " + suit; }

    private static final List<Card> protoDeck = new ArrayList<Card>();

    // Initialize prototype deck
    static {
        for (Suit suit : Suit.values())
            for (Rank rank : Rank.values())
                protoDeck.add(new Card(rank, suit));
    }

    public static ArrayList<Card> newDeck() {
        return new ArrayList<Card>(protoDeck); // Return copy of prototype deck
    }
}

```

This builds your deck. The following then shuffles with `Collections.shuffle()` and deals some cards.

```
public class Deal {
    public static void main(String args[]) {
        int numHands = Integer.parseInt(args[0]);
        int cardsPerHand = Integer.parseInt(args[1]);
        List<Card> deck  = Card.newDeck();
        Collections.shuffle(deck);
        for (int i=0; i < numHands; i++)
            System.out.println(deal(deck, cardsPerHand));
    }

    public static ArrayList<Card> deal(List<Card> deck, int n) {
         int deckSize = deck.size();
         List<Card> handView = deck.subList(deckSize-n, deckSize);
         ArrayList<Card> hand = new ArrayList<Card>(handView);
         handView.clear();
         return hand;
     }
}

```
> 0 votes

---
Tags: java, random
---


# Question
Title: How can I make different levels in a game?
Let's say I was working on a platform game. Each level has an exit. When the player reaches the exit, the game switches to the next level.

What would be the best way represent and switch to the next level?

One idea I had is to make a `Level` class. This class handles most of the game logic and has most of the program's code, but doesn't paint anything on the screen.

For each level, I create a class that extends (inherits) `Level` class. All of these classes would inherit everything from `Level`, but paint different things on the screen. When the player finishes a level, `finishedLevel()` method is activated inside class `Main`, and this class creates an instance of the next level.

Is this approach reasonable, or is there a better one?

# Answer
> 7 votes
Most games don't have a separate class for each level. The usual way is to store the layout of each level in a file. These map files contain the environment and the positions and properties of all objects in it.

When a level starts, the map file is loaded and a Level object is initialized with the data from that file.

When the player finishes the level, the Level object is discarded and a new one is initialized with the data from the file for the next level.

By storing the level-data in files, you are separating content from programming, which is usually a good thing from the maintainance perspective. You can use an external map editor to edit your maps (when you use a tile-based 2d engine, I can recommend Tiled as a map editor) and you can do so without having to recompile your game. This doesn't just makes it easier for yourself, it also allows you to work together with level designers who have no programming knowledge. They just need to know how to use your level editor and don't have to bother with your programming language and development tools.

# Answer
> 2 votes
Your approach is workable, but suffers from the problem of overusing inheritance. If all your `Level` classes share everything but their method that paints the actual level data on the screen, then perhaps there is a way you can have them share even *that*?

The solution is to store the description of what should be painted for a particular level in an external data source. Often, this is a file. The contents of this file can be as simple or as complex as you need to represent the entities in your level. For example, many games can get a way with a simple text file representing background or foreground tiles of the level with numbers or characters, such as

```
      ____X
      L
S_____L___E

```

where spaces represent empty space, `_` represents a floor, `S` the start position of the player, `E` the start position of an enemy, `L` a ladder and `X` the level exit.

This gives you enough information to load the level and understand what graphics to render where, where to place mobile game objects or collision information, and so on.

It also has the advantages of reducing the amount of code you have to maintain (now you have just a single level class) and driving your game more with data than with code (data is generally easier to change quickly and iterate upon).

---
Tags: software-engineering, game-mechanics, platformer, levels
---


title: Clamp the scroll wheel value

text:
# Question
Title: Clamp the scroll wheel value
I'm having something like an inventory bar at the bottom of the screen. However, when the highlight square (indicates what object you are going to place) reaches the end. The value of the scroll wheel will keep going up if you keep on scrolling up. So if scroll up a lot, you'll have to scroll a lot back down to change the highlight square position and vice versa for the first square. I would have thought that this would prevent this problem:

```
highlightPos.X = MathHelper.Clamp(currentMouseState.ScrollWheelValue, 0, 480);

```

As you can see I want to basically clamp the scroll wheel value between 0 and 480 but this doesn't seem to work, this is my first time using the scroll wheel so I'm not too knowledgeable on it's in's & out's.

# Answer
As the documentation for the `MouseState.ScrollWheelValue` notes, you should not use `MouseState.ScrollWheelValue` directly, as it is an accumulated value and most likely will never have the value you expect to.

You will need to store this value every frame and compare with the value from the previous frame to obtain a "DeltaScrollWheelValue", which only then you can use in your code.

I suggest you work with this delta just as you would with the delta time you receive in your `Update()` functions.

This is an example to obtain this delta:

```
// Declare these outside the Update() function
int deltaScrollWheelValue = 0;
int currentScrollWheelValue = 0;

public void Update(GameTime gameTime)
{
    deltaScrollWheelValue = currentMouseState.ScrollWheelValue - currentScrollWheelValue;
    currentScrollWheelValue += deltaScrollWheelValue;

    // Here you can use deltaScrollWheelValue for your code
}

```

You can also use the answer in this question and its code as a reference.
> 2 votes

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


# Question
Title: How can I make a player-interactable bookshelf?
In the player's house `Interiors->WhiterunBrezeehouse` (`FormID 000165A8`) I duplicated a bookshelf (`CommonShelf03 FormID 000ce784` near the fire pit) and the book proxies, container, triggers, collision boxes, et cetera.

When I enter the house the duplicated book shelve is there and it shows the `"E to interact"` text, but when I press `E` nothing happens (I'm supposed to get up the book shelf manager).

Any clue of what it might be? What do I need to support proper interaction between a player and the shelf?

# Answer
Copying and pasting the bookshelves tends to be problematic; the resuling objects, as you have noticed, tend to not function properly. Instead, I'd recommend creating one from scratch.

Creating an interactive bookshelf from scratch involves:

* Placing the actual bookshelf object.
* Placing some `DefaultBook` objects on the shelf.
* Create a `PlayerBookshelfContainer`.
* Create `PlayerBookshelfClickTrigger` trigger with the bookshelf object (the in-game one) selected. Resize the trigger volume to cover the surface of the shelf you are making intractable (this trigger is the thing a player will actually interact with in-game).
* Create `PlayerBookshelfTrigger` trigger (with the bookshelf selected again). Resize this trigger to fill the volume of the shelf and enclose the books, more or less.
* Using the Link References tab available by double-clicking the bookshelf container, add reference links to each book you placed above. Use `BookshelfN` (where *N* is 1 to 18) as the keyword for each link.
* Similarly, link the click trigger to the container object. The keyword is `BookshelfContainer`. In the primitive tab, make sure the trigger supports player activation.
* Link the other trigger to the container; you don't need a keyword for this reference. Ensure, in the primitive tab, the trigger type is `L_TRIGGER`.
* Finally, link the *container* back to the trigger above (not the click one, the regular one). Use `BookshelfTrigger01` as the keyword.

That should cover the basics. For extra credit, you probably want to set up collision barriers between the placed books so they don't move around, and hide the actual container object outside the world slightly. You have to repeat this for each shelf. It's a bit tedious.

If you really want to try to debug the cloned bookshelves you've created, I'd go through the above steps with them and make sure all the links are in place, and that your click trigger volume is accessible, and so on.
> 3 votes

---
Tags: assets, modding, skyrim-modding
---


# Question
Title: How to obtain "gravity" and "initial impulse" given "desired time to reach max height" and "desired max height"?
I'm developing a 2d fighting game, using time steps based on frames ie, each call to Update() of the game represents a frame so, no variable time at all.

My jump physics code doesn't need to consider delta time, since each Update() corresponds exactly to the next frame step. Here how it looks:

```
double gravity = 0.78;
double initialImpulse = -17.5;

Vector2 actualPosition;
double actualVerticalVelocity;

InitializeJump() {
    actualVerticalVelocity = initialImpulse;
}

Update() {
    actualPosition.Y += actualVerticalVelocity;

    actualVerticalVelocity += gravity;
}

```

It works great and results in a smooth arc. However, it's hard to determine the values for "gravity" and "initialImpulse" that will generate the jump that I want.

Do you know if it's possible to calculate the "gravity" and "initialImpulse", if the only known variable is the "desired time to reach max height" (in frames) and "desired max height"?

This question should lead to the answer I'm looking for, but its current answer does not fit my needs.

**UPDATE:**

As @MickLH figured me out, I was using an inefficient Euler integration. Here is the correct Update() code:

```
Update() {
    actualVerticalVelocity += gravity / 2;

    actualPosition.Y += actualVerticalVelocity;

    actualVerticalVelocity += gravity / 2;
}

```

Only the very first step of the Update() will change and will move the object by initialVelocity plus the half of the gravity, instead of the full gravity. Each step after the first will add the full gravity to the current velocity.

# Answer
> 8 votes
**Short answer:**

```
gravity = -2*desiredMaxHeight/(desiredTimeInTicks*desiredTimeInTicks)
impulse = 2*desiredMaxHeight/desiredTimeInTicks

```

---

**Long answer:** *(pre-calculus required)*

Define your jump function which is a simple integral over time:

* yielding:

Now to find the peak of this function we solve for where the derivative equals zero:

* simplified:

We have built a system of equations which:

1. represent the relationship of ***t*** (time), ***h*** (height), impulse, and gravity
2. constrain the height to its global maxima

The solution to this system yields the the variables you are interested in:

# Answer
> 1 votes
Like the work you've already done to get your character jumping and falling, you can derive `gravity` and `initialImpulse` using basic physics equations and algebra. First, the equations:

```
y1 = y0 + initialImpulse * t1 + 1/2 * gravity * t1 * t1
v1 = initialImpulse + gravity * t1

```

We'll try to find initialImpulse and `gravity` based on what we know. What we know is:

* y0 is 0, since the character hasn't left the ground at time 0
* y1 is your desired jump height, which I'll call 'h'
* v1 is 0, since the character has to stop moving up when they reach height h
* t1 is your desired jump-up time, which I'll call 't'

Plug these known values into the equations:

```
1. h = 0 + initialImpulse * t + 1/2 * gravity * t * t
2. 0 = initialImpulse + gravity * t

```

Solve equation 2 for `initialImpulse`:

```
3. initialImpulse = -gravity * t

```

...then replace `initialImpulse` in 1 with the right-hand side of 3:

```
4. h = -gravity * t * t + 1/2 * gravity * t * t

```

Solve for `gravity`:

```
5. h = -1/2 * gravity * t * t
6. gravity = -2 * h / (t * t)

```

That's one part down. Find the value of `initialImpulse` by replacing `gravity` in 3 with the right-hand side from 6:

```
7. initialImpulse = -(-2 * h / (t * t)) * t
8. initialImpulse = 2 * h / t

```

Side note: Check out the right-hand side at the end there, because it's useful in more than just this situation. It shows that the average velocity you wanted (to move upward to height 'h' over time 't') is half of the starting velocity. The general rule would be that a character who changes velocity linearly from `v0` to `v1` over time `t` will move at an average velocity of `(v0 + v1) / 2` and travel `t * (v0 + v1) / 2`.

With that in your pocket, you could solve this same problem a little bit more concisely:

```
average_speed = initialImpulse / 2 = h / t
initialImpulse = 2 * h / t

gravity * t + initialImpulse = 0
gravity = -initialImpulse / t
gravity = -2 * h / (t * t)

```

---
Tags: physics, projectile-physics, jumping
---


# Question
Title: How to prevent a sprite to move in an angle that will lead to collision
I have two sprites that can move in any angle. The sprites are rectangular.

I created bounding boxes for both the sprites. These boxes rotate whenever the sprite rotates. They always surround the sprite and only the sprite. (Exact fit).

I have succesfully implemented collision detection for the two bounding boxes. I did this by checking wether box1 contains any of the vertices of the box2, and the opposite. (I know this way is not perfect, since *it is* possible for two rectangles to intersect without having each other's vertices inside themselves, but for my needs it's good enough). So now I know when the two sprites collide.

But I have a problem with reacting when the two sprites collide.

When these sprites collide, I want to prevent them from overlapping each other (any more than a few pixels). In other words, upon collision, I want to allow the sprite to move only in a direction where it won't go deeper into the other sprite.

As I said, each sprite can move freely in any angle (the game is for two players, each controls a sprite).

EDIT: To word it differently - **Upon collision of two sprites, I need to find out the range of angles a sprite can move, that will allow it to to move out of the collision** \- this is so I can prevent the user from moving the sprite in any other angle, upon collision.

How can I do that? Thank you for your help

# Answer
> 1 votes
Finally found a solution!

This solution isn't perfect, sometimes sprites get a little stuck. But it doesn't involve all the math stuff that people like me struggle with. I'm sharing this because maybe it will help someone.

Everytime I move a sprite, I save it's previous location in a variable. If the sprites collide, I reset it's location to the location it had before the collision. This will take the sprite only a small number of pixels back, so the 'bouncing back' won't be noticable. It will prevent the sprite from overlapping the other sprite.

Thanks for those who tried to help :)

---
Tags: sprites, movement, collision-resolution, collision-avoidance
---


# Question
Title: Efficient per-frame constants in shaders
I have some variables that stay the same during the entire frame and will be used by a large number of the various shaders I use (several dozens). These include things such as the various transforms of the camera, light source data, etc.

The main options to provide this data to all the shaders (at least that I can think of) are:

* Just give each shader uniforms for the data and set all uniforms manually when they're required
* Use buffers, such as
    + Uniform Buffer Objects
    + Shader Storage Buffer Objects
    + Buffer Textures

Which of these options is generally the most performance efficient, and why?

# Answer
> 8 votes
Uniform buffer objects (the GL equivalent of D3D constant buffers) are designed just for such things and will probably give you the best results.

First of all, you will have lower CPU overhead by filling a buffer yourself and uploading it to the GPU all at once, than by setting each uniform with its own individual GL call (which also makes the driver do some work to track changed uniforms and upload them when needed, etc).

Moreover, UBOs can be shared across multiple shaders if desired, and only need to be filled out and uploaded once, rather than per-shader.

As for the various types of buffers, GPUs and their drivers often have optimizations for UBOs that don't apply to buffer textures or SSBOs. For example, when executing a warp/wavefront, when you read a value from a UBO, the read could be issued just once and the result broadcast to all threads; but reading from a buffer texture or SSBO might issue a read for each thread, which would be less efficient. Also, GPUs often have a special memory cache dedicated just to uniforms, while reading from a buffer texture or SSBO would go through the texture cache and potentially conflict with other texture accesses also done by the shader.

# Answer
> 1 votes
Given that nothing has the absolute performance superiority. But rather each one was designed to give you a convenience (read:performance but not absolutely) in certain operations.

**Buffer textures** are used to store larger data buffers (like huge matrices) and be accessed directly by shaders, without the filtering and image specific operations that are used on regular textures.

While, the biggest difference between a **uniform block** and a **shader storage block** is that your shader can write into the shader storage block, so if you are not going to write on them use a Uniform Buffer Objects ( so in your case you should use them ).

I think of the difference as a semantic one, so I would say use each one for it's original purpose.

---
Tags: opengl
---


# Question
Title: libgdx game process dies on loading texture atlases
I try to load a lot of texture atlases (10) with approximately 5 (~2048x~2048)(not using PoT) .pngs each. I'm using AssetManager and there is no trouble with it on my pc but when I try it on my tablet the app just dies without any error messages or crash reports and there aren't any outOfMemoryExceptions.

Here's my log:

DropBox link

the max memory: 67 is

```
Runtime().getRuntime().maxMemory() / 1000000

```

I'm running out of ideas of what to do. Maybe I don't fully understand the way mobile games work: is that a lot of atlases (I have other textures not atlases apart from these atlases)? because everything looks quite fine in the memory segment as much as I know. Anyway I'm open to suggestions and maybe some tips. And I'd really like to keep these atlases in my game.

EDIT: the game loads on my tablet but not phone when I use 1 png per atlas (8192x8192) but my tablet doesn't show images larger than 2048x2048 for some reason oh and the images in the atlas aren't even 1024x1024 so idk why it doesn't show them must be because the atlas is 8192x8192.

EDIT #2: I load only atlases now, no separate .png files and I am now using PoT (2048x2048). 17 atlases some have 2 pngs some even have 1 png but there are some that have 5+ and that's my level plus player animations plus I'm using a gradient for my whole level that is ~10000px in width combined and I use FBO to do a Lighten shader on the level and my level has animations. Is that too much? Anyway this time the game died @ 94% on my phone(Galaxy S2) and @ 58% on my tablet(Lenovo IdeaTab A2109) and here's my new log but this time from my phone:

DropBox link log\_new

I'm confused because there aren't any outOfMemory exceptions and I'm disposing every possible thing there is to dispose. btw my app in the logs is com.comraz.slashem Is theree something I can do? f.e. downscale textures or use mipmaps or something? my level textures are 1024x768 when zoomed in and 1024x1536 when zoomed out. If you have any ideas or any questions please do ask or tell me. Oh and my camera size is 1280x768

# Answer
The amount of memory required for your 17 textures at 2048x2048 using 32-bit color is:

```
17 * 2048 * 2048 * 4 = ~272MB

```

It's not too excessive, but that is just for graphics and it does not account for memory used by other assets (audio, etc), background tasks, OS usage, etc.

You may need to **load** the bitmap using a lower color depth to conserve memory. It's a trade off between quality and resource usage, and is very important on mobile devices with lower memory.

If you are using glTexImage2D() for loading, specify a lower bpp value using the `internalFormat` argument - set it to some value like `GL_RGB5` (for 16bit color, which will only use half the amount of space). This will degrade your graphics but might help on devices with lower memory.

Another option is to lower the resolution of your textures.
> 0 votes

---
Tags: java, android, libgdx, opengl-es, opengl-es2
---


title: Bullet physics in python and pygame

text:
# Question
Title: Bullet physics in python and pygame
I am programming a 2D sidescroller in python and pygame and am having trouble making a bullet go farther than just farther than the player. The bullet travels straight to the ground after i fire it. How, in python code using pygame do I make the bullet go farther. If you need code, here is the method that handles the bullet firing:

```
    self.xv += math.sin(math.radians(self.angle)) * self.attrs['speed']
    self.yv += math.cos(math.radians(self.angle)) * self.attrs['speed']
    self.rect.left += self.xv
    self.rect.top += self.yv

```

# Answer
> 1 votes
It's unclear what happens to the bullet.

Does it have the same speed as the player? In that case, obviously the bullet should have a greater speed.

Does it disappears just after it appeared? Maybe you misplaced it and collided with the player.

# Answer
> 0 votes
There is a 2D physics engine that integrates nicely with PyGame. It is called PyMunk and uses the Chipmunk 2D physics engine. You might want to use it if you do something more with physics in your games.

---
Tags: 2d, python, pygame, bullet-physics, side-scroller
---


# Question
Title: How do we apply different textures to different faces generated via geometry shader?
I am trying to render a cube by starting of with one vertex into the shader, then geometry shader to expand into a cube, and then apply a different texture to each side. **The part I am facing the issue with applying unique textures to each side.**

So I am currently doing this by creating it via quads pushing the vertices, and applying the textures one by one. In fact, I drawIndexed() a set of vertices, then switch over to a different textures every 6 vertices. But pushing in so many vertices is expensive for higher FPS. So, I looked in to Geometry shader and it seems like it did the job. After studying it, I understand how to develop the vertices in the geometry shader. However, I don't know how to apply a different texture say every 6 vertices - since we are in the pipeline already.

# Answer
The bound textures in a single draw call cannot be changed. This means that your geometry shader cannot select arbitrarily between different textures.

The solution is to use either *texture atlasing* or *array textures*. In either case, for each cube face you generate both new positions and new texture coordinates.

The C++ code must still bind the correct atlas or array that covers the needs of all faces of a cube. Games like Minecraft need only a single atlas for all cubes; they could also have used an array if they targetted newer versions of GL.

In either case, your geometry shader needs to sample some information from the vertex attributes that indicates which 6 slices of the atlas/array are used for each face. It then uses that information to set the proper texture coordinates.
> 4 votes

---
Tags: directx, shaders, geometry-shader
---