# Question
Title: How to blend two cameras when traveling through a portal in Unity3D
**Before I get to my question, I know the most obvious solution would be to use the normalized view port rect, however I need more complex shapes than a rectangle, and I've looked in to using the view port rect and it seems to not be my solution.**

EDIT: Some people were confused by my question, let me go in to a bit more detail. What's happening is as the player moves in to one portal, I create a clone FPS controller and move it out of the other. This gives me two cameras, and the view you see on the right above. It's just showing one camera, and clipping through the portal. What I want is something similar to this where the cameras blend to create the illusion of a smooth transition. What I want to do is delete everything from the green checker image to the left in the image below, and replace that with the other camera. That way you get the part of camera A's view that is peaking out of the portal, blended with the part of camera B's view that's peaking out of the other portal, to get one complete image. And as you move through the portal the cut changes appropriately.

I've been designing a portal system, I have everything down, including getting the player to smoothly move through the portal. My main problem now is getting that camera blend effect Valve does. I need two cameras to blend together seamlessly, as if you were poking your head through the portal. And it can't just be a rectangle, it has to match however the player is looking through the portal.

My best lead on this right now is to possibly project a depth mask shader behind each portal, then make the camera from the portal you're traveling to be depth only. Then somehow mix the two cameras. My main problem is figuring out exactly how I'd do this, how to make the second camera only render what's outside of the portal, and have the rest default to camera 1 to get one full screen projection.

If you could give me ideas, or explain how I may do this with the depth mask shader that would be a tremendous help. I'll continue to work on this and update as I make break throughs.

# Answer
> 4 votes
The suggested answers were very good, but I ended up going for a different technique using a depth mask.

What you do is take THIS script and shader, you put the script on every object with a renderer in your scene and set the render queue to 3020 (I'll post a script to make this easy later).

Then, you create a box of planes (all facing inwards, in the picture you can't see the side of the box closest to you, but when you're inside the box all you should see is gray) behind BOTH of your portals like so: And set them on to a special layer of their own (I chose "DepthMask" for mine), then you add a material with the shader above to them.

You then take the main camera and uncheck your special layer from it's culling mask (I unchecked DepthMask layer) and set it's depth to 0.

Then when you're teleporting through and clone the camera, set the other camera's clear flags to "Depth Only" and it's depth to 1.

You then get a seamless screen blended between the two camera views.

# Answer
> 7 votes
## Understanding the Problem

From what I can see the problem you are describing is the result of the camera's near plane intersecting the plane defined by the portal. While this intersection occurs you can see behind the wall the portal is on.

This is similar to a problem experienced in other games when the player is just transitioning from above water to underwater. If the camera is just above the water, no post processing effect is applied to obfuscate the players view (make it dark and blurry and blue). So if the bottom of the near plane is just under the water the player can see clearly under water.

If I am correct, you can confirm it by changing the position of this plane when defining the projection matrix. As the distance from the camera origin to the near plane increases, so should the problem.

## The Easy Solution

Making the near plane very close to the camera should almost eradicate this issue. This solution is not a complete one, but will yield a good enough result in the vast majority of cases and it's efficient.

## The Full Solution

If just putting the near plane closer to the camera doesn't satisfy, then you can create a "mask" to blend the images generated by rendering the scene from the player and portal perspective.

Assuming you only allow for portals to be applied to flat surfaces, you can calculate the line of intersection between the camera's near plane and the plane defined by the portal (or the wall on which it lies). This line will split the screen into two parts. Determining which side of the line a screen pixel is on will let you know which render image to use, the portal image or the player camera image.

Keep in mind that if this problem is occurring then the camera view frustum has to be completely within the portal so the intersection line will always cut completely from one screen edge to another.

This link should help with the maths to find the line. The code below should be roughly correct.

The line of intersection is defined using a point on the line and the line direction. Below the intersection direction is calculated using the cross product of the portal normal and the camera view direction (near plane normal). A point on the line is given by casting a ray from a point on the near plane directly towards the portal plane (along the portal normal) and finding the intersection point.

```
Vector3 intersectionDir = Vector3.cross(portalNorm, viewDir);
Ray ray = new Ray(camPos + viewDir * camNearPlaneDist, portalNorm);
Vector3 intersectionPos = ray.intersects(new Plane(portalVert1, portalVert2, portalVert3);

```

Make sure the viewDir is a unit vector. portalVert1, 2 and 3 are just 3 of the 4 vertices used for the portal decal or the surface it's on. There are other ways to define the plane on which the portal lies, but I assume this is the most readily available information.

Once you have these two vectors to define the intersection line multiply each by the view and then projection matrices to get them in screen space.

You can then use a post process shader to blend these images. You select which image to use at each pixel by determining which side of the dividing line the current pixel lies on. This is done by taking the pixel position (which is also the position you use to look up the render target texel) and doing;

```
float d = (pixelX - intersectionPos.X) * intersectionDir.Y - (pixelY - intersectionPos.Y) * intersectionDir.X;

```

The side is given by whether d is more or less than 0. If it's exactly 0, then you're on the line.

For reference on the maths above see this.

This method can also be used when creating a depth mask / stencil buffer for use before rendering from the portal perspective. You can create a full screen quad and use the line to slice it.

---
Tags: c#, unity, camera, valve, portals
---


title: generating animations in runtime

text:
# Question
Title: generating animations in runtime
i am creating my 3d game engine using Opengl.

this question might sound stupid to you but i am still in the process of learning, i have a 3d animated girl that slaps guys of different talls on the face.

however the animation is specified for a tall say 1.85CM. when i want her to slap a guy that is 1.60CM tall then she slaps the space over his head.

do i have to create animations for the girl slapping different talls of guys?!

this would be a lot of work, i hope you give me some insight about how such thing are handled.

also could you please give me some resource on generating animations in runtime?

to get my idea for example take a game like fight night, a head punch would be directed to the head no mater how the tall of the other guy is.

# Answer
> 4 votes
Technique you are searching for might be *Inverse Kinematics*. In short the input is the desired global pose of single joint (hand of your woman slapping 1.6m guy) which is the end effector. You solve for the local poses of other joints in your animation that will bring the end effector to desired location.

It's explained in detail in Jason's Weber article called "Constrained Inverse Kinematics" in this book. Unfortunatelly I don't know of any good web articles but it might give you an idea what to search for.

# Answer
> 2 votes
If it is just for this single situation of slapping faces, **you could simply overwrite the shoulder pitch angle**. You could probably work out what it should be with some simple trig, but I would just find values empirically for each male. Of course a full inverse kinematics solver is better, but if your cases are so limited, a simple hack is a better option.

---
Tags: c++, opengl, animation, scripting
---


title: Smoother controls

text:
# Question
Title: Smoother controls
I am trying to move my background left if the user hits the right key. and right if the user hits the left key, so that it will look like the player is moving.

The problem is that whenever I hold the right key, there is a pause of 1 second, then the background moves to the left. I want to make it smoother so that if the user holds the right key, the background moves left immediately.

Note that the background is a 2d int array with just 2's in it, and in Paint I am drawing a green rectangle, so the background is green.

main.java

```
.....
public void keyPressed(KeyEvent e){
   int keys = e.getKeyCode();

    if(keys == KeyEvent.VK_RIGHT)
    {
        level_class.hitRIGHT();  //move camera left
    }
    else if(keys == KeyEvent.VK_LEFT)
    {
        level_class.hitLEFT();  //move camera right
    }
    }/*** end of key pressed method ***/

    /*** KEY RELEASED ***/
    public void keyReleased(KeyEvent e)
    {
        int keys = e.getKeyCode();

            if(keys == KeyEvent.VK_RIGHT)
            {

            }
            else if(keys == KeyEvent.VK_LEFT)
            {

            }
    }/*** end of key pressed method ***/

```

Level class:

```
public class levels {
//note my array is alot bigger than this. i just made a small one here
    private int map01[][] = { { 2, 2, 2 },
                            { 2, 2, 2} };

    int camera_pos_x = 0;
    int camera_pos_y = 0;
    int camera_speed = 5;   //camera speed

    .....
    /*** move camera left ***/
public void hitRIGHT()
{
    camera_pos_x += camera_speed;
}
public void hitLEFT()
{
    camera_pos_x -= camera_speed;
}

    public void paint(Graphics g) {
        for (int y = 0; y < map01.length; y++) // rows
        {
            for (int x = 0; x < map01[y].length; x++) // cols
            {
                if (map01[y][x] == 0)
                {
                    g.setColor(Color.green);
                    g.fillRect(x * tile_size - camera_pos_x, y * tile_size -camera_pos_y, tile_size, tile_size);
                }
            }
        }// end of main for loop
    }// end of paint method
}

```

# Answer
Yes, as ScrambledRK said, you should be settting flags. You should create 2 boolean variables:

```
Boolean left_key_down = false;
Boolean right_key_down = false;

```

and set them to appropriate values in the event listeners:

```
public void keyPressed(KeyEvent e) {
   int keys = e.getKeyCode();
   if(keys == KeyEvent.VK_RIGHT)
   {
      right_key_down = true;
   }
   else if(keys == KeyEvent.VK_LEFT)
   {
      left_key_down = true;
   }
}
public void keyReleased(KeyEvent e)
{
   int keys = e.getKeyCode();
   if(keys == KeyEvent.VK_RIGHT)
   {
      right_key_down = false;
   }
   else if(keys == KeyEvent.VK_LEFT)
   {
      left_key_down = false;
   }
}

```

Then, do your motion in your main update loop based on those flags.

```
// main loop blah blah
if( left_key_down ) hitRIGHT();
if( right_key_down ) hitLEFT();

```

That *should* result in smooth motion.
> 2 votes

# Answer
you are prob. better of checking the key-pressed status every frame and using the key-listener to just flag the key as pressed (using a map/array with the keycode as key).

I'm not familiar with java, but flash has the same issue. The reason might be related to the way a frame is split up internally and the fps your app runs in similar to the AS2/AS3 VM
> 0 votes

---
Tags: java, movement, control
---


# Question
Title: How to develop multi-player game without involving server side code?
There have been lot of cloud based frameworks released in past few years. They provide real-time communication among users but does not allow developers to write server side code. So, how can we use these frameworks to develop mulitplayer games.

I want to know how we can deal with network latency and write prediction algorithm to recover network lag.

# Answer
I am not really familiar with cloud based frameworks nor using them for network related game development. However, I am familiar with ways on multiplayer game development, where you get to code the part of the game that will handle network packets.

It is more of a choice of the network protocol actually, TCP/IP or UDP.

TCP/IP is a good choice if your game do not require realtime updates, like turn based games (tic-tac-toe, chess and the like).

However, when we talk about speed and close to real time updates, UDP a lot more favorable. UDP is stateless, meaning that when you send something, you don't care whether if the user received the data or not, nor are you expecting a reply which reduces the overall size of the packet (no more additional headers) and it does not require a thread to wait for a response.

TCP/IP on the other hand works the other way around. It sends and receives, and during the receive period, the application/game has to wait for the response, otherwise a time out exception may occur which you might manually handle in code.

UDP works on fast update games because all the game has to do is to send its current state to everyone else, and everyone else just read whatever it receives and render them into the game.

About the question, "How to develop multi-player game without involving server side code?"

I'm not really sure it can be done. Sooner or later, whether UDP or TCP/IP is used, there always has to be a managing entity of all the packets running around the game (the computing unit that handles the current state of all users). I'm pretty sure that is the server, and that server requires some code.

I hope I hadn't misinterpreted your question. Cheers

Very good reference:

http://gafferongames.com/networking-for-game-programmers/
> 1 votes

---
Tags: game-design, networking, multiplayer, cloud-computing
---


title: How much lines of code is 1kB?

text:
# Question
Title: How much lines of code is 1kB?
My friend told me that it's something about 40 lines of code for 1kB.

For an old 8-bit computers with 48kB of RAM it is only 1920 lines of code!

Then when I think about it, it seems to me incredible that sometimes my CSS files have more than 2000 lines of code.

How can somebody create something like a game e.g. Dizzy on the ZX Spectrum within 2000 lines available?

Even if they have used assambly or machine code for some parts it seems to me incredible.

Is really 1kB about 40 lines of code or is it different?

# Answer
> 10 votes
1 kB = 1024 Bytes.

Most of programming languages have 1 Byte = 1 character, so:

* If your lines are 1 character long, 1 kB = 1024 lines
* If your lines are 1024 characters long, 1 kB = 1 line
* If your lines are 25 characters long, 1 kB = about 40 lines

BTW. if your programming language is compiled, it has nothing to do with memory-efficiency.

BTW2: There is a very interesting site JS1K, where people submit cute things that use 1024 Bytes of Javascript code.

# Answer
> 2 votes
Especially in the time of games like Dizzy your code was compiled something as long as this

```
while(myLongVariable < 10)
{
    myLongVariable++
}

```

Would become (line numbers added for clarity, some pseudo assembly code here)

```
10: cmp_s r1 10 40
20: add r1 1
30: jmp 10
40:

```

Now this is a textual representation of pseudo assembly, but actual assembly is not in a text format but is binary which is even smaller. In very old games like Dizzy they also use a lot more tricks by jumping through memory.

---
Tags: memory-efficiency
---


title: C++ Game Library for SVG Based Game

text:
# Question
Title: C++ Game Library for SVG Based Game
I'm looking into building a cross-platform opensource 2D RPG style game engine for ChaiScript.

I want to be able to do all of the graphics with SVG and need joystick input. I also need the libraries I use to be opensource and compatible with the BSD license.

I'm familiar with allegro, ClanLib, and SDL. As far as I can tell, none of these libraries have built in or obvious integration for SVG. Also, I'm aware of the previous conversations on this site regarding Qt for SVG game development.

I'm hoping to avoid Qt because of the size and complexity of making it a requirement. Also, Qt does not seem to have joystick input support, which would require that SDL or some other library also be used.

So my question can be summed up as this:

* What is the best way to get SVG and joystick support in a 2D C++ library while minimizing dependencies as much as possible (preferably avoiding Qt altogether)?

# Answer
> 2 votes
I don't see any reason why you couldn't use SDL or another input library with a 2D graphics library like libcairo.

As for ChaiScript, have you heard of Lua?

# Answer
> 2 votes
> I'm familiar with allegro, ClanLib, and SDL. As far as I can tell, none of these libraries have built in or obvious integration for SVG.

Has it ever occurred to you to ask... why that is?

Sure, SVG is a complicated specification to implement on a basic "getting the XML into memory and validating it" level. But I don't think you fully appreciate the simple fact that SVG rendering *is not fast*.

Web browsers are fast if they render a webpage in less than 500ms or so. SVG images may take 20ms+ to render, and that's for small, simple ones. Something you might find in a game, a non-graphically-trivial game, are going to take much, *much* longer. SVG image rendering is not intended for fast animation.

Even something lower-level like libCairo isn't exactly a high-performance renderer. Sure, it's fast enough for a browser, but it isn't exactly blazing in its software-rendering performance.

In short, I would ditch SVG entirely and see if libCairo can serve your needs. That's just for evaluation purposes, to see if it performs fast enough in circumstances that approximate the purpose you intend for them. Once that's determined, you can decide what to do next in terms of technology (Qt, SDL, whatever).

# Answer
> 1 votes
In regards to this SVG is not the best for generating on-the-fly content and for real-time rendering, even in 2d, however....

If you were to use the SVG files to make your original content you could then have a pre-level/area generation phase with appropriate loading screen/cut-scene where you would use the SVG content to render standard images of the resolution you need, this would allow you to code simply with normal images as whilst retaining the flexibility of the SVG for multi-resolution targeting. It is not idea but this way you can leverage the hardware to play with the prerendered images in the way it was designed to do, rather than trying to generate content on the fly from SVG files. As the computer would only be displaying the loading screen/cut-scene you could dedicate a huge proportion of available resources to generating the standard images from SVG and therefore do it in a fast and efficient fashion.

# Answer
> 0 votes
Irrlicht have SVG and joystick support

---
Tags: c++, svg, joystick
---


title: Input handling with callbacks

text:
# Question
Title: Input handling with callbacks
I have set up a class for input handling that allows me to create key bindings with different key behaviours such as single press action bindings where the action will only happen once if the key is held, and state like actions to make things happen more than once.

In the constructor of the key handler class I pass in the value of the key to bind to and a pointer to a callback function to be called as necessary. My problem comes when I try to pass the pointer to the function in to the constructor since the method I am trying to pass is a member function of my main game class.

I know of solutions that involve making the members static but my problem here is that doing so would require for me to change the signature of every method which has to take the pointer as a parameter and doing so would impact upon the re-usability of my input class for other projects.

Are there any other solutions to this problem that wouldn't involve changing the signature of the methods to accommodate the member function?

# Answer
> 1 votes
Sounds like you need delegates. Try boost::bind or FastDelegate.

Essentially, these will allow you to write:

```
boost::function<void()> f = boost::bind(&MyClass::onEscPressed, myClassPtr);

```

That is, a delegate can act as a pointer to method + pointer to the object on which the method should be invoked. Boost::bind can actually do much more than that, because it can bind any almost any variable and allow functions with arguments and return types (like a clojure):

```
float pi = 3.14;
function<float(int)> f = (&MyClass::something, myClassPtr, pi, _1);

```

Don't get carried away, there is a performence cost :) Unnoticeable for input handling, but no so cool for commonly executed code (for example, I got burned by using boost::bind for collision detection once. Silly idea anyways).

# Answer
> 1 votes
This is the approach i've seen implemented in a number of games, and while it isn't a quick and dirty approach, it is a relatively good design I feel. When reacting to input within the game, you want to provide the ability to bundle functionality into particular events or actions, as well as provide access to raw values for something such as mouse positions.

Dispatching raw input is relatively straightforward, and providing the ability to react to specific events allows you to decouple your application code from the input itself. For instance, if you have your "CharacterController" class (which would implement an input listener interface) listening for jump events, then the character controller doesn't care in the slightest bit whether jump is space bar, or left-ctrl. Without this event based decoupling, any changes to your input map would require additional changes to your game specific code.

Writing an input manager that acts as a central dispatcher, and uses an input map (a list of keys mapped to actions) to distribute events to classes that implement an input listener interface is the summary of my proposal. At its simplest the listener is just a pure virtual function accepting an input event, and the input map a set of key/event-list pairs.

# Answer
> 1 votes
To solve your function signatures problems, people usually use function adapters and binders, you have different options that I can think off:

**Using boost::bind:**

* using boost::bind is convenient you can bind almost any function, you can even use member functions as callbacks.
* regarding performance boost::bind uses alot of small heap allocations which might not be a good idea in a performance critical applications (e.g. as Liosan mentioned Collision Detection). But anyway you should always profile and measure before judging.
* Will introduce dependency on boost (might not be a problem for you).
* Is Compatible with boost::function; which makes it even easier to move function objects around.
* boost::bind is not compatible (directly) with function pointers, so you won't be able to pass functions using bind as function pointers. both Win32 API and SDL use pure function pointers.
* boost::bind "might" be inlined by the compiler, though boost::function will prevent inlining.

**You can use static functions as Adaptors**

* Need to write alot of static functions.
* No heap allocation.
* You can still "bind" member functions using the "unsigned int arg" by sending the pointer "this" of your object example:

````
class C
{
public:
    void EventHandler(void)
    {
        //Your Logic
    }

    static void OnHelper(unsigned long context) // you can send this as callback, and internally call your member function.
    {
      C* thisInstance  = reinterpret_cast<C*>(context); // Crash if used the wrong type
      thisInstance->EventHandler();
    }
};

````

**Writing your own function object adapter**

* You can customize it for your specific needs (example make it directly compatible with function pointers, be careful that the standard directly states that function pointers should not be stored in data pointers).
* You may only need 2-3 parameters avoiding all the complexity boost::bind provides.
* Will learn a couple of things (in case you have time).
* Can be hard and/or time consuming.
* No boost dependency.

**as a side note Using STL Solution**

* STL introduced std::mem\_fun, std::bind1st, std::2nd which can be useful in your case.
* C++11 introduced lambda expressions (also part of boost) but I don't have experience with either.

---
Tags: c++, input
---


# Question
Title: Is there an alternative to SDL 1.3 for a C++ game that should run on iOS and Android?
I've used SDL for many desktop games, always as the cross-platform glue for:

* Creating a window
* Processing input
* Rendering images
* Rendering fonts
* Playing sounds/music

It has never disappointed me at those tasks.

But when it comes to graphics, I prefer to work with the OpenGL API directly, even though all of our games are 2D.

In the project I'm currently working on, I've made sure to only use the API subset supported by both OpenGL 1.3 and OpenGL 1.0, so making the thing run on Android should be easy, I thought.

Turns out there is no official Android or iOS port of SDL yet. However, there's one in SDL 1.3, which is still in development.

SDL 1.3 doesn't seem very appealing to me for three reasons:

1. It's been in development for at least 4 years, and I have no idea when it will be done, not to mention stable.
2. It's not ported to as many platforms as SDL 1.2.
3. From what I've seen, it uses OpenGL for drawing, so I suppose the community will move away from directly using OpenGL.

So I'm wondering if I should use a different library for our current project - it doesn't matter much if I need to port my existing code from SDL 1.2 to SDL 1.3 or to some other library. We're planning to release on Windows, Mac OS X, Linux, iOS and Android, so good support for these platforms is essential.

Is there anything stable that does what I want?

# Answer
SDL 1.3 is now called SDL 2 now. Also, I've been using it, and it's quite stable (I'm using OS X, so that should say something). It is in development, however even if it does get to a point where it is unstable, I'm sure the developers will fix it quite fast (it is under active development; commits are made to the repo often). I've personally never pulled from the repo and had a compile error, or runtime error.

Anyway, I think a good alternative to SDL would be Allegro 5, which does support iOS (not 100% sure about Android), and is in a stable release. Allegro 5.1+ is under development, not allegro 5.
> 1 votes

# Answer
You can try the Marmalade SDK which is not open-source or free but has an affordable price: http://www.madewithmarmalade.com/
> 0 votes

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


# Question
Title: How does a 2D game like Zelda handle the character being behind buildings where only part of him is shown?
I'm trying to develop a simple Zelda-style game. I found this very useful topic

How did LoZ: A Link to the Past handle sub-tile collisions?

that I'm using as reference to develop my collision detection mechanism. However, there's something I've failed to understand. When Link is behind buildings, only part of him is shown. Can anyone please help me understanding how this effect can be achieved? Isn't the building part of the background?

# Answer
2D Tiled games usually have more layers which renders in different layers - some renders in the background others above the player.

That part of the roof renders above the player and that's why player can go behind that building.

Here is the image example from my game to explain better:
> 32 votes

# Answer
While Blodyavenger's answer covers how it is most likely done, here's another possibility which would allow for easy perspective switching (e.g. four or eight different directions, or some camera elevation levels):

Consider the top-down view of your map, e.g.

```
  ABCDEFGHIJKL
1 +-----=----+
2 |  .    .  |
3 |    X   o |
4 | .        ||
5 |    .   . |
6 +--=-------+

```

Where, say, `X` marks a high pillar. For each object you store images of all possible perspectives (or use the same...), which may be arbitrary many tiles high. Now when drawing, simply start with the column or row that is on the back in the current perspective, e.g. row 1 if looking from south. After that draw the row/column the second-most to the back and so on. This way, when something is higher than one tile (stretched to the current perspective), it will simply overdraw what lies behind.

(Sorry for the lack of nice pictures, I'm not too good at *applied* graphics...)
> 5 votes

# Answer
You should have a variable for depth , and have the images with biggest depth drawn first , then the others with lowest depth. And the depth of each object should equal the negative of its y coordinate.

`Depth=-y`
> 1 votes

---
Tags: 2d
---


title: C++ SDL/SFML advancing help

text:
# Question
Title: C++ SDL/SFML advancing help
I've been playing around programming using SDL and SFML for a while now and done all the basic tutorials I can find(love lazyfoo).

but I'm stuck and not sure how to move on from simple games like Pong.

Could someone help point me in the right direction, I have a good understanding of the code I've worked with however not entirely sure how to apply it to more adventurous projects.

Is there a good game design theory site someone could recommended?

Any help or direction is really appreciated, let me know how you learnt and progressed :)

# Answer
> 2 votes
The best way to learn how to make more complex games is to start making more complex games. Just make games and on that path you'll meet with new problems which you'll solve at that time. Theory is nothing without practice - you'll easily forget it without applying it.

Once again, just **make games**! If you need ideas, I suggest you to take a look at this list:

“I Need Practice Programming”: 49 Ideas for Game Clones to Code

Pick one game and start working on it. After each game you'll have more experience until you'll be experienced enough to make what you wish.

---

I started with Pong -\> Tetris -\> Sokoban -\> My own ideas -\> My current game

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


# Question
Title: Powers of 2 textures in Android 2d games?
I've read a lot about the importance of using powers of 2 png's for textures when using OpenGL ES. However, how does this relate to Google's own documentation regarding the resizing of graphics for the various screen density's. I will explain:

Let's say I have a 256 x 256 texture that I use for in the XHDPI folder for use on Extra High Density screens. Using Google's own recommended scaling factors, I would scale this by 75% to use in my HDPI folder, it would then become 185 by 185 which isn't a power of 2?

Could someone clear this up for me?

As noted, I'm asking specifically with regards to 2D sprites using quads.

# Answer
> 2 votes
Regarding scaling up or down your textures: no, absolutely not. The DPI/scaling factors are for readability of icons. It doesn't change the data inside the images. Having a very high density screen is akin to making a PC game designed to run on a monitor with a high resolution. You need to prepare for it, but not by simply scaling your texture assets.

The power of two recommendations are for graphics hardware's ability to manage ram efficiently. For instance, some graphics libraries and hardware can only handle mipmap generation if the texture has an easily divisible (or bit-shiftable) number. Modern, dedicate hardware doesn't really care, although they are probably still optimized to handle power-of-two more efficiently.

The screen density/scaling recommendations are generally ridiculous (IMO). Don't use them as your guide for graphics programming.

---
Tags: android, textures, sprites, opengl-es2, png
---


# Question
Title: Do larger sprite sheets improve performance in html 5 games?
I know when I did some game development with XNA they recommended that we try to group are sprites into fewer sheets because the graphic card could process it faster. Does this also apply to web based games?

**Note**: Not sure if this makes a difference but most of my artwork is pretty defined by separate levels. In other words I'm not really reusing artwork across levels, which kind of made me wonder if I should be loading sprites that never get used just for the sake of grouping them into a spritesheet.

# Answer
The idea behind condensing sprite sheets is that the actual loading of the file (the sprite sheet) is considered heavy lifting in any game system. Imagine you have this system where all your data types are highly optimized and all these algorithms to reduce the memory foot print but then you have to constantly bottle-neck memory with loading and parsing files.

However, I wouldn't say packing "all" sprites on to one sheet would be a good idea. Creating sheets specific to each level could be a better approach. I wouldn't see any point in having large sprite sheets where significant portions may never be used in a user's game session.
> 5 votes

# Answer
It is not only the memory footprint you have to think about but also the number of requests the client is making to the server to fetch the images.

By default the maximum number of parallel requests is 2 but some browsers ignore this.

If you have many images then this will become a bottleneck.
> 1 votes

# Answer
In my game engine, I load the sprite sheet once, parse it upon load completion, calculate indices and animation frame data, and it's ready to go. It's extremely fast, and the only level loading is done dynamically as the player progresses through the game world.

YMMV, but consider either background-loading, or loading everything at startup and caching it client-side using manifest/caching.
> 0 votes

---
Tags: sprites, html5, performance, spritesheet
---


# Question
Title: Separate renderng thread in Android (OpenGL ES 2.0)
I'm used to mainly working with the Canvas SurfaceView API on Android and have recently been learning openGL ES 2.0

With canvas I know that surfaceView gives you the ability to start a new thread to render on, but it doesn't specifically do this for you, so I was creating a new thread and managing that thread when the app was ended / paused etc....

However, from what I've read with glSurfaceView it seems that this is actually done for you automatically? Does this mean I don't actually need to manually create / start and manage my own rendering thread? (I'm talking specifically about a rendering thread (which could also be used for logic updates) which is separate the main UI thread.

Clarification on this matter would be greatly appreciated.

# Answer
All rendering is done on a separate thread, and this is done for you automatically. The documentation is very explicit about this (quoted from http://developer.android.com/reference/android/opengl/GLSurfaceView.Renderer.html) :

> **Threading**
>
> The renderer will be called on a separate thread, so that rendering performance is decoupled from the UI thread. Clients typically need to communicate with the renderer from the UI thread, because that's where input events are received. Clients can communicate using any of the standard Java techniques for cross-thread communication, or they can use the queueEvent(Runnable) convenience method.

This means you do NOT have to create and manage a rendering thread yourself.

I hope this clarifies the matter :)
> 5 votes

---
Tags: android, opengl-es2, multithreading
---


title: View port for my canvas game

text:
# Question
Title: View port for my canvas game
I am developing a canvas game, and im struggling to get my head around how i can make a view port so when the character moves the world moves with it.

Unlike traditional 2d maps built with arrays i have loaded in a json file from tiled map editor and here is the code where the images get drawn to the canvas:

```
this.draw_layer = function(layer){

    var size = data.tilewidth;
    layer.data.forEach(function(tile_idx, i) {
        if (!tile_idx) { return; }
        var img_x, img_y, s_x, s_y,
            tile = data.tilesets[0];
        tile_idx--;
        img_x = (tile_idx % (tile.imagewidth / size)) * size;
        img_y = ~~(tile_idx / (tile.imagewidth / size)) * size ;
        s_x = (i % layer.width) * size;
        s_y = ~~(i / layer.width) * size;
        ctx.drawImage(Level.tileset, img_x, img_y, size, size,
            s_x, s_y, size, size);
    });
};

```

Here is the update function for my character:

```
this.update = function(elapsed) {
    var prev_X = x;
    var prev_Y = y;
    collided = false;

    switch (this.keys[this.keys.length - 1])
    {
        case 37:
            // move the player left on the screen
            x -= this.moveSpeed * elapsed;
            break;
        case 38:
            // move the player up on the screen
            y -= this.moveSpeed * elapsed;
            break;
        case 39:
            // move the player right on the screen
            x += this.moveSpeed * elapsed;
            break;
        case 40:
            // move the player down on the screen
            y += this.moveSpeed * elapsed;
            break;
    }

    if (x < 0)
    {
        x = 0;
    }
    if (x >= gameW - w)
    {
        x = gameW - w;
    }
    if (y < 0)
    {
        y = 0;
    }
    if (y >= gameH - h)
    {
        y = gameH - h;
    }

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

        var block_x = collision_array[i][0],
            block_y = collision_array[i][1],
            block_w = collision_array[i][2],
            block_h = collision_array[i][3];

            if ((x < (block_x + block_w) && Math.floor(x + w) > block_x)
                && (y < (block_y + block_h) && Math.floor(y + h) > block_y))
            {
                if(collision_array[i][4] == "dialogue"){
                    dialog.say(collision_array[i][5])
                }
                else if(collision_array[i][4] == "object"){
                    dialog.set_inv(collision_array[i][6]);
                }
                else{
                    $('#dialog').hide();
                    x = prev_X;
                    y = prev_Y;
                }
            }
    }
    return {
        'pos_X':x,
        'pos_Y':y
    };
};

```

SO my question is, for the way i am loading my maps, how would i create a view port to move the map whilst the player is moving?

Also what do i do with the character when the view port reaches an edge of the view port? How would i let him move to the edge too?

Thanks for you time

# Answer
> 1 votes
Have a look at canvas.translate. To scroll your view of the map, use translate to move the origin of coordinate system relative to the `canvas` element on your page.

To put it another way: Instead of scrolling the "viewport" around the map, the viewport remains stationary and you just move the entire canvas.

Then the trick is, getting the character's position and calculating the required translation. You'll (probably) need to stop scrolling when you hit the side of a level, for example, to avoid viewing graphics space which is "out of bounds".

For reference, many graphics interfaces in many libs and languages have some sort of `translate` function, but they behave differently. For example, the java.awt.Graphics.translate is *absolute*; each time you call it, the translation occurs in relation to the default origin of `(0, 0)`. So if you call `graphics.translate(10, 20)`, the graphics origin will be moved/scrolled 10 pixels on the x-axis and 20 on the y-axis. Calling this function again with the same args will not do anything; the new origin will remain at `(10, 20)`.

By contrast, `canvas.translate` is *relative*, meaning that each time you call it the translation occurs in relation to the current origin. If you call `canvas.translate(10, 20)`, the origin will be moved to `(10, 20)`. If you call `canvas.translate(10, 20)` again, the origin will be moved to `(20, 40)`.

---
Tags: javascript, html-canvas, viewport, jquery
---


title: Cannot get 3D mouse coordinantes

text:
# Question
Title: Cannot get 3D mouse coordinantes
I'm using `viewport.project()` to find my mouse position in 3D space. I have my projection, view and world matrices defined in the same area that they are used to draw the model. Code is below:

NOTE: Please forgive the awful mess, I've been working on this for two weeks and to no avail. EDIT: It is notable to mention that I have disabled rotation in case it affected my mouse position. It did not. Here is the method that I'm calling to get the mouse position.

`viewport.Project(New Vector3(mousePos.X, mousePos.Y, 0), projection, view, world)`

```
Dim transforms() As Matrix
transforms = New Matrix(Model.Bones.Count) {}
Dim campos As Vector3
campos = New Vector3(0.0F, 0.0F, 5000.0F)
Model.CopyAbsoluteBoneTransformsTo(transforms)
For Each Mesh As ModelMesh In Model.Meshes
    For Each effect As BasicEffect In Mesh.Effects
        effect.EnableDefaultLighting()
        camTarget = New Vector3(0, 0, 0)
        myScale.X = 0.2
        myScale.Y = 0.2
        myScale.Z = 0.2
        effect.View = Matrix.CreateLookAt(campos, New Vector3(0, 0, 0), Vector3.Up)
        Dim translationMatrix As Matrix
        effect.World = transforms(Mesh.ParentBone.Index)
        world = effect.World
        effect.World = effect.World * Matrix.CreateScale(myScale)

        '   effect.World = effect.World * Matrix.CreateRotationY(CSng(MathHelper.ToRadians(CSng(Rotation)))) * Matrix.CreateRotationY(MathHelper.ToRadians(-90.0F))
        effect.World = effect.World * Matrix.CreateFromYawPitchRoll(1.0F, 1.0F, 0.0F)
        translationMatrix = Matrix.CreateTranslation(WorldPos + New Vector3(Offset.X, Offset.Y, 0))
        effect.World = effect.World * translationMatrix
        WorldPos += MovementRay * Speed

        effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(60.0F), Camera._aspectRatio, 1.0F, 100000.0F)
        'effect.Projection = Matrix.CreateOrthographic(Viewport.Width, Viewport.Height, -5000, 5000)
        projection = effect.Projection

        view = effect.View

        'Testing

        'Testing

        If Selected = True Then
            effect.AmbientLightColor = Color.Green.ToVector3
        End If
        ScreenPos = Viewport.Project(WorldPos, effect.Projection, effect.View, effect.World)
        Mesh.Draw()
    Next
Next

```

My mouse position only occasionally actually produces a reasonable result- every other time, it's completely off and it throws my calculations. What am I doing wrong?

# Answer
> 2 votes
You are using the wrong method?

**Project**

http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.viewport.project.aspx

> Projects a 3D vector from object space into screen space.

As you can read there Project is from world coordinates to screen coordinates (even though it returns a Vector3). If you want to know what your mouse hovers over you should use UnProject:

**UnProject**

http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.viewport.unproject.aspx

> Converts a screen space point into a corresponding point in world space.

Note that of course unprojecting will only give you a ray, since given only the camera and 2D mouse coordinates you still don't know the depth. You can find the exact position by finding the closest point of intersection with the ray and your geometry.

---
Tags: xna, 3d, mouse
---


# Question
Title: Write a 2d game that is portable to mobile, browsers and computers?
I would like to develop some 2D and 2D Isometric games. Anything ranging from Tetris to Terraria style games. My problem is that if I develop said game for a PC user, I want to be able to port it web browsers and mobile platforms, and easily. And by easy, I mean I want to develop something which can run in all 3. Perhaps I can isolate the gaming logic, graphics and input logic too. But I don't want to rewrite major components. So I will need to work with an engine that runs on all of those, or at least 2 out of 3 (mobile, computer, browser). I considered Java applets but for some reason those are the most unpopular method for playing online web games. There are just so many decent flash games, the only applet based game I can think of is runecraft and that is pretty old.

# Answer
My standard advice to anyone who asks this question (or similar) is: **DON'T**.

You're starting out, you want to make a first game, you're making the engine yourself, *by definition you have no idea what you are doing*.

You need to learn so so much; how to structure a game loop, how to handle timing, how to handle input, networking, sound, display, possibly networking, communication between a client and server, storing and update of game states.

On top of that you *also* want to run it on multiple platforms for which a considerable proportion of this functionality is going to range from being completely different to having weird corner cases and gotchas that need to be handled.

Forget it. *You have enough to be getting on with in the first batch of stuff you need to learn*. Adding multiple platform support *on top of that* is going to spread yourself too thin.

Now, there's absolutely nothing wrong with supporting multiple platforms; it's a great thing, but your job right now is not to support multiple platforms, it's to learn the basics of how to build a game. So focus on one thing at a time, assimilate it, then move onto to the next, because taking on all of this together is too much.

So, for the first game, pick a single platform, learn how to set things up properly and get them working on that. Once you know how to handle input, timing, networking, whatever properly on a single platform, *then* you can go and port it.

Otherwise take the (IMO good) advice in the other answer and forget about the engine, use something like Unity that handles all of that stuff for you (somebody else has suffered so you don't have to) and focus on the game itself.
> 5 votes

# Answer
Unity of course. With it you can develop games on: Windows, Linux, Mobiles and Web. Have a look at http://unity3d.com/learn. Hope it can help you.
> 1 votes

# Answer
With Libgdx you can write your game once and share it to Windows, Android, Web, Mac. http://libgdx.badlogicgames.com/
> -1 votes

---
Tags: porting
---


# Question
Title: How do I make an entity move once per second in crafty.js
I am trying to implement "Snake" using crafty.js but I can't seem to get the snake entity to move just once in a second. How do I do this?

# Answer
You could use the timeout method from Crafty core functions.

First argument is the function to be executed, second argument is the time in miliseconds

```
Crafty.c("Snake",{
  init: ...
  move: function() {
      //code for movement
      this.timeout(move, 1000);
  }
});

```

or you can pass an anonymus function as argument

```
this.timeout(function() {
//code code coode
}, 1000);

```

source: http://craftyjs.com/api/Crafty-Core.html#-timeout

*Sorry if i my English is bad*
> 0 votes

---
Tags: javascript, grid, crafty
---


# Question
Title: Finding moves with multiple jumps in checkers
I'm currently working on a minimax implementation for a game of checkers in C#. The minimax itself works fine if you ignore a few bugs I've yet to fix, but I'm having some problems finding a way I can properly create lists of 'Chain' moves, or moves with multiple jumps.

I've made several attempts at building a function which would take an attacking move and run it through some recursion to find all the possible branches, but so far the main result is that no attack move at all has been working.

Anyhow I'd appreciate some pointers on how to go about generating all the attack moves that could follow as a result of an attack. I'm guessing some form of recursion is going to be necessary at the very least.

# Answer
> 3 votes
each time you find a jump check on the resulting board if that piece can jump again

this is easiest if you can clone a board state (or restore it again after the recursion)

basic code to find longest jump chain (easily adapted to find all jumps)

```
maxjumps;
foreach(piece: board){
    if piece.color = currentplayer
        jumps = canAttack(piece,board)
        if jumps.count>maxjump.count
            maxjump = jumps
}

```

and canAttack will be:

```
maxjumps;
foreach(move: piece.attackingMoves){
    if board.isValid(move)
        tmpboard = board.clone
        tmpboard.domove(move)
        jumps = move.concatJumps(canattack(move.resultpiece,tmpboard))
        if jumps.count>maxjump.count
            maxjump = jumps
}
return maxjumps

```

if you don't want to clone the board you do a `undomove` on the board right after the `canattack` call

---
Tags: ai, turn-based
---


# Question
Title: cost of Adding Social Feature to your game such Creating guilds/guild chat
I'm making a f2p game in unity C#. The game currently has no social features.

I would like to have players to have their own accounts and also a guild tab. This tab is where they can create a guild and invite other players to the roster and being able to chat with each other.

Also would like to add leader boards for individual and guild rankings.

Was just wondering if any programmers can give me a estimate on labor to be able to make that feature in a game and how long roughly it would take.

I'm think I will need a mySql and php. I'm not really familiar with how it works.

Thanks,

Phil

# Answer
There's a simple formula you can use:

`estimatedCost = (hoursRequired * costPerHour) + additionalCosts`

The `hoursRequired` can range anywhere from a few hours for someone advanced making something very simple to hundreds of hours for someone very amateur making something very complex. The `costPerHour` will vary depending on the number of developers and their wages. `additionalCosts` include things like pre-built solutions, libraries to support certain functionality and so on.

Unfortunately only you will know the details of the variables, so only you can compute `estimatedCost`.
> 3 votes

---
Tags: software-engineering, databases, social, free-to-play
---


title: How do you make Minecraft mods?

text:
# Question
Title: How do you make Minecraft mods?
I want to make my own Minecraft mods and I'm wondering what I need to do to get started. Is there any good software or anything for it?

# Answer
> 15 votes
Download MCP, aka the Minecraft Coder Pack. This is how all the mods were released, and I've used it a couple of times, albeit for simple mods.

# Answer
> 6 votes
You need a couple of things:

* Basic Java programming skills
* MCP (Minecraft Coder Pack)
* A code decompiler (EditRocket, Eclipse, NetBeans)
* A good idea that nobody has done already (Unless you want to do it for practice)

After you have those, you need to set up MCP. You can find videos on how to do that on youtube. (I don't know if you have Windows XP, Windows 7, Mac) You need to set up the decompiler. (I don't know which one you will get, so I can't help with that) Once all that is done, you can code! Depending on which mod you want to make (Mobs, Items, Blocks), you will need to learn how to do this. I would start with new crafting recipes, like craftable web, or craftable spawners. Once you learn a little about how the minecraft modding works, you can start to make more complex mods. If you need help with learning how to do something for your mod, what I do is look up tutorials on youtube, or look on a search engine. If you need any more info, just comment :)

# Answer
> 1 votes
Use MCP, just like SourceTurtle said. If you need help using it, here are some YouTube tutorials I found:

# Answer
> -2 votes
go to minecraft forge website download source and run install (http://www.minecraftforge.net)

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


title: Gamemaker Loop Question

text:
# Question
Title: Gamemaker Loop Question
How often do loops repeat in game maker? Is it every step, or as fast as it can handle? I need it to loop every step, is it possible to do that? I'm talking about in code, I have a do until loop. Just interested in the facts, here.

# Answer
The entire loop will process every time the script that contains it is called. This happens inside a single frame.
> 5 votes

---
Tags: game-loop, game-maker
---


# Question
Title: Raytracer texture mapping (to triangle mesh) leaving artifacts
So I am trying to get OBJ loading working in my raytracer. Loading OBJs works fine, but I am having some trouble with getting the texture mapping working.

Here is an image of my result. It is supposed to be a black sphere with colored "latitude and longitude" lines, with a black spot in the middle. But it seems like every second triangle is left black. You can see the result here:

My prof said that it looks like the normals are backwards, but I don't think that is the case because the shape is still being hit - and the color of the "wrong" triangles is the color of background color of the texture (ie. black in this case).

When I load the OBJ, each vertex has a UV coord associated with it. What I do to get a UV coord when a ray hits the shape is as follows:

```
T: the triangle that was hit
hp: where on the triangle the ray hit
v1,v2,v3: the vertices of the triangle, each has a UV coord UV1, UV2, UV3

find the distance to each v[i] from hp (d1,d2,d3 respectively)
find the weight of each of these (w1 = d1/(d1+d2+d3), same for d2,d3)
find the weighted UV coord: UV1/w1 + UV2/w2 + UV3/w3

find the pixel color based on this weighted coord

```

Does anyone have any ideas what might be going on? I can post parts of my code if you think that would help.

# Answer
What kind of shading do you use. I assume some kind of blinn-phong. If that's the case, your shading depends on the dot product of your normal and the half vector of reflected light: (http://en.wikipedia.org/wiki/Blinn%E2%80%93Phong\_shading\_model)

The dot-product will be below zero on your triangles if your prof is right and your normals are pointing in the wrong direction. Blinn-Phong assumes no reflection in this case making your triangles pitch black.
> 1 votes

# Answer
I am not sure this is the actual answer to your problem (although it might be related).

I noticed that you are generating UV of the hit in the triangle by the (normalised) weighted sum of distances from the vertices.

This is wrong.

Think what you get if your ray exactly hits v1: d1=0 therefore w1=0 and you get a divide by zero.

What you should do is get the distance to the opposite edge. So d1 = distance to edge created between v2 and v3.

Normalise the result: d1,d2,d3 /= d1+d2+d3

Then UV(hit) = UV(1)\*d1 + UV(2)\*d2 + UV(3)\*d3 where d1=1, d2=0, d3=0 which gives exactl y the right answer.

This is called barycentric coordinates. It may not solve your immediate bug, but it will fix your uv generation.
> 0 votes

---
Tags: c#, textures, raytracing, obj
---


# Question
Title: Best system for creating a 2d racing track
I am working a 2D racing game and I'm trying to figure out what is the best way to define the track.

At the very least, I need to be able to create a closed circuit with any amount of turns at any angle, and I need vehicles to collide with the edges of the track. I also want the following things to be true if possible (but they are optional):

* The code is simple and free of funky workarounds and extras
* I can define all of the parts of the track (such as turns) relative to the previous parts
* I can predict the exact position of the road at a certain point (that way I can easily and cleanly make closed circuits)

Here are my options:

1. **Use a set of points.** This is my current system. I have a set of turns and width changes that the track is supposed to make over time. I have a point which I transform according to these instructions, and I place a point every 5 steps or so, depending on how precise I want the track to be. These points make up the track. The main problem with this is the discrepancy between the collisions and the way the track is drawn. I won't get into too much detail, but the picture below shows what is happening (although it is exaggerated a bit). The blue lines are what is drawn, the red lines are what the vehicle collides with. I could work around this, but I'd rather avoid funky workaround code.
2. **Beizer curves.** These seem cool, but my first impression of them is that they'll be a little daunting to learn and are probably too complicated for my needs.
3. **Some other kind of curve?** I have heard of some other kinds of curves; maybe those are more applicable.
4. **Use Box2D or another physics engine.** Instead of defining the center of the track, I could use a physics engine to define shapes that make up the road. The downside to this, however, is that I have to put in a little more work to place the checkpoints.
5. **Something completely different.**

Basically, what is the simplest system for generating a race track that would allow me to create closed circuits cleanly, handle collisions, and not have a ton of weird code?

# Answer
> 4 votes
I would suggest something you haven't listed.

## Don't "create" your track at all.

Rather, define it indirectly by placing a bunch of collide-able objects **around** where you want your track to be. Walls, old cars, wrecked buildings, semi-transparent-laser-beams... whatever you want. Heck, they don't even have to be visible. Then you can do your collision against those objects.

This has the benefit of being relatively fast, because each of those objects will end up just being a rectangle, and now you can just test for rectangle intersections.

In my opinion, this is the simplest way to go for any racing game, especially 2d.

# Answer
> 2 votes
I am currently working on a 3D wipeout clone, and my tracks are constructed using a Catmull-Rom spline from a small number of points. Catmull-Rom is good because it goes through the points, unlike Bezier which uses the points as a hull.

In 3D it is more complicated because I use quaternions to control orientation at the points. But you can get away with using just positions if you construct the tangents from next and previous points.

Regarding collisions with the track surface and edges: Each vehicle has a world position, velocity, orientation and angular velocity, as usual, but I also store the parametric distance around the loop (s) and the horizontal distance across the track (x).

Then, every frame, I sample the curve at 'time' s to get a matrix and other info like track width. Using the inverse of the matrix I transform the vehicles position and velocity into track space and do track/wall collisions there (almost trivial), before transforming position and velocity back into world space.

Then a simple world-space euler update to find the next position.

Finally I have to update the parameter s to reflect the new position. Currently I do this with an iterative approach: take a few steps of s, calculating the track matrix until it is in front of the vehicle. Then a few more iterations using a binary search to get a more accurate sample. I am not overly happy about this step, but it works well and I use an adaptive stepsize to keep number of samples to a minimum.

# Answer
> 0 votes
To second a note made in comments: the notion of defining your track via a chain of points making up its spine *should* work just fine; if the red path in your question is what you're getting out of your procedure, then I would start by considering changes to that.

My recommendation for doing the 'chain of points' version of the track is essentially a linear version of a spline: at each point along the spine Pi, define the current tangent to the track Ti by Ti = Normalize(Pi+1-Pi-1) (this is the *central difference* approximation to the derivative). Once you have the tangent you can find a 'rib' vector at a right angle to the tangent: if the tangent is Ti = (Tx, Ty), then the rib vector is Ri = (Ty, -Tx). With the spine points and the rib vectors, you can define the outer boundaries of the track: the left boundary is BiL = Pi-w\*Ri and the right boundary is BiR = Pi+w\*Ri (this creates a track of width 2w — that is, w units out to either side of the central spine). Once you have that, you can think of the track as the union of the quadrilaterals ⟨B0L, B1L, B1R, B0R⟩, ⟨B1L, B2L, B2R, B1R⟩, etc. This approach will occasionally have problems around hairpin turns (particularly if the curvature gets to be tighter than the width of the track), and you may want enough manual control over the intermediate points that I would use this as just an autogenerated starting point rather than the final result of the process — but it should serve as a good starting point for building the track. This also means that the collision envelope for the track should be the same as the displayed envelope, which is important in its own right — the player should expect that what they see on the screen actually represents the functional bounds of the track.

---
Tags: 2d, collision-detection, racing, curves
---


# Question
Title: How can I disable the forward/back buttons in AS3?
How can I disable the Flash player forward and back button in AS3? These buttons make it possible to cheat in my game by moving from level to level.

# Answer
I guess you're referring to the default entries in the Flash-Player menu:

The entries there can be customize (to a certain degree) by using the ContextMenu class.

Here's an example. In a frame of your timeline (preferrably at the beginning), place the following code:

```
var menu:ContextMenu = new ContextMenu();
var items:ContextMenuBuiltInItems = new ContextMenuBuiltInItems();

// disable the undesired items from the built-in items
items.play = false;
items.rewind = false;
items.forwardAndBack = false;

menu.builtInItems = items;

// override the context menu with our own menu
this.contextMenu = menu;

```
> 5 votes

# Answer
No, there is no way to disable that browser function in ac3. I wouldn't worry about cheating too much.
> 0 votes

---
Tags: actionscript-3
---


title: 1D functions and shapes

text:
# Question
Title: 1D functions and shapes
I have a set of numbers I normalize ( so the converted number is between 0 and 1 ) which I want to pass trough a function, which in return gives me a different number between 0 and 1 based on the curve/shape.

For animation the following would do for easeInQuad ( From ):

```
Math.easeInQuad = function (t, b, c, d) {
    t /= d;
    return c*t*t + b;
};

```

Where t = current time. b = start value. c = change in value. d = duration

which looks like:

In my case the min is always 0 and max is always 1. How would I go about creating a function equal to the shape but without all parameters that are required for animation?

# Answer
Not exactly what I'm looking for but I've opt it for another less "elegant" way of doing it.

I set up a table of points and their values.

The object looks like

```
public class CustomCurve {

    public float[] points;
    public float[] height;
    public int size;

    public CustomCurve(int size){
        points = new float[size];
        height = new float[size];
        this.size = size;
    }
}

```

**points** are the points on line t;
**height** are their values from which the lines are drawn from one point to another.

The function that goes with it:

```
 public static float Custom(float t, CustomCurve c)
 {

    float result = 0.0f;

    if(t > 1) return c.height[c.height.Length-1];
    if(t < 0) return c.height[0];

    for (int i = 0; i < c.size-1; i++) {
        if(t >= c.points[i] && t <= c.points[i+1]){

            result = Linear(t/(c.points[i+1]-c.points[i]),c.height[i],c.height[i+1]);
            break;
        }

    }
    return result;

}

```

Simply put, I iterate over the points on my t line. Check if t is between any of the points and calculate the inner interpolation of two points. Using the simple linear interpolation equation:

v0+(v1-v0)\*t;

So a table of:

```
Point   Height
0       0
0,2     0,95
0,3     1
0,33    0,95
0,4     0
0,5     0,95
0,7     1
0,8     0,95
1       0

```

Looks like:

Granted, the line won't be smooth. But if I need more detail I add more points. And once created I can reuse them.

**If anyone knows a way to get rid of the forloop please do tell!**
> 0 votes

---
Tags: mathematics
---


# Question
Title: How to create a 2D ocean effect in cocos2dx and box2d for iphone, android, windows phones
Currently my game needs a top ocean view. Can this ocean effect done using box2d? or should I dive into write my own physics (liquid/water simulation). Ideas and suggestions are welcome.

# Answer
Water physics and graphics are two completely different concepts. It is unclear which one you are asking about, so I'll consider both.

## Physics

To simulate top-down objects you have to set the gravity in your physics engine to \[0, 0\] and manually apply forces for movement. The rest depends on your goals.

You probably want to have wind/waves in your game that affect objects' movement. For "global" force, which affects the whole map, you could actually use the engine's gravity (set it to a desired value instead of \[0, 0\]) and have this force applied automatically to all your objects on every tick.

To have different wind/waves in different parts of the map, a more sophisticated approach is required (e.g. keep a low-resolution map of wind vectors over your game field and manually apply the forces by looping through all floating objects). For sailing ships you could take into account things like sail direction relative to the wind, so that the wind affects a ship stronger the more perpendicular it is to the sail and the bigger the sail is (just take a dot product of wind force vector and a perpendicular to a vector representing the ship's sail).

You may want to simulate water drag, otherwise your objects will preserve their velocities indefinitely until changed by some other force (wind, user input, etc). You can use Box2d's `linearDamping` property on your bodies and easily get constant damping for any object, or, again, do it manually to achieve more accurate results. A nice approximation for drag is

`F<sub>drag</sub> = -x * (0.1v + 0.01v<sup>2</sup>)`

where `x` is your object's width perpendicular to the movement direction and `v` is its velocity (relative to the water's velocity, if you want that kind of accuracy). You should tweak the 0.1 and 0.01 coefficients to better suit your application.

## Graphics

The easiest way to draw water in top-down 2d is to make a water tile and fill the whole water surface with it. It is possible to generate the water texture procedurally (you can use caustics generation algorithm, e.g. the one from this GPU Gems article; noise generation algorithms like Perlin/Simplex Noise can also come in handy). General techniques for tiles apply, so you can use multiple layers (one layer with tiled water texture, another layer for waves, etc) or choose tiles randomly. If your water is of different colors/textures in different places, you can blend between them by applying a blending mask.

A nice trick can be found in this article by twolivesleft. They make an animated texture where each frame is seamlessly tileable with every other frame (total of 16 frames in their case). They then arrange 16 tiles in a 4x4 square, initialize each at random frame and start animating. It looks consistent (due to all frames being tileable with each other) and not repetitive (animations are same, but they start at different frames). This square can then be used to tile your whole water surface.

You could also write a shader that combines your water tiles with an animated normal map.

These are just some techniques off the top of my head, though for many applications this is enough. Of course, there are many more.
> 3 votes

---
Tags: c++, android, ios
---


# Question
Title: OUYA Developer Kit throws various errors on start
I followed these instructions for Mac OS X using an existing IDE (shell + text editor) instead of the Eclipse ADT thingy. I activated “Use Host GPU”, and installed Intel HAXM. Installing the ouya-framework.apk and ouya-launcher.apk appears to go well. But when I start up my AVD there’s a dialog box saying “Unfortunately, the OUYA Launcher has stopped.”, I still get the choice of starting up the OUYA Launcher. When I do so there’s another dialog box saying “Can’t play this video”. I skip the controller settings, and then there’s a JOIN A WIRELESS NETWORK screen which I can’t get past.

This is the ODK 1.0.2, and I tried it using both Mac OS X 10.8.3 and 10.7.5.

# Answer
The wireless network problem has been discussed on the OUYA forums. It seems impossible to proceed beyond that point on an Android emulator. You’ll need to test on a real device.

This isn’t only an OS X problem: I’ve encountered similar problems (“OUYA Launcher has stopped” and “Can’t play this video”) on Windows too.
> 2 votes

---
Tags: android, ouya
---


title: Select display adapter in D3D9

text:
# Question
Title: Select display adapter in D3D9
I have a notebook that has 2 graphics card one Intel and one nvidia graphics cards. When I want to start my game I right click on the exe file and select run with graphics processor-\>Nvidia but my engine stills run with my Intel graphics card on d3d9. Is there any way to choose the graphics card with code?

# Answer
The following page includes a link to a PDF from NVIDIA outlining procedures for how to ensure that the NVIDIA adapter is always selected: https://developer.nvidia.com/optimus
> 3 votes

---
Tags: c++, directx9
---


title: Java Slick2d particles error

text:
# Question
Title: Java Slick2d particles error
When i run the game particles crash the game, im not sure what am i doing wrong because the program doesnt tell me. But i know particles are causing this , if i remove the code in update code at bottom, the runnable jar works fine.

Particle class : http://pastebin.com/ATLN6qzR

Particle manager : http://pastebin.com/vAk1nwmi

Slick 2d docmentation : http://www.slick2d.org/javadoc/

It says error is here where the for starts

```
public void update(int delta){

    for (Particle o: particleList) {
        if(o.emitter.completed() == true){
            particleList.remove(o);
        }
        else{
            o.system.update(delta);
        }

    }
}

```

# Answer
> 4 votes
I'm not sure how you're not seeing this problem in the debug version.

```
for (Particle o: particleList) {
    if(o.emitter.completed() == true){
        particleList.remove(o);
    }

```

Attempting to remove an item from a list while iterating through that list will give you a concurrency exception.

Instead of `particleList.remove(o);` add the item to remove list. Then after your for each loop, loop through the remove list and use the `particleList.remove(o);` call. Then clear your remove list.

Like this:

```
ArrayList<Particle> toRemove = new ArrayList<Particle>();
for (Particle o: particleList) {
    if(o.emitter.completed() == true)
        toRemove.add(o);
    else
        o.system.update(delta);
}

//remove finished particles
for (Particle o: toRemove) {
    particleList.remove(o);
}
toRemove.clear();

```

---
Tags: java, slick
---


title: SDL Access Violation

text:
# Question
Title: SDL Access Violation
I've created a SDL game project and this window popped up while trying to compile:

```
First-chance exception at 0x00000000 in SDL_Game.exe: 0xC0000005:
Access violation executing location 0x00000000.

If there is a handler for this exception, the program may be safely continued.

```

The buttons gave the option to `break, continue, ignore`**.**

Code shows no errors whatsoever. Has anyone ran into this sort of problem in the past? I've googled around, but nothing was in line with this that I've found.

**UPDATE:** Through the debugger, error points to `vShaderID`:

```
GLint Shader::makeVertexShader (char* shaderSource)
{
    GLint vShaderID = glCreateShader(GL_VERTEX_SHADER); //<<----- Debugger
    glShaderSource (vShaderID, 1, (const GLchar**) &shaderSource, NULL);
    glCompileShader(vShaderID);
    bool compiledCorrectly = compiledStatus(vShaderID);

    if (compiledCorrectly)
    {
        return vShaderID;
    }
    return -1;
}

```

And the second line in the debugger points inside the constructor to `vertexID`:

```
Shader::Shader(const char* vertexFilename, const char* fragmentFilename)
{
    ....
    // Read in the vertex program file
    char* vertexCode = readFile(vertexFilename);
    ....
    GLint vertexID = makeVertexShader(vertexCode); //<<--------Debugger

```

# Answer
You have an execute violation at 0x00000000 which means a function call tries to jump to this location.

By the position your debugger points out it looks like glCreateShader is null.

Some of the possible reaons:

* You did not intialize OpenGl correctly/at all? Did you check the return values from the SDL initialization for errors?
* You did initialize an OpenGL version not supporting this function. (glCreateShader requires OpenGL \>= 2.0)
* Your platform/driver does not support this feature. This should return an error during initialization as the requested OpenGL is not supported.
> 3 votes

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


# Question
Title: Why wouldn't one use Canvas for HTML 5 game development?
I'm just getting into the HTML 5 game development. I've discovered that some games seem to be created using just JS/CSS/HTML instead of the canvas.

Since canvas seems to enjoy good browser compatibility (http://caniuse.com/#feat=canvas), I'm wondering why someone wouldn't use it?

# Answer
> 11 votes
1) Lack of knowledge. Developing for Canvas might be well beyond some web developers who are very accustomed to manipulating DOM.

2) Lack of a scene graph. The DOM is (in game engine terms) a scene graph, permitting strong querying and manipulation of DOM nodes. Writing a game using Canvas requires the developer to "reinvent" that part of the wheel.

3) Lack of sprite animation. Animated GIFs or CSS style manipulation are a trade-off for writing your own sprite animation library, which developing on Canvas requires you to do.

Essentially, writing a game for Canvas requires the web developer to become a 1990s-era game developer, where there were no DirectXs or OpenGLs, and media resource management must be written by the developer. Without a lot of knowledge in this field -- especially since there has been a game development knowledge gap between when games moved from 2D to 3D and then returned back to 2D in the form of casual and smartphone games -- it becomes a daunting task.

For the rest of us who started game development in mode 21h and enjoyed evolving as DX and OpenGL evolved, Canvas is a welcome nostalgic throwback where we also happen to have rare knowledge. :-)

# Answer
> 2 votes
1. No Picking. What did the user click on? It's up to you to sort that out. HTML Elements or SVG provide that functionality out of the box.
2. No Layout. If you intend on adding text UI, buttons, or other user interface that HTML is already good at solving you'll have to re-invent it in canvas.

# Answer
> 0 votes
Like you, I am also getting into the HTML 5 game development ;)

Initially I found canvas an exciting and viable medium. I tried to get what I wanted out of it, but It was very slow for my needs. So I turned to WebGL.

To see the difference, check the following three.js examples:

The original one shows a trotting horse and on my machine runs at 60 FPS. The canvas one though, looses the trotting animation (and only keeps the rotating animation), and runs at 30 FPS on the same machine.

And by the way, if you use three.js, you can switch between using canvas, webgl, css3d and even svg very easily. In the canvas example above, all I have changed is one line, i.e. commented out:

```
renderer = new THREE.WebGLRenderer();

```

and added:

```
renderer = new THREE.CanvasRenderer();

```

# Answer
> 0 votes
The main competitor to HTML5 Canvas when it comes to browser-based games is still the good, old Macromedia Adobe Flash. Most people who are in the web-based game market already have plenty of experience with Flash, and almost none with Javascript. So unless HTML5 becomes clearly more powerful than Flash, this is not going to change soon.

When you compare both tools as a pure game development plattform, Flash still seems to be superior. It has a very mature, artist-friendly authoring tool which does most of the ground-work for you, while HTML5 development is still mostly done with text editors due to lack of proper IDE support. Sure, there are some libraries which make canvas programming easier, but these are as new as canvas itself and still need time to mature.

It is, however, just a matter of time until this will change. Both Microsoft and Apple have decided that flash must die so that HTML5 can live. So I am sure that we will soon see some advanced, artist-friendly development tools for HTML5.

---
Tags: html5, html-canvas, browser-based-games
---


title: Stop music in crafty.js

text:
# Question
Title: Stop music in crafty.js
How do I stop a looping music file from playing in crafty.js? I want the music to stop playing once a gameover condition has been reached.

# Answer
> 2 votes
According to this issue page: `Crafty.audio.stop("soundname");` or `Crafty.audio.stop()` to stop all sounds. Apparently the documentation is very out of date. The issue linked is from 10 months ago, and the documentation is still out of date.

However, you can always check the source code to see what's available to you.

---
Tags: javascript, music, crafty
---


title: XNA model texture maps

text:
# Question
Title: XNA model texture maps
Is it possible to make a texture maps for XNA .fbx models? Just one texture file for the whole model.

# Answer
Yes.

Formats vary greatly, although the content pipeline can handle a lot of situations. Here are some stumbling blocks:

* Modeling software will segregate textures by material, or mesh, ect. To unify them, you'll need to merge those somehow to use a single texture (while using the default `Model` class)
* 3DSMax will not package textures into the model by default. It will save references. You'll need separate texture files available for loading from the content project.
* Model references will usually contain absolute path information. This confuses the importer when it copies content into the project's content folder, let alone from one developer's computer to another.
* Having path information *at all* is unnecessary. XNA will chain-load texture and shader assets simply by referencing their file names in material/texture nodes of the model.
* These textures are loaded directly into the properties of the built-in `Model` class. They do not need their own `Texture` objects. The texture properties can be reassigned to other loaded assets at run-time.

It is good to remember that the default `Model` class was an imperfect solution to a very difficult problem. Almost any deviation from the most basic usage requires a lot of infrastructure and cumbersome work. It's probably still worth it to do, rather than trying to make other workflow pieces fit into that class. Shawn Hargreaves (XNA lead) posted a long summary of all the considerations that went into designing it, and all the reason why you might not like it.
> 1 votes

# Answer
Yes, you can make textures for .fbx files. Probably the easiest is to export a texture from whatever app you are using. For example here is a Blender example: http://xboxforums.create.msdn.com/forums/t/4614.aspx.
> 0 votes

---
Tags: xna-4.0, models
---


# Question
Title: Translating Viewmatrix is inverted, why?
So I've defined a Projectionmatrix, Viewmatrix and a Modelmatrix using OpenGL (LWJGL).

But when I translate my Viewmatrix to +X it moves my object to the right (hence my camera is moving to the left), and when I move it to -X the object moves to the left (camera moving to the right). Same goes for Y movement, Z works as it should though.

My matrices are as follows:

Projectionmatrix

```
perspectiveMatrix = new Matrix4f();
perspectiveMatrix.setIdentity();

float aspectRatio = WIDTH / HEIGHT;
float zRange = zNear - zFar;

//COLUMN / ROW
perspectiveMatrix.m00 = (float) (1.0f / (aspectRatio * Math.tan(degreesToRadians(fieldOfView / 2.0f))));
perspectiveMatrix.m11 =  (float) (1.0f / (Math.tan(degreesToRadians(fieldOfView / 2.0f))));
perspectiveMatrix.m22 = (-zNear - zFar) / zRange;
perspectiveMatrix.m23 = 1;
perspectiveMatrix.m32 = (2 * zFar * zNear) / zRange;

```

Viewmatrix

```
Matrices.viewMatrix = new Matrix4f();
    Matrix4f.setIdentity(Matrices.viewMatrix);

    //Initialize all vectors
    this.xAxis = new Vector3f();
    this.yAxis = new Vector3f();
    this.zAxis = new Vector3f();
    this.newPos = new Vector3f();
    this.currPos = new Vector3f();

    /*
     * position.xyz = 0, 2, 7
     * target.xyz = 0, 0, -1
     * up.xyz = 0, 1, 0
     */
    //Set all values to the Camera-class values
    position.negate(this.currPos);
    target.normalise(this.zAxis);
    up.normalise(this.yAxis);

    Vector3f.cross(target, up, xAxis);
    Vector3f.cross(xAxis, target, yAxis); //Recalulate yAxis to make it valid coordinate system.

    /*
     * This defines the View Matrix. This is calculated and explained here:
     * http://ogldev.atspace.co.uk/www/tutorial13/tutorial13.html
     *
     * m(Column)(Row)
     */
    Matrices.viewMatrix.m00 = xAxis.x; Matrices.viewMatrix.m10 = xAxis.y; Matrices.viewMatrix.m20 = xAxis.z;
    Matrices.viewMatrix.m01 = yAxis.x; Matrices.viewMatrix.m11 = yAxis.y; Matrices.viewMatrix.m21 = yAxis.z;
    Matrices.viewMatrix.m02 = zAxis.x; Matrices.viewMatrix.m12 = zAxis.y; Matrices.viewMatrix.m22 = zAxis.z;
    Matrices.viewMatrix.m33 = 1;

    Matrices.viewMatrix.translate(this.currPos);

```

Modelmatrix

```
Identity

```

# Answer
What you are describing is exactly how the view matrix is supposed to work. The view matrix is the inverse of the camera's world matrix, so you would expect that translating the view matrix is the same as performing the opposite translation on the camera's world matrix.

The reason the z-axis has the opposite effect is that camera's face down the negative z-axis by default, so that if your object and the camera are at the origin and you translate the camera by +50, the camera is now "in-front" of and looking at the object, since it is looking down the negative z-axis. To achieve this same effect by manipulating the view matrix, you would perform the inverse operation so you would translate it by -50 to bring the camera out in front of the object.
> 2 votes

---
Tags: opengl, matrix, transformation
---


title: Generate slot combinations

text:
# Question
Title: Generate slot combinations
How do you generate combinations in slots to achieve a wanted probability of the user winning?

Say, you decide that he should win $200. How do you generate combinations that'll cause winnings approximately $200?

# Answer
I'm going to assume this is for a game that doesn't cheat the player. Maybe for a tutorial where you want it to appear random, but need them to have a specific amount of money at the end.

The probability of winning a slot machine depends on the number of slots and the possible combinations. I think you'll be able to figure that out once you have those values.

For the second part of your question, to find some random values that add up to $200, you can add random numbers until you reach $200.

```
int total = 0;
list<int> winnings = new list<int>();
while(total < desiredTotal)
{
     //pick a random win bounded on what we still need to reach desiredTotal
     //inclusive random between 1 and what's left
     int win = random(1,desiredTotal-total);
     winnings.add(win);
     total+=win;
}

```

Then just iterate through `winnings` when selecting a win amount.
> 2 votes

# Answer
Normally what we do professionally (I work at a company that makes slot machines and their games) is we create something called a paytable which has a list of all the winning combinations we want to appear and how likely they are to appear that way you never have to dynamically decide where the reels stop, you just look it up in the table and spin to that location.
> 2 votes

# Answer
So you basically want to cheat the user. Slot games are inherently random. Yes, you set a possibility of winning, but that's it. You don't decide if the user wins or loses.

The best way is to generate a random combination, then calculate the winning on that (2 of a kind, 3, royal flush). If you want to let low-earning users win a bit more than usual, just lower the number of permutations.

An example:

User has 2000$ and rolls once: He is given 5 x 5 x 5 slots. However, if the user drops under 1000$, he's given 3 x 3 x 3 slots. (This dramatically increases the chances of winning, but the animation looks the same, so the user doesn't realize what's happening.)
> 0 votes

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


# Question
Title: XNA change a specific color of a model to another
Is it possible to change a specific color of a model to another?

Example:

Everything that's blue should be red or something like that.

And is it possible to do this without the use of effects? I still want to use the basic effect.

# Answer
Because you are unwilling to employ a non `BasicEffect` to accomplish this, here is your only other option. This is quoted from the description of the **complete, free, and functional example project created by the developers of the XNA framework,** Color Replacement.

> When it's the Red Team versus the Blue Team, or when you want to drive a car painted with your favorite color, you either need to create a texture for each color  or perform color replacement programmatically.

In this quote, the pragmatically refers to using an instance of `Effect` and a shader. So you can see what you are left with. (In case you would consider changing the model's data at runtime, don't forget that it is compiled into binary before the game ever runs.)

I strongly recommend that you reconsider your position about only using `BasicEffect`. Drawing models does not require it.
> 2 votes

# Answer
You can create a texture of the same size, alter the colors programmatically, and then use it in place of the original. Then you can replace the altered texture using the BasicEffect.Texture property.

```
Texture2D newt = new Texture2D(graphicsDevice, t.width, t.height);

Color[] data = new Color[t.Width * t.Height];
t.GetData(data);

for (int x = 0; x < t.width * t.height) {
    if (data[x] == Color.White) {
        data[x] = Color.Blue;
    }
}

newt.SetData(data);

```

Note that this is much more memory intensive than using a shader to recolor the texture dynamically since you need as many textures as number models * active colors.
> 1 votes

---
Tags: xna-4.0, models, color
---


title: Overlapping svn repositories

text:
# Question
Title: Overlapping svn repositories
We use svn at work, but the repository is getting pretty large, so checkout times are long, as is update when artists batch process all assets.

The problem is that we also store work in progress, prototypes, small tests, legacy stuff and other 'junk'.

Now theoretically, some of it can remain local and uncommitted until it is ready to be included, and a lot could be deleted and cleaned, but that's irrelevant for this question.

Imagine a new asset, a level for example. The artists and designers want it shared and in version control so several of them can work on it, but everybody else does not need it.

Obviously multiple repositories are an answer: one for artists, one for programmers and one for the main project (for testers, building demo versions and finally the main product), which would be really tight and minimal, with everything needed for the game and no more. And then when an asset or some code is 'mature', it can be copied into the main project and committed.

Here's my questions: is it possible to have multiple repositories overlapping so that the artists can have one with everything they need, likewise for programmers. And only when ready commit *the same file* into the project repository too? This would eliminate bloat of having multiple copies of files and avoid conflicts between repositories.

I know old svn versions stored invisible files in all directories, so it would be impossible, but new svn versions store all meta data in the root directory right? So it might be possible.

I imaging the answer will be 'impossible', or even if possible, yuck! I suppose it would cause all kinds of headaches. Like checking it out in one repository would mean it would need to be committed/deleted in another.

But how about making a svn\_commit script, that overrides svn commit with additional checks and housekeeping?

This is just a thought experiment really. I was wondering if anyone has ever done anything like this, and what would be the issues to be resolved. Cheers

# Answer
> 4 votes
I *think* (from your description), that svn externals will be correct answer:

* You have not copy object from repo to repo - you have single object, which is linked to and can be used from different targets
* "Thin" final repositories can be just *any* (only) collection of externals to the repositories, which holds data: you have additional flexibility in building needed trees and managing access-rights

# Answer
> 6 votes
https://stackoverflow.com/questions/50945/can-you-do-a-partial-checkout-with-subversion

Specifically, not everybody has to check out the whole tree. TortoiseSVN has a pretty user-friendly GUI for this.

You can tell people to not check out certain folders (for example, programmers could skip the art source folder).

Depending on your exact directory structure, this won't require any changes on your part.

---
Tags: resource-management, version-control, teamwork
---


title: "lerp" returning value (Shader)?

text:
# Question
Title: "lerp" returning value (Shader)?
I don't understand the `lerp` example in this code :

```
if(dot(WorldNormalVector(IN, o.Normal), _SnowDirection.xyz)>=lerp(1,-1,_Snow))
                o.Albedo = _SnowColor.rgb;
            else

```

(Snow is in the range 0..1)

The article says :
We then compare the dot value with a lerp - if our Snow level is 0 (no snow) this returns 1 and if the Snow level is 1 it will return -1 (the entire rock is covered). It's quite normal to only vary the snow level between 0..0.5 when we use this shader so that we only have snow on surfaces that actually face the snow direction.

Why does it return 1 (with Snow at 0) and -1 (with Snow at 1) ?

(source: http://unitygems.com/noobs-guide-shaders-2/ )

Thanks

# Answer
> 1 votes
`_Snow` is in the range 0 to 1. The dot product returns a value from -1 to 1. The `lerp` is being used to convert `_Snow` to the -1 to 1 range for comparison with the dot product. When `_Snow` is zero, no snow is desired, so the comparison becomes "dot product \>= 1", which will never be true (well, except at points exactly facing the snow direction). Conversely, when `_Snow` is 1, the comparison becomes "dot product \>= -1", which will always be true, so you'll get snow everywhere. Intermediate values of `_Snow` should generate intermediate values to compare the dot product against, hence the interpolation.

---
Tags: unity, shaders, lerp
---


# Question
Title: relationship between eye height and collision body in UDK
We are using the UDK in a research lab setting so we must understand exactly how tall users feel in the virtual world (camera position). By Googling and digging through code, we have discovered the BaseEyeHeight parameter and also the dimensions of the collision cylinder (CollisionHeight). We attempted to set these using Remote Control and could not deduce the relationship between the variables.

For one thing, it seems that BaseEyeHeight has a ceiling. We cannot set it arbitrarily high but the height that is allowable seems to be dependent on the height of the collision cylinder, though it can be higher than the cylinder. Is there a ceiling for the eye height?

Secondly, the height we set for the collision cylinder does not seem to match the height of an object in the world that should be the same height. Is the collision cylinder in the same units as the rest of the world? Is there some padding that I am not accounting for?

Finally, BaseEyeHeight does not seem to be the height from the ground. I read somewhere that it should be the height from the center of the cylinder. Is this true? I would expect the eye height to be a bit lower than the actual collision height (as in the real world). Is this the case?

The big picture problem is that we cannot find a diagram or detailed description of how these numbers relate to one another. Is there a comprehensive source we've missed?

# Answer
> 0 votes
The cylinder height property is the distance to the center of the cylinder, so it is actually half the total height of the cylinder. The eye position is BaseEyeHeight above the center of the cylinder, or cylinder height + BaseEyeHeight above the ground. Also, the cylinder floats about 2 u real units above the floor, so add that in to be really precise. The UDK forums at http://forums.epicgames.com/forums/366-UDK are a good place to ask this kind of question. Also, check out the UDK documentation at http://udn.epicgames.com/Main/WebHome.html .

---
Tags: collision-detection, camera, udk, character
---