# Question
Title: Best way to Draw a cube for 3D Picking on a specific face
Currently I am drawing a cube for a game that I am making and the cube draw method is below. My question is, what is the best way to draw a cube and to be able to easily find the face that the cursor is over? My draw method works just fine, but I am getting ready to start to add picking (this will be used to mold the cubes into other shaps), and would like to know the best way to find a face of the cube.

```
public void  Draw() {
    // center point posX, posY, posZ
    float radius = size / 2;

    //top
    glPushMatrix();
    glBegin(GL_QUADS);
        {
            glColor3f(1.0f,0.0f,0.0f); // red
            glVertex3f(posX + radius, posY + radius, posZ - radius);
            glVertex3f(posX - radius, posY + radius, posZ - radius);
            glVertex3f(posX - radius, posY + radius, posZ + radius);
            glVertex3f(posX + radius, posY + radius, posZ + radius);
        }
    glEnd();
    glPopMatrix();

    //bottom
    glPushMatrix();
    glBegin(GL_QUADS);
        {
            glColor3f(1.0f,1.0f,0.0f); // ?? color
            glVertex3f(posX + radius, posY - radius, posZ + radius);
            glVertex3f(posX - radius, posY - radius, posZ + radius);
            glVertex3f(posX - radius, posY - radius, posZ - radius);
            glVertex3f(posX + radius, posY - radius, posZ - radius);
        }
    glEnd();
    glPopMatrix();

    //right side
    glPushMatrix();
    glBegin(GL_QUADS);
        {
            glColor3f(1.0f,0.0f,1.0f); // ?? color
            glVertex3f(posX + radius, posY + radius, posZ + radius);
            glVertex3f(posX + radius, posY - radius, posZ + radius);
            glVertex3f(posX + radius, posY - radius, posZ - radius);
            glVertex3f(posX + radius, posY + radius, posZ - radius);
        }
    glEnd();
    glPopMatrix();

    //left side
    glPushMatrix();
    glBegin(GL_QUADS);
        {
            glColor3f(0.0f,1.0f,1.0f); // ?? color
            glVertex3f(posX - radius, posY + radius, posZ - radius);
            glVertex3f(posX - radius, posY - radius, posZ - radius);
            glVertex3f(posX - radius, posY - radius, posZ + radius);
            glVertex3f(posX - radius, posY + radius, posZ + radius);
        }
    glEnd();
    glPopMatrix();

    //front side
    glPushMatrix();
    glBegin(GL_QUADS);
        {
            glColor3f(0.0f,0.0f,1.0f); // blue
            glVertex3f(posX + radius, posY + radius, posZ + radius);
            glVertex3f(posX - radius, posY + radius, posZ + radius);
            glVertex3f(posX - radius, posY - radius, posZ + radius);
            glVertex3f(posX + radius, posY - radius, posZ + radius);
        }
    glEnd();
    glPopMatrix();

    //back side
    glPushMatrix();
    glBegin(GL_QUADS);
        {
            glColor3f(0.0f,1.0f,0.0f); // green
            glVertex3f(posX + radius, posY - radius, posZ - radius);
            glVertex3f(posX - radius, posY - radius, posZ - radius);
            glVertex3f(posX - radius, posY + radius, posZ - radius);
            glVertex3f(posX + radius, posY + radius, posZ - radius);
        }
    glEnd();
    glPopMatrix();
}

```

# Answer
It depends on how you implement picking. It may not matter how you draw it, because you won't be detecting a face that's been drawn already. Since it's already been sent to the graphics card, it's usually more work to get information back from the drawn image than just checking your objects directly.

If you implement picking in the way I've described here, you'll just be casting a ray and checking it against the objects in your game world to see if there's an intersection. So it will matter how you're storing your objects in your game world. For example, it's very useful if you can query your world to find objects at a specific location. If your objects were just stored in an array, you'd suffer O(N) time for determining if an object existed at a specific point.

As a side note. Just looking at your drawing code, you probably want to modernize that a bit. Direct drawing like that is very out of date. Look into VBOs.
> 3 votes

---
Tags: java, 3d, lwjgl, picking
---


title: The need to reduce mesh count

text:
# Question
Title: The need to reduce mesh count
In Panda3d, I load a model and place 10000 references to it in the scene-graph. It runs at (say) 2Hz.

I load a 3d model containing 10000 copies of that exact same object, and it runs at (say) 60Hz. As does using the flattenStrong() command which is effectively the same thing but at runtime.

So the question is: is this behaviour a peculiarity of Panda3d, or is it a fundamental law which applies to all games engines?

# Answer
> 4 votes
I believe that what you're talking about is a large number of individual draw calls to the rendering api vs a single large draw call to the rendering api.

There is CPU overhead associated with setting up the rendering state (binding vertex buffers, textures, shaders etc) as well as the actual draw call itself it is generally more efficient to render a large amount of geometry in a single call.

Note that Panda3D most likely attempts to reduce rendering api state changes such as bound texture and shaders by grouping renderables together so these need to be set the minimum number of times. But even with this optimisation if you are drawing many single objects, you must call draw in the rendering api which incurs unavoidable CPU overhead while communicating with the GPU.

The CPU-to-GPU overhead is something we want reduce as much as possible when using rendering apis such as OpenGL and DirectX. This is done in many ways but some optimisations that generally yield good results are to minimise unnecessary state changes and to batch geometry together to reduce the number of draw calls. This is what the flattenStrong command is doing for you.

To say it again, it is generally more efficient to render 1,000,000 vertices in a single draw call than it is to render 1,000 vertices in 1,000 draw calls. Therefore you could call this a fundamental law of the rendering apis which most game engines use under the hood.

# Answer
> 2 votes
It's a matter of the number of draws being performed by the GPU. There is a large amount of overhead involved in telling the CPU to tell the GPU to draw something. On the other hand, GPU's are very good at drawing a lot of stuff all at once. So, even though your model with 1000X the vertices may take a few extra microseconds to transfer into video memory, it takes the same amount of time to draw it.

The Mythbusters demonstrated an analogy for the expense of preparing for a GPU draw, versus the speed at which it draws. http://www.youtube.com/watch?NR=1&feature=endscreen&v=XtGf0HaW7x4

You are reloading the mega-paintball launcher 1000 times with your 1000 draw calls.

# Answer
> 0 votes
Seems that your slowdown is coming from the 9999 extra world-\>view transforms that are being performed, one per object.

---
Tags: graphics, 3d-meshes, panda3d
---


title: Attach my sprite with Box2d

text:
# Question
Title: Attach my sprite with Box2d
I'm coding Javascript(HTML5) with Box2D. And I want to ask how to attach Sprite with Box2D.

This is function My sprite:

```
function My_Sprite() {
    this.m_Image = new Image();
    this.m_Position = new Vector2D(0,0);
    this.m_CurFrame = 0;
    this.m_ColFrame = 0;
    this.m_Size = new Vector2D(0,0);
    this.m_Scale = new Vector2D(0,0);
    this.m_Rotation = 0;
}
My_Sprite.prototype.constructor = function (_Image_SRC) {

    this.m_Image.src = _Image_SRC;
}
My_Sprite.prototype.constructor = function (_Image_SRC,_Size,_Col) {

    this.m_Image.src = _Image_SRC;
    this.m_Size = _Size;
    this.m_ColFrame = _Col;
    this.m_Scale = new Vector2D(1, 1);
}
My_Sprite.prototype.Draw = function (context) {
    context.drawImage(this.m_Image,
        this.m_Size.X * (this.m_CurFrame % this.m_ColFrame),
        this.m_Size.Y * parseInt(this.m_CurFrame / this.m_ColFrame),
        this.m_Size.X, this.m_Size.Y,
        this.m_Position.X, this.m_Position.Y,
        this.m_Size.X * this.m_Scale.X, this.m_Size.Y * this.m_Scale.Y
        );
}

```

and this is function Object :

```
function Circle(type, angle, size) {

  //  Circle.prototype = new My_Object();
   // Circle.prototype.constructor = Circle;
   // Circle.prototype.parent = My_Object.prototype;

    this.m_den = 1.0;
    this.m_fri = 0.5;
    this.m_res = 0.2;

    fixDef.density = this.m_den;
    fixDef.friction = this.m_fri;
    fixDef.restitution = this.m_res;
    fixDef.shape = new b2PolygonShape;

    bodyDef.type = type;
    bodyDef.angle = angle;
    bodyDef.userData = m_spriteCircle;

    fixDef.shape = new b2CircleShape(
           Radius / SCALE //radius
        );
    this.m_Body = world.CreateBody(bodyDef);
    this.m_Body.CreateFixture(fixDef);

    m_spriteCircle = new My_Sprite();

    this.Init();
}
Circle.prototype.Init = function () {

    m_spriteCircle.constructor("images/circle.png", new Vector2D(80, 80), 1);
    m_spriteCircle.m_CurFrame = 0;

}

Circle.prototype.Draw = function (context) {
    m_spriteCircle.Draw(context);
}

```

and I draw it :

```
   var m_Circle = new Circle();

   m_Circle.Draw(context);

```

# Answer
The problem is the circle's position, and the position of the Box2D physics body are not the same thing.

You're going to have to either update the circle objects position to match that of the box2D body, or just exclude the position from the circle object, and always draw using the box2D's position.

If you retain a reference to the body when you create it, you can access the position using the GetPosition method:

```
var p = ph._body.GetPosition();

circle.m_Position.x = (p.x / SCALE) - (circle.size.x / 2);
circle.m_Position.y = (p.y / SCALE) - (circle.size.y / 2);

```

Keep in mind two things though:

1. You need to adjust for scale (typically a set translated scale of 0.1 works well. You have to translate whenever you get/set position from pixels to the scale you want to use in Box2D.
2. Positions in box2D are based on the center of an object, not the top left used in canvas drawing. Hence why the code above offsets the position by the size of the circle.

Hope all that helps.
> 1 votes

---
Tags: javascript, box2d
---


title: Make game for iPhone only

text:
# Question
Title: Make game for iPhone only
From the beginning of development on my game I was hoping to release it as a universal app, but the gameplay simply doesn't work as well on the iPad. Also, it was designed to work on the iPhone screen, and the (even slight) difference in width to height ratio gives iPhone users an advantage over iPad users by seeing more of the path ahead. Not to mention it doesn't look quite right on the larger screen.

Hypothetically, if my game becomes a top seller, would it be a bad idea to have it only an iPhone app? Would it make it far less likely for my app to become viral? My app would still work on the iPad like any other iPhone app, and I plan on eventually releasing an update that supports both iPad and iPhone.

# Answer
It varies game to game, regarding Game Play.

If your game's Game Play is good for both iPhone & iPad, then it is bette to create for both devices.

* For example, ROVIO's Angry Birds

If your game becomes a top seller, then obviously you have to think about "viral" (Because there are many users at iPad). Then you have to make a good R&D whether it is possible to port at iPad.

And a good R&D will suggest whether it is better to create for both iPad and iPhone or still work on the iPad like any other iPhone app. Because here several issues arises regarding Game Play, UX etc.
> 2 votes

---
Tags: iphone, ios, ipad
---


# Question
Title: Algorithm for approximating sihlouette image as polygon
> **Possible Duplicate:**
> Is there any heuristic to polygonize a closed 2D raster shape with n triangles?

I want to be able to analyze a texture in real time and approximate a polygon to represent a silhouette. Imagine a person standing in front of a green screen and I want to approximately trace around their outline and get a 2D polygon as the result. Are there algorithms to do this and are they fast enough to work frame-to-frame in a game?

(I have found algorithms to triangulate polygons, but I am having trouble knowing what to search for that describes my goal.)

# Answer
> 0 votes
Checkout the DetectVertices function here. Its pretty good I've used it quite a bit myself.

---
Tags: textures, algorithm
---


# Question
Title: How to load data for specific level at runtime?
I'm trying to create a game with many levels loaded from XML files. In my game I have many objects in each level.

At present my game contains 20 levels, and I load all the textures at once on startup. But I think the correct way to do it is to only load textures used in the current level. I don't know how to do that. So please explain this by providing some example code.

At present I create a class for each type of entity by extending my Sprite class. This subclass loads the appropriate image. I know this is not the best way to do things.

**Basically I want to know how to load large levels efficiently in Andengine. What is the proper method for loading textures, level data and background images from files when the level is run?**

# Answer
What you're looking for is a method to generate the asset dependencies of your individual levels. 'Dependencies' meaning that your levels rely on those files being loaded in order to run properly.

What I would suggest is that your run your XML files through some sort of processing prior to runtime. You can write a process that traverses an XML file and determines what textures it references, and then write the names of those textures either into the same XML file or into a separate 'dependencies file'. At runtime, when you load a level's XML, you will also need to write code to load that level's dependencies.

I can't speak directly to a method to use in Andengine, nor can I provide good example code because the solution will vary depending on how your data is organized and loaded, but this should be a good guideline to get you started.
> 2 votes

---
Tags: textures, andengine, loading, levels
---


# Question
Title: Is there a free and open source 3D engine for Android?
Is there a free and unlimited open source 3D engine for Android? Something that is a direct, thin layer to the NDK?

I have only found two engines: Unity and Shiva 3D. But no free or open source ones.

# Answer
Open Source C++ 3D Engine available for Android:

* Ogre3D: the best open source 3d engine but it is a large framework
* Irrlicht: good performance, light framework. I use it
* libgdx: Java API with NDK code
> 17 votes

# Answer
Linderdaum Engine 2D/3D open source engine in C++ for Windows and Android. All prototyping can be done on Windows. Also contains some Java code for JNI interoperation with Android SDK.
> 4 votes

# Answer
**gamekit** is completely free even if you produce commercial venture with it. You can download it free at http://code.google.com/p/gamekit/.
> 2 votes

# Answer
OpenSceneGraph. Don't know about thin, but it runs on android.
> 1 votes

# Answer
How about Min3D ?
> 1 votes

---
Tags: 3d, android, open-source
---


# Question
Title: How can unrealscript halt event handler execution after an arbitrary number of lines with no return or error?
I have created a class that extends TcpLink and is instantiated in a custom Kismet Sequence Action. It is being instantiated correctly and is making the GET HTTP request that I need it to (I have checked my access log in apache) and Apache is responding to the request with the appropriate content.

The problem I have is that I'm using the event receive mode and it appears that somehow the handler for the Opened event is halted after a specific number of lines of code have executed.

Here is my code for the Opened event:

```
event Opened()
{
    // A connection was established
    WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] event opened");
    WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] Sending simple HTTP query");

    //The HTTP GET request
    //char(13) and char(10) are carrage returns and new lines
    requesttext = "userId="$userId$"&apartmentId="$apartmentId;

    SendText("GET /"$path$"?"$requesttext$" HTTP/1.0");
    SendText(chr(13)$chr(10));
    SendText("Host: "$TargetHost);
    SendText(chr(13)$chr(10));
    SendText("Connection: Close");
    SendText(chr(13)$chr(10)$chr(13)$chr(10));

    //WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] Sent request: "$requesttext);

    //WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] end HTTP query");

    //WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] LinkState: "$LinkState);
    //WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] LinkMode: "$LinkMode);
    WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] ReceiveMode: "$ReceiveMode);
    WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] Error: "$string(GetLastError()));
}

```

As you can see, a number of the Broadcast calls have been commented out. Initially, only the lines up to the Broadcast containing "\[DNomad\_TcpLinkClient\] Sent request: " were being executed and none of the Broadcasts were commented out. After commenting out that line, the next Broadcast was successful and so on and so forth.

As a test, I commented out the very first Broadcast to see if the connection closing had any effect:

```
    // A connection was established
    //WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] event opened");
    WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] Sending simple HTTP query");

```

Upon doing that, an additional Broadcast at the end of the function executed. Thus the inference that there is an upper limit to the number of lines executed.

Additionally, my ReceivedText handler is never called, despite Apache returning the correct HTTP 200 response with a body.

My working hypothesis is that somehow after the Sequence Action finishes executing the garbage collector cleans up the TcpLinkClient instance. My biggest source of confusion with that is how on earth it does it during the execution of an event handler.

Has anyone ever seen anything like this before? My full TcpLinkClient class is below:

```
/*
 * TcpLinkClient based on an example usage of the TcpLink class by Michiel 'elmuerte' Hendriks for Epic Games, Inc.
 *
 */

class DNomad_TcpLinkClient extends TcpLink;

var PlayerController PC;
var string TargetHost;
var int TargetPort;
var string path;
var string requesttext;
var string userId;
var string apartmentId;
var string statusCode;
var string responseData;

event PostBeginPlay()
{
    super.PostBeginPlay();
}

function DoTcpLinkRequest(string uid, string id) //removes having to send a host
{
    userId = uid;
    apartmentId = id;
    Resolve(targethost);
}

function string GetStatus() {
    return statusCode;
}

event Resolved( IpAddr Addr )
{
    // The hostname was resolved succefully
    WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] "$TargetHost$" resolved to "$ IpAddrToString(Addr));

    // Make sure the correct remote port is set, resolving doesn't set
    // the port value of the IpAddr structure
    Addr.Port = TargetPort;

    //dont comment out this log because it rungs the function bindport
    WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] Bound to port: "$ BindPort() );
    if (!Open(Addr))
    {
        WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] Open failed");
    }
}

event ResolveFailed()
{
    WorldInfo.Game.Broadcast(self, "[TcpLinkClient] Unable to resolve "$TargetHost);
    // You could retry resolving here if you have an alternative
    // remote host.

    //send failed message to scaleform UI
    //JunHud(JunPlayerController(PC).myHUD).JunMovie.CallSetHTML("Failed");
}

event Opened()
{
    // A connection was established
    //WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] event opened");
    WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] Sending simple HTTP query");

    //The HTTP GET request
    //char(13) and char(10) are carrage returns and new lines
    requesttext = "userId="$userId$"&apartmentId="$apartmentId;

    SendText("GET /"$path$"?"$requesttext$" HTTP/1.0");
    SendText(chr(13)$chr(10));
    SendText("Host: "$TargetHost);
    SendText(chr(13)$chr(10));
    SendText("Connection: Close");
    SendText(chr(13)$chr(10)$chr(13)$chr(10));

    //WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] Sent request: "$requesttext);

    //WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] end HTTP query");

    //WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] LinkState: "$LinkState);
    //WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] LinkMode: "$LinkMode);
    WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] ReceiveMode: "$ReceiveMode);
    WorldInfo.Game.Broadcast(self, "[DNomad_TcpLinkClient] Error: "$string(GetLastError()));
}

event Closed()
{
    // In this case the remote client should have automatically closed
    // the connection, because we requested it in the HTTP request.

    WorldInfo.Game.Broadcast(self, "Connection closed.");

    // After the connection was closed we could establish a new
    // connection using the same TcpLink instance.
}

event ReceivedText( string Text )
{
    WorldInfo.Game.Broadcast(self, "Received Text: "$Text);

    //we dont want the header info, so we split the string after two new lines
    Text = Split(Text, chr(13)$chr(10)$chr(13)$chr(10), true);

    WorldInfo.Game.Broadcast(self, "Split Text: "$Text);

    statusCode = Text;
}

event ReceivedLine( string Line ) {
    WorldInfo.Game.Broadcast(self, "Received Line: "$Line);
}

event ReceivedBinary( int Count, byte B[255] ) {
    WorldInfo.Game.Broadcast(self, "Received Binary of length: "$Count);
}

defaultproperties
{
    TargetHost="127.0.0.1"
    TargetPort=80 //default for HTTP
    LinkMode=MODE_Text
    ReceiveMode=RMODE_Event
    path = "dnomad/datafeed.php"
    userId = "0";
    apartmentId = "0";
    statusCode = "";
    send = false;
}

```

# Answer
> 2 votes
While I'd be very happy for someone else to come and give a more specific reason as I don't really have the facts to back up my claim, but it looks like this is a limitation of Broadcast. Alternatively you can write to the console or maybe update some UI elements depending on how you want to handle your messages.

---
Tags: software-engineering, udk, unreal
---


title: HTML5 game obfuscation

text:
# Question
Title: HTML5 game obfuscation
HTML5 games have viewable source code. Is there a way to make them like swf file?

How to hide the game algorithm?

What do you think of the Firefox JavaScript Deobfuscator Plugin and obfuscation?

# Answer
> 10 votes
If you want to protect your source, don't write it in HTML/Javascript?

Part of the really nice things about the web as it's all human-readable. This makes it an excellent learning resource. If you're telling me that you've never looked at the source of a website to learn how it does something, then feel free to tell me I'm wrong.

I'm all bout sharing the love with code, otherwise I wouldn't answer questions on a website about offering help, all for free, would I?

Edit: I've said what I think of it, is there a way to make it non-readable? No, not in pure JS/HTML. The reason for this is simple: Somewhere down the line, it becomes readable. If you obfuscate it then a deobfuscator gets you. If you use a cipher or translate it somehow, at some point you have to translate it back into javascript (and the code to translate it back needs to be in your source too!).

The best you can do is to protect against bandwidth theft and obfuscate if you really feel the need, but it's not going to stop people if they're really determined.

# Answer
> 5 votes
You can put a lot of it on the server via Node.js and just return back results of functions. but other than that it's like Matt Kemp says. The code that runs is readable by a human, it's impossible to hide it.

# Answer
> 2 votes
Even if you don't obfuscate your code, HTML/ JS is already about the same level of difficulty to reverse engineer as SWF.

SWF files contain the original Actionscript code, (IIRC), with comments etc, unless they're obfuscated. Names of objects etc, are also contained within the SWF.

SWF decompilers / recompilers exist, and just because you can't see it with a text editor, does not mean SWF is in any way safe from reverse engineering.

In fact the level of obfuscation is really no different to a SWF. You could obfuscate your JS code using some obfuscator, but that just makes bug reports more difficult to interpret.

You probably want to focus your efforts into making something worth stealing, rather than preventing people stealing it. Plenty of SWFs get ripped off and used for unauthorised purposes (with changed graphics, etc)

# Answer
> 2 votes
Use the free Yahoo YUI compressor.

I use it because it compresses my code drastically (including removing comments and unnecessary whitespace). This lets me comment and structure my code exactly how I want without worrying about how easy I'm making it for thieves.

Additionally if you want to read the Javascript for a complex site after all variable and function names have been essentially destroyed -- well, good luck with that. It's much harder to figure out what code is doing when you have no hints.

(Though with YUI compressor you may need to augment its functionality to also get rid of function names. I have altered the way I name functions specifically for the purpose of automatically and selectively removing most function names. This may require some custom code on your end.)

# Answer
> 1 votes
No, and there is really no reason to! If you want to sell your work, you can do that without obfuscation. People pay for content, not code. Sell your artwork, story, music, etc., and give away the code freely (it already is, anyway).

# Answer
> 1 votes
> HTML5 games have viewable source code. Is there a way to make them like swf files?

Yeah, use Flash and translate your code to ActionScript.

> How would one go about hiding the game algorithms?

In absolute terms, you can't do that.

> What do you think of the Firefox JavaScript Deobfuscator Plugin and obfuscation?

Obfuscation is nothing but a very thin barrier for somebody who'd be serious about stealing your code. Still, it's simple to setup, it can repulse the most dumb script kiddies, and it's the only thing you can do to protect client-side code. It has the additional benefit that it reduces the script size (faster download) and can even optimize the code (faster execution). Check this entry on Stack Overflow for details on obfuscation. Summary: you have *plenty* of options. I personally tried UglifyJS and had very satisfactory results.

# Answer
> 0 votes
As we all know HTML5 relies on JavaScript as a programming language. In theory all tools that protect JavaScript should work on HTML5.

The only tool I know that currently supports HTML5 in the context of Gaming development is JScrambler. I'm not sure if others will work.

For the porpoise of discussion, obfuscation is not a silver bullet. We have software that is compiled encrypted, protected with several anti copy solutions and still o can get them without paying. That said I believe that obfuscation beats leaving your code open for any one to read when you intention is not that.

I really love open source and support the movement yet sometimes closing the source makes lots of sense.

# Answer
> 0 votes
You can use native code. Programming on C++ and compile for HTML5. Cocos2d-X is a library that work on iOS, Android, and HTML5. Your code will be hidden.

---
Tags: javascript, html5
---


# Question
Title: jBullet Collision/Physics not working as expected
Below is the code for one of my objects in the game I am creating (yes although this is a cube, I am not making anything remotely like MineCraft), and my issue is I while the cube will display and is does follow the physics if the cube falls, it does not interact with any other objects in the game. If I was to have multiple cubes in screen at once they all just sit there, or shoot off in all directions never stopping. Anyway, I am new to jBullet, and any help would be appreciated.

```
    // Constructor
public Cube(float pX, float pY, float pZ, float pSize)  {
    posX = pX;
    posY = pY;
    posZ = pZ;
    size = pSize;
    rotX = 0;
    rotY = 0;
    rotZ = 0;

    // physics stuff
    fallMotionState = new DefaultMotionState(new Transform(new Matrix4f(new Quat4f(0, 0, 0, 1), new Vector3f(posX, posY, posZ), 1)));
    fallRigidBodyCI = new RigidBodyConstructionInfo(mass, fallMotionState, fallShape, fallInertia);
    fallRigidBody = new RigidBody(fallRigidBodyCI);
}

```

# Answer
> 0 votes
From the given code I cannot say what the problem could be. The following code is working fine for me.

First create the physics world:

```
// Create the physics world
BroadphaseInterface broadphase = new DbvtBroadphase();
CollisionConfiguration collisionConfiguration = new DefaultCollisionConfiguration();
Dispatcher dispatcher = new CollisionDispatcher(collisionConfiguration);
ConstraintSolver solver = new SequentialImpulseConstraintSolver();
DiscreteDynamicsWorld dynamicsWorld =
    new DiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
dynamicsWorld.setGravity(new Vector3f(0, gravity, 0));

```

Then create physics objects:

```
// Create a physics object (sphere)
MotionState motionState = new DefaultMotionState();
CollisionShape collisionShape = new SphereShape(radius);
Vector3f localInertia = new Vector3f(0, 0, 0);
collisionShape.calculateLocalInertia(mass, localInertia);
RigidBody rigidBody = new RigidBody(mass, motionState, collisionShape, localInertia);
rigidBody.setActivationState(CollisionObject.DISABLE_DEACTIVATION);
Transform transform = new Transform();
transform.origin.set(x, y, z);
rigidBody.setWorldTransform(transform);

```

And finally add the physics object to the physics world:

```
// Add the object to the world
dynamicsWorld.addRigidBody(rigidBody);

```

---
Tags: java, collision-detection, game-mechanics, bullet-physics
---


# Question
Title: Calculating a child object's Position, Rotation and Scale values?
I am making my own game editor, but have encountered the following problem:

I have two objects, A and B.

A's initial values:

```
Position: (3,3,3), Rotation: (45,10,0), Scale(1,2,2.5)

```

B's initial values:

```
Position: (1,1,1), Rotation: (10,34,18), Scale(1.5,2,1)

```

If I now make B a child of A, I need to re-calculate the B's Position, Rotation and Scale relative to A such that it maintains its current position, rotation and scale in world coordinates. So B's position would now be (-2, -2, -2) since now A is its center and (-2, -2, -2) will keep B in the same position.

I think I got the Position and scale figured out, but not rotation.

So I opened Unity and ran the same example and I noticed that when making a child object, the child object did not move at all. but had its Position, Rotation and Scale values changed relative to the parent.

For example:

Unity (Parent Object "A"):

```
Position: (0,0,0)
Rotation: (45,10,0)
Scale: (1,1,1)

```

Unity (Child Object "B"):

```
Position: (0,0,0)
Rotation: (0,0,0)
Scale: (1,1,1)

```

When B becomes a child of A, it's rotation values become:

```
X: -44.13605
Y: -14.00195
Z: 9.851074

```

If I plug the same rotation values into the B object in my editor, the object does not move at all.

How did Unity arrive at those rotation values for the child? What are the calculations?

If you can put all the equations for the Position, Rotation or Scale then I can double check I am doing it correctly but the Rotation is what I really need.

# Answer
Put some research in using Matrices.

Use a Matrix for each child object and matrix for the parent object. First transform all the objects with the child matrix, then transform all the objects with the parent matrix. This way when you transform the parent matrix all childs will transform with it.

You could take a look at my question: Transform coordinates from 3d to 2d without matrix or built in methods
> 4 votes

---
Tags: 3d
---


title: Arbitrary Rotation about a Sphere

text:
# Question
Title: Arbitrary Rotation about a Sphere
I'm coding a mechanic which allows a user to move around the surface of a sphere. The position on the sphere is currently stored as `theta` and `phi`, where `theta` is the angle between the z-axis and the xz projection of the current position (i.e. rotation about the y axis), and `phi` is the angle from the y-axis to the position. I explained that poorly, but it is essentially `theta = yaw`, `phi = pitch`

```
Vector3 position = new Vector3(0,0,1);
position.X = (float)Math.Sin(phi) * (float)Math.Sin(theta);
position.Y = (float)Math.Sin(phi) * (float)Math.Cos(theta);
position.Z = (float)Math.Cos(phi);
position *= r;

```

I believe this is accurate, however I could be wrong. I need to be able to move in an arbitrary pseudo two dimensional direction around the surface of a sphere at the origin of world space with radius `r`. For example, holding `W` should move around the sphere in an upwards direction relative to the orientation of the player.

I believe I should be using a Quaternion to represent the position/orientation on the sphere, but I can't think of the correct way of doing it. Spherical geometry is not my strong suit.

Essentially, I need to fill the following block:

```
public void Move(Direction dir)
{
    switch (dir)
    {
        case Direction.Left:
            // update quaternion to rotate left
            break;
        case Direction.Right:
            // update quaternion to rotate right
            break;
        case Direction.Up:
            // update quaternion to rotate upward
            break;
        case Direction.Down:
            // update quaternion to rotate downward
            break;
    }
}

```

# Answer
Actually, it turns out that you can't have it 'both ways': if your intention is to not have any sense of 'absolute orientation' on the sphere (that is, if the players aren't always e.g. facing towards the poles), then you'll need to have a notion of player orientation. This is because, contrary to what intuition might suggest, movement on the sphere is *not* exactly like movement on a plane, not even locally (quite); the intrinsic curvature of the sphere means that players can take actions that will rotate themselves!

For the most extreme example of what I'm talking about, imagine that the player starts at a point on the equator (for convenience we'll imagine a clock face mapped onto the equator from above, and put the player at 6 o'clock), facing 'up' - that is, towards the North Pole. Suppose the player walks all the way to the North Pole; then they'll be facing directly towards the 12 o'clock point. Now, let the player move directly to their right, from the North Pole back to the equator; they'll wind up at the 3 o'clock point - but because *their facing doesn't change when they move right* (the idea is that their facing doesn't change no matter how they move), they'll still be facing the 12 o'clock point - they're now facing along the equator! Now, let them move 'backwards' back to their starting (6 o'clock) point; then they'll still be facing along the equator, so they'll be facing towards the 3 o'clock point - just moving along the sphere without ever changing their 'personal' orientation has caused them to rotate from facing towards the north pole to facing along the equator! In a sense, this is an elaboration of the old 'a hunter moves a mile south, a mile west and then a mile north' joke - but here we're taking advantage of the curvature of the sphere to effect a change of direction. Note that the same effect still happens even on much smaller scales; this is the most extreme version of it, but even just short 'one foot north, one foot east, one foot south, one foot west' rectangles won't leave the player facing precisely the way they were before - this is an expression of the fact that the sphere has nontrivial curvature.

Fortunately, quaternions do (as you noted yourself) handle this situation; since a quaternion represents an arbitrary rotation, it effectively represents an arbitrary 'point plus orientation' on the sphere: imagine starting with a 'triaxis' at the origin and giving it some arbitrary rotation, then moving one unit in whichever direction the rotated axes' Z-axis points; a little thought will convince you that this brings you to a point on the unit sphere with some 'orientation' (i.e., some arrangement of the X and Y axes of your triaxis), and that you can get to every point+orientation on the unit sphere this way (just assign your Z axis to point along the line from the origin through your point on the sphere, then transport your triaxes back to the origin along that line). What's more, since multiplication of quaternions corresponds to composition of rotations, each of the operations you describe can be represented by multiplying your 'current orientation' by an appropriately-chosen quaternion: specifically, since the (unit) quaternion (qx,qy,qz,qw) means 'rotate about the (qx,qy,qz) axis by arccos(qw)', then (depending on your specific choice of coordinate system, and letting c\_a be cos(alpha) and s\_a be sin(alpha)) two of the three quaternions M\_x = (s\_a, 0, 0, c\_a), M\_y = (0, s\_a, 0, c\_a), and M\_z = (0, 0, s\_a, c\_a) will represent 'rotate (i.e. move) in the direction I'm currently facing by alpha' and 'rotate in a direction orthogonal to the one I'm currently facing by alpha'. (The third of those quaternions will represent 'rotate my character about his own axis') This means that every tick you'll figure out which key has been pressed and then, e.g., say `Cur_q = M_x * Cur_q` if the player has pressed up, or `Cur_q = M_y * Cur_q` if the player pressed right (or possibly something like `Cur_q = M_yinv * Cur_q` if the player pressed left, where M\_yinv is the 'inverse' of the M\_y quaternion, representing a rotation the other way). Note that you have to be careful which 'side' you apply the rotation on, whether to premultiply or postmultiply; to be frank, it may be easiest to solve that with trial-and-error, trying both multiplications and seeing which works.

Going from your updated quaternion to a point on the sphere (and to an orientation of your character) is relatively straightforward, too: by the correspondence of the last paragraph, all you have to do is use your quaternion on the basis vectors (1,0,0), (0,1,0) and (0,0,1) of your frame via 'rotate vector by quaternion' operation v → qvq<sup>-1</sup> (where the multiplications here are quaternion multiplies and we identify the vector v=(x,y,z) with the 'degenerate quaternion' (x,y,z,0)). For instance, the position on the unit sphere is gotten by just transforming the z vector: pos = (qx, qy, qz, qw) * (0, 0, 1, 0) * (-qx, -qy, -qz, qw) = (qx, qy, qz, qw) * (qy, -qx, qw, qz) = (2(qy\*qw+qz\*qx), 2(qz\*qy-qw\*qx), (qz^2+qw^2)-(qx^2+qy^2), 0), so `(2(qy*qw+qz*qx), 2(qz*qy-qw*qx), (qz^2+qw^2)-(qx^2+qy^2))` would be the coordinates of the 'transformed' user on the unit sphere (and to get the coordinates on an arbitrary sphere, of course, you'd just multiply those by the sphere's radius); similar calculations work for the other axes, to define e.g. the user's facing direction.
> 5 votes

# Answer
I think you want something similar to this http://www.youtube.com/watch?v=L2YRZbRSD1k

I developed that for a 48h gamejam... you can donwload the code here... http://archive.globalgamejam.org/2011/evil-god

I used something similar to your code to get the 3D coords... but I rotated the planet and the player was in the same pos, I think you are interested in the creature movement, is this:

```
    // To add movement
    protected override void LocalUpdate(float seconds)
    {
        Creature.Alfa += Direction.X * seconds * Speed;
        Creature.Beta += Direction.Y * seconds * Speed;
    }

    // To calculate position
       World.Planet.GetCartesian(Alfa, Beta, out Position); // as you do
       Matrix PositionMatrix = Matrix.CreateTranslation(Position) * World.Planet.RotationMatrix;
       LastPositionAbsolute = PositionAbsolute;
       Vector3 Up = PositionAbsolute = Vector3.Transform(Vector3.Zero, PositionMatrix);
       Up.Normalize();
       // This is to add and offset to the creature model position
       PositionAbsolute += Up * 8;
      // calculate new forward vector if needed

       if ((PositionAbsolute - LastPositionAbsolute).Length() > 0.1f) {
           Forward = PositionAbsolute - LastPositionAbsolute;
           Forward.Normalize();
       }

       // Calculate the world transform with position, forward vector and up vector
       Matrix LocalWorld = Matrix.CreateWorld(PositionAbsolute, Forward, Up);

       Transform = Matrix.CreateScale(Scale * ScaleFactor) * LocalWorld;

```
> 1 votes

---
Tags: xna, rotation, geometry, quaternion
---


# Question
Title: Read an object from compressed file generated from ActionScript 3
I have made a simple game Map Editor and I want to save a array that contain map tile info to a file, as below:

```
var arr:Array = [.....2d tile info in it...];
var ba:ByteArray = new ByteArray();
ba.writeObject(arr);
ba.compress();
var file:File = new File();
file.save(ba);

```

I had successfully saved a compressed object to a file. Now the problem is my server side need to read this file and decompress the array out from the file, then convert it to a Python list. Is that possible?

# Answer
> 0 votes
As usual almost any `Is that possible?` question is answered **Yes**. To do that, you need to know compression method used by ActionScript (most possibly is some of zlib methods). After that you need to somehow get serialization format of array, and read it back.

But zipped Json and XML can be not much larger than binary compressed.

Also this question has not much to do with game programming, so you can try it on StackOverflow.

---
Tags: actionscript-3, python
---


# Question
Title: Drawing an animation over an already drawn screen
I am working on a XNA WP7 card game whose basic prototype is complete. In game screen, 6 cards are displayed at a time (3 for each of the two players say 1,2 and 3).

If player A attacks one of player B's card then I want to show an animation over player B's card i.e the victim card(say a claw scratch for e.g.)

My question is how do I approach with the animation system so that I can draw an animation over a card upon certain events e.g. dead, fire, claw attack etc.

I have an attack function which detects which type of card is attacking which type of card. Depending on the type of attacker card I want to display the animation on the victim card.

Can I call animation classes function for different animations in the attack function itself without actually having to call separate draw and update functions. If so, how?

Also how do I play sound at the same time when the animation is going on?

EDIT- Heres what I have done.

I took your advice and created an animation routine in a different class. Here's how it works.

1. I have a separate Animation.cs class file (where animation occurs)
2. I have a wrapper class called CardAnimation which has a Dictionary object as animations with animation type as key and animation object as value.
3. I created a static object of CardAnimation class in Card class so that its not created every time I call animation routine.
4. I am calling the card's update method from another class called MAINGAMESCREEN.

Here's the flow of Update methods

MAINGAMESCREEN -\> CARD -\> CARDANIMATION -\> ANIMATION

Animation works but it occurs very fast that I can see only first frame. Same animation code works fine in an independent project. What can I do to slow it down?

# Answer
> 1 votes
You can just draw the animation over the card by a second draw call. The code will look something like this:

```
SpriteBatch.Begin();
SpriteBatch.Draw(Cards);
if(Animation_should_play);
 SpriteBatch.Draw(Animation);
SpriteBatch.End();

```

You can also define a Routine in every card (if you are using OOP) for the Animation and pass the SpriteBatch as an Parameter: *In the card class*

```
public void DrawDeathAnim(SpriteBatch batch)
 Batch.Draw(Animation)

```

Note that you don´t need to call Begin and End if you are calling this function from inside the main Draw logic.

EDIT:

To control the speed of your animation you need to pass he elapsed time since the last update and multiply your values with it. This is passed to XNAs update routine as gameTime.

# Answer
> 0 votes
You need to control(slow) the animation update somehow, i would create an update event which is raised each time you want the next frame.

here is a good example http://www.xnawiki.com/index.php/Event\_Driven\_Timer

Good luck :)

---
Tags: xna, animation, windows-phone-7, sound
---


# Question
Title: 2D lighting theory: day-and-night cycle, spot lights at night
I am writing a rogue-like 'zombie' management game. The game map will be similar to Prison Architect. A top-down 50 X 50 grid.

I want to implemented a day night cycle and during the night I would like the player to be able to position lights.

I would like to be able to lighten and dark to whole map to display the day and night cycle.

Then lights would be a circle of light blocked by game entities such as walls, players, trees etc.

How would I achieve and what is the standard way of achieving this?

# Answer
Sorry for posting a collection of links but your problem has many possible solutions! :)

Various gridbased lighting algorithms traditionally used by roguelikes: http://roguebasin.roguelikedevelopment.org/index.php?title=Category:LOS http://roguebasin.roguelikedevelopment.org/index.php?title=Field\_of\_Vision

A solution I developed to support **partial occlusion** of grid cells: http://blog.pixelpracht.net/?p=340

Rather complicated pixel-perfect approach that calculates the Field of View as a Polygon: http://www.redblobgames.com/articles/visibility/

A game I wrote a while ago using a similar math based approach: http://runehunt.pixelpracht.net/

Projecting each face outwards, kinda what Carmack did in Doom3 but in 2d space. Causes a lot of overdraw which doesn't matter so much if you have access to hardware acceleration. http://forums.tigsource.com/index.php?topic=8803.0
> 4 votes

# Answer
http://www.catalinzima.com/2010/07/my-technique-for-the-shader-based-dynamic-2d-shadows/

there is also a link at teh bottom of the comments to an 'improved' version of this
> 0 votes

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


# Question
Title: Simulate 'Shock absorbtion' with tire rubber in PhysX (2.8.x)
This is a kinda tricky question and I fear there is no easy enough solution, but I figured I'd hit SE up before giving up on it and just doing what I can.

A machine I am working on has no suspension or shocks or springs of any sort in the real machine, so you would think that when it drives over bumps, it would shake like crazy but because its tires (6 of them) are quite large they seem to absorb a lot of shock from the bumps. Part of this is because the machine is around 30k lbs and it just smashes/compresses any bumps in the ground down (This is another issue im still working on) and the other part is that the tires seem to have a lot of flex to them with a lot of air as well.

So my current task is to simulate shock absorption in physx without visibly separating the tires from the spindle/axle..

I have been messing with all kinds of NxMaterial, NxSpring, Joints, etc. and have had no luck getting this to work. The main problem is that the spindle attached to the tire is directly in the center and the axle is basically solidly attached to the chassis, so if i give it any spring or suspension travel, that spindle on the tires will move upwards or downwards, looking very odd because now its not any longer in the center of the tire. I tried giving it a higher restitution but that just makes it bouncy without any shock absorption.

Another avenue I am messing with is to actively smooth the terrain in front of the tires so that before it hits a bumpy patch, that patch is smoothed and it doesn't bounce. The only issue with this is that it is pretty expensive to do with 6 tires, high tessellation of the terrain and other complex things going on at the same time in this simulation. I am still working on this but I am hoping to mix and match a few different aspects to get the best possible outcome.

This is a bit of a complex issue so I'm not expecting anyone to have a definitive answer, just hoping someone may think of something I haven't =-)

-Side note: Yes i know PhysX 2.8.x is quite outdated but we have to stick with it for this implementation. We are in the process of going to another physics engine but it is out of scope to apply that engine to this project.

# Answer
It may be that you are treating the wheel as being soft as a whole instead of just making the tire soft. This would lead to the center of the tire going away from the axle.

Make the hub of the wheel a solid shape and try surrounding it in springs. Weld one end of each spring to the hub of the wheel. Align the spring with the surface normal of the hub. At the other end, join it to it's neighbour spring via a spring for each neighbour.

I found the perfect image to illustrate what I mean, although you would obviously be using spring joints to hold up a body:

You may want several rows of springs running around the hub and you might want to try different configurations of joining them to each other with springs.

Here is an alternative way you could organize springs to make the tire, but in your simulation you would need to join several spring joints together to simulate an actual spring to spread across the tire:

You could do something similar when laying out the springs. You could try adding a little extra support by placing a spring under some of the "joining nodes" and hopefully you could find a configuration that looks good enough for the performance requirement.

Another alternative is to make a soft body deforming torus but I'm not sure if physx has soft body support. If it doesn't it could get tricky. But it does come down to applying an outward force (aligned to the vertex's normal) relative to the difference in volume between the shape it started as and what it is currently. Keep in mind that pulling it would make the difference negative and so it would pull the points inwards.
> 2 votes

---
Tags: physics, physx, vehicle
---


# Question
Title: Where can I find a basic algorithm for parsing tiled maps?
I have attempted to use Tiled for creating 2d maps, and saving them under a text file. The resulting text file seems difficult to parse at first, I gave it a shot here however to no good result.

I have been wondering if anyone has a basic tiled map parsing algorithm. I have searched for a possible algorithm but to no avail so far.

# Answer
Note that the txt export option of Tiled is a format used by one specific engine. Copying that format might not be the best solution for your use-case.

I would recommend you to save your Tiled maps in the native TMX format and parse it with an XML parser like libXML. The JSON export is also an option, but I have never worked with any JSON library in C++, so I can't recommend you one.

Open source code which loads TMX maps with libXML2 can be found in the sourcecode of the client of the open source MMORPG *The Mana World*. By the way: The lead developer of Tiled is also participating in the development of TMW.

Full Disclosure: I used to be a developer of TMW myself and wrote a few lines of the code linked above.
> 4 votes

---
Tags: c++, maps
---


title: Rotate a particle system

text:
# Question
Title: Rotate a particle system
Languages / Libraries in use: C++, OpenGL, GLUT

## Okay, here's the deal.

I've got a particle system which shoots out alpha blended textures to produce a flame. The system only keeps track of very basic things such as, time alive, life, xyz and spread.

The direction in which the flames are currently moving in is purely based on other things which are going on in my code ( I assume ).

My goal however, is to attach the flame to the camera (DONE) and have the flame pointing in the direction my camera is facing (NOT WORKING).

I've tried glRotate for both x,y,z and I can't get it to work properly.

I'm currently using gluLookAt to move the camera, and get the flame to follow the XYZ of the camera by calling glTranslatef(camX, camY - offset, camZ);

## Any suggestions on how I can rotate the direction of the flame with the camera would be greatly appreciated.

Heres an image of what I've got: https://i.stack.imgur.com/ha3gh.png

Notes: Crosshair depicts where camera is facing

if I turn the camera, flame doesn't follow the crosshair

Also asked here: https://stackoverflow.com/questions/9560396/rotate-a-particle-system but was referred here

# Answer
Just at a quick glance I would check in your code where you are drawing the particle system in comparison to when you actually do the world rotations and translations. Drawing the particle system before you do the any changes could cause it to remain in the same position. Just trying to help in any way. Good Luck!
> 2 votes

# Answer
Personally, my preference would be to not use gluLookAt. Instead, I'd recommend using gluPerspective to set your perspective transform. Then, push a translation and rotation to define the global co-ordinate space relative to the camera co-ordinates. (That is, don't move the camera, move the world). Draw things whose positions are fixed relative to the camera either at the begining, before you push the global co-ordinate transform, or at the end, after popping the transform.

In this manner, to get a camera at (10,10,0) which is rotated down 30deg about the x axis, you could write:

```
glLoadIdentity();
gluPerspective(60, 1.5, 0.1, 1000.0);
/* Draw things relative to camera */
glPushMatrkx();
glTranslatef(-10,-10,0);
glRotatef(-30, 1, 0, 0);
/* Draw the world */
glPopMatrix();
/* Relative to camera again*/

```

If you want to continue to move the camera in the way you are now, here's what I would recommend doing.

Be careful to ensure that the flame co-ordinate system is rotated before it is translated. Remember, matrix multiplication is not communtative, so rotating and then translating is not at all the same as translating and then rotating.

First, compute the rotation axis and angle. Given a unit vector pointing in the camera view direction, V, and another unit vector pointing in the direction of the flame, F, you can compute the required axis of rotation as A = (F cross V). The rotation angle is given by theta = acos(F dot V).

Recalling that GL right-multiplies matrices, call glTranslatef before glRotatef. So you'll get something along the lines of:

```
glPushMatrix();
glTranslatef(camX, camY - offset, camZ);
glRotatef(theta * 180 / pi, A.x, A.y, A.z);  // acos usually gives radians
/* Draw fire */
glPopMatrix()

```
> 0 votes

# Answer
OpenGL uses a left-handed coordinate system, so the camera's Z axis is always pointing "into" the scene.

What you need to do is rotate the camera's Z axis into object space, which is actually quite simple:

Say the upper 3x3 of your model-view matrix is orthogonal (a scaled rotation). Use the normalization of the 3rd row of it as the direction vector.

For a general model space matrix, you need to do this:

```
objZ = (inverse(MV)*vec4(0,0,1,0)).xyz;

```

Then normalize.
> 0 votes

---
Tags: c++, opengl, rotation, particles, glut
---


title: Implementing hitbox polygon

text:
# Question
Title: Implementing hitbox polygon
I'm creating a shooter, it's still very early, but i'm implementing some polygon hitboxes.

So far i have created a polygon class, and i'm looking into how i can hook it onto my player.

I'm trying to stay away from having a `Tick()` function in my polygon class, and I would rather not update the position every tick (it would clutter up my tick functions). At the same time I would really like to have the positions in there somehow (it has a drawing function, and i will be using it for hit detection)

How would i go about implementing this polygon object into my entities?

# Answer
> 3 votes
This seems like a good place to use Composition.

Give the `Entity` your `Polygon` class as a property and update it whenever the entity moves.

```
public class Entity {
    public Polygon Hitbox { get; private set; }

    public void Move() {
        // stuff to move player
        this.Hitbox.X = this.Position.X;
        this.Hitbox.Width = ...
    }
}

```

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


# Question
Title: Is there a way to legally create a game mod?
> **Possible Duplicate:**
> How closely can a game resemble another game without legal problems

Some questions about it:

* If I create a funny version of a copyrighted game and sell it (crediting the original developers) would it be considered a parody or would I need to pay royalties?
* If I create a game mod for my own personal use would it be legal? What if I gave it for free to a friend?
* Is there a general rule about it or it depends on the developer will?

P.S.: I'm not talking about cloning games like this question. It's all about a game clearly based on another. Something like "GTA Gotham City" ;)

**EDIT**: This picture that I found over the internet illustrate what I'm talking about:

Just in case I was not clear:

* I never created a mod game. I was just wondering if it would be legally possible before trying to do it.
* I'm not apologizing piracy. I pay dearly for my games (you guys have no idea how expensive games are in Brazil due to taxes).
* Once more I say that the question is not about cloning. Cloning is copy something and try to make your version look like a brand new product. Mods are intended to make reference to one or more of its source. I'm not sure if it can be done legally (if I knew I wasn't asking) but I'm sure this question is not a duplicate. Even so, I trust in the moderators and if they close my question I will not be offended - at least I had an opportunity to explain myself and got 1 good answer (by the time I write this, maybe some more will be given later).

# Answer
> 5 votes
When modding games, you'll be vulnerable to legal action from two places.

First, from the original game creators. I'm not sure how common this is now, but at one point making mods was against most EULA's because it required reverse engineering the game files. I'm sure there are plenty of games that still have this type of clause to try to combat hacks and cheats, however a lot of games encourage a limited form of modding by providing official tools to do so. IMO, modern gaming culture has adopted a general rule of thumb that as long as your mod is free and requires someone to own a working copy of the game, there's no real harm. In your example of GTA3, you should **read the EULA** that you agreed to and watch that specific modding community a bit to see what mods have been already made.

Secondly, IMO more probably, you might face legal action from the owners of the copyright on the characters/places/themes that you want to import into the game. There has been at least one recent example of a cease and desist letter sent to modders because they were using copyright content. In your example, the owner would be DC Comics. Satires/parodies often have a lawyer on staff and take care to scrub out every trademark or direct reference to the material they're covering.

To sum up: Selling a mod will probably get you in trouble. Distributing mods to your friends will probably get you in trouble if you're using themes that are copyright or trademark. The general rule is to ask a lawyer (I am not one, the internet doesn't count either).

# Answer
> 1 votes
Generally speaking, parody is protected under Fair Use if you are not selling it. Many game engines, such as Unreal, Source, and others, allow and encourage game modding that uses their assets and characters that you can freely distribute but not sell.

I do not thing there are any cases where you can sell a mod and not be under fire for copyright violation, as you are competing with the creators of the original game.

---
Tags: legal, modding
---


# Question
Title: setting the position in different resolution
I have a normal game window which is 640\*480, and everything is fine, but when I try to maximize the window, the objects translate to different positions on the screen, for example If I have a circle which is drawn at the center in the normal window, when I try to maximize it, it shifts away from the center of the screen. How do I adjust it so it draws at the center in both normal window and maximized window ?

# Answer
> 3 votes
Is this is a 2D game, you need to position your objects based on ratios or percentages.

For example instead of putting your object at `(320, 240)` to center it. Put it at `(.5f*ScreenWidth, .5f*ScreenHeight)`. Make sure you update any bufferer vertices when resizing so that their positions are updated.

If it's a 3D game, your camera class should expand the view port from the center out. Meaning, keep the camera in the same position, with the same target vector.

# Answer
> 0 votes
This may not be the most efficient method, but it's certainly easy. If you can make canvases/surfaces/framebuffers/whatever you call them, then you can just code the game for a specific resolution (may as well stick with 640x480), draw everything gameplay-related to the canvas, and then draw the canvas scaled based on the window width and/or height.

For a game that is usually 640x480:

```
x_scale = 480 / window_height
y_scale = 480 / window_height

```

---
Tags: opengl, mathematics
---


# Question
Title: Fixing a collision detection bug in Slick2D
My game has a bug with collision detection. If you go against the wall and tap forward/back sometimes the game thinks the speed you travelled at is 0 and the game doesn't know how to get you out of the wall. My collision detection works by getting the speed you hit the wall at and if it is positive it moves you back, if it is negative it moves you forward.

It might help if you download it: https://rapidshare.com/files/1550046269/game.zip

Sorry if I explained badly, it's hard to explain.

```
float maxSpeed = 0.3f;
float minSpeed = -0.2f;
float acceleration = 0.002f;
float deacceleration = 0.001f;

float slowdownSpeed = 0.002f;
float rotateSpeed = 0.08f;
static float currentSpeed = 0;

boolean up = false;
boolean down = false;

boolean noKey = false;

static float rotate = 0;

//Image effect system
static String locationCarNormal;
static String locationCarFront;
static String locationCarBack;
static String locationCarBoth;

static boolean carFront = false;
static boolean carBack = false;

static String imageRef;

boolean collision = false;

public ComponentPlayerMovement(String id, String ScarNormal, String ScarFront, String ScarBack, String ScarBoth)
{
    this.id = id;
    playerBody = new Rectangle(900/2-16, 700/2-16, 32, 32);

    locationCarNormal = ScarNormal;
    locationCarFront = ScarFront;
    locationCarBack = ScarBack;
    locationCarBoth = ScarBoth;

    imageRef = locationCarNormal;
}

@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException
{
    Input input = gc.getInput();

    playerBody.transform(Transform.createRotateTransform(2));

    float hip = currentSpeed * delta;
    float unstuckspeed = 0.05f * delta;

    if(carBack && !carFront)
    {
        imageRef = locationCarBack;
        ComponentImageRender.updateImage();
    }
    else if(carFront && !carBack)
    {
        imageRef = locationCarFront;
        ComponentImageRender.updateImage();
    }
    else if(carFront && carBack)
    {
        imageRef = locationCarBoth;
        ComponentImageRender.updateImage();
    }

    if(input.isKeyDown(Input.KEY_RIGHT))
    {
        rotate += rotateSpeed * delta;
        owner.setRotation(rotate);
    }

    if(input.isKeyDown(Input.KEY_LEFT))
    {
        rotate -= rotateSpeed * delta;
        owner.setRotation(rotate);
    }

    if(input.isKeyDown(Input.KEY_UP))
    {
        if(!collision)
        {
            up = true;
            noKey = false;

            if(currentSpeed < maxSpeed)
            {
                currentSpeed += acceleration;
            }
            MapCoordStorage.mapX += hip * Math.sin(Math.toRadians(rotate));
            MapCoordStorage.mapY -= hip * Math.cos(Math.toRadians(rotate));
        }
        else
        {
            currentSpeed = 1;
        }
    }
    else if(input.isKeyDown(Input.KEY_DOWN) && !collision)
    {
        down = true;
        noKey = false;

        if(currentSpeed > minSpeed)
        {
            currentSpeed -= slowdownSpeed;
        }
        MapCoordStorage.mapX += hip * Math.sin(Math.toRadians(rotate));
        MapCoordStorage.mapY -= hip * Math.cos(Math.toRadians(rotate));
    }
    else
    {
        noKey = true;
        if(currentSpeed > 0)
        {
            currentSpeed -= deacceleration;
        }
        else if(currentSpeed < 0)
        {
            currentSpeed += acceleration;
        }
        MapCoordStorage.mapX += hip * Math.sin(Math.toRadians(rotate));
        MapCoordStorage.mapY -= hip * Math.cos(Math.toRadians(rotate));
    }

    if(entityCollisionWith())
    {
        collision = true;
        if(currentSpeed > 0 || up)
        {
            up = true;
            currentSpeed = 0;

            carFront = true;

            MapCoordStorage.mapX += unstuckspeed * Math.sin(Math.toRadians(rotate-180));
            MapCoordStorage.mapY -= unstuckspeed * Math.cos(Math.toRadians(rotate-180));
        }
        else if(currentSpeed < 0 || down)
        {
            down = true;
            currentSpeed = 0;

            carBack = true;

            MapCoordStorage.mapX += unstuckspeed * Math.sin(Math.toRadians(rotate));
            MapCoordStorage.mapY -= unstuckspeed * Math.cos(Math.toRadians(rotate));
        }
        else
        {
            currentSpeed = 0;
        }
    }
    else
    {
        collision = false;
        up = false;
        down = false;
    }

    if(currentSpeed >= -0.01f && currentSpeed <= 0.01f && noKey && !collision)
    {
        currentSpeed = 0;
    }
}

public static boolean entityCollisionWith() throws SlickException
{
    for (int i = 0; i < BlockMap.entities.size(); i++)
    {
        Block entity1 = (Block) BlockMap.entities.get(i);
        if (playerBody.intersects(entity1.poly))
        {
            return true;
        }
    }
    return false;
}

```

}

# Answer
> 1 votes
You might benefit from a collision methodology which detects a collision that is about to happen due to velocity, and truncates motion to the collision point. Your model would not get stuck in that state of colliding in all directions.

Or, a more complicated but better strategy, is to detect an oncoming collision and the fraction of oncoming motion before that collision happens. Move that first fraction, then reverse the velocity's direction and continue moving. This guarantees (in theory only :) ) not getting stuck and provides a very accurate collision, and makes the total motion equal to the inteded motion for that frame.

The simplest answer might be to give your collisions a direction, such that your model can always move away from the center of the bounding box of the object with which it collided. That will require a collision state more complex than a bool, of course.

---
Tags: java, collision-detection, slick
---


title: How do I create weapon attachments?

text:
# Question
Title: How do I create weapon attachments?
My question is; I am developing a game for XNA and I am trying to create a weapon attachment for my player model. My player model loads the .md3 format and reads tags for attachment points. I am able to get the tag of my model's hand. And I am also able to get the tag of my weapon's handle. Each tag I am able to get the rotation and position of and this is how I am calculating it:

```
Model.worldMatrix = Matrix.CreateScale(Model.scale) *
                    Matrix.CreateRotationX(-MathHelper.PiOver2) *
                    Matrix.CreateRotationY(MathHelper.PiOver2);

```

Pretty simple, the player model has a scale and its orientation(it loads on its side so I just use a 90 degree X axis rotation, and a Y axis rotation to face away from the camera). I then calculate the torso tag on the lower body, which gives me a local coordinate at the waist. Then I take that matrix and calculate the tag\_weapon in the upper body. This gives me the hand position in local space. I also get the rotation matrix from that tag that I store for later use. All this seems to work fine.

Now I move onto my weapon:

```
Matrix weaponWorld = Matrix.CreateScale(CurrentWeapon.scale) *
                            Matrix.CreateRotationX(-MathHelper.PiOver2) *
                            TagRotationMatrix *
                            Matrix.CreateTranslation(HandTag.Position) *
                            Matrix.CreateRotationY(PlayerRotation) *
                            Matrix.CreateTranslation(CollisionBody.Position) *

```

You may notice the weapon matrix gets rotated by 90 degress on the X axis as well. This is because they load in on their sides. Once again this seems pretty simple and follows the SRT order I keep reading about.

My `TagRotation` matrix is the hand's rotation. `HandTag.Position` is its position in local space. `CreateRotationY(PlayerRotation)` is the player's rotation in world space, and the `CollisionBody.Position` is the player's world location. Everything seems to be in order, and almost works in game. However when the gun spawns and follows the player's hand it seems to be flipped on an axis every couple frames. Almost like the X or Y axis is being inversed then put right back. Its hard to explain and I am totally stumped. Even removing all my X axis fixes does nothing to solve the problem. Hopefully I explained everything enough as I am a bit new to this! Thanks!

# Answer
> 2 votes
It might be a trigonometric discontinuity where the rotation matrixes `Matrix.CreateRotationY(PlayerRotation)` or `TagRotationMatrix` flip from one quadrant of a circle to another. That *might* result in a value that instantly changes from +pi/2 to -pi/2, (or the like) creating the symptoms you describe. You might try putting all your matrices and vectors into debug output, to try to isolate which link in the chain of multiplication is flipping.

---
Tags: xna, mathematics, models, matrix
---


# Question
Title: Client Side Prediction for a Look Vector
So I am making a first person networked shooter. I am working on client-side prediction where I am predicting player position and look vectors client-side based on input messages received from the server. Right now I am only worried about the look vectors though. I am receiving the correct look vector from the server about 20 times per second and I am checking that against the look vector that I have client side. I want to interpolate the clients look vector towards the correct one that is server side over a period of time. Therefore no matter how far you are away from the servers look vector you will interpolate to it over the same amount of time. Ex. if you were 10 degrees off it would take the same amount of time as if you were 2 degrees off to be correctly lined up with the server copy. My code looks something like this but the problem is that the amount that you are changing the clients copy gets infinitesimally small so you will actually never reach the servers copy. This is because I am always calculating the difference and only moving by a percentage of that every frame. Does anyone have any suggestions on how to interpolate towards the servers copy correctly?

```
if(rotationDiffY > ClientSideAttributes::minRotation)
{

    if(serverRotY > clientRotY)
    {
        playerObjects[i]->collisionObject->rotation.y += (rotationDiffY * deltaTime);
    }
    else
    {
        playerObjects[i]->collisionObject->rotation.y -= (rotationDiffY deltaTime);
    }

}

```

# Answer
> 2 votes
You could try using a lerp (linear interpolation) function using the current client rotation and the last rotation received from the server. Because you always want to use the same time period to update the rotation you could reset a variable each time the server receives a message and increment it by delta time each frame. For example, if you want the rotation to be corrected over 0.5 seconds, each time you receive a message from the server reset the timer to 0.0 and increment it up to 0.5.

```
template<typename T>
T lerp(T a, T b, T t)
{
    return a + (b-a) * t;
}

// Trim the t value to between 0.0 and 1.0
float t = timeSinceServerMessage / ROTATION_CORRECTION_TIME;

// Interpolate between the current rotation and the server rotation based on t
float newRotation = lerp<float>(currentClientRotation, serverRotation, t);

```

More information available here - Wikipedia: Linear Interpolation

---
Tags: physics, server, first-person-shooter, client
---


# Question
Title: Data model for unlockable card collection
My game has a collection of cards (about 64) that are unlocked (one by one) provided that 4 items are collected/gained in the game.

Right now the deck of cards is modeled with a plist file, like this:

```
<plist>
     <dict>
    <key>card1</key>
  <dict>
    <key>available</key>
    <true/>
    <key>series</key>
    <integer>1</integer>
    <key>model</key>
    <integer>1</integer>
    <key>color</key>
    <integer>1</integer>
</dict>
<key>card2</key>
<dict>
    <key>available</key>
    <false/>
    <key>series</key>
    <integer>1</integer>
    <key>model</key>
    <integer>1</integer>
    <key>color</key>
    <integer>2</integer>
</dict>

```

The value for the key named "available" marks if the item is locked or not. Right now I have to include the data for the items collected by the user, but including that inside the plist looks like too much hassle.

What kind of structure should be more suitable for this? How do you manage a collection of unlockable items like this?

# Answer
> 0 votes
I assume there's gonna be some kind of "save game" mechanic in your game. In this case, the simplest solution is to include in the player's saved game file a list of the cards the player already unlocked. Unfortunately I'm not familiar with the plist data structure, so I'll just provide an example in xml:

```
<UnlockedCards>
   <CardId>1</CardId>
   <CardId>5</CardId>
   <CardId>9</CardId>
   <CardId>23</CardId>
</UnlockedCards>

```

The reason I'm using CardId's instead of CardName's, is that your card names might change with localization, or patches (typo fixes etc.). If you associate an Id with each card, then you won't have to worry about those changes.

---
Tags: objective-c, data-structure, xml
---


# Question
Title: How do I deal with the problems of a fast side-scroller?
I'm making a side scrolling airplane game and when I begin going very fast I begin to experience some problems as a player:

* Elements are not distinguishable, like power-ups from bullets, etc
* I start to feel dizzy and uncomfortable
* There isn't enough time to see what's coming

How can I sort this out? Do I use less details in all the grahpics?

Tiny Wings has the same horizontal movement speed as in my game but it doesn't suffer from these problems. Are there any other really fast side-scrollers I could take as a reference?

# Answer
> Elements are not distinguishable, like power-ups from bullets, etc

Make them simple color based power ups. Words, letters or even icons may be too hard to distinguish at fast speeds. Make powerups one color and nothing else that color.

> I start to feel dizzy and uncomfortable

Maybe you're getting too old to play those types of games :) This is likely a symptom of the other issues, solving those will probably help with this. Lerping movements with the camera and zoom will help with this. Jarring quick motions or quick changes in perspective can induce these feelings.

> There isn't enough time to see what's coming

The faster the player goes, the farther out the zoom should be. Many games zoom out when using a boost/afterburners. Since you're going faster you need more time to react. The farther out you can see, the more time you have to plan for what's coming. Additionally, having indicators at the leading edge of the screen may be useful. For example if some kind of obstacle is coming that the player will need to use a special ability to avoid/destroy. Show an indicator at the leading edge of the screen to let them know it's coming before it comes into sight.
> 19 votes

# Answer
To make things more distinguishable, I would avoid using graphics with too many details. Instead, use graphics that primarily have a certain color, and possibly apply motion blur. This way, a power-up, for example, might be a blue streak, which should be pretty recognizable.

To avoid motion sickness, if you made the background kind of a fast-moving blur, I think that would avoid the problems of a fast-moving background being dizzying.
> 8 votes

# Answer
Well, since you didn't tell about your framerate, I'll assume it's pretty low. That would explain at least some of your issues.

Make sure your game runs at the highest framerate possible, ideally **60 fps**. When you game starts to get really fast, 30 fps is no longer comfortable for the human eye.
> 1 votes

---
Tags: game-design, side-scroller
---


# Question
Title: How do I sync client and server when sending player speed changes?
I'm implementing client-side prediction. Most explanations assume the client sends messages like "*Move my player up by 1 position*". **What if** I send messages like "*Set my player's velocity to x*"?

On the client, the player sets his own velocity (by client-side prediction) before the server does, resulting in the two getting out of sync. This problem persists even considering average latency.

How can I tackle this?

# Answer
> 8 votes
You should send redundant data, which here means send the position and the velocity. Even if you are out of sync, the fact that you have the position and the velocity allows you to correct the trajectory using an interpolation function.

Then using some tricks like delayed animations, accelerations, etc. allows to hide the latency.

**Edit:** I assume that the server is authoritative.

---
Tags: networking, client-server, movement-prediction
---


title: 2-d lighting day/night cycle

text:
# Question
Title: 2-d lighting day/night cycle
Off the back of this post in which I asked two questions and received one answer, which I accepted as a valid answer. I have decided to re-ask the outstanding question.

I have implemented light points with shadow casting as shown here but I would like an overall map light with no point/light source.

The map setup is a top-down 2-d 50X50 pixel grid.

**How would I go about implementing a day/night cycle lighting across a map?**

# Answer
> 1 votes
Thank you for your answer floAr I'm be up-voting your answer for giving me the term I was searching for:

*Ambient lighting* \- lighting which is from no particular source but which is background lighting across all entities.

I've found this blog post with some very simple code which I'll be trying later.

this is the key for me:

**new Color(ambientColor.R / 255f * ambient, ambientColor.G / 255f * ambient, ambientColor.B / 255f * ambient);**

From the blog post:

(the approach is to modify the color of every sprite when drawing it)

> Add to the top of your game class:
>
> ```
> float ambient = 1f;
> Color ambientColor = Color.White;
>
> ```
>
> In the Update method:
>
> ```
> KeyboardState c = Keyboard.GetState();
> if (c.IsKeyDown(Keys.Space))
> {
>    ambient -= 0.01f;
>    if (ambient <= 0)
>       ambient = 1f;
> }
>
> ```
>
> And finally, to apply ambient lighting to sprites:
>
> ```
> Color drawColor = new Color(ambientColor.R / 255f * ambient, ambientColor.G / 255f * ambient, ambientColor.B / 255f * ambient);
> spriteBatch.Begin();
> spriteBatch.Draw(mySprite, new Vector2(0,0), drawColor);
> spriteBatch.End();
>
> ```
>
> As you see, it's very easy :) With this, you could simulate for example day cycle.

# Answer
> 2 votes
You should take a look into ambient lightning. This means you set a light color which is applied to all elements. This could be done in several ways. If you are using a shader for postprocessing you can add it there as a parameter and just change it to simulate day and night cycles.

A nice example was shown here (its in german, but maybe the source will help you a bit). It basically uses blend states to mix up different render targets containing the light sources.

---
Tags: xna, lighting
---


# Question
Title: What is the breakdown of jobs in game development?
There's a project I'm trying to start for Indie Game Development; specifically, it's going to be a social networking website that lets developers meet through (*It's a secret*). One of the key components is showing what skills members have.

**Question**: I need to know what *MAJOR* game development roles are not represented in the following list, keeping in mind that many specialist roles are being condensed into more broad, generalist roles:

* Art

1. Animator (Characters, creatures, props, etc.)
    2. Concept Artist (2D scenes, environments, props, silhouettes, etc.)
    3. Technical Artist (UI artists, typefaces, graphic designers, etc.)
    4. 3D Artist (Modeling, rigging, texture, lighting, etc.)
* Audio

1. Composer (Scores, music, etc.)
    2. Sound Engineer (SFX, mood setting, audio implementation, etc.)
    3. Voice (Dialog, acting, etc.)
* Design

1. Creative Director (Initial direction, team management, communications, etc.)
    2. Gameplay Designer (Systems, mechanics, control mapping, etc.)
    3. World Designer (Level design, aesthetics, game progression, events, etc.)
    4. Writer (Story, mythos, dialog, flavor text, etc.)
* Programming

1. Engine Programming (Engine creation, scripting, physics, etc.)
    2. Graphics Engineer (Sprites, lighting, GUI, etc.)
    3. Network Engineer (LAN, multiplayer, server support, etc.)
    4. Technical Director (I don't know what a technical director would even do.)

**Post Script**: I have an art background, so i'm not familiar with what the others behind game creation actually do. What's missing from this list, and if you feel some things should be changed around how so?

# Answer
> 10 votes
By no means I am experienced with big game development, but I like the game team roles description as given by Jason Gregory in the Game Engine Architecture, because it is broad enough to hold true most of the time:

* Engineers (from runtime to tools)
* Artists (from concept, throught 3D and writing all the way to sound)
* Designers (gameplay, interface/interaction)
* Producers (actual job of the producer quite varies)
* Publishers (manufacture, marketing, distribution)
* Other (IT, QA, administrative, support)

I think something along these lines is the best you can get. I wouldn't try to be any more specific about this, as then things start to vary a lot from team to team.

# Answer
> 4 votes
I'm going to *attempt* to answer what I'm perceiving to be the question behind your question (which is, I think, "how should I present the breakdown of roles on my social network site dedicated to having developers meet up for projects?") and not your direct question regarding what major roles I think you're missing from your list. I think you've already got all the major roles you need, and in fact have already tried to break them down too specifically.

Instead, I think you should allow people to select from a pre-defined list of only the most general roles -- programmer, artist, designer, et cetera. Don't subdivide those roles yourself because it will probably only lead to confusion and mis-classification of skillset since, as I commented, the specific daily tasks of an "engine programmer" can vary wildly between projects, sometimes even overlapping heavily with those of a "graphics programmer."

In your situation, what I would do is allow people to select their broad discipline but then augment that with free-form tags (the same kinds of tags that StackExchange or the Careers 2.0 does) that indicate their specializations or topics they have experience with. You're probably correct that specific *roles* are less valued, but that doesn't mean specific skills or familiarity with specific technologies are not important to somebody setting up a project.

This allows users to characterize themselves, which is about as accurate as you can expect to get, but does not impose a ton of friction is signing up (as a user) to this site since you only *need* to choose your basic discipline or disciplines. It also lets you build sorting and searching systems around the tags, allowing potential "employers" to easily filter for users who are programmers with the "Mac" and "OpenGL" tags.

Plus, with the two-level mechanism of discipline and proficiency tags you can avoid some of the false positives you might get with a cross-domain tags like "rigging" -- a animator who is familiar with rigging is probably familiar with actually building it, whereas a programmer familiar with rigging is probably familiar with writing game code to support animating or driving rigs.

# Answer
> 3 votes
I guess we'll get this started as a community wiki. Please edit this as you see fit (better than replying in the comments).

* Art

1. Animator (Characters, creatures, props, etc.)
    2. Concept Artist (2D scenes, environments, props, silhouettes, etc.)
    3. Technical Artist (UI artists, typefaces, graphic designers, etc.)
    4. 3D Artist (Modeling, rigging, texture, lighting, etc.)
* Audio

1. Composer (Scores, music, etc.)
    2. Sound Engineer (SFX, mood setting, audio implementation, etc.)
    3. Voice (Dialog, acting, etc.)
* Design

1. Creative Director (Initial direction, team management, communications, etc.)
    2. Gameplay Designer (Systems, mechanics, control mapping, etc.)
    3. World Designer (Level design, aesthetics, game progression, events, etc.)
    4. Writer (Story, mythos, dialog, flavor text, etc.)
* Programming

1. Engine Programming (Engine creation, scripting, physics, etc.)
    2. Graphics Engineer (Sprites, lighting, GUI, etc.)
    3. Network Engineer (LAN, multiplayer, server support, etc.)
    4. Technical Director (I don't know what a technical director would even do.)
* Quality Assurance

1. Play tester (Plays the game, ensures balance, learning curve, "fun", doesn't see code)
    2. Whitebox tester (Tests functionality with access to code, unit testing, etc.)
    3. Automation tester (Writes automated tests for testing functionality)

# Answer
> 1 votes
> What's missing from this list?

Recognition that not all games are 3D.

Where would a pixel artist fit in your artist categorisation? How many people are good at animation in 2D and in 3D?

Where would a 2D minigame programmer fit in your programmer categorisation? "Engine" doesn't really carry the right connotations. Besides, for smaller games one person does the gameplay, graphics, networking, etc., so they don't fit in any pigeon-hole more specific than "programmer".

---
Tags: career, project-management
---


title: Logic in Entity Components Systems

text:
# Question
Title: Logic in Entity Components Systems
I'm making a game that uses an Entity/Component architecture basically a port of Artemis's framework to c++,the problem arises when I try to make a PlayerControllerComponent, my original idea was this.

```
class PlayerControllerComponent: Component {
public:
    virtual void update() = 0;
};

class FpsPlayerControllerComponent: PlayerControllerComponent {
public:
    void update() {
        //handle input
    }
};

```

and have a system that updates PlayerControllerComponents, but I found out that the artemis framework does not look at sub-classes the way I thought it would. So all in all my question here is should I make the framework aware of subclasses or should I add a new Component like object that is used for logic.

# Answer
> 8 votes
Components can have functions. What you want to try to stay away from is having a lot of functionality in them. The functions should be simple things. For example, my inventory component has a function for adding an item to the inventory:

```
public boolean addItem(ItemAttribute item) {
    if (items.size() < maxItems) {
        items.add(item);
        return true;
    }
    return false;
}

```

It's more than a setter function, but doesn't have anything sophisticated. I would leave the function creation up to the individual deploying the framework though. Don't force an update function on them, let them decide what to implement.

Make sure you check out the example games that are on the Artemis site. Those should help you see how components are employed.

Also, check out this answer I gave with Artemis, specifically, in mind.

So with your example. The player control component wouldn't need much data in it at all. Nor functionality. However, simply attaching it to an entity that also had a position would make the `PlayerControlSystem` pick up that component and process the incoming keyboard input. Sometimes you can think of components like flags for systems. The component is really only there so that the system adds that entity to its processing group.

Components should be objects that the system can access. When a system accesses a component it should be able to access its data and whatever simple functionality it has.

There should be a different system for each control type and a different component for each control type. If you want to compress that into a single system or a single component you can, but it'll just end up in a switch statement like described in Sidar's answer.

# Answer
> 1 votes
In my Artemis port it would look something like so:

My component:

```
 class PlayerControllerComponent : public artemis::Component{
       enum PlayerControl{
         TPS,FSP,TD
       };
      public:
       PlayerControl pc;
       PlayerControllerComponent(PlayerControl pc){
         this->pc = pc;
       }

    };

```

And the system would be something like so:

```
class PlayerControlSystem: public artemis::EntityProcessingSystem {

    private:

        artemis::ComponentMapper<PlayerControllerComponent > pcm;

    public:
        PlayerControlSystem() {

            setComponentTypes<PlayerControllerComponent>();
        };

        virtual void begin() {
            //before logic
        }

        virtual void end() {
            //after logic
        }

        virtual void initialize() {
            pcm.init(*world);
        };

        virtual void processEntity(artemis::Entity &e) {

            PlayerControllerComponent & ent = *pcm.get(e);

                   switch(ent.pc)
                   {
                      case TPS:
                        //call internal function for TPS
                       break;
                        case FPS:
                        //call internal function for FPS
                       break;
                          case TD:
                        //call internal function for TD
                       break;

                   };
        };
};

```

I have to admit that I'm still trying to wrap my head around Artemis completely. But since the bitset for components is so specific systems are more 1:1 with components. So this is how I would do it.

# Answer
> 1 votes
Your input component doesn't need any logic. It needs a control scheme since that's going to differ among entities but that's all. The rest should be handled by the system. It's the same as it is for rendering and physics, just detect which entity has the component and act upon it. Putting input handling logic in the component is a dead end because there's only so much it can do before you start creating hacks.

Trying to avoid one switch statement at a cost of creating inheritance chains is a poor decision since you gain absolutely nothing. You need the same logic for handling the input. The switch statement was created for situations like this one, it doesn't make your application less robust. Also adding a new type of control is going to be easier with a switch statement; just add one more case and a function to handle it. Otherwise you're bloating your inheritance chains more and relying on run-time type checking, again, gaining nothing in return.

# Answer
> 1 votes
My suggestion is to use abstract pure virtual class as Interfaces OR template policy. Your system can accept only components that inherit from a specified interface OR that implements template policies. In this way your system will be aware of the fact that your component has an Update function in this way.

you could do something like this:

```
class Test
{
    std::vector<Interface *> items;
    public:

        void AddComponent(T& param)
        {
            items.push_back(&param);
        };

        void Update()
        {
            for (unsigned i = 0; i < items.size(); i++)
                items[i]->Update();
        }
};

```

OR

```
template <class T>
class Test
{
    std::vector<T *> items;
    public:

        void AddComponent(T& param)
        {
            items.push_back(&param);
        };

        void Update()
        {
            for (unsigned i = 0; i < items.size(); i++)
                items[i]->Update();
        }
};

```

The second one does not need the use of the interfaces, however the compiler will not compile the code if T does not implement a public Update function.

# Answer
> 0 votes
I would create the FpsPlayerControllerComponent as a sub-class of Component and create a system which process the entities that contain this component.

If you find you need another PlayerController, say, TpsPlayerController, just create a new subclass of Component and a new system, this way, your code will not need *switchs* or *ifs*.

Systems are generally more generic than that, but I think the controller system can be implemented that way, because you will probably not need FpsPlayerController and TpsPlayerController at the same time.

# Answer
> 0 votes
Logic in these systems? There is almost none. :) After chatting for some time about this problem with other GD.SE users, we came to a conclusion that many of us weren't really convinced by these systems that everyone's an expert with.

The original idea of components in programming was somewhere along these lines:

```
class MyRendererComponent { function MyFunction(){..}; data MyData; };
class MyOtherComponent { function MyOtherFunction(){..}; data MyOtherData; }
class MyEntity { MyRendererComponent C; MyOtherComponent C2; ... };

```

With this approach, components behave any way the entities want them to behave. Put logic into this the same way you'd put it into entities. There might appear to be some redundant glue code in this approach but all things considered, this one actually proves to require less work than any other system.

All of the other approaches are mainly meant for data-driving the engine heavily (enabling entity composition in game editors), which is what most people don't actually need (most don't even have editors). Even GTA3 didn't need it. And I'd most probably be right if I said that you don't have a bigger game in development...

---
Tags: component-based, entity-system
---


# Question
Title: Calculating minimum velocity of the projectile needed to hit target in parabolic arc
If I have a point which I want to hit at the end or during a parabolic arc, how would I calculate the needed x and y velocity?

# Answer
> 15 votes
Parabolic trayectory function is defined as:

```
   Fx = Vox*t + Ox;
   Fy = -0.5 * g * t * t + Voy*t + Oy;

```
* Known values:

```
P: the target point.
O: the origin point.
g: gravity.
t: time needed to impact.

```
* Unknown values:

```
Vo: Initial Velocity

```
* To calculate 'Vo', we can give values to F function :

```
't' = flight time  'duration'
'F' = target point 'P'

      (Px-Ox)
Vox = --------
      duration

      Py + 0.5* g * duration * duration - Oy
Voy = ---------------------------------------
                 duration

```
* You can now get all the values to reach the target from the origin giving values to t into the F equation:

```
 When t = 0         => F == O (Origin)
 When t = duration  => F == P (Target)

```

# Answer
> 12 votes
I recently had to solve a similar problem, i came up with two solutions, based on the formula i found on the wikipedia page 'Dan the Man' already mentioned: Trajectory of a projectile

In this solution you acctually need eitherway the launch angle fixed or the x velocity. Y velocity is not needed as we launch the projectile in a specific angle.

**Solution 1, launch angle is fixed, calculate the velocity:**

```
g = 9.81; // gravity
x = 49; // target x
y = 0; // target y
o = 45; // launch angle
v = (sqrt(g) * sqrt(x) * sqrt((tan(o)*tan(o))+1)) / sqrt(2 * tan(o) - (2 * g * y) / x); // velocity

```

**Solution 2, velocity is fixed, calculate launch angle:**

```
g = 9.81; // gravity
v = 40; // velocity
x = 42; // target x
y = 0; // target y
s = (v * v * v * v) - g * (g * (x * x) + 2 * y * (v * v)); //substitution
o = atan(((v * v) + sqrt(s)) / (g * x)); // launch angle

```

In my case this solutions worked quite well.

# Answer
> 3 votes
If you don't care if it is mathematically correct, only that it looks correct enough, calculate the straight path and make your projectile follow that path, but "push it up" along the normal of that line as a function of it's distance down the line segment, so it rises as it approaches the middle of the segment and falls as it goes away from the middle of the line segment.

You could use a sine wave for this, using the range of degrees from -90 to +90 (where -90 is the left point on the line segment, 90 is right point, and you lerp in the middle), and multiply the result by a constant to scale it up.

If you need the purely correct mathematical / physical answer this won't help. If you don't, this can probably work pretty well for you!

Don't forget, game programming is about using illusions that look correct (and are cheaper to compute), instead of realism.

# Answer
> 2 votes
If you just need something that is just about right and have a fixed velocity you can use this very simplified method.

```
distance = to.x - from.x;
angleToPoint = atan2(to.y - from.y, to.x - from.x);
distanceFactor = 1/1000;
angleCorrection = (PI*0.18) * (distance * distanceFactor);
velocity.X = cos(angleToPoint+angleCorrection) * power;
velocity.Y = sin(angleToPoint+angleCorrection) * power;

```

Distance can be negative but it will still works because the angle depends on the distance too. If the distance is negative the angle that needs to be added is negative too.

You'll need to play around with distanceFactor to find the right value. It depends on the gravity and power of the projectile. It should be near 1 divided through the maximum distance the projectile can cover.

---
Tags: mathematics, algorithm, projectile-physics
---