# Question
Title: Simulate camera movement in two dimensions (OpenGL)
I've been told by the folks over at Stack Overflow that there's no way to move the camera in OpenGL. I'm developing a 2D RPG with LWJGL and need to know the proper way to simulate camera movement as though it is "following" my player. Remember, this game is in two dimensions, so rotation of the world is not a problem here.

And another, related question: If camera movement simulation involves moving the world and not the player, how would it be possible to ever implement multiplayer? I'm a bit of a noob at OpenGL, but I see it used in a handful of popular multiplayer Java games, and can't get my head around the concept of being unable to move the perspective (and thus being forced to move the world) and not having players interfere with each other's movement.

# Answer
> 2 votes
> I've been told by the folks over at Stack Overflow that there's no way to move the camera in OpenGL

Well, technically speaking there is no camera in openGL, what openGL provides is a series of transformations that you need to provide in order to simulate the idea of the camera; so the camera is just transforming some objects relative to some mathematical space ( traditionally you use the inverse of rotation and translation matrix in case of 3D space not counting the projection here).

> If camera movement simulation involves moving the world and not the player, how would it be possible to ever implement multiplayer?

As I said in the first part you need think of it as relative movement, you move the "whole world" relative to the camera space so for example if you move the world with (x=2, y=0), you can think of it as moving the camera with (x=-2, y=0). My advice is to use one notation and stick with it. Keep in mind that OpenGL doesn't directly deal with 2D, so you need to set up orthographic projection with fixed camera axis probably (right=x, up=y, forward=-z) and a translation where you need to fix the Z like for example (x,y, 10) and let the camera move in the xy plane.

In case of the player you need to understand that the camera does't matter here, you only move the player relative to the world space, hence the same concept above applies here you either move the player relative to the stage ( I used the term stage here instead of world to avoid confusion) or the stage relative to the player.

Regarding multiplayer games, which is something I haven't done before, I think that moving the player relative to the stage is more straight forward to deal with, but I don't have any concrete example.

**\[Edit Based on comments\]** To make the camera follow the player; given that your camera is at position (x,y) - I am going to drop the Z from the solution- and your player is at a fixed offset from your camera say (x+t, y+t), you need to make the camera move towards (x+t, y+t) there are different ways of doing this, I can think of:

* Use any kind of interpolation, a simple example might be linear interpolation, expressed in parameterized vector notation NewPos = camPos + t\*( normalize(PlayerPos - camPos) ). Note that updating the values will depending on how you handle your animation and game update. You can also change the equation for smoother animation.
* Use elastic based camera, with the formula **F=kx** where **F** stands for Force, **K** constant based on the spring stiffness (you can choose as you see fit), and **x** can be used distance between the camera and the player. Note that **F** can be factored into **F=m\*a** where **m** is **mass**(constant) and a is acceleration so you can modify the camera position using the calculated values. In general this will give you a spring like behavior but you need to multiply with some damping factor so it won't "bounce" forever.
* I forgot to mention that the easiest way to make your camera follow the player is to set the camera position to equal the player position every frame, but that won't simulate the following behavior but rather the camera will be fixed on the player position, and it might be annoying if the player has some sharp movements, since it will exactly match its position.

---
Tags: opengl, java, multiplayer, camera, lwjgl
---


title: SDL2 render to texture support

text:
# Question
Title: SDL2 render to texture support
I'd like to use the function

```
int SDL_SetRenderTarget(SDL_Renderer *renderer, SDL_Texture  *texture)

```

in my 2D game. At this point I am using only the SDL 2.0 API, and using openGL seems overkill to me. Rendering to an intermediate texture would greatly simplify the programming of a camera system and split-screen support. However, the (sparse) SDL wiki documentation states:

> Before using this function, you should check the SDL\_RENDERER\_TARGETTEXTURE bit in the flags of SDL\_RendererInfo to see if render targets are supported.

This raises the question wether or not can I rely on the availability of this function. I was unable to find any information on the subject on the web.

# Answer
> 3 votes
Internally SDL uses Framebuffer Objects to implement Render Targets on OpenGL/ES/ES2. The Direct3D backend uses D3D9 SetRenderTarget .

FWIW, the only system I found not to support this functionality is the sketchy OpenGL ES 1.x implementation in the nVidia binary driver for Linux, which is just an anecdote (you either just use regular OpenGL or GL ES 2), pretty much anything supports this functionality.

---
Tags: textures, sdl, rendertargets
---


title: WebGL immediate mode

text:
# Question
Title: WebGL immediate mode
I know that WebGL is based on OpenGL ES 2.0 and that `glBegin` and `glEnd` have been removed and replaced with vertex buffer objects. I understand that VBOs are faster and use less code but is there a library or add-on for JavaScript / WebGL that re-implements these functions?

After more research, I have discovered that this functionality is called immediate mode.

# Answer
It's unclear what your rationale is for doing this. You might want to ask a new question about the problems you're running into that would inspire you to look for such a utility.

There is a library called LightGL that attempts to do what you're asking. This is just a simulation of immediate mode, since true immediate mode is not supported. It's not really very close to immediate mode either, but it's likely as close as you're going to get.
> 1 votes

---
Tags: opengl, javascript, html5, webgl
---


# Question
Title: Is it possible to use ALSA or OSS on Windows?
Has nobody written a wrapper over DirectSound or something yet?

# Answer
> 1 votes
ALSA and OSS, as far as I am aware, are not sound formats but rather audio platforms for Linux; a means of interacting with MIDI devices or sound cards.

As of this writing, I know of no ports or implementations of their APIs to the Windows platform. Both projects look relatively stale from a quick glance at their respective pages, so that doesn't seem surprising.

---
Tags: windows, sound
---


# Question
Title: Adding Functionality to a basic Java 2D Camera
Creating a little LoZ inspired game in Java here just to get into the feeling of things (learning CS at my school but the only teacher who's willing to help is travelling for 6-months, so I'm teaching myself in the meantime). Thing is, I've run into a little snag with the functionality of the "camera".

I've so far been able to successfully limit where the camera goes in terms of the level size (stopping the camera when it gets to top, bottom, left, and right edges of the level), and keep the camera centered on the player as he moves around the level. The issue I'm having is that once my camera stops moving, I can't figure out how to wait until the player is in the center of the screen again for the camera to move again.

So if my player starts out in the center of the map and then moves all the way to the top left, if I move down or right then my sprite isn't in the center of the camera anymore.

Anyone have any suggestions? And sorry if this blatantly obvious, I'm still new to game development.

Thanks. ^^

# Answer
Just add some extra if statement that will prevent camera movement until the sprite is in the middle. Like:

If player is below middle and camera is at the bottom of the map don't move
> 0 votes

---
Tags: java, 2d, camera
---


# Question
Title: Is it legal to record music with a synthesizer and use it in my game?
I want to make music for game on my own because I don't have professional composer hired. I have found some softwares for making music, but most of them cost some money. I have an idea to record music on synthesizer, then edit it and use in my game. My question is:

**Is it legal to record music (that I have composed and edited) on synthesizer and use it in my game (the game may be free or charged)?**

# Answer
This *should* be legal, but be careful where your music is coming from. If you're using sound samples provided by software you need to ensure it's OK to use those sound samples. There's something in music composition called Sampling. This is taking small bits of other music and re-using it in your own. The legal issues surrounding sampling are a grey area, wikipedia has this to say about it:

> Sampling has been an area of contention from a legal perspective. Early sampling artists simply used portions of other artists' recordings, without permission; once rap and other music incorporating samples began to make significant money, the original artists began to take legal action, claiming copyright infringement. Some sampling artists fought back, claiming their samples were fair use (a legal doctrine in the USA that is not universal).

However, if you're creating the music yourself, and it's composed by you, there shouldn't be any issue.
> 8 votes

---
Tags: legal, music
---


# Question
Title: Automated Unity iOS command line build on Mac
I am doing the iOS builds for a group of Unity (Unity3d) game developers.

After pulling the latest git updates, I start up the Unity editor on my Mac and choose "Build Settings", select the iOS target platform, press Build, specify a destination folder and that is it.

Can this exact process be done automatically via the terminal prompt?

# Answer
Android and iOS are not directly supported by the command line utility. However, you can use the command line utility to run a script that will build for iOS. In the simplest form, it would be something like:

```
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.IO;

public static class AutoBuilder {

    static string GetProjectName()
    {
        string[] s = Application.dataPath.Split('/');
        return s[s.Length - 2];
    }

    static string[] GetScenePaths()
    {
        string[] scenes = new string[EditorBuildSettings.scenes.Length];

        for(int i = 0; i < scenes.Length; i++)
        {
            scenes[i] = EditorBuildSettings.scenes[i].path;
        }

        return scenes;
    }
    [MenuItem("File/AutoBuilder/iOS")]
    static void PerformiOSBuild ()
    {
        EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTarget.iPhone);
        BuildPipeline.BuildPlayer(GetScenePaths(), "Builds/iOS",BuildTarget.iPhone,BuildOptions.None);
    }
}

```

Then, you would call this from the command line with

```
-executeMethod AutoBuilder.PerformiOSBuild

```
> 12 votes

---
Tags: unity, ios
---


title: What does ddx (hlsl) actually do?

text:
# Question
Title: What does ddx (hlsl) actually do?
I'm a bit confused. The official documentation (http://msdn.microsoft.com/en-us/library/windows/desktop/bb509588(v=vs.85).aspx) says that ddx(input) is the partial derivative of the input with respect to the "screen-space x-coordinate."

My calculus is fine, but how can it tell what the input is coming from? If I passed it a function, fine, I can imagine what it would do, but the derivative of a number is always zero...?

Is it just a scaling? Like, this would get scaled to one tenth of its size at this distance, so it returns one tenth? But then it doesn't need an input...

Can someone give a quick explanation of what's actually happening?

# Answer
Internally, GPUs never run one instance of a pixel shader at a time. At the finest level of granularity, they are always running 32-64 pixels at the same time using a SIMD architecture. Within this, the pixels are further organized into 2x2 quads, so each group of 4 consecutive pixels in the SIMD vector corresponds to a 2x2 block of pixels on screen.

Derivatives are calculated by taking differences between the pixels in a quad. For instance, `ddx` will subtract the values in the pixels on the left side of the quad from the values on the right side, and `ddy` will subtract the bottom pixels from the top ones. The differences can then be returned as the derivative to all four pixels in the quad.

Since the pixel shader is running in SIMD, it's guaranteed that the corresponding value is in the same register at the same time for all the pixels in the quad. So whatever expression or value you put into `ddx` or `ddy`, it will be evaluated in all four pixels of the quad, then the values from different pixels subtracted as described above.

So taking the derivative of a constant value will give zero (as you'd expect from calculus, right?) because it's the same constant value in all four pixels.

Also note that there are "coarse" and "fine" derivatives, `ddx_coarse`/`ddy_coarse` and `ddx_fine`/`ddy_fine`. An explanation of the distinction is given here. Just plain `ddx`/`ddy` are aliases for the coarse versions.

BTW, the reason this functionality exists is that GPUs internally have to take derivatives of texture coordinates in order to do mipmap selection and anisotropic filtering. Since the hardware needs the capability anyway (you can use any arbitrary expression for texture coordinates in a shader), it was easy enough to also expose it to shader programmers directly.
> 44 votes

---
Tags: hlsl
---


title: Finding Pixels within UV Coordinates

text:
# Question
Title: Finding Pixels within UV Coordinates
I am building lightmaps for 3D models. My lightmap algorithm needs to determine which pixels( lumels ) within the lightmap texture fall within the boundary of a mesh face( triangle )...this process takes place for each mesh face...

I was using barycentric coordinate techniques to accomplish this task. It works for the most part...here is code:

```
bool PixelIsWithinBounds( const D3DXVECTOR2 &t0,
                            const D3DXVECTOR2 &t1,
                            const D3DXVECTOR2 &t2,
                            const D3DXVECTOR2 &pUV )
{
    // compute vectors
    D3DXVECTOR2 v0 = t1 - t0,
        v1 = t2 - t0,
        v2 = pUV - t0;

    // do bounds test for each position
    float f00 = D3DXVec2Dot( &v0, &v0 );
    float f01 = D3DXVec2Dot( &v0, &v1 );
    float f11 = D3DXVec2Dot( &v1, &v1 );

    float f02 = D3DXVec2Dot( &v0, &v2 );
    float f12 = D3DXVec2Dot( &v1, &v2 );

    // Compute barycentric coordinates
    float invDenom = 1 / ( f00 * f11 - f01 * f01 );
    float fU = ( f11 * f02 - f01 * f12 ) * invDenom;
    float fV = ( f00 * f12 - f01 * f02 ) * invDenom;

    // Check if point is in triangle
    if( ( fU >= 0 ) && ( fV >= 0 ) && ( fU + fV <= 1 ) )
        return true;

    return false;
}

```

This function takes as input 3 UV coordinates( mesh face ) and a pixel UV coordinate. The problem with this method is that if the pixel is only partially covered by the face, the function returns false( because the pixel center does not ly within the triangle ). I could do overlap tests for each point on the triangle...I would like to know if there is a more efficient method...as this process takes place many times per generation of a lightmap...

...any ideas?

here is a screenshot showing the endpoint of a mesh face after lightmap generation...the corner of this face overlaps a pixel surface but doesn't overlap the pixel center...the algorithm left this pixel black( no light )...

EDIT: Shader code to dilate pixels

```
//--------------------------------------------------------------//
// Dilation Pass
//--------------------------------------------------------------//
PS_INPUT_Quad DilationPass_Vertex_Shader( VS_INPUT_Quad Input )
{
    PS_INPUT_Quad Output = ( PS_INPUT_Quad )0;

    Output.Position = mul( Input.Position, mOrtho );
    Output.UV = Input.UV;
    return Output;
}
float4 DilationPass_Pixel_Shader( PS_INPUT_Quad Input ) : COLOR0
{
    float4 vC = tex2D( g_SamplerLightMap, Input.UV );
    if( vC.w != 0 )
        return vC;

    int nValidPixels = 0;
    float4 vFinalColor = 0;
    for( int i = 0; i < 8; ++i )
    {
        float4 vNeighborColor = tex2D( g_SamplerLightMap, Input.UV + TexelKernel[ i ] );
        if( vNeighborColor.w == 0 )
            continue;

        //vFinalColor = ( length( vFinalColor ) > length( vNeighborColor ) ) ? vFinalColor : vNeighborColor;
        vFinalColor += vNeighborColor;
        nValidPixels++;
    }
    return vFinalColor / max( nValidPixels, 1 );
}

```

# Answer
> 3 votes
First of all, the process of finding the pixels that fall in a triangle is called rasterization. You might want to look up some articles on fast software rasterization, or better yet move the lightmap build process (or at least the rasterization part of it) to the GPU, as it'll be much, much faster.

There are two possible solutions to the problem of cracks in lightmaps. One solution is image-based. After rasterizing the triangles normally, apply a dilation filter using a pixel shader, to fill in the value of undrawn pixels with adjacent drawn ones. (You can use the alpha channel to easily keep track of which pixels were drawn.) Run a couple passes of this and it'll grow a couple-pixels-thick border around each patch in the lightmap.

The other possible solution is conservative rasterization (google it). That means rasterizing all pixels that touch a primitive, instead of just those whose center falls in the primitive. IIRC in a software rasterizer it's a fairly simple modification of the equations; GPU hardware rasterizers don't directly support it, but it can be simulated by expanding each triangle by one pixel (as shown in this article for example). This will have the side effect that previously-watertight adjacent triangles will now overlap, though, which can cause its own set of problems. I'd probably stick with the image-space method.

---
Tags: c++, directx, uv-mapping, lightmap, barycentric-coordinates
---


# Question
Title: How can I get post-processing effects with pygame?
I'd like to be able to make the screen like blurry and wavy, like when a player enters a portal in Minecraft.

How would I make this with pygame?

# Answer
My suggestion would be to use surfarrays in conjunction with NumPy.

Assuming you already have an algorithm for the post-processing effects you want, all you'll have to do is port it into NumPy syntax, which will probably just take some tinkering. Examples of usage can be found here, here, here, and here.

After manipulating the surface, you just have to take whatever is output and blit it back to the screen.

A word of warning: full screen processing in pygame, even with surfarrays and NumPy, can be very slow. I once tried to create a desaturation post-processing effect for a pygame game, and struggled to get the game to run at 30fps at something like 640x480 resolution. Of course, if you get speedy results, I'd love to see how you did it :)
> 3 votes

---
Tags: python, pygame, post-processing
---


# Question
Title: How to implement "model quality" in OpenGL
In many games, there is an option named: "Model Quality", which ranges from Low to High. Low model quality simply removes a lot of vertices from the model, to make it faster, while High preserves the original model vertices (I think).

So I'm wondering, how do I implement this in my game?

# Answer
Usually this is done through LODs (Level of Detail). This is just a name for having several models of the same object with different detalization. In the options you may specify the highest LOD to use.

**LOD models are usually made manually** by artists because programmatic simplification often results in poor quality for anything more complex than a generic sphere. Programmatic approach may work well for untextures lowest quality models (usually used at a great distances from camera).

In the game you have e.g. 3 models, High-Medium-Low. High quality model is used from 0 to 50 meters away from camera, Medium from 50 to 150 and Low for anything farther that 150 meters. In setting you can specify Medium quality and then you rig Medium model to be used from 0 to 100 meters and Low otherwise. The exact numbers may depend on your game and models quality.
> 4 votes

---
Tags: opengl, models
---


title: How can I create a Killing Floor map?

text:
# Question
Title: How can I create a Killing Floor map?
I'm trying to create a Killing Floor map and i have the latest Unreal Engine but i dont know how to export my map to Killing Floor. Where can i find the correct version of Unreal Editor ? How can i export my map with current version ?

# Answer
Killing Floor was created with the Unreal-2 engine, not the Unreal-3 engine (UDK), so you're kind of trying to export backwards. You're going to run into problems doing this - if it even works at all.

Try copying it across in chunks. First select all the BSP (Right click on a BSP mesh and go Select All \> Same Class), then copy and see if it will paste into the Unreal-2 editor. As BSP should more or less be the same in both engines, this *should* work. As for meshes and other assets, you'll have to export them from your Unreal-3 package, then import them individually into your assets package in Unreal-2. ... And then manually place them back in to your map. This is generally the only way you could do something like this.

What you're trying to do is very arduous and tedious due to the fact you're trying to move a map from one engine to another. There is definitely no in-built function in UDK for backwards-exporting. I wish you the best of luck if you're still attempting this.
> 2 votes

---
Tags: maps, udk, unreal, map-editor
---


# Question
Title: How can I structure my ASCII terrain object?
So I have this object which represents a simple ASCII "overworld". Note the code is broken, but it's for demonstration purposes...

```
var TerrainObj = {
    w: { name: 'water', glyph: 'w' },
    g: { name: 'ground', glyph: 'g' },

    terrain: [[w, w, w, w],
              [w, g, g, w],
              [w, g, w, w],
              [g, g, w, w]],

    generate_display: function(terrain) {
        ...
        Code that returns an array the same as terrain but containing
        the glyphs from the objects in terrain
        ...
    }
}

```

So as you can see, the object contains the data for different types of terrain cell, the overworld itself, and a method to covert the terrain info into an array of glyphs for printing to the screen. But of course the problem with this code is that in the `terrain` array, there will be an reference error to each object.

I want to be able to write out the terrain array without using more than a one-letter name, because presumably to get this to work I'd have to do something like

```
terrain: function() {
    var map = [[this.w, this.w, this.w, ...],
               ...
               ...
               ];
}

```

So is there a nicer way I can produce my "semantic" terrain layer that references objects but without me having to write lengthy references to them in my array declaration?

# Answer
> 1 votes
So, from what I've read, it appears that you want be able to write the map without much work. Here's a few ideas:

**1)** Create a small application/app/whatever you want to build the maps. It could be as simple as making a bunch of check boxes if you only have two types of terrain. Or a bunch of square text fields that you can tab through and type into. This approach will be quite useful if you end up making lots of maps.

**2)** Declare your array like so:

```
terrain: function() {
    var map = [['w', 'w', 'w', ...],
           ...
           ...
           ];
}

```

By doing that, you can simply index the other table with the value of whatever location you need in the table. So, if you need square 3,3 you can get all of its info with:

```
TerrainObj[map[2][2]].WhateverProperty

```

I apologize for any messed up JavaScript syntax I may have given you.

---
Tags: javascript, roguelikes
---


title: generating complex maps in xna

text:
# Question
Title: generating complex maps in xna
I just wonder how does these maps like in this video are made.
http://www.youtube.com/watch?v=TM6kcOau5oQ
I was looking for some tutorials on the web but no success. All I found was some 2D Vectors (Matrixes) with 0,1,2 values on it but I think these maps are generated and stored in a different ways. Can somebody help me or give me some advice about these maps.
I saw some presentations about indie games and I was just amazed by these games. I want to make my own game. I am a beginner and already started an XNA book and some tutorials. I would like to learn how these games are made. Thanks!

# Answer
> 1 votes
To create maps like the one in the video you could start with 'tile-base maps'. Tiled maps implement the idea that your map is created from similiar sized blocks with different textures. There is a good tutorial for tile based maps with XNA. This tutorial explains some of the basics and shows different concepts which may be usefull. You question is very broad, so feel free to refine it, or get in contact if you got any particular problems with your journey in XNA ;)

LostGarden provides you with some graphics to start withenter link description here, if you just want to get your hands dirty with XNA and tile based maps.

---
Tags: xna, 2d, textures, maps
---


# Question
Title: How to transfer a luabind::object between two lua states
I store an object by a function call from Lua to C++ in first script in my application and after that I'll try to pass that object to other scripts and vice versa.

A part of script class in C++:

```
void script::set_property(lua_State* L, luabind::argument const& value)
{
  this->property_field = luabind::object(L, value);
}

luabind::object script::get_property(lua_State* L)
{
  return this->property_field;
}

```

Then in my script which is Script1.lua I do this:

```
script1:set_property(a table or a userdata or a string)
print(type(script1:get_property()))

```

The problem is, values sent by scripts are distinct in different Lua states because every script in my application has its own `lua_State`. The above code works fine when I call `script::get_property` from `Script1.lua`.

Since all of my scripts have access to other scripts in their contexts when I try to do this in other scripts like Script2.lua or Script3.lua or others:

```
print(type(script1:get_property()))

```

It won't print data type here properly and it'll return a number instead, which is a wrong result and the reason is `script1:get_property()` is returning a value that is only understood by `script1` and not in other scripts.

I understand values that have been registered in `script1` are only registered into that script's stack and registry table particularly and no one else, but my question is, is there any way to transfer these values between different Lua states?

Thanks.

# Answer
> 1 votes
Since you can't guarantee anything about the type of the argument you're passing between the states, essentially what you're looking for is to serialize / de-serialize the object. Fortunately Programming in Lua covers this: Chapter 12 - Data Files and Persistence. Essentially you are converting your Lua object from one state into a stream of bytes, passing it to your C++ layer as a stream of bytes, then passing it to the second state still as a stream of bytes, and then de-serialising it into table/object form again on the other side.

That's the only type-safe, generic way to transfer data of arbitrary types between lua\_States, although if you have constraints on the types of data then you might be able to make assumptions about what sort of data you need to serialize.

---
Tags: c++, lua
---


title: How to shoot on direction of touch

text:
# Question
Title: How to shoot on direction of touch
I'm new to the Corona SDK(and I also suck in trigonometry) and I'm trying to achieve this:

Shoot a bullet from the player, towards the direction of the point the user touched, but always with ethe same speed, regardless of how far the touch was from the player.

I have tried several solutions. After some research I saw that I should calculate the angle from the two deltas in degrees, and then use the cos and sin of the angle as the x and y values respectively. But when I try to do so, I get pretty random results.

The closer I was able to get from what I want to achieve was to use the delta variables as the X and Y (multiplied by the speed factor). It worked, but then the speed varied based on how far from the player I touched and I want the speed to be fixed.

Here's my latest code(using sin and cos)

```
local math, physics = require("math"), require('physics')

physics.start()
physics.setGravity( 0, 0 )

display.setStatusBar( display.HiddenStatusBar )

local screenW, screenH = display.contentWidth, display.contentHeight
local playerX, playerY = (screenW / 2), (screenH / 2)

local player = display.newRect( 0, 0, 30, 30 )
player.x = playerX
player.y = playerY

-- local sinT = display.newText("", 100, 10)
-- local cosT = display.newText("", 100, 30)
local angleT = display.newText("", 100, 70)

local function onScreenTouch( event )
  if (event.phase == "began") then
    speed = 3
    deltaX = event.x - playerX
    deltaY = event.y - playerY

    angle = math.atan2( deltaY, deltaX ) * 180 / math.pi

    -- sin, cos = math.sin( angle ), math.cos( angle )

    -- sinT.text = sin
    -- cosT.text = cos
    angleT.text = angle

    bullet = display.newRect( 0, 0, 6, 6 )
    bullet.x = playerX
    bullet.y = playerY

    physics.addBody( bullet )

    bullet:setLinearVelocity( math.cos( angle ) * speed, math.sin( angle ) * speed )
  end
end

Runtime:addEventListener( "touch", onScreenTouch )

```

# Answer
Basically you will want to do something like this:

```
deltaX = event.x - playerX
deltaY = event.y - playerY
normDeltaX = deltaX / math.sqrt(math.pow(deltaX,2) + math.pow(deltaY,2))
normDeltaY = deltaY / math.sqrt(math.pow(deltaX,2) + math.pow(deltaY,2))

...
bullet:setLinearVelocity( normDeltaX  * speed, normDeltaY  * speed )

```
> 1 votes

---
Tags: corona-sdk, trigonometry, angles
---


# Question
Title: Placing nodes in a graph in a random but readable way
I'd like to create a simple map from vertices and lines - you know, like a usual graph. A tree, to be precise.

To select the location of the next point that comes from one, I use a simple circle-equation function:

```
function Point_on_Circle(circle_x, circle_y)

degree = math.random(rad_min, rad_max)

point = { x = 0, y = 0, t = math.rad(degree) }

point.x = circle_x + radius*math.cos(point.t)
point.y = circle_y + radius*math.sin(point.t)

return point

end

```

The result is something like this:

That's a complete mess! What to do to make it readable? As you can see, I checked, how many ways are going from each single points, but don't have much idea, what to do with them.

The problem is that it's impossible to see individual points because their lines cross each other. I want to avoid line crossing *at all*, like in a usual tree.

# Answer
Force-directed graphs may be use to create a planar graph *embedding* in which there are no crossings and each individual node is a reasonable distance (depending on your definition thereof) from each of the others. **However** there is more to this than meets the eye.

A planar *embedding* is distinct from the concept of a planar *graph*. A planar *embedding* is simply *one* representation of a graph, which contains no edge crossings. Consider a bundle of string, with various sections tied together in a complex pattern: If you drop that bundle of string, then there may be an infinite number of ways in which it may lie, once it has fallen... each of these is a separate embedding (arrangement) of the very same graph. However, some graphs are inherently non-planar and so **cannot** be drawn without crossings... a planar *graph* is a graph which may, in some way shape or form, be embedded / drawn without crossing edges. Ascertaining whether a *graph* is definitely planar is **hard**, because the definition of a non-planar graph is one which contains the Kuratowski subgraphs K3,3 or K5 as minors (not quite the same as subgraphs), and finding / extracting these algorithmically is an incredibly complex process (c.f. Boyer-Myrvold, Fraysseix et al.).

However, as you are presumably generating this graph yourself (?), and in doing so, appear to be generating a DAG (from what I can see of your snapshot), you should never have to worry about introducing either of the dreaded Kuratowski subgraphs. That is to say that without the introduction of cycles, K3,3 and K5 cannot be formed as minors.

The simplest approach to enforcing graph planarity *if you are generating the graph yourself*, is as follows: Instead of trying to map an existing graph topology to a planar surface topography, instead generate the graph within a surface that is already planar, then recursively subdivide the space as necessary in order to create more space for each new node as it is constructed. Structures that immediately come to mind in this regard are:

Alternatively, you may note from the Kuratowski subgraph link above, that Boost contains an implementation of Boyer-Myrvold, if you are using C++ and don't mind adding the library.

Also, a Voronoi plane along with the use of Lloyd's algorithm will give you a similar end result to a force-repelled set of nodes, ultimately resulting in a nice, organic-looking graph compare with the 3- and 4-gon approaches.
> 3 votes

---
Tags: algorithm, maps, procedural-generation, tree, graph
---


title: Tile Maps and vertexZ order for sprites

text:
# Question
Title: Tile Maps and vertexZ order for sprites
Here is the setup. I have a orthogonal tile map made with Tiled. There are 5 layers. The bottom 4 comprise the background, while the top layer is the foreground that I will refer to as the “tree” layer. I have a hero sprite that I have added as a child of the tile map at the same node zorder as the tree layer.

The issue that invariably comes up with this scenario is that I want my hero to be in front of trees that he is “below”, but behind those trees that he is “above”. Below and above are determined by the Y coordinate of the hero versus the Y coordinate of any given tree.

The Cocos2d programming guide contains a section for tile maps, and in that section it specifically discusses how to achieve the affect I have described. This information can be found here.

http://www.cocos2d-iphone.org/wiki/doku.php/prog\_guide:tiled\_maps

The solution is pretty simple. Enable the depth buffer in my code. Add a cc\_vertexz property with a value of -1000 to each layer that the hero will be above. Then add a cc\_vertexz property to the tree layer with a value of “automatic” as well as a cc\_alpha\_func property with a value of .5. Then as your hero moves re-adjust its sprite’s vertexz value based on its position within the map.

I did all this and it worked great. However, a problem appeared as soon as I added other “enemy” sprites to this map. As with the hero sprite these sprites were added to the map with the same node zorder as the tree layer, and they too have their vertexz values changed based on their Y coordinate within the map. It should be noted that the hero sprite is added after the enemy sprites. In addition, both the hero and enemy sprites are animated and their textures are not part of the tile map textures. Based on the Cocos2d documentation this should not matter.

The problem is this. If my hero is below an enemy sprite on the map then everything looks and works fine. However, if my hero is above an enemy sprite on the map then as the enemy passes over the hero sprite the background comes through rather than the hero sprite. The best way to describe it is to say that as soon as the enemy sprite begins to pass over the hero sprite, the transparent areas of the enemy sprite begin to fill with the background and the hero sprite is partially obscured until then enemy sprite moves off the hero. It is like the hero sprite is not there.

I know this is related to the order that the sprites are added to the map, because if I change this and have the hero sprite added to the map before the enemy sprites, then the effect reverses in that the background comes through the transparent areas of the hero sprite rather than the enemy sprites. It is almost like the vertexz property is not absolutely determining the order that things are drawn.

Looking into this it appears to be a blending issue and I found what seems to be the solution, which is to subclass the CCSprite class and override the draw method with the following:

```
-(void) draw {

   glEnable(GL_ALPHA_TEST);

   glAlphaFunc( GL_GREATER, 0 );

   [super draw];

   glDisable(GL_ALPHA_TEST);

}

```

The problem however is that this code is not applicable to the version of Cocos2d that I use, which is Cocos2d 2.1. In addition this appears to be handled by the CCTMXLayer drawing function if automatic vertexz is enabled. As such I do not know if subclassing CCSprite would just be redundant. See below for how CCTMXLayer handles this:

```
// CCTMXLayer drawing function
-(void) draw

{

    if( useAutomaticVertexZ_ ) {
        glEnable(GL_ALPHA_TEST);
        glAlphaFunc(GL_GREATER, alphaFuncValue_);
    }

    [super draw];

    if( useAutomaticVertexZ_ )
        glDisable(GL_ALPHA_TEST);
}

```

I am not new to Cocos2d, but I am very new to anything related to OpenGL. So in short, is the solution just to subclass CCSprite and find the Cocos2d 2.1 equivalent to the above code snippet, or am I simply doing something wrong? I suspect the latter.

Any help would be very much appreciated. Thanks!

# Answer
This has been resolved. The solution was to use the following on my sprites or sprite sheets as the case may be:

```
mySprite.shaderProgram = [[CCShaderCache sharedShaderCache]programForKey:kCCShader_PositionTextureColorAlphaTest];

```

This essentially takes the place of sub-classing CCSprite and overriding the draw method, which is the prescribed method for Cocos2d 1.x, whereas I am using Cocos2d 2.x.
> 0 votes

---
Tags: cocos2d, tilemap, draw-order
---


title: Split up a screen into regions

text:
# Question
Title: Split up a screen into regions
My task: I want to split up a screen into 3 regions for buffs-bar (with picked items), score-info and a game-map. It doesn't matter are regions intersect with each other or not.

For example: I have a screen with `width=1; height=1` and the origin of coordinates (0;0) is the left bottom point. I have 3 functions: draw items, draw info, draw map. If I use it without any matrix transformations, it draws fullscreen, because it's vertex coordinates are from 0;0 to 1;1. (pseudo-code)

```
drawItems();
drawInfo();
drawMap();

```

And after that I see only map onto info onto items.

My goal: I have some matrixes for transformation vertexes with 0;0-\>1;1 coordinates to strict regions. There is only one thing, what I need to do - set matrix before drawing. So my call of drawItems-function is like: (pseudo-code)

```
adjustViewMatrixes_andSomethingElse(items.position_of_the_region_there_it_should_be_drawn, items.sizes_of_region_to_draw);
setItemsMatrix();
drawItems(); //the same function with vertex coordinates 0;0->1;1,
             //but it draws in other coordinates,
             //because I have just set the matrix for region

```

I know only some people will understand me, so there is a picture with regions which I need to make. Every region has 0;0 -\> 1;1 inner coordinates.

# Answer
This is basic arithmetic, really, and is easily extended to basic linear algebra if you're matrix-inclined.

If you have coordinates `(X,Y)` with range `[0,1]`. You want these to map to a screen region with range `X:[Lx,Ux]` and `Y:[Ly,Uy]`. You need only solve the simple algebraic expressions `0Sx+Tx=Lx` and `1Sx+Tx=Ux` (and then the same for the Y coordinates), where `Sx` is the amount you *scale* X from one coordinate basis to the other and `Tx` is the amount you *translate* X. These terms should look familiar to a game developer and you should be able to trivially see how to make a standard 2D affine transformation matrix out of these terms.

**Example:**

You want to make a region which is in the upper quarter of an 800x600 screen. So the ranges are `X:[400,800]` and `Y:[0,300]`. Solving for Sx and Tx:

```
0Sx+Tx=400   1Sx+Tx=800
Tx=400       Sx+400=800
Tx=400       Sx=400

X2=X1*400+400

```

And that's it. To take a `[0,1]` coordinate to the upper right quadrant in screen-space coordinates, multiply by 400 and add 400. If you need to translate to view-space coordinates, e.g. where the coordinate ranges are `[-1,+1]`, the upper right quadrant is now `X:[0,+1]` and `Y:[-1,0]`. So now the math comes out:

```
0Sx+Tx=0     1Sx+Tx=1
Tx=0         Sx+0=1
Tx=0         Sx=1

X2=X1*1+0
X2=X1

```

And of course scaling by 1 is the identity scale and translating by 0 is the identity translation... so for the X component, mapping coordinates from `[0,1]` to the right-half of the screen is a no-op! Let's look at the slightly more interesting Y component:

```
0Sy+Ty=-1    1Sy+Ty=0
Ty=-1        Sy-1=0
Ty=-1        Sy=1

Y2=Y1*1-1
Y2=Y1-1

```

And indeed, that's the correct result. Mapping `[0,1]` to `[-1,0]` really is just a matter of subtracting 1.

If you need to find the region of the screen in view-space coordinates from screen-space coordinates (e.g. to map the pixel coordinates to the view-space coordinates), use the exact same approach. Just remember you're mapping from something like `[0,800)` to `[-1,+1]`, e.g.

```
 0Sx+Tx=-1    800Sx+Tx=1
 Tx=-1        800Sx-1=1
 Tx=-1        800Sx=2
 Tx=-1        Sx=1/400

 X2=X1/400 - 1

```

And the 3x3 affine matrix in a column-major format:

```
 | Sx 0  Tx |
 | 0  Sy Ty |
 | 0  0  0  |

```
> 1 votes

# Answer
I see what you are saying, but it most likely would be simpler to just use the coordinates for the whole screen.

However one way you could implement would be to have three pairs of x and y floats, then offset them depending on how big your screen is.
> 0 votes

---
Tags: opengl, java, 2d, android, transformation
---


# Question
Title: How to reduce the time it takes to speed up an object?
I have a body that I am applying a force to every step. However, I it takes a significant amount of time for it to speed up, which I do not want. Is there some value I can adjust to help with this?

# Answer
> 4 votes
Like in "real life" physics to make it speed up faster (higher acceleration), increase the force or decrease the mass. You may be familiar with the common physics equation `F=MA`, you can also look at that as: `Acceleration=Force/Mass`.

So lowering the mass or increasing the force will change the acceleration. Where acceleration, of course, is the change in velocity over time, which is exactly what you're interested in.

---
Tags: physics, box2d
---


title: Game design for lumosity type games

text:
# Question
Title: Game design for lumosity type games
This must be a odd question. My company asked me to design some games similar type of lumosity (http://www.lumosity.com/). I guess someone already played those games. I fight with them, saying , the algorithm behind is proprietor and gave a reference of below link:

http://www.lumosity.com/blog/brain-performance-index-what-is-bpi/

They said, keep the algorithm in BLACK BOX and go ahead of designing the game. Now I have no idea how to start without that algorithm. So I need experts suggestions. Anyone have any idea about this, I mean how to think/design about the games? Should I simply tell them, it is not possible, you can fire me?

# Answer
1) Collect small puzzles under these topics memory, attention, flexibility, speed of processing, and problem solving.

2) Give the user points based on their performance in each mini games. And finally give them a performance based points for each factors.

3) With all these points calculate a index. Find which factor they are falling back. If they are bad in memory, give them more training towards memory based games until they increase their points in those area.

The index algorithm is what is tough to form. The company should have done good research and statistics from lots of users before framing the algorithm. Otherwise it should be quite easy to roughly show a graph based on they score in different games.
> 4 votes

---
Tags: game-design
---


# Question
Title: libgdx fixture is giving unresponsive error
need some support. I am novice in libgdx game engine. Below is my code

```
package com.game.box2d.fruitcart;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.Shape;
import com.badlogic.gdx.physics.box2d.World;

public class FruitCartBox2D extends Game{

    World world;
    Box2DDebugRenderer debugRenderer;
    OrthographicCamera camera;

    static final float BOX_STEP = 1 / 60f;
    static final int BOX_VELOCITY_ITERATIONS = 6;
    static final int BOX_POSITION_ITERATIONS = 2;
    static final float WORLD_TO_BOX = 0.01f;
    static final float BOX_WORLD_TO = 100f;

    Sprite backgroundSprite;
    Sprite grassSprite;
    Sprite bucketSprite;
    Sprite fruitSprite;
    Music backgroundMusic;
    Sound dropSound;
    TextureAtlas atlas;
    SpriteBatch batch;
    Body body;
    @Override
    public void create() {

        world = new World(new Vector2(0, -10), true);
        camera = new OrthographicCamera();
        camera.viewportHeight = 480;
        camera.viewportWidth = 800;
        camera.position.set(camera.viewportWidth * .5f,
                camera.viewportHeight * .5f, 0f);
        camera.update();

        atlas = new TextureAtlas(Gdx.files.internal("data/packed.txt"));

        backgroundSprite = atlas.createSprite("background_original");
        grassSprite = atlas.createSprite("grass");
        bucketSprite = atlas.createSprite("bucket");
        fruitSprite = atlas.createSprite("apple");
        batch = new SpriteBatch();
        bucketSprite.setBounds(800 / 2 - 80 / 2, 35,80, 80);

        BodyDef bodyDef = new BodyDef();
        bodyDef.type = BodyType.DynamicBody;
        bodyDef.position.set(camera.viewportWidth / 2,
                camera.viewportHeight / 2);

        body = world.createBody(bodyDef);
        body.setUserData(fruitSprite);

        FixtureDef fixtureDef = new FixtureDef();
        fixtureDef.shape = new PolygonShape();
        fixtureDef.density = 1.0f;
        fixtureDef.friction = 1.0f;
        fixtureDef.restitution = 1;

        body.createFixture(fixtureDef);

        debugRenderer = new Box2DDebugRenderer();
    }

    @Override
    public void render() {

        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

        camera.update();
        debugRenderer.render(world, camera.combined);
        batch.setProjectionMatrix(camera.combined);

        batch.begin();
        batch.disableBlending();

        backgroundSprite.draw(batch);

        batch.enableBlending();
        grassSprite.draw(batch);
        bucketSprite.draw(batch);
        Sprite sprite = (Sprite) body.getUserData();
        sprite.setBounds(100, 400, 40, 45);
        sprite.draw(batch);
        batch.end();

        world.step(BOX_STEP, BOX_VELOCITY_ITERATIONS, BOX_POSITION_ITERATIONS);
    }
}

```

In above code, I have added a background in the form of sprites.It's working fine. After that, there is a fruitSprite, now I want to handle it with box2d so that I can apply gravity on fruitSprite. To achieve this, I've created a dynamic body, added fixture. Now, the problem is here : when I add a polygon shape to fixture and than attached to a body, it gives an unexpected error. It doesn't show any stacktrace. Following is the snapshot of error encountered.

If, I remove polygon shape from fixture, than it gives NullPointerException which shows that shape is mandatory for fixturedef.

I want to add fruitSprite to the box2d body so that I don't have to handle gravity of fruit.

Any help is appreciable, struggling from last 3-4 days.

# Answer
You haven't set any vertices on the shape. Create a new polygonshape and set the vertices of the shape using setAsBox or set(float\[\] vertices). Have a look at the documentation!
> 2 votes

---
Tags: java, libgdx, box2d
---


title: Record new animation in Motion Builder

text:
# Question
Title: Record new animation in Motion Builder
I was rigged a 3d character model using MotionBuilder software. now i want to record my own animation for this 3d model. im new for the motion builder and i was unable to find a good reference for learn about recording animation in motion builder.(i press the record button in time line but it says nothing to record). please help me and give me a brief introduction or reference that i can learn about creating new animation on rigged character in Autodesk MotionBuilder. thanks.... :)

# Answer
> 0 votes
You should watch 3dbuzz tutorials first. MoBu is not complicated but you need to learn it. the record button records the existing animation, so if you don't have one... you can find online mocap data Good luck

---
Tags: 3d, skeletal-animation
---


title: Getting body position

text:
# Question
Title: Getting body position
I am using `BodyA.getPosition().x` and `BodyA.getPosition().y` to get the `x` and `y` vector of a body location so i may attach some text above its head, but the `log` of that position prints out something like `3.666757....`. I want this text to be moving when the body moves so it should be relative to the body position at all times until removed. Currently when I try to use this

```
speech = new TickerText( 0, 0, font,
            ptext, new TickerText.TickerTextOptions( 10 ),
            ResourceManager.getInstance().vertexManager );

speech.setBlendFunction( GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA );
speech.setScale( 0.5f );
speech.setAutoWrapWidth( 500f );
speech.setAutoWrap( AutoWrap.WORDS );
speech.setPosition( xVal, yVal );`

```

The text is not displayed on screen on screen at all, I figure its the x and y location being wrong because when I manually set x and y to positions I know would be on the screen area it is shown. I am looking for help as how to get the actual `X` and `Y` coordinate of the body on screen so I can have the text follow the body.

# Answer
Basically there are two engine right now working for your game.

1. Game Engine
2. Physics Engine

Game engine works on pixel coordinate system and physics engine works on meter coordinate system. So that you print body x and y, you get coordinate in meter, this thing already you are getting.

You have to use

```
PhysicsConstant.PIXEL_TO_METER_RATIO

```

to convert meter data into pixel data.

So to get actual x and y for you text related to player body you have to write following statement :

```
playerX = bodyA.getPosition().x * PhysicsConstant.PIXEL_TO_METER_RATIO;
playerY = bodyA.getPosition().y * PhysicsConstant.PIXEL_TO_METER_RATIO;

```

If you don't want to all these stuff then you can directly use sprite x and y coordinate.
> 2 votes

---
Tags: android, box2d, andengine
---


# Question
Title: Trouble with a modified parallax scrolling concept
I have a set of layers (each of them being a list of items) moving with different speeds as I mentioned here: https://stackoverflow.com/a/18962019/270197. Layers back in the scene move with slower speed than those in the front. The position of items in the front layer is calculated from `VelocityTracker.getYVelocity()` (we are not doing infinite scrolling but responding to the user's gestures) by using standard Euler integration with friction applied to decrease the velocity by a fixed number of percent each frame.

I would need a similar dynamics class for the background layers that act as a satellite, that is, movement should gracefully finish at the same time so instead of an abrupt pause, the velocity of the slower layers should dynamically adjust to the top layer's velocity on each frame (reaching 0 together) to create a realistic but synchronized fling movement on each layer. Any ideas about the algorithm to achieve that?

**Update:** it is implemented now on github.

# Answer
> 0 votes
To keep the scroll velocity of each layer related to each other layer, I'd calculate the velocity of the top layer and then modify it by the relative depth of the current layer you're evaluating. Something like:

`layer_velocity = mVelocity * (1.0 - layer_depth)`

where layer\_depth is ranged 0.0 (top or surface level) to 1.0 (bottom or deepest level)

Notice that you won't get any movement at 1.0 depth, possible floating point errors aside, so you would either want to set your actual deepest layer to something less than 1.0, or modify the calculation to accommodate a depth of 1.0 while still providing a non-zero velocity result.

---
Tags: java, 2d, android, physics, parallax-scrolling
---


# Question
Title: Just 2 images on a window loaded using DirectX10...But how?
I am a beginner to DX and I have tried looking everywhere for something very similar to this concept but can't find anything.

I just want two rectangles on a window.

Rectangle 1 : on some x,y with some width and height with background as a PNG image Rectangle 2 : on some x,y with some width and height with background as a PNG image

And one other thing. I am trying to make it so that the image doesn't resize as I resize the window as this makes the pictures really blurry as they get bigger.

I know this is not the type of question that stack likes, but if you can give me some example that does this, I would be very delighted.

Thank you so much.

# Answer
Since you expressed interest in learning how to use DirectX, just in the context of your specific challenge, I have to direct you to an outside source.

'Teach me how to use DirectX' is a bit outside the scope of what this is meant for, and any complete answer would be far too long, besides.

For decent intro tutorials, I recommend: http://rastertek.com/tutindex.html

By tutorial 5 you'll have the tools you need to be able to complete your request. If, at that point, you still need help or are confused about something, that is a good time to post a question here about it.

The tutorials create an engine that *works*, though it needs a bit of redesign to be useful for more than learning. Regardless, that is a good place to start.
> 1 votes

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


# Question
Title: How to define type-specific scripts when using a 'type object' programming pattern?
I am in the process of creating a game engine written in C++, using the C/C++ SQLite interface to achieve a 'type object' pattern. The process is largely similar to what is outlined here (Thank you Bob Nystrom for the great resource!).

I have a generally defined Entity class that when a new object is created, data is taken from a SQLite database and then is pushed back into a pointer vector, which is then iterated through, calling update() for each object. All the ints, floats, strings are loaded in fine, but the script() member of Entity is proving an issue. It's not much fun having a bunch of stationary objects laying around my gameworld.

The only solutions I've come up with so far are:

1. Create a monolithic EntityScript class with member functions encompassing all game AI and then calling the corresponding script when iterating through the Entity vector. **(Not ideal)**
2. Create bindings between C++ and a scripting language.
    * This would seem to get the job done, but it feels like implementing this (given the potential memory overhead) and learning a new language is overkill for a small team (2-3 people) that know the entirety of the existing game engine.

Can you suggest any possible alternatives? My ideal situation would be that to add content to the game, one would simply add a script file to the appropriate directory and append the SQLite database with all the object data. All that is required is to have a variety of integers and floats passed between both the engine and the script file.

# Answer
> 1 votes
Make a series of Behaviour\* subclasses that implement each of your behaviours. Register them by name in a table. Store/load the name of the behaviour in the database.

```
 struct IBehavior { void think(); }
 struct VillagerBehavior : IBehavior;
 struct MonkeyBehavior : IBehavior;
 struct OgreBehavior : IBehavior;

 std::pair<string, IFactory*> behaviors[] = {
   { "villager", CreateFactory<VillagerBehavior>() },
   { "monkey", CreateFactory<MonkeyBehavior>() },
   { "ogre", CreateFactory<OgreBehavior>() },
 };

 IFactory* GetBehavior(string name) {
   return behaviors[name];
 }

```

Note that you can even extend this to allow multiple behaviors per entity using a priority list or action list AI.

---
Tags: c++
---


# Question
Title: Is it legal to use the Source Engine out of Steam?
I would like to create a game that uses the Source Engine on Desura, the problem is that I am afraid that it is illegal to use the Source Engine in other platforms are not managed by Valve

# Answer
Yes, you can as long as you license the engine, with terms permitting it.

The version of Source that comes with the games that you purchase is for modding those existing games, and you won't be able to produce executables with it (and if you do manage to, you're going to run into some other more costly problems).

Interested in licensing Source, refer to this handy information sheet.
> 4 votes

---
Tags: legal, valve, steam, source-engine
---


# Question
Title: cocos2d collision detection between two ccsprites i am using boundingBox but this method is not working
I am making a cocos2d side scroller and I am currently putting collision detection in. I have an enemy that shoots at the player. I want to have the bullets disappear when they hit the player. The enemy itself disappears when it touches the player but for some reason the bullet collision detection does not work. Here is the code for the enemy, bullets, and collision detection.

```
@implementation RedEnemy
@synthesize redEnemySprite,redEnemyBulletSprite;

+(id)createRedEnemy{
return [[[self alloc]init]autorelease];
}

-(id)init{
if ((self = [super init])) {
    CGSize size = [[CCDirector sharedDirector]winSize];
    screenWidth = size.width;
    screenHeight = size.height;

    //Make the redEnemy
    redEnemySprite = [CCSprite spriteWithFile:@"redenemy.png"];
    redEnemySprite.position = ccp(screenWidth + 100, screenHeight/2);
    [self addChild:redEnemySprite];

    //Set the speed of the redEnemy and bullet moving
    speed = 15;

    //Set the redEnemyFlameCounter
    redEnemyFlameCounter = 1;

    //Create the array
    bulletArray = [[NSMutableArray alloc]init];

    //Call the method that moves the redEnemy
    [self moveTheRedEnemy];

    //Start the redEnemyFlame
    [self schedule:@selector(redEnemyFlame:)interval:1.0f/7.0f];

    //Shoot the bullets
    [self schedule:@selector(shootTheBullets:)interval:1.0f/1.0f];

    //Check to see if redEnemy is off screen
    [self schedule:@selector(isRedEnemyOffScreen:)interval:1.0f/60.0f];

    //Test for bulletcollisions
    player = [Player createPlayer];
    [self addChild:player];
    [self schedule:@selector(testForRedEnemyBulletCollisions:)interval:1.0f/60.0f];

}
return self;
}

-(void)redEnemyFlame:(ccTime)delta{
redEnemyFlameCounter ++;

if (redEnemyFlameCounter % 2){
    [redEnemySprite setTexture:[[CCSprite spriteWithFile:@"redenemy2.png"]texture]];
}else{
    [redEnemySprite setTexture:[[CCSprite spriteWithFile:@"redenemy.png"]texture]];
}
}

-(void)moveTheRedEnemy{
ccBezierConfig redEnemyPath;
redEnemyPath.controlPoint_1 = ccp(screenWidth - 200, screenHeight + 750);
redEnemyPath.controlPoint_2 = ccp(screenWidth - 400, -1000);
//redEnemyPath.endPosition = ccp(screenWidth/3.4, screenHeight/2);
redEnemyPath.endPosition = ccp(-300, screenHeight + 150);

CCBezierTo* redEnemyBezierPath = [CCBezierTo actionWithDuration:speed    bezier:redEnemyPath];
[redEnemySprite runAction:redEnemyBezierPath];

}

-(void)shootTheBullets:(ccTime)delta{
//Create redEnemyBullets
redEnemyBulletSprite = [CCSprite spriteWithFile:@"thebullet.png"];
redEnemyBulletSprite.position = ccp(redEnemySprite.position.x, redEnemySprite.position.y);
[self addChild:redEnemyBulletSprite];

[bulletArray addObject:redEnemyBulletSprite];

//CCMoveTo* bulletMove = [CCMoveTo actionWithDuration:5.0 position:ccp(player.playerSprite.position.x, player.playerSprite.position.y)];
CCMoveTo* bulletMove = [CCMoveTo actionWithDuration:5.0 position:ccp(-500, redEnemyBulletSprite.position.y)];
[redEnemyBulletSprite runAction:bulletMove];
}

-(void)isRedEnemyOffScreen:(ccTime)delta{
if (redEnemySprite.position.x < -100) {
    [self unschedule:@selector(isRedEnemyOffScreen:)];
    [self unschedule:@selector(redEnemyFlame:)];
    [self unschedule:@selector(shootTheBullets:)];
}

}

-(void)testForRedEnemyBulletCollisions:(ccTime)delta{
if (CGRectIntersectsRect(redEnemyBulletSprite.boundingBox, player.playerSprite.boundingBox)){
       wasPlayerHitByRedEnemyBullet = YES;
}
if (wasPlayerHitByRedEnemyBullet) {
    redEnemyBulletSprite.visible = NO;
}
}

-(void)dealloc{
[super dealloc];
}
@end

```

The player is created in a different class. Here is the code.

```
@implementation Player
@synthesize playerSprite;

+(id)createPlayer{
return [[[self alloc]init]autorelease];
}

-(id)init{
if((self = [super init])){
    CGSize size = [[CCDirector sharedDirector]winSize];
    screenWidth = size.width;
    screenHeight = size.height;

    gravity = 2;

    playerSprite = [CCSprite spriteWithFile:@"thefinalcharacter.png"];
    playerSprite.scale = 1.5;
    playerSprite.position = ccp(screenWidth/3.4, screenHeight/2);
    [self addChild:playerSprite z:-3];

    [self schedule: @selector(flight:)interval:1.0f/7.0f];

    }
return self;
}

-(void)flight:(ccTime)delta{
flightCounter ++;

if (flightCounter % 2){
    [playerSprite setTexture:[[CCSprite spriteWithFile:@"thefinalcharacter.png"]texture]];
}else{
    [playerSprite setTexture:[[CCSprite spriteWithFile:@"thefinalcharacter2.png"]texture]];
}
//[self schedule:@selector(updatePosition:)interval:1.0f/30.0f];
}

-(void)updatePosition:(ccTime)delta{
if(playerSprite.position.y < 35){
    gravity = 0;
}else if(playerSprite.position.y > screenHeight - 150) {
        playerSprite.position = ccp(playerSprite.position.x, playerSprite.position.y - 100);
}else{
    gravity = 2;
}

playerSprite.position = ccp(playerSprite.position.x, playerSprite.position.y - gravity);
}

-(void)dealloc{
[super dealloc];
}
@end

```

# Answer
I am a little confused by the code, but I will do my best to help you.

Well, it looks like your intent was to create a bullet sprite each time the shootTheBullets routine is called, and then add the sprite to your bulletArray. If that is the case you need to change the testForRedEnemyBulletCollisions routine to loop through the bulletArray and check each bullet against the player. Presently your code keeps checking the same instance variable called redEnemyBulletSprite over and over again. This would work fine if you only had one bullet on the screen at any given time, but if that were the case then you would not need a bullet array. The bullet array implies that you want to have multiple bullets at a time.

Now, even if you begin to loop through your array I perceive a problem with your code. First, redEnemyBulletSprite is an instance variable that you use each time you create a bullet, and you keep adding this same instance variable to the same parent and to the same bulletArray. This could have unpredictable results. Also, it is my guess that you only do see one bullet per enemy on the screen at any given time because of this, but that is hard to say by just looking at the code you have posted. Regardless, if this is not your intent then you should instead us a local variable to define your bullet sprite, such as bullet, then add the bullet to the parent and to your bulletArray. Then just simply loop through the bullet array in your testForRedEnemyBulletCollisions routine to check each bullet sprite against the player.

The problem with this approach is that your bulletArray will continue to grow as your game plays on, since you are adding a new bullet to the parent and to the bullet array each time one is fired. This could cause a significant performance issue if you end up with hundreds or potentially even thousands of bullets being fired in a given level. Obviously this depends on the number of enemy ships, their rate of fire, and how long the level lasts.

To avoid this you can remove the bullet from the parent and from the bullet array if it hits the player or leaves the screen. This in my opinion is not the best approach because of potential performance issues, but it will work depending on your particular situation.

Let me know if this helps, or if you need further information.
> 0 votes

---
Tags: collision-detection, ios, cocos2d, objective-c, side-scroller
---


# Question
Title: Is it possible to emulate vector scaling with raster graphics?
I'm looking to develop a Tech Design Document with my programming team and we're now on the fence about a major 2D graphical engine decision.

What we would like to try to emulate is a more dynamic camera to allow dynamic and fluid zooming in order to have in game cutscenes and add some extra mood to the game.

Someone has already asked pretty well the same question we'd ask about vector vs raster so I'd like to ask a follow up question elaborating on that.

Considering that vector graphics can lead to trouble down the line. Could we potentially have a master sprite that is, using the metric of the discussion at the link, 10x bigger than the desired in game sprite and then actively scale it down. Then when we want to zoom in and out we can change the down scaling so that the output sprite gets smoothly larger and smaller as the 'camera' zooms?

Would it be possible to optimize such a system for a game that has a somewhat complex environment, 2 player controlled characters and around... a maximum of 10 enemies on screen at any given time?

# Answer
As Nathan Reed said, this is a standard feature of 3D engines. The texture resolution can be as high as the memory permits, and mipmapping can be used to adapt the workload to the viewing distance and reduce aliasing. Hardware acc

Nowadays lots of 2D games are actually using a 3D engine in the background, because that's the easiest path. If you want to get fancy you could probably find a 2D framework that benefits from hardware acceleration, see this answer for some suggestions.

So I guess the answer is: if you have the resources to handle the extra work, no problem.
> 0 votes

---
Tags: graphics, vector-art
---


# Question
Title: Smooth animation when using fixed time step
I'm trying to implement the game loop where the physics is independent from rendering but my animation isn't as smooth as I would like it to be and it seems to periodically jump. Here is my code:

```
// alpha is used for interpolation
double alpha = 0, counter_old_time = 0;
double accumulator = 0, delta_time = 0, current_time = 0, previous_time = 0;
unsigned frame_counter = 0, current_fps = 0;

const unsigned physics_rate = 40, max_step_count = 5;
const double step_duration = 1.0 / 40.0, accumulator_max = step_duration * 5;

// information about the circ;e (position and velocity)
int old_pos_x = 100, new_pos_x = 100, render_pos_x = 100, velocity_x = 60;

previous_time = al_get_time();

while(true) {
    current_time = al_get_time();
    delta_time = current_time - previous_time;
    previous_time = current_time;
    accumulator += delta_time;

    if(accumulator > accumulator_max) {
        accumulator = accumulator_max;
    }

    while(accumulator >= step_duration) {
        if(new_pos_x > 1330) velocity_x = -15;
        else if(new_pos_x < 70) velocity_x = 15;

        old_pos_x = new_pos_x;
        new_pos_x += velocity_x;
        accumulator -= step_duration;
    }

    alpha = accumulator / static_cast<double>(step_duration);
    render_pos_x = old_pos_x + (new_pos_x - old_pos_x) * alpha;

    al_clear_to_color(al_map_rgb(20, 20, 40)); // clears the screen
    al_draw_textf(font, al_map_rgb(255, 255, 255), 20, 20, 0, "current_fps: %i", current_fps); // print fps
    al_draw_filled_circle(render_pos_x, 400, 15, al_map_rgb(255, 255, 255)); // draw circle
    // I've added this to test how the program will behave when rendering takes
    // considerably longer than updating the game.
    al_rest(0.008);
    al_flip_display(); // swaps the buffers

    frame_counter++;

    if(al_get_time() - counter_old_time >= 1) {
        current_fps = frame_counter;
        frame_counter = 0;
        counter_old_time = al_get_time();
    }
}

```

I have added a pause during the rendering part because I wanted to see how the code would behave when a lot of rendering is involved. Removing it makes the animation smooth but then I'll have to make sure that I don't let the frame rate drop too much and that doesn't seem like a good solution. I've been trying to fix this for a week and have had no luck so I'd be very grateful if someone can read through my code. Thank you!

Edit: I added the following code to work out the actual velocity (pixels per second) of the ball each time the ball is rendered and surprisingly it's not constant so I'm guessing that's the issue. I'm not sure why it's not constant.

```
alpha = accumulator / static_cast<double>(step_duration);
render_pos_x = old_pos_x + (new_pos_x - old_pos_x) * alpha;
cout << (render_pos_x - old_render_pos) / delta_time << endl;
old_render_pos = render_pos_x;

```

# Answer
> 2 votes
I think that the following part of your code is problematic:

```
if(accumulator > accumulator_max) {
    accumulator = accumulator_max;
}

```

You are basically doing a `clamp()` here, saying that every time difference which exceeds five steps should be disregarded, since

```
accumulator_max = step_duration * 5;

```

Should one iteration of your game loop require more than 0.125 seconds, your code will ignore this and move your objects not as far as it should do according to the real time difference.

# Answer
> 1 votes
@ph4nt0m's answer is *probably* the fix to your problem.

Another potential issue you're seeing is that the physics are simple too coarse. You can try increasing the rate of physics iterations (reduce `step_duration`). Your current duration is only 40Hz, so the game is going to look choppy compared to many 60Hz games, especially as 40 does not evenly divide into 60 (some render frames will see a physics update, some won't). Consider running at \>=60Hz for physics, or sticking to 20 or 30 or another number that divides evenly into 60.

Yet another more complicated fix, necessary in "higher end" games, is to interpolate between physics updates. You store the previous physics state and the current one calculated at each physics step. You then use the raw `delta_time` to interpolate between these two states during rendering. This lets you get away with a longer interval between physics updates and adds a mostly negligable overhead to rendering if done intelligently. The support for interpolation here comes in handy for network support, too.

---
Tags: animation, fixed-timestep, allegro
---


# Question
Title: Flexible alternatives to many many small polymorphic classes (for use as properties or messages or events) C++
There are two classes in my game that are really useful, but slowly becoming a pain. Message and Property (property is essentially a component).

They both derive from a base class and contain a static id so that systems can only pay attention to the ones they want to. It's working out very well... except...

I'm constantly making new message types and property types as I extend my game. Each time I need to write 2 files (hpp and cpp) and a ton of boilerplate to get essentially an classID and one or two standard data types or a pointer.

It's starting to make playing around and testing out new ideas a real chore. I wish when I want to create a new message or property type, I want to be able to just type something like

```
ShootableProperty:  int gunType, float shotspeed;

ItemCollectedMessage:  int itemType;

```

instead of creating a header and cpp file, writing a constructor, including the parent class, etc etc.

It's around 20 - 40 lines (including include guards, and everything) just to do what logically is 1 or 2 lines in my mind.

Is there some programming pattern to get around this?

What about with scripting (which I know nothing of)... is there a way to define a bunch of classes that are almost the same?

---

Here is exactly what one class looks like:

```
// Velocity.h

#ifndef VELOCITY_H_
#define VELOCITY_H_

#include "Properties.h"

#include <SFML/System/Vector2.hpp>

namespace LaB
{
namespace P
{

class Velocity: public LaB::Property
{
public:
    static const PropertyID id;

    Velocity(float vx = 0.0, float vy = 0.0)
    : velocity(vx,vy) {}
    Velocity(sf::Vector2f v) : velocity(v) {};

    sf::Vector2f velocity;
};

} /* namespace P */
} /* namespace LaB */
#endif /* LaB::P_VELOCITY_H_ */

// Velocity.cpp

#include "Properties/Velocity.h"

namespace LaB
{
namespace P
{

const PropertyID Velocity::id = Property::registerID();

} /* namespace P */
} /* namespace LaB */

```

All of that just for a 2D Vector and an ID saying to expect a 2D vector. (Granted, some properties have more complicated elements, but it's the same idea)

# Answer
C++ is powerful, but it's *verbose*. If what you want is lots of small polymorphic classes that are all different, then yes, it's going to take lots of source code to declare and define. There's nothing to do about it, really.

Now, as ltjax said, what you're doing here isn't exactly polymorphism, at least for the code you've provided. I can't see a common interface that would hide the specific implementation of sub-classes. Except maybe for the class ID, but this is actually redundant with the real class ID: it's name. This seems to be just a bunch of classes containing some data, nothing really complicated.

But this doesn't solve your problem: you want to create lots of messages and properties with the least amount of code. Less code means less bugs so this is a wise decision. Unfortunately for you there's no single solution. It's hard to tell what would suit your needs the most *without knowing precisely what you intend to do with those messages and properties*. So let me just expose your options:

1. Use C++ templates. Templates are a great way to let the compiler "write code" for you. It's becoming more and prominent in the C++ world, as the language evolves to support them better (e.g. you can now use a variable number of template parameters). There's a whole discipline dedicated to the automated generation of code through templates: template metaprogramming. Problem is: it's tough. Don't expect non-programmers to be able to add new properties themselves if you plan to use such a technique.
2. Use plain-old C macros. It's old school, easy to over-abuse, and error-prone. They are also very simple to create. Macros are just glorified copy-pastes performed by the preprocessor, so they're actually quite suited to create tons of things that are almost the same with little variations. But don't expect other programmers to love you for using them, as macros are often used to hide flaws in the overall program design. Sometimes, though, they're helpful.
3. Another option is to use an external tool to generate the code for you. It's already been mentioned in a previous answer so I won't expand on that.
4. There are other languages that are less verbose and will allow you to create classes way more easily. So *if* you already have script bindings (or you plan on having them), defining those classes in script might be an option. Accessing them from C++ will be quite complicated though, and you'll lose most of the benefit of the simplified creation of classes. So this is probably viable only is you plan on doing most of your game logic in another language.
5. Finally last but not least, you should consider using a data-driven design. You could be define those "classes" in simple text files using a layout similar to the one you proposed yourself. You'll have to create a custom format and parser for it, or use one of the several already available options (.ini, XML, JSON and whatnot). Then on the C++ side, you'll need to create a system that supports a collection of those different kinds of objects. This is almost equivalent to the scripting approach (and probably requires even more work), except you'll be able to tailor it more precisely to your needs. And if you make it simple enough, non-programmers might be able to create new things by themselves.
> 1 votes

# Answer
How about a code generation tool to help you out?

for example, you could define your message type and members in a small text file and have the code gen tool parse it and write all the boilerplate C++ files as a pre-build step.

There are existing solutions like ANTLR or LEX/YACC, and it would not be hard to roll your own depending on complexity of your properties and messages.
> 0 votes

# Answer
I advise you to research about Google's Protocol Buffers (http://code.google.com/p/protobuf/). They are a very clever way to handle generic messages. You just have to specify the properties in a struct-llike pattern and a code generator do all the job of generating the classes for you (Java, C++ or C#). All generated classes have text and binary parsers, which make them good for both text-based message initialization and serialization.
> 0 votes

---
Tags: c++, architecture, software-engineering, polymorphism
---


title: Collide with rotation of the object

text:
# Question
Title: Collide with rotation of the object
I'm developing a mirror for lazer beam(Ball sprite). There I'm trying to redirect the laze beam according to the ration degree of the mirror(Rectangle). How can I collide the ball to the correct angle if the colliding object is with some angle(45 deg) rather than colliding back.

here is an screen shot of my work

here is my code

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace collision
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        Texture2D ballTexture;
        Rectangle ballBounds;
        Vector2 ballPosition;
        Vector2 ballVelocity;
        float ballSpeed = 30f;
        Texture2D blockTexture;
        Rectangle blockBounds;
        Vector2 blockPosition;
        private Vector2 origin;
        KeyboardState keyboardState;

        //Font
        SpriteFont Font1;
        Vector2 FontPos;
        private String displayText;
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            ballPosition = new Vector2(this.GraphicsDevice.Viewport.Width / 2,
                           this.GraphicsDevice.Viewport.Height * 0.25f);
            blockPosition = new Vector2(this.GraphicsDevice.Viewport.Width / 2,
                                       this.GraphicsDevice.Viewport.Height /2);
            ballVelocity = new Vector2(0, 1);

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            ballTexture = Content.Load<Texture2D>("ball");
            blockTexture = Content.Load<Texture2D>("mirror");

            //create rectangles based off the size of the textures
            ballBounds = new Rectangle((int)(ballPosition.X - ballTexture.Width / 2),
            (int)(ballPosition.Y - ballTexture.Height / 2), ballTexture.Width, ballTexture.Height);

            blockBounds = new Rectangle((int)(blockPosition.X - blockTexture.Width / 2),
            (int)(blockPosition.Y - blockTexture.Height / 2), blockTexture.Width, blockTexture.Height);

            origin.X = blockTexture.Width / 2;
            origin.Y = blockTexture.Height / 2;
            // TODO: use this.Content to load your game content here
            Font1 = Content.Load<SpriteFont>("SpriteFont1");
            FontPos = new Vector2(graphics.GraphicsDevice.Viewport.Width - 100, 20);

        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        ///
        private float RotationAngle;
          float circle = MathHelper.Pi * 2;
          float angle;

        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here
            //check for collision between the ball and the block, or if the ball is outside the bounds of the screen

            if (ballBounds.Intersects(blockBounds) || !GraphicsDevice.Viewport.Bounds.Contains(ballBounds))
            {

                //we have a simple collision!
                //if it has hit, swap the direction of the ball, and update it's position
                ballVelocity = -ballVelocity;
                ballPosition += ballVelocity * ballSpeed;

            }

            else
            {

                //move the ball a bit
                ballPosition += ballVelocity * ballSpeed;

            }

            //update bounding boxes
            ballBounds.X = (int)ballPosition.X;
            ballBounds.Y = (int)ballPosition.Y;

            blockBounds.X = (int)blockPosition.X;
            blockBounds.Y = (int)blockPosition.Y;

            keyboardState = Keyboard.GetState();

            float val = 1.568017f/90;

            if (keyboardState.IsKeyDown(Keys.Space))
                RotationAngle = RotationAngle + (float)Math.PI;

            if (keyboardState.IsKeyDown(Keys.Left))
                RotationAngle = RotationAngle - val;

            angle = (float)Math.PI / 4.0f;  // 90 degrees
            RotationAngle = angle;
            //   RotationAngle = RotationAngle % circle;
                displayText = RotationAngle.ToString();
            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here
            spriteBatch.Begin();

            // Find the center of the string
            Vector2 FontOrigin = Font1.MeasureString(displayText) / 2;
            spriteBatch.DrawString(Font1, displayText, FontPos, Color.White, 0, FontOrigin, 1.0f, SpriteEffects.None, 0.5f);
            spriteBatch.Draw(ballTexture, ballPosition, Color.White);
            spriteBatch.Draw(blockTexture, blockPosition,null, Color.White, RotationAngle,origin, 1.0f, SpriteEffects.None, 0f);

            spriteBatch.End();
            base.Draw(gameTime);
        }
    }
}

```

# Answer
You should determine what side of the rectangle is colliding with the ball, and get the normal N of that side.

If the ball movement vector is V, then the reflected vector is:

```
 var reflected = Vector3.Reflect(V,N);

```

http://msdn.microsoft.com/en-us/library/bb198637.aspx

To determine if the ball is colliding you can work in the rectangle space:

```
   TrasnformToWorld = MatrixCreateTranslation(-origin )
                    * Matrix.CreateRotationZ(angle)
                    * MatrixCreateTranslation(recPos);
   TransformToRectangleSpace = Matrix.Invert(TransformToWorld);

   BallPositionInRectangleSpace = Vector3.Transform(ballPos, TransformToRectangleSpace );
   BallDirectionInRectangleSpace = Vector3.TransformNormal(ballDir, TransformToRectangleSpace);

```

Now we have the ball pos and dir related to a rectangle with position in (0,0) and size (width, height) and knowing where is colliding is easy. When you are determined the reflection vector, you have to transform it to world coordinates:

```
 var newBallDir = Vector3.TransformNormal(reflectedInrectangleSpace, TrasnformToWorld );

```
> 1 votes

# Answer
Reflection follows a very simple law. The angle between the ray falling in to the mirror and the normal of the mirror is equal to the angle between the ray out of the mirror and the normal of the mirror.

I can think of two ways to calculate this. The first would be to reverse the velocity of the ball in to the mirror and then rotate it by two times the angle between the reversed velocity and the mirror normal.

The second would be to project the velocity on to the normal vector and reverse that component (i.e. subtract it twice).
> 0 votes

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


# Question
Title: Using an Entity System Architecture with Task Based Parallelism
**Background**

I have been working on creating a multithreaded game engine in my spare time and I currently trying to decide the best way to work an entity sytem into what I have already created. So far, I have used this article from Intel for a starting point for my engine. Thus far I have implemented the normal game loop using tasks, and I am now moving on to getting some of the systems and/or entity-systems incorporated. I have used something similar to Artemis in the past, but the parallelism is throwing me off.

The article from Intel seems to advocate having multiple copies of entity data, and a having changes made to each entity internally being distributed at the end of a complete update. This means that rendering will always be one frame behind, but that seems like an acceptable compromise given the performance benefits that should be gained. When it comes to an entity system like Artemis, though, having each entity being duplicated for each system means that each component will also need to be duplicated. This is doable but to me it seems like it would use up a lot of memory. The portions of the Intel document that discus this are 2.2 and 3.2.2 mainly. I have done some searching to see if I could find any good references for integrating the architectures I am going for, but I have not yet been able to turn up anything useful.

*Note:* I am using C++11 for this project, but I imagine most of what I am asking should be pretty language agnostic.

**Possible Solution**

Have a global EntityManager that is used for creating and managing Entities and EntityAttributes. Allow read access to them only during the update phase, and store all changes in a queue per thread. Once all tasks are completed the queues are combined and the changes in each are applied. This would possibly have problems with multiple writes to the same fields but I am sure there could be a priority system or timestamp to sort that out. This seems like a good approach to me because systems can be notified of changes to entities pretty naturally during the change distribution stage.

**Question**

I am looking for some feedback on my solution to see if it even makes sense. I won't lie and claim to be an expert on multithreading, and I am doing this largely for practice. I can forsee some complicated messes rising from my solution where multiple systems are reading/writing multiple values. The change queue I mentioned could also be hard to format in a way that any possible change could easily be communicated when I am not working with POD.

Any feedback/advice would be much appreciated! Thanks!

**Links**

# Answer
**Fork-Join**

You don't need separate copies of components. Just use a fork-join model, which is (extremely poorly) mentioned in that article from Intel.

In an ECS, you effectively have a loop something like:

```
while in game:
  for each system:
    for each component in system:
      update component

```

Change this to something like:

```
while in game:
  for each system:
    divide components into groups
    for each group:
      start thread (
        for each component in group:
          update component
      )
    wait for all threads to finish

```

The tricky part is the "divide components into groups" bit. For graphics there's almost no need for shared data so it's simple (divide renderable objects evenly by number of worker threads available). For physics and AI, you want to find logical "islands" of objects that don't interact and put those together. The less interaction between components, the better.

For interaction that must exist, delayed messages work best. If object A needs to tell object B to take damage, A can just enqueue a message into a per-thread pool. When the threads are joined, the pools are all concatenated into a single pool. While not directly related to threading, see event series of articles from the BitSquid devs (in fact, read the whole blog; I don't agree with everything on there, but it is a fantastic resource).

Note that "fork-join" does *not* mean using `fork()` (which creates processes, not threads), nor does it imply that you actually must join the threads. It just means that you take a single task, parcel it out into smaller pieces to be handled by your pool of worker threads, and then wait for all the parcels to be processed.

**Proxies**

This approach can be used on its own or in combination with the fork-join method to make the need for strict separation less important.

You can be more friendly to interacting threads by using a simple two-layer approach. Have "authoritative" entities and "proxy" entities. Authoritative entities can only be modified from a single thread that is the clear owner of the authoritative entity. Proxies entities cannot be modified, only read. At a sync up point in the game loop, propagate all changes from authoritative entities to the corresponding proxies.

Replace "entities" with "components" as appropriate. The gist is that you need at most two copies of any object, and there are clear "sync" points in your game loop when you can copy from one to the other in most sane threaded game engine designs.

You can expand proxies to still allow (a subset of) methods/messages to be used by simply having all such things forward into a queue that is delivered to the authoritative object next frame.

Note that the proxy approach is a fantastic design to have at a higher level as it makes network support super easy.
> 13 votes

---
Tags: c++, architecture, entity-system, multithreading
---


title: shadow mapping and linear depth

text:
# Question
Title: shadow mapping and linear depth
I'm implementing ominidirectional shadow mapping for point lights. I want to use a linear depth which will be stored in the color textures (cube map). A program will contain two filtering techniques: software pcf (because hardware pcf works only with depth textures) and variance shadow mapping. I found two ways of storing linear depth:

```
const float linearDepthConstant = 1.0 / (zFar - zNear);
//first
float moment1 = -viewSpace.z * linearDepthConstant;
float moment2 = moment1 * moment1;
outColor = vec2(moment1, moment2);
//second
float moment1 = length(viewSpace) * linearDepthConstant;
float moment2 = moment1 * moment1;
outColor = vec2(moment1, moment2);

```

What are differences between them ? Are both ways correct ?

For the standard shadow mapping with software pcf a shadow test will depend on the linear depth format. What about variance shadow mapping ?

I implemented omnidirectional shadow mapping for points light using a non-linear depth and hardware pcf. In that case a shadow test looks like this:

```
vec3 lightToPixel = worldSpacePos - worldSpaceLightPos;
vec3 aPos = abs(lightToPixel);
float fZ = -max(aPos.x, max(aPos.y, aPos.z));
vec4 clip = pLightProjection * vec4(0.0, 0.0, fZ, 1.0);
float depth = (clip.z / clip.w) * 0.5 + 0.5;
float shadow = texture(ShadowMapCube, vec4(normalize(lightToPixel), depth));

```

I also implemented standard shadow mapping without pcf which using second format of linear depth: (**Edit 1**: i.e. distance to the light + some offset to fix shadow acne)

```
vec3 lightToPixel = worldSpacePos - worldSpaceLightPos;
const float linearDepthConstant = 1.0 / (zFar - zNear);
float fZ = length(lightToPixel) * linearDepthConstant;
float depth = texture(ShadowMapCube, normalize(lightToPixel)).x;
if(depth <= fZ)
{
     shadow = 0.0;
}
else
{
     shadow = 1.0;
}

```

but I have no idea how to do that for the first format of linear depth. Is it possible ?

**Edit 2:** For non-linear depth I used glPolygonOffset to fix shadow acne. For linear depth and distance to the light some offset should be add in the shader. I'm trying to implement standard shadow mapping without pcf using a linear depth (-viewSpace.z * linearDepthConstant + offset) but following shadow test doesn't produce correct results:

```
vec3 lightToPixel = worldSpacePos - worldSpaceLightPos;
vec3 aPos = abs(lightToPixel);
float fZ = -max(aPos.x, max(aPos.y, aPos.z));
vec4 clip = pLightProjection * vec4(0.0, 0.0, fZ, 1.0);
float fDepth = (clip.z / clip.w) * 0.5 + 0.5;
float depth = texture(ShadowMapCube, normalize(lightToPixel)).x;
if(depth <= fDepth)
{
     shadow = 0.0;
}
else
{
     shadow = 1.0;
}

```

How to fix that ?

# Answer
> 2 votes
The method with `viewSpace.z` is storing depth, while the method with `length(viewSpace)` is storing *distance* to the light, not depth (which is always measured parallel to a view direction).

You could store either one, but you have to be consistent about it. If you store distance instead of depth when you render your shadow map, you have to compare against distance instead of depth when you apply the shadow map.

Depth is the natural choice as that's what will be generated by the GPU rasterizer when you draw the shadow map. It takes extra work to convert it to distance (you have to set up the `viewSpace` vector). But I can imagine that distance might give better results in some situations with VSM. You'd have to experiment to see.

---
Tags: opengl, linear-algebra, shadow-mapping
---