title: 2D Platformer Collisions

text:
# Question
Title: 2D Platformer Collisions
I've basically asked this question before, and I know it's been asked probably a billion times, but I still can't seem to do it. All I want to know is how I should go about doing basic 4-way, rectangular collisions (up, down, left, right). I have been searching for an answer on and off for months and I can't seem to find it. All I need to know is some basic code examples (in Java, preferably) for how I would do this. I've tried a few different methods before, but they just don't seem to work (I can get certain sides to work, but not all of them at the same time). I'm making this game entirely from scratch and I'm using libgdx as my framework. I don't want to use Box2D or any other engine. Thanks in advance to anyone who will help me!

tl;dr: 4 way collisions, how do they work?

# Answer
The XNA 2D Platformer example has a pretty straight forward algorithm it uses for collision detection and resolution. Here's an answer I've given over on Stack Overflow a couple of times. It's a language agnostic approach that can likely be adjusted to fit your actual needs. If you want to see their actual code (though it's in C#), it is in `player.cs` in the `HandleCollisions()` function.

1. *After* applying movement, check for and resolve collisions by doing the following.
2. Determine the tiles the player overlaps based on the player's bounding box.
3. Iterate through all of those tiles doing the following: (it's usually not very many unless your player is huge compared to your world tiles)
    1. If the tile being checked isn't passable:
        1. Determine how far on the X and Y axes the player is overlapping the non-passable tile
        2. Resolve collision by moving the player out of that tile *only on the shallow axis* (whichever axis is **least** penetrated)
            * For example, if Y is the shallow axis and the collision is below, shift the player up to no longer overlap that tile.
            * Something like this: `if(abs(overlap.y) < abs(overlap.x)) { position.y += overlap.y; } else { position.x += overlap.x; }`
        3. Update the bounding box's position based on the player's new position
        4. Move on to the next tile...
    2. If the tile being checked *is* passable, do nothing
4. If it's possible that resolving a collision could move the player into another collision, you may want to run through the above algorithm a second time. Or redesign your level.
> 4 votes

# Answer
Okay language agnostic, I much prefer my approach to the shallow penetration test.

**Things You Need**

1. You need some way to store previous positions of your objects
2. You need a way to detect and store all current objects you're colliding with

**How It Works**

First, you need to find the object with the nearest wall- in a tile system this is a simple check for the tile with the nearest center. When I did this I sorted my objects from closest to farthest.

Next, you run this routine on it:

```
if (we are colliding){
 if (mypreviousdown <= theirpreviousup){ //if I was previously above them
  move upwards() //probably set our position to their position - our height
  set our y velocity = their y velocity() // for moving platforms
  //optional
  add their velocity to our position() // for sticky platforms
  // end optional
 }
 if (mypreviousup >= theirpreviousdown){ //if I was previously below them
  move downwards()
  set our y velocity = their y velocity() // for moving platforms
  //optional
  add their velocity to our position() // for sticky platforms
  // end optional
 }
}

if (we are still colliding){
 if (mypreviousright <= theirpreviousleft){
  move to the left()
  set our x velocity = their x velocity
 }
 if (mypreviousleft >= theirpreviousright){
  move to the right()
  set our y velocity = their y velocity
 }
}

```

**Considerations**

This system works fantastically well, and I have yet to see any bugs- unless you're moving fast enough to move to the other side of the object, but if you're not, this works great.

One thing you may want to consider is adding some functionality to slip around edges or go up steps, it will add some good gameplay mechanics to your game.

Another thing you may want to add is a way to detect which side is currently colliding at any given time(for things like jumping and such)

You may also consider a custom event system, it's been a great help to my game programming lately.
> 2 votes

# Answer
Simply said: on each frame for each moved rectangle, check if it intersects with any other rectangle if so, don't update the position. There are numerous ways to optimize this using spatial partitioning techniques. But what are you having trouble with precisely?

Note that http://code.google.com/p/libgdx/source/browse/trunk/gdx/src/com/badlogic/gdx/math/Rectangle.java says that the rectangle is defined by it's most bottom-left point, while it is more common to use the top-left point so take that in to account when using intersection code snippets and tutorials.
> 1 votes

# Answer
One way: You might look at Box2D source code, or collison source code in Java.

Other way: I understood logic behind collisions from article about collision detection on Flipcode. I took a piece of paper, wrote down and derived what he wrote about. Then I was able to code it. Math helped me, it might do for You too. (I believe that Youry rectangular 4way is on the beginning)
> 0 votes

---
Tags: 2d, java, collision-detection, libgdx
---


title: Model not rendering correctly XNA

text:
# Question
Title: Model not rendering correctly XNA
Basically i am trying to render a model yet it seems to draw polygons that should be behind something, in front of it. So i end up seeing some faces that should be behind something, totally covering it. Bah, i suck at explaining so here's the pic:

See the Railing? It should be at the front, but it's covered by the top of the platform. Also, on the side, the shadowed area should be practically hidden from that front wall... Other bits are around the place too if you just look at it... :(

I tried the 3 different cull modes, none of them fixed it, so i don't think its the culling (in fact Clockwise made it worse... :P). Thanks for any help.

# Answer
> 3 votes
It looks like your depth buffer is not working. You should try something like:

```
device.RenderState.DepthBufferEnable = true;

```

I cant now test it, so this is just what I have googled. If it doesnt help, you can also try:

```
device.RenderState.DepthBufferFunction = CompareFunction.LessEqual;
device.RenderState.DepthBufferWriteEnable = true;

```

---
Tags: xna, c#, 3d, models, rendering
---


# Question
Title: Starting a Game Dev Incubator - Engines to Start With?
I'm currently in the process of developing a technology incubator in my region to cater to game development professionals and aspiring devs and I'm curious about what engines are best to use, with regards to flexible licensing (e.g. right now we're on a shoestring budget) and also performance/popularity and a solid community/company backing.

As my background is in web development my focus with this group is more of the management and logistics while other professionals will be on the board to handle the other aspects, but I'm still trying to pick a few solid engines.

Garry's Mod at the moment seems to be the most feasible option since I've used it a lot and I know it's simple to pick up, but I wanted to ask if there is anything similar to that.

Also, this group is purely for PC gaming so we're not handling consoles and we are ideally looking to do 2-D and 3-D development or even game engine coding.

# Answer
> 5 votes
I'm a little confused as to what you mean by incubator.

Are you talking about an incubator like Tech Stars or Y Combinator in which you bring in teams and help them with the development process? If that's the case, wouldn't the decision for which engine to use generally be left to the people running the individual projects?

You may decide to focus on Unity and UDK, sure. But what about when someone comes in wanting to make a purely 2D game, and they've already developed a large code base on top of something totally unfamiliar to you like SDL or Monocle. I'd say you'd be better served diving into a project using whatever tool makes sense at the time and building your general knowledge so that you can help future teams that come through.

The only other type of organization that I can think of as an incubator would be a sort of collective, where you work on projects and provide a way for people to come in and get experience working on a game. Then your concern about choosing an engine would make a little bit more sense. Even still, you would have to factor in the skills and professional goals of your first batch of team members.

What languages and libraries are your programmers familiar with? Do you have programmers? If you have all pixel artists then forget about UDK or Unity, look at something 2D like SDL, SFML, or even Flash with Flixel, FlashPunk, or the standard Flash graphics api. Since you say your background is in web development, maybe think about a design with multiplayer, or at least something that would require or benefit from storing player statistics in an online database so they could be publicly viewable through a web interface.

A group that I worked with initially started writing 2D games in C++ with SFML. Later we switched to as3 and Flixel to reduce development time. Then we decided to give XNA a shot since a lot of our artists were primarily 3d modelers and animators and wanted to be able to hone and showcase their skills in that area. Unfortunately that project ended up going nowhere because it was chaotically managed and blew up in scope. That's another thing to consider, you probably don't want to start off the bat with the kind of project that UDK would be useful for.

# Answer
> 2 votes
I think you will learn the most by doing it from the ground up.

Now having said that having an engine or two to start poking around with does not seem like it to be too bad of an idea either.

Unity seems to be a popular engine as of let. I have not used it myself but the licensing seems fair and the deployment range, though not of interest to you right now, is always a possibility later on down the road.

I would also recommend looking at the Unreal and CryTek engines. To release a full game on them I think is very expensive, but they are free to play around and mod with and for PC game engines, I think it safe to say they are top of the line.

In and around wanting to learn, I can recommend previous ID Tech engines. ID Software has released full source code to many of their previous engines (Under GPL licensing for the most part I believe). I am currently unable to produce direct links to the different engines as their FTP site (ftp.idsoftware.com) where they reside seems non-responsive. Various links can be found on their website however at www.idsoftware.com.

Good luck and I hope this helps.

---
Tags: architecture, software-engineering
---


# Question
Title: Line segment / circle intersection - X value seems wrong?
**Major Edit**

I'm making a Breakout clone, and having difficulty with collision detection between a circle and line segment.

Apologies, my earlier question was a result of frustration and no sleep :)

Having read this post on collision detection I've re-written my collision code to the following:

```
    // Takes 2 points on a line, a circle centre, and a circle radius
    // Returns true is collision, false otherwise
    public Boolean DoesCollide(Vector2 a, Vector2 b, Vector2 c, float rad)
    {
        // First up, let's normalise our vectors so the circle is on the origin
        Vector2 normA = a - c;
        Vector2 normB = b - c;

        Vector2 d = normB - normA;

        // Want to solve as a quadratic equation, need 'a','b','c' components
        float aa = Vector2.Dot(d, d);
        float bb = 2 * (Vector2.Dot(normA, d));
        float cc = Vector2.Dot(normA,normA)-(rad*rad);

        // Get determinant to see if LINE intersects
        double deter = Math.Pow(bb, 2.0) - 4 * aa * cc;
        if (deter > 0)
        {
            // Get t values (solve equation) to see if LINE SEGMENT intersects
            double t = (-bb - Math.Sqrt(deter)) / (2 * aa);
            double t2 = (-bb + Math.Sqrt(deter)) / (2 * aa);
            Boolean match = false;

            if (0.0 <= t && t <= 1.0)
            {
                // Interpolate to get collision point
                Vector2 collisionPoint = c + Vector2.Lerp(normA, normB, (float)t);
                match = true;
            }
            if (0.0 <= t2 && t2 <= 1.0)
            {
                Vector2 collisionPoint2 = c + Vector2.Lerp(normA, normB, (float)t2);
                match = true;
            }
            return match;
        }
        else
            return false;
    }

```

However, I'm getting strange results for the X components of the collision points found 'on hit' - see the following debug output:

```
Coll at {X:1033.931 Y:620}, t1 = 0.203759334390812, Normalised = {X:0.8576241    Y:0.5142772}
Coll2 at {X:1052.069 Y:620}, t2 = 0.409877029245551, Normalised = {X:0.8615275 Y:0.5077109}
Circ cent = {X:1043 Y:610}, rad = 13.5

```

As you can see, the X components are 10px either side of the circle centre, but the Y component (620) is the very topmost pixel of the top of the Breakout paddle. Surely here the X points can't be 20 pixels apart, given the location of the Y point?

# Answer
You are missing a stage before calculating t0 and t1. It should look more like this:

```
float q; // Holds the solution to the quadratic equation
if (bb >= 0)
{
   q = (-bb - Math.Sqrt(deter)) / 2;
}
else
{
   q = (-bb + Math.Sqrt(deter)) / 2;
}

float t0 = q / aa;
float t1 = cc / q;

```

After that, make sure t0 and t1 are sorted. \[Edit\] I made a small error with the determinant signs, note they are now reversed.
> 2 votes

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


# Question
Title: How can I run my XNA demo straight from a CD?
I was told by a company that better than putting an installer on a CD would be allowing the user to run the demo directly from the CD. Is this even possible when the demo might require things such as the XNA framework to run? Are they actually wrong and an installer is in fact necessary for the dependencies?

# Answer
XNA, like many libraries, has dependencies on runtime components that must be in place in order for applications that depend on it to run. While you don't strictly speaking *need* an installer, the alternative is to ask or expect the user to have the appropriate dependencies installed or install them themselves (which makes for a very poor user experience).

You can create an autorun file on your CD which launches your installer. What many games do is have the launcher detect the presence of your game and/or its dependencies and have the installation app tailor itself to what's installed -- presenting install options normally, and if the game is already there, presenting a "launch" option or possibly even launching directly into the game (this may annoy users though).

Note that if you elect not to use existing installation solutions (NSIS, Inno, Windows Installer, et cetera) and write your installer shim yourself you have to be careful -- even C and C++ code requires redistributable components, so make sure to ensure the minimum OS level you support already guarantees them or build something that won't depend on them.

Once the dependencies are in place, the game itself can be launched from the disc so long as it won't try and write to any relative directories, such as its own .exe directory (a well-behaved Windows application shouldn't do this anyway).

Obviously the above applies only to XNA on Windows, as it's the only platform you can execute code off a disc on.
> 4 votes

---
Tags: xna, deployment
---


# Question
Title: Blender: projecting an image via a spotlight onto a plane
I've create a plane with a spot light shining from above onto it. The spot light projects a texture of an image onto the plane. The light shots out at an angle but the texture is projecting in a flat 2d form on the plane.

I expected it to stretch out much like the advertisements you'd see drawn on the pitch during a rugby or cricket match. Any idea how I'd change the way the image is shawn onto the plane?

The image should stretch out with the nearer section looking a bit more narrow than the top far section.

# Answer
> 1 votes
Here is a good tutorial.

He used an empty transform to control the position and scale of the projection.

---
Tags: textures, blender, lighting
---


# Question
Title: Which language and tools should I choose for creating 2D games?
Recently I have returned to my childhood hobby (programming games) and found it quite enjoyable. I've been tinkering with PyGame (for Python) for a few months, made a couple of projects for educational purposes. PyGame is nice, however there is not an awful lot of commercial games using PyGame, and I'd like to invest my time in the best way and **ideally** to make an extra buck in the future.

What I like:

* doing things alone. I do not dream about working at huge corporation and making one tiny bit of World of Duty-7
* frameworks like LÖVE (for Lua) or PyGame. I doubt I am able to figure out how to draw those fancy pixels without it
* cross-platform things.
* free stuff.

What I don't like:

* C++ scares me, however feel free to tell me how stupid I am
* IDEs like GameMaker, RPGmaker etc. I like making my own tools.

My goal is to make 2D games like Terraria, Super Meat Boy, DefCon, etc. Which language and tools should I choose to accomplish my goal?

# Answer
> 4 votes
I want to be a game developer... now what?

This is a pretty comprehensive guide to starting out in game development, covering what languages are available, then a list of the most popular tools and libraries, as well as free and commercial book suggestions. Most of what is inside is completely free and provides direct download links. However, it is a long read, but I promise you that you will be much more knowledgeable when you finish!

There is nothing directly wrong with C++, but it is not a very approachable language and there is a level of difficulty in just getting up and running that adds another level of complexity that a new developer doesn't need. It is a language to consider in the future, but in my humble opinion, not one to learn with! Then again, nobody listens and they start with C++ anyways! :)

# Answer
> 5 votes
> however there is not an awful lot of commercial games using PyGame, and I'd like to invest my time in the best way and ideally to make an extra buck in the future.

And who cares? The toolchain is not what makes a game commercial or not, it's not what makes it a AAA title or not. PyGame will not prevent you from realizing your goal of creating a commercial game that makes you a bit of money.

Only *you* will prevent (or enable) that success.

If you are comfortable with Python and PyGame, then continue using them to create games, even games you sell. Since you are comfortable with the tools **they will be the ones best suited to you** and your goals.

# Answer
> 2 votes
> C++ scares me, however feel free to tell me how stupid I am

You shouldn't fear c++ it is a great language.

> My goal is to make 2D games like Terraria, Super Meat Boy, DefCon, etc. Which language and tools should I choose to accomplish my goal?

Awesome! You can do this in pygame, there's nothing wrong with that.

Do you *like* programming in python with pygame? If so, keep going, you can move on to other languages (read c++) if you so desire later on. As you get more proficient in one language you'll find others come easier as well. Don't worry so much about what you're going to do later- instead focus on getting better with the tools you have, and gaining proficiency in learning new tools, as those are quite dynamic.

# Answer
> 2 votes
LOVE2D seems like a cool language. I'll state now that Lua's weird to me, particularly trying to get OOP down with it, since there's no real built-in easy method to do this with. In any case, Pygame (framework; based on Python), Love2D (framework; based on Lua), Game Maker (game engine with IDE), and StencylWorks (free game engine with IDE; makes Flash games) are pretty good.

On the 3D side, there's a lot of options, but the Blender Game Engine's pretty good (and can make 2D games).

---
Tags: 2d, pygame, love2d
---


# Question
Title: How does one make a 3D background in a 2D game?
I am trying to figure out how to make a background that looks 3D in a game that is 2D. Below there is a video of the game "Under The Lotus." I am trying to get a background with similar effect (it looks like a 3D environment, while the game runs basically in the X and Y axis).

http://www.youtube.com/watch?v=3GsTwsx5aWo

Can anyone give me an idea how to do that? Or point me in some direction on what to read to be able to figure this out?

I am planning on using SDL for this game. If I could avoid using OpenGL that would be better, but it is not a real requirement.

# Answer
Like chrish said, I would recommend writing a game in a 3D engine or with a 3D framework than working with a 2D engine or framework and trying to add in 3D just for a single effect. OpenGL can do it, and so can many other game engines, like Unity (I would assume) and the BGE.
> 1 votes

# Answer
A lot of 2D games are actually written using OpenGL (which is still a good option with SDL, actually); you can take advantage of the 3D hardware for creating very nice special effects without impacting your draw performance.

In a case like this, you'd draw your 3D background, switch to an orthographic projection, then draw your 2D bits on top. If I remember correctly, `glOrtho()` sets up the projection you want, and should be enough info to get you going (finding ortho tutorials is as simple as hitting up the Google). For example, NeHe's Tutorial 21 shows you how to use `glOrtho()` for drawing 2D objects.
> 0 votes

# Answer
As others have said, using OpenGL/DirectX will give you more options and better performance for most things. It's definitely a lot more complex than SDL, but it will pay off.

The particular effect looks a pixel shader that uses noise (probably multiple times - first to find the coordinates in the noise, then to find the value). I was able to achieve a similar effect with this (HLSL, sorry):

```
sampler sNoise = sampler_state { texture = <_noise>; magfilter = ANISOTROPIC; minfilter = ANISOTROPIC; mipfilter = ANISOTROPIC; AddressU = MIRROR; AddressV = MIRROR; };
sampler sColors = sampler_state { texture = <_colors>; magfilter = ANISOTROPIC; minfilter = ANISOTROPIC; mipfilter = ANISOTROPIC; AddressU = BORDER; AddressV = BORDER; };

float4 background(PixelInfo p) : COLOR0
{
    float3 ofs = _time * _velocity + _ofs;
    float3 spos = float3((p.uv - ofs.xy) * 512 / _screenSize, ofs.z);

    float3 vpos;
    vpos.x = tex3D(sNoise, spos + 0.0000).r - 0.5;
    vpos.y = tex3D(sNoise, spos + 0.3333).r - 0.5;
    vpos.z = tex3D(sNoise, spos + 0.6667).r - 0.5;

    float v = tex3D(sNoise, vpos).r;
    return tex1D(sColors, pow(v, _density));
}

```
> 0 votes

---
Tags: sdl, 2.5d
---


# Question
Title: How to verify if the client files are the same as the server files?
In a client-server game architecture, what are the possible ways to verify that the client has not modified things like gfx assets or client side scripts?

Obviously no solution is perfect, but I would love to hear some ideas.

I am thinking something like an hash on all the files in the resources directory. Does that sound feasible?

# Answer
If this is for hack prevention, it's a losing battle.

Things like hashes and sending random bits of data back to the server for validation come to mind, but nothing stops the hacker from using a separate, non-compromised copy of the original data as source for answering such checks.

Same goes for sending checksums of in-memory resources.

One way might be to send screenshots or checksums thereof, but then you hit the problem of different video cards/drivers rendering subtly different frames...

All that said, I'd consider outsourcing the problem to someone who has been doing it for a while, like http://www.evenbalance.com/ (punkbuster).
> 7 votes

# Answer
There's no way to reliably protect an engine that is executing on a computer you don't control, but you can make it a lot harder to cheat, for example by encrypting resources and communications traffic. Also, no one trying to hack your system will be able to do it perfectly the first time. Put in some tripwires to detect attempts to hack and permanantly ban any accounts that are caught.
> 1 votes

---
Tags: client-server, security, anti-cheat
---


# Question
Title: Equivalent of glDrawTexfOES in OpenGL ES 2.0?
I have been using the `glDrawTexf` extension to draw labels in my Android app using OpenGL ES 1.1.

But I have now moved to OpenGL ES 2.0 and can't figure out **what is the equivalent of this call**? I could create triangles to hold the texture and draw it like a regular texture. But the `glDrawTexf` was very convenient:

* It didn't require any triangles/quads to be setup.
* You could give it screen co-ordinates.
* You could specify cropping parameters to pick smaller areas from a large texture.

# Answer
> 5 votes
However "convenient" it may have been, it was only ever that: a convenience. All it was ever doing was just drawing textured triangles.

OpenGL ES 2.0 doesn't have very many convenience functions. It's a bare-bones, relatively low-level rendering API. So that means you're going to have to build those convenience features yourself.

You can easily set up an orthographic projection matrix that provides a 1:1 correspondence between vertex coordinates a pixels. This allows you to work directly in pixel coordinates. The texture coordinates of your vertex data "crop" which texels of the texture are drawn.

---
Tags: android, opengl-es
---


# Question
Title: Unity: 2D problem (I'm using Orthello package but any advice appreciated)
So instead of dishing out 150$ for SpriteManager 2 (Unity Package), I've been playing around with Orthello which a **free** SpriteManager package.

I got most of everything I'd like working and it was fairly easy to setup however I am running into a few issues:
**General 2D Question**
1. How does one go about moving the gameObject with an animation?
I have an animation of a monkey that I'd like to play as I jump from Vine to vine. The animation plays on the spot (as I was instructed they should all do). However now I'm running into problems on ways in which I should move my transform according with the animation playing?
Should I lerp on the update thread? Lerp on every frame event?

**Specific To Orthello**

1. I've setup my animations on the animation container and assigned 'Duration' values. The problem is that the animation will finish playing once the Duration has passed without playing **every** frame of the animation. Is this normal behaviour for animation systems? I imagine it's doing this in order to compensate for how often it gets updated.

If people would like I can post my C# Script. Here is a youtube video of so what I have also if anyone is curious.
here is a blog post I made on the subject as well (include the video)

# Answer
Yeah just move your character in the update method when you press forward, you can make your animations reactive to the movement or your reactive to the buttons, you'll have to decide yourself.

something like this perhaps? To add to my script you can also put in more checks to see if you are playing already with animation.IsPlaying("") so you don't call animations when you don't need to..

```
void Update ()
{
    Vector3 moveDirection = Vector3.zero;
    if (Input.GetKeyDown(KeyCode.LeftArrow))
    {
        moveDirection = new Vector3(1, 0, 0);
    }
    if (Input.GetKeyDown(KeyCode.RightArrow))
    {
        moveDirection += new Vector3(-1, 0, 0);
    }
    if (Input.GetKeyDown(KeyCode.Space))
    {
        // jump
        moveDirection += new Vector3(0, 1, 0);
    }

    if (moveDirection.y > 1)
    {
        animation.Play("JumpAnim");
    }
    else
    {
        // wait for jump animation to stop
    }

    if (moveDirection.x > 0)
    {
        animation.Play("LeftAnim");
    }
    else if (moveDirection.x < 0)
    {
        animation.Play("RightAnim");
    }
    else
    {
        animation.Stop("LeftAnim");
        animation.Stop("RightAnim");
    }
    transform.Translate(moveDirection * Time.deltaTime);
}

```

To answer some of your blog post questions.. Should animations with movement still be animated in the center (i.e. on the spot)? Yes, if you created a walk cycle for you character you don't move the characters position in the animation, you do this in code.

How do you take care of moving the sprite during the animation? Lerp the position? Use Transform.Translate method

How do you tie in the movement distance/time it takes to get there with the number of frames in the animation? You get properties like length, time, and speed from your animation like so

```
animation["JumpAnim"]

```

Please reference these links when developing with Unity

http://unity3d.com/support/documentation/ScriptReference

http://www.unifycommunity.com/wiki/index.php?title=Tutorials

http://www.unifycommunity.com/wiki/index.php?title=Scripts

http://www.unifycommunity.com/wiki/index.php?title=Tips

this deals with 2d movement http://unity3d.com/support/resources/tutorials/3d-platform-game

sprite stuff http://www.unifycommunity.com/wiki/index.php?title=SpriteManager http://www.anbsoft.com/middleware/sm2/

Here's a custom search tool created with google search for unity related stuff http://www.google.com/cse?cx=002470491425767499270:iugs1ezlsfq&ie=UTF-8&tbs=qdr:y&q=unity%20search

Unity has a well established community full of examples of this kind of stuff.
> 1 votes

# Answer
On Orthello,

An OTAnimation object can have multiple named animation framesets, each of those named framesets can be given a duration.

When you OTAnimatingSprite.Play a named frameset, this duration is used and all the framesets's frames are displayed in exact the duration of the named frameset.

You can OTAnimatingSprite.PlayLoop to keep it looping.

When you play the entire animation (so all framesets) the OTAnimation.duration or fps is used to determine how fast all frames have to be played.

Orthello does not stop an animation or named animation frameset before all frames have been played.

Regards and check the online user manual 'Using Animations' for further info. Orthello User Manual
> 0 votes

---
Tags: 2d, animation, unity, sprites
---


# Question
Title: Create quaternion based on where a unit is hit (shield effect as in Starcraft 2)
I'd like to implement a shield effect like that done for Protoss units in Starcraft 2. I'm guessing that the technique involved uses a partial sphere that is rotated to reflect where a unit is hit.

Assuming this is the idea, how can I create a quaternion to rotate this model to achieve the desired effect? My collision detection system conveniently relies on sphere-sphere intersection.

Edit: this is pretty much a dupe of this, which has a pretty thorough answer.

# Answer
> 2 votes
You can use the same "look at" rotation techniques you would use to have a camera look at a target object; just rotate the partial sphere as if it were the camera. I don't know enough about quaternion math to give a specific answer for quaternion computation, but the way you construct the coordinate system is this:

1. Inputs: unit position, hit position, 'up' vector.
2. Subtract hit position from unit position to get 'look at' vector.
3. Normalize it.
4. Take the cross product of 'up' and 'look at' to get the 'right' vector.
5. Replace 'up' with the cross product of 'right' and 'look at'.
6. Use these vectors (which are basis vectors for a coordinate system) to construct your rotation; they are the columns-or-rows-depending of a rotation matrix, and I don't know what they are for a quaternion.

The 'up' vector can be arbitrary, but it must not be parallel to the 'look at' vector; it determines the rotation of your shield geometry around the hit-direction axis. By the hairy ball theorem, there is no way to "smoothly" pick an up vector, so just do it in some arbitrary way.

# Answer
> 3 votes
Does your quaternion library have something that's akin to "LookAt" in it's API? If so, author the content so the effect is on the forward vector and just tell your sphere to look at the object that caused the hit effect.

# Answer
> 2 votes
Not sure if it helps, but I was thinking about what you're asking, specifically "create a quaternion to rotate this model" etc..

I think the way it's done in SC2 is quite simple. There are two ways to attack a unit or building... either by air or by ground.

All the ground attacks on a shield is animated at the same height. So it's essentially just a pivoted animation, duplicated depending on all the angles it's being attacked from. Note that a single marine attacking a nexus (really low dps), the shield damage is barely visible, so it's almost transparent so that if a lot of units attack from the same side, it won't just become an opaque block of bad graphics. This sort of proves that it's duplicated for every single hit.

Same with air attacks, except the animation has a slightly bigger "surface area", but it still pivots horizontally around the unit.

Air units are the same, except flipped vertically (they can't be attacked from the top, but from the bottom instead).

So SC2 is quite 2d-oriented with this problem. If your game is more flexible in the Z-dimension then you may need a different solution.

Edit: I also thought of a different way, instead of duplicating the animation, you have a logarithmic opacity setting... so that the more damage is done, the more opaque it is, but being logarithmic it will reach a point where you won't see much difference if you add MORE damage. This way you can also prevent a big block of bad graphics.

---
Tags: rotation, quaternion
---


title: Making a HUD/GUI with OpenGL (LWJGL)

text:
# Question
Title: Making a HUD/GUI with OpenGL (LWJGL)
I'm at the stage in my game development where I need to make a HUD or GUI. I've never gotten to this part, so I don't know how its done. I tried rendering a simple quad at a fixed position on the screen, but there's a problem. To make my camera work with orthographic, I use this:

```
public void lookThrough()
{
    GL11.glMatrixMode(GL11.GL_PROJECTION);
    GL11.glLoadIdentity();
    GL11.glOrtho(position.x, position.x + Display.getDisplayMode().getWidth()/zoom, position.y + Display.getDisplayMode().getHeight()/zoom, position.y, -1, 1);
    GL11.glMatrixMode(GL11.GL_MODELVIEW);
}

```

I don't see how I would be able to make something fixed on the screen using this method? Any way around this? Thanks :)

# Answer
> 13 votes
This is from an old OpenGL-based game engine I was trying to write about seven years ago written in C++ so bare with me as I try to explain how I handled 3D world and 2D GUI rendering operations within it. I used four primary methods within my OpenGL renderer class (OGLRender) of which are:

* **ready3D()** for preparing OpenGL to render the 3D world scene.
* **ready2D()** for preparing OpenGL to render the 2D GUI.
* **render3D()** for the actual 3D world scene drawing.
* **render2D()** for the actual 2D GUI drawing.

```
void OGLRender::ready3D()
{
    glViewport(0, 0, m_Setup.width, m_Setup.height);
    glMatrixMode(GL_PROJECTION);

    glLoadIdentity();
    gluPerspective(45, (float) m_Setup.width / m_Setup.height, 0.1, 5000.0);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glDepthFunc(GL_LEQUAL);
    glEnable(GL_DEPTH_TEST);
}

void OGLRender::ready2D()
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    gluOrtho2D(0.0f, m_Setup.width, m_Setup.height, 0.0f);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(0.375, 0.375, 0.0);

    glDisable(GL_DEPTH_TEST);
}

void OGLRender::render3D()
{
    this->ready3D();

    // ... draw 3D world scene here ...
}

void OGLRender::render2D()
{
    this->ready2D();

    // ... draw GUI here ...
}

```

And then in the main thread loop I would basically just call the methods in the following order:

```
while(m_drawFrame)
{
    gm_Render->render3D(); // draw 3D scene
    gm_Render->render2D(); // draw GUI

    SDL_GL_SwapBuffers(); // make drawn frame visible
}

```

So, what I am doing is I draw my 3D world scene first and then I draw my GUI last that way the GUI is always on top of the world scene. **ready3D()** method gets the 3D world projection ready for world scene drawing and **ready2D()** method gets the 2D ortho scene ready for GUI drawing. `m_Setup.width` and `m_Setup.height` are just the view port screen dimensions.

What is special about the **ready2D()** method is that `gluOrtho2D()` function is called with arguments that tell it when we draw the GUI primitives we draw them in the screen coordinates specified to match Windows, Mac, and other desktop screen coordinate systems. Such as top-left is (0,0) in (X,Y) format while bottom-right is `(ViewportWidth-1, ViewportHeight-1)`. And `glTranslatef()` is used to correct for per-pixel accurate positioning. So that when we draw a line from (0,0) through (0,9) then the line will actually draw from the top-left and straight down ten pixels total in length and one pixel width.

Overall you're most likely just interested in what the **ready2D()** method is doing. I provided the other methods' source code examples to give you an idea as to generally how most games do 3D world scene and GUI drawing order.

---
Tags: opengl, java, gui, lwjgl
---


# Question
Title: How'd they do it: sphere effects in Osmos
I'm curious how the sphere effects were done in Osmos from Hemisphere Games. Any ideas how the resolution independent zoom in was achieved?

Edit, more specifics on questions:

1. How do you render the spheres so they look good at full zoom out, and full zoom in?
2. How would one make the nice particle effects in 100's of spheres all at once?
3. How to construct your scene/spheres so the big spheres look round even at full zoom?

Gameplay video

Hemisphere Games

# Answer
Daniel, I have this game and I was wondering the same thing myself when I first played it. It's quite impressive. I don't know for sure, but I think for the spheres, they're using a series of overlapping translucent rotating bitmaps to give the illusion of particles within the spheres. This is very efficient in OpenGL. They would be rather large in source (probably twice the largest size you see on-screen) and then down-sampled as textures on-the-fly during rendering. This would also solve the problem of appearing round at any size, since it avoids using a finite polygon. Whether or not this is the technique used in Osmos, it's something you might want to give a try...
> 0 votes

# Answer
1 and 3: It's all pretty basic functionality of a modern graphics chip, there is a pixel sampling method which ensures that things look smooth even though an image is rendered in non-native resolution. You just have to make sure that the image is of reasonable size for the big spheres not to become blurry.

The common method is to use a 3D api for invoking this, even though your game is 2D. Often you'd use a piece of middleware that translates 2D commands into 3D equivalents.

I don't know how it specifically works on the iPhone, but it's certainly nothing out of the ordinary so there should be plenty material covering the topic.

2: I don't see a lot of particle effects in that video, there is a few particles of exhaust, but they don't need to be implemented in a different manner than the spheres.
> 2 votes

---
Tags: glsl, ipad, graphic-effects
---


# Question
Title: Tilemap rendering with openGL (why the rendering is extremely messed up)
I'm using SDL & openGL to render a tile-map. The issue is that the tile-map rendering is extremely messed up, and I'm just a bit unsure what I'm doing wrong exactly.

It should just be the first tile being rendered, but I'm getting a blurred mess :S. My rendering code:

```
glBindTexture(GL_TEXTURE_2D, texture);
float texscale = 1.0f / (float)tileWidth;
sourceX = sourceX / (float)tileSheetWidth;

glBegin(GL_QUADS);

// Top-left vertex (corner)
glTexCoord2f( sourceX, sourceY);
glVertex2i(x, y);

// Bottom-left vertex (corner)
glTexCoord2f( sourceX + texscale, sourceY);
glVertex2i( x + tileWidth, y);

// Bottom-right vertex (corner)
glTexCoord2f( sourceX + texscale, texscale + sourceY);
glVertex2i( x + tileWidth, y + tileHeight);

// Top-right vertex (corner)
glTexCoord2f( sourceX, texscale + sourceY);
glVertex2i(x, y + tileHeight);

glEnd();
glLoadIdentity();

```

My initialization code for OpenGL:

```
// Set the OpenGL state after creating the context with SDL_SetVideoMode
glClearColor(0, 0, 0, 0);
glDisable(GL_DEPTH_TEST);
glEnable(GL_TEXTURE_2D); //Enable 2D rendering
glViewport(0, 0, Width, Height); //Set Up openGL viewport (screen)
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, Width, Height, 0, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

```

Just in-case, here's my image loading code, I think that perhaps this may be were the problem lies somehow:

```
LoadImage(string filename, bool loadingTileSheet)
{
  SDL_Surface *LoadedImage = NULL;
  GLuint texture;
  Uint32 rmask, gmask, bmask, amask;
  LoadedImage = IMG_Load(filename.c_str());

  if (loadingTileSheet)
  {
    tileSheetWidth = LoadedImage->w;
    numberOfTiles = (LoadedImage->w / tileWidth) + 1;
  }

  SDL_PixelFormat *pixf = SDL_GetVideoSurface()->format;
  SDL_SetAlpha(LoadedImage, 0, 0);

  if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
  {
    rmask = 0xff000000;
    gmask = 0x00ff0000;
    bmask = 0x0000ff00;
    amask = 0x000000ff;
  }
  else
  {
    rmask = 0x000000ff;
    gmask = 0x0000ff00;
    bmask = 0x00ff0000;
    amask = 0xff000000;
  }

  SDL_Surface *image = SDL_CreateRGBSurface(SDL_SWSURFACE, LoadedImage->w, LoadedImage->h, 32, rmask, gmask, bmask, amask);
  SDL_BlitSurface(LoadedImage, NULL, image, NULL);

  glGenTextures(1, &texture);
  glBindTexture(GL_TEXTURE_2D, texture);

  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, image->w, image->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, image->pixels);

  return texture;
}

```

# Answer
> 4 votes
Code dump + find my problem, doesn't make a good question. I suggest finding code that works via a tutorial or other source, and build off of that code or compare it to yours.

That being said... Test your texture loading code by drawing a quad with the full texture on it (use the texcoords 0 -\> 1). If that displays correctly then check your glTexCoord2f calls.

# Answer
> 1 votes
```
float texscale = 1.0f / (float)tileWidth;
;;;
glTexCoord2f( sourceX + texscale, texscale + sourceY);

```

You are computing `texScale` from your x axis but applying it to the y axis too.

Compute the height of a tile in the texture separately from the width of a tile in texture coordinates, as they are different values when your atlas is packed to not have the same number of tiles vertically as horizontally...

---
Tags: c++, opengl, rendering, tilemap
---


title: hexagon tiles to square tiled map

text:
# Question
Title: hexagon tiles to square tiled map
in a previous question asked here:how-to-create-a-hexagon-world-map @Tim Holt has provided code that does the job that i'm wanted to do, the only difference I would like is to have it as squares rather than hex. Is this easy to convert, or is there a better way? thank you.

# Answer
> 1 votes
I didn't look too closely, but the code in that answer was heavily involved with hex calculations -- like figuring out where the mouse is pointing on the hex grid. This is trivial if the tile is a square, you wouldn't even need to examine this carefully. The same would be true for most of that code. So I suggest starting from scratch, but using the concepts / code you need from that example if you find yourself stuck.

Start with a 2 dimensional array, each element containing a value for the type of tile it is and which directly maps to actual tile images with a set width defined as a constant somewhere.

---
Tags: tiles, php
---


# Question
Title: 3d immersive Virtual Conference meeting environment development on the web (3d website)-Help required
I want to develop 3d immersive virtual collaborative conference meeting environment on the web i.e an immersive virtual environment for our university Teachers to attend and address conference (meeting) Virtually in 3d

Each attendee have login with their customized avatar and can collaborate and discuss different issues(USING SPEECH IN REAL TIME) with each other by using their personalized avatar(other teachers present in meeting Virtually ) I want to implement these features + some other like text support , Multimedia Projector for presentation etc

I need help regarding platform selection preferably I want to Implement it as a webpage (3d website) with no installation or plugin support (plugin independent ) other wise I'll go for Plugin Solution I don't know WebGL and graphics programming I want to do it more by designing in 3d and integration with reusable components

I'm confused in choosing platform I've explored these names so far \[ WebGL/Google O3d/web 3d's X3D ,VRML /X3doom/Sirikata Platform/yogurt3d/Unity3d/Jibe/OpenSim/Papervision3d/Flash/3dmlw/Java3d/Infinity3d/ Cube3/CloudMach\] also please tell me if other are available and appropriate for me

# Answer
The speech side of this alone is enough for a full project.

Consider the problem you are trying to solve first. Are you simply trying to develop a way for a number of people to collaborate over the internet, or does it really have to be a "3d immersive environment"? From a user experience perspective, one could argue that a "3d immersive environment" makes actual collaboration more difficult, due to having to figure out how to immerse yourself in the 3d world. How much time do you expect a user to customize their appearance, for example? Would this time be better spent actually collaborating? Could you get away with using something like a Wiki, forum, chat room, or some other service designed for collaborative discussion of a presentation (webinar)?

If "3d immersive environment" is not absolutely essential, I would say consider using existing video conferencing solutions, like Skype, Google Hangouts, or for just voice, Ventrilo. If you wanted more control over how the interface works, you could program your own solution using an API like Opentok. By definition a user does not have to "customize" their appearance with video, and you leverage the existing platform. All of these platforms have spent considerable time thinking about scaling issues (not just network / server scaling, but also as an example, what happens if three people are trying to talk at the same time and nobody is wearing headphones?)

If it is essential, but you don't necessarily have to make it yourself, consider Second Life or an existing 3d avatar service. I believe SL provides VoIP and I would imagine alternatives do as well. Even if you just found an acceptable 3d avatar service with no VoIP, you could always use it in combination with another VoIP service (perhaps Ventrilo).

Now, if you really insist on creating a 3d world with VoIP yourself, my personal bias is to suggest using Flash. It is a very well developed programming platform, it can handle this challenge and since it is so popular, you may even be able to find and leverage existing middleware (like VoIP) for the various components of the project. Unfortunately, I can't provide any concrete examples, except that Opentok does have a Flash SDK.

On top of this, you will need to consider server-side development as well, or some sort of P2P solution. The user will have to get information about each other user (position, appearance, audio, etc) in some fashion. Again, I can't provide much in the way of concrete suggestions, but know that it is going to be a large part of the work.
> 2 votes

---
Tags: platformer, webgl, cross-platform, web
---


# Question
Title: How do I move a 3D particle using the Mercury particle engine?
I'm currently creating a 3D game with XNA, and I am in need of some particles.That's why I searched for a particle engine. I found Mercury, watched the tutorials and integrated it in the game.

But now I have a problem, I trying to have particle in 3D but I don't how to do this with Mercury. How can I do this (is it even possible)?

# Answer
> 2 votes
Mercury is a 2D particle engine, so you can't directly position/manipulate/simulate particles in 3D using it.

While you could perhaps abuse it into looking 3D with a combination of a custom modifier on an emitter and some clever overloading of particle properties (or outboard storage of extra particle data), you're better off finding another solution.

Mercury is open-source and released under a reasonably permissive license (MS-PL) so you could fork it and adopt its techniques to 3D rendering. You could also look for alternatives or hand-roll a solution. There are several examples you could use as a starting point:

...and several others available via Google. There's also this API which may be useful.

**EDIT:**

As a follow-up to Jaakko's comment I went and dug around their repository a little more. They do appear to have a "4.0" branch which looks like it will (or perhaps already does) support 3D. If this is the case and you can use the API from that branch (I'm not clear on its release status), you probably just need to create a custom particle modifier and attach it to your emitters. You can instantiate this modifier with whatever additional data you need to compute the 3D positions, and in the modifier's `Process` method, apply whatever logic is appropriate and update each particle's 3D position directly.

# Answer
> 0 votes
If you can't with Mercury, one option would be to check out the sample in the education section of the app-hub.

http://create.msdn.com/en-US/education/catalog/sample/particle\_3d

---
Tags: 3d, xna-4.0, particles
---


# Question
Title: What are the pros and cons of incorporating Lua into a C++ game?
I have a C++ game programming book and it has a Lua section in it. I've started to read the Lua section, and it sounds interesting, but I can't determine the pros and cons of using Lua in my C++ game. The only benefit I can currently think of is that you can make some coding updates, via Lua, without having to recompile. Other than that, I can't think of anything. So what are the pros and cons of adding Lua to a C++ game?

Examples would be appreciated.

# Answer
> 33 votes
> The only benefit I can currently think of is that you can make some coding updates, via Lua, without having to recompile.

Do not discount the utility of this so easily. You will *never* understand how productive you will be until you take away the recompilation step.

The "flow" is a fairly well-understood psychological concept when it comes to work. The flow is that feeling you get when you're focused on an activity, when you're analyzing and solving problems almost without thinking, etc. You are at your most productive when you are "flowing".

Compile times screw all of that up. It's hard to stay in the flow if you have even a 10-second compile between testing something.

When you are developing gameplay, what you usually have is a "tight loop". You have an idea, you code up a test to see if it works, and then you try it out. If it doesn't work, you modify it and try again. The "code-to-test" time is very important for maintaining flow. Getting it as small as possible is crucial.

What Lua (or any embedded scripting language) allows you to do is to test changes, not just without "compiling", but *live in the game*. Depending on how you build your game, you can run a command that will restart the game with new scripts without having to stop and reload data and so forth. Not only do you not have to recompile, you don't have to re-run.

The ability to do this, given the proper engine support, can dramatically increase productivity.

---

Another major benefit to scripting is the ability to just not care. If you've spent a long time writing C++, you would be amazed at how much time you spend over minutae. Where memory is deleted. Where this gets freed. Even if you're using `shared_ptr` everywhere, just the act of typing in all of those variable type names slows you down.

In a dynamically-typed scripting language, you don't have to care. Scoping is simple. Functions are first-class objects; you don't have to manually build functors. It is just so *easy* to do some things.

Now that does have negatives, if you're not a disciplined programmer. It's very easy to use globals in Lua (though there are ways to prevent that). Not caring means that you can be very sloppy when you code.

But then again, being very sloppy can have advantages.

---

Another upside of Lua is that it makes a nice data description language. Much like JSON is just a JavaScript file that builds and returns an array/table, you can make Lua scripts that return tables.

This is useful for configuration files; Lua's table format is a lot better than .ini formats. The format is still rather clean, compact, and extensible.

Oh, and it's still a Lua script, so it can perform actual logic. The downside of that is... well, it's a *Lua script, so it can perform actual logic*. That could be disastrous in game, since the user could potentially start screwing things up.

But actually, this is easily dealt with. Lua is designed for embedding, which means that isolation is actually quite easy. Indeed, a fresh Lua state provides *nothing* by default; you have to actually do something to expose even the most basic of the standard Lua libraries. File access, game-state access, etc, is all opt-in, not opt-out. And each Lua state is separate from each other one. The Lua state you use for AI scripts does not have to be the Lua state you use for config files.

I actually have some code that allows you to register many Lua standard libraries, but goes through and removes all file IO. Ultimately, the worst that a Lua script-based configuration file could do is cause your game to crash immediately upon running it, by running it out of memory. And since you're not sharing these config files manually, that wouldn't be much fun for a hacker.

---

I would say that the biggest downside of any scripting language is debugging. Most scripting languages do not have debuggers, and Lua is no different. Lua does have all of the tools one would need to build debugging tools. But it does not actually have a debugger built-in. You have to put one together. And that's going to require a reasonable degree of work.

Or you can make due with "printf debugging". It really depends on how much Lua code you write.

# Answer
> 25 votes
Where I work:

Pros:

* **iteration time** improvements. Our game is set up to poll a host filesystem for changes and automatically "slurp" in changes. (They only take effect at next file open, but in practice, that's a major improvement: reload the level, and your new lua changes come in immediately.)
* **console integration**. Any debug functionality can be hooked to a traditional Quake-style console with a REPL. For internal builds we can even hook a lua REPL to a simple socket that speaks telnet, and we have network control over our game.
* **reduced api** and **lower learning curve**. Nontechnical artists and designers can join in on some tasks that would be typically programmer-bottlenecked.
* **specialized static code analysis**. It's easy to parse the output of `luac -l` and peek at the bytecode to do some analysis; it's also pretty easy to parse most lua source files, especially if you have a coding convention. We can enforce local convention. You can also look into metalua for even more power here.
* **error handling**. If our API is crash-free, even if lua does something silly, we can catch it and recover using `lua_pcall`.
* **easy API extension**. Writing a new function for the Lua \<-\> C++ API is not too hard. There are also packages that will help automate this.
* **simple source**. Making changes to e.g. avoid floating point mathematics in the lua interpreter (important on some embedded platforms) or to optimize for particular systems is not too hard!
* **metatables**. These are awesome. So much potential to do interesting things at runtime. We have "virtual tables" that actually have no contents and perform a lookup into a complicated data structure on the C++-side of our games.
* **coroutines**. Being able to stop and resume e.g. AI behavior scripts is amazing. It takes a bit more savvy on the lua scripter's part, though -- we're still working on how to make this more "safe" with our engine.

Cons:

* **unpredictable GC**. Tuning what our `step` should be changes drastically per game. Some work better with full GC every frame (small working set). Some work better with much smaller passes more infrequently. Note there's a lot of work in improving the GC on newer lua versions and in some patches (which you shouldn't be afraid to use!)
* **higher overhead**. We keep a lot of our large data structures C-side in order to avoid per-table-entry memory overhead. C++, C, and assembly generally produce faster code. So it's kept to the 90% of the game engine that isn't performance critical, and occasionally we do migrate things from lua to C (or vice versa).
* **fragmentation**. Perhaps the biggest issue on small memory systems. We usually use small object pools and a completely separate large object heap for lua. We put full GC passes in strategic points in the game. We unload scripts or throw away the `lua_State` entirely in some cases. And we still sometimes have issues. Tuning the sizes of the small object pools (they're fixed, for simplicity and lower overhead) and the size of the lua-specific large object heap can be a pain. But on systems larger than about 4MB, we have not yet bothered with the specialized heaps and pools.
* **lack of type safety**. If you don't have a good static code analysis toolset built, you're going to fall back on a lot of runtime error checking (perhaps using `__index` and `__newindex`). It's better if you can catch errors at compile time. There are various things you can do to alleviate this.

Lua's highly recommended, just be willing to work with it a bit! You may also want to check out Squirrel, although I believe it has a smaller userbase.

# Answer
> 5 votes
Actually there are 3 great advantages:

These factors allow you as a game developer to enable features that will speedup the development and increase the quality of your game.

For example:

* You will be able to change your game logics simply by updating your game from a file or a network socket.
* You can allow users to create their own scripts (for bots or mods)
* Your game designers and artists will be able to update and tests parts of the game without having to use your compile tool set.
* You will not have to recompile every time you change a few scripts.
* You won't have to rewrite the entire game if you change platforms/engines/languages.

# Answer
> 3 votes
From my experience, boiled down a bit.

**Pros**

* Initial integration is really easy. Tools exist to help generate bindings, but the binding mechanism is so simple that you could write your own version thereof, with your own custom features, in no time
* You get much faster iteration on game logic (assuming you implement runtime reloading)
* You'll get a liberating environment to experiment in: you'll try out more things because the overhead for doing so drops significantly
* Familiar syntax: for all its differences, you'd be hard pressed as a C programmer not to be comfortable in it within hours
* Better separation of game logic to "engine": your engine becomes a service provider that has to expose a decent API to the Lua client. The language barrier makes you think about that more, instead of just reaching in there and fiddling a member variable

**Cons**

* Lua memory management isn't ideal for games. You cope with it, you don't like it
* Lua debugging is awful out of the box. You'll have to work to improve the experience
* Keeping data in Lua means you'll need to debug in Lua: inspecting it from C will initially be tricky
* Lua has a good amount of shoot yourself in the foot syntax, like all variables being global by default
* Lua is a programing language, just like any other. Don't expect non programers to magically turn into programers just because you removed the compiler
* Getting good at integrating and supporting Lua is a big chunk of work. Don't expect it to purr right out of the box. It's fair to assume that you'll actually have to amortize this cost over a few games

Final, personal, verdict: if you're building a decent sized game and don't already have a scripting language, then get Lua. It'll be worth it.

# Answer
> 1 votes
Garry's Mod is one example of a game that uses Lua and C++. They use Lua for all of the mods, which makes them much easier for people to make. C++ is used for all of the internals. The only con I can think of would be the fact that Lua is not as fast as C++.

---
Tags: lua
---


# Question
Title: How can I draw many objects on screen instead of just one?
Like many beginner graphics programmers I followed a tutorial which showed me how to set up buffer descriptions and fill out the vertex buffer etc... - the steps involved in drawing a simple indexed cube on the screen. There is a leap however when it comes to drawing more than one of these cubes. My code below is the original cube drawing code, if called more than once, each call overwrites the vertex buffer and only one object is drawn - the last one.

So what are the options for drawing many of these cubes?

```
Cube::Cube(D3DXCOLOR colour, D3DXVECTOR3 min, D3DXVECTOR3 max)
{
// create eight vertices to represent the corners of the cube
VERTEX OurVertices[] =
{
    {D3DXVECTOR3(min.x, max.y, max.z), colour},
    {D3DXVECTOR3(min.x, max.y, min.z), colour},
    {D3DXVECTOR3(min.x, min.y, max.z), colour},
    {min, colour},
    {max, colour},
    {D3DXVECTOR3(max.x, max.y, min.z), colour},
    {D3DXVECTOR3(max.x, min.y, max.z), colour},
    {D3DXVECTOR3(max.x, min.y, min.z), colour},
};

// create the vertex buffer
D3D10_BUFFER_DESC bd;
bd.Usage = D3D10_USAGE_DYNAMIC;
bd.ByteWidth = sizeof(VERTEX) * 8;
bd.BindFlags = D3D10_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
bd.MiscFlags = 0;

device->CreateBuffer(&bd, NULL, &pBuffer);

void* pVoid;    // the void pointer

pBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &pVoid);    // map the vertex buffer
memcpy(pVoid, OurVertices, sizeof(OurVertices));    // copy the vertices to the buffer
pBuffer->Unmap();

// create the index buffer out of DWORDs
DWORD OurIndices[] =
{
    0, 1, 2,    // side 1
    2, 1, 3,
    4, 0, 6,    // side 2
    6, 0, 2,
    7, 5, 6,    // side 3
    6, 5, 4,
    3, 1, 7,    // side 4
    7, 1, 5,
    4, 5, 0,    // side 5
    0, 5, 1,
    3, 7, 2,    // side 6
    2, 7, 6,
};

// create the index buffer
// D3D10_BUFFER_DESC bd;    // redefinition
bd.Usage = D3D10_USAGE_DYNAMIC;
bd.ByteWidth = sizeof(DWORD) * 36;
bd.BindFlags = D3D10_BIND_INDEX_BUFFER;
bd.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
bd.MiscFlags = 0;

device->CreateBuffer(&bd, NULL, &iBuffer);

iBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &pVoid);    // map the index buffer
memcpy(pVoid, OurIndices, sizeof(OurIndices));    // copy the indices to the buffer
iBuffer->Unmap();

//this is simply a single call to the update method that sets up the scale, rotation
//and translation matrices, in case the cubes are static and you don't want to have to
//call update every frame
Update(D3DXVECTOR3(1, 1, 1), D3DXVECTOR3(0, 0, 0), D3DXVECTOR3(0, 0, 0));
}

```

# Answer
> 2 votes
If you want to draw many identical cubes, you would typically create the vertex and index buffer once - for a cube at the origin - and then re-use it for multiple draw calls. The vertex shader for the cube would include a local-to-world transformation matrix set via a shader parameter, and you'd change the transform for each draw, causing the cubes to appear in different locations and orientations.

Another way is to use instancing. For instancing you'd have two vertex buffers, one containing a single cube at the origin as before, and the other containing a list of matrices, one for each cube. With the correct vertex shader and input layout set-up you can then do a single draw call to render all the cubes. The "inner" vertex buffer (the single cube) would be static, and if you wanted the cubes to move around, the "outer" vertex buffer (the transforms) would be dynamic, and you'd update it once per frame using D3D10\_MAP\_WRITE\_DISCARD.

Instancing is more efficient for drawing large numbers of small objects, but it takes a bit more code to set up. I'd recommend starting by drawing one cube at a time, setting the matrix via a shader parameter. Get that working first; you can worry about instancing later.

---
Tags: c++, directx, graphics-programming, directx10
---


title: Animation in OpenGL using 3D Models

text:
# Question
Title: Animation in OpenGL using 3D Models
I have created a model in Blender. Now i want to read that 3D model in my c++ program. I figured that a model can be exported to various file formats e.g. .obj, .3ds or COLLADA and then can be read in a c++ program. I have been searching web for doing that for quite a while and found many tutorials. But i ran into issues with most of them. For example, IN the Nehe tutorial they are using glaux which I don't want to use in my program. And the remaining tutorials use md2 which is not supported by Blender.
So can anyone guide me which file format to use for exporting 3D model and how to load that in my OpenGL program? Also how can I animate that model? Is it possible to add extra effects like tone mapping after it has been loaded in the c++ program using OpenGL? if yes then how?
P.S. I am using Linux for game developement

# Answer
I'd go for OBJ format. As you have already probably realised, there's hundreds of OBJ loaders for C++ **out there**. I believe one of the most mature ones is **Assimp**, it supports many different formats and it is pretty well documented. **Here** you have an example where they use it.
> 2 votes

# Answer
Blender 2.60 has fixed COLLADA animation support, it was more or less broken in earlier versions. However, if you haven't loaded any model formats yet in your own code, I'd suggest learning to load .obj first. It's in ASCII so it's human readable and easy to read without external loader libraries.
> 2 votes

# Answer
3ds isn't containing any animation data so that one won't work. Collada I don't know much about but when I decided on which format to use in my game I searched and compared a lot and finally I went with the B3D format, it supports skeletal animation and is loadable from Irrlicht (it also contains lighting values).

I use the 'b3d pipeline' exporter from 3dsMax and I have coded my own hlsl shader to animate and light the meshes, it works really well.

You can check out how Irrlicht does it (ie. loading and animating), it does the animation in software though but there are examples if you search a bit on how to do it with a shader (if you want that). A nice thing is that Irrlicht supports both OpenGL and Linux.

Another format that is quite straight forward is the .X format, there must be tons of examples out there on how to export, load, parse and set up the skeleton and animating with it. It is a Microsof format though so maybe you won't want to use it :-)

Tone mapping and such has absolutely nothing to do with animating so yeah if you know how to use that technique you can do that with animated meshes.
> 1 votes

---
Tags: opengl, graphics, animation, models
---


title: creation of a meta-game

text:
# Question
Title: creation of a meta-game
OK, I feel like this should be on meta, because it is a very meta question, but I thought it would be interesting to discuss here. it is relevant and it might provide a little break from coding.

Using these sites you can essentially get a very good answer to any problem. In fact I think it would be safe to say you can pretty much get people to discuss the best algorithm for any given problem.

I was wondering if it would be interesting to create a whole game this way. you would ask the first question for instance:

What type of game would be the best game to make if the project was going to be worked on by an unknown amount of designers and developers?

The answer would be subjective, but people could discuss and after a time the answer with the most votes could be chosen and the question locked out. This would be the hardest question I suppose, because after that you would get more and more technical and the questions would become more and more like the questions you ask on these forums.

What would be the best class structure for this segments of a game?

What would be the best way of testing for collisions etc..

Do you think it would be possible to create a whole game this way? Sorry if this seems bizarre or annoying, but I think it might be worth a try! Think of this as the zeroth question. What do you think?

# Answer
> 7 votes
This kind of question isn't really what SE was designed for ... it works better to have focused, objective questions than to have 100 questions about "What is the best kind of X?" For example, Question 1 in your series is the canonical question that I hate on Gamedev.SE: "I'm about to make a game! What language/platform should I use?!?!?! Please suggest the best possible engine"

I've also seen disaster cases on StackOverflow where a programmer who obviously has no idea how to program tries to use a series of StackOverflow questions to do his job for him. The questions wound up being too localized, and not very useful to anyone other than the OP.

**Addenddum (Meta-Answer)**

What is your goal with this "meta-game"? Would you actually continue building this community-driven game as people answered the questions? Or was this more of a meta-question?

* Are you bored? Go out and make a game.
* Trying to get ideas to make a game? You could take just about any idea and run with it. The biggest challenge in a hobby project is *sitting down and doing it*. It is not hard to come up with seeds for a game itself. See this question What are good games to "earn your wings" with? for some ideas to start with.

---
Tags: game-design
---


# Question
Title: What are heterogeneous coordinate systems and reasons for using them?
The book I'm following for a computer graphics course only talks about homogeneous coordinate systems.

But today, our teacher asked:

> What are the reasons for using heterogeneous coordinate systems?

I cannot find anything about this topic.

# Answer
> 1 votes
Simplicity and approachability. Most people understand heterogeneous systems with a high school level of education. For example: you would typically spend less time figuring out how to interpolate them the first time you attempt it.

They can be visualized. (1, 2) is easer to visualize than (1, 2, 5) - because you first need to eliminate the 5.

Furthermore they can be multiplied by a scalar value with a significant effect. Multiplying a homogeneous coordinate by a scalar achieves nothing. In some problems (`|Velocity| = |Velocity| + |Acceleration| * Time)`) this is important.

If you need to identify infinities they would help there as well.

I would basically take every advantage given in the Wikipedia article and invert it.

# Answer
> 1 votes
Where homogeneous coordinates include both points and vectors, heterogeneous coordinate systems only include one or the other. The basic point being that the homogeneous coordinate system (x,y,z,w) includes in it the ability to take on translations during transformation based on the w value.

In a heterogeneous system, there is no W value, so normals and positions cannot be multiplied by the same matrix to provide correct output, but the fact that you wont be storing the W value can save memory.

For example: if you have a model matrix, and a set of vertices, those vertices might contain positions, normals, texture coordinates, and colours. If you transform your vertices and normals by the same matrix, you want to use homogeneous vectors (where the position has a 1 in the W, and the normals have a 0 in the W) this will mean that when the 4x4 matrix multiply transforms your vertex data, only the position vector will snag the translation component of the matrix. You can think of a matrix multiply as being a element by element multiplication and final tally of each of the axes of the matrix with the elements in the vector.

If your vector X(1,0,0,0) multiplies an identity matrix, the only row it will pull out will be the first one (the first element in the X vector is 1, the rest are 0), and the first row of the identity matrix is (1,0,0,0), so that's how you get no change. If your vector Y(0,1,0,0) multiplies an identity matrix, the only row it will pull out will be the second one (0,1,0,0) Now, if your matrix includes a translation component, you can see why a vector with a 1 in the W will pick up the translation, but a vector with a 0 in the W will not pick up the translation.

If you want to transform heterogeneous vectors by matrices, you must specify (usually by way of which function you call) what your vector is. If your vector is a position, then you call something like MatrixTransformVector, and if your vector is a normal, then you call something like MatrixRotateAndScaleVector.

In short:

* homogeneous = less code, more instructions
* heterogeneous = less memory, more special cases.

Heterogeneous can also be a little simpler when doing collision detection with minkowski sums as you want to subtract one set of positions from another, but doing that with homogeneous position vectors effectively gets you a mesh of normals rather than a mesh of positions,unless you subtract one of the meshes from the origin before doing the minkowski sum, or add the result to the origin.

# Answer
> 0 votes
This is not going to be the best answer, as I have limited knowledge in this field, but the only big advantages that I know of are that they require less information, and they're easier to understand.

A coordinate of (X, Y) representing a 2d point is much easier to interpret than (X, Y, W).

For computing, storing coordinates without the extra homogeneous component means that less memory is needed.

---
Tags: coordinates
---


# Question
Title: Why would you want multiple render targets?
In d3d11, you can bind multiple render targets ID3D11DeviceContext::OMSetRenderTargets. But why would you want to do this?

# Answer
> 14 votes
When multiple render targets are bound, they can each be written to individually by the pixel shader -- it isn't (necessarily) the case that all render targets will get the same image. You could write only the red component into one output, only the blue into another, et cetera.

This is used when implementing deferred rendering for example: position, normal, color, et cetera information are each written to their own render target.

# Answer
> 2 votes
The added benefit to using multiple render targets, as in deferred rendering like Josh mentioned, is that you send the scene's geometry to the vertex shader only once and apply it to different pixel shader outputs, instead of re-sending the geometry for every output you need. This saves a lot of computation time for the GPU. The trade-off for faster GPU performance is higher consumption of frame buffer memory.

---
Tags: rendering, directx11
---


# Question
Title: Tangible benefits to speed-coding your personal game projects
I noticed a few programmers setting time-sensitive challenges for themselves, usually in the area of "write game of type X in Y amount of time" or "write X number of games giving only Y time for each". What are the tangible benefits for setting your workflow in this manner to speed-code for a while? It feels like you have to trade off efficient code to get something done quick. And I suppose adding a final layer of polish isn't a big priority in these challenges, so it's okay to use programmer.

I've made some simple 2D scrolling shooters and puzzle games a few years ago and out of stupidity I deleted most of my code. So now I'm curious about using the speed-coding approach to get a couple simple things done again, and get myself more into game logic.

# Answer
> 16 votes
At least in my experience, certain kinds of programmers are what are sometimes called architecture astronauts.

If you're the kind of person who must abstract everything out in a certain way or is constantly trying to refactor your code so it's more beautiful, or anything like that, having timed sessions where you focus on the end product are a very good exercise. It can reinforce the fact that sometimes a simpler solution can get you to something playable sooner, and therefore you can get into a quicker iteration loop than if you did big design up front.

In contrast to the architecture astronaut, if you're a cowboy programmer, then these timed exercises are probably redundant.

# Answer
> 9 votes
I've never explicitly set deadlines for myself like that, but getting things done quickly can be important when working for yourself.

> It feels like you have to trade off efficient code to get something done quick

When writing a game yourself, efficient code is usually not the problem. The problem is often staying motivated. Getting something that works, even if it's not optimally efficient, can be a big enough motivator to keep you going and *finish* it. You can always go back and refactor later if you end up with something good. Trying to do everything right from the beginning might lead to it never getting finished.

# Answer
> 2 votes
I do this a few times a year; give myself a week to design and implement and release a game.

I do it because I'm a perfectionist. Given my choice, I'd work on a game forever. Having a hard deadline (which I publish in advance) forces me to actually stop developing and to just release the damn game on schedule. Since my personal rule going into these exercises is that I'm not allowed to modify any of these games after their deadline passes, it also keeps me focused on future projects, and not distracted by thoughts of tweaking older ones.

---
Tags: software-engineering, motivation
---


title: Movement prediction for non-shooters

text:
# Question
Title: Movement prediction for non-shooters
I'm working on an isometric 2D game with moderate-scale multiplayer, approximately 20-30 players connected at once to a persistent server. I've had some difficulty getting a good movement prediction implementation in place.

**Physics/Movement**

The game doesn't have a true physics implementation, but uses the basic principles to implement movement. Rather than continually polling input, state changes (ie/ mouse down/up/move events) are used to change the state of the character entity the player is controlling. The player's direction (ie/ north-east) is combined with a constant speed and turned into a true 3D vector - the entity's velocity.

In the main game loop, "Update" is called before "Draw". The update logic triggers a "physics update task" that tracks all entities with a non-zero velocity uses very basic integration to change the entities position. For example: entity.Position += entity.Velocity.Scale(ElapsedTime.Seconds) (where "Seconds" is a floating point value, but the same approach would work for millisecond integer values).

The key point is that no interpolation is used for movement - the rudimentary physics engine has no concept of a "previous state" or "current state", only a position and velocity.

**State Change and Update Packets**

When the velocity of the character entity the player is controlling changes, a "move avatar" packet is sent to the server containing the entity's action type (stand, walk, run), direction (north-east), and current position. This is different from how 3D first person games work. In a 3D game the velocity (direction) can change frame to frame as the player moves around. Sending every state change would effectively transmit a packet per frame, which would be too expensive. Instead, 3D games seem to ignore state changes and send "state update" packets on a fixed interval - say, every 80-150ms.

Since speed and direction updates occur much less frequently in my game, I can get away with sending every state change. Although all of the physics simulations occur at the same speed and are deterministic, latency is still an issue. For that reason, I send out routine position update packets (similar to a 3D game) but much less frequently - right now every 250ms, but I suspect with good prediction I can easily boost it towards 500ms. The biggest problem is that I've now deviated from the norm - all other documentation, guides, and samples online send routine updates and interpolate between the two states. It seems incompatible with my architecture, and I need to come up with a better movement prediction algorithm that is closer to a (very basic) "networked physics" architecture.

The server then receives the packet and determines the players speed from it's movement type based on a script (Is the player able to run? Get the player's running speed). Once it has the speed, it combines it with the direction to get a vector - the entity's velocity. Some cheat detection and basic validation occurs, and the entity on the server side is updated with the current velocity, direction, and position. Basic throttling is also performed to prevent players from flooding the server with movement requests.

After updating its own entity, the server broadcasts an "avatar position update" packet to all other players within range. The position update packet is used to update the client side physics simulations (world state) of the remote clients and perform prediction and lag compensation.

**Prediction and Lag Compensation**

As mentioned above, clients are authoritative for their own position. Except in cases of cheating or anomalies, the client's avatar will never be repositioned by the server. No extrapolation ("move now and correct later") is required for the client's avatar - what the player sees *is* correct. However, some sort of extrapolation or interpolation is required for all remote entities that are moving. Some sort of prediction and/or lag-compensation is clearly required within the client's local simulation / physics engine.

**Problems**

I've been struggling with various algorithms, and have a number of questions and problems:

1. Should I be extrapolating, interpolating, or both? My "gut feeling" is that I should be using pure extrapolation based on velocity. State change is received by the client, client computes a "predicted" velocity that compensates for lag, and the regular physics system does the rest. However, it feels at odds to all other sample code and articles - they all seem to store a number of states and perform interpolation without a physics engine.
2. When a packet arrives, I've tried interpolating the packet's position with the packet's velocity over a fixed time period (say, 200ms). I then take the difference between the interpolated position and the current "error" position to compute a new vector and place that on the entity instead of the velocity that was sent. However, the assumption is that another packet will arrive in that time interval, and it's incredibly difficult to "guess" when the next packet will arrive - especially since they don't all arrive on fixed intervals (ie/ state changes as well). Is the concept fundamentally flawed, or is it correct but needs some fixes / adjustments?
3. What happens when a remote player stops? I can immediately stop the entity, but it will be positioned in the "wrong" spot until it moves again. If I estimate a vector or try to interpolate, I have an issue because I don't store the previous state - the physics engine has no way to say "you need to stop after you reach position X". It simply understands a velocity, nothing more complex. I'm reluctant to add the "packet movement state" information to the entities or physics engine, since it violates basic design principles and bleeds network code across the rest of the game engine.
4. What should happen when entities collide? There are three scenarios - the controlling player collides locally, two entities collide on the server during a position update, or a remote entity update collides on the local client. In all cases I'm uncertain how to handle the collision - aside from cheating, both states are "correct" but at different time periods. In the case of a remote entity it doesn't make sense to draw it walking through a wall, so I perform collision detection on the local client and cause it to "stop". Based on point #2 above, I might compute a "corrected vector" that continually tries to move the entity "through the wall" which will never succeed - the remote avatar is stuck there until the error gets too high and it "snaps" into position. How do games work around this?

# Answer
> 4 votes
The only thing to say is that 2D, isometric, 3D, they're all the same when it comes to this problem. Because you see many examples of 3D and you're only using a 2D octant-limited input system with instantaneous velocity doesn't mean that you can throw out networking principles that have evolved over the last 20+ years.

Design principles be damned when game play is compromised!

By throwing out previous and current you're discarding the few pieces of information that could solve your problem. To those data I would add time-stamps and calculated lag so the extrapolation can better predict where that player will be and the interpolation can better smooth out velocity changes over time.

The above is a big reason why servers seem to send out a lot of state information and not control inputs. Another big reason is based on what protocol you're using. UDP with accepted packet loss and out of order delivery? TCP with assured delivery and retries? With any protocol you're going to get packets at weird times, delayed or piled on top of each other in a flurry of activity. All of those weird packets need to fit into a context so the client can figure out what's going on.

Finally, even though your inputs are very limited to 8 directions the actual change can happen at any time - enforcing a 250ms cycle will just frustrate quick players. 30 players is nothing big for any server to handle. If you're talking about thousands... even then groups of them are split across multiple boxen so individual servers are only carrying a reasonable load.

Have you ever profiled a physics engine like Havok or Bullet running? They're really quite optimized and very, very fast. You may be falling into the trap of assuming operation ABC will be slow and optimizing something that doesn't need it.

# Answer
> 1 votes
So your server is essentially a "referee"? In this case, I believe that everything in your client has to be deterministic; you need to make sure that everything on each client will always give the same result.

For your first question, once the local player recieves the other players' direction, apart from being able to decellerate his movement over time and apply collisions, I don't see how you could predict which direction the player will next turn, especially in an 8 direction environment.

When you recieve the "real position" update of each player (that maybe you could try staggering on the server) yes you will need to interpolate the position and direction of the player. If the "guessed" position is very wrong (i.e. the player completely changed direction just after the last direction packet was sent) you will have a huge gap. This means that either the player jumps position, or you can interpolate to the next *guessed* position. This will provide smoother interpolation over time.

When entities collide, if you can create a determinist system, each player can simulate the collision locally, and they results shouldn't be too far from the reality. Each local machine should simulate the collision for both players, in which case making sure that the final state will be non-blocking and acceptable.

For the server side of things, a referee server can still do simple calculations to check *for example* to speed of a player over short times to use as a simple anti-cheat mechanism. If you loop through monitoring each player over 1s at a time, your cheat detection will be scalable, only it will take longer to find cheaters.

# Answer
> 0 votes
Can you not include velocity in your state change messages and use that to predict movement? e.g. assume velocity doesn't change until you get a message saying it changed? I think you are already sending positions, so if something "overshoots" because of this you have the correct position from the next update anyway. Then you can step positions during updates as you already do using the velocity from the last message, and overwriting the position whenever a message is received with a new position. This also means that if position doesn't change, but velocity does you need to send a message (if that is even a valid case in your game), but that won't impact your bandwidth usage much, if at all.

Interpolation should not matter here, that is for e.g when you **know** where something will be in future, whether you have it, what method you are using etc. Are you confused with extrapolation perhaps? (for which what I describe is one, simple, approach)

# Answer
> -1 votes
My first questions would be: What is wrong with using a model where the server has authority? Why does it matter whether the environment is 2D or 3D? It would make your cheat protection a lot easier if your server was authoritative.

> Most of the samples I saw tightly couple movement prediction right into the entities themselves. For example, storing the previous state along with the current state. I'd like to avoid that and keep entities with their "current state" only. Is there a better way to handle this?

When performing prediction, it is necessary to maintain several states (or at least deltas) on the client so that the when the authoritative state/delta is received from the server, it can be compared with those of the client and you can make the necessary corrections. The idea is to keep as much as possible deterministic to minimize the amount of corrections required. If you don't maintain the previous states, you can't know if something different happened on the server.

> What should happen when the player stops? I can't interpolate to the correct position, since they might need to walk backwards or another strange direction if their position is too far ahead.

Why do you need to interpolate? The authoritative server should override any erroneous movements.

> What should happen when entities collide? If the current player collides with something, the answer is simple - just stop the player from moving. But what happens if two entities take up the same space on the server? What if the local prediction causes a remote entity to collide with the player or another entity - do I stop them as well? If the prediction had the misfortune of sticking them in front of a wall that the player has gone around, the prediction will never be able to compensate and once the error gets to high the entity will snap to the new position.

These are the situations where there would be a conflict between the server and client and is why you need to maintain states on the client so that the server can correct any errors.

Sorry for the quick answers, I've gotta head off. Read this article, it does mention shooters but should work for any game requiring real-time networking.

---
Tags: physics, networking
---


# Question
Title: How do I align the matrix used in SpriteBatch and the matrix used in BasicEffect?
I'm writing a Windows tool that uses XNA and allows the user to place textures on the screen.

I'm using a 'camera' for the SpriteBatch used to draw the textures, e.g:

```
Matrix matrixForSpriteBatch = Matrix.CreateTranslation(
    -_cameraPosition.X, -_cameraPosition.Y, 0.0f) *
Matrix.CreateRotationZ(_rotation) *
Matrix.CreateScale(_scale) *
Matrix.CreateTranslation(
     GraphicsDevice.Viewport.Width / 2,
     GraphicsDevice.Viewport.Height / 2, 0.0f);

```

This is working fine - the user can drop a texture onto the canvas and move, rotate and size it. They can also move the camera around to see more things.

What I now want to do is let the users click around to define points of a polygon. These points are then sent to my `DrawPolygonFilled` method:

```
public void DrawPolygonFilled( SpriteBatch spriteBatch,
        Vector2[ ] worldPoints,
        Color color )
{
    Matrix matrixForVertices =
        Matrix.CreateTranslation( _cameraPosition.X, -_cameraPosition.Y, 0.0f ) *
            Matrix.CreateRotationZ( -rotation ) *
                Matrix.CreateScale( camera.Scale ) ;

    Vector2[] transformedPoints = worldPoints.Transform( matrixForVertices ) ;

    var vertices = new VertexPositionColor[ transformedPoints.Length ] ;

    for (int i = 0; i < transformedPoints.Length; i++)
    {
        vertices[ i ] = new VertexPositionColor( new Vector3( transformedPoints[ i ], 0 ), color ) ;
    }

    Vector2[ ] outputVertices ;
    short[ ] outputIndicies ;
    Vertices.Triangulate( transformedPoints, Vertices.WindingOrder.Clockwise, out outputVertices, out outputIndicies ) ;

    if (outputIndicies.Length > 0)
    {
        foreach( EffectPass pass in _basicEffect.CurrentTechnique.Passes )
        {
            pass.Apply( ) ;

            spriteBatch.GraphicsDevice.DrawUserIndexedPrimitives<VertexPositionColor>(
                Microsoft.Xna.Framework.Graphics.PrimitiveType.TriangleList,
                vertices,
                0,
                vertices.Length,
                outputIndicies,
                0,
                outputIndicies.Length /3 ) ;
        }
    }
}

```

This isn't displaying anything as the client space for `BasicEffect` is 0,0 at top-left, and 1-1 at bottom-right. So I added this to `BasicEffect`:

```
_basicEffect = new BasicEffect( GraphicsDevice )
    {
        VertexColorEnabled = true
    } ;

_viewMatrix = Matrix.CreateLookAt(
    new Vector3( 0, 0, GraphicsDevice.Viewport.Width ),
    Vector3.Zero,
    Vector3.Up
    ) ;

_projectionMatrix = Matrix.CreateOrthographic(
    GraphicsDevice.Viewport.Width,
    GraphicsDevice.Viewport.Height,
    .1f,
    GraphicsDevice.Viewport.Width ) ;

_basicEffect.Projection = _projectionMatrix ;
_basicEffect.View = _viewMatrix ;

```

With this, the polygon is displayed but it's upside-down. Also, when the position of the polygon changes (the user can drag the polygon around with the mouse), the polygon goes up when the user moves the mouse down!

I'm a bit thick (but trying to become less thick) when it comes to matrices and geometry. Am I missing something? I tried changing `Down` to `Up` in `CreateLookAt` but it still didn't draw correctly and now when the user mouses left, then polygon goes right!

Here's a screen-shot when drawing a polygon at 0,0:

The points on the white path are where the user clicked (and are drawn with SpriteBatch) and the yellow polygon is what's drawn by my method above.

Here's another screen-shot that show what happens when I move the polygon to 20,20:

The white path is drawn starting from 20,20, but the filled polygon is starting from 20,-20 and is drawn upside-down

I think this is a matrix issue between the matrix used by the `SpriteBatch` (to draw the white paths) and the matrix used by the `BasicEffect` (to draw the filled polygon).

# Answer
r2d2rigo's answer is *almost* correct. Here is the *correct* matrix code to set up a `BasicEffect` that matches `SpriteBatch` (from Shawn Hargreaves' blog):

```
Matrix projection = Matrix.CreateOrthographicOffCenter(0, viewport.Width, viewport.Height, 0, 0, 1);
Matrix halfPixelOffset = Matrix.CreateTranslation(-0.5f, -0.5f, 0);

basicEffect.World = Matrix.Identity;
basicEffect.View = Matrix.Identity;
basicEffect.Projection = halfPixelOffset * projection;

```

Note the half-pixel offset (explanation, MSDN).
> 6 votes

# Answer
The matrix used in SpriteBatch is created with Matrix.CreateOrthographicOffCenter:

```
Matrix ortho = Matrix.CreateOrthographicOffCenter(0.0f, yourWidth, yourHeight, 0.0f, 0.0f, 1.0f);

```

This way you will retain your world origin at the top left corner.
> 3 votes

---
Tags: xna, xna-4.0, geometry, effects
---