# Question
Title: XNA shield effect with a Primative sphere problem
I'm having issue with a shield effect i'm trying to develop. I want to do a shield effect that surrounds part of a model like this: https://i.stack.imgur.com/Ytc2a.png

I currently got this: https://i.stack.imgur.com/nWwaS.png (The red likes are a simple texture a black background with a red cross in it, for testing purposes: https://i.stack.imgur.com/gA0b4.png where the smaller cross in the middle shows the contact point)

This sphere is drawn via a primitive (DrawIndexedPrimitives)

This is how i calculate the pieces of the sphere using a class i've called Sphere

(this class is based off the code here: http://xbox.create.msdn.com/en-US/education/catalog/sample/primitives\_3d)

public class Sphere { // During the process of constructing a primitive model, vertex // and index data is stored on the CPU in these managed lists. List vertices = new List(); List indices = new List();

```
    // Once all the geometry has been specified, the InitializePrimitive
    // method copies the vertex and index data into these buffers, which
    // store it on the GPU ready for efficient rendering.
    VertexBuffer vertexBuffer;
    IndexBuffer indexBuffer;
    BasicEffect basicEffect;

    public Vector3 position = Vector3.Zero;
    public Matrix RotationMatrix = Matrix.Identity;

    public Texture2D texture;

    /// <summary>
    /// Constructs a new sphere primitive,
    /// with the specified size and tessellation level.
    /// </summary>
    public Sphere(float diameter, int tessellation, Texture2D text, float up, float down, float portstar, float frontback)
    {
        texture = text;
        if (tessellation < 3)
            throw new ArgumentOutOfRangeException("tessellation");

        int verticalSegments = tessellation;
        int horizontalSegments = tessellation * 2;

        float radius = diameter / 2;

        // Start with a single vertex at the bottom of the sphere.
        AddVertex(Vector3.Down * ((radius / up) + 1), Vector3.Down, Vector2.Zero);//bottom position5

        // Create rings of vertices at progressively higher latitudes.
        for (int i = 0; i < verticalSegments - 1; i++)
        {
            float latitude = ((i + 1) * MathHelper.Pi /
                                        verticalSegments) - MathHelper.PiOver2;

            float dy = (float)Math.Sin(latitude / up);//(up)5
            float dxz = (float)Math.Cos(latitude);

            // Create a single ring of vertices at this latitude.
            for (int j = 0; j < horizontalSegments; j++)
            {
                float longitude = j * MathHelper.TwoPi / horizontalSegments;

                float dx = (float)(Math.Cos(longitude) * dxz) / portstar;//port and starboard (right)2
                float dz = (float)(Math.Sin(longitude) * dxz) * frontback;//front and back1.4

                Vector3 normal = new Vector3(dx, dy, dz);

                AddVertex(normal * radius, normal, new Vector2(j, i));
            }
        }

        // Finish with a single vertex at the top of the sphere.
        AddVertex(Vector3.Up * ((radius / down) + 1), Vector3.Up, Vector2.One);//top position5

        // Create a fan connecting the bottom vertex to the bottom latitude ring.
        for (int i = 0; i < horizontalSegments; i++)
        {
            AddIndex(0);
            AddIndex(1 + (i + 1) % horizontalSegments);
            AddIndex(1 + i);
        }

        // Fill the sphere body with triangles joining each pair of latitude rings.
        for (int i = 0; i < verticalSegments - 2; i++)
        {
            for (int j = 0; j < horizontalSegments; j++)
            {
                int nextI = i + 1;
                int nextJ = (j + 1) % horizontalSegments;

                AddIndex(1 + i * horizontalSegments + j);
                AddIndex(1 + i * horizontalSegments + nextJ);
                AddIndex(1 + nextI * horizontalSegments + j);

                AddIndex(1 + i * horizontalSegments + nextJ);
                AddIndex(1 + nextI * horizontalSegments + nextJ);
                AddIndex(1 + nextI * horizontalSegments + j);
            }
        }

        // Create a fan connecting the top vertex to the top latitude ring.
        for (int i = 0; i < horizontalSegments; i++)
        {
            AddIndex(CurrentVertex - 1);
            AddIndex(CurrentVertex - 2 - (i + 1) % horizontalSegments);
            AddIndex(CurrentVertex - 2 - i);
        }

        //InitializePrimitive(graphicsDevice);
    }

    /// <summary>
    /// Adds a new vertex to the primitive model. This should only be called
    /// during the initialization process, before InitializePrimitive.
    /// </summary>
    protected void AddVertex(Vector3 position, Vector3 normal, Vector2 texturecoordinate)
    {
        vertices.Add(new VertexPositionNormal(position, normal, texturecoordinate));
    }

    /// <summary>
    /// Adds a new index to the primitive model. This should only be called
    /// during the initialization process, before InitializePrimitive.
    /// </summary>
    protected void AddIndex(int index)
    {
        if (index > ushort.MaxValue)
            throw new ArgumentOutOfRangeException("index");

        indices.Add((ushort)index);
    }

    /// <summary>
    /// Queries the index of the current vertex. This starts at
    /// zero, and increments every time AddVertex is called.
    /// </summary>
    protected int CurrentVertex
    {
        get { return vertices.Count; }
    }

    public void InitializePrimitive(GraphicsDevice graphicsDevice)
    {
        // Create a vertex declaration, describing the format of our vertex data.

        // Create a vertex buffer, and copy our vertex data into it.
        vertexBuffer = new VertexBuffer(graphicsDevice,
                                        typeof(VertexPositionNormal),
                                        vertices.Count, BufferUsage.None);

        vertexBuffer.SetData(vertices.ToArray());

        // Create an index buffer, and copy our index data into it.
        indexBuffer = new IndexBuffer(graphicsDevice, typeof(ushort),
                                      indices.Count, BufferUsage.None);

        indexBuffer.SetData(indices.ToArray());

        // Create a BasicEffect, which will be used to render the primitive.
        basicEffect = new BasicEffect(graphicsDevice);
        //basicEffect.EnableDefaultLighting();
    }

    /// <summary>
    /// Draws the primitive model, using the specified effect. Unlike the other
    /// Draw overload where you just specify the world/view/projection matrices
    /// and color, this method does not set any renderstates, so you must make
    /// sure all states are set to sensible values before you call it.
    /// </summary>
    public void Draw(Effect effect)
    {
        GraphicsDevice graphicsDevice = effect.GraphicsDevice;

        // Set our vertex declaration, vertex buffer, and index buffer.
        graphicsDevice.SetVertexBuffer(vertexBuffer);

        graphicsDevice.Indices = indexBuffer;

        graphicsDevice.BlendState = BlendState.Additive;

        foreach (EffectPass effectPass in effect.CurrentTechnique.Passes)
        {
            effectPass.Apply();

            int primitiveCount = indices.Count / 3;

            graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0,
                                                 vertices.Count, 0, primitiveCount);

        }
        graphicsDevice.BlendState = BlendState.Opaque;
    }

    /// <summary>
    /// Draws the primitive model, using a BasicEffect shader with default
    /// lighting. Unlike the other Draw overload where you specify a custom
    /// effect, this method sets important renderstates to sensible values
    /// for 3D model rendering, so you do not need to set these states before
    /// you call it.
    /// </summary>
    public void Draw(Camera camera, Color color)
    {
        // Set BasicEffect parameters.
        basicEffect.World = GetWorld();
        basicEffect.View = camera.view;
        basicEffect.Projection = camera.projection;
        basicEffect.DiffuseColor = color.ToVector3();
        basicEffect.TextureEnabled = true;
        basicEffect.Texture = texture;

        GraphicsDevice device = basicEffect.GraphicsDevice;
        device.DepthStencilState = DepthStencilState.Default;

        if (color.A < 255)
        {
            // Set renderstates for alpha blended rendering.
            device.BlendState = BlendState.AlphaBlend;
        }
        else
        {
            // Set renderstates for opaque rendering.
            device.BlendState = BlendState.Opaque;
        }

        // Draw the model, using BasicEffect.
        Draw(basicEffect);
    }

    public virtual Matrix GetWorld()
    {
        return /*world */ Matrix.CreateScale(1f) * RotationMatrix * Matrix.CreateTranslation(position);
    }
}

public struct VertexPositionNormal : IVertexType
{
    public Vector3 Position;
    public Vector3 Normal;
    public Vector2 TextureCoordinate;

    /// <summary>
    /// Constructor.
    /// </summary>
    public VertexPositionNormal(Vector3 position, Vector3 normal, Vector2 textCoor)
    {
        Position = position;
        Normal = normal;
        TextureCoordinate = textCoor;
    }

    /// <summary>
    /// A VertexDeclaration object, which contains information about the vertex
    /// elements contained within this struct.
    /// </summary>
    public static readonly VertexDeclaration VertexDeclaration = new VertexDeclaration
    (
        new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0),
        new VertexElement(12, VertexElementFormat.Vector3, VertexElementUsage.Normal, 0),
        new VertexElement(24, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0)
    );

    VertexDeclaration IVertexType.VertexDeclaration
    {
        get { return VertexPositionNormal.VertexDeclaration; }
    }

}

```

A simple call to the class to initialise it. The Draw method is called in the master draw method in the Gamecomponent.

My current thoughts on this are:

1. The direction of the weapon hitting the ship is used to get the middle position for the texture
2. Wrap a texture around the drawn sphere based on this point of contact

Problem is i'm not sure how to do this. Can anyone help or if you have a better idea please tell me i'm open for opinion? :-) Thanks.

# Answer
> 1 votes
Looks like you're on the right track. I did this before in a game, and instead of changing where on the texture the impact is centered, I merely rotated the sphere. I also used a procedural shader instead of a texture. Here's some of the code I used (public domain, do whatever you want with it).

**EDIT:** Uploaded a video of it: http://www.youtube.com/watch?v=DqKkaJHf1gg

*(NOTE: This code is for XNA 3.1, and has a couple calls to internal functions, so it won't work out of the box. It also does a lot of allocation, so will not perform well on the 360)*

```
[SingletonRenderer]
public sealed class ShieldRenderer : Renderer
{
    private static readonly Texture3D _noiseTexture = SpacerGame.load<Texture3D>("textures/noise");

    /// <summary>
    /// Since the default render state culls back-facing edges (i.e. those with normals opposite the
    /// viewer), the shader is not see-through. This could be fixed by order-independent trasnparency
    /// or disabling backface culling, but since we're only going to be seeing the shader from one
    /// direction, it's easier (and faster, and provides more control) to fake the effect by rotating
    /// the sphere a bit towards the camera.
    /// </summary>
    private const float ROTATION_Y = -MathHelper.Pi * 3 / 8;
    private const float NOISE_SPEED = 0.15f;
    private const float IMPACT_TIME = 1.0f;

    private readonly Sphere _sphere;
    private readonly ShieldShader _shader;
    private readonly ReaderWriterCollection<SimpleList<ShieldImpact>, ShieldImpact> _impacts;
    private readonly ShieldParameters _params;

    public ShieldRenderer() : base(RenderPass.SHIELDS)
    {
        _params = Effects.initShieldRenderer(this);
        _sphere = new Sphere(1, 20);
        _shader = new ShieldShader
        {
            noise = _noiseTexture,
            speed = NOISE_SPEED,
        };
        _impacts = new ReaderWriterCollection<SimpleList<ShieldImpact>, ShieldImpact>();
    }

    public override void draw(DeltaT dt)
    {
        _impacts.synchronize();
        foreach(ShieldImpact impact in _impacts)
        {
            // Update time
            if(impact.startTime == 0) impact.startTime = dt.totalActual;
            else                      impact.time += dt.dtAt(impact.target.pos);

            // Kill off dead impacts
            if (impact.time > IMPACT_TIME)
            {
                _impacts.Remove(impact);
                continue;
            }

            // Skip offscreen targets
            if(!impact.target.bounds.isPartiallyOnScreen())
                continue;

            _shader.worldViewProj = impact.baseTransform *
                impact.target.pos.toScreenWvpMatrix();
            _shader.startTime = impact.startTime;
            _shader.color = impact.color;
            _shader.time = impact.time / IMPACT_TIME;

            _shader.begin();
            _sphere.draw(_shader.shield);
            _shader.end();
        }
    }

    protected override void dispose()
    {
        base.dispose();
        _sphere.Dispose();
        _shader.Dispose();
    }

    protected override void finalize()
    {
        base.finalize();
        _impacts.synchronize();
        _impacts.Clear();
        _impacts.Dispose();
    }

    public void addImpact(Entity target, float direction, float shieldStrength)
    {
        // TODO -- figurre out right shield radius
        _impacts.Add(new ShieldImpact
        {
            target = target,
            color = _params.colors.sample(shieldStrength).ToVector3(),
            baseTransform = Matrix.CreateScale(target.size.X) *
                Matrix.CreateRotationY(ROTATION_Y) *
                Matrix.CreateRotationZ(-direction),
        });
    }

    private sealed class ShieldImpact : ISimpleListNode<ShieldImpact>
    {
        public Entity target;
        public Matrix baseTransform;
        public Vector3 color;
        public float startTime;
        public float time;

        ShieldImpact ISimpleListNode<ShieldImpact>.next { get; set; }
        ShieldImpact ISimpleListNode<ShieldImpact>.prev { get; set; }
    }
}

public sealed class ShieldParameters
{
    public ColorGradient colors;
}

```

**Shader:**

```
#include "common.fxh"

// @params
float4x4 _worldViewProj;
texture _noise;
float _time;
float _startTime;
float _speed;
float3 _color;
// @end

sampler sNoise = sampler_state { texture = <_noise>; magfilter = ANISOTROPIC; minfilter = ANISOTROPIC; mipfilter = ANISOTROPIC; AddressU = WRAP; AddressV = WRAP; };

PixelInfo shieldVS(float4 inPos : POSITION, float2 inUv : TEXCOORD)
{
    PixelInfo p;
    p.uv = inUv;
    p.pos = mul(inPos, _worldViewProj);
    return p;
}

static const float NOISINESS = 1;
static const float NOISE_SCALE_PRE_EXP = 1.25;
static const float NOISE_SCALE_POST_EXP = 3;
static const float NOISE_EXP = 4;

static const float DISTANCE_EXP_MIN = 0.015;
static const float DISTANCE_EXP_MAX = 0.06;
static const float DISTANCE_VALUE_CLAMP = 0.1;
static const float DISTANCE_SCALE = 144;

static const float TIME_SCALE_PRE_EXP = 3;
static const float TIME_SCALE_POST_EXP = 1;
static const float TIME_EXP = 3;

float4 shieldPS(PixelInfo p) : COLOR0
{
    // Get some noise-sampled noise (a la the background)
    float3 vpos;
    float3 spos = float3(p.uv * NOISINESS + float2(_startTime, _startTime), _time * _speed);
    vpos.x = tex3D(sNoise, spos + 0.00).r - 0.5;
    vpos.y = tex3D(sNoise, spos + 0.33).r - 0.5;
    vpos.z = tex3D(sNoise, spos + 0.67).r - 0.5;
    float sample = tex3D(sNoise, vpos).r;
    sample = pow(sample * NOISE_SCALE_PRE_EXP, NOISE_EXP) * NOISE_SCALE_POST_EXP;

    // Fade out with time
    float timeFactor = (pow((1 - _time) * TIME_SCALE_PRE_EXP, TIME_EXP)) * TIME_SCALE_POST_EXP;

    // Glow more closer to the center; spread out over time
    float d = distance(float2(smoothstep(0.125, 0.875, p.uv.x), p.uv.y), float2(0.5, 0.5));
    float distanceFactor = 1 - pow(d, lerp(DISTANCE_EXP_MIN, DISTANCE_EXP_MAX, _time));
    distanceFactor = smoothstep(DISTANCE_VALUE_CLAMP, 1, distanceFactor * distanceFactor * DISTANCE_SCALE);

    // If alpha > 1, multiply the color by it to get an HDRish effect
    float alpha = sample * timeFactor * distanceFactor;
    return float4(alpha > 1 ? alpha * _color : _color, saturate(alpha));
}

technique shield
{
    // @passes
    pass shield { VertexShader = compile vs_1_1 shieldVS(); PixelShader = compile ps_2_0 shieldPS(); }
    // @end
}

```

**Code for sphere:**

```
/// <summary>
/// Simple sphere mesh generator.
/// </summary>
public sealed class Sphere : IDisposable
{
    private readonly VertexBuffer _vertexBuf;
    private readonly IndexBuffer _indexBuf;
    private readonly VertexDeclaration _vertexDecl;
    private readonly int _nVerticies;
    private readonly int _nFaces;

    public Sphere(float radius, int slices)
    {
        _nVerticies = (slices + 1) * (slices + 1);
        int nIndicies = 6 * slices * (slices + 1);

        var indices = new int[nIndicies];
        var vertices = new VertexPositionNormalTexture[_nVerticies];
        float thetaStep = MathHelper.Pi / slices;
        float phiStep = MathHelper.TwoPi / slices;

        int iIndex = 0;
        int iVertex = 0;
        int iVertex2 = 0;

        for (int sliceTheta = 0; sliceTheta < slices + 1; sliceTheta++)
        {
            float r = (float) Math.Sin(sliceTheta * thetaStep);
            float y = (float) Math.Cos(sliceTheta * thetaStep);

            for (int slicePhi = 0; slicePhi < (slices + 1); slicePhi++)
            {
                float x = r * (float) Math.Sin(slicePhi * phiStep);
                float z = r * (float) Math.Cos(slicePhi * phiStep);

                vertices[iVertex].Position = new Vector3(x, y, z) * radius;
                vertices[iVertex].Normal = Vector3.Normalize(new Vector3(x, y, z));
                vertices[iVertex].TextureCoordinate = new Vector2((float)slicePhi / slices,
                    (float)sliceTheta / slices);
                iVertex++;

                if (sliceTheta != (slices - 1))
                {
                    indices[iIndex++] = iVertex2 + (slices + 1);
                    indices[iIndex++] = iVertex2 + 1;
                    indices[iIndex++] = iVertex2;
                    indices[iIndex++] = iVertex2 + (slices);
                    indices[iIndex++] = iVertex2 + (slices + 1);
                    indices[iIndex++] = iVertex2;
                    iVertex2++;
                }
            }
        }

        GraphicsDevice device = RenderManager.current.device;
        _vertexBuf = new VertexBuffer(device, typeof(VertexPositionNormalTexture), _nVerticies, BufferUsage.None);
        _indexBuf = new IndexBuffer(device, typeof(int), nIndicies, BufferUsage.None);
        _vertexDecl = new VertexDeclaration(device, VertexPositionNormalTexture.VertexElements);
        _vertexBuf.SetData(vertices, 0, vertices.Length);
        _indexBuf.SetData(indices, 0, indices.Length);
        _nFaces = nIndicies / 3;
    }

    public void draw(EffectPass pass)
    {
        GraphicsDevice device = RenderManager.current.device;
        device.Indices = _indexBuf;
        device.VertexDeclaration = _vertexDecl;
        device.Vertices[0].SetSource(_vertexBuf, 0, VertexPositionNormalTexture.SizeInBytes);

        pass.Begin();
        device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _nVerticies, 0, _nFaces);
        pass.End();
    }

    public void Dispose()
    {
        _vertexBuf.Dispose();
        _indexBuf.Dispose();
        _vertexDecl.Dispose();
    }
}

```

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


# Question
Title: Messaging/Event System in Generic Game Engine? Yay or nay?
Should I develop a basic messaging/event system for a generic game engine or should I leave it up to the individual case-by-case basis of the end-users to create systems specific to the game being developed?

This question raises some valid points: (I am currently using the per-frame function call system mentioned)

Per-frame-function-calls-versus-event-driven-messaging-in-game-design

# Answer
> 4 votes
You need to ask yourself this question:

**Will this messaging/events system be used by the engine?** (including for the purposes of communicating to/from game code)

If so, then yes, you have to build it as part of the engine (since the engine needs to know about it).

But if you're intending for it to only be used within game code, then don't make it part of the engine; any such system which is unrelated to the engine should be designed by and for the game that's going to be using it.

Simple.

---
Tags: c++, messaging
---


# Question
Title: How to Contact prominent game devs for discussion and queries?
What is the medium to contact and discuss problems with Game devs, and engine hackers? Any irc, forum, mailing list?

Note : Somehow, I did not like gamedev.net

# Answer
> 1 votes
I find that e-mail and SMS can both be effective. Telephone can yield more immediate responses, but can also annoy people if you interrupt them during dinner, so probably should be used very sparingly.

If they have their headphones on when you go over to talk to them in person, that means they're trying to concentrate and don't want to be disturbed, so unless you are literally on fire, either come back later or else leave them an e-mail, rather than disturbing them.

# Answer
> 0 votes
Sounds to me as if the "prominent game devs" over on gamedev.net perhaps didn't live up to your projections / expectations.

They're people, like anyone other. They also *just happen* to be damned good at what they do. It's up to those who seek the knowledge, to woo the experts in the field. Perhaps you didn't try hard enough over there. Or perhaps you were seeking a John Carmack or a Peter Molyneux and didn't find one. That doesn't mean the people who frequent gamedev.net aren't very experienced indeed. It probably just means that those who really are at the very pinnacle of their game usually don't have time for internet forums. But as for those experts you will find: They speak like normal people, act like normal people, and like normal people, expect thonly dispense knowledge if they see fit.

So if you couldn't obey the rules of *this* site (hence the downvotes), you probably didn't obey the etiquette of that site, either. Maybe you should go back, apologise if necessary, and try again.

Re chat, this site and gamedev.net have browser-based chat forums, and I don't doubt that a quick google search would turn up tons of results on developer IRC channels (pretty much every IRC server I've ever been on has had a #hackerz channel).

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


# Question
Title: Raycasting mouse coordinates to rotated object?
I am trying to cast a ray from my mouse to a plane at a specified position with a known width and length and height.

I know that you can use the NDC (Normalized Device Coordinates) to cast ray but I don't know how can I detect if the ray actually hit the plane and when it did. The plane is translated -100 on the Y and rotated 60 on the X then translated again -100.

Can anyone please give me a good tutorial on this? For a complete noob! I am almost new to matrix and vector transformations.

# Answer
> 2 votes
There's a list of different collision types (ray-plane included) that can be found here. One of the better sources of ray-plane intersection can be found here.

With a c++ implementation:

```
// intersect3D_SegmentPlane(): intersect a segment and a plane
//    Input:  S = a segment, and Pn = a plane = {Point V0;  Vector n;}
//    Output: *I0 = the intersect point (when it exists)
//    Return: 0 = disjoint (no intersection)
//            1 =  intersection in the unique point *I0
//            2 = the  segment lies in the plane
int
intersect3D_SegmentPlane( Segment S, Plane Pn, Point* I )
{
    Vector    u = S.P1 - S.P0;
    Vector    w = S.P0 - Pn.V0;

    float     D = dot(Pn.n, u);
    float     N = -dot(Pn.n, w);

    if (fabs(D) < SMALL_NUM) {           // segment is parallel to plane
        if (N == 0)                      // segment lies in plane
            return 2;
        else
            return 0;                    // no intersection
    }
    // they are not parallel
    // compute intersect param
    float sI = N / D;
    if (sI < 0 || sI > 1)
        return 0;                        // no intersection

    *I = S.P0 + sI * u;                  // compute segment intersect point
    return 1;
}

```

# Answer
> 0 votes
The are two processes involved here. The first one is to obtain a ray (or line) toward the place the user feels the mouse is pointing to. The second one is to resolve the line and plane intersection equation.

Use the camera view-projection matrix to resolve the direction of the mouse. MVP matrix transform a point in space into screen coordinates so one can think that the inverse would transform a point in screen space into world space. As the camera is projecting the scene into a virtual plane called near plane you will get a point within that plane. Then trace a line from the camera position towards that near-plane point and you obtain a ray that goes into the scene. An example in java:

```
public Vector3 rayDirectionForViewportCoordinate(float x, float y){
    float normalized_x = 2.f * x / _viewportWidth - 1.f;
    float normalized_y = 1 - 2.f * y / _viewportHeight;

    Matrix.multiplyMM(mvp_f, 0, this.getProjectionMatrix().getAsArray(), 0, this.getViewMatrix().getAsArray(), 0);
    Matrix.invertM(inv_mvp_f, 0, mvp_f, 0);

    Matrix4 inv_mvp = new Matrix4(inv_mvp_f);
    Vector4 near_point = inv_mvp.mul(new Vector4(normalized_x, normalized_y, 0 , 1));

    float w = 1.f/near_point.getW();
    Vector3 point = new Vector3(near_point.getX()*w, near_point.getY()*w, near_point.getZ()*w);
    point.subNoCopy(_position);
    point.normalizeNoCopy();
    return point;
}

```

After you have obtained the ray, use any plane-line solver out there to test at which place that casted ray intersects your plane.

Move the ray origin and direction into object space (your rotation&translation matrix you want to check against). Use the inverse of the model matrix for that specific object. For example by multiplying the ray's origin against the inverse of the object model matrix you effectively move the origin into object space. Do the same with the direction and check if the line hits the plane using. Alternatively, rotate the plane and do the maths in world space.

If this is not clear enough drop me a message.

---
Tags: opengl, raycasting
---


# Question
Title: How to prevent a hacked-server from spoofing a master server?
I wish to setup a room-based multiplayer game model where players may host matches and serve as host (IE the server with authoritative power). I wish to host a master server which tracks player's items, rank, cash, exp, etc.

In such a model, how can I prevent someone who is hosting a game (with a modified server) from spoofing the master server with invalid match results, thus gaining exp, money or rankings.

# Answer
> 6 votes
It's been pointed out that my previous answer may have been based on a misunderstanding of what you meant by "spoofing". (If so, please let me know and I'll delete it.)

If what you want to prevent is the game servers sending bogus data to the master server, then — as Jari Komppa notes — that's generally impossible to prevent completely. In fact, it's simply a variant of the classic multiplayer cheating prevention problem, except with the intermediate servers rather than the clients being the ones suspected of cheating. Many of the same techniques used for traditional cheating prevention could work here too, but as usual, none of them are completely foolproof.

That said, there *are* some things you could do that would specifically help against cheating servers. One of them would be to have each player in a match separately contact the master server and confirm that they're participating in that match. (You'll probably want to do that *before* the match begins, so that you can make sure everyone agrees who the participants are and so that nobody's tempted to claim they didn't participate in a match they lost. You *could* use digital signatures to defer that, though; essentially, you could have every player in a match sign a message saying "*I'm player X and I'm participating in match M on server S at time T with players Y, Z and W.*" and send it to the game server, which can later relay it to the master server.) That way, you can at least ensure that a cheating server can't affect the rankings of any player who doesn't actually play on that server.

This is particularly useful if you're using something like Elo ratings where player ranking mostly depends on their *relative* performance. Sure, someone running a bogus server might still create a bunch of fake accounts and submit results saying that their own account beat the fake ones, but with a relative ranking system, all that will do is make the cheater's account rank slightly above the fakes (which in turn will have rock bottom ratings).

Another obvious thing to do to discourage cheating is to let players verify their match results directly from the master server. If a player wins a match on a new server, but the results sent to the master server say that they lost (or if the results are never sent at all), that will let them know that something fishy is going on. Hopefully, at that point they'll either report the server for cheating, or at least vote with their feet and never play on that server again.

In fact, you could make this automatic: after each game, once the results have been sent to the master server, have the clients fetch them back from the master server and compare them to how the client thinks the game ended. If there's a mismatch, report it both to the player (so that they'll know something's wrong) and to the master server (so that you can detect cheating servers). Of course, as the operator of the master server, you'll then need to decide who's lying — the server or the player — but hopefully in most cases that will be fairly obvious from the pattern of reports.

# Answer
> 5 votes
**Note:** This answer may be based on a misunderstanding of the question — see comments below.

---

Short generic answer: use digital signatures.

Specifically, the master server should have a private key for a suitable digital signature scheme (RSA, DSA, ECDSA, etc.) and should somehow securely relay its public key to all the clients. Then the server can sign any data it sends to clients with the private key (or possibly use it to negotiate a shared secret usable for symmetrically encrypting and/or authenticating communications between it and that particular client) and the client can use the public key to verify that the signature has been generated by the server.

Of course, your next problem is distributing the public key so that a rogue server can't spoof *that* and substitute its own public key. That might not be so hard if you can do it in advance (e.g. distributing the key along with the game executable), but it gets tricky if you have to do it later, for example because the identity of the master server is not known in advance. One standard solution is to distribute some *other* public key (whose corresponding private key is known only to you) in advance to all the clients, and then sign the message containing the master server's public key with that other key before broadcasting it.

In fact, you could even extend such signature chains further — say, have one super-secret master private key, which is kept locked in a safe somewhere and whose public key is known to all clients, and another "daily use" private key which is used to actually sign the server keys, and whose public key is itself signed with the super-secret master key before it's locked up in the safe. This is not that useful by itself, but it becomes potentially very useful if you also include some mechanism to revoke compromised keys, so that e.g. if your daily use key is leaked, you can just revoke it and generate another one.

What I describe above is a rudimentary kind of public key infrastructure. Actually implementing one securely can get quite complicated, but fortunately it's been done before. In fact, whenever you connect to a website (like Wikipedia) using HTTPS, this is pretty much exactly what you browser does: it receives a public key certificate from the server, verifies that the certificate matches the server name in the URL, is not listed as revoked and has been signed by a known and trusted certificate authority, and then uses it to negotiate a temporary symmetric encryption key known only to itself and to the owner of the private key corresponding to the certificate. This symmetric key is then used to encrypt and authenticate all data sent between the client and the server.

In particular, you really should take a look at existing SSL/TLS libraries (which typically come with an X.509 PKI implementation), or possibly at SPKI. These are still somewhat complicated, but probably easier (and more secure) than trying to roll your own.

# Answer
> 2 votes
This depends on the nature of the game and on the reason you're offloading the server role.

In certain circumstances you might be able to mostly achieve this with cryptographic audit logs. E.g. if it's a two-player turn-based game and you can arrange for each client to have a private asymmetric key for signature purposes, you can have a protocol along the lines of

* The initial state S0 includes a unique identifier for the game (to prevent replay attacks) and is otherwise assumed to be constant. If there's a random element, that should be produced by the central server and cached there for future comparison.
* P1 makes move m1; signs the resulting state S1, producing signature C1; and sends it with his move (S1, C1, m1) to P2.
* P2 makes move m2; signs the resulting state S2, producing signature C2; and sends it with his move (S2, C2, m2) to P1.
* etc.

At the end both clients submit the result to the central server, and if they disagree then they submit the audit trails: (S1, C1, m1), (S2, C2, m2), etc. Since each player has signed their moves, they are committed to them.

It's still vulnerable to one player DDOSing the other to prevent them submitting their result, but there really isn't much you can do about that.

**NB** This is just a quick sketch - I'm sure that if you post it to crypto.stackexchange.com someone will poke massive holes in it - but I think the principle is sound. Get whatever scheme you design reviewed by someone who knows their stuff before you start relying on it.

---
Tags: networking, multiplayer
---


# Question
Title: How would I handle input with a Game Component?
I am currently having problems from finding my way into the component-oriented XNA design.

I read an overview over the general design pattern and googled a lot of XNA examples. However, they seem to be right on the opposite site. In the general design pattern, an object (my current player) is passed to `InputComponent::update(Player)`. This means the class will know what to do and how this will affect the game (e.g. move person vs. scroll text in a menu).

Yet, in XNA `GameComponent::update(GameTime)` is called automatically without a reference to the current player.

The only XNA examples I found built some sort of higher-level Keyboard engine into the game component like this:

```
class InputComponent: GameComponent
{
    public void keyReleased(Keys);
    public void keyPressed(Keys);
    public bool keyDown(Keys);

    public void override update(GameTime gameTime)
    {
        // compare previous state with current state and
        // determine if released, pressed, down or nothing
    }
 }

```

Some others went a bit further making it possible to use a Service Locator by a design like this:

```
interface IInputComponent
{
    public void downwardsMovement(Keys);
    public void upwardsMovement(Keys);
    public bool pausedGame(Keys);

    // determine which keys pressed and what that means
    // can be done for different inputs in different implementations
    public void override update(GameTime);
 }

```

Yet, then I am wondering if it is possible to design an input class to resolve all possible situations. Like in a menu a mouse click can mean "click that button", but in game play it can mean "shoot that weapon".

So if I am using such a modular design with game components for input, how much logic is to be put into the InputComponent / KeyboardComponent / GamepadComponent and where is the rest handled?

What I had in mind, when I heard about Game Components and Service Locator in XNA was something like this:

* use Game Components to run the InputHandler automatically in the loop
* use Service Locator to be able to switch input at runtime (i.e. let player choose if he wants to use a gamepad or a keyboard; or which shall be player 1 and which player 2).

However, now I cannot see how this can be done.

* First code example does not seem flexible enough, as on a game pad you could require some combination of buttons for something that is possible on keyboard with only one button or with the mouse)
* The second code example seems really hard to implement, because the InputComponent has to know in which context we are currently. Moreover, you could imagine your application to be multi-layered and let the key-stroke go through all layers to the bottom-layer which requires a different behaviour than the InputComponent would have guessed from the top-layer.
* The general design pattern with passing the `Player` to `update()` does not have a representation in XNA and I also cannot see how and where to decide which class should be passed to `update()`. At most time of course the player, but sometimes there could be menu items you have to or can click

I see that the question in general is already dealt with here, but probably from a more elobate point-of-view. At least, I am not smart enough in game development to understand it. I am searching for a rather code-based example directly for XNA.

And the answer there leaves (a noob like) me still alone in how the object that should receive the detected event is chosen. Like if I have a key-up event, should it go to the text box or to the player?

# Answer
I just wrestled with this myself -- how to create a simple component/entity framework for XNA. Here's what I did; my goals were:

* Create reusable components (reusable within and across games) that are generic
* Create game-specific entities that encapsulate "business domain" logic of my game

I ended up creating a basic `Entity` class (behind an interface):

```
public interface IEntity
    {
        void Update(double elapsedSeconds);
        bool HasComponent<T>() where T : IComponent;
        T GetComponent<T>() where T : IComponent;
    }

```

My `Player` class, enemies, etc. all subclass from this. My components also live behind an interface with a simple `Update` method. Most of them expose specific functionality (eg. for input, events for when keys/mouse are pressed).

Creating the player was simple:

```
public class Player : Entity {
  public Player() {
    var input = new InputComponent();
    input.OnPress += (key) => {
      if (key == Keys.Space) { this.Jump(); }
    }
    this.addComponent(input);
  }
}

```

My input component reads keyboard input only. I personally created a different component for handling mouse input, although it could be the same. Tomorrow, I can always extend my input component to expose an event for when a gamepad button is pressed.

In this way, components really encapsulate only their specific piece of functionality, and I can easily reuse them across games; while entities are game-specific, and probably won't be reused; at the same time, it's easy to see where the "game logic" lives.

As for service locators, I think that amount of indirection is probably overkill for a small or medium-sized project. I would start with something a bit simpler first.
> 1 votes

---
Tags: xna, input
---


title: Picking a tile in an Iso Engine

text:
# Question
Title: Picking a tile in an Iso Engine
I have developed an iso engine for a farm game. In general it works fine, but the problem is that it is not always accurate when pressing the tiles, so the tile I wanted to select is not the one picked. Anybody has some ideas how to improve this?

# Answer
> 1 votes
You should use a transform matrix. Check out this tutorial: http://www.alcove-games.com/isometric\_tile\_picking.php

# Answer
> 0 votes
In this answer the ratio between the projected diagonal of a square laying on the ground are 70:30. You can generalize with ease for the particular perspective you are using.

---
Tags: isometric, picking
---


# Question
Title: Getting isometric grid coordinates from standard X,Y coordinates
I'm currently trying to add sprites to an isometric Tiled TMX map using Objects in cocos2d. The problem is the X and Y metadata from TMX object are in standard 2d format (pixels x, pixels y), instead of isometric grid X and Y format. Usually you would just divide them by the tile size, but isometric needs some sort of transform.

For example on a 64x32 isometric tilemap of size 40 tiles by 40 tiles an object at (20,21)'s coordinates come out as (640,584)

So the question really is what formula gets (20,21) from (640,584)?

# Answer
After a few days of researching, I found a solution to this particular transform. This is much more mathematical than program-oriented. Therefore, I will be using pseudo code.

Now, given a screen coordinate (x,y), we first want to represent (x,y) respected, or fixed, to the world, not the screen. For example, my game use the top-left most corner of isometric map as (0,0). So anything representation of coordinates in this game will be respected to this world.

Therefore, the new coordinate is calculated like this:

```
inputWorldCoordXY = inputScreenCoordXY - drawOffsetXY

```

where drawOffset in my program is the screenCoordXY of the top-left most corner of my isometric map.

The reason we do this is because we want an isometric **world** coordinate system, not isometric **screen** coordinate system. As of what we have done so far, we have a **cartesian** world coordinate system, but we want a projected, or **isometric**, world coordinate system.

To accomplish this, I'd like to start with **the theory behind it**. In normal cartesian system, any coord point can be represented in form of vector. These vectors have vector's component, which can be represented by what we called **basis** vector. In 2D cartesian coord, we have two basis vector **i** and **j**, representing **x** and **y** respectively.

For a better clarification, the following **point** can be expressed as **vector v** which can be represent as a sum of **cartesian** basis vectors **3i+4j**:

So, how does this relate to **isometric coord system**? Well, the concept is the same, in any isometric coordinate system, any point can be represent in form of vector components, where the **basis** vectors are parallel with isometric axis:

Let the **isometric** basis vectors be **U,V** respectively.

Let **vectorW** be a vector representation of the point of **unknown** coordinate system. This vector can be represented with either sum of **cartesian components** or **isometric components**. These two ways of representing **produce the same vector.**

```
vectorW = cartesianPointX*i + cartesianPointY*j = isometricPointX*U + isometricPointY*V

```

Now, given that we already know where **the point lies in cartesian coordinate** and representation of vector **U** and **V** in term of cartesian **i j**. What we want to find is the isometric counterpart of this point: **isometricPointXY**, which is our desired isometric coordinate. Now, with **U,V, and W** in term of **i j**, which enable them to dotproduct each other and produce scalar quantity. We can use this property to produce 2 simultaneous equations:

let **A.B** be **A dotproduct B**, from equation above

```
W.U = isometricPointX * (U.U) + isometricPointY * (U.V)
W.V = isometricPointX * (U.V) + isometricPointY * (V.V)

```

Dotproduct produce scalar value, or constant. Therefore, we have a simultaneous equation, which can be solve using any mathematical method of your choice--- I prefer cramer rule.

Another thing to point out is the magnitude of U and V will **expand or compress** your isometric coordinate.

For example, if I define u and v to exactly cover 1 full isometric tile, then (1,1) would be the same thing as **1u + 1v** which is the bottom-right corner of the first tile in my isometric system, where top-left most is the origin.
> 9 votes

# Answer
So I guess what you're saying is that you want to convert from *world space* (isometric coordinates) to *screen space* (a point on the screen).

This is a known and solved problem in 3D graphics, so we can use a transformation matrix. First, let me give you the general solution and then we'll work our way up to your specific case.

The general solution is that you have a projection matrix. It can be perspective or orthogonal, it doesn't matter. It transforms points from *world space* to *clip space*, which is a really complicated 4D (yes, four) space that will make your head hurt if you think about it too long. This results in a *homogenized space coordinate*, meaning that it starts at the center of the screen, runs from -1 to 1 on the horizontal plane (-1 being left, 1 being right) and -1 to 1 on the vertical plane (-1 being up, 1 being down).

So our function becomes:

```
tb::Vec2 ProjectOnScreen(const tb::Vec3& a_WorldPosition)
{
    tb::Vec3 homogenized_pos = m_MatrixProjection * a_WorldPosition;

    return tb::Vec2(
        (homogenized_pos.x * 0.5f + 0.5f) * m_WindowWidth,
        (1.f - (homogenized_pos.y * 0.5f + 0.5f)) * m_WindowHeight
    );
}

```

As you can see, it uses these crucial variables:

* `a_WorldPosition` \- As the name implies, this is position in world space, for instance (0.0, 50.0, 0.0)
* `m_MatrixProjection` \- The projection matrix. This is often the combination of the *camera transform* (think rotation and position) with the actual projection matrix.
* `m_WindowWidth` \- The width of the window in pixels.
* `m_WindowHeight` \- The height of the window in pixels.

So, what about your specific case? You mention that you have an isometric projection. That means an orthographic projection matrix and a camera that is fixed to a certain angle, let's say 45 degrees on the Z axis and 90 degrees on the Y axis.

```
// note: I have swapped the bottom and top parameters
// of the glOrtho function for my own convenience

m_MatrixScreen.FromOrthographic(
    0.f, m_WindowWidth,
    0.f, m_WindowHeight,
    -1.f, 1.f
);

m_MatrixCamera.Identity();
m_MatrixCamera.AddRotationZ(45.f);
m_MatrixCamera.AddRotationY(90.f);
m_MatrixCamera.AddTranslation(m_Camera->GetPosition());

m_MatrixProjection = m_MatrixScreen * m_MatrixCamera;

```

If you plug that matrix into the function you should get the results you want.
> 2 votes

# Answer
Knight666, this helped me TREMENDOUSLY solving this issue.

However, there is some scaling to do as well; this code will not work out of the box. I use:

```

isoTransform = new Matrix4();
isoTransform.idt();
isoTransform.translate(0.0f, 0.25f, 0.0f);
isoTransform.scale((float)(Math.sqrt(2.0) / 2.0), (float)(Math.sqrt(2.0) / 4.0), 1.0f);
isoTransform.rotate(0.0f, 0.0f, 1.0f, -45.0f);

```

The reason for these weird sqrt(2) is all explained there: http://www.alcove-games.com/isometric\_tile\_picking.php
> 1 votes

---
Tags: mathematics, iphone, cocos2d-iphone, tiles, isometric
---


# Question
Title: How to factorize code in Unreal Kismet (i.e. "Material Function"s for Kismet)
In the Unreal Development Kit, when using the Material Editor, one can factorize frequently-used groups of nodes by creating a Material Function (content Browser → right-click → new matrial function, IIRC).

When defining the behaviour of some actor in Kismet, one can easily have a dozen nodes involved.

If I have many actors that share the same behaviour, then I'll copy-paste these nodes, and change the variables so they point to the other actors.

This leads to inconsistencies (a modification in the behaviour of an actor isn't propagated in the copy-pasted nodes), complexity (you end up with hundreds of nodes), and generally useless effort.

**My question is :** Can I create a "kismet function", just like a material function ?

Note: I'd rather avoid using UnrealScript.

1. I don't even know where to type UnrealScripts, don't know where the documentation is and more generally don't have enough time to invest in learning UnrealScript.
2. This "kismet function" feature must be usable by graphists (with little programming knowledge).
3. If a (simple) script suffices to add this feature in the Kismet editor, so that one can create several "functions" without using UnrealScript, then fine, but I don't really want to have to write a script each time I want to factorize a few nodes.

Thanks for any information !

# Answer
You can't make Kismet function in the sense that it will exists once in memory and can be called from several places at the same time. Every time you want to have the same piece of script, you must duplicate nodes.

However, you can use sub-sequences to clean-up a bit your Kismet canvas. A sub-sequence is a single node into your main sequence, which contains itself several nodes. It can have inputs, outputs and also variables.

At first, right-click on your Kismet canvas, and create a new sequence (which will actually be a sub-sequence. Now you can select the subsequence in the Sequence treeview. Do it and add some action nodes. You can create an input to this subsequence by adding an event "Sequence activated". You can expose variables (for exemple, actor references) by adding a variable "External variable" You can create an output by adding an action "Finish Sequence" (in the Misc category)

You can see the subsequence in the parent canvas with all the inputs/variables/outputs you created. When you're done, you can copy-paste it as much times as you want to make a copy of the same piece of script, and simply links the corrects input/variables/output to it.

But remember that if you want to modify this sub-sequence afterwards, your changes won't be propagated to the other copies. You have to modify one of them, then delete the other ones and re-do the copy-paste for every other instances. To be clear, this won't improbe the maintainability of your Kismet script, only the reading of it.

Finally, it is also possible to export a sub-sequence to a package to use it in different level. However, it won't be editable anymore after that (you can't open a Sequence from the Content Browser with Kismet), and by experience you may have trouble to import it in your kismet scripts if you do this.
> 2 votes

---
Tags: udk
---


title: As a indie, how to protect your game?

text:
# Question
Title: As a indie, how to protect your game?
As a indie, you might not work in a company. And you may have a great game idea and you feel it gonna be a big success. When you released your game. How do you protect it as your own creation? So that someone also can't steal the title and publish a "sequel" e.g. Your-Game-Name 2,3,4. Or even produce by-products like Angry Birds but without your permission.

So how we can prevent these from happening by legal methods. Like copyrights, trademarks? If a professional can fill us those info, it will be great.

# Answer
I believe a copyright would be helpful, but you have intellectual rights to begin with, getting a registered trademark or trademark on the game name would also help protect from people using the name for "Sequels".
> 11 votes

# Answer
In 1605, Miguel de Cervantes published a book, "The Ingenious Gentleman Don Quixote of La Mancha" (now typically known simply as "Don Quixote"). It was (and remains to this day) quite popular.

In 1614, an anonymous other author published a book, "Second Volume of the Ingenious Gentleman Don Quixote of La Mancha", without permission. Cervantes was quite upset, particularly with the portrayal his characters received in this book.

Of course, our modern Copyright laws didn't arrive until the 18th century. And even now, the usage of other people's characters in an original work is a bit murky, particularly when their core qualities are changed. So Cervantes couldn't make a legal challenge on the basis of copyright, the way that we can today.

Instead, Cervantes published his own sequel in 1615 (now typically printed together with the original book), in which miscreants unknown are alleged to have travelled around the country, pretending to be the book's chief protagonists, Don Quixote and Sancho Panza (thus explaining their uncharacteristic behaviours described in the unauthorised book).

To stop future authors from producing further derivative works using his characters, Cervantes has Don Quixote die at the end of the second book, and informs readers that since Don Quixote is now dead, any Don Quixotes which may appear in further books must therefore be fraudulent ones.

....so you could always do that. :)
> 11 votes

# Answer
The best way to protect your intellectual property from others is to register the name of your game as a trademark.

Trademarks are usually registered for a specific product category. So when you register "Awesomequest" as a game name, you can challenge anyone who makes an "Awesomequest 2" game for being too close to your trademark, but not someone who makes an "Awesomequest" toothbrush, because it's in a different product category and thus unlike to be mistaken for being connected to your product. You can register your trademark for multiple product categories when you want, but this costs extra and is usually unnecessary unless your get as super-successful as Angry Birds so that your game name can be used to sell just about anything.

But this still doesn't prevent people to create a sequel to your game under a completely different name. See, for example, the remake of Star Control II, which is identical to the original in almost every aspect (which is OK because they have the rights to the original game code and assets), but which has to be named "The Ur-Quan Masters", because they don't own the trademark.

As an additional protection you could consider to also register trademarks for certain other intellectual properties of your game, like the names of character, locations, plot devices or factions. You can also register image-trademarks on your game logo, the likeliness of your characters or other iconic assets of your game. But registering just about everything as a trademark can get too expensive for the budget of an independent game and is usually only worth it for the big companies.
> 4 votes

# Answer
I may be here to learn about Game Dev, but I do know something about legal issues! :-)

As it's creator, from the moment of creation you're protected under the U.S. Copyright code! See § 104 of the code. When you publish it, however, you must make sure you or one of the other "authors" are *a national or domiciliary of the United States, or is a national, domiciliary, or sovereign authority of a treaty party*

If you need to sue, however, you'll need to

1. Prove you're the author
2. Register with the copyright office

As long as you can prove it is yours --i.e. mail the concept with examples to yourself with postal reciept and don't open it-- you're fine until you **need** to sue!
> 3 votes

# Answer
Possibly the best way to protect your work from being copied is to make it so unique that nobody could copy it without it being very clear that they have based the work on your own. This maxim applies to all forms of legal protection and also as a general discouragement to others.

Regarding formal legal methods:

* Copyright is normally granted to your work automatically, but check your local laws. This doesn't protect concepts, only the final product, large bodies of text within, specific images, etc. This stops people using your graphics, sounds, etc., except where law provides exceptions (eg. for review purposes, criticism, parody, etc.)
* Patents are rarely applicable to games, but sometimes can apply to interface methods or occasionally game mechanics. Some jurisdictions won't even recognise them. This avenue is rarely worth looking at for an indie developer.
* Trademarks protect names and logos and the like within a certain industry, to stop other companies from pretending to make your goods. This is what would stop someone making a sequel to your game under the same name. It is worth seeking a trademark if you think your title is a big selling point but this is rarely a problem in indie game development.
> 1 votes

# Answer
It's like Lauryn Hill said

Everything you did has already been done

Although 'L is talking about hip hop music here, her point is the same for any creative discipline.

If you look far enough you will find pretty much every element of the game you create, in some other game, somewhere else, perhaps made 20 years ago. You might have only played it once, and not even realize you're completely copying another game's mechanic in the 3 months you spend developing your game.

Some games creators even cite their influences openly, like Binding of Isaac creator said he was out to create a Zelda-1-like dungeon game. And that's exactly what he did.

As has been hammered again and again, **it's not about ideas**, ideas are a cent each. It's about successful execution of your game idea.

If you deliver a successful incarnation of your idea, people will play your game, talk about it, and it will be recognized.
> 0 votes

# Answer
Do not protect it, as an indie you want your game to be played by everyone to make if popular. After that you can think about these things for the second one. So if another make a sequel it is a good chance to take some articles talking about you and your game
> -2 votes

---
Tags: marketing
---


# Question
Title: How to efficiently map tokens to code in a script interpreter?
I'm writing an interpreter for a simple scripting language where each line is a complete, executable command. (Like the instructions in assembler)

When parsing a line I have to map the requested command to actual code. My current solution looks like this:

```
std::string op, param1, param2;
//parse line, identify op, param1, param2
...
//call command specific code
if(op == "MOV")
    ExecuteMov(AsNumber(param1));
else if(op == "ROT")
    ExecuteRot(AsNumber(param1));
else if(op == "SZE")
    ExecuteSze(AsNumber(param1));
else if(op == "POS")
    ExecutePos((AsNumber(param1), AsNumber(param2));
else if(op == "DIR")
    ExecuteDir((AsNumber(param1), AsNumber(param2));
else if(op == "SET")
    ExecuteSet(param1, AsNumber(param2));
else if(op == "EVL")
    ...

```

The more commands are supported the more string comparisions I'll have to do to identify and call the associated method.

Can you point me to a more efficient implementation in the described scenario?

# Answer
You can use a hash table that maps the command names to either an integer enum/define or to function pointers that implement the actual command.

**Hash Tables**

I usually roll my own simple hash tables so you'll need to find a library you like or do the same. I'll use a placeholder "HashTable" in these examples.

**Enum/Define**

If you use an Enum/Define you might also put all the command execution in a big switch/case. This will save a lot of overhead on function calls.

Example:

```
enum OpType { OP_MOV, OP_ROT, ... };

HashTable<string,OpType> op_lookup;  // HashTable is a placeholder type
op_lookup["MOV"] = OP_MOV;
...

// parse 'op', 'param1', 'param2'
switch (op_lookup[op])
{
  case OP_MOV:
    // perform mov code here
    break;  // or 'continue'
  ...
}

```

**Function Pointers**

Use globals or class variables for 'op', 'param1', and 'param2' values to avoid having to pass them around as parameters.

```
typedef void (*OpFn)();

void OpMov()
{
  // use global 'param1' etc.
}
...

HashTable<string,OpFn> op_dispatch;
op_dispatch["mov"] = OpMov;
...

// parse 'op', 'param1', 'param2'
op_dispatch[op]();  // call the function that 'op' maps to.

```

Note: code examples are untested.
> 4 votes

# Answer
You could use the concept of opcodes, which it seems like you're doing already (to some extent, with strings).

To gain some efficiency, you could parse your script files and generate a list of opcodes. The opcodes could be an enum or just integers. This would allow you to use a simple switch where the cases are your opcodes. To run the script, you just keep looping through the list of codes until you get to the end.
> 0 votes

---
Tags: c++, performance
---


# Question
Title: Problems implementing a screen space shadow ray tracing shader
Here I previously asked for the possibility of ray tracing shadows in screen space in a deferred shader. Several problems were pointed out. One of the most important problem is that only visible objects can cast shadows and objects between the camera and the shadow caster can interfere. Still I thought it'd be a fun experiment.

The idea is to calculate the view coordinates of pixels and cast a ray to the light. The ray is then traced pixel by pixel to the light and its depth is compared with the depth at the pixel. If a pixel is in front of the ray, a shadow is casted at the original pixel.

At first I thought that I could use the DDA algorithm in 2D to calculate the distance 't' (in p = o + t d, where o origin, d direction) to the next pixel and use it in the 3D ray equation to find the ray's z coordinate at that pixel's position. For the 2D ray, I would use the projected and biased 3D ray direction and origin. The idea was that 't' would be the same in both 2D and 3D equations. Unfortunately, this is not the case since the projection matrix is 4D. Thus, some tweak needs to be done to make this work this way.

I would like to ask if someone knows of a way to do what I described above, i.e. from a 2D ray in texture coordinate space to get the 3D ray in screen space.

I did implement a simple version of the idea which you can see in the following video: video here

Shadows may seem a bit pixelated, but that's mostly because of the size of the step in 't' I chose.

And here is the shader:

```

#version 330 core

uniform sampler2D DepthMap;

uniform vec2 projAB;
uniform mat4 projectionMatrix;

const vec3 light_p = vec3(-30.0, 30.0, -10.0);

noperspective in vec2 pass_TexCoord;
smooth in vec3 viewRay;

layout(location = 0) out float out_AO;

vec3 CalcPosition(void){
    float depth = texture(DepthMap, pass_TexCoord).r;
    float linearDepth = projAB.y / (depth - projAB.x);
    vec3 ray = normalize(viewRay);
    ray = ray / ray.z;
    return linearDepth * ray;
}

void main(void){
    vec3 origin = CalcPosition();
    if(origin.z < -60) discard;
    vec2 pixOrigin = pass_TexCoord; //tex coords
    vec3 dir = normalize(light_p - origin);

    vec2 texel_size = vec2(1.0 / 600.0);

    float t = 0.1;
    ivec2 pixIndex = ivec2(pixOrigin / texel_size);
    out_AO = 1.0;
    while(true){
        vec3 ray = origin + t * dir;
        vec4 temp = projectionMatrix * vec4(ray, 1.0);
        vec2 texCoord = (temp.xy / temp.w) * 0.5 + 0.5;
        ivec2 newIndex = ivec2(texCoord / texel_size);
        if(newIndex != pixIndex){
            float depth = texture(DepthMap, texCoord).r;
            float linearDepth = projAB.y / (depth - projAB.x);
            if(linearDepth > ray.z + 0.1){
                out_AO = 0.2;
                break;
            }
            pixIndex = newIndex;
        }
        t += 0.5;
        if(texCoord.x < 0 || texCoord.x > 1.0 || texCoord.y < 0 || texCoord.y > 1.0) break;
    }
}

```

As you can see, here I just increment 't' by some arbitrary factor, calculate the 3D ray and project it to get the pixel coordinates, which is not really optimal. Hopefully, I would like to optimize the code as much as possible and compare it with shadow mapping and how it scales with the number of lights.

PS: Keep in mind that I reconstruct position from depth by interpolating rays through a full screen quad.

# Answer
I have fixed the problem I had with the DDA algorithm. I was using the 3D direction's xy coordinates but I should instead use the projection matrix on the direction with 4th component 0.

The performance of the shader as expected is not that good, but it seems to scale quite ok with number of lights. The performance can also be increased by increasing the step of the DDA algorithm, thus effectively sampling at a lower resolution.

Below is the shader for whoever may be interested.

```

#version 330 core

uniform sampler2D DepthMap;

uniform vec2 projAB;
uniform ivec2 resolution;
uniform mat4 projectionMatrix;

uniform vec3 light_p;

noperspective in vec2 pass_TexCoord;
smooth in vec3 viewRay;

layout(location = 0) out float out_SH;

vec3 CalcPosition(void){
    float depth = texture(DepthMap, pass_TexCoord).r;
    float linearDepth = projAB.y / (depth - projAB.x);
    vec3 ray = normalize(viewRay);
    ray = ray / ray.z;
    return linearDepth * ray;
}

void main(void){
    vec2 texel_size = vec2(1.0 / resolution.x, 1.0 / resolution.y);
    vec3 origin = CalcPosition();
    if(origin.z < -99) discard; //Don't check points at infinity
    vec2 pixOrigin = pass_TexCoord;

    vec3 dir = normalize(light_p - origin);
    vec4 tempDir = projectionMatrix * vec4(dir, 0.0);
    vec2 pixDir = -tempDir.xy / tempDir.w;
    float dirLength = length(pixDir);
    pixDir = pixDir / dirLength;

    vec2 nextT, deltaT;

    if(pixDir.x < 0){
        deltaT.x = -texel_size.x / pixDir.x;
        nextT.x = (floor(pixOrigin.x * resolution.x) * texel_size.x - pixOrigin.x) / pixDir.x;
    }
    else {
        deltaT.x = texel_size.x / pixDir.x;
        nextT.x = ((floor(pixOrigin.x * resolution.x) + 1.0) * texel_size.x - pixOrigin.x) / pixDir.x;
    }
    if(pixDir.y < 0){
        deltaT.y = -texel_size.y / pixDir.y;
        nextT.y = (floor(pixOrigin.y * resolution.y) * texel_size.y - pixOrigin.y) / pixDir.y;
    }
    else {
        deltaT.y = texel_size.y / pixDir.y;
        nextT.y = ((floor(pixOrigin.y * resolution.y) + 1.0) * texel_size.y - pixOrigin.y) / pixDir.y;
    }

    float t = 0.0;
    ivec2 pixIndex = ivec2(pixOrigin * resolution);
    out_SH = 1.0;
    while(true){
        if(t > 0){
            float rayDepth = (origin + t * dir).z;
            vec2 texCoord = pixOrigin + 0.5 * pixDir * t * dirLength;
            float depth = texture(DepthMap, texCoord).r;
            float linearDepth = projAB.y / (depth - projAB.x);
            if(linearDepth > rayDepth + 0.1){
                out_SH = 0.2;
                break;
            }
        }
        if(nextT.x < nextT.y){
            t = nextT.x;
            nextT.x += deltaT.x;
            if(pixDir.x < 0) pixIndex.x -= 1;
            else pixIndex.x += 1;
        }
        else {
            t = nextT.y;
            nextT.y += deltaT.y;
            if(pixDir.y < 0) pixIndex.y -= 1;
            else pixIndex.y += 1;
        }
        if(pixIndex.x < 0 || pixIndex.x > resolution.x || pixIndex.y < 0 || pixIndex.y > resolution.y) break;
    }
}

```

The vertex shader passes a view ray by multiplying the vertices of a full screen quad with the inverse projection matrix.

`vec2 projAB` is defined as:

`vec2 projAB = vec2( zfar / (zfar - znear), zfar * znear / (zfar - znear) )`

The above implementation is for one light, but it is easily extended to multiple lights by using a loop over the light positions.
> 2 votes

---
Tags: opengl, glsl, shadows, raycasting
---


# Question
Title: Efficient Algorithm for Recording gameplay's objects positions
So, I have a game idea in mind, and for that I need to record the game around the player. I'me not talking about recording it as video, but rather recording the scene objects, and their positions within the game, and then render them, giving the player the ability to go back and forth, to stop time and move around.

I've made a prototype with some data structures in C#, since this is going to be the programming language we'll be using in our game, but if we want the player to be able to go back just five minutes back with the data of just 100 NPC's, it takes almost 1GB of RAM.

Right now, I'm just storing a Doubly linked list, each item with the object position. In the game, I'll need to store even more data in each node, so I need something even more ligher. Of course, this algorithm is zero optimized, but still, that is a lot.

The alternatives would be create the NPC's that aren't really important to the game when the user is viewing the past, but I don't really like it very much for the sake of realism.

I wonder if there is a better way to store this?

Thanks in advance, Scorch

# Answer
> 2 votes
1. Don't use a linked list, use a linked list of arrays that each have (say) 1min reserved
2. You probably don't need to be recording most frames. Recording only every 3rd frame would save a lot of space, and you could get away with less than that.
3. If your game is deterministic, you could just record the player input
4. Your position is most likely being stored as either 3 floats or 3 doubles (12/24 bytes, possible 16/32 if the memory is being padded). You could probably save some space and save them as integer shorts (short x=position.x\*10). This would be lossy saving, as you would lose precision (only one decimal place if you multiply by 10, and your positions couldn't be greater than 3,276)

# Answer
> 1 votes
Just a thought, and this might be completely invalid depending on how you want your NPCs to operate, but if you give the NPCs/world elements a repeating pattern to execute, you wouldn't have to actually store the data of their position. Rather, take the modulus of the time and interval over which the first iteration of the pattern is executed, and base the game entities position off of that.

And if you want those entities to respond to the player, you can have their reactions begin by triggering a boolean that says this entity is no longer part of the pattern, which in turn will trigger position recording.

I've never done something like this, but it sounds like this might work. I'd be happy to hear otherwise.

# Answer
> 1 votes
Instead of recording all object positions at every frame, just record the information you need to recalculate them. Generally, this consists of three things:

1. The initial state of the world, including object positions, velocities etc., at the beginning of the recording.
2. Player input, i.e. every action taken in direct response to player commands. (You don't necessarily have to record irrelevant details like the exact path of the mouse cursor, if that doesn't affect what happens in the actual game world. Just pick whatever abstraction of the player's actions that seems most compact and natural.)
3. Random events. In general, this can be achieved by recording the outcome of every call to the random number generator, but if you're using a deterministic PRNG, it's enough to record its initial state.

---

Note that, if you only record the initial PRNG state, any changes made to the timeline are likely to have very strong global "butterfly effects" as soon as they change the number of calls made to the PRNG, which will cause the sequence of outputs to be shifted. If you find this undesirable, you could mitigate it in various ways, such as:

* Try to make sure that each entity makes the same number of calls to the PRNG regardless of external circumstances. This may not be very practical, but I include it for completeness.
* Reseed the PRNG regularly (e.g. before each frame) from an external source (either a recorded copy of its state or a second "master" PRNG which is only used for this purpose). This will temporally limit the butterfly effect, since changes in the PRNG output will not propagate between frames.
* Give each NPC or other entity that makes random choices a separate instance of the PRNG with its own state. That way, any butterfly effects will be spatially localized to the affected entities (until, of course, these entities interact with others, which may cause the behavior of the other entities to diverge as well).

You could, of course, also combine the alternatives above, e.g. by giving each entity *two* PRNG instances, one of which is only used to reset the other every frame.

---
Tags: c#, architecture
---


# Question
Title: Glenn Fiedler's fixed timestep with fake threads
I've implemented Glenn Fiedler's Fix Your Timestep! quite a few times in single-threaded games.

Now I'm facing a different situation: I'm trying to do this in JavaScript. I know JS is single-threaded, but I plan on using requestAnimationFrame for the rendering part.

This leaves me with two independent fake threads: simulation and rendering. Timing in these threads is independent too: `dt` for simulation and render is not the same.

If I'm not mistaken, simulation should be up to Fiedler's while loop end. After the while loop, `accumulator < dt` so I'm left with some unspent time (`accumulator`) in the simulation thread.

The problem comes in the draw/interpolation phase:

```
const double alpha = accumulator / dt;
State state = currentState*alpha + previousState * ( 1.0 - alpha );
render( state );

```

In my render callback, I have the current timestamp to which I can subtract the last-simulated-in-physics-timestamp to have a `dt` for the current frame.

Should I just forget about this `dt` and draw using the physics thread's `accumulator`? It seems weird, since, well, I want to interpolate for the unspent time between simulation and render too, right?

Of course, I want simulation and rendering to be completely independent, but I can't get around the fact that in Glenn's implementation *the renderer produces time and the simulation consumes it in discrete dt sized chunks.*

A similar question was asked in Semi Fixed-timestep ported to javascript but the question doesn't really get to the point, and answers there point to removing physics from the render thread (which is what I'm trying to do) or just keeping physics in the render callback too (which is what I'm trying to avoid.)

# Answer
How much time does the game logic update take? If your's like most games use very little resources for the game logic there is no need to run multiple virtual threads.

Interpolation takes a lot of extra code, you shouldn't waste your time on it unless you have to. Running your logic at a rate that gives a whole number of updates per screen update should give smooth animation without interpolation, since 60 Hz is pretty much the standard these days that is pretty easy to do, your logic rate should be a multiple of 60. A more brutal approach is to simply run the logic at a very high rate, thus limiting the amount that any frame can be off, a high enough logic rate will make the animation smooth irrespective of any synchronization issues. If it isn't too much of a CPU strain on any target platform I'd combine the two methods and run at least at 120 Hz. Otherwise try 60 Hz.

```
function update(){
    var advance=(+new Date()-startTime)*logicRate
    while(stepCount*1000<advance){
        doLogic()
        stepCount++
    }
    render()
}

```

One thing to remember is that input should be applied to the correct update, put keyboard and mouse events in a buffer and apply them only as you do the logic step where they belong.

I wouldn't remove the game logic update from the render call, it's a great place to have it in order to ensure that the logic is up to date, but you could make a separate routine that most likely get the job done beforehand:

```
function updateLogic(){
    var advance=(+new Date()-startTime)*logicRate
    if(stepCount*1000<advance){
        doLogic()
        stepCount++
    }
}
setInterval(updateLogic,1)

```

It won't make any real difference unless the logic update takes a significant amount of time.
> 1 votes

---
Tags: javascript, timestep
---


# Question
Title: How can I make iPhone apps (games) on Windows?
I want to start making iPhone games, but sadly I'm a Windows geek.. Is there a way to make good profesional iPhone games without Xcode/owning a Mac computer?

If not, what do you recommend, a Mac Mini?

Thanks in advance!

# Answer
> 5 votes
There are a few options available to you:

* **Buy a Mac:** This is the most full-proof, but probably the most expensive. If you can figure out what exactly you need (eg. Lion vs. Leopard), you can probably save some of the cost by buying something that's not latest-and-greatest, but "good enough" for development.
* **Run a Mac VM:** This is usually illegal (depending on where you live), plus none of the virtualization tools on Windows support running Mac VMs. I suggest you avoid this route completely.
* **Find a Mac:** If you are studying at a university, chances are that they will have a lab with a Mac. This may be a viable, albeit short-term, option.
* **Cloud Mac services:** There are some services like MacinCloud (which I have never used) which offer a service similar to Amazon EC2, but for Macs. It's probably expensive, and may be worthwhile if you can build and test your app on Windows in entirety, but only need a Mac for the final steps of publishing or building iOS builds.

Again, buying a Mac is probably the "best" all around option, albeit the heftiest. Depending on your needs, a cloud mac service may be viable too.

# Answer
> 3 votes
A friend of mine released his game with Xamarin. You just need to create your game in C#, then this software can compile the source to iOS and Android. (And of course, because of the C#, you can also release it on Windows Phone.) Really good stuff.

# Answer
> 1 votes
I've been programing on a mac mini for about a year now and it's been great. They are quite honestly the most powerful mac for the buck. I bought an i3 w/ 2G of ram and installed 8G later on for $40USD. Its much better programming iOS apps on a Mac than any other computer.

Let me know if you have any questions. I'd love to answer them for you

# Answer
> 0 votes
Another alternative to buying a mac, is to look into programming using the marmalade frame work. Its one of those cross platform kind of packages where you can deploy on a bunch of platforms. I believe you can even use Cocos2dx ontop of it.

---
Tags: iphone, windows, macos
---


title: Basic modelling of radar

text:
# Question
Title: Basic modelling of radar
I'm currently researching how to model/simulate radar for my naval simulation. Since the emphasis is on modelling ASW or submarines in general, I need only a basic radar model - at least for the beginning.

So, does anybody know a resource for such a simple model?

The model should take signal strength of the sensor, the size of the target and the terrain (height/ground clutter) into account.

Edit: This question is not about displaying a radar screen but to simulate the underlying physics of radar. The model would need to work for ships/aircraft/missiles.

Thanks.

# Answer
I assume you've already read the Wikipedia article on radar. Here's another site I found (radartutorial.eu) which might be useful.

If you really want to implement realistic radar (or sonar), you'll probably want to use ray tracing. The basic principle is just the same as in the usual light ray tracing used for 3D rendering, so you can use any of the usual implementation techniques.

One difference is that, for distance/time-of-flight estimation, you'll want to keep track of the total length of the ray. Also, you'll typically have only one "light source", which is located at the same position as the "camera", which might allow some extra optimizations. (However, if you add the possibility of radar jamming into the mix, this is no longer always the case.)

The tricky part will be in coming up with realistic values for the radar reflectances of various surfaces, as well as modelling any relevant atmospheric effects as well as reflections from the sea surface. Also, at longer wavelengths, diffraction effects (which cannot be fully modeled by ray tracing) start to become more significant; however, I think the typical wavelengths used for modern marine radar should be short enough for these to be mostly negligible.

In any case, most of the basic code should be the same for both radar and sonar, so if you're going for a realistic implementation of one, you might as well start with that and then reuse the framework for the other.
> 2 votes

# Answer
I'm assuming you're talking about something like the sonar screens seen in movies, with a line sweeping about in a circle. If so...

Address the basic model first (with no parameters), using a 2D circular line sweep. There are a couple of ways you can do this:

**Continuous linear collision detection**

1. Set up a class representing a line (not rays -- the difference being that lines have endpoints). Ensure that the class supports check intersection of one line against another line eg. `Line.intersect(Line a, Line b)`. Also make sure it internally encapsulates the trig for rotating the line. Countless vector, ray and line classes exist online for easy reference. Test your line class and *be sure* it works.
2. Each nearby vessel will need to have their silhouettes constructed as individual lines, or alternatively they may be represented as a circle or set of circles. Circles may be a little cheaper to calculate collisions against.
3. Now test your sweeping line against every line, or circle, constituting every vessel in detection range, to see if there are any hits. If so, register the hit on your display.

**Quantised grid collision detection**

1. Set up a regional grid representing the larger area in which naval action is taking place.
2. Set up a local grid representing the area currently surrounding the player vessel. This area will essentially a subset of the region's cells, at some (x, y) offset dependant on player vessel position.
3. Set up your surrounding vessels by marking each grid cell they occupy, a bit like Battleships. How you discern occupation of cells is up to you -- some vessels may be rotated, for instance, making this a little more tricky.
4. Set up your angle of your sonar line (per update).
5. Using trig, calculate the dx and dy of the line. Now walk those dx, dy steps in the local grid, moving out from the centre (player position) to the edge of the detection circle, and on each step check to see if you've hit a cell where an enemy vessel already exists. This is again reminiscent of Battleships, though instead of plotting single discrete points to check for a hit, you are plotting a line of points until a hit is found (and possibly beyond the first hit, as well, out to the edge of the sonar radius).
> 2 votes

---
Tags: algorithm, simulations
---


title: Efficient skeletal animation

text:
# Question
Title: Efficient skeletal animation
I am looking at adopting a skeletal animation format (as prompted here) for an RTS game. The individual representation of each model on-screen will be small but there will be lots of them!

In skeletal animation e.g. MD5 files, each individual vertex can be attached to an arbitrary number of joints.

How can you efficiently support this whilst doing the interpolation in GLSL? Or do engines do their animation on the CPU?

Or do engines set arbitrary limits on maximum joints per vertex and invoke nop multiplies for those joints that don't use the maximum number?

Are there games that use skeletal animation in an RTS-like setting thus proving that on integrated graphics cards I have nothing to worry about in going the bones route?

# Answer
> 6 votes
Limiting the number of bone influences is common, yes. You can either 0-weight unused influences, or have a loop/early-out mechanism to skip.

As for whether it works for an RTS, I don't have a reference for you, but I imagine you're going to need LOD if working with a large number of characters on-screen, and also if those characters are small.

LODing skeletal characters is much the same as LODing anything else, except you'll probably want to LOD the bone influences and skeleton as well as the mesh.

For example, a low-ish level of detail might only use a single bone with the highest influence per-vertex (also known as "hard skinning").

You would probably also limit the number of bones in the skeleton for a low LOD model.

Finally - consider whether you *ever* need to render the characters close-up. You probably only want to model, skin and animate the characters for the closest view distance... certainly you don't want to be storing all the runtime data at a resolution far higher than you'll ever render. You might find that you just don't need more than a very basic skeleton and a couple of influences per-vertex for your situation.

# Answer
> 2 votes
I dont think skeletal animation is good for an RTS game, skeletal animation will require extra process for all characters, while keyframe animation consumes more memory but you will use the same for lots of characters, also a rts game requires little animations per character

---
Tags: opengl, animation, shaders, skeletal-animation
---


# Question
Title: XNA 4.0 Refresh AudioEngine, WaveBank and Others Not Found
I'm going through the Learning XNA 4.0 book, and unfortunately I installed XNA 4.0 refresh. All the code up until now has worked, with the exception of me needing to remove the Framework.Net and Framework.Storage. (As a side question, will this be problematic later?)

The problem I'm having now is that in my Game1.cs file, I have imported all of the XNA.Framework libraries, and when I try and create instances of any of the following classes, an error pops up saying VisualStudio can't find them: AudiEngine, WaveBank, SoundBank, and Cue.

I have googled around for a while, and the only solution I saw was to import Microsoft.Xna.Framework.Xact, but this doesn't seem to exist for me.

Any help is much appreciated, Thanks Peter.

# Answer
Ok, I did some googling (this is a verb now, and my spell check should know better) and I found the solution.

I'm more familiar with Java that C# so when everything online said to add a reference to the Microsoft.Xna.Framework.Xact binary, I thought it was how you said 'import' in C#. For those of you who will inevitably make the same mistake as I have, you have to right click the reference folder in your project (NOT the one in the Content folder) and add a reference from there.

Hope this helps someone
> 0 votes

---
Tags: xna, import
---


# Question
Title: Full screen blackout using allegro in codeblocks
I'm very interested in game programming and I'm taking my first steps alone. So I installed allegro. Although Dev-C++ didn't work, Code::Blocks compiled successfully. I started out with this basic program:

```
#include <allegro.h>

int main(){

    allegro_init();
    install_keyboard();
    set_gfx_mode( GFX_AUTODETECT, 640, 480, 0, 0);

    readkey();

    return 0;

}
END_OF_MAIN();

```

The problem comes in when I try to run it. It opens the little window as always, but rapidly blacks out my whole screen. I press any key and it takes me back to the little window telling me that it finished, which means the program worked. But I try any other program with allegro, like:

```
#include <allegro.h>

int x = 10;
int y = 10;

int main(){

    allegro_init();
    install_keyboard();
    set_gfx_mode( GFX_AUTODETECT, 640, 480, 0, 0);

    while ( !key[KEY_ESC] ){

        clear_keybuf();

        acquire_screen();

        textout_ex( screen, font, " ", x, y, makecol( 0, 0, 0), makecol( 0, 0, 0) );

        if (key[KEY_UP]) --y;
        else if (key[KEY_DOWN]) ++y;
        else if (key[KEY_RIGHT]) ++x;
        else if (key[KEY_LEFT]) --x;

        textout_ex( screen, font, "@", x, y, makecol( 255, 0, 0), makecol( 0, 0, 0) );

        release_screen();

        rest(50);

    }

    return 0;

}
END_OF_MAIN();

```

And the same thing happens over and over again! Is there something I'm doing wrong?

# Answer
Okay, I entered -lalleg in the Project/Project Options/Parameters/Compiler and added the lalleg.dll.a library in the Linker and everything turned out alright. Leftium helped with the GFX\_AUTODETECT\_WINDOWED. The solution was probably made by creating a diffferent project for every individual source code though.
> 1 votes

# Answer
It is difficult to understand what the problem is from your question:

1. What results are you expecting?
2. What are the actual results you are getting?

---

Nevertheless, I'll take a guess: Modern versions of Windows (XP and later?) don't support Allegro full-screen mode very well. You are probably seeing the unwanted effects of this.

Changing `GFX_AUTODETECT` to `GFX_AUTODETECT_WINDOWED` will cause Allegro to start your program in a window instead of fullscreen.

Related Allegro documentation
> 0 votes

---
Tags: windows, allegro
---


title: add collision detection to sprite?

text:
# Question
Title: add collision detection to sprite?
bassically im trying to add collision detection to the sprite below, using the following:

```
self.rect = bounds_rect

                collide = pygame.sprite.spritecollide(self, wall_list, False)

                if collide:
            # yes

                     print("collide")

```

However it seems that when the collide is triggered it continuously prints 'collide' over and over when instead i want them to simply not be able to walk through the object, any help?

```
def update(self, time_passed):
        """ Update the creep.

            time_passed:
                The time passed (in ms) since the previous update.
        """
        if self.state == Creep.ALIVE:
            # Maybe it's time to change the direction ?
            #
            self._change_direction(time_passed)

            # Make the creep point in the correct direction.
            # Since our direction vector is in screen coordinates
            # (i.e. right bottom is 1, 1), and rotate() rotates
            # counter-clockwise, the angle must be inverted to
            # work correctly.
            #
            self.image = pygame.transform.rotate(
                self.base_image, -self.direction.angle)

            # Compute and apply the displacement to the position
            # vector. The displacement is a vector, having the angle
            # of self.direction (which is normalized to not affect
            # the magnitude of the displacement)
            #
            displacement = vec2d(
                self.direction.x * self.speed * time_passed,
                self.direction.y * self.speed * time_passed)

            self.pos += displacement

            # When the image is rotated, its size is changed.
            # We must take the size into account for detecting
            # collisions with the walls.
            #
            self.image_w, self.image_h = self.image.get_size()
            global bounds_rect
            bounds_rect = self.field.inflate(
                            -self.image_w, -self.image_h)

            if self.pos.x < bounds_rect.left:
                self.pos.x = bounds_rect.left
                self.direction.x *= -1
            elif self.pos.x > bounds_rect.right:
                self.pos.x = bounds_rect.right
                self.direction.x *= -1
            elif self.pos.y < bounds_rect.top:
                self.pos.y = bounds_rect.top
                self.direction.y *= -1
            elif self.pos.y > bounds_rect.bottom:
                self.pos.y = bounds_rect.bottom
                self.direction.y *= -1

            self.rect = bounds_rect

            collide = pygame.sprite.spritecollide(self, wall_list, False)

            if collide:
        # yes

                 print("collide")

        elif self.state == Creep.EXPLODING:
            if self.explode_animation.active:
                self.explode_animation.update(time_passed)
            else:
                self.state = Creep.DEAD
                self.kill()

        elif self.state == Creep.DEAD:
            pass

        #------------------ PRIVATE PARTS ------------------#

    # States the creep can be in.
    #
    # ALIVE: The creep is roaming around the screen
    # EXPLODING:
    #   The creep is now exploding, just a moment before dying.
    # DEAD: The creep is dead and inactive
    #
    (ALIVE, EXPLODING, DEAD) = range(3)

    _counter = 0

    def _change_direction(self, time_passed):
        """ Turn by 45 degrees in a random direction once per
            0.4 to 0.5 seconds.
        """
        self._counter += time_passed
        if self._counter > randint(400, 500):
            self.direction.rotate(45 * randint(-1, 1))
            self._counter = 0

    def _point_is_inside(self, point):
        """ Is the point (given as a vec2d) inside our creep's
            body?
        """
        img_point = point - vec2d(
            int(self.pos.x - self.image_w / 2),
            int(self.pos.y - self.image_h / 2))

        try:
            pix = self.image.get_at(img_point)
            return pix[3] > 0
        except IndexError:
            return False

    def _decrease_health(self, n):
        """ Decrease my health by n (or to 0, if it's currently
            less than n)
        """
        self.health = max(0, self.health - n)
        if self.health == 0:
            self._explode()

    def _explode(self):
        """ Starts the explosion animation that ends the Creep's
            life.
        """
        self.state = Creep.EXPLODING
        pos = ( self.pos.x - self.explosion_images[0].get_width() / 2,
                self.pos.y - self.explosion_images[0].get_height() / 2)
        self.explode_animation = SimpleAnimation(
            self.screen, pos, self.explosion_images,
            100, 300)
        global remainingCreeps

        remainingCreeps-=1

        if remainingCreeps == 0:
                print("all dead")

```

# Answer
When the collision happens you need to do something to resolve it, for example, stop the motion of the offending sprite, and probably move it back a small step, else it will continue to collide in every loop through your update.
> 1 votes

---
Tags: python, pygame
---


title: XNA development tutorials

text:
# Question
Title: XNA development tutorials
Can anybody guide me about where can I get the basic starter tutorials for developing using XNA framework?

# Answer
> 16 votes
(Silly that I can only post one link as a "new user")

If you haven't already looked through it, the XNA Creator's Club has quite a bit of resources: http://creators.xna.com/en-US/education/

Also, the first result when you search Google for "xna shader tutorials" has links to some great tutorials to learn Shader programming for XNA.

First result when you search Google for "xna development site" has a few tutorials in their Tutorial tab.

Good luck! (Sorry again for the lack of links.)

# Answer
> 16 votes
I grew up with Riemers.net \- very nice tutorial site covering everything form basics (drawing Your first triangle) to advanced techniques (HLSL). In every tutorial You create a cool application, like a flight simulator for example.

# Answer
> 3 votes
And here's a long list of blogs and sites related to XNA: http://creators.xna.com/en-US/community\_resources

# Answer
> 3 votes
I have found the videos at 3D Buzz to be of very high quality.

# Answer
> 2 votes
http://sgtconker.com is a good place to start.

# Answer
> 2 votes
I really highly recommend digging through How To Make A Game (For Free In XNA) by Doolwind. Excellent read with terrific links :)

# Answer
> 1 votes
I enjoyed these high quality beginner tutorials. http://rbwhitaker.wikidot.com/xna-tutorials

# Answer
> 1 votes
I found XNA Development: Tutorials for the masses to be absolutely great. It covers basic things well - sprites, moving them, firing things, scrolling backgrounds, and comes with full source. The other material, on game states and other bits, are equally good.

The other thing I found useful, but definitely at a slightly more advanced level, is Nick Gravelyn's tutorial for Alien Aggressors. It's a full featuring Space Invaders/Galaga clone. I cannot find it, since his site's been taken down. But it was in pdf form and a great read if anyone can find.

# Answer
> 1 votes
XNA 4.0 Game Development by Example - Kurt Jaegers

# Answer
> 0 votes
I found a blog on one of Microsofts sites to be quite useful http://blogs.microsoft.co.il/blogs/pavely/

Helped me start developing a 2D game.

# Answer
> 0 votes
There’s a 2D tile-based RPG tutorial for XNA4 out there. Seems the guy always keeps it up to date, so there might also be a version for future versions of XNA.

http://xnagpa.net/xna4rpg.php

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