title: Collision detection logic

text:
# Question
Title: Collision detection logic
**Edit 2**

In the following picture sprite1 (the red square) is hitting the platform from the left, so:

```
 sprite1_rightEdge>platformSprite leftEdge

```

would be true, so I can simply reposition sprite1 to align it with the left edge of the platform. So....

```
sprite1X=platformSpriteX-platformSpriteWidth

```

This is fine, however, lets say that sprite1 hits from the *right*, the problem I have here is that the first condition (above) is still true. So....

```
sprite1_rightEdge>platformSprite leftEdge

```

So my sprite1 still gets positioned at the left edge of the platform......

The same also happens in reverse....

**Using velocity**

I've had some success with velocity, but again I'm not clear on how this works properly.

For example, if I say something like:

```
if (Sprite1 moving right at time of collision)

```

Then I can assume it's hit the platform from the left. This works, but what if the sprite is 'falling' from the top and lands on the platform while *also* moving right? It will again get re-positioned at the left edge of the platform.

**partial sucess**

So far, I managed to get this working (although not fully implemented yet), by saving the old position of Sprite1, repositioning it and checking the old position, so if the old position was to the left of the platform, then I can assume it came in from the left.

If someone could let me know the best way to proceed it would be much appreciated.

Just to clarify what I'm asking - I have 2 objects - 1 is a platform and the other is the main character, I wish to make the player stop regardless of which side he hits the platform (from the top, bottom, left or right) - I will definitely be moving at distances of more than 1 px at a time).

I've attempted using velocity but this doesn't seem to work correctly as well as double checking x/y positions once a collision has happened but again I get some very off results. Some pseudo code of how to detect which side a sprite has hit would be much appreciated :-)

I have researched this and have seen pretty much every Q&A on this site regarding this subject (as far as I know) but the answers are either not relevant to my particular query or I simply don't understand them.

**Original question**

I understand the basic principles of collision detection for squares / rectangles

i.e.,

**(Pseudo code)**

```
public boolean testCollision(){

if (bottom of sprite1<top of sprite2)
return false;

if(top of sprite1>bottom of sprite2)
return false;

if(left edge of sprite1 > right edge of sprite2)
return false;

if(right edge of sprite1 < left edge of sprite2)
return false;

return true;
}

```

I also know that I can stop my sprite going off the edge of the screen like so:

```
if(spriteX<0){spriteX=0};

```

However using something akin to the first method above for detecting collision between 2 specific objects, how can I make my 1st sprite actually stop so he can't pass through it?

At the moment, although I can detect when the two are touching, I'm unsure how to make it so that they can't actually pass through each other.

A push in the right direction would be a great help - thanks!

# Answer
Demonstration:

Crude but functional collision detection and response

Video: https://vimeo.com/64923588

The idea is that the player controlled sprite (actually a 32x32 pixels red box) can raise the speed of its next move, but it cannot go back to original speed except if it collide with something. Also if speed is enough the green wall can be "damaged" until it finally is destroyed. Gravity can be disabled. This situation shows AABB in action.

In the video, the red text shows some game variables, penx y peny are the lengths of penetration vectors into each axis (of the player sprite into other objects).

T.x and T.y are the coordinates of the 2d vector that go from the center of a box to the one again it is tested. If you go for AABB as I recommend, you will need T.

The formula used for T is:

```
T = PlatformAABB.position - PlayerAABB.position

```

Vector from Platform to Player.

If you do not want to use an structure/class to represent vectors, then another option is to use separate variables for x and y elements:

```
Tx = platform.x - player.x
Ty = platform.y - player.y

```

Note that the position of each AABB is measured from its center, not from top, left corner. So if you are positioning your sprites like me, using left and top to mean the upper left corner of the rectangle containing the sprite, then you may need to calculate the AABB center like this: PlayerAABB.position.x = player.left + player.width / 2. And the same for y but replacing left for top and width for height.

```
Tx = (platform.left + platform.width / 2) - (player.left + player.width / 2)
Ty = (platform.top + platform.height / 2) - (player.top + player.height / 2)

```

If your x and y coordinates are taken from the center of each sprite then don't worry simply apply the first formula.

To detect if boxes overlap

```
if (absolute(T.x) > (currentSpr.width / 2) + (otherSpr.width / 2)) stop here;
if (absolute(T.y) > (currentSpr.height / 2) + (otherSpr.height / 2)) stop here;

```

Is enough to know that T is greater in one axis than the sum of the length of the two relevant half extents of each involved box to know that there is no overlapping. Then you can stop and assume no collision.

Logic to detect collision finalizes here for most games. If your objects are moving really fast, more than its width or height in a single game tick, then you will need a more complex method, like divide the movement in small steps (less than the box dimensions) and then do the collision check. Remember the previous position is useful for this.

What to do when colliding?

For the case of Player Sprite vs Platform. Assuming Platforms never move, whatever impacts them.

If collision is positive, then you will have to find penetration vector to move the player sprite back. We are using AABB to make that task simple. You want the sprite to remain in touch with the platform, not to go back to its previous position, that may be far away.

We already calculated T, and used it to find overlapping, now we will use it again:

Formula for penetration vectors lengths. (We don't know direction yet).

```
penx = (currentSpr.width / 2) + (otherSpr.width / 2) - absolute(T.x);
peny = (currentSpr.height / 2) + (otherSpr.height / 2) - absolute(T.y);

```

Now, we choose the lesser of them to displace the sprite back. If you want to understand why the lesser, do the opposite, run your program and have some fun watching the result.

And we need a direction too, we know that we are always axis aligned but we still have 2 choices, left or right, up or down.

```
if (peny <= penx)
{
    if (T[1] < 0) spr1.top += peny;
    else
    if (T[1] > 0) spr1.top -= peny;
} else
{
    if (T[0] < 0) spr1.left += penx;
    else
    if (T[0] > 0) spr1.left -= penx;
}

```

(formula edited to make it more readable)

I have to do some extra calculations because of the left, top, system. I hope this does not make it to look more complicated than it really is.

What to do when colliding to another thing than a platform?

Be creative. You can divide the penetration vector by 2 and displace both sprites but in opposite directions. Or simply destroy the player. Or think in something more complex. Articles for "friction" in games exists.

Notes:

To return absolute values in C++ use fabs() function. In javascript use Math.abs(). Other languages have their owns.

I think that you don't need a vector library for this, as only basic operations were used.

Depending how you iterate through objects in your scene, the player sprite will not always be at the left (currentSpr in the examples) and the platforms may not always be at the right (otherSpr) in the calculations, beware of not applying the penetration vector to a platform by mistake.

Original answer:

Save the previous position of the sprite before move to the next position is what I'm doing for my game and I see no shame on that. I like the solution.

Now that you have previous position and current position, the vector giving you the direction of movement when colliding with other non movable objects (platforms, walls) has its tail in current position, and its head in previous position.

The question that remains to be answered is how much the colliding object should retreat. You don't want it to move back to previous position in all cases, specially when the speed of a given movement is too high. You probably want the object to remain in contact to the platform without trespassing its borders.

The SAT (Separating Axis Theorem) is what I would use in this case:

1 - Find penetration vector using SAT

2 - Move the penetrating sprite back by apply the penetration vector

Please, see this: http://www.metanetsoftware.com/technique/tutorialA.html

For this specific problem read sections, 0, 1 and 2.

Separating Axis Theorem for AABBs is what you need for this specific case.

Note the case where two character sprites collide is another story. You can use SAT too for detect penetration vector, but you probably want some kind of physics acting in both sprites, and alter the position of both. Depending on the game, maybe destroy the player sprite is enough, in this case no penetration vector needed.
> 3 votes

# Answer
Here's a different algorithm; instead of stepping the player forward and moving him back if he's colliding, check where the *next* collision will occur:

1. Get the position of a corner of the object.
2. Shoot a line down (or up, or to the right/left, depending on your movement direction) from that position.
3. Figure out the first place that line intersects a platform.
4. Get the distance from that place to the corner.
5. Repeat for the other corner of the object you need to check.
6. Move the player down the minimum of his current movespeed and both of those distances.

So, if the player's moving in an X direction, such as right, you need to take the top right and bottom right corners (left; top left and bottom left corners, respectively). For a Y direction, such as down, you take the bottom left and bottom right corners (and similarly for the up direction).

Basic code for detecting collisions below the character:

```
float botLeftDist = GetDistToNearestPlatform(botLeftCorner);
float botRightDist = GetDistToNearestPlatform(botRightCorner);
float minDist = min(botLeftDist,botRightDist);
sprite.move(min(moveSpeed.x, minDist), 0.0);

```

Do this for all four directions, every frame. For example, checking for a collision on the right side of the player object would be the same, except replace `botLeft` with `topRight`.

There's three basic cases:

1. If you're high in the air, it'll just move the character down depending on his movespeed, because moveSpeed \< nearest platform position.
2. If you're about to hit the platform, it'll move the character down to the platform, and won't leave him in the air.
3. If you're touching the platform, it won't move the character at all, since the platform is 0 distance away.

Putting it all together, you get something like this:

```
float nearestY, nearestX;
if(movingUp)
    float nearestY = GetNearestUp();
else
    float nearestY = GetNearestDown();

if(movingLeft)
    float nearestX = GetNearestLeft();
else(movingRight)
    float nearestX = GetNearestRight();

sprite.move(min(moveSpeed.x, nearestX), min(moveSpeed.y, nearestY));

```

where `GetNearestDown()` contains the first three lines of the first three lines of the code above (the first portion in this post), and returns `minDist`. The other three functions are defined similarly.

**EDIT**: As for implementing `GetDistToNearestPlatform`, it depends on how you implement your scene. It could be as expensive as starting at the position you want, moving pixel-by-pixel and checking each platform to see if they contain that pixel. I implemented this algorithm in a tile-based system, so I moved down tile-by-tile until I found an occupied tile, then checked pixels within that tile until I found an occupied one.
> 1 votes

# Answer
So instead of checking their current position for collision. You can check where they will be.

IE: (very pseudo code)

```
newPos = currentPos + movement;
if(checkCollision(newPos,otherSpritePos) == FALSE) { currentPos = newPos; }
else { /*oh noes collision!*/ }

```

As for determining which side the object is colliding with:

```
difference = objectBCenter - objectACenter;
if(|difference.x| > |difference.y| && difference.x > 0) {left side}
if(|difference.x| > |difference.y| && difference.x < 0) {right side}
if(|difference.x| < |difference.y| && difference.y > 0) {top side}
if(|difference.x| < |difference.y| && difference.y < 0) {bottom side}

```

note this is all designed around boxes with relatively small movement steps. the || around the variables indicates absolute value.
> 0 votes

# Answer
If the player is touching the platform and the velocity is pushing it down, then move it back to it's last posistion.

Save the old position:

```
Position oldPosition = player.position;

```

Now do all your input checks here.

Then check for collision:

```
if (player.checkCollision(platform) == false && player.velocity < 0)
{
    player.velocity = 0;
    player.position = oldPosition;
}

```

Of course, replace the type **Position** in the example about with an object that stores the players and/or platforms location. Also when I mention velocity, I mean vertical velocity. And not to mention that when I put **player.velocity \< 0** generally that means the player is being pulled down. Good luck!
> 0 votes

# Answer
Building up on the discussion from @UnderscoreZero's answer... You can have something like this:

```
public float testCollision(){

if (bottom of sprite1<top of sprite2)
return <top of sprite2>;

if(top of sprite1>bottom of sprite2)
return <bottom of sprite2>;

if(left edge of sprite1 > right edge of sprite2)
return  <right edge of sprite2>;

if(right edge of sprite1 < left edge of sprite2)
return <left edge of sprite2>;

return 0; // or some value that cannot be attained by any return value and make sure you replace that value in the if condition below
}

newPos = currentPos + movement;
checkCollision = testCollision();
if(checkCollision != 0) { currentPos = checkCollision }
else { currentPos = newPos }

```

**EDIT**

> This is fine, however, lets say that sprite1 hits from the right, the problem I have here is that the first condition (above) is still true. So....
>
> sprite1\_rightEdge\>platformSprite leftEdge
>
> So my sprite1 still gets positioned at the left edge of the platform......
>
> The same also happens in reverse....

This is simple: Modify the collision check as follows:

```
if (top of sprite1<top of sprite2 && bottom of sprite1 > top of Sprite2)
return <top of sprite2>;

else if(top of sprite1<bottom of sprite2 && bottom of sprite1 > bottom of Sprite2)
return <bottom of sprite2>;

if(left edge of sprite1 < right edge of sprite2 && right edge of sprite1 > right edge of sprite2)
return  <right edge of sprite2>;

else if(left edge of sprite1 < left edge of sprite2 && right edge of sprite1 > left edge of sprite2)
return <left edge of sprite2>;

```

A word of caution here... These conditions only checks for collision in one dimension, if you are going to have collision detection in two dimensions, like your image you may want to break the tie b/w position based on the direction of motion or any other parameter you define and have to modify the return values and conditions appropriately.
> 0 votes

---
Tags: collision-detection, physics, sprites
---


# Question
Title: Mip Maps on 2D Sprite causing black line above. Why is this?
I am new to Unity. I'm trying it out and using Futile for a code-first approach, but still importing textures using the Unity system.

The problem I'm having is that when I use mip maps to scale large sprites down to smaller sizes without jagged edges, I'm getting a black line artefact above said sprites.

A little hard to see, but they're there. If I turn down the resolution, you can clearly see them:

These are my texture settings:

My question is, why are these black lines here? Is it a mistake I've made? Is it just a common side effect? How can I reduce these? Also, if this is the wrong approach, how can I use smooth sprites in a game with the ability for them to scale up smoothly?

Thanks!

# Answer
> 10 votes
There are many reasons why you may be getting those lines. I wrote a more detailed answer in here, but the bottom line is:

> Do not do atlasing and mipmapping at the same time.

For 2D, in general, you don't want/need to do mipmapping. That's useful mostly in 3D where you don't know the size at which your textures will be rendered, but that's usually uncommon in 2D.

If you definitely have a texture that you will aggressively downscale, then don't include it in an atlas.

And I'd also recommend you turn anisotropy off. That's meant to give you better results when you're looking at big textures from extremely sharp angles, which simply doesn't happen if your game is 2D.

---
Tags: unity, textures, sprites, mipmaps
---


title: LibGDX Cross Platform Networking

text:
# Question
Title: LibGDX Cross Platform Networking
**Backstory:**
I've been developing a game with LibGDX for the past two years, and I've seen it refactored more times than I remember.

I jumped on the iOS iKVM port as soon as it was released. But I've been struggling with it ever since in regards to cross platform networking. Kryonet will not port over to iOS unfortunately. So it's either I ditch Kryonet, or lose a large chunk of my target audience (iOS Users)

**My question for you is:**
I noticed LibGDX has cross platform classes ready for sockets and HTTP Requests, but no documentation exists for these sockets at all.

Has anyone used these sockets at all in the past, and does anyone know how they work?

# Answer
> 2 votes
There is a bit of documentation on the `Net` package that gives a very brief overview: http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/Net.html The `Net.HttpRequest` doc covers the http setup in a bit more detail.

The http API is based on callbacks to listeners that handle results or failures. The raw Socket API provides stream-oriented access to connection data.

---
Tags: java, networking, libgdx, cross-platform
---


# Question
Title: How to flatten out terrain and make better caves with Perlin noise
I'm currently using Perlin noise to generate a terrain. This is my actual attempt to create caves. I do get some sort of cave structures but they are small and are always close to the edges of the terrain. Also my terrain looks very irregular I'd like to have a more flat terrain. I've been playing with the values I pass to the Perlin noise function but I can't seem to get something good.

Do you have any pointers or suggestions to my actual approach in order to get something more regular within the Minecraft standards?

# Answer
> 10 votes
Terrain generation falls under *the form* part of development. It's an artistic endeavor, so I'm not so sure there's a *correct* answer. However, I can try to tell you about the knobs you can turn to get different results, and it'll be up to you to turn them to get the result you want.

* **Compress/expand:** You can stretch or shrink the noise along a specific axis to alter the features of your terrain. This would primarily be useful on the Y axis, but would also work when used on the X and Z together. For example, if you want flatter terrain, apply a factor of .2f to the Y input on your noise function. Or if you wanted wider valleys and hills, you could expand the X and Z axis to stretch the noise out over a larger area.
* **Mixing noise**: You can have multiple noise functions and combine them for interesting effects. For example, always choosing the maximum between your two noise values will give you more features (hills, peaks, etc.).

+ **Noise selector**: You can even use a third noise value as a selector to choose between two noise values. This is a good way of generating cliff faces and dramatic changes in landscape. I used this technique with some success in my game.
* **2D noise with 3D noise**: You can use a 2D height map to limit your 3D noise. This makes it far easier to control the surface of your world and vastly reduces weird features like floating islands.
* **Caves**: Likely the easiest way to generate caves is to make them in a later stage of generation and remove them from the existing terrain. There's a bunch of methods to use, and it totally depends on what kind of caves you want. You can use simple 3D noise with a very low cut off between solid/air. Or you can use noise like Perlin worms to generate special noise that works well for caves.

I suggest you set up your code in such a way that you can easily change values and generate a new map, preferably without rebuilding. You need to be able to quickly test changes in your values so you can start to find the input values that work with your algorithm to give you the results you want.

---
Tags: voxels, perlin-noise
---


title: Indoor 3D game worlds

text:
# Question
Title: Indoor 3D game worlds
I'm looking for a little direction.

I'm building a game engine as a part of my university project, and I'm having a little trouble about what to look for when it comes to indoor 3D game worlds.

Now I say indoor specifically because I have already set up an outside environment with heightmaps and skyboxes, so I'm roughly in the know with that.

What I'm struggling with is what I should be looking at to help me build an indoor level of my game, for instance on board a spaceship.

So my question is, how would I go about building an indoor world with walls, doorways, windows etc?

I'm using C++ OpenGL and SFML to build the engine, and the game levels in mind will be fairly big, so it would be appreciated if this was kept in mind whilst answering my question.

Any tutorials or guides will also be appreciated.

# Answer
> 3 votes
There haven't been many answers, so I'll just chip in what I can. **Disclaimer**: I really do not have much experience in 3D. This is from what little experience I do have.

I am fairly sure UDK and many other engines use, for indoor surfaces, static meshes. They block out levels using rough polygon geometry and use these to playtest in the beginning, but then have artists build meshes and substitute these for the geometry when it's time to start thinking about releasing.

However, I do know for a fact that nearly everything in Valve's Source Engine (TF2, Half-life 2) is polygon geometry. Stairs, buildings, most of the levels are just made of rectangles and the occasional wedge. To be honest, I'm not sure how exactly they're defined in the .bsp format, but I'd imagine it's fairly simple.

Even then, they do need some static meshes (represented, during collision, by axis-aligned bounding boxes) so they can represent things like trees, or fences, or other complex geometry. In addition, they have heightmaps (named displacements) to take care of terrains. Using these three tools (brushes, meshes & displacements), good level designers, and a hell of a lot of optimization tricks, Valve manages to make some pretty impressive maps. Here's an example (credit goes to visualwalkthroughs.com for the screenshot):

Nearly everything you see here is simple convex geometry (except for the robot, of course). The arch is made up of triangles approximating a curve.

What I'm trying to get at here is that there's no shame in using plain block geometry, just defined as coordinates & length/width/height. Basically, your hallways would just be made of four rectangular prisms - a floor, two walls, and a ceiling. Doorways would also basically be walls, except the wall would have to be made into three rectangles - two for the sides, one for the top of the doorway. Windows... well, you'd have to think about those yourself, because 3D lighting is beyond the scope of this post.

If I were starting out, I'd probably just go with that kind of static geometry at first, and then work on some sort of mesh loader later to pretty up the maps. Hope that helps.

---
Tags: c++, opengl, 3d, level-design, sfml
---


# Question
Title: Why are my game ticks longer than expected?
I was working on my game, adding stuff to it, when I noticed my ticks were in the low 50's when I had set it to do a constant 60. This is my run method.

```
public void run() {
    init();
    long lastTime = System.nanoTime();
    final double amountOfTicks = 60.0;
    double ns = 1000000000.0 / amountOfTicks;
    double delta = 0;
    int updates = 0;
    int frames = 0;
    long timer = System.currentTimeMillis();

    while (running){
        long now = System.nanoTime();
        delta += (now - lastTime) / ns;
        lastTime = now;
        if (delta >= 1) {
            gameUpdate();
            updates++;
            delta--;
        }

        try {
            Thread.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        gameRender();
        frames++;

        if (System.currentTimeMillis() - timer > 1000) {
            timer += 1000;
            frame.setTitle(title + "   |   " + "Frames Per Second: "
                    + frames);
            System.out.println(updates + " Ticks, " + frames + " Frames");
            updates = 0;
            frames = 0;
        }
    }
    stopGame();
}

```

I've tried removing all the code I added before this occurrence happened and it didn't help. Suggestions would be great!

# Answer
Delete the `Thread.sleep()` call (**assuming you're on a desktop machine and have power to spare**!).

In general you *never* sleep in your game loop (except on Android, where there appears to be no other choice). The bad thing about Thread.sleep is it is unpredictable and may cause your game to give up exec time for longer than 16ms, which is the *maximum* time a frame can take to complete a frame at 60 fps.

If there is too much time at the end of your loop, you usually can let the GPU VSYNC keep you at 60 FPS. If VSYNC is off, then **you *busy wait***, basically in the form of a loop like:

```
while( getTimeDeltaThisFrame() <= 16 ms )  ;  // keep "spinning" until
                                              // 16ms have passed.

```

Note that busy waiting on a portable device is going to burn a lot of battery, and you may have to allow a `sleep` call and step down to a lower frame rate there.
> 13 votes

# Answer
Make sure never to have the `Thread.sleep()`. It takes time for a render to complete... That's why the FPS is lower than expected.
> 1 votes

---
Tags: java, game-loop, frame-rate
---


# Question
Title: Issues upscaling pixel art with SampleState.PointClamp
I'm developing a 2D game, and I'm striving to create a nice blocky low-res appearance for the game, yet allow it to be played at variable resolutions. So, I've researched resolution independency and have a nice system in place to have my game rendered at 640x480 to a RenderTarget2D, and then have the RenderTarget blown up on the back buffer. Anybody that's looked into this knows that by default scaled images will be antialiased, and to disable that, change the SampleState to PointClamp. So, I've done that, but now I'm having this issue where my sprites aren't upscaling properly. Certain pixels are becoming particularly chunky where they shouldn't be, and I'm not sure what the cause of this behavior is, and I haven't been able to find any documentation of anybody else having this issue, can anybody offer any insight?

The last image illustrates the image rendered in game at 2X the original size. A 2:1 ratio should be a pretty straightforward scale to render, but if you look closely, there are some pixels that are at half size the others.

Edit #2: Here's some code regarding the scaling.

First, the game is captured by the render target at 640x480 resolution, then it is drawn at the back buffer's resolution (in the second image, reslution is 800x600, in the third image, resolution is 1280x960, I haven't messed with alternate aspect ratios yet).

```
graphicsDevice.SetRenderTarget(RenderTarget);
spriteBatch.Begin();
spriteBatch.Draw(Texture,
            new Rectangle((int)location.X, (int)location.Y, frameWidth, frameHeight),
            new Rectangle((int)spriteLocation.X, (int)spriteLocation.Y, spriteWidth, spriteHeight,
            Color.White,
            0f,
            Vector2.Zero,
            effect,
            .826f);
spriteBatch.End();
graphicsDevice.SetRenderTarget(null);
spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.PointClamp, null, null);
spriteBatch.Draw(RenderTarget, new Rectangle(0,0, backbufferWidth, backbufferHeight), Color.White);
spriteBatch.End();

```

Edit #3: Code involving the sprite's height and width. First, in the class that my monster inherits from, is this little method that runs in the base class' Update() method. It just makes sure that if I have animations with non-uniform sizes, that the sizes are updating properly.

```
protected void UpdateFrameSizes()
    {
        frameWidth = animations[currentAnimation].Frames[animations[currentAnimation].currentFrame].SizeAndsource.Width;
        frameHeight = animations[currentAnimation].Frames[animations[currentAnimation].currentFrame].SizeAndsource.Height;
    }

```

Then, just to make sure that the Width and Height were correct in his animation class, I checked those:

```
idleFrame1 = new AnimationFrame(Texture, new Rectangle(154 * 0, 107 * 0, 154, 107), 1f);
        idleFrame2 = new AnimationFrame(Texture, new Rectangle(154 * 1, 107 * 0, 154, 107), 1f);
        idleFrame3 = new AnimationFrame(Texture, new Rectangle(154 * 2, 107 * 0, 154, 107), 1f);

```

All looks correct here, I even went to the source image and counted the pixels (Yes, I know, his sprite sheet's dimensions are weird, but they're accurate).

And then this data is all used in Edit #2's code snippet during the draw method.

# Answer
You have to upscale in whole numbers to get the effect you are expecting.

You are scaling it by about 1.8 so dividing the second image by 0.55 would get you the pixel you are sampling. Below is approximately how the sampling is being handled in the example you provided.

```
1 = 0.55 = 1
2 = 1.1  = 1
3 = 1.65 = 2
4 = 2.2  = 2
5 = 2.75 = 3
6 = 3.3  = 3
7 = 3.85 = 4
8 = 4.4  = 4
9 = 4.95 = 5  <-- This is what is causing your artifact (It can work both ways causing a jump or repeating a pixel more often than is nommal)
10 = 5.5 = 6

```

Because you are not scaling by a while number you are going to sample inconsistently because the rounding is going to jump in a constant rotation dictated by the ration of the remainder.

In general sprites don't scale very well. If aesthetics are important to you you might want to draw all of the sizes a sprite can be.
> 3 votes

---
Tags: xna, 2d, xna-4.0, rendering, rendertargets
---


title: Model draws always on front

text:
# Question
Title: Model draws always on front
I have a couple of Models here, but there's only one, which will always draw in front of the others.

I tried to replace the asset-source to an other model and then the order is correct, but on this particular one, it won't render behind the other model like it should.

See the problem here (Problematic model is the dark mountain)

http://s1.postimg.org/d92ku9mvh/image.png

Why is that happening?

# Answer
> 1 votes
Make sure that the winding order is correct for this model. Try drawing the asset with an opposite winding.

# Answer
> 0 votes
I haven't wrote anything in XNA for a long time, but I think one of those XNA settings should solve your problem

```
 rs = new RasterizerState();
 rs.CullMode = CullMode.None;
 Device.RasterizerState=rs;

```

or

```
 Device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.AliceBlue, 1.0f,0);
 Device.DepthStencilState = DepthStencilState.Default;

```

# Answer
> 0 votes
Seeing as how it works correctly when using another model, have you check the file to make sure the vertices are in the correct place? Can you rotate the view around to see if the model is *physically* in-front of the models or if it's just rendering weirdly?

# Answer
> 0 votes
The problem was the Z-Axis.

The model had an immense length regarding the Z-Axis, so that it seemed "always not drawed in order"

So solution: Decrease length in Z-Axis

---
Tags: xna
---


# Question
Title: How to snap a 2D Quad to the mouse cursor using OpenGL 3.0?
I've been having issues trying to snap a 2D Quad to the mouse cursor position I'm able :

1.) To get values into posX, posY, posZ

2.) Translate with the values from those 3 variables

But the quad positioning I'm not able to do correctly in such a way that the 2D Quad is near the mouse cursor using those values from those 3 variables eg."posX, posY, posZ"

I need the mouse cursor in the center of the 2D Quad.

I'm hoping someone can help me achieve this.

I've tried searching around with no avail.

Heres the function that is ment to do the snapping but instead creates weird flicker or shows nothing at all only the 3d models show up :

```
void display()
{
  glClearColor(0.0,0.0,0.0,1.0);
  glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

  for(std::vector<GLuint>::iterator I = cube.begin(); I != cube.end(); ++I)
  {
      glCallList(*I);

       }

     if(DrawArea == true)
     {

    glReadPixels(winX, winY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);

cerr << winZ << endl;

glGetDoublev(GL_MODELVIEW_MATRIX, modelview);

glGetDoublev(GL_PROJECTION_MATRIX, projection);

glGetIntegerv(GL_VIEWPORT, viewport);

gluUnProject(winX, winY, winZ , modelview, projection, viewport, &posX, &posY, & posZ);

    glBindTexture(GL_TEXTURE_2D, DrawAreaTexture);

    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);

    glTexImage2D (GL_TEXTURE_2D, 0, GL_RGB, DrawAreaSurface->w, DrawAreaSurface->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, DrawAreaSurface->pixels);

    glEnable(GL_TEXTURE_2D);

    glBindTexture(GL_TEXTURE_2D, DrawAreaTexture);

glTranslatef(posX , posY, posZ);

     glBegin(GL_QUADS);

     glTexCoord2f (0.0, 0.0);
     glVertex3f(0.5, 0.5, 0);

     glTexCoord2f (1.0, 0.0);
     glVertex3f(0, 0.5, 0);

     glTexCoord2f (1.0, 1.0);
     glVertex3f(0, 0, 0);

     glTexCoord2f (0.0, 1.0);
     glVertex3f(0.5, 0, 0);

     glEnd();

        }

      SwapBuffers(hDC);
}

```

I'm using :

OpenGL 3.0 WIN32 API C++ GLSL

if you really want the full source here it is -\> http://pastebin.com/1Ncm9HNf , Its pretty messy.

# Answer
> 1 votes
It might be easier to just use an Orthogonal projection matrix instead of unprojecting.

```
glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);

```

Then take the mouse position on the screen and map it to the range 0 to 1

eg

```
float mousePosX = mouseWindowPosX/windowWidth;
float mousePosY = mouseWindowPosY/windowHeight;

```

Then translate

```
glTranslatef(mousePosX , mousePosY, 0.0f);

```

Remember to switch back to your previous matrix afterwards.

# Answer
> 0 votes
If you want it centered you should draw the quad with the origin in the center. You will probably want it to face the screen as well, which involves some math with the rotation matrix (search for "camera facing billboard").

(Nitpick: you don't want to upload new texture data each frame do you?)

---
Tags: opengl
---


title: Negative scale in Matrix 4x4

text:
# Question
Title: Negative scale in Matrix 4x4
After some rotations and to from quaternion conversions I get negative scale from Matrix 4x4, is it possible? I need that scale to draw sprite on screen so I get sprite flipped, how to deal with this problem should I just handle negative scale in sprite drawing method.

**if MatrixHasNegativeScale then invert scale, draw sprite with inverted scale** after **m4.initWithHeadPitchRoll(0, 0, 180);** I already get negative scale. or something wrong with matrix class?

**Edit** I create transformation matrix(rotation + scale + translate) rotation around Oz by 180 and when I extract scale from it, it has negative value is it normal?

# Answer
If your matrix and quaternion classes are functioning properly, then a sequence of rotations should not ever give you a reflection (inverting or flipping a sprite). You should not just sweep the problem under the rug by writing code to flip something if it comes out with a reflection; you should try to figure out the actual problem.

That being said, based on the comments, it's not clear to me that you actually have a reflection showing up. Negative *components* in a matrix show up naturally as a result of rotations. For example a 2D rotation matrix for a 180-degree rotation is

```
[ -1  0 ]
[  0 -1 ]

```

The presence of negative values in the matrix - even along the main diagonal - doesn't mean anything by itself. You have to look at the *determinant* of the matrix to see whether it's orientation-preserving (positive) or orientation-reversing (negative), and in this case the determinant is +1, so this is a perfectly legit rotation matrix, with no reflection.
> 8 votes

---
Tags: 3d, mathematics, matrix
---


# Question
Title: How do I implement movement in a WPF Adventure game?
I'm working on making a short WPF adventure game. The only major hurdle I have right now is how to animate objects on the screen correctly. I've experimented with `DoubleAnimation` and `ThicknessAnimation` both enable movement of the character, but the speed is a bit erratic. The objects I'm trying to move around are `labels` in a `grid`, I'm checking the mouse's position in terms of the `canvas` I have the `grid` in.

Does anyone have any suggestions for coding the movement, while still allowing mouse clicks to pick up items when needed? It would be nice if I could continue using the Visual Studio GUI Editor. **By the way, I'm fine with scrapping `labels` in a `grid` for a more ideal object to manipulate.**

Here's my movement code:

```
ThicknessAnimation ta = new ThicknessAnimation();

```

The event handling movement:

```
private void Hansel_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
     ta.FillBehavior = FillBehavior.HoldEnd;
     ta.From = Hansel.Margin;

      double newX = Mouse.GetPosition(PlayArea).X;
      double newY = Mouse.GetPosition(PlayArea).Y;
      if (newX < Convert.ToDouble(Hansel.Margin.Left))
      {
           //newX = -1 * newX;
           ta.To = new Thickness(0, newY, newX, 0);

      }
      else if (newY < Convert.ToDouble(Hansel.Margin.Top))
      {
            newY = -1 * newY;
      }
      else
      {
            ta.To = new Thickness(newX, newY, 0, 0);
      }
      ta.Duration = new Duration(TimeSpan.FromSeconds(2));
      Hansel.BeginAnimation(Grid.MarginProperty, ta);
}

```

Screenshot with annotations:

Screenshot with example movement:

# Answer
I've spent a lot of time worrying about WPF performance and animations when writing the WPF Mind Mapping app NovaMind.

On Stackoverflow I've written down some WPF animation best practices. Maybe those can help you.

Regarding your question:

> I've experimented with `DoubleAnimation` and `ThicknessAnimation` both enable movement of the character, but the speed is a bit erratic.

Without knowing the details of your app it's hard to say why your animation is erratic. Most often the reason is the misuse of Effects such as a `DropDownShadow` or `Blur`.

If the element you are moving has Effects on them it's probably better to cache the visual in a Bitmap first or to move the Effect to the container.

One way to find out what's going on is to use the WPF Performance Suite. Especially the Visual Profiler can show you easily if you have a CPU-bound issue or problems on the GPU.

As far as coding animations is concerned I had way more fun with artefact animator. Definitely worth a look as it makes it easier to define nice animations.

Overall I can only warn you that WPF is really not suited for game development. It might be fine for a prototype or hobby project and for a simple adventure game it might be okay but if you're interested in game development I would not invest any more time in WPF. One reason for this is that it's impossible to get a constant framerate which makes it pretty much useless for games.

Having written a game in HTML/JS myself since I've worked with WPF I see how much easier it can be. WPF is simply not suited.
> 2 votes

---
Tags: c#, movement, wpf
---


# Question
Title: How do I improve terrain rendering batch counts using DirectX?
We have determined that our terrain rendering system needs some work to minimize the number of batches being transferred to the GPU in order to improve performance. I'm looking for suggestions on how best to improve what we're trying to accomplish.

We logically split our terrain mesh into smaller grid cells which are 32x32 world units. Each cell has meta data that dictates the four 256x256 textures that are used for spatting along with the alpha blend data, shadow, and light mappings. Each cell contains 81 vertices in a 9x9 grid.

Presently, we examine each cell and determine the four textures that are being used to spat the cell. We combine that geometry with any other cell that perhaps uses the same four textures regardless of spat order. If the spat order for a cell differs, the blend map is adjusted so that the spat order is maintained the same as other like cells and blending happens in the right order too.

But even with this batching approach, it isn't uncommon when looking out across an area of open terrain to have between 1200-1700 batch count depending upon how frequently textures differ or have different texture blends are between cells. We are only doing frustum culling presently.

So using texture spatting, are there other alternatives that can reduce the batch count and allow rendering to be extremely performance-friendly even under DirectX9c?

We considered using texture atlases since we're targeting DirectX 9c & older OpenGL platforms but trying to repeat textures using atlases and shaders result in seam artifacts which we haven't been able to eliminate with the exception of disabling mipmapping. Disabling mipmapping results in poor quality textures from a distance.

How have others batched together terrain geometry such that one could spat terrain using various textures, minimizing batch count and texture state switches so that rendering performance isn't negatively impacted?

# Answer
I would explore precalculating textures that cover a number of your grid cells. Combined with rendering more distant grid cells from the precalculated textures, at a distance that only requires, say, 64x64 mipmaps (instead of your original 256x256 textures) then you could draw up to a 32x32 array of *grid cells* in one batch with a precalculated 2048x2048 texture.

You'd need to select your grid cells for spatting or using the precalculated texture by e.g. measuring their longest edge when projected into screen space, and combined with your screen resolution, would let you choose the ideal time to switch; when it drops below 64 pixels.

You will see less seams between cells that you mention, except of course on the grid cells that render from around the edge of the 2048x2048 texture. In this case you can precalculate a border of pixels that takes in the surrounding tiles and scale the texture coordinates on the grid cells accordingly. This reduces the resolution on your tiles. To compensate for *that*, you can reduce the number of grid cells by one in each dimension, maintaining 64x64 texels per tile, from 31x31 grid cells, with a border of 32 texels around the edge from neighbouring tiles. Tweak as needed, set texture read to clamp...

If you have a lot of terrain, then you can have a second set of 2048x2048 textures for even further out, and stream your mid-range textures as required.

A couple of notes:

* Don't disable mipmapping, it makes the texture cache on your GPU work much harder.
* If you pack more textures into a draw call, when sampling from a texture that is *not used* in the pixel shader, there can be an improvement in performance if you squash its sampling coordinate to 0,0 (or some other fixed point) which helps out the texture cache.
> 2 votes

---
Tags: directx, graphics, rendering, terrain
---


title: Drone targeting

text:
# Question
Title: Drone targeting
Imagine a "drone" and a target point on a 2d plane. There are eight parameters:

```
P = my position
Q = target position
V = my velocity
I = my moment of inertia
w = my angular velocity
s = my angular position
T = max thrust
U = max torque

```

(we'll just say the target is stationary)

The drone's job is to get to the target as fast as possible, obeying max torque and max thrust. There are only two ways to apply the torque, since this is only in a 2d plane. Thrust is restricted to only go in one direction relative to the orientation of the craft, and cannot be aimed without rotating the drone. Neglect any resistance, you can just pretend it is floating around in 2d outer space. Let's say the drone checks an equation at time interval `t` (maybe something like every .01 seconds), plugs in the parameters, and adjusts its torque and thrust accordingly. What should the equations for thrust and torque be?

# Answer
> 5 votes
In light of your question's context, http://nodewar.com/, there are a couple specific considerations for your solution:

1. You have a (low) maximum angular velocity, and enough maximum torque to reach it in very short time.
2. Your drone and target each have velocity and external acceleration unrelated to thrust (gravitation abounds).
3. Your desired target changes so frequently that trying to aim perfectly would be a waste. You should try to get close, and correct it every frame.

These methods are what I determined to work for reaching a desired acceleration.

### Acceleration, not velocity

Because you have a given velocity already, and your target is moving, you don't need thrust toward a point. You need thrust to change your velocity to what it should be. This means that your ship needs to point not toward where it is going, but in the direction in which it should accelerate.

```
// My target velocity is for maintaining a circular orbit.  Yours may differ.
// Earlier, I calculated total gravity and the perpendicular direction.
// You may wish to subtract gravity from your total, rather than match it.
var targetVel = o.lib.vec.times(lateralDir, targetVelMag);

var targetAccel = lv.sum(
  o.lib.vec.diff(targetVel, o.me.vel),
  o.lib.vec.times(gravity, 1 / o.me.mass)
);

```

### Steering toward the right heading

You have an acceleration vector, now you want to apply it. Determine how far you need to rotate. I probably used more steps than required here, but rotational coordinates confound me, and I think the uncapped ship rotation value is a bug in the API anyway.

```
// convert acceleration to an angle
var polar = o.lib.vec.toPolar(targetAccel);
var traj = polar[1];

// constrain the angle to +/-2PI, because the ship's rotation is not limited
// by default
var fixed_rot = o.lib.ang.rescale(o.me.rot);

// limit the correction to be +/-1PI
var traj_correction = traj - fixed_rot;
if (traj_correction > (Math.PI)){
  traj_correction = (2 * Math.PI) - traj_correction;
} else if (traj_correction < (-1 * Math.PI)){
  traj_correction = (2 * Math.PI) + traj_correction;
}

```

A simple formula. There is no harm in turning all the time, so don't bother applying partial torque values. If you need a small correction in angular velocity, you get to make this determination many times per second, anyway.

```
if (traj_correction > 0){
  torque = 1;
} else if (traj_correction < 0){
  torque = -1;
}

```

A less simple formula. There will come a point where you don't want to continue turning, because you eventually want to stop. Fortunately, that angular velocity cap means that you can rapidly slow down from max angular speed to zero. You only need to calculate when to do so.

```
var max_a_accel = c.MAX_TORQUE / o.me.m_i;
var a_deccel_time = Math.abs(o.me.a_vel) / max_a_accel;
// the same math as linear acceleration, now in angles.
var stopping_angle = 0.5 * max_a_accel * a_deccel_time * a_deccel_time;

if (stopping_angle >= Math.abs(traj_correction)){
  // slowdown required.  Reverse torque
  torque *= -1;
}

```

After tweaking the code above to suit your needs, your ship should rapidly and precisely rotate to whatever angle you gave it to target.

### Ramming speed

So, when to thrust? Again, the rapid change of the target and other factors create great difficulty in resolving an exact solution. Don't try to.

```
// if the heading is close to the final value, thrust.
if (Math.abs(traj_correction ) < 0.02) {  // about 1 degree
  if (true
      // some logical test, in case you don't want to accelerate past
      // a maximum speed, or some such.  Not required for your stated purpose.
     ){
    thrust = 1;
  }
}

```

For those cases where you need partial thrust, you can again rely on the fact that you can choose between 0 and 1 thrust many times per second. This gives you an effective partial thrust without varying the actual value.

Good luck!

# Answer
> 3 votes
A similar question, with some good answers, including the apparent name of this whole subject, "motion planning":
https://stackoverflow.com/questions/2560817/2d-trajectory-planning-of-a-spaceship-with-physics

As a programmer, I like the practicality of user470365's suggestion. However, I'll take a stab at a more rigorous approach. My suggestion here computes a full plan at the start, but I suppose you could re-evaluate as often as desired if the parameters are changing.

## The Plan

1. Turn to a certain direction, ***d***, and hold that direction.
2. Wait until a certain time, ***t***, then do one, sustained thrust until the target is reached.

## Details

I suggest iterative methods to find ***d*** and ***t***:

1. Assuming no thrust, traverse along the drone's future trajectory using a loop and a small timestep:

* For the drone's position and velocity at this future time, find the direction, ***d***, such that a sustained thrust will bring the drone to the target. Do this by sampling lots of directions between 0 and 360 degrees and finding the one that will bring the drone close to the target in the shortest time.
    * Check to see if we have enough time between now and this future time to turn to ***d***. (Turning is non-trivial. See discussion at end.)
    * If we have enough time, then our search is complete, so break out of this loop.
2. We've now found ***d*** and ***t***.
3. Turn to ***d*** as quickly as possible (again, see discussion below).
4. Wait until ***t***, then start the sustained thrust.
5. The drone should eventually hit the target.

## Turning

When I say "turn to ***d***", I really mean, "do a sequence of torques such that we rotate to ***d*** as quickly as possible while also bringing angular velocity to zero". There's probably an equation for this involving current direction, current angular velocity, and max angular acceleration, but it's complicated by the wrapping behavior of angles.

---
Tags: mathematics, physics, algorithm, path-finding
---


# Question
Title: using lua in kobold2d to control parameters
Is there a tutorial on using LUA in Kobold2d?

I want to know if its possible to use it to control the game behavior (like max speed decrease of timer, and bonus points) by uploading a new script to the app.

I found this link in the FAQ:

http://www.kobold2d.com/pages/viewpage.action?pageId=917888

but it does not mention if I can replace the lua script from within the game, and reload it, is that possible? Should i just have a parameter file instead that i can download and replace?

# Answer
From that page you linked to (emphasis mine):

> Kobold2D does not provide a Lua scripting interface for game engine classes, eg **you can't script game logic in Lua**. What you can do is to edit your game's parameters in Lua, then read them in with just one line of code.

Max speed, timers and bonus points are all *game logic*. That same page goes into detail on why exactly you shouldn't try to do this.

The documentation recommends Corona SDK as a similar framework if you like Lua.
> 1 votes

---
Tags: cocos2d, lua
---


# Question
Title: Are there methods faster than Strings for sending a sprite's state over UDP?
I'm programming a 2.5D networked game in Java. The networking works like this right now:

1. Create new networked sprite object at the client. Send it to the server. Server distributes and saves it. (`TCP-ObjectStream`s are used)
2. The Sprite's state is represented by a `String` that contains its id (Player's name+Index) and values. You can request the state with the method `getState()`:

```
return getID()+"|x"+getX()+"y"+getY()+"#";
//Example: "Grimey2|x402y123#"

```

These states are collected multiple times a second by adding them to a single big `String`:

```
zState += spriteArray[x].getState();
//Example: "Grimey1|x752y133#Grimey2|x410y31#Grimey3|x202y13#"

```

All sprites' states are then saved in a `HashMap` at the client, sent to the server (Java `DatagramSocket`) and saved there too.

Is there a more performant way to handle sprite-updating than with `String`s?

# Answer
Assuming the player index is unique, there's no need to send the name along with it each frame. Send the name + index once, store it in a lookup table on the client, and only send the index in your per-frame updates.

Also, if there are multiple location changes per update, why send the ones that have already expired? Unless I'm misunderstanding the purpose, the client only needs to be aware of the most recent state. If it changed 3 times since the last update, and the first two are completely nullified by the third, send only the third (final) state.

As for string vs other format for efficiency, strings are rarely the best choice for anything other than actual text. Establishing a known binary format could further reduce your update token size. For example:

`[player_index](2 bytes)[x_position](4 bytes)[y_position](4 bytes)`

would allow you to represent the same data in a guaranteed 10 bytes, rather than the variable length strings you're currently using. With a fixed format, you can remove the tokens that appear to be delimiters, "|" and "#" at the beginning and end of the (x.y) data, as well as the 'x' and 'y' labels.

Edit: though you would need to distinguish between player lookup data and player updates, so an additional byte or two at the beginning to identify the format you'll be reading after that would be required.
> 6 votes

# Answer
The source of your performance drain is likely **string concatenation**. There are great answers here on how to concatenate strings efficiently in Java.

Summary: Learn `StringBuilder`.

If even this performance boost isn't enough, you *could* design a binary protocol, but think very, very hard about it first.
> 1 votes

# Answer
Have you looked at how any network libraries are constructed? For java, I would highly recommend the Kryonet Library. It uses a serialization system called Kryo and is very performant with UDP and TCP...

http://code.google.com/p/kryonet/

http://code.google.com/p/kryo/
> 0 votes

---
Tags: java, networking, optimization
---


# Question
Title: Need help with a complex 3d scene (using Ogre and bullet)
In my setup there is a box with a hole on one side, and a freely movable "stick" (or bar, tube). This stick can be inserted/moved through the hole into the box. This hole is exactly as wide as the diameter of the stick.

In reality, when you would now hold the end of the stick in your hand and move the hand left/right or up/down, the other end of the stick, which is inside the box, would move into the opposite direction of your hand movement (because the stick is affixed at the pivot point where it is entering the box through the hole).

(I hope you understand what I mean so far.)

Now I need to simulate such a setup in a 3d program. I have already successfully developed an Ogre3d framework for this application, including bullet. But what I don't know is how I can implement in my program what I have described above. This application must include two more features:

1. The scene camera is attached to the end of the stick that is inserted into the box. So when the user would move the mouse (to control "his" end of the stick outside the box), then the camera attached to the stick would move in the opposite direction, as described above.
2. The stick has some length, and the user can push it further into the box, or pull it closer to him again. That means of course that the max. radius on which the end of the stick inside the box can move depends on how far the stick is pushed into the box. Thus, the more the stick is pushed into the box, the larger the max. radius of this end of the stick with the camera will be.

I understand this is maybe quite a complex thing, so I don't expect any real source code here. I already have the Ogre and bullet part as said up and running, as well as a camera attached to the stick. This works fine. What I don't know though is how I can simulate the setup described above. Especially the requirement that the stick is affixed at the position of the hole on the box, where it is inserted into the box.

Any ideas how I could approach to implement the described setup?

# Answer
> 1 votes
Have you considered building a set of animations that go from rest post (stick with no interaction applied) to end poses (we need a picture to really get what you're talking about) and blending the animation(s) based on user input?

I may not understand the extent of your interactivity, or needs.

---
Tags: 3d, mathematics, ogre, bullet-physics, simulations
---


# Question
Title: Can not enable IME to capture Chinese characters in SharpDX
> Just found that direct integration of IME is blocked in Windows 8, moving on to TSF now. By now, there is lack of Microsoft's Document about TSF, this will be hard.

I am using SharpDX and the RenderForm. However, when I execute the game, IME is disabled and I can only capture English chars.

Hot Keys are not working. I tried using

```
ImmSetOpenStatus(imeContext, true);

```

and

```
this.ImeMode = System.Windows.Forms.ImeMode.On;

```

but nope, not working, and I tried to disable DirectInput in the game, still can not switch on the IME.

Are there any window message that tells IME to open? Here is my code of capturing window's message:

```
    protected override void WndProc(ref Message m)
    {
        if (m.Msg == WindowMessage.InputLanguageChange)
            return;
        if (m.Msg == WindowMessage.ImeSetContext && m.WParam.ToInt32() == 1)
        {
            IntPtr imeContext = ImmGetContext(this.Handle);
            if (context == IntPtr.Zero)
                context = imeContext;
            ImmSetOpenStatus(imeContext, true);
            ImmAssociateContext(this.Handle, context);
        }
        base.WndProc(ref m);

        switch (m.Msg)
        {
            case (int)WindowMessages.WM_GETDLGCODE:
                if (Is32Bit)
                {
                    int returnCode = m.Result.ToInt32();
                    returnCode |= (DLGC_WANTALLKEYS | DLGC_WANTCHARS);
                    m.Result = new IntPtr(returnCode);
                }
                else
                {
                    long returnCode = m.Result.ToInt64();
                    returnCode |= (DLGC_WANTALLKEYS | DLGC_WANTCHARS);
                    m.Result = new IntPtr(returnCode);
                }
                break;
            case (int)WindowMessages.WM_CHAR:
                int charInt = m.WParam.ToInt32();
                InputChar InputChar = new InputChar();
                InputChar.IsUsed = false;
                InputChar.Chars = (char)charInt;
                    switch (charInt)
                    {
                        case 8:
                            InputChar.CharacterType = charType.BackSpace;
                            break;
                        case 9:
                            InputChar.CharacterType = charType.Tab;
                            break;
                        case 13:
                            InputChar.CharacterType = charType.Enter;
                            break;
                        case 27:
                            InputChar.CharacterType = charType.Esc;
                            break;
                        default:
                            InputChar.CharacterType = charType.Char;
                            break;
                    }
                    if (OnInput != null)
                    {
                        InputChars.Add(InputChar);
                        OnInput(this, InputString);
                    }
                break;
        }
    }

```

Hope you guys can help me, really don't know what to do now.

# Answer
Finally figured out why I can't activate IME supports.

Please correct me if my concept is wrong.

### Concept Behind

In windows 8, the default Input method provided is "TSF". While referring to the documents from Microsoft, TSF is a service below IME, which means IME uses TSF to provide Text service. However TSF support different input "source" ( Voice input, Pen input and etc. )

IME only integrated with the keyboard input part of TSF, so Microsoft is trying to make developer and user to use TSF instead of IME. ( To force support the tablet "Surface" I think? )

So, if you capture the IME's window messages it will return nothing. Because the OS is not using an IME input method.

### Solution

Install IME input method or legacy input method from Windows 7 and below, which is using IME not TSF.

I have installed a Chinese Windows 8 input method which is using IME, and everything works fine. There is no problem or bug in the code.
> 3 votes

---
Tags: c#, directx, input, sharpdx
---


title: Splitting tileset into individual tiles

text:
# Question
Title: Splitting tileset into individual tiles
I'm trying to split a tileset (from here) into individual tiles.

For debugging purposes I wrote some code to split the tileset into individual tiles and display them on screen, but some aren't being split correctly.

There are some small icons after the mob in the 3rd line from the bottom that got mixed up because they seemed to be smaller than 32x32. Here is my code for splitting them:

```
public class TilesetEngine : Game
{
    Dictionary<int, Texture2D> individualTiles = new Dictionary<int, Texture2D>();

    public void LoadTiles(string szFileName, ContentManager content, GraphicsDevice graphicsDevice)
    {
        var foo = content.Load<Texture2D>(szFileName);

        Color[] imageData = new Color[foo.Width * foo.Height];
        foo.GetData<Color>(imageData);

        var horizontalElements = foo.Width / 32;
        var verticalLines = foo.Height / 32;

        var i = 0;

        for (int y = 0; y < verticalLines; y++)
        {

            for (int x = 0; x < horizontalElements; x++)
            {
                var startRect = new Rectangle(x * 32, y * 32, 32, 32);

                var colorPiece = getImageData(imageData, foo.Width, startRect);
                var subTexture = new Texture2D(graphicsDevice, 32, 32);
                subTexture.SetData<Color>(colorPiece);
                individualTiles.Add(i, subTexture);

                i++;
            }
        }
    }

    public IEnumerable<Texture2D> GetTiles()
    {
        return individualTiles.Values.AsEnumerable<Texture2D>();
    }

    Color[] getImageData(Color[] colorData, int width, Rectangle rectangle)
    {
        var color = new Color[rectangle.Width * rectangle.Height];
        for (int x = 0; x < rectangle.Width; x++)
            for (int y = 0; y < rectangle.Height; y++)
                color[x + y * rectangle.Width] = colorData[x + rectangle.X + (y + rectangle.Y) * width];
        return color;
    }
}

```

**Usage**

```
        tileEngine = new TilesetEngine();
        tileEngine.LoadTiles("fantasy-tileset", Content,GraphicsDevice);

```

**Drawing code**

```
        spriteBatch.Begin();

        int i = 0;
        int padding = 10;
        var tiles = tileEngine.GetTiles();

        var maxPerLine = 10;
        var count = 0;
        var vertLine = 0;

        foreach (var p in tiles)
        {
            spriteBatch.Draw(p, new Rectangle(count * 32 + padding * count, vertLine * 32 + padding * vertLine, p.Width, p.Height), Color.White);
            count++;

            if (count == maxPerLine)
            {
                count = 0;
                vertLine++;
            }
        }

        spriteBatch.End();

```

I don't believe this is the best way, since I always found tilesets with pictures with variable size, what would be the best way to detect an individual tile from a tileset and split it?

# Answer
> 2 votes
This is very much something that I would hard-code. If there were fewer tiles, I'd be tempted to simply hard-code the rectangles for each tile. But in this case, you can hard-code the regions and do a bit of maths to get the rectangles for individual tiles:

```
public static class TilesetInfo
{
    private static Rectangle TileInRegion(int regionX, int regionY,
            int regionWidthInTiles, int tileWidth, int tileHeight, int tileNumber)
    {
        int row = tileNumber / regionWidthInTiles;
        int column = tileNumber % regionWidthInTiles;
        return new Rectangle(regionX + column * tileWidth, regionY + row * tileHeight,
                tileWidth, tileHeight);
    }

    public static Rectangle GetRectangle(int tile)
    {
        if(tile < 184) return TileInRegion(0, 0, 8, 32, 32, tile); // Large tiles
        if(tile < 192) return TileInRegion(0, 800, 8, 32, 32, tile - 184); // Fancy tiles
        if(tile < 235) return TileInRegion(0, 736, 16, 16, 16, tile - 192); // Icons
        if(tile < 237) return TileInRegion(64, 784, 2, 16, 16, tile - 235); // 2 more icons
        if(tile < 243) return TileInRegion(0, 784, 6, 8, 8, tile - 237); // Hearts
        if(tile < 250) return TileInRegion(0, 792, 7, 8, 8, tile - 243); // Bar graph
        if(tile < 270) return TileInRegion(176, 768, 10, 8, 16, tile - 250); // Big font
        if(tile < 290) return TileInRegion(96, 784, 10, 8, 8, tile - 270); // Small font
        throw new ArgumentOutOfRangeException();
    }
}

```

(I got the numbers here with a combination of simply counting tiles, and selecting sections in an image editor and looking at the pixel coordinates.)

If this code seems ugly - that's because it is. But **it's perfectly ok to write ugly bits of code for once-off things like this.** Save the beautiful code for the rest of your codebase, you can always come back and replace this section with a complex, beautiful system later on, if the needs arises. Google these acronyms: DTSTTCPW and YAGNI.

**If it makes you feel better - pretend this code is just another piece of content**, standing in for an XML file or something that has the same data.

---

You could then take the above code and use it in a `Draw` method like the following. This uses the `sourceRectangle` parameter to `Draw`, as I mentioned in comments, to avoid having to slice up the texture (which is slow at both load time and draw time - fewer texture swaps means fewer batches).

```
protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);

    int tileBaseWidth = 32;
    int tilePadding = 10;
    int displayTilesPerRow = (GraphicsDevice.Viewport.Width - tilePadding) / (tileBaseWidth + tilePadding);

    spriteBatch.Begin();
    for(int i = 0; i < 290; i++)
    {
        int row = i / displayTilesPerRow;
        int column = i % displayTilesPerRow;
        Vector2 position = new Vector2(tilePadding + column * (tileBaseWidth + tilePadding),
                tilePadding + row * (tileBaseWidth + tilePadding));
        spriteBatch.Draw(tilesetTexture, position, TilesetInfo.GetRectangle(i), Color.White);
    }
    spriteBatch.End();

    base.Draw(gameTime);
}

```

# Answer
> 0 votes
Leandro, you can simply use Tiled and a tmx map loader for XNA. Tiled will load your tileset image and split it into several different tiles, allowing you to visually create your map without coding. Then, you'll use the tmx map loader to import the map into your game.

Tiled: http://www.mapeditor.org/

TMX Map Loader for XNA and other resources: https://github.com/bjorn/tiled/wiki/Support-for-TMX-maps

# Answer
> 0 votes
If I read it right try checking the center 9px for an alpha color. If there is not that much deviation you probably need to split your 32px sprites into 4 16px sprites.

The center 9 being

```
x-1, y-1 :x, y-1 :x+1, y-1
x-1, y   :x, y   :x+1, y
x-1, y+1 :x, y+1 :x+1, y+1

```

where x,y = top+16,left+16

---
Tags: xna, c#, 2d, tiles
---


# Question
Title: How do I make an arrow line up with a bow when rotating them?
I am trying to create a bow and arrow animation in which the player can drag downwards to increase the bow strength (see the image) and release it to hit a target. I can't get the arrow to align with the bow when the arrow's height is changed (third image). I am rotating both the bow and arrow around their respective origins `(w/2, h/2)`.

What is the correct way to do it?

# Answer
Since the arrow is rotating around a center point (the same point of the bow), when you draw back on the bow, you need to keep the center point at the same point as the bow, but move the arrow back across it.

That way, you're rotating both the bow and arrow around the same point.
> 4 votes

# Answer
If the arrow is of different dimensions than the bow the point which it should rotate around should not be its own center but rather the around the same point of rotation the bow rotates around, which might very well be outside the image of the arrow.
> 5 votes

# Answer
Try setting up a rotation matrix for both sprites.

Rotation matrix - Wikipedia

Set the point to where you want to rotate. Although to make it an easier point of reference, I would rotate at the point where the bow crosses the arrow.

If i knew what language you're programming in I could look up more information to help. If you haven't worked with matrices yet, do a search for the language you're using and graphics matrix. Eg "c# graphics matrix".
> 0 votes

---
Tags: 2d, animation, rotation
---


title: Asteroids Movement

text:
# Question
Title: Asteroids Movement
I have been making an asteroids clone, in C#. However, the ship's movement is... not quite right.

My plan is this: there is a speed, and two directions, namely the direction the ship is facing (visual), and the one is is going (motion). The ship would travel its speed in its motion direction continually (no friction). If you were to press the up key, however, it would generate a vector of a predetermined value (thrust per step), and it would add this vector with the current, and thus, go more in that direction. However, it is... not working. Here is my code:

```
KeyboardState keyboard = Keyboard.GetState();

        if (keyboard.IsKeyDown(Keys.Left))
            direction -= 3;
        else if (keyboard.IsKeyDown(Keys.Right))
            direction += 3;

        if (speed == 0)
            speed = 0.1;

        Vector2 currentVector;

        currentVector.X = (float)(Math.Cos(DegreeToRadian.degreeToRadian(motionDirection)) * speed);
        currentVector.Y = (float)(Math.Sin(DegreeToRadian.degreeToRadian(motionDirection)) * speed);

        Vector2 keyVector;

        keyVector.X = ((float)(Math.Cos(DegreeToRadian.degreeToRadian(direction)) * 10)) * (Keyboard.GetState().IsKeyDown(Keys.Up) ? 1 : 0);
        keyVector.Y = ((float)(Math.Sin(DegreeToRadian.degreeToRadian(direction)) * 10)) * (Keyboard.GetState().IsKeyDown(Keys.Up) ? 1 : 0);

        Vector2 newVector = Vector2.Add(currentVector, keyVector);

        if (!(newVector.X == 0 || newVector.Y == 0))
        {
            speed = Math.Sqrt(Math.Pow(newVector.X, 2) + Math.Pow(newVector.Y, 2));
            motionDirection = Math.Atan(newVector.Y / newVector.X);
        }

        if (speed > 10)
            speed = 10;

        position.X += (float) (Math.Cos(DegreeToRadian.degreeToRadian(motionDirection)) * speed);
        position.Y += (float) (Math.Sin(DegreeToRadian.degreeToRadian(motionDirection)) * speed);

```

Note that this is C# code, but I think the issue is more of a non-language logic issue. Note that C#'s trig functions take radians, and the degreeToRadian works as expected. The keyboard works as you would expect, and is not the issue. The vectors are an object with and x and y, both floats.

The problem? Well, as I said, it.. doesn't really work. It visually turns correctly, but only moves to the right. Holding the up arrow increases its speed, of which the values are yet to be fine-tuned, but does not apply thrust in any direction but the way it was going, seemingly. Debugging through seems to indicate that the y values generated are exceedingly small - say, 3.1x10^-6 or similar. I cannot think of why this would be the case, however. In addition, thrusting left, goes right, so there is more than one issue at play here, it would seem.

Any ideas?

EDIT: I have revised my code to use radians, and it now looks like so:

```
double speed = 0;
    double motionDirection;
    double direction;

    Polygon polygon;

    Vector2 position;

    public Player()
    {
        polygon = new Polygon();

        polygon.addPoint(new Vector2(50, 0));
        polygon.addPoint(new Vector2(-30, -10));
        polygon.addPoint(new Vector2(-30, 10));
    }

    public void update()
    {
        KeyboardState keyboard = Keyboard.GetState();

        if (keyboard.IsKeyDown(Keys.Left))
            direction -= 0.05;

        if (keyboard.IsKeyDown(Keys.Right))
            direction += 0.05;

        if (speed == 0)
            speed = 0.1;

        Vector2 currentVector = new Vector2((float) (Math.Cos(motionDirection) * speed), (float) (Math.Sin(motionDirection) * speed));
        Vector2 keyVector = keyboard.IsKeyDown(Keys.Up) ? new Vector2((float) (Math.Cos(direction)*2), (float) (Math.Sin(direction)*2))  : Vector2.Zero;
        Vector2 newVector = Vector2.Add(currentVector, keyVector);

        if (Vector2.Distance(Vector2.Zero, newVector) != 0)
        {
            speed = (float)Math.Sqrt(Math.Pow(newVector.X, 2) + Math.Pow(newVector.Y, 2));
            motionDirection = (float)Math.Atan(newVector.Y / newVector.X);
        }

        if (speed > 2)
            speed = 2;

        position.X += newVector.X;
        position.Y += newVector.Y;

```

It sort of works, and sort of does not. It seems to - but I cannot guarantee this - that it works going, if you picture a circle, in a direction that fallsin the right half, but shudders and has odd shifts of momentum while in the left half.

# Answer
> 1 votes
I found the problem. First I want to say, Jimmy's answer was useful advice, and I would recommend following it (having everything in radians).

That being said, the problem was incorrect use of atan. Atan has quadrant-case issues, which I did not account for. This can be fixed by using atan2, which was made with that purpose in mind, or manually doing it. You can do it manually by determining the quadrant, and taking specific actions based on which it is to calculate the correct answer. I recommend using atan2 however.

# Answer
> 4 votes
The main reason behind the behavior you notice is that in the line `motionDirection <- Math.Atan(newVector.Y / newVector.X);` You set motionDirection to a radian measure, but then assume it is a degree measure on the following line. Since radian values are much smaller than degree values, this tends to just push the angle towards 0.

The main reason your code is hard to read is because you aren't using vectors properly. I generally advise people to use radian angles for calculation just so you don't have to keep converting back and forth and forget a conversion here and there. However, oftentimes you can avoid using angles entirely. For example, if you track motionDirection as a vector (we typically call it `velocity` in that case, and it would serve the same function as your `currentVector` variable), and direction as a radian, your code would turn out to be something like the following:

```
var keyVector = keyboard.IsKeyDown(Keys.Up) ? new Vector2(Math.Sin(direction), Math.Cos(direction)) : Vector2.Zero;
var newVector = velocity + keyVector;
var newspeed = newVector.Length();
velocity = newspeed < 10 ? newVector : newVector * 10 / newspeed;
speed = velocity.Length();
position += velocity;

```

---
Tags: movement, vector, trigonometry
---


title: Using random numbers with a bias

text:
# Question
Title: Using random numbers with a bias
I appear to be awful at describing the question so I'll try and describe the problem.

I want to add a random amount of heads to my creatures but I want to be able to determine several things. a) The minimum number of possible heads b) The maximum number of possible heads c) The probability of the number being high/low within the above values.

So i could add heads like so: addHeads(5, 10, 0.5); // should produce creatures with "around" 7.5 heads but they could have anywhere from 5 to 10.

So random number generation isn't the problem, but controlling and actually using them in a game is. :D

# Answer
One way to do it is to apply a power function: $$f(x) = ax^p+b$$

Start with a random number \\$x\\$ in \[0, 1\] and then raise it to the power of some positive number \\$p\\$. Powers \< 1 will bias upward, i.e. the numbers will be more likely to be higher than lower within \[0, 1\], and powers \> 1 will bias downward. Then use multiplication (\\$a\\$) and addition (\\$b\\$) to shift the range of numbers from \[0, 1\] to your desired range. In pseudocode:

```
function random(low, high, bias)
{
    float r = rand01();    // random between 0 and 1
    r = pow(r, bias);
    return low + (high - low) * r;
}

// Examples:
random(5, 10, 1.0);  // between 5 and 10, average is 7.5
random(5, 10, 0.5);  // between 5 and 10, average is somewhere around 8.5
random(5, 10, 2.0);  // between 5 and 10, average is somewhere around 6.5

```

Here's a plot of the second example:

On the horizontal is the initial random number in \[0, 1\] and on the vertical is the output. You can see that something like 75% of the initial range is mapped to values higher than 7.5, and 25% of the initial range is mapped below 7.5. So the result is that numbers generated by this function are more likely to be higher.
> 7 votes

# Answer
The usual answer will be some code that can tweak the random number distribution to give you the properties you want. I'd suggest instead working backwards:

1. first decide what distribution you actually want and draw it out
2. calculate the “cumulative distribution” which is the sum of the function in step 1
3. choose a random number from the cumulative distribution
4. look up the number from the original distribution you drew

This way you don't ever actually need to find a function (like power or logarithm) that matches your desired behavior. You can directly model your desired behavior.

How do you implement this? You can approximate step 1 with a table. For step 2 you add the values in the table. For step 3 you pick a random number from 0 to the sum in the cumulative table. Then for step 4 you look for the corresponding entry in the cumulative table.

I don't yet have a great description of this technique, but I've written a little bit in the “Designing your own distribution” section of this page.

This approach probably won't work for everything but I mention it because tables are nice for designers to edit, and the designer is not limited to existing mathematical functions but instead can choose any arbitrary wacky shape. For example, if you decide that a prime number of heads should be unusually rare, that's easy to write in a table, but it might be harder to find a mathematical function that fits that shape.
> 4 votes

# Answer
I have a harvest system implemented in my game that utilizes rejection sampling. Each item has a weighted chance of being produced. It's easy to assign weights to certain items and get one randomly using that weighted chance. This is similar to your situation, except you don't have harvest items, you have number of heads. So, you'd first assign a weighted chance to each head count value for the values you want.

So we have # of heads : weighted chance

```
5 heads:2
6 heads:4
7 heads:3
8 heads:1
9 heads:2
10 heads:1

```

The weighted chance values don't have to add up to anything specific, but you should know that they are going to be relative to each other.

Then we go through and make a list of them all:

```
ArrayList<ProducedItemInfo> tmpList = new ArrayList<ProducedItemInfo>();
    int totalChance = 0;
    for (HeadWeightPair hwp: headWeightPairs) {
        if(conditionsMetFor(hwp)) {
            totalChance += hwp.weightedChance;
            tmpList.add(hwp);
        }
    } //add up the total weight and create a list of the available options
      // at this stage, you could have conditions that would preclude certain options
      // for example, you could check the size of the creature and
      // not allow high numbers of heads
      // if you'll never have conditions, just generate this list once and keep it
    //now we go through removing a random value from the totalChance
    // if one of the items is less than the total, we return that item
    if (totalChance > 0) {
        int rand = randomInt(totalChance);
        for (HeadWeightPair hwp: tmpList) {
            if (rand < hwp.weightedChance) { return hwp.headCount; }
            rand -= hwp.weightedChance;
        }
    }

```

It's log(n) if you have a pre-compiled list (if you don't have conditions you can do that).
> 1 votes

---
Tags: java, procedural-generation, random
---


# Question
Title: In an iOS OpenGL ES 2 game, is it better to use a few large texture atlas or many small textures?
I'm working on new game, this time moving to more 3d objects and open gl es 2. Previous (successful) game was open gl es 1 and mostly 2d. For es 2 I'm developing my own 3d engine.

My 3d artist delivers .obj's each with a texture map for base and one for bump (normal). I already have a way to import them all into a single vbo. But combining the textures is a more challenging problem.

In the es 1 game I did a couple of large texture atlases and could have them all loaded at once. But since all my geometry was just boxes it was easy to shift them around (small number of vertex) to fit. I stacked gfx like tetris pieces to fit everything in. For this though it's a bigger pain to combine textures as there are many many more vertices and they're already mapped to these individual textures.

I have several ideas for ways to approach the problem:

1. Keep the separate but manage the loading and releasing of texture images better, so that when a level is loaded it loads just the images needed for the objects needed for the level. If I did this how many images can the ios implementation handle? How would performance suffer on older devices like the iPhone 4?
2. Combine multiple textures into atlases and cram image parts together however necessary to fit. Then load the obj's into my 3d app and basically manually remap everything to the combined texture. It's a pain and basically what I'm paying the 3d artist to do.
3. Combine multiple textures into atlases but by putting 4, 8, 16, etc smaller ones into each larger one.. DON'T cram them together but uniformly shrink each one. Then the remapping can be mathematical instead of a manual remapping. (This would leave possibly a lot of un-used space in some of the sub-textures)

1. Pre-calculate the math beforehand in the importing process.
    2. Modify my shader to shrink and offset the textcoord on the fly by an amount provided as a uniform.

Also.. is it better to combine the base texture and normal texture into one or have 2? Combining them would mean having the shader do math to move the textcoord over for the normal map.

# Answer
The less times you have to send texture data through the pipeline for rendering the better. A single larger texture set would be more efficient than 1,000 smaller ones of the same memory capacity. It is not uncommon for developers on limited platforms, or developers trying to push the limits of consoles (even today) to pack textures and limit the amount of texture set calls necessary. Packing a texture atlas is a relatively easily automated process, and the extra effort up front reduces the run time performance hits.
> 2 votes

---
Tags: ios, opengl-es2
---


title: Managing Background Sprites

text:
# Question
Title: Managing Background Sprites
I tried asking in Chat and no one answered, so the question goes here.

Anyone have advice for loading background Sprite maps? I'm trying to do it as efficiently as possible for a grid of 25 locations. So, I'm thinking only have 5 sprite backgrounds loaded at a time, when applicable, for clean transition from location to location. (Like The original Zelda.) So, should I load up all 25 at once, or only keep the minimum up? (I just want to avoid confusion sprite variables are up.)

# Answer
> 2 votes
If the memory footprint of the individual map segments is small enough, then you could easily get away with simply loading them in when the world loads. If on the other hand you are limited on memory, then I would instead implement a streaming system. The streaming system would allow you to divide the world into separate zones, and load only the appropriate resources depending on which zone you are in. You could also set it up to simply load in the neighboring tiles in addition to the current tile, and then update the loaded tiles whenever there is a transition.

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


# Question
Title: What kind of projection is ScreenX=X/Z, ScreenY=Y/Z?
I have an existing class which transforms 3D vectors and projects them on a 2D plane (Camera). The code is all written in C without help from an external library.

To project a single vector (X,Y,Z) on the screen, the code first applies the View matrix of the camera and then for the actual projection does the following:

```
ScreenX=X/Z;
ScreenY=Y/Z;

```

ScreenX and ScreenY are then used as the screen coordinates (after additional scaling and translation).

What kind of projection is this?

Since it uses the Z coordinate to adjust the X and Y coordinates, I would think it is a perspective projection, but I'm not sure. If it's indeed a perspectice projection, then what would be the FOV for this?

I'm just trying to understand how the existing code works so that I can rebuild it using standard libraries and using a standard projection matrix if possible.

Any idea?

**Edit - Some more information:**

After this division, the coordinates are multiplied (scaled) by the "lens resolution" (pixels per unit) and translated by the lens center (X,Y coordinates in pixels):

```
ScreenX = ScreenX * Res + CenterX;
ScreenY = ScreenY * Res + CenterY;

```

`Res` is a large number and I'm guessing it defines the projection plane, letting the coordinates scale from 0 to the size of the actual image in pixels.

# Answer
After some more research I found out it's a **Pinhole Camera Model**. It is supposed to model a real camera.

There is a nice description here: http://www.epixea.com/research/multi-view-coding-thesisse8.html

What I was having trouble understanding was that I need some sort of projection plane. If there is no projection plane, all pixels would basically meet in the same singular point and would have the same coordinates. This is basically the same as the Near Plane in a perspective projection. It is a very small value, but it can't be zero.

There is no Far-Plane, since in a real camera there is no clipping of far objects. Just like in a real camera this means that you don't have a Z (depth) value that you can use.
> 4 votes

# Answer
It is a perspective projection, but those elements alone do not define the field of view.

This article covers more of the basics of the components of a projection. http://msdn.microsoft.com/en-us/library/aa916436.aspx
> 3 votes

---
Tags: mathematics, matrix, vector, geometry, projection
---


# Question
Title: Applying Angular Acceleration in a Basic Physics Model
I'm attempting to use a basic physics system to create an arcade flight model. So far I have managed to get the aircraft moving forward, apply gravity, etc. However, after trying to implement torque I noticed some interesting behaviour in the flight model. When turning after a while the controls appear to reverse, sometimes, the controls for the different movements (pitch, roll, yaw) also seem to change. I was hoping that someone may be able to advise me as to what I should check next. I have included my source code in case anyone spots any glaring mistakes! I have listed some of the variables below to show their data types:

```
Quaternion rotation = Quaternion.Identity;
Quaternion newRotation = Quaternion.Identity;
Vector3 rotationChange = Vector3.Zero;
Vector3 rotVec = Vector3.Zero;

```

Below is the update logic for the rotational forces:

```
dt = (float)gameTime.ElapsedGameTime.TotalSeconds;
if (dt > 1.0f / 60.0f)
{
    dt = 1.0f / 60.0f;
}

Vector3 newRotationChange = rotationChange + dt * angularAcceleration;
Vector3 newRotVec = rotVec + dt * newRotationChange;

rotationChange = newRotationChange;
rotVec = newRotVec;

Vector3 rotAxis = rotVec;
rotAxis.Normalize();

if (rotVec.Length() < 0.001f)
{
    rotVec = Vector3.Zero;
    newRotation = Quaternion.CreateFromAxisAngle(forwardVector, 0.0f);
}
else
{
    float angle = rotVec.Length();
    newRotation = Quaternion.CreateFromAxisAngle(rotAxis, angle);
}

if (rotationChange.Length() < 0.001f)
{
    rotationChange = Vector3.Zero;
}

rotation = newRotation;
angularAcceleration = Vector3.Zero;

```

My method for creating the torque:

```
/// <summary>
/// Creates a rotational force for an object
/// </summary>
/// <param name="pointOfAction">Point the force is being applied on the object
/// </param>
/// <param name="forceAmount">Magnitude of the force being applied</param>
/// <param name="forceDir">Direction of the force being applied</param>
public void CreateTorque(Vector3 pointOfAction, float forceAmount, Vector3
        forceDir)
{
    // Vector from position to pointOfAction
    Vector3 r = pointOfAction - position;

    // Create the force
    Vector3 force = forceDir * forceAmount;

    // Create the torque force
    torque = Vector3.Cross(r, force);

    angularAcceleration += torque;
}

```

Sorry for the massive code block and thanks in advance for any help you can give.

# Answer
> 3 votes
Ok so I finally managed to work out what I was doing wrong. The issue was how I was applying the rotation vector to the quaternion. Basically rather than use `Quaternion.CreateFromAxisAngle()` I now create a rotation change Quaternion using my angular velocity as the X,Y,Z components and 0 for the scalar. So just for clarity here is my new update code for rotational physics. ( This replaces every line of code after calculating `dt`)

```
Vector3 newAngularVelocity = angularVelocity + dt * angularAcceleration;
Quaternion rotChange =
    new Quaternion(angularVelocity.X, angularVelocity.Y, angularVelocity.z, 0);
rotChange = Quaternion.Multiply(rotChange, dampeningFactor) * rotation;
rotation += rotChange * dt;
rotation.Normalize();

angularVelocity = newAngularVelocity;
angularAcceleration = Vector3.Zero;

```

Hopefully this proves helpful to someone else!

# Answer
> -1 votes
Whenever you use `.CreateFromAxisAngle()` it is necessary to supply a unit length vector for the `axis` param. If you don't, it will over or under rotate the result since the axis magnitude is a factor in the rotation calculation.

Try normalizing it like this:

```
else
{
    float angle = rotVec.Length();
    rotVec /= angle;//this normalizes rotVec
    newRotation = Quaternion.CreateFromAxisAngle(rotVec, angle);// use 'rotVec' as the axis, not rotAxis
}

```

---
Tags: physics, xna-4.0, torque
---


title: example of texture mapping in pyglet

text:
# Question
Title: example of texture mapping in pyglet
Using pyglet, I am trying to create a UVSphere mesh, and on its surface I would like to display a mercator-projection map. In researching examples of pyglet texture mapping, I have found:

Are there any simple examples of a working mesh + texture map in pyglet?

**Edit:** I found out the pyglet\_obj\_test code is looking for lines in the `.obj` file starting with `vt` in order to create texture mapping coordinates. However the Wavefront exporter in Blender apparently has no option to export this information. I exported the same mesh with each of the other available types:

* `COLLADA (.dae)`
* `Stanford (.ply)`
* `Stl (.stl)`
* `3D Studio (.3ds)`
* `Autodesk FBX (.fbx)`
* `X3D Extensible 3D (.x3d)`

Perhaps there's a pyglet importer for one of these formats...

**Edit 2:** I clearly have a poor understanding of the wavefront format. It seems `vt` lines are *not* necessary. What I was missing is full `f` maps.

For instance, to simplify things way down, I created a 3d mesh that was actually a single square, with a texture mapped onto it. In Blender it shows the square with distorted texture, but the built-in wavefront exporter produces a single line of texture mapping `f 2//1 1//1 3//1 4//1`. These should apparently instead be something like `f 2/0/1 1/0/1 3/0/1 4/0/1` (note there should be a number between the two slashes).

Apparently Blender only does a full (proper?) export of these lines if a texture is *UV mapped*. Applying a texture without a UV Map renders properly in Blender, but I guess the wavefront exporter doesn't properly handle it. Perhaps it's time for me to submit a Blender bug report...

# Answer
> 1 votes
I pursued the pyglet\_obj\_test solution further and got it working. So, to answer my own question, here's a complete example:

* Using Blender, create a mesh with a UV-mapped texture. The UV-mapping is important! If it is working properly, you will see the texture applied within Blender's 3d view.
* Export the mesh from Blender using the Wavefront format, including normals.
* Clone pyglet\_obj\_test, and run `display.py your_mesh.obj`

---
Tags: textures, pyglet
---


# Question
Title: How to make healthbar size relative to hp
Like in most games with healthbars, the units in my game have a hp\_bar object which is a frame, with a slightly smaller rectangle inside which should get smaller (and change color) as a unit loses hp, but I'm unsure how to work the math which will make the rectangle size an integer which represents an percentage rather than the actual hp.

Say the hp bar is 40 pixels in width, and hp is some arbitrary integer amount, what is the python magic to convert the hp to hp bar width?

# Answer
Well, consider the following:

The ratio between the max width of the bar and the real width of the bar is the same as the ratio between max HP and HP; so:

```
width / max_width = hp / max_hp =>

width = hp / max_hp * max_width

```
> 2 votes

---
Tags: mathematics, python
---