# Question
Title: Accelerate a Bullet on The Right Direction
I'm creating a simple asteroids 2D game with XNA so I can learn more on game development, I've started by reading this tutorial and, with my previous knowledge from developing Windows Phone applications, I've started changing the code. I've designed a simple isosceles triangle that is rotated with the accelerometer, like this:

```
private void CurrentValueChanged(MotionReading e)
{
    // Check to see if the Motion data is valid.
    if (motion.IsDataValid)
    {
        triangle.Update(MathHelper.ToDegrees(e.Attitude.Yaw));
        System.Diagnostics.Debug.WriteLine("Yaw: " + MathHelper.ToDegrees(e.Attitude.Yaw));
        System.Diagnostics.Debug.WriteLine("Angle: " + triangle.getAngle());
    }
}

```

The `triangle.Update` just changes the `batch.Draw` `rotation` parameter.

I'm also creating a "bullet", when the user clicks on the screen, using a circle texture, what I want to know is how I can point this "bullet" to the direction that the triangle sprite is heading.

*PS: The triangle "point", where the bullet should be fired, is exactly the `width / 2`.*

# Answer
That's (below) standard geometry: As you rotate the triangle from its initial position using the angle you got from user input, you can also define the shooting vector direction MC where M is the middle of the base (width/2) and C is the opposite vertex of the triangle. Rotating the triangle will automatically rotate the shooting direction.
> 1 votes

---
Tags: xna, 2d
---


# Question
Title: What data to exchange in multiplayer real time games?
I am a hobbyist programmer and right now I am curious about what data is exchanged in a multiplayer session in real time games like starcraft 2. I did a bunch of searches. I found gafferongames.com offering a very good overview of the issues to consider.

Glenn in his article and comments gives a very strong case for using UDP over TCP, but SC2 obviously uses TCP. To qoute Gleen,

> The problem with using TCP for games is that unlike web browsers, or email or most other applications, multiplayer games have a real time requirement on packet delivery. For many parts of your game, for example player input and character positions, it really doesn’t matter what happened a second ago, you only care about the most recent data.

So from his statement, I am guessing that his approach is to **send the the full game state** of every unit on each frame. If the server does not receive a player input on the current frame, then it's just back luck on that player. For God of War: Acension, in which he is lead network dev, this should work quite well I guess.

For SC2, due to it's replay capability, my gut feeling tells me that the underlying engine is a deterministic fixed timestep "user input playback machine", where the only **data exchanged is player inputs**. Hence Glenn's statement mybe completely irrelevant for SC2. Player input is important, and input sequence is even more important. I don't think it's feasible for SC2 sending game state of 200 units and more at 30 - 60 FPS.

Question: I could be wrong, but I have attempted to identify 2 possible types of data. What are other techniques? Will be good to qoute the game if you will.

EDIT: found this link about starcraft networking model

# Answer
> Glenn in his article and comments gives a very strong case for using UDP over TCP, but SC2 obviously uses TCP.

Glenn mostly talks about physics-driven games, ie. first person shooters and driving games. These have different requirements to real time strategy games where precise unit positions at every logic step are important. So the communications strategies are necessarily different.

"Real-time" means different things in different contexts. Games are not 'hard' real time in that if a message is late, the whole thing breaks. (At least, there is no good reason for a game to be so demanding, as a software-only system should be able to recover from processing delays, unlike a nuclear power station or a piece of medical equipment for example.) Games are really 'soft' or 'firm' real time. (Definitions at Wikipedia as usual.) The type of game makes a difference as to how quickly you need the information, whether you can lose information and get away with it, etc. Suffice to say that TCP is good enough for many games, but for other games, UDP is preferable.

> I am guessing that his approach is to send the the full game state of every unit on each frame.

He would send enough information to reconstruct the relevant game state of any unit that has changed.

1. You don't need to send any information about something that has not changed.
2. You don't need to send the full state if you can send enough information for the recipient to construct the new state from the old state. (eg. Just send a delta value relative to an old state. Or just send the parts of the state that have changed and not the rest.)
3. If two games run exactly the same algorithm and have exactly the same data then you can just send inputs and the recipient resimulates the effects locally to derive the new state.

Most games don't fulfil the criteria for 3, so they use 1 and 2 instead. Many RTS games however can, and do, make use of 3.

Also, it doesn't necessarily have to be "every frame". The concept of a frame is also nebulous. Is it a frame of rendering? Is it a batch of logic? Is it a frame of network data being sent? Do the three always align one-to-one or do you get variable graphics rate with fixed logic rates? Some games, especially real time strategy games like Starcraft 2, or games with replay ability (as you touch upon) like to keep everything in perfect lockstep by having regular network updates (which may or may not match 'frames' in other senses) but this is not a requirement for all games. Many games just send out updates on a semi-regular basis, depending on how far behind they're willing to let the clients run.

> Player input is important, and input sequence is even more important. I don't think it's feasible for SC2 sending game state of 200 units and more at 30 - 60 FPS.

Many games won't necessarily treat a rendering frame as a logical frame. They might have 60FPS in graphics but only have 10 logic updates a second, and send 1 network update for each one. But even 30 network updates per second is reasonable if you use the 'send input' method, certainly.

> I have attempted to identify 2 possible types of data. What are other techniques? Will be good to qoute the game if you will.

It's not so much that there are distinct techniques, but several different constraints on the systems, and the importance of each constraint will vary from game to game. So you just have to pick a system that works for you.

* Few units, moving quickly and erratically via user input, latency is sensitive, exact synchronisation across systems not important - broadcast positions via an unreliable protocol (eg. UDP) to get maximum speed, and missed messages won't matter as a new one will come in soon. Simulate physics locally to improve rendering quality but correct the positions when new information arrives. Good for shooters and driving games.
* Many units, but most are irrelevant, and they move slowly - only send updates for units near the recipient, send them as changes rather than full states, send them relatively infrequently, and send over a reliable protocol (eg. TCP) to avoid having to worry about how to handle missed updates. Good for MMOs.
* Many units, moved by the AI based on prior user input, exact synchronisation across systems very important - send time stamped user input over a reliable protocol and resimulate locally to have the game algorithms keep state synchronised. Good for RTSes and turn-based games.
> 12 votes

# Answer
The main technique you need to be aware of is the "1500 archers" technique. It was famously used by Age of Empires, but is also used in other games such as the (open source) OpenTTD (based on Transport Tycoon Deluxe).

To be clear: using this technique, you do not need to send ANY game state while playing the game. The whole game state is sent at initial startup, connect and resync. The only things you need to regularly send are time signals and synch checks. Only player-commands are normally sent from the client to the server and vice versa. If a player executes no commands (as is the case on most ticks), no data need to be sent.

See this link.

http://www.gamasutra.com/view/feature/3094/1500\_archers\_on\_a\_288\_network\_.php

Update: Kylotan calls this "technique 3" in the answer.
> 4 votes

---
Tags: multiplayer, rts
---


# Question
Title: What is the simplest way to render video into memory (for drawing to a texture) in .NET?
In my project I would like to be able to play back video on surfaces in the world. I intend to do this by having the video frames rendered to a block of memory, then use this to update a texture each frame. Everything is in place - except for the part that *actually gets the video.*

I have looked on Google and found that the video library world is very expansive (and geared towards video *processing*), and am having trouble finding a suitable one.

FFMpeg is very comprehensive, but is an entire suite and would take a good amount of work to integrate. So far the most promising library I've found is the one based on the VLC player libraries \- by virtue of it using the same resources as VLC Player it is known to be very capable; it also renders to blocks of memory, but the API (at least of the one on Github) is more of a port of the C++ API rather than a managed wrapper.

The 'solution' can be any wrapper/API/library, but with characteristics that make it suitable for use in a rendering engine, namely:

1. Renders the video frame data to memory, so it can be picked up and passed to a texture on the GPU easily.
2. Super simple - all that is needed is a way to load, jump and render a frame programatically - ideally it would use the systems codecs and not require an assortment of plugins.
3. Permissive license (LGPL or more free-er)
4. .NET bindings at least; all the better if it is natively managed

**Can anyone suggest a lightweight, (.NET) library, that can take a video file, and spit out some frames into a byte\[\]?**

# Answer
> 6 votes
*(EDIT: The library in progress mentioned at the end of this post now has a project here - https://smallmedialibrary.codeplex.com/)*

I have spent a few days looking at this and so I will share what I know (and as usual leave the Q. open for future additions).

As it turns out, doing video is *really* hard. It also turns out the only thing harder than doing video is navigating the licenses for the various libraries that *do* do video!

**FFMpeg** can play a number of roles in the solution. It is a suite but it modularised and there are different components that may be of assistance to game developers:

1. **libavcodec** is a library providing access to FFMpeg's huge array of decoders. This can be utilised directly from a library but it will not 'unwrap' the container of whatever format the video is provided in.
2. **ffdshow** is a DirectShow filter that can be installed independently of any solution and will be utilised by DirectShow to decode a range of types - i.e. you could I believe create a DirectShow library, install ffdshow and have the ability to decode all FFMpeg supported formats automatically, without needing to interact with FFMpeg directly.
3. GStreamer also has an FFMpeg plugin, which brings me to...

**GStreamer** \- this is an open source multimedia toolkit. It is a framework making use of graphs of filters and plugins, similar to DirectShow but from what I understand cleaner and simpler, which can only be a good thing! Unfortunately there isn't a repository of Windows binaries and building it will require MingW or the like.
That said, there are .NET bindings, which look very promising! What is not clear though is the extent of dependencies for solutions making use of GStreamer.

**LibVLC** has a number of .NET wrappers and none are really much help except for http://www.helyar.net/2009/libvlc-media-player-in-c/ \- which is not a wrapper - but a blog bost demonstrating how easy it is to utilise libvlc via PInvoke. (Which is, truly, easier than learning to use a wrapper\*)
LibVLC consists a large number of specialsed functions that do highly specific things. It does though utilise a graph of objects, such as a player object and a media object making it nice to work with. I have read posts from people complaining about the lack of 'design' in the API and that it should be remodelled to be generic.
I started writing a library with it and found it fine and easy to work with, and the documentation helpful. It operates at a higher level than the previous technologies though and it becomes apparent that if one of the specialised functions does not do what you want you are in for a struggle; when it does however it works wonderfully and I can see it being very productive.
(\*one point about wrappers - until recently LibVLC was GPL, not LGPL and so many of the wrappers use contrary licences)

To add to the list of my incorrect assumptions, DirectShow also seems a good bet. I was put off by the Direct in **DirectShow**, as it suggested interop with DirectX was a requirement but it is not. The DX SDK is completely seperate so DirectShow libraries could be used in OpenGL games to render video in the way as suggested in the question.
DirectShow is being superceeded by the Windows Media Foundation (for Vista, 7 and up only) but I have read it is not as feature complete as DirectShow. Neither DirectShow or WMF have supported .NET bindings however there are third-party 'wrappers' for each. I say ''wrappers'' beacuse they are mostly thin layers for PInvoking the DS/WMF functions.
The official line from MS is that .NET bindings are not going to be produced because of performance concerns (neither DS or WMF was designed with a managed environment in mind)

I have decided to write my own library in C++/CLI using DirectShow.
I opted for DirectShow because there is a huge amount of material available for it (its been around for 6 years) - both in terms of documentation and codecs (and if those fail, ffdshow is a "50x encodings with one stone shot") - and using it without a wrapper means C&P examples. It also has the most permissive license of all of the above. Further its graph/filter based design means it doesn't need to be hacked to read video from a memory stream, or render to a block of memory like LibVLC - and the principles are the same as used by GStreamer for a Linux/Mac/Symbian version of the library should one be needed.

(@lzcd +1 I did look at **XNA Video Player** and it looks good but I think it uses DirectShow to draw directly to a DX9 surface, and so would be fairly inefficient if not using DX9 as it would require reading from the GPU! There is also **XNA DirectShow Player** which appears to do the same thing but still looks really nice so I will check it out esp. as they are doing pretty much what I want to, only for XNA.)

# Answer
> -1 votes
While this is a bit over the top, XNA does have built in video playback. And, it will return the current frame in the form of a texture

---
Tags: .net, video
---


# Question
Title: Quaternion to axis-angle, or ripping apart a full transform matrix
My game entities currently hold a quaternion for their orientation with the ability to return either a 3X3 full rotation matrix (based on that quaternion), or a full 4X4 transform matrix. though what I have come to find is that I am not able to convert from my matricies to `DirectX` matricies directly, so my next thought would be to force the conversion by hand. which of the following methods would work best/easiest/accurate?

* take the quaternion, and break it down into the individual axis-aligned rotations
* take either the full rotation matrix, or the full transform matrix and break it down

for either approach it would need to yield the component rotations (theta about X, phi about Y, rho about Z).

I have a feeling that breaking the quaternion down might be the easier rout, but I am not sure as to the actual operations to do this break down.

# Answer
> which of the following methods would work best/easiest/accurate?

The first step in the most efficient angle/axis-\>matrix transform is converting the angle/axis matrix into a quaternion. So if you already have a quaternion, there's no point in turning it into angle/axis, only to give it to someone else who's going to turn it *back* into a quaternion to make it into a matrix.

The D3DXMATRIX class has several constructors, one of which takes an array of floats. If your array and D3D's array order their components the same way, then you can just use that. If not, then you can use it *anyway* and simply transpose the matrix afterwards.
> 2 votes

---
Tags: directx, rotation, quaternion
---


title: handling buffers in OpenGL

text:
# Question
Title: handling buffers in OpenGL
I'm reading through the OpenGL documentation for version 3.3 core. I'm having issues understanding proper buffer deletion.

At the moment I have an object that loads itself into OpenGL memory in the constructor and only exposes a VAO with the attribute pointers and a bound element array ready for rendering. When it stops existing it deletes all the buffers and sets pointers to NULL.

How do I properly delete OpenGL data? I'm going to assume that the object doesn't stop existing while it's being rendered. Do I have to do something more than just delete the VAO and then delete the buffer objects? Does that leave anything out? Should I bind the VAO disable the attributes, unbind it and then delete it?

# Answer
> 2 votes
In general, deleting an object in OpenGL involves nothing more than calling one of the `glDelete*` functions, where `*` is the type of object. OpenGL is smart enough to not break or otherwise implode when told to delete an object that may still be used by the renderer.

If you delete an object that is still attached to another object (a buffer object in a VAO or a texture attached to an FBO), then the *actual* deletion is deferred until all attachments are broken or the objects attached to them are themselves deleted. So if you delete a buffer object that a VAO uses, that VAO *will still work*, preserving the lifetime of the buffer object until it's no longer using it.

So ultimately, you don't have to care.

---
Tags: opengl, graphics, graphics-programming
---


# Question
Title: Steps to take before trying to implement screen space ambient occlusion
I very recently started learning modern OpenGL. I have implemented a wavefront file loader and a basic ADS shading model. At some point I'd like to implement screen space ambient occlusion. I tried reading on the technique and I understand the concept, but I have trouble understanding the details (i.e. extracting the depth information and reconstructing the positions in space etc.).

Thus the question is, what techniques should I learn/practice before trying to implement the SSAO?

# Answer
Deferred rendering. 90% of what you need to implement SSAO is found in basic deferred rendering algorithms. That's one reason why SSAO is often used by deferred renderers; it's a natural fit.
> 2 votes

---
Tags: opengl, glsl, lighting, ssao
---


# Question
Title: How do I implement parallax scrolling in 2D?
Suppose I have three layers: a foreground, an intermediate-ground and a background. What is involved in using these three layers to create parallax scrolling?

# Answer
Divide the position of each layer by the “distance” you want it to have from the camera.

For example: Create a couple of variables to represent the camera position, `cameraX` and `cameraY`. Set these to equal the position of your character, possibly adding on a bit extra in the direction of movement.

The main layer would just be positioned at

```
mainLayer.x = -cameraX;

```

the middle layer at something like

```
middleLayer.x = -cameraX * 0.5;

```

and the far layer at

```
farLayer.x = -cameraX * 0.2;

```

Change the constants as needed.
> 20 votes

# Answer
Basically you want objects to move faster, the closer they are to the 'camera'. How you implement that is up to you.

I assign each of my layers a depth, and then as I scroll the scene, for each layer I divide that scroll by the depth of the layer, so that layers that are further away move slower.
> 7 votes

# Answer
A layer that's "further back" would need to scroll at a fraction of the speed of the foreground layer. Half the speed implies double the distance. Other effects like tinting to simulate fog, etc, might also add to the illusion.
> 5 votes

# Answer
The best way to do this is to simply render sprites as billboarded quads in 3D. The "gameplay" can happen all on one plane, while the background and foreground can be positioned closer or further in 3d space. That way, the parallax effect is handled for you without you having to do any special coding :-)
> 1 votes

# Answer
Make the bottom layer scroll by subtracting from its position, draw the middle layer as normal, and make the top layer scroll at the speed of the bottom layer divided by two.
> 0 votes

---
Tags: 2d, parallax-scrolling
---


# Question
Title: Where in code to for collision? In object class? Mainline code?
Making a simple game in Love 2D framework where if I click on an object then it disappears.

Do I check to see if I've clicked the enemy inside a function in the enemy object? Or just in my main.lua? Currently I have this code in my main.lua:

```
function love.mousepressed(x, y, button)
   if button == "l" then
      for i,b in ipairs(bugs) do
         if b:isClicked(x, y) then
            table.remove(bugs, i)
         end
      end
   end
end

```

Is there a standard design pattern on where this code should belong?

# Answer
What I do is make each entity handle its own collisions in its update function. This may or may not be practical depending on your project...But for me, it works and makes it easier to manage collisions when there's multiple instances of an object.
> 1 votes

---
Tags: collision-detection, design-patterns, lua, love2d
---


# Question
Title: match-3, 4, 5, 6? Algorithm for a puzzle match game that will change the number of matches required
I was wondering if someone had an idea or had some thoughts behind creating a match-3, match-4, match-5... all the way to match-10 just by changing a variable.

I think it is easy to do a match 3 or 4, but with higher matches, it becomes difficult and a new algorithm is needed. Does anyone have an idea on how this would be implemented?

I'm totally stuck. Thanks!

# Answer
Just keep it as a variable, i.e. `numToMatch = 3`. In your algorithm, refer to this variable exclusively when you're trying to determine if there's a match or not.

If you want to vary this, say from level to level, I would suggest some algorithm like breadth-first or depth-first search, where you note the amount of touching, matched tiles. If it reaches the number you want, boom, victory.
> 4 votes

---
Tags: algorithm, ai, puzzle
---


title: GLSL shader compilation

text:
# Question
Title: GLSL shader compilation
When i'm compiling a shader does it have to be complete? Can i use glCompileShader on a shader without a main() function? The OpenGL reference documentation has a nice writeup on program linking errors, but i can't find one for shader linking, so i have to ask here.

I want to have the ability to have each part of a shader in a different file. So f.e. i'll have a material calculating function and i'll have a "main" shader with the main function that'll only reference the material calculating function. Right now i have my shaderes as arrays of strings that they can read from a file, then i put together an array of string pointeres and compile that into a single shader (vertex, fragment, geometry). But if i could compile each invidividual shaders (parts of vertex shaders, instead of the whole vertex shader put together in an array of strings) and put them together when i'm linking the program, that would make the code much clearer and i could move the shader compilation code from the program managing code to the shader object itself (the one that load the string from file and exposes it).

# Answer
> 4 votes
The compilation model for OpenGL is described on the Wiki. But for your needs, I would suggest you simply use the fact that `glShaderSource` takes multiple strings. These strings effectively act as header files; the shader stitches them together and compiles them as a single unit.

The "linking" model within a shader stage is not something I would... rely on. Not because of the specification, but because it's not widely used. And that means it's more likely to have driver bugs in it. Stick to the path most commonly used and just use multiple source strings. That way, your code is more likely to *work*.

# Answer
> 1 votes
You can compile shaders without main. This makes sense since a program can only have one main per shader type (i.e. vertex, fragment...) but several shaders of the same type can be linked.

---
Tags: opengl, graphics, glsl, graphics-programming
---


# Question
Title: Can I swap out Farseer physics fixtures at runtime?
I am working on a 2D side-scroller using Farseer Physics Engine v3.3.1.

In order to create a realistic physical skeleton for the player, I am using a method similar to the one explained here (See "Texture to polygon" section).

Below is my code for creating the player body:

```
uint[] data = new uint[Source.Width * Source.Height];

mTexture.GetData(0, Source, data, 0, Source.Width * Source.Height);

Vertices textureVertices = PolygonTools.CreatePolygon(data, Source.Width, false);

Vector2 centroid = -textureVertices.GetCentroid();
textureVertices.Translate(ref centroid);

mPhysicalDrawOrigin = -centroid;

textureVertices = SimplifyTools.ReduceByDistance(textureVertices, 2.5f);

List<Vertices> list = BayazitDecomposer.ConvexPartition(textureVertices);

Vector2 vertScale = new Vector2(ConvertUnits.ToSimUnits(1)) * Scale;
foreach (Vertices vertices in list)
{
    vertices.Scale(ref vertScale);
}

mBody = BodyFactory.CreateCompoundPolygon(mWorld, list, 1f, BodyType.Dynamic);

```

The player's sprite is animated, though, so the problem arises when switching states - I.e. the player is crouching or jumping. The physical body created above only reflects one state (currently standing).

Is there a way I could somehow create a body for each sprite and swap them out later?

---

**UPDATE:**

As suggested by @Nick Wiggill, I am creating one physical body per player state (I.e. walking, standing, jumping, etc) when the player is loaded, and saving them within my class. All the bodies have `.Enabled = false;` initially, and are only enabled when the player is in the state that corresponds to that physical body. The Bodies and their corresponding states are stored in parallel lists.

Currently, my class has a function `SetState` which takes care of changing the physical body when the state is changed:

```
new protected void SetState(object nState)
{
    //If mBody == null, the player is being loaded for the first time
    if (mBody == null)
    {
        mBody = mBodies[mStates.IndexOf(nState)];
        mBody.Enabled = true;
    }
    else
    {
        //Get the body for the given state
        Body nBody = mBodies[mStates.IndexOf(nState)];
        //Disable the current body
        mBody.Enabled = false;
        //Copy the current body's attributes to the new one
        nBody.Position = mBody.Position;
        nBody.LinearVelocity = mBody.LinearVelocity;
        nBody.AngularVelocity = mBody.AngularVelocity;
        //Set the current body to the new body
        mBody = nBody;
        //Enable the new body
        nBody.Enabled = true;
    }
}

```

Currently, when the game loads, a `NullReferenceException` is thrown when calling `World.Step`: mWorld.Step(Math.Min((float)nGameTime.ElapsedGameTime.TotalSeconds, (1f / 30f)));

In the above function, `mBody` is just a variable I have to keep track of the current active body. I'm not modifying the body in any other way outside of the above function, and none of the `m*` variables are referenced or saved anywhere outside of my class. Perhaps I am swapping the bodies incorrectly?

---

**UPDATE:** Created a new question with the newer, slightly more specific issue: IndexOutOfRangeException on World.Step after enabling/disabling a Farseer physics body?

# Answer
> 1 votes
You can have more than one `b2World` (i.e. standalone Box2D simulation) in place at a given time... this is also used to implement wrap-around worlds. You could store spare bodies there. If you disable/sleep them all, it won't cost much, just a bit of memory.

The other alternative is to create the spare bodies (yech!) in a "no-fly zone", a remote part of the map that will never be traversed in normal play.

The cost per body, as you've probably guessed, is very light. You should be able to safely simulate several thousand bodies at a given time. Unless you are thinking about having huge armies of units in motion at once (which, given the area of interest around the player being limited, would be unlikely anyway after basic optimisation), I wouldn't worry about duplicating bodies too much; it all depends on your figures though.

I remember dealing with a similar issue to yours when prototyping once, and a similar solution came to mind. Can't recall if I got around to trying it, though.

# Answer
> 2 votes
It is actually really easy

```
for (int i = 0; i < origin.body.FixtureList.Count; i++)
{
     origin.body.DestroyFixture(origin.body.FixtureList[i]);
}
FixtureFactory.AttachCompoundPolygon(verticeslist, 1f, origin.body, null);

return origin.body;

```

# Answer
> 0 votes
Your sprites are drawn separate from your physics engine, so unless you need to provide proper collision detection when crouching, you shouldn't have to swap the body. Just draw the crouched texture on top of it.

If you really need to replace the body, you can consider creating all the bodies you need, and then set their position to something like Int.Min so that it doesn't draw on your screen. Then you can simply swap positions with the active body when needed.

Might be a few issues with this method, considering your body is dynamic.

The point though, is to try not to destroy/create bodies everytime your character crouches.

---
Tags: c#, animation, side-scroller, farseer-physics-engine
---


# Question
Title: C++ Namespace vs Reference passed around like crazy - Implement a quest journal
May sound funny, but that's what the question is about.

Suppose you have this situation: http://i48.tinypic.com/whl6pk.jpg

Red squares are data types. Hexagons are methods and Journal is the main issue here. Or more exactly, how the link between Game and Journal should be interpreted. Basically, a lot of game components (instantiated inside of Game) will have to gain access to the Journal functionality. The two options that I have thought of myself are the following:

Journal could be a namespace w/ 'globally' used methods and fields. Something like:

```
journal::AddEntry(someEntry);

```

OR I could make Journal a Class, just like Game, and instantiate it inside of Game, and then pass a reference to Journal to each property of Game that needs to use the journal. Something like:

```
  GameProperty *property = new GameProperty(&ourJournal);
  //...inside of property:
  Journal *referenceToJournal;

```

But then, if I'd delete referenceToJournal, the actual ourJournal object would be deleted too, right? I'm pretty sure this just complicates things by a lot, and having lots of references towards the same object is a bad habit.

I'm kind of thinking that the:

```
namespace Journal
{
//Fields and methods go here
}
...
#include "Journal.h"
Journal::method();

```

is the best way to achieve global visibility for the Journal without much stress. But it kind of hurts, since I come from a C# & XNA background where everything is object oriented. Which is the main reason I have thought of a:

```
class Game()
{
void loadcontent();
void update();
void draw();
}

```

logic.

How would you attempt to achieve given the scenario? Instantiate a Journal inside of Game and then constantly pass a reference to Journal to all the other game components (instantiated inside of Game), or just treat everything (including Game) as namespaces to provide 'global' access to all required components? I'm also thinking about classes with public static fields and methods, but that'd be just like namespaces, at least from my point of view. Here is some more supportive code, to better describe my view on things (pseudocode for the namespace idea):

```
//FILE Journal.cpp (implementation of Journal.h)
namespace Journal
{
struct JournalEntry
{
    INT QuestID;
    String Description;
};

Vector<JournalEntry> Entries;

void AddEntry(JournalEntry theEntry)
{
    Entries.Add(Entry);
}

/*
* Used at getting all text that has to be shown on the
*/
Vector<String> GetDescriptionsForEntriesWithQuestID(INT theQuestID)
{
    Vector<String> Descriptions;
    foreach (JournalEntry jEntry in Entries)
    {
        if (jEntry.QuestID == theQuestID)
        {
            Descriptions.Add(jEntry.Description);
        }
    }
    return Descriptions;
}
};

//FILE GameComponent.cpp implementation of GameComponent.h
#include "Journal.h"
void GameComponent::ShowInfo()
{
Vector<String> info = Journal::GetDescriptionsForEntriesWithQuestID(3);
//go through the collection and do stuff
}

```

Thanks!

# Answer
> 3 votes
My first instinct is that you've got a mistaken assumption hiding in the sentence 'Basically, a lot of game components (instantiated inside of Game) will have to gain access to the Journal functionality.' *Why* will a lot of game components need access to the journal? The way you've laid it out, journal entries should only be coming from your 'story manager' or equivalent; information the player learns about NPCs can come from this, information they learn about objects can come from this, etc. At worst, it feels like you should hang the journal methods off of your core Player class somewhere and be making calls along the lines of `Player->AddJournalEntry()` (which will then call to the journal class behind the scenes, of course). Regardless, the upshot is that 'lots of game components' needing access to this fairly specialized entity is a good sign of a design error somewhere else in the chain.

# Answer
> 2 votes
Well, namespace are more to organize code, and a journal seems to me better as a class. To help you out, you could use C++ references `(Journal& myJournal)` and also use the theory of "whoever creates, is the same one that deletes". That is, if your `Game` new'ed `Journal`, it should delete it too, no other object should bother about deleting it, `Game` should.

This works very well, and avoid memory leaks, since you know who should delete it, and you don't get confused about where to delete it.

And just one plus: Namespaces are just names. a static global and namespace members are just the same on compiled code.

# Answer
> 1 votes
This started as a comment on Steven Stadnicki's comment, but grew too big so I figured might as well answer it fully.

As for your question on whether to use a class or module-type thing with a namespace, I don't think it actually matters. Rid yourself of this need to constantly be object-oriented! Whether you should use a namespace or some kind of global/singleton/dependency-injected class depends on how you're using namespaces in general.

If you'd have multiple journals loaded at one time with different state, then yes it should be a class. Otherwise, it might be unnecessary. I presume that the general flow for setting up and using the journal is something like this:

```
On game startup:
  Initialize Journal (either Player.Journal = new Journal(); or Journal::Initialize()).
    This should grab memory that the journal needs to do work
  On game startup, Journal load quest data from disk for lookup by ID
  On saved-game load, Journal loads quest data for the current player
  During gameplay, Journal accepts queries and operations to lookup quest info or add quests to current player's journal
  On saved-game unload, flag all player-specific data as "dirty" or reset on the spot
  On game quit, Journal cleans itself up

```

For games where you'd only have a single Journal (ie: no multiplayer, sync or async), the namespace approach is perfectly valid so long as it fits within your scheme of namespace usage. You could also make a class with entirely static members. The differences are subtle and not worth thinking about. There's fundamentally little difference between calling `Journal* journalInstance = new Journal(); ... delete journalInstance;` and `Journal::Init(); ... Journal::DeInit();`. You're just allocating and initializing memory, manipulating it, and then freeing it.

Now for my commentary on Steven's comment. I might have misinterpreted what you were getting at, I apologize and please let me know so I can edit this to make more sense. This approach doesn't seem to be that flexible in the long run. If I'm following your logic correctly, this means that for any sort of system like this related to any system that may be a part of the player, you'd need to add a check to the list of things that happens when the player interacts with an object. Say you wanted a rock that would add something to your journal and give you a buff. That's an extra conditional in the `Interact()` function. "Do you have journal text to add? Do you have buffs to apply to the player?" Now what if you have another rock that adds a buff to the player, but also triggers a cutscene. Now you have "Do you have journal text to add? Do you have any buffs to apply to the player? Do you have a cutscene to play?" This will get out of hand.

It would make more sense to me to make `AddJournalEntryOnInteract` a behavior/component which would be in charge of calling the Journal functions. That way you could add as many sorts of components as you'd like that could respond to a player interact. If there's only ever one Journal ever, then hiding Journal functions behind the player class seems like it's adding unnecessary overhead. This would make sense in multiplayer, since each player would have their own journal, but if this is single player, that's not really necessary to do and just adds one more set of functions to your player class that don't need to be there.

The implementation could be, that in your scene data, you give this rock a list of components that respond to `Interact();`. When the rock is `Interact()`ed with, it iterates through all of its components that respond to `Interact();` and each has the opportunity to do their thing like adding content to the journal, buffing the player, triggering a cutscene, or whatever.

## EDIT

One point I forgot to mention about the Journal namespace vs class thing, is that you'll likely find it easier to create and use mock journal objects if you want to do unit testing with a mocked `Journal`.

**ANOTHER EDIT:** But then again, what's so bad about include guards?

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


# Question
Title: "Null Pointer Exception" Animating sprite in cocos2d android
I am converting this monkey jump game tutorial in android. I have done til monkey sliding right to left and left to right but I am stuck in the part of monkey walking animation. I have tried but getting the "Null Pointer Exception"

This is my code

```
CCSpriteFrame frame = CCSpriteFrameCache.spriteFrameByName("left_1.png");
walkAnimation.addFrame(frame);
CCSpriteFrame frame2 = CCSpriteFrameCache.spriteFrameByName("left_2.png");
walkAnimation.addFrame(frame2);
monkey.addAnimation(walkAnimation);
CCAnimate  wAction = CCAnimate.action(walkAnimation,true);
monkey.runAction(wAction);

```

# Answer
> 1 votes
You should learn how to read the stack trace. I suggest you read this.

---
Tags: android, cocos2d
---


# Question
Title: Scrolling and Parallax scrolling in 2D game
I'm developing a 2D side-scrolling game.I have a scrollable bitmap for background with size 2400x480.How can i scroll this bitmap?I have searched for algorithms but i can't find any solution.

I know that i can do it with following code:

```
for(int i=0;i<100;i++)
draw(bitmap,2400*i,480);

```

So it will scroll bitmap for 240000 pixels.

But i don't want to draw images which stays out of screen(with size 800x480).

How can i render scrolling tile?How can i give velocity to it?(For parallax scrolling after normal scrolling)

# Answer
> 3 votes
This is not how you should scroll your bitmap. You should override the draw method and measure the time from the last draw,with this time you will know how much pixels you have to scroll your bitmap. Imagine your CPU is super-fast, with your code, the bitmap will scroll at the speed of light!

---
Tags: 2d, android, opengl-es
---


# Question
Title: How to remotely debug a D3D9 application
I've got a D3D9 application, which works fine on my machine. But when I send it to a friend, his machine won't render any of the 3D content. I already changed the build to enable all error-code checking and they all come back clean. How can I remotely debug why his machine's rendering is broken?

# Answer
Here is something that may help.

Ask your friend to install the DirectX SDK, then launch the DirectX control panel. From there, select the debug runtime. Finally, tell your friend to launch PIX (included in the DirectX SDK, too) and record a whole frame of your program, then save the result and send it to you. You can run PIX locally in order to guide your friend around the software.

You can then replay the PIX stream on your box and you should get verbose information about what is happening.

Also, it is possible that running PIX on your own machine will tell you what your program is doing wrong.
> 3 votes

# Answer
Visual Studio does support remote debugging in the non-express editions. Instructions for setting it up are here: http://msdn.microsoft.com/en-us/library/bt727f1t.aspx

On top of that you'll need some method of seeing the screen and speaking to your friend. I'd go with using Skype with their webcam pointed at their screen.
> 1 votes

# Answer
What steps have you taken, "enable all error-code checking" means nothing to us without knowing what errors you are checking or how. What exactly happens on your friend's machine and how is it different from when you run it, where do the differences show up?

Have you tried running the exact same files on your machine, but NOT in your development environment and from a freshly create directory? You need to do this to verify that all the files needed are present in the package and in the right place before going any further.

A common problem is only running the Debug version and then shipping a Release build, have you tried running the same build type that you send to your friend? Remember that Release will not zero-out allocations and this will cause some D3D initializations to do odd things because of the junk values in the parameter structures.

Look through your code, what could cause models to not render? Are the buffers created from the models NULL and the render is simply skipped, verify that kind of logic.

Do you check D3D device caps to see if it supports features you need? Are you simply choosing the primary device, or do you have a selector to choose which device?

Add logging to a text file, track your startup sequence and important loop events.

Do you track your models loading? How do you know that your models are loaded?

Does everything else work, do you have a HUD or any kind of other rendering in your D3D window that's working just fine or is all rendering broken?

So much can be done to log what's happening and debug locally before trying to find a remote, and more difficult method.
> 0 votes

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


title: What should a game engine do?

text:
# Question
Title: What should a game engine do?
I'd like to improve my skills/try something new and I'd like to start with 3D. I have read Starting programming in 3D with C++ but I have question about engines:

* What should engine do? I know it is abstraction layer above 3D API (i.e. OpenGL or DirectX) but what should it exactly do?

# Answer
You're right in saying that a game engine is abstracting away from the low level graphics APIs, but a fully fledged game engine does a lot more.

Game engines are intended to make everything with regards to game development easier. They do each have their own unique features, but generally they provide easy abstraction layers for graphics, audio, input, scene management, collision detection, maths and general useful utilities. Some provide wrappers and plugins for physics APIs and some even have some AI support (mostly limited to FSMs, pathfinding and - the current trend - behaviour trees). A lot of them support, and pride themselves, on cross-platform functionality.

A game engine's purpose is to make it easier for the user to create a game, without having to deal with the small annoyances in creating a game from scratch or having to install a whole bunch of libraries and writing your own wrappers for them to suit your game.

There are a lot of engines out there, but beware of the difference between a graphics engine and a games engine (For example, Unity would be a games engine, whereas Ogre would be a graphics engine).

I've got two books on the subject, but they provide a good overview on the subject:

* 3D Game Engine Architecture by David H Eberly
* Game Coding Complete by Mike McShaffry

They're not too in depth as you would need several books on each component to get the depth of knowledge you'd need to create a full, professional game engine, but they explain the concepts very well, I think.

If you're starting out game dev, don't make an engine. I refer you to the following page: http://geometrian.com/programming/tutorials/write-games-not-engines/

Engines are a tricky thing to get right. If you write a load of games, you'll find you have a lot of reusable code after a while which you can use to make your own personal engine to help you out. And having a lot of (complete) games under your belt is a lot more impressive than a single engine.

Hope that helps.

Ray
> 27 votes

# Answer
Adding to Ray's answer: Engines (Game, Graphics, Audio, etc...) not only make it easier to interact with the underlying APIs, but implement functionality specific to the game, ex: Shading model, 3D sound.

Specifically for Game engines: they manage game objects, resources (Memory, threads, all the other engines), and inter-module communication. They give the game stucture, scalability, and flexibility, which is essential for any non-trivial project.
> 5 votes

# Answer
I've written a detailed tutorial on what a game engine is - specifically in the context of the iPhone and Android platforms. I've included detailed descriptions with examples of the various parts of a game engine: UI, Graphics, Sound, Physics, Particle effects. The tutorial is available here: What is a game engine? . Hope it's helpful.
> 1 votes

# Answer
Every game engine has a slightly different idea of what a game engine should do.

But because there are too many game engines already, I really recommend that you make a GAME not an ENGINE.
> 0 votes

---
Tags: software-engineering
---


title: XNA game looks laggy below 100 fps?

text:
# Question
Title: XNA game looks laggy below 100 fps?
My xna game is running at about 70-90fps and it looks laggy at this fps. I'm using fraps to record the fps and I have a 120hz monitor, over 120hz looks fine but I can't understand why it feels like it's lagging so much at high fps :/.

# Answer
I think you have some very inconsistent frame times. You can test this by printing out the frame times to a log (or similar) and measuring their jitter.

**Edit:** *If you find that a small number of frames consume substantially more time than most, this is indicative of a performance problem. If this is the case, you need to use a profiler to help you understand where this problem is and fix it.*

In general, the faster you try to draw your frames, the more your framerate can be affected by outside factors (such as the OS scheduling CPU time for other tasks, or a function in your game running unusually slow).

At 120 fps, you have 8.33 millis to have your frame drawn. As you are not hitting your 120 fps, it can be assumed that your game can't be run on that hardware at 120 fps, and that it will draw as fast as it can. This means that any extra load on the CPU will necessarily drag your framerate down. In other words, you have no built-in tolerance to fluctuations in CPU load.

I would suggest capping the framerate. If you really want to optimize around the minority of people who have the equipment to draw frames so frequently, allow them to change the max fps in your games's settings, or you can run some analysis on the framerate in your game itself to find an appropriate max.

Capping the framerate at a rate below which it can be drawn provides some "down time" for your game. This can absorb any of the fluctuations mentioned above without affecting your framerate. If you cap it at 60 fps, you have 16.66 millis to draw your frame. If you can draw the frame in 12, you have almost 5 millis for other things to happen without anyone noticing.

If it were me, I'd set it at 60 and be done with it.
> 9 votes

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


# Question
Title: How can I implement temporary effects in Objective-C?
How could I use this IBAction

```
-(IBAction)shield:(id)sender{
    appDelegate.healthInt = 150;
}

```

and simply make it work for a limited time. I want to set `appDelegate.healthint = 150` for about 20 seconds. I'd assume this works with some sort of `NSTimer`. Not really sure. I'm not using any frameworks.

# Answer
You could do this by first setting the health value to 150 and then setting up a timer to restore that value after the desired amount of time, but that will not scale well, particularly once you have scenarios where other subsystems can be affecting (directly or indirectly) that value.

The more typical approach to this problem is to create an object represent the modifier or buff that is applied to some target. Part of that object's data is the remaining duration of the modifier. You maintain a list of these active modifiers somewhere that makes sense within the context of the rest of your game logic.

When you need to know the health (for example) of a character, you call that character's "get health" method, which in turn looks at all the active buffs that might modify health and applies them to the baseline health of the character before returning the value.

Then, since your game logic should ideally be functioning off of elapsed time between successive updates (as opposed to assuming every frame will last exactly the same amount of time), you go through each of these active modifiers every game logic update and decrease the time remaining on the modifier by the elapsed time since the last update.

If during that process, a modifiers remaining time reaches or falls below zero, you destroy that buff, which should in turn prevent that buff from being involved in the computation of whatever attributes or values it modified during the next game logic update.
> 1 votes

---
Tags: iphone, objective-c
---


# Question
Title: What AI scheme is appropriate for a 4 player, Tic-Tac-Toe style game?
I am about to release an android game that is like tic tac toe, but on a bigger board, and 4 player. Instead of winning when you get 3 in a row, you get points for chains, and the most points at the end wins.

I'm going to have a later release that will include AI, but I'm quite new to this. Would minimax be a good choice, but does it work in 4 player? I'm worried that because there are around 90 possible moves for each turn then this would get slow too slow for large enough searches.

Any suggestions?

# Answer
If you don't have any idea how one can win the game, you can go with minmax. But there are too many other complicated algorithms you can implement. Here is an small list:

* If you do have an idea about what would result in a player win a game, you can directly implement that idea. This will result in human like behavior, while giving other players a chance to win.
* As you said you can go with a min-max tree, but you can also use branch and bounding to reduce searching area. As you said having 90 possible moves is a little bit to high!
* You also can use sampling and for every move approximate an score you might get. To explain it more you pick a valid move, and for that valid move predict what the board might look like after 10 or 20 random moves. Use those data to estimate how good that move is relative to other moves.
* Also you can use an scoring system giving score to each valid board state. Those scores doesn't need to be precise, or exactly the score AI will get if he plays that way but they're only an approximation of how much score AI will gain until the game finishes. and use a greedy algorithm to always do the best move possible now.

You can also combine those algorithms, for example for late game that number of valid move are very limited you can go for a simple min-max tree. But for the early game scenarios you might want to implement faster algorithm like sampling or scoring. you also can provide sampling mechanism by better searching method, such as picking moves with higher heuristic values each turn instead of some random moves.
> 1 votes

# Answer
No hard game theory exist for interactive games with more that 2 sides. Some multi-side games still allow a fair amount of skill, but there is no well defined optimal play.

Anything Gomoku-like however completely fall apart, since players tend to always pick on the strongest opponent there is no advantage of getting ahead.

Min-max simply ain't defined for such games since there is no way of telling how the opponents will prioritize.
> 1 votes

# Answer
The problem using minmax in your circumstances is that you're unlikely to get enough depth to make a significant improvement over a simple static evaluator - consider that a 5 ply search is necessary to see your position after all oppenent's responses.

A UCT search might work very well.
> 1 votes

---
Tags: ai
---


# Question
Title: Is it possible to combine Blender with PHP?
I want to build a web game with Blender and I know PHP. Is it possible to mesh Blender with PHP?

# Answer
> 2 votes
The short answer is: *not really*. Blender can be used directly to implement game logic. Also internally Blender can be scripted using Python.

As @Byte56 mentions you could create graphics in Blender and then export them.

But, as @Bane and @stephelton mention, you appear to have some holes in your knowledge of game development, and possibly development generally.

I would recommend you take a look at How do I make games? A Path to Game Development and even some other questions here or on related SE's like:

# Answer
> 1 votes
Of course it is possible. You can use urllib and open a http connection from the python, get data from PHP and visualize in Blender. You can even do this online using Burster Burster website.

The second possibility, depending on what you realy want to do. If you want in example to do some modification of camera using the web, and you want to get a rendered image from Blender over the Web you can implement very simple WWW server in Python in Blender (example here: making a simple web server in python).

So, if you can describe your task in more details, i would be able to answer with examples of how to do this .

# Answer
> 0 votes
If you know PHP you also know that PHP is a server-side scripting language which in turn needs another language (html, html5 for instance) to display something.

So if we consider your question as: "*Is it possible to combine Blender with html/html5?*", then the answer is **yes you somehow can do it.**.

For example, you can load a model exported from Blender using WebGL which is a JavaScript API for rendering interactive 3D graphics within any compatible web browser without the use of plug-ins. It is based on OpenGL ES 2.0 and provides an API for 3D graphics. It uses the HTML5 canvas element and is accessed using Document Object Model interfaces. You can even use shaders...

Another solution to "combine" Blender with you browser content, is to simply export images from Blender and use then with html...

Next, you can use 3D plug-ins such as UNITY but it's already far from your "PHP" question ;)

---
Tags: 3d, blender, php
---


# Question
Title: How to move an UIView along a curved CGPath according to user dragging the view
I'm trying to build a interface that the user can move his finger around the screen an a list of images moves along a path. The idea is that the images center nevers leaves de path.

Most of the things I found was about how to animate using CGPath and not about actually using the path as the track to a user movement.

I need to objects to be tracked on the path even if the user isn't moving his fingers over the path.

For example (image bellow), if the object is at the beginning of the path and the user touches anywhere on the screen and moves his fingers from left to right I need that the object moves from left to right but following the path, that is, going up as it goes to the right towards the path's end.

This is the path I've draw, imagine that I'll have a view (any image) that the user can touch and drag it along the path, there's no need to move the finger exactly over the path. If the user move from left to right the image should move from left to right but going up if need following the path.

This is how I'm creating the path:

```
   CGPoint endPointUp = CGPointMake(315, 124);
    CGPoint endPointDown = CGPointMake(0, 403);
    CGPoint controlPoint1 = CGPointMake(133, 187);
    CGPoint controlPoint2 = CGPointMake(174, 318);

    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, endPointUp.x, endPointUp.y);
    CGPathAddCurveToPoint(path, NULL, controlPoint1.x, controlPoint1.y, controlPoint2.x, controlPoint2.y, endPointDown.x, endPointDown.y);

```

Any idead how can I achieve this?

# Answer
> 1 votes
Try using the CAKeyframeAnimation class.

Also see this question: CGPath Animation

However, based on your description, wanting an animation seems like it might not be what you want. IF the user is going to have 'live' control on the left/right slide being the location of the subview on the path, you might want to simply calculate the x/y of the path programatically, and apply the x/y values based only on the user's touches x value.

So, try using the NSBezierPath class to create your paths, then flatten them by calling bezierPathByFlatteningPath, finally, upon a touch that you want to update the view with, walk through the flattened path by looking at each 'elementAtIndex:associatedPoints' until you find the first one greater than your X value. The X/Y of that point will be the point you want to place your object.

---
Tags: iphone, movement, ios
---


# Question
Title: How can I convert a 2D bitmap (Used for terrain) to a 2D polygon mesh for collision?
So I'm making an artillery type game, sort of similar to Worms with all the usual stuff like destructible terrain etc... and while I could use per-pixel collision that doesn't give me collision normals or anything like that. Converting it all to a mesh would also mean I could use an existing physics library, which would be better than anything I can make by myself.

I've seen people mention doing this by using Marching Squares to get contours in the bitmap, but I can't find anything which mentions how to turn these into a mesh (Unless it refers to a 3D mesh with contour lines defining different heights, which is NOT what I want). At the moment I can get a basic Marching Squares contour which looks something like this (Where the grid-like lines in the background would be the Marching Squares 'cells'):

That needs to be interpolated to get a smoother, more accurate result but that's the general idea. I had a couple ideas for how to turn this into a mesh, but many of them wouldn't work in certain cases, and the one which I thought would work perfectly has turned out to be very slow and I've not even finished it yet! Ideally I'd like whatever I end up using to be fast enough to do every frame for cases such as rapidly-firing weapons, or digging tools.

I'm thinking there must be some kind of existing algorithm/technique for turning something like this into a mesh, but I can't seem to find anything. I've looked at some things like Delaunay Triangulation, but as far as I can tell that won't correctly handle concave shapes like the above example, and also wouldn't account for holes within the terrain.

I'll go through the technique I came up with for comparison and I guess I'll see if anyone has a better idea. First of all interpolate the Marching Squares contour lines, creating vertices from the line ends, and *getting vertices where lines cross cell edges* (Important). Then, for each cell containing vertices create polygons by using 2 vertices, and a cell corner as the 3rd vertex (Probably the closest corner).

Do this for each cell and I think you should have a mesh which accurately represents the original bitmap (Though there will only be polygons at the edges of the bitmap, and large filled in areas in between will be empty). The only problem with this is that it involves lopping through every pixel once for the initial Marching Squares, then looping through every cell (image height + 1 x image width + 1) at least twice, which ends up being really slow for any decently sized image...

# Answer
I haven't worked with 2D physics engines before, I'm not sure exactly how the collision mesh is supposed to look.

If it's simply a set of 2D triangles, then you should look into triangulation methods. For example, constrained Delauney triangulation.

> Delaunay triangulations maximize the minimum angle of all the angles of the triangles in the triangulation; they tend to avoid skinny triangles.

Which is a good thing when it comes to rendering these triangles at least, and may or may not be good for collision detection as well.

A constrained Delauny triangulation incorporates fixed edges, which would be your detected edges. This library may provide what you need
> 2 votes

---
Tags: collision-detection, physics, terrain, image, dynamic-mesh
---


# Question
Title: Procedural mesh generation from raytracer
I'm interested in applying the following technique:

* Define game objects using a object definition DSL similar to what you would use for a raytracer (e.g. POVRay)
* Use a specialised raytracer to sample the shape of the object as a mesh and render a texture/normal map for the object
* Subsequently use the generated mesh / textures in a 3D game engine as usual

It seems like this technique would be a good way of developing a lot of high quality meshes fairly efficiently, assuming a resoanably expressive object definition DSL.

Has this technique been effectively used anywhere?

# Answer
> 1 votes
What you are looking for might be Marching Cubes to generate the geometry, and that method can be very useful for sampling parametric volumes. The problem is that you might need a very large resolution sampling grid to achieve sufficient surface quality, and you may need to optimize the mesh afterwards regardless to minimize irregularities, see for example.

You could have a look at vector field displacement:

But without more details about what it is you want to procedurally generate, I don't really know if this would be useful to you or not.

---
Tags: 3d, procedural-generation, 3d-meshes, raytracing
---


# Question
Title: How to calculate the viewing cone radius at a distance in raymarching?
I'm "raymarching distance fields" (proper lingo: sphere-tracing) in GLSL. To implement cone-marching atop of it (and also to minimize the number of raymarching steps regardless of whether cone-marching is added or not), I need to estimate the radius of the ray cone at any given distance.

Recall with raymarching distance fields, a "hit" is recorded when the distance to an object is smaller than a threshold value, often in code named nearLimit or epsilon. This threshold can be seen as equivalent to the ray-cone radius if we increase it exponentially with distance traveled -- this way, we don't shoot straight thin ray lines into space but cones expanding in accordance with perspective projection. This more accurately covers catching the "right" distant objects (at this point let's ignore the issue of blending materials and filtering normals of *all* intersected objects in the viewing cone at distance t for now...).

At step 0, this radius can be approximated by something such as

```
float fInitialRadius = 1 / min(screenwidth, screenheight);

```

This can then be increased at each step exponentially by applying the starting radius to the distance:

```
fNearLimit = fTotalDist * fInitialRadius;  // after each raymarching step

```

This works OK but still has artifacts. If I use fInitialRadius\*fInitialRadius (resulting in a smaller number since initial radius for a 640px framebuffer and a unit-width view-plane is 1/640) I get less artifacts and a more accurate result. But both approaches are inaccurate, the first is too eager (increases radius too much too early), the latter too lazy (increases radius too little too late).

The most accurate factor to increase fNearLimit / the cone radius at a given distance must most likely take into account my current field of view and will vary depending on whether field-of-view is 45° or 60° or 90° or...

**TL;DR**: I want to know **what's the proper calculation or most acceptable approximation of the cone radius at a given distance** given the initial pixel radius at step 0 and the field of view angle?

# Answer
If I understand your question correctly, the calculation you're trying to do is very similar to the standard projection or primary-ray generation calculations. Here's a rough diagram that illustrates the solution.
> 2 votes

---
Tags: glsl, raycasting, antialiasing, raytracing, signed-distance-field
---


# Question
Title: What is the technical term for animation of a dead body?
In some 3D games when a 3D model of a person is shot to death (or suddenly dead) his body falls to the ground and every limb, the head and the body move free.
What is this particular way of handling dead bodies called?
Is it possible with UDK?

If you didn't understand, I meant like in this video: see how the corpse falls.

# Answer
> 14 votes
It's called Ragdoll physics. However, I have no idea if it's possible to use it with UDK

# Answer
> 2 votes
Yes, UDK can do ragdoll physics. You have to use the PhAT (Wiki Doc and Video Tut) to create a ragdoll for your mesh.

You can look at UTPawn.uc for how to link the PhysicsAsset into the mesh, and then you can look at PlayDying() or PlayFeignDeath() to see how to turn the ragdoll on.

---
Tags: animation, udk
---


# Question
Title: What should I do to prevent my monsters from walking off platforms?
I have a question that is driving me crazy because I think it should be fairly easy to find a tutorial on it. I'm currently using XNA and Farseer to create a simple platformer game. I'm about to be done with it but I want my monsters to be smarter. In this case that means that I don't want my monsters to fall off cliffs.

To put it simply, I want something that checks the area in front of my "monster" in order to determine when the monster should change direction. Could you guys point me in the right direction?

What am I supposed to use, there should exist a simple solution or simple algorithm to check this, no?

# Answer
I've never worked with XNA before and i think it will appear better solutions then mine. But a workaround that might work is that you could put a invisible object on the extremes of the cliffs and the monster could check for collision with those object. If it collides, then changes direction.
> 17 votes

# Answer
One naive way of implementing it is by using raycasting.

Calculate where your monster will be in some small chunk of time (probably a frame). From that position (or if you want to be more robust, that position +/- the bounding area of your enemy) do a raycast down. If it doesn't hit something within an appropriate range (depending on where you start your raycast vertically, the height of the character, your desired "step size", etc) you can figure that there's a cliff where the character wants to be, and decide to change directions appropriately.
> 7 votes

# Answer
With my AI, I simply check if there's a platform below and int the direction of its travel (not using a tilesystem, just a groovy collision system). If there is not- or if it hits a solid block, it gets a confused look and turns around.

This way you can have dynamic maps and still have a working(term used loosely) AI.
> 1 votes

# Answer
I suspect you are using a tile map, in which case on of the solution would be to do it based on tile indices. You need to find on what tile your monster currently is on, with the following formulas:

```
int tileX = (int)(monster.Position.X / TILE_WIDTH);
int tileY = (int(monster.Position.Y / TILE_HEIGHT);

```

Once you know these, you have to find in which X direction you're going (in order to check for blocks ahead):

```
int direction = 0;
if (monster.Velocity > 0f)
    direction = 1;
if (monster.Velocity < 0f)
    direction = -1;

```

Now you have a normalized X direction to work with.

Next, you'll want to check the blocks around to see if you should change direction:

```
if (GetTileCollision(tileX + direction, tileY) == TileCollision.Impassable || // going into a wall
    GetTileCollision(tileX + direction, tileY) == TIleCollision.Passable &&
    GetTileCollision(tileX + direction, tileY + 1) == TileCollision.Passable)) // we're going to fall down a block
    ChangeDirection(); // we change direction

```

You get the general idea. Make sure that you return `TileCollision.Impassable` (or whatever) if the tile indices are outside the map, to prevent your program from crashing with an invalid index, and it also prevents monsters from going outside of the map.

I guess it really depends on the way you handle tiles but this is the solution that worked for me.

*Based on the tutorials off http://www.sgtconker.com/ (although the website is down as I write this)*
> 0 votes

# Answer
Set a box on the outside of the platform that is on a separate layer, and have the monsters check for that, so they won't fall off but the player still can.
> 0 votes

---
Tags: xna, farseer-physics-engine
---


title: HLSL weird matrix behaviour

text:
# Question
Title: HLSL weird matrix behaviour
I have some problems using an int 3x3 matrix as the convolution filter to do edge detection. (I know int matrices are not very meaningful since there is only float on the gpu)

Here is the code:

```
   float2 stepSizeX = (1.0/512.0,  0.0);
   float2 stepSizeY = (0.0, 1.0/512.0);

   for(int y = -1; y <= 1; y++)
   {
      for(int x = -1; x <= 1; x++)
      {
        float4 c = tex2D(origSampler, TexCoord + stepSizeX * x + stepSizeY * y);
        endColorX.rgb += c.rgb * theMatrix[x+1][y+1];
      }
   }

```

The matrix is set to:

```
-1 -2 -1
0 0 0
1 2 1

```

..in the application, but it seems the values in the HLSL shader are different, though I can't figure out how and why?

# Answer
> 2 votes
Check this line

```
        float4 c = tex2D(origSampler, TexCoord + stepSizeX * x + stepSizeY * y);

```

I think you're adding to a float2 a scalar.. shouldn't it be:

```
         float4 c = tex2D(origSampler, TexCoord + float2(stepSizeX * x , stepSizeY * y));

```

---
Tags: directx, hlsl
---


# Question
Title: Human-readable text file format for game parameters
Basically what I want to do is put a lot of different parameters in a text file I edit by-hand, to avoid recompiling. I'm using Ogre3D, so I'm using configfile, but it gets messed up, and I'm looking for something with more features.

I've tried YAML-CPP, but it seems to be a pain to use, I had a very hard time figuring out how to make a difference between a pair and a mapping.

XML is a no-no, it's not human readable.

My program only reads the file, and I always edit it by hand.

Any C-like format ?

# Answer
> 1 votes
I use a simple format for many programs, where each line consists of a key,value pair. It's easy for both humans and programs to parse.

```
#
# this is a comment line
#
keyname,this is the value of the key "keyname"
key2,this is a multi line key called "key2"
,this is the continuation of the previous line

```

---
Tags: file-format, configuration
---


# Question
Title: Which app markets should I deploy my Android game to?
I just launched my Android game today. I'm curious to know where I can deploy it. Of course, Google Play is the veritable king of markets, and my own game site will be next.

After that, which marketplaces are mature and are worth deploying to?

I looked at:

And some other ones that I didn't use:

* YAAM (kept crashing and erroring out)
* 1Mobile (couldn't figure out how to upload my app)
* Insyde Market

My question is really, which ones are out there and are worth uploading too? (And 1Mobile seems good, but just can't figure out how to upload.)

Each site requires their own size screenshots and logo, so it's a bunch of extra work. I'd rather stick to the 80/20 rule and apply 20% effort to hit 80% of the markets.

# Answer
> 2 votes
The Amazon Appstore for Android would be my first thought after Google Play. I guess that I don't see the harm in adding your game to every app store that will accept it. Is the extra work of making some more screenshots that bad?

I can't imagine that the different markets require such a big difference that you couldn't take some screenshots at high res, and then write a script to resize them for each market you want to update?

---
Tags: android, appstore
---


# Question
Title: How to detect whether or not a tile is occupied?
I'm using Python 2.7 on Win7x64 with PyGame

What is the best way to iterate over all the tiles in the game or screen, efficienty? Ideally I have about 800 tiles, but that is a dynamic number I've been playing around with.

The way I've got it is the logic is looking through all the tiles per frame (at 60fps, and I haven't yet got GFX and Logic decoupled):

```
for tile in TILES: #tiles is a simple list
  if player_pos is in tile.coords: #coords is a list filled with (x, y) tuples
     tile.color = RED #a simple attribute change, performance hit whether this line is 'pass' or not

```

but the list of `TILES` is huge enough that looking through 800 tiles, 60x a second obviously isn't efficient.

What is the best way to proceed from here? How do I find the occupied tiles, without iterating over them every frame? I could split the map up into quadrants or something similar, but maybe there's a fancy concept I'm not familiar with that would work better.

**edit: Solved, for now**: I added an attribute to the Tile class that has the lowest and highest two coordinates and then every frame, the logic looks to see of the player's pos is between the two ranges like so:

```
for tile in TILEs: #pos is player pos
    if tile.range_x[0] <= pos[0] <= tile.range_x[1]: #range_x is the lowest and highest
                                       # x coordinate within the tile in pixels
        if tile.range_y[0] <= pos[1] <= tile.range_y[1]: #low and high y here
                     pos_tiles.append(tile)

```

**edit2;** I should mention that a tile holds several coordinates, meaning a unit (or player) can move within a tile.

# Answer
It would be faster to store all the tiles in a array and then simply check the tile at the players position. That would eliminate the loop (pseudo code):

```
TileDataClass[500,500] arr = mapdata
arr[playerposx,playerposy].color = red

```
> 5 votes

# Answer
If your tiles are rectangular, and if you make your tiles a 2D structure rather than a 1D structure then you can deduce the boundaries in world coordinates from the tile's position in 'tile coordinates', without needing to store any such values for each tile or iterate at all to find which tile is at a certain place.

Assuming tiles start at 0,0 in world space, the tile index for the world position (x,y) will be (x/tile width, y/tile height), rounding down.

Similarly, the world coordinate bounds of a tile at (p,q) are from (p\*tile\_width) to (p\*tile\_width+tile\_width), and (q\*tile\_height) to (p\*tile\_width+tile\_height), non-inclusive of the end-points.
> 0 votes

---
Tags: tiles, python, pygame
---


# Question
Title: Attach simple, portable 2D graphics for a c++ game
I have a game written in C++ (using STL and c++11 extensively).

I would like to do the following things:

* Attach graphics to this game -\> Think chessboard of some kind. I just need some pictures and simple status bars, no movement necessary, even though it would be nice I guess. It's a turn based game.
* Port the game across Windows / Android / iOS

So, all in all, I need a tool that would provide a portable, simple, 2D graphical interface. A tool that would allow me to "bind" my c++ code to portable graphical representation.

How would I go about making this idea come true?

# Answer
Since the customary language for ios is objective-c and android is java, you should add to your question that you need a kit that also supports C++ across those platforms.

http://www.madewithmarmalade.com/ is one, it's probably stronger than what you're looking for and it's not free... but there is a trial version.

I have not tried it personally, your mileage may vary.
> 2 votes

# Answer
No need to hook to HTML5 or native iOS/Android graphics functions when you have native OpenGL ES support on both platforms. On android binding native graphics Java functions to your C++ code would give you horrendous results.

I think your problem can be solved with a little help from a friend... I would safely bet **cocos2d-x** does what you need. It is mainly a 2D graphics engine. It's a cross platform C++ OpenGL (ES) based library.

It's a port of cocos2d which is a very successful Objective-C game framework. But don't reject it on the basis of it's framework status. You don't have to use everything.

Of course you will have to take the time to get to know the library, the features and optimizations it offers. But I believe you will find a lasting friendship with this one.

To run your C++ code on android you will have to go with the Android NDK. You will have to compile most of your game as a library and bridge calls to the native Android functions.
> 3 votes

# Answer
You've really started backwards in some respects. Even if your only goal was to add "simple" graphics for one platform, you would find yourself spending much more time on the graphics than on the underlying game implementation.

I would look at using a browser to display the pictures you need, which would be platform independent; and put your game logic on a web server. I would guess that a turn based game wants a web server in the loop anyway.
> 1 votes

# Answer
Have you considered using the Qt framework? It has the UI and simple 2D graphics capability all in one package. Works on Windows, Apple, and phones.
> 1 votes

# Answer
* Portable C++0x is not quite there yet, depending on what features you use.
* As for cross platform input, graphics, etc SDL2 is *stable enough* these days.
> 0 votes

---
Tags: graphics, porting, c++
---


# Question
Title: How to implement Ragdoll physics to 2D characters in XNA?
I'm starting a new project with XNA. I want to create a game where the main character is subject to ragdoll physics when killed. I was wondering if anyone can give me any tips on how should I implement the character class and apply these ragdoll physics before I start coding so I don't have to refactor my code later. No code is necessary, just a basic overview of an algorithm and some tips. I've found a lot of information about ragdoll physics in 3D but nothig about 2D in XNA.

# Answer
> 0 votes
*As requested I've converted my comment to an answer*

Take a look at this paper http://www.gpgstudy.com/gpgiki/GDC%202001%3A%20Advanced%20Character%20Physics by Thomas Jakobsen, the ideas in there are as valid for 2D as they are for 3D.

Nic Foster (in the comments) also makes a good point that Farseer Physics supports 2D Ragdolls (I totally forgot about that) so that would be a good 'instant' solution and you can take a peak in the source code to see how it's done.

---
Tags: xna, physics
---


title: GLSL default shaders

text:
# Question
Title: GLSL default shaders
I've been arming my engine with error checking code. I'll try to describe this situation to my best abilities. Whenever i load a shader and there's an error (file doesn't exist, compilation error, anything that could go wrong) i delete the shader and set the pointer to 0 (can't think of annother way to make sure i don't try to attach or delete trash by accident). I don't want to stop the program if this happens, because somebody might delete or modify a single file by accident in the game folder and don't want to render the whole game unusable because of that.

Now the thing is, is there a default behavior in the situation where i attach shaders to a program that have the pointer equal to 0?

In my program, if i attach a vertex shader equal 0 and a fragment shader equal 0, then OpenGL will use the default program (will display everything white):

This is a rotated cube that's dimensions are in clip space already, rendered without perspective projection or depth checking. It's loaded from an .obj file.

Now, if i attach a proper fragment shader, but the vertex shader will be 0, i get this:

Which is what i would expect, all the fragment shader does is outputs a vec4(1.0, 0.3, 0.7, 1.0), there's no vertex shader so OpenGL uses the default one (is this a correct assumption?).

Now, however, if i attach a correct vertex shader, but i attach a fragment shader equal to 0 (or i won't attach a fragment shader at all) i'll get this mess:

Something you can't see is that this model is contantly being painted different colors, so on my screen it looks like an acid trip with black horizontal lines going through.

I'm confused a bit, because i would expect the cube to just be white. I'd like to point out that my shader code is bare bones, i'm not exchanging any variables between vertex and fragment shaders. Checking if the pointer is not equal to 0 doesn't change anything, the linked program acts the same as if i gave it a pointer equal to 0. The weirdest thing to me is that it's always nicely shaded, it's not just trash.

EDIT: Maybe the default fragment shader expects a gl\_ value from the vertex that i'm ommiting to set? That would kind of explain why the surface is nicely shaded, the fragment shader expects a smooth in, but that value is just trash, because i didnt' set it.

Now is this an "undefined behavior" or is this how it's suppoused to work?

# Answer
Check section 2.11 of the OpenGL 4.2 specification:

> The executable code for an individual shader stage is taken from the current program for that stage. If there is a current program object established by UseProgram, that program is considered current for all stages. Otherwise, if there is a bound program pipeline object (see section 2.11.4), the program bound to the appropriate stage of the pipeline object is considered current. If there is no current program object or bound program pipeline object, no program is current for any stage. The current program for a stage is considered active if it contains executable code for that stage; otherwise, no program is considered active for that stage. **If there is no active program for the vertex or fragment shader stages, the results of vertex and/or fragment processing will be undeﬁned.** However, this is not an error. If there is no active program for the tessellation control, tessellation evaluation, or geometry shader stages, those stages are ignored.

This is "undefined behavior" that acts differently per implementation.

As for the solution to not being able to find a shader, I've found it's best to hardcode both a vertex and fragment shader and load them before anything else, then use it in place of any missing shaders. That way a lot of the uniforms I define (transformation matrices) will still go through and the result will look half-decent. For example, here's how I do it (C#):

```
string defaultVertShaderText =
    @"#version 120

    attribute vec4 in_vertex;

    uniform mat4 model;
    uniform mat4 view;
    uniform mat4 projection;

    void main()
    {
        gl_Position = projection * view * model * in_vertex;
    }";

string defaultFragShaderText =
    @"#version 120

    void main()
    {
        gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
    }";

```

Also hardcoding a default texture is a good idea.
> 5 votes

---
Tags: opengl, graphics, glsl, graphics-programming
---


title: XNA Camera 2D confusion

text:
# Question
Title: XNA Camera 2D confusion
I have followed the tutorial at http://www.david-amador.com/2009/10/xna-camera-2d-with-zoom-and-rotation/ to implement my 2D camera and everything works just fine. However this leaves me confused. From that implementation i see that first there is the translation applied, then rotation, then scale and then again translation to "offset" the camera.

However, in every book i read, there is one core principle to keep in mind when working with matrix translations, and that is the order of the application of transformations. And it is different: Scale, Rotation, Translate.

What am i not getting?

# Answer
**Short Answer**

SRT is the usual order for a *world* matrix. The camera uses a *view* matrix which works by taking the entire world and transforming it in the *opposite* direction from where the camera is located. Since this opperation is the opposite of a world matrix, the multiplication order needs to be reversed as well as its arguments.

**Long Answer**

The SRT order mentioned in the books is the correct order to create a transformation matrix to position an object in the world, or in other words, a *world matrix*.

Your 2D camera class on the other hand, is creating a *view matrix* which works almost in the opposite way. To be more specific, it moves the entire world in the *opposite* direction as the camera, giving the illusion that the camera is the new origin of the world.

So for instance, if you have a camera that's positioned at (50, 0) and rotated 45º to the right, the way to simulate that is to perform the *inverse* transformation on the world, i.e. translate everything in the world by (-50, 0) so that the camera becomes positioned at (0,0) and then rotate it 45º to the *left* to give the illusion that the camera is rotated to the right.

The conclusion is, since you're performing the inverse operation as a world matrix, the multiplication order needs to be reversed too.

**With Pictures**

Not sure if it helps, but I tried making a few pictures to demonstrate why order matters, and why there's a correct order (they didn't turn out too well though..).

First for world matrices. Imagine a square object located at (50,0), rotated 45 degrees to the left, and double its normal size. Since *transformations are always relative to the origin* the image below should make it clear why SRT gives the correct results, while TRS does not.

Now, as I explained earlier the view matrix works by doing the opposite of the world matrix. Look at the image below and imagine that the red square outline is the camera. The job of the view matrix is to transformeverything so that the camera is placed at the origin, while maintaining all the relative proportions and positions between the camera and the world. The example shown is the correct transformation order for a view matrix.

As you can see, TRS works in this case, and places the camera at the origin. Now if you try doing it SRT instead, while using the same parameters, the camera will end up far away from the origin which is not what we want.
> 2 votes

# Answer
After some poking around, i found an answer to a different question, that discusses various matrix operation orders and what they are used for. Though they lack explicit detail they are a good reference

Transformation order when dealing with Meshes
> 0 votes

---
Tags: xna-4.0, camera, matrix
---


# Question
Title: GL11.glTexCoord2f(1.0f, 1.0f); 1.0f screws the image up
I recently started using LWJGL in my java programs for the graphics. I'm currently working on a simple game, which I make, to get better at this kind of programming. I ran into some trouble when adding textures to my 2D game.

To show my problem, I have made a simple program which shows one quad with a texture. This is how the texture looks:

http://i1197.photobucket.com/albums/aa428/GWigWam/LWJGL%20problem/Test.png

However my program shows it like this:

http://i1197.photobucket.com/albums/aa428/GWigWam/LWJGL%20problem/showsme.png

You see the right and the bottom have some strange line hanging there. the shown picture is 100x100 from the top left to the little pixel right down.

The code used for drawing this is:

```
texture1.bind();
GL11.glBegin(GL11.GL_QUADS);
   GL11.glTexCoord2f(0f,0f);
   GL11.glVertex2f(100, 200);
   GL11.glTexCoord2f(1f,0f);
   GL11.glVertex2f(200, 200);
   GL11.glTexCoord2f(1f,1f);
   GL11.glVertex2f(200, 100);
   GL11.glTexCoord2f(0f,1f);
   GL11.glVertex2f(100, 100);
GL11.glEnd();

```

This code is called before drawing:

```
    GL11.glEnable(GL11.GL_TEXTURE_2D);
    GL11.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    GL11.glEnable(GL11.GL_BLEND);
    GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
    GL11.glOrtho(0, width, 0, height, -1, 1);

```

When I use

```
GL11.glTexCoord2f(0.9f,0.9f);

```

so 0.9f instead of 1.0f the weird lines don't appear. But that's no real solution because I want to use the whole texture not 90% of it.

I hope I did not ask something which has been asked before, I really couldn't find I using google, it is however quite hard to think of the right search words.

# Answer
> 1 votes
The problem is fixed now, the WRAP\_S wasn't the solution. It is **the size of the image** a 100x100 image shows this weird bug, but a 128x128 does not. 500x500 does not work 512x512 does.

Thanks to Nicol Bolas for trying to help, I would like to +rep, but I can't. Thanks for the support!

# Answer
> 4 votes
You should set your texture's wrap S and T modes to `GL_CLAMP_TO_EDGE`. This is done with the `glTexParameter` set of functions. Something like this:

```
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);

```

Or the LWJGL equivalent to this.

You should call this when you're creating the texture (after your call to glTexImage2D), not when you're using it.

Also, don't forget to call it with `GL_TEXTURE_WRAP_T` too.

---
Tags: java, textures, lwjgl
---


# Question
Title: Ball Physics : Bounce height altered by elasticity of ball and bounce surface
I have created a bouncing ball simulator using XNA and I am happy with my use of gravity, acceleration, change of direction and friction/spin.

However, I am now at a stage where I would like to define my ball as being made of a different material, subsequently meaning that the "bounce height" will be different depending on the elasticity of the material.

Ultimately, I will also want differing types of bounce surfaces as well. This will mean that I could have bounces as varied as:

* Rubber ball on concrete.
* Ping-pong ball on wood.
* Concrete ball on mud.
* Etc., etc.

My question is; How should I alter my bounce height depending on the material(s)?

I have found some information about Young's Modulus of Elasticity but I would be grateful if someone could advise as to how I use this (or another) value as a ratio in my "bounce" calculation.

Thanks in advance and please let me know if you would like to know anything else.

# Answer
> 3 votes
The bounce is implemented by inverting the Y component of velocity, when the ball collides with the ground.

Ball.Velocity.Y \*= -1 * COEFF;

If the COEFF is 1, the ball will have a "perfect" bounce, i.e. no energy will be lost. If COEFF is 0, the ball won't bounce at all. Put a fractional value between 0 and 1 in COEFF to get a realistic bounce.

Now you want to implement two "materials". So you could have two coefficients and calculate COEFF as follows:

COEFF = BALL\_COEFF * SURFACE\_COEFF

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


title: Is SDL too low level for a beginner?

text:
# Question
Title: Is SDL too low level for a beginner?
I am getting started in game development. I started by learning SDL because it seems before I start developing big games, I have to start with the most basic stuff, like Tetris or Snake. I was wondering if SDL is too low-level. If I start with something as low level as SDL, will that make other high level libraries easier to pick up? Like for example, when someone is good with assembler, C seems easy.

# Answer
> 7 votes
No. The C++ and SDL combination is fairly low level, but not so much so that a beginner can't make good progress with it, and you can't really get much more 'high level' than SDL unless you use a premade engine.

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


# Question
Title: How is JS source protected in Chrome games?
I was playing a space arcade shooter https://moonbreakers.com/ and tried to see some of the JS and shader code. However, I was unable to find anything but some server communication code. Game code is thus probably run on servers, but the shaders should at least be local, right? And I have understood that even if the server runs the true game state, clients commonly do some physics interpolation etc by themselves.

My only guess is that the game gets the code with jQuery and it doesn't show in the page source. Can that code be looked at via a debugger?

# Answer
> 3 votes
The game you linked is written in C/C++ (Native Client), it's embedding the executable. As for JavaScript obfuscation, look into tools like the closure compiler, etc.

# Answer
> 0 votes
Seems weird to me too. Are you user is a WebGl app? Maybe they are using NaCl (Native code inside the Chrome brownser) https://developers.google.com/native-client/

---

Old answer (before the edit) Hum, I have no experience in Chrome games, but code obfuscation seems like the way to go. Take a look at this community answer in SO:

https://stackoverflow.com/questions/194397/how-can-i-obfuscate-javascript

---
Tags: javascript, webgl
---


# Question
Title: Pixel-perfect collision against rotated sprite in Flixel
I've got a roughly 500x50 graphic of a lockpick that I need to be able to rotate very finely while doing pixel-perfect collision detection against the lock object.

There's no way to do pixel perfect collision detection in Flixel, so I'm using the Power Tools' FlxCollision class to accomplish this. The problem is that this class only works with rotated sprites if they were loaded with loadRotatedGraphic.

...the problem with that is that it only allows you to rotate to discrete angles. You pass it how many angles you need to be able to rotate to and it, I think, pre-prepares all the frames for you.

And the reason that's a problem is because I need such fine rotation. I need at least 128 different angle values, but when I do that I get `Error 2015: Invalid Bitmap`, which I'm assuming is because the resulting 128 frames of a 500x50 lockpick results in a bitmap larger than AS3's limit. I can load the graphic using loadGraphic instead, which I think just calculates the rotated image real-time, but then FlxCollision won't notice that it's been rotated. Another problem is that with the pre-rotated graphics, you can't rotate about a specific point, and I need the lockpick to rotate around the tip of its handle.

...so how the heck do I do pixel perfect collision against a rotated sprite? I'm trying to mod FlxSprite so that FlxCollision will see the rotated sprites even when they're calculated in real time, and to do this I Ctrl+F'd through the class looking for appearances of "angle", the variable that you set to rotate a sprite, but all I can find is some obscure calculation in it's used to compute a frame number, and I can't find a single call to any function that looks like it's doing real-time bitmap rotating.

---

---

So, I was able to solve this problem. All FlxSprites hold the bitmap for their currently visible frame in an internal variable called framePixels. If you load a graphic using loadGraphic, then you can do real-time rotation: in this case, the draw() function rotate s framePixels "at the last minute", right before rendering it. Meaning the rotated bitmap is not stored, and FlxCollision has no way of seeing it. FlxCollision runs its collision checks against the unrotated bitmap.

So this is what need to be done:

1. Get the sprite to store its rotated graphic somewhere rather than just sending it to the renderer and then abandoning it.
2. Get FlxCollision to use that stored rotated graphic rather than framePixels.

This is summarized in the following diagram. Flixel's default logic is in black, my changes are in red.

I applied all of this in a sub-class of FlxSprite that I called PerfectCollisionSprite.

Here's my code.

# Answer
The draw() function uses matrix rotation to rotate a non-baked FlxSprite. You can see the relevant section in the code block marked "Advanced render", line 456 of FlxSprite.as in the current version. That section already accounts for a different rotation origin, held in the "origin" variable.

What I'd do is extend the FlxSprite class. The pixels variable will hold your original lockpick image. Override the angle variable with a property that sets dirty=true each time you change the angle.

Now override calcFrame() so that the rotation happens there instead of in draw(). calcFrame() normally copies the correct frame from pixels to framePixels; instead, you're going to use something like the advanced render code from draw() to copy a rotated version of pixels to framePixels.

Of course, you also need to change draw() or apply some other fix so that it doesn't perform a second rotation in the aforementioned advanced render section.

I assume FlxCollision bases its pixel-perfect collision on framePixels, so that should make your collisions work right.
> 1 votes

---
Tags: flash, actionscript-3, flixel
---