title: Making Ball Fling in a Curve Direction

text:
# Question
Title: Making Ball Fling in a Curve Direction
I was wondering how to figuring out how to slice a ball (banana kick) by flinging it curve-ways. However, according to the LibGDX's gesture listener, the method for flinging only focuses on a straight direction, whether if the ball went to the left, right, or straight.

```
@Override
public boolean fling(float velocityX, float velocityY, int button)
{
    // Set flag for goal.
    gotPoint = false;
    isBallMissed = true;

    // Set flag to enable scrolling goalkeeper when a player's turn as a goalkeeper.
    isAIKicked = false;

    // Re-adjust ball fling coordinates...
    x = velocityX/25;
    y = (velocityY/25) * -1;

    if(!flingLocked && !gotPoint)
    {
        if(y > 100) // --> Checks if the gling power is just right or else it miss.
        {
            if(y > 130)
            {
                goalpostHit = false;
                crossbarHit = false;
                disableGoal = true;
                meterSpeed = 50f;

            } else {

                goalpostHit = false;
                crossbarHit = true;
                disableGoal = true;
                meterSpeed = 20f;

            }

        } else {

            goalpostHit = true;
            crossbarHit = true;
            disableGoal = false;
            meterSpeed = 3f;

        }
    }

    // Get the value to set the collision on or off.
    bp.setGhostPost(goalpostHit);
    bp.setGhostCrossbar(crossbarHit);

    // For debugging purposes only. Checks if the fling direction of the ball went. (output display console only)
    System.out.println("Hit Post Enabled Status: " + goalpostHit);
    System.out.println("Hit Bar Enabled Status: " + crossbarHit);
    System.out.println("touchUp() at Y: " + y);
    System.out.println("fling() at Y: " + y);
    System.out.println("fling() at X: " + x);

    // For debugging purposes only. Checks if the fling direction of the ball went.
    if(x >= 1)
    {
        directionStatus = "RIGHT";

    } else if(x <= -1) {

        directionStatus = "LEFT";

    } else {

        directionStatus = "FOWARD";

    }

    if(!goalKeeper && !flingLocked && !freezeGame && !isPaused && !gotPoint) // --> Tells is the ball is flinged or not while the player is under kicker role.
    {
        // Play SFX.
        SFX.getBallKicked().play(1f);

        // Set Timer
        timer4 = 0;

        // Set AI's smart level as a goalkeeper
        speedLevel = (rnd.nextInt(175 - 55) + 55);
        isReversed = rnd.nextInt(10);

        // Set mass of a body.
        MassData mass = new MassData();
        mass.mass = 400;

        // Re-create body of the ball.
        wc.getWorld().destroyBody(ballBody);
        ballDef.position.rotate(0f);
        ballDef.angle = 30f;
        ballDef.position.set(rc.getSoccerBallX(), 10);
        ballDef.allowSleep = true;
        ballBody = wc.getWorld().createBody(ballDef);
        ballBody.setActive(true);
        ballBody.applyLinearImpulse(x, y, rc.getSoccerBallX(), 10); // --> Makes the direction go left or right?
        ballBody.applyAngularImpulse(200);
        ballBody.isBullet();
        ballBody.setMassData(mass);
        ballBody.setLinearDamping(-990f); // --> This will set how fast will accelerate the object will fall. Set it to a negative value to increase falling speed.
        ballBody.setGravityScale(0); // --> Set it to negative value and the ball will lift. Set it to a positive value and the ball falls normally.

        // Load the ball.
        ballLoader.attachFixture(ballBody, "soccer ball", ballFixture, rc.getSoccerBallWidth());
        v2.ball_origin = ballLoader.getOrigin("soccer ball", rc.getSoccerBallWidth()).cpy();

        // Disable fling and set timer.
        switchRoleTimer = true;
        flingLocked = true;

        // Action ended per turn.
        if ((noOfTries < 11) && !isSuddenDeathmatch)
        {
            noOfTries++;
        }

        // Disable fling temporarily.
        Gdx.input.setInputProcessor(this);
    }

    return false;
}

```

What can I do to make the ball fling in curve-ways if I fling it curve-ways? Should I make a flag and mathematically computed the coordinates by analyzing the finger in order to recognize the response of this kind of fling? Take note that I'm making a 2D overview of the soccer game.

# Answer
> 3 votes
i didn't read all of your code but if i get it right you want a curve movement.

in linar algebra you can use vector addition for velocity and acceleration of object

lets say :

```
  my_pos = (0,0)

  velocity = (1,3)

  acceleration = (0,-1) //gravity?

  do(lets say  every half a second?)
  {
       to_move_x =velocity.x  + acceleration.x
       to_move_y =velocity.y  + acceleration.y

       my_pos .x += to_move_x
       my_pos .y += to_move_y
   }
   //if (y<0) {y=0} or the object hits ground or solid, stop move loop

```

first loop to move will be(1,2) and my\_pos =(1,2)

second loop to move will be(1,1) and my\_pos =(2,3)

third loop to move will be(1,0) and my\_pos =(3,3)

fourth loop to move will be(1,-1) and my\_pos =(4,2)

which will look like:

```
           (3,3)
             _
 (2,3) ->   /  \<-(4,2)
 (1,2) ->  /    \<-(5,1)

```

and thats a curve.

i hope thats what you looked for.

learn linar algebra it solves stuff like that.its very helpful for game dev (and geometry and trigonometry).

---
Tags: java, mathematics, libgdx, physics, direction
---


# Question
Title: Creating Multiple Instances of a camera at run time
I'm trying to create a bunch of different game objects from a settings file I'm passing in at run time. I've checked and my game is reading in settings fine. But when I run the program, I get the following error:

> ArgumentException: The prefab you want to instantiate is null.

But, I still get two cameras appearing in my scene. So I'm confused as to why this is happening.

Here is the code that is acting on the information received from the settings file:

```
public void CreateCamera()
{

for (int i = 0; i < testCamera.Count; i++)
{

    camera = Instantiate(gameObject.AddComponent<Camera>(), new Vector3(0, 0, 0), Quaternion.identity) as Camera;
    camera.name = testCamera[i].Name;
    camera.near = Convert.ToSingle(testCamera[i].Near);
    camera.far = Convert.ToSingle(testCamera[i].Far);
    camera.aspect = Convert.ToSingle(testCamera[i].AspectRatio);
    camera.fov = Convert.ToSingle(testCamera[i].FOV);
}

}

```

Following this, I also get the following message as well:

> Can't add component 'Camera' to GameObject because such a component is already added to the game object!

Can anyone help me in fixing these issues?

# Answer
> 4 votes
What the error messages are saying is that 1) You can't add a camera to the existing game object because you can only have one camera component per game object (a limitation of Unity) 2) because of 1) the return value of your `AddComponent` is null and therefore 3) `Instantiate` is failing.

Your code doesn't really make any sense because you're trying to add multiple cameras to the same game object. `camera.name` changes the name of the game object the camera is attached to. Components themselves don't have names.

Basically, you don't want to use `Instantiate`. That's specifically for creating instances of prefabs. Just do `new GameObject()` and then add the camera to it. The rest of your code should be the same. E.g.:

```
for (int i = 0; i < testCamera.Count; i++)
{

    var cameraGameObject = new GameObject( testCamera[i].Name );
    var camera = cameraGameObject.AddComponent<Camera>();
    camera.near = Convert.ToSingle(testCamera[i].Near);
    camera.far = Convert.ToSingle(testCamera[i].Far);
    camera.aspect = Convert.ToSingle(testCamera[i].AspectRatio);
    camera.fov = Convert.ToSingle(testCamera[i].FOV);
}

```

(Also you might not want to use the variable name `camera` as it's a property on `MonoBehaviour`s that essentially does `GetComponent<Camera>`. That might be messing you up as well.)

# Answer
> 0 votes
I think you need to create a new instance of Camera at the beginning of your method. It looks like you're using the same camera variable for all instances of the Camera, this is unwise and most likely the issue.

Try:

```
public void CreateCamera()
{
    Camera camera;

    for (int i = 0; i < testCamera.Count; i++)
    {
        camera = new Camera();

        camera = Instantiate(gameObject.AddComponent<Camera>(), new Vector3(0, 0, 0), Quaternion.identity) as Camera;
        camera.name = testCamera[i].Name;
        camera.near = Convert.ToSingle(testCamera[i].Near);
        camera.far = Convert.ToSingle(testCamera[i].Far);
        camera.aspect = Convert.ToSingle(testCamera[i].AspectRatio);
        camera.fov = Convert.ToSingle(testCamera[i].FOV);
    }
}

```

# Answer
> 0 votes
Create a public variable called `CameraPrefab` of `Camera` type in your script, set it equal to `null`. Then in the editor, select the object that has the script you added `CameraPrefab` to.

You'll see your script in the inspector, and the `CameraPrefab` variable with `None (Camera)` as the value.

Drag the camera prefab you want to instantiate onto the `CameraPrefab` variable. You should now see `None (Camera)` replaced with the name of your prefab.

Now when you want to `Instantiate` an instance of that prefab, you just do the following:

```
camera = Instantiate(CameraPrefab, new Vector3(0, 0, 0), Quaternion.identity) as Camera;

```

`Instantiate`(doc) is used to create an instance of a prefab. Essentially a clone of the object.

Using `gameObject.AddComponent<Camera>()` doesn't work because only one camera component per object is allowed.

---
Tags: c#, unity
---


title: Python + Pygame - Collision problems

text:
# Question
Title: Python + Pygame - Collision problems
I'm currently developing a game in Python + Pygame and i came up with a problem with the player and the platforms. The game is a 'runner' where the player it's fixed (The 'x' position isn't variable, only the jump).

This is how i'm currently doing the collisions managment:

```
def collide(self, yvel, platforms):
    for p in platforms:
        if pygame.sprite.collide_rect(self, p):
            if yvel > 0:
                self.rect.bottom = p.rect.top
                self.onGround = True
                self.yvel = 0
            if yvel < 0: self.rect.top = p.rect.bottom

```

'platforms' its a RenderUpdate group with the platforms (a simple sprite).

When the player is falling from a platform and collides with the next platform, not exactly on top of it but a little below, that's when the character jumps to the position shown in the code above, rather than collide and fall. I don't know how to check the left bound without a 'xvel' parameter.

*(The screen shows an example, but the player only changes the y-axis coordinates, the platforms are updating their position)*

I've tried supply a number to a 'xvel' parameter, and check if the character wasn't on the ground (Jumping) and the 'xvel' was greater than 0, but it isn't working at all.

Thanks in advance.

# Answer
> 2 votes
It looks like you're constantly moving the platforms to the left, as you explain, but you're only checking for collisions along the Y axis. So what happens if you fall down a pit? The platforms will continue moving to the left, the collision will register from the right side of your player, and the position will be adjusted back up to the surface of the platform. You need to implement another check that stops the player from moving horizontally in the platforms and resolving back up to the top.

If your world is moving around your character then your character's x velocity will be 0 relative to our view, but when the player collides with a platform either the world has to stop moving or the player has to move *back* to avoid progressing through the platforms. If the world is moving around you then you might just want to make an instant game over condition if you're colliding with the side of an obstacle rather than landing on it, or just stop the movement and let the player fall.

---
Tags: collision-detection, python, pygame, side-scroller, jumping
---


# Question
Title: How can I emulate point sprites in D3D11?
I have points which I pass to a vertex shader and then to a geometry shader, but now I want to get from the geometry shader a "bigger" point. So the point should get a "dadius" like it was possible in Direct3D 9.

Can anyone help me what I have to write in my geometry shader? I actually have the following code, which only passes the point to the pixel shader.

```
void LightGeometryShader( point GeometryInputType input[1], inout PointStream<GeometryInputType> TriStream)
{
    GeometryInputType output;

    for( int i=0; i<1; i++ )
    {
        output.position = input[i].position;
        output.color = input[i].color;
        output.tex = input[i].tex;
        output.viewDirection = input[i].viewDirection;
        TriStream.Append( output );
    }
}

```

# Answer
> 4 votes
You can pass any vertex attributes you want in from IA to the VS, which in turn you can pass to the GS. Create a `radius` attribute in your `InputLayout`. The VS can pass that on to the GS, which in turn can use it to construct a view-aligned circle or a billboard of a circle texture via that radius value. You could also just set it as a uniform if all your point sprites will be of the same size and save on update bandwidth a bit.

There are GDSE articles on billboarding and a ton of information on billboarding online once you get to that part.

---
Tags: c++, shaders, directx11
---


# Question
Title: What is a good "easily" moddable and scriptable 3D game?
I've made a fair number of 2D games (and actually completed/released a few of them). I'm hesitant to move into the 3D realm, because of the order of magnitude (everything takes ~10x more work).

To get started, I was thinking about picking something and modding it. What's a good, "easily" moddable game? By easily, I really mean:

* Most or all of the content can be changed via tools (not code)
* Tools are included, and mature (don't crash much, etc.)
* The game is free or cheap
* The game is scriptable (scripting language or SDK)

I'm not really particular about a target language, although I lean towards something more like C# than JavaScript.

If this is not a "good" question, we can make it a list and community wiki it. I really want to know options to get started in the 3D modding realm.

# Answer
> 6 votes
Roblox is a game scripted in Lua, it's 3D, free (You can pay for virtual money), and has lots of tools. Lua is a very easy language. Roblox is a basically a website, where you make games or play games. There is a shop to customize your avatar and buy gear. The only problem is that mostly everything in the shop is extremely expensive. The games in it can be made with or without Lua. Roblox is made out of blocks, but with ramps and stuff. If you want to check it out, it's www.roblox.com

My second favorite game is Minecraft. It uses java to script. You can make mods for it, but you cannot actually program in-game. You can generate a world randomly, and everything is made out of blocks. The only problem is it's $20 (maybe $30 now that it's out of beta), but I think it is totally worth it. If you want to try it, it's at www.minecraft.net

# Answer
> 0 votes
Although I've never used it personally, I believe The Elder Scroll Construction Set is **incredibly powerful** and lets you change virtually anything in The Elder's Scroll games (as you can probably deduce from the over 25 thousands mods available here). I've seen both Oblivion and Morrowind for sale at 75% off before on Steam (i.e. at 5$ each) although that's not the case right now.

And of course, Half Life and most other Valve games are also extremely moddable. For a more complete coverage of the topic, you might want to start exploring this website though.

# Answer
> 0 votes
I have had a good experience with Bohemia Interactive's ArmA II. Very good support by both the creators and the community. Scripting is particularly well thought-out, with a built-in mission editor that live-reloads your scripts.
I found the vanilla game itself a bit off-putting, though. I feel this is an important aspect to consider when choosing a game to mod. It's easier to create a fun mod when starting with a fun game.

# Answer
> -3 votes
Modding is dead. Don't misinterpret that - modding was originally introduced as a way for people to experiment with virtual worlds without creating them entirely from scratch; many assets made for them, most common game code already in place.

We can now get most of that in free programs entirely built for that purpose, without bothering to having a $50 game surrounding it. Unity3D, Unreal Development Kit, and CryEngine 3 are all examples of open-to-use engines that come with some basic assets, a physics engine, and a number of useful developer tools that don't necessarily need you to program. So when I say "modding is dead", all I mean is that those hobbyists called modders can now just pick a free engine and call themselves "game developers".

Unity supports C# directly. UDK uses its own scripting language, UnrealScript, which I believe is similar to Java in some ways.

---
Tags: 3d, scripting, modding
---


title: How do I take a screenshot and blur it?

text:
# Question
Title: How do I take a screenshot and blur it?
I want to take a screenshot of the game when it's running, blur it and draw it on the screen. Could you help me with taking a screenshot and blurring it?

# Answer
I have no source code to provide you, but I will point you in the correct direction. "Taking a Picture" is a simple task when rendering a game, you simply need to make a copy of the back buffer before it is swapped at the end of the render stage of your game loop.

If you then want to blur it, you will need to filter your image using one of many blur functions and a convolution matrix. This is typically done as a post processing step in engines, and it involves rendering a quad the size of the screen to a texture, while sampling the original back buffer image as an input.

A note here, this isn't a trivial thing unless you have sufficient experience with your rendering pipeline, and it would be far too much code to simply demonstrate the entire process.

Here is a link to the theory behind a Gaussian filter, and how it can be used to produce a blurred/smoothed image in the general context of computer vision.

http://homepages.inf.ed.ac.uk/rbf/HIPR2/gsmooth.htm
> 9 votes

# Answer
I managed to do what I've wanted with this. Code:

```
bool prepareToPause, first, drawn, blurredReady;
Texture2D pausedScreenshot, blurredPauseScreenshot;
RenderTarget2D renderTarget;
enum GameState
        {
            MainMenu,
            Playing,
            Paused
        };
const int BLUR_RADIUS = 7;
const float BLUR_AMOUNT = 2.0f;
GaussianBlur gaussianBlur;
int renderTargetWidth, renderTargetHeight;
RenderTarget2D renderTarget1, renderTarget2;

protected override void LoadContent()
    {
        //
        gaussianBlur = new GaussianBlur(this);
        gaussianBlur.ComputeKernel(BLUR_RADIUS, BLUR_AMOUNT);
        //

        renderTarget = new RenderTarget2D(
            GraphicsDevice,
            (int)graphicsDeviceManager.PreferredBackBufferWidth,
            (int)graphicsDeviceManager.PreferredBackBufferHeight);
        currentGameState = GameState.MainMenu;
    }

private void InitRenderTargets()
        {
            renderTargetWidth = pausedScreenshot.Width / 2;
            renderTargetHeight = pausedScreenshot.Height / 2;

            renderTarget1 = new RenderTarget2D(GraphicsDevice,
                renderTargetWidth, renderTargetHeight, false,
                GraphicsDevice.PresentationParameters.BackBufferFormat,
                DepthFormat.None);

            renderTarget2 = new RenderTarget2D(GraphicsDevice,
                renderTargetWidth, renderTargetHeight, false,
                GraphicsDevice.PresentationParameters.BackBufferFormat,
                DepthFormat.None);

            gaussianBlur.ComputeOffsets(renderTargetWidth, renderTargetHeight);
        }

protected override void Draw(GameTime gameTime)
        {
            if (prepareToPause && !first)
            {
                GraphicsDevice.SetRenderTarget(renderTarget);
                drawn = true;
                GraphicsDevice.Clear(Color.Black);
            }
            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);

            if (currentGameState == GameState.Playing)
            {
                [...]
                if (mouseRectangle.Intersects(nextWaveRectangle) && mouseState.RightButton == ButtonState.Pressed)
                    prepareToPause = true;
            }

            if (prepareToPause && !first && drawn)
            {

                pausedScreenshot = renderTarget;
                GraphicsDevice.SetRenderTarget(null);
                currentGameState = GameState.Paused;
            }
            spriteBatch.End();

            if (!first && drawn && currentGameState == GameState.Paused)
            {
                InitRenderTargets();
                blurredPauseScreenshot = gaussianBlur.PerformGaussianBlur(pausedScreenshot, renderTarget1, renderTarget2, spriteBatch);
                blurRectangle = new Rectangle(0, 0, pausedScreenshot.Width, pausedScreenshot.Height);

                prepareToPause = false;
                blurredReady = true;
                first = true;
            }

            if(blurredReady)
            {
                spriteBatch.Begin();
                spriteBatch.Draw(blurredPauseScreenshot, blurRectangle, Color.White);
                spriteBatch.End();
            }

            base.Draw(gameTime);
        }

```

I've probably made many errors but it's working and that's important for me at this point of my game development. Criticism and suggestions are welcome.
> 0 votes

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


# Question
Title: Windows wchar_t to char conversion errors
I have been following this code from "Introduction to 3D Game Programming with Directx 10" and I am typing out the main class. While I was typing I noticed a few errors. I tryed googling them but there were no results. So I ask you if you can help me.

The code:

```
    HR(md3dDevice->CreateTexture2D(&depthStencilDesc, 0, &mDepthStencilBuffer));
    HR(md3dDevice->CreateDepthStencilView(mDepthStencilBuffer, 0,  &mDepthStencilView));
    HR(mSwapChain->ResizeBuffers(1, mClientWidth, mClientHeight, DXGI_FORMAT_R8G8B8A8_UNORM, 0));

```

where the error is: "argument type 'const wchar\_t\*' is incompatible with parameter of 'const char\*'"

and

```
 wcscpy(fontDesc.FaceName, L"Times New Roman");

```

where the error is: "argument of type 'CHAR\*' is incompatible with parameter of type 'wchar\_t\*'" **EDIT:** The error is at `fontDesc.FaceName`

# Answer
As noted in the comments, this isn't strictly a gamedev question, but it was easy to answer. Assuming you're using Visual Studio, you need to enable Unicode in the project settings:

Make sure "All Configurations" and "All Platforms" are selected, then under the "General" tab, select "Use Unicode Character Set" as shown. Then rebuild the solution and those errors should go away.
> 0 votes

---
Tags: windows
---


# Question
Title: Throttling MonoGame actions (explosions, sounds, etc)
I'm trying to find a way to deal with throttling/managing actions that need to happen on a regular (regulated) basis.

Right now, if I want to throttle an "action" in MonoGame I need to setup a "timer".

Let's say I want to spawn a bunch of explosions during the update loop, but I don't want to spam them. I would setup a variable to track the countdown to the next time I can spawn an explosion, and another variable for the time between:

```
public override void Update(GameTime gameTime)
{
    // ExplosionTimer is a class variable, defaulted to 0
    // ExplosionTimerMax is a class variable set to something like 1000 milliseconds
    ExplosionTimer += elapsedGameTime;

    if (ExplosionTimer >= ExplosionTimerMax)
    {
        // Perform actions
        ExplosionSound.Play();
        SpawnExplosion();

        // Reset the timer
        ExplosionTimer = 0;
    }

    // Other update code
    ...
}

```

This is pretty easy to setup and straightforward, but is there a better way? If I need to setup 5 different timers, that means I need to define 10 variables, increment them all, run checks for their state, and reset them if needed.

# Answer
> 1 votes
What you want to be able to do, is script game events. And I'm using *script* in the loosest possible way. The way I prefer to do this is using an "Event" or some other asynchronous construct to communicate things between systems. I like to do this because it limits the coupling between systems.

Lets use the "Set of a lot of explosions" concept.

Something happens in your game, and you now want to fire off 5 explosions (using the FireExplosion event) over a 3 second period. and you want these explosions to be placed randomly within a specified area (2D Rect). The game logic builds up a "Event" which contains this information and flicks it in the general direction of your "Scripted Sequence" system.

The Scripted Sequence system grabs the event when it updates next, and queues up 5 "FireExplosion" events, evenly spaced in time across the 3 second period, with the desired "2D Rect" payload data.

Each frame, your Scripted Sequence System will check to see if any events need to be raised to the Game. If there are, it then generates the required events (In our case the FireExplosion event), assigns the payload and flicks it into the Game's Event queue for processing on the next update. Next frame, It'll check to see if anything's ready to go, and so on. Eventually, this system will raise 5 events over 3 seconds as requested!.

The Game, on its next update, duly processes the queue of incoming events, and sets up an Explosion, as requested by the incoming FireExplosion Event..

This is a neat paradigm to use for a few reasons.

1. If you're using a networked game you can sync up things to happen at specific points in time in the future. Useful for "End Of Game" events and what not.
2. It also means you can record what goes through this system and play it back at any point. giving you a neat way to setup repeatable tests.
3. You can easily expand on it to do simple cutscenes.
4. Or even implement a proper scripting language to respond to in game events!

# Answer
> 1 votes
I usually create a class called a DelayedAction like this:

```
public class DelayedAction : IUpdatable
{
    public DelayedAction(Action action, float delay)
    {
        TimeRemaining = delay;
        Action = action;
    }

    public Action Action { get; private set; }
    public float Delay { get; private set; }
    public float TimeRemaining { get; private set; }

    public bool Update(float deltaTime)
    {
        TimeRemaining -= deltaTime;

        if (TimeRemaining <= 0)
        {
            Action();
            return false;
        }

        return true;
    }
}

```

Then I add everything that implements the IUpdatable interface to a list:

```
_updatables.Add(new DelayedAction(PlaySound, 1.0f));

```

That gets executed in a loop in the update method, and removed if it returns false:

```
foreach(var updatable in _updatables.ToArray())
{
    if(!updatable.Update(deltaTime))
         _updatables.Remove(updatable);
}

```

It's a little more complicated than that for optimization reasons, but the above implementation should work.

Obviously, the action that gets fired can either just play the sound, or you can use it to spawn a new one like the code in your question. You can also queue up a bunch of things with different delays for various effects.

```
_updatables.Add(new DelayedAction(PlaySound, 1.0f));
_updatables.Add(new DelayedAction(PlaySound, 2.0f));

```

---
Tags: xna, performance, monogame
---


# Question
Title: Which is the right way to build a OpenGL Projection Matrix
This time I'm trying to learn the core of matrix transformations. I dont like the idea to using a Math library and dont understand what is hapening on background, because this I'm having some dificulties with Projection Matrix. I've read many tutorials that explain how Projection Matrices show be and what they do. But at this moment I got two different Projection Matrices and I dont know which should I use.

Look at this, frist from this tutorial:

```
private float near = 0.1f;
private float far = 100.0f;
private float fov = (float)Math.toRadians(45.0);
private float aspect = (float) 400 / (float) 300;

private float f = (float)Math.tan(fov / 2.0f) * near;
private float Sx = (2.0f * near) / (f * aspect + f * aspect);
private float Sy = near / f;
private float Sz = -(far + near) / (far - near);
private float Pz = -(2.0f * far * near) / (far - near);

projection = new Matrix4f(new float[]{
        Sx,   0.0f, 0.0f, 0.0f,
        0.0f, Sy,   0.0f, 0.0f,
        0.0f, 0.0f, Sz,   -1.0f,
        0.0f, 0.f,  Pz,   0.0f,
    });

```

Now look this second, from this tutorial:

```
private float near = 0.1f;
private float far = 100.0f;
private float fov = (float)Math.toRadians(45.0);
private float aspect = (float) 400 / (float) 300;

private float f = 1.0f / (float)Math.tan(fov / 2.0f);
private float Sx = f / aspect;
private float Sy = f;
private float Sz = -(far+near) / (far-near);
private float Pz = -(2.0f * near * far) / (far – near);

projection = new Matrix4f(new float[]{
        Sx,   0.0f, 0.0f, 0.0f,
        0.0f, Sy,   0.0f, 0.0f,
        0.0f, 0.0f, Sz,   -1.0f,
        0.0f, 0.f,  Pz,   0.0f,
    });

```

So, which is correct? Or if both are correct, there is some recommendations? I think the second one is more easy to read.

**P.S.:** In my code i'm using Right Handed System and Column-Major Matrices.

Thanks for your attention!

# Answer
> 2 votes
They are both correct and are mathematically equivalent - they should generate the same numerical values (up to some roundoff error). As you say, the second one is easier to read (and is a direct transcription of the matrix in the gluPerspective doc page). In the first one, the calculation of `Sx` and `Sy` isn't completely simplified: the factors of `near` should be canceled out since it appears in both numerator and denominator. It shouldn't affect the correctness but it is doing unnecessary work.

---
Tags: opengl, mathematics, projection
---


# Question
Title: How can I minimize the chances of my game getting pirated?
I am planning to make a small game in the near future. How can I minimize the chances of it being pirated?

# Answer
Make the distribution of your game as simple as possible and release frequent updates (with free new content)

eg. Angry Birds on the iPhone. Even if somebody pirates the game first, he might decide to buy it just because of the auto update function. (+ the new free content will give a feeling of getting much more for the money and that you are a decent developer)

On the PC I would use steam. It is great for small developers and the only distribution path more convenient than pirating.

Pricing is far less important in my opinion. A game for 9.99$ on steam will be bought far more often than one for 7$ on a private homepage.

And most importantly: don't focus on the pirates and potential losses. Concentrate instead on the paying customers, quality, and increasing the revenue.
> 51 votes

# Answer
Copy protection is useless. Whatever you do, it will be cracked because your product will be in the hands of the bad guys. The only people you will be inconveniencing are the people who purchased your product (look at what happened to Spore).

Besides, pirates are usually the people that buy the most. The best you can do is make your product reasonably priced, don't piss off the consumer, make a good product, and make it accessible (steam, app stores, etc). Last one is very important. People pirate cause its hard or inconvenient to get it legitimately.
> 51 votes

# Answer
Your game will be cracked, and it will be pirated. Having said that... Keeping the pirates at bay is an old article about an old game for an old system, but it still makes for interesting reading, and may give you some ideas to keep a game 'uncracked' for a little while.

This article also covers the basics of obfuscating function calls in c/c++.
> 16 votes

# Answer
Just to add two minor points to others' answers:

First, another reason why your game WILL be pirated is that pirates' resources are greater than yours. Maybe there are a dozen people trying to crack your game, for every one person on your dev team assigned to the task of "copy protection." You just cannot compete on man-hours.

Second, even professional big-budget AAA games get cracked, often within a week or two of release. For major titles, that may be worth the extra expense: an extra week of sales for a million-plus seller is big money, easy to justify spending a few tens of thousands -- not to keep pirates out for good, but to buy an extra few days of release sales. If your game is more modest in budget, and you don't expect to make the majority of your sales on release day, it's probably not a good use of your time from a pure cost/benefit analysis.

Third, remember that SOME people pirate because the company doesn't release a demo, and they're using this as a "try-before-you-buy" approach. It doesn't matter what you think of this practice ethically, but if you release a reasonable gameplay demo that serves this purpose, you will at least cut out one chunk of piracy.
> 12 votes

# Answer
As others have stated, once your game is out, it really does not matter if they have the source code or not; it will get cracked. However, you can do a lot to make sure it doesn't burn you.

The first recommendation I have is for you to **make it easier to purchase/download the game than for a pirate to torrent and crack it**. For example, steam makes it very easy for me to buy a game, so much so that it takes far less effort to buy a game than to crack it. Therefore, if you make your paying customers jump through hoops to play your game, by putting in some crazy DRM or registration system, you could be shooting yourself in the foot.

Another thing to consider is that **you should not think about pirates as lost sales**. These people may never have bought your game even if no crack existed. But more importantly, they may actually be helping spread the word about your game to people who may not even know about it. Their friends wont necessarily pirate the game. Also, some pirates may enjoy your game enough to actually consider buying it.
> 11 votes

# Answer
Here's my position on piracy and copy protection, from the standpoint of an end user:

* **You can't eliminate piracy.** Pirates will eventually defeat any anti-piracy feature included in any game. As such, the only situation where DRM will be effective is against casual users trying to make copies for the purpose of distribution to friends or otherwise, without the specific intention to crack a protection system.
    + A corollary of this is that **attempting to stop more complex attempts to illegally copy content is useless**. Therefore, using advanced techniques beyond what is needed to prevent casual attempts to copy the content is wasted effort and is likely to interfere with the experience of legitimate users. A simple DRM system that only aims to block casual copying attempts is the most that can be considered useful. Alternatively, consider not including any DRM at all.
* **Ensure that you do not disrupt the experience of legitimate users.** This includes installing any low-level software for the purpose of implementing DRM, as this can interfere with the performance of users' computers. Doing so would only worsen piracy and decrease the perceived value of the game. Using only a simple DRM system, or not using one at all, can minimize disruption to legitimate users.
* If a non-genuine copy is detected, **limit functionality to that of a demo, but do not interfere with play otherwise.** Many games are designed to covertly disrupt gameplay, such as adding enemies that cannot be defeated, upon detecting that the game is non-genuine. While this can makes pirates less likely to attempt to crack the game, this can confuse users and cause frustration. Instead, notify the user that this copy of the game appears to be non-genuine and and limit functionality to that of a demo. Do not interfere with gameplay in the demo sections, and display a screen at the end of this content similar to that of a normal demo version of the game. This will reduce frustration by making it clear that the game is non-genuine and give players a chance to experience part of the game to encourage buying a genuine copy.

---

In any case, the best way to encourage purchases of genuine copies is to **ensure that the value of the content justifies the cost of the game**, *both in terms of money and the amount of effort required to obtain a genuine copy*. Piracy simply cannot be eliminated.
> 6 votes

# Answer
If you want to add some protection (so only the people who are willing to at least hit google a bit can get your game without paying you) make sure to make it fun.

Add optional community features which require internet or link it to physical goods.

Remember the nifty monkey island pirate wheel? A pirated copy was actually less fun (no pirate game) or more work (search the copied data) than a bought one.

An example: If your game should run offline (yes, I think it should), you could add a physical ID card which is needed to unlock the higher levels. On that you encode name and ID of the buyer over and over again to generate diffent data, a fraction of which the buyer has to type in when accessing the higher levels. This would work with an espionage game (the information could be a list of false IDs). Encoding the real information in the cards makes it less likely that people post their cards online. Once someone buys the game, you send him/her the card.
> 4 votes

# Answer
The most effective type of DRM is to make sure that at least one part of the game is not actually included with the installer and cannot be duplicated by pirates. For example, have all the maps be stored on a server which you maintain and downloaded when the user runs the game. You can make this somewhat more effective by making users sign in with a username and password before the game can download this content.

However, then the game won't run without an Internet connection and you have to maintain the server and pay for this bandwidth. In addition, even this can easily be defeated by a determined pirate.

In fact, almost all traditional DRM methods don't work. The best you could hope for is making it too inconvenient to pirate the game, so it's not worth the trouble.

There is a lot to be said for the honor system. Sure, you end up with some piracy, but there are plenty of businesses (GoG.com, Wolfire, 2DBoy, etc.) which have been very profitable without using any form of DRM.
> 3 votes

# Answer
Host it online.

No downloads, no pirates. Have you ever heard of somebody downloading a pirate copy of farmville? =)
> 3 votes

# Answer
All can be pirated. Yet though you can stop a big amount of more newbie people using certain sofwtare like Asprotect or ExeCryptor. But keeping a glance on if it lowers too much performance, specially at initial load.
> 1 votes

# Answer
I recommend implementing AOE III's method of anti-piracy.

---

# Part 1

**(doesn't work!)**

When you buy the game, they give you serial codes (the old school, serial codes). Obviously, only after you input the codes, you can play the game. Now, there's a problem with this method. The ever wretched crack. If you can crack it you can play it.

# Part 2

**(works!)**

Now that the hacker cracked the game, **they can play it, but only to a certain degree.** You can't play online without having to re-input your serial codes to make a username & password. But here's the gist, it contacts the servers and checks if the serial code has been used yet!

If AOE III would have used "Part 2" from the beginning of installation, the problem would be solved! **No playing the game without contacting the servers.** This of course can be a slight problem to some players that don't have internet.
> 1 votes

# Answer
If your a small company don't bother with DRM or copy protection, or if you do just make it a very token attempt.

While personally I don't agree with people calling DRM totally useless because it gets cracked (I do agree that all forms of DRM short of online streaming will be cracked). Financially DRM probably does make sense for large companies, just because those games do get cracked doesn't mean there isn't enough inconvertible to people who are not that competent when it comes to pirating (this can inhibit school yard/soccer mom piracy), or impatient to wait for a crack.

That horrible highly invasive always online DRM for example takes weeks or even months to get cracked as they encrypt the game content with various different keys requiring people to play through them inorder to unlock all the keys. For most major games a majority of their sales are likely to be right after release. Although I think companies selling that stuff should release a DRM removal patch after a few months of being released.

But a small/indie company doesn't have the same business model.

Firstly you require your customers to be happy (large companies don't, they own established brands that you can get elsewhere and they are the only ones that can afford to spend millions of dollars on making highend games). Small companies rely on word of mouth. DRM is bad PR, people hate it. It can only be a bad thing for a consumer (unless you buy into the idea that more games sold end up with games being cheaper as a result but I doubt companies pass on the savings, that charge what they can get away with as they always have). The customers who buy indie games are normally willing to pay to help small devs also tend to be very anti-drm. Form a bond with your community.

Secondly most indie games lack the massive hype that big AAA games can afford to buy. They will probably have a much flatter sales curve, it might start low and go up as word of mouth spreads or otherwise if you don't get word of mouth you will just get a somewhat constant rate of sales trickling along.

Thirdly you just don't have the resources to implement DRM. You either have to code in a hole bunch of copy protection things or pay for an off the self solution. If you do use some kind of DRM just make it the most basic version possible.

For a small game Piracy might actually boost sales. People will tend to pay more attention to something hitting a release site that one of the 10,000 $2 games for sale in some app store.

The best thing you can do to stop piracy is to add online services. Either post frequent updates online, that add new stuff not just fixing minor bugs. Require an online username/password linked to the game purchase/key to start the game (but preferably with some purpose other than requring the login). Add multiplayer, ensure that the server code verifys a game/useraccount is legit with a central authority server. Have a game browser (Gamespy style) that pull in the games from the server. Multiplayer will only help stop piracy if the multiplayer is a big focus of your game. Multiplayer can be cracked but it's generally going to have much less players and more cheats. Allow users to create game content/mods and share it with each other through some site/integrated ingame thing. You can host the servers yourself and ensure the client doesn't have the server code, this is what MMORPGs do, I wouldn't advise it for non 'massive' games.

Another thing you can do is sell through Steam. People love Steam. People love steam sales. You could also try getting into the next Humble Indie Bundle if you make it cross platform.

Sell your game cheap. People will buy a legit copy of a game if its only $5 (unless it looks really basic like a tetris clone), $10 if it seems like a fairly solid game (decent 3D graphics, gameplay, etc...). The problem is what people are willing to pay and what is worth it for the game developers don't necessarily line up but there will be a price point where people who would have pirated it or passed it over will buy, you might make more money selling for less.

Just accept piracy. There is a whole bunch of talk that if you make a really good game then people will buy it to support you rather than hitting a torrent site. Maybe that's true for a small % of the community but pirates don't go by how much they enjoy a game. I doubt Minecraft would have sold as well as it did if it wasn't for the online portion.
> 1 votes

# Answer
Create an online game where most of the game runs on the server.

To pirate your game, players need to create their own server. This means they either have to break into your network and steal your software or create a clone of your whole server software.

Both scenarios aren't that unlikely: They already happened to various companies.

About how to prevent server break-ins, consult http://security.stackexchange.com and http://serverfault.com

When there is a popular online game, there is often a project to clone the server. But such a project usually takes years before it can offer a game experience comparable to yours, so you have plenty of time to attack them legally or put more resources into developing your server than they can put into development of their clone, so you will always be ahead of them.

But please resist the temptation of doing it like a certain publisher *cough EA cough* and create a game which is actually completely client-sided and single-player, but got a pseudo server-component tagged on just so you can prevent piracy *cough Sim City cough*.

1. your players will hate you, because it's obvious that the online features are only in your interest and not in theirs
2. your server component won't be doing much, so the amateur coders won't take long to replicate its functionality
> 1 votes

---
Tags: game-industry, piracy
---


# Question
Title: Unable to create suitable graphics device?
I've been following the Eye of the Dragon tutorial, which is basicly a guide to making a 2D RPG game, **obviously**.

I recently finished the tutorial about making pop up screens in the menu and changed the screen to load as a full screen.

Whenever I try and load the game it just goes black and my mouse sits there. I cannot change out of it other then with `Ctrl``Alt``Del`. Once i do that it says **No suitable graphics card found, unable to create graphics device**.

I read somewhere about XNA not allowing more then one screen when any one of them is **full screen**. but it wasnt very informative. Anyone have any ideas whats going on and/or how to fix this?

Just incase if this helps this is the code for the graphics device:

```
public Game1()
{
    graphics = new GraphicsDeviceManager(this);
    graphics.PreferredBackBufferWidth = 900;
    graphics.PreferredBackBufferHeight = 768;
    graphics.IsFullScreen = true;
    this.Window.Title = "Eyes of the Dragon";
    Content.RootDirectory = "Content";
}

```

# Answer
> 1 votes
Are you sure your resolution is right and supported by both your graphics card and your monitor? To me it sounds like that's not the case.

What happens if you pick 1024x768? You can't just pick any (fullscreen) resolution you want and expect it to work.

If you need such an odd resolution for whatever reason, use transformations to properly scale the output.

Some cards might be able to still properly transform/scale this through drivers. E.g. Nvidia cards got a setting for upscaling (whether it's done by the monitor or graphics card). If it's done by the card, I think it will accept pretty much any resolution (which doesn't mean you should do it).

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


title: Black borders in Andengine

text:
# Question
Title: Black borders in Andengine
I am using Andengine and when I start the examples there are black borders on left and right of the screen. Like this:

```
10000001
10000001
10000001

```

where 1 is black and 0 is not black. On my phone (Google Nexus 4) it is always. In emulator sometimes. it is in all examples from here: https://github.com/nicolasgramlich/AndEngineExamples

What is causing this?

# Answer
> 2 votes
Most likely this is because of the ResolutionPolicy you defined. For example if you choose the RatioResolutionPolicy AndEngine will try to keep the same width/height ratio, even if the real device resolutions vary. If you have a screen that is wider than the ratio allows, it will show the mentioned black bars.

You can find all the resolution policies in the GitHub Folder

Consider using CroppedResolutionPolicy that stretches the image beyond the borders and instead of black bars, you will get a bit of your screen cropped. The linked class will also give you two methods to find out how much was cropped.

---
Tags: andengine
---


title: Multiple viewpoints in Unity3D?

text:
# Question
Title: Multiple viewpoints in Unity3D?
I'm working on a 3D game in Unity. The primary view is a top-down view, but I am also looking to do target profiles that are true animated versions that reflect the actions of the target. The easiest way to do this, as far as I can see, is to create a second camera, a set offset from my target, facing at it. But how do I show the view from that camera in a small area of the screen?

A possibly related question - how to handle a mini-map? I considered doing this the same way - with a camera fixed high above the character that would show the area around him, but there may be a better way to do this, I'm open to any suggestions.

# Answer
> 4 votes
You're right about creating a second camera, it should work for this purpose (and for minimap as well), you just need to pay attention to its settings:

* **Normalized View Port Rect** \- use this to set up position and size of the second (third, etc.) camera's rectangle on the screen, all numbers are relative coordinates \[0..1\]. For example X=0.0, Y=0.8, W=0.2, H=0.2 will render this camera's viewport in the upper left corner.
* **Depth** \- should be some value larger than the main camera's, in order to render everything on top of the main picture.
* **Culling Mask** \- may be useful for rendering a minimap. For example, you could assign your level's meshes to some layer, say, "Terrain", and set camera's Culling Mask to render only this layer and ignore all characters and other objects. Or, you could create a smaller and simplified copy of the terrain specifically for minimap purposes, assign it to layer "Minimap", set minimap camera to render only this layer and set all other cameras to ignore it.
* **Clear Flags** \- depending on your needs, for example "Don't Clear" can be used to render a non-rectangular image (like I did here with a round minimap).

# Answer
> 3 votes
The usual way to do this is to use a RenderTexture. You point the camera to a render texture target and that texture updates with whatever the camera sees. This requires Unity Pro. There is an example project here: http://blog.almostlogical.com/2009/12/11/render-to-texture-unity3d/

Barring that, you can set up the second camera to render to a portion of the screen using the `rect` parameter and set it to a higher `depth` so it renders in that corner of the screen and after the primary camera. See the reference here: http://docs.unity3d.com/Documentation/ScriptReference/Camera.html

---
Tags: unity, camera, viewport
---


title: AndEngine Box2d game

text:
# Question
Title: AndEngine Box2d game
I'm developing a 2d survival shooter using Box2d extension and I've got some questions:

1. I have two AnalogOnScreenControls. Their listeners modify both sprites and bodies. I receive `TouchEventPool was exhausted` and as their number grows the game crashes accidently. I've tried to put the modification of the bodies and sprites on the UpdateThread but that does not solve the problem. What could be the cause?
2. I have a class that at the beginnig of the game loads all the textures. After I relaunch the game activity several times I receive `Unable to find Phys Addr for` and "green color" interface. But that doesn't happen if I clear the memory manually through the Task Manager before relaunch What could be the cause? I unload my atlas at the end of the game.
3. The game sometimes crashes at start with NullPointerException in onResumeGame. The solution suggested is to set android:configChanges="orientation|screenSize" but my device is API 10 so it doesn't have screenSize property and orientation only does not seem to help, because the game starts in portrait mode at times (though landscape is set in the code)

# Answer
1. `TouchEventPool was exhausted` this is perfectly normal, don't worry about it. AndEngine allocates touch events when needed. This should not happen all the time though. Make sure you are not "saving" the events into some array or something like that.
2. You probably load your textures over and over again. It's impossible to tell, but I guess your activity is not destroyed (e.g. when you press home) and when you relaunch the game, textures are loaded again.
3. This is probably a bug in your code :)
> 2 votes

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


# Question
Title: AndEngine GLES2 - getting Black screen on emulator 4.1
I'm new in andengine . I create following code

```
public class MainActivity extends BaseGameActivity {

static final int CAMERA_WIDTH = 800;
static final int CAMERA_HEIGHT = 480;

public Font mFont;
public Camera mCamera;

//A reference to the current scene
public Scene mCurrentScene;
public static BaseActivity instance;

public EngineOptions onCreateEngineOptions() {
    instance = this;
    mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);

    return new EngineOptions(true, ScreenOrientation.LANDSCAPE_SENSOR, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), mCamera);
}

@Override
public void onCreateResources(OnCreateResourcesCallback arg0)
        throws Exception {

    mFont = FontFactory.create(this.getFontManager(),this.getTextureManager(), 256, 256,Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 32);
            mFont.load();
}

@Override
public void onCreateScene(OnCreateSceneCallback arg0) throws Exception {

    mEngine.registerUpdateHandler(new FPSLogger());
    mCurrentScene = new Scene();
    Log.v("Scene","enter");
            mCurrentScene.setBackground(new Background(0.09804f, 0.7274f, 0.8f));
 //             return mCurrentScene;

}

@Override
public void onPopulateScene(Scene arg0, OnPopulateSceneCallback arg1)
        throws Exception {
    // TODO Auto-generated method stub

}

 }

```

I got code on sites there is returning scene but in AndEngine GLES2 in method onCreateScene() there is no return scene ... so my First run is BLACK .. any suggestion :)

# Answer
> 1 votes
The definitive answer is that the OpenGL APIs are not implemented on the emulator. Essentially, the OpenGL interface is just a big method stub that does nothing. That means any app that uses OpenGL for rendering will not display on the emulator.

So, yes, use a phone directly to test your application.

# Answer
> 0 votes
I've already dumped by AndEngine just like you. I copied the source code from the website, struggled with F5 button during 2 hours. And at last, I found that AndEngine GLES2 DIDN'T work in EMULATOR, in a youtube video of AndEngine's author :D.

Just plug your real Android phone and it'll work.

# Answer
> 0 votes
I had the same problem as you, the `onCreateScene` method was void.

Check this post, he is using a callback function to initialize the scene.

# Answer
> 0 votes
Currently the emulator supports OpenGL ES 2.0 and you can run AndEngine apps in it. The latest emulator also allows you to use your graphics hardware. In combination with Intel HAXM driver and the latest Intel Atom images for Android 4+ and 2.3+ this makes the emulator much faster on Intel machines.

---
Tags: android, andengine
---


title: Keeping everything within one Activity

text:
# Question
Title: Keeping everything within one Activity
**Overview**

My game is currently based on a single activity (rather than multiple activities) and I would like to keep it that way.

At the moment, it goes straight into the game at level 1. I will shortly be adding an options menu and another 20 or so levels. (As well as a high-score screen, help screen etc).

The thing I'm not sure about is, how do I tell the app/renderer what screen/part of the game to render?

It's an openGL ES 2.0 app so at the moment, the method I have in my mind is something like this:

**Code Snippets**

```
int level = 0;  //0 means menu, 1 means level 1 etc

```

in onDrawFrame(); have something like this:

```
@Override
public void onDrawFrame(GL10 gl) {

switch (level){

case 0:renderMenu();break;
case 1:renderLevel1();break
case 2............

```

And so on.

I would also do the same with the logic updating.

Is this the way to go? I'm just not sure it's very efficient but I can't really see what the alternatives are - another way I was looking into was having a separate GLRenderer for each 'screen / level' but this seems much more over-kill.

Would appreciate some guidance as to how to display the correct screen / level at the right time.

**Edit** This is the current structure of my code:

**Activity class**

```
public class MainActivity extends Activity {

//Various pieces of code here

    class MyGLSurfaceView extends GLSurfaceView {

    //Various pieces of code here

    @Override
    public boolean onTouchEvent(MotionEvent event) {

    //Touch events handles here

}

```

**GL Renderer class**

```
onDrawFrame(){

    render();
    update();
}

```

# Answer
You are asking for a concept of **scenes inside one activity**. This is as easy as creating an abstract scene or an interface that will have methods like `renderMe()` and `onUpdate(long timeElapsed)`. Then in your *engine* or *game-loop* you simply render the current scene. How do you switch between scenes is upto you. You can have a governing class `SceneManager`. So how is this gonna work?

**Scene concept:**

```
interface Scene {
  void renderMe(); // do the graphics rendering
  onUpdate(long timeElapsed); // update positions etc
  onTouch(MotionEvent e); // handle user input
}

class MyScene implements Scene {
  // implement rendering and update methods, you can pass in the activity and GLSurfaceView (in constructor or some injection)
}

```

Your **game loop** should look like this:

```
void loop() {
  while(running) {
    long timeStampBegin = getCurrentTime();
    SceneManager.getInstance().getCurrentScene().renderMe();
    SceneManager.getInstance().getCurrentScene().onUpdate(getCurrentTime() - timeStampBegin);
  }
}

```

And then when you switch your scenes by calling `SceneManager.setCurrentScene()`, your loop will just start rendering something else. `SceneManager` can be a singleton class or simply a class with static reference to the scene.

**SceneManager concept** (singleton):

```
class SceneManager {

  private static SceneManager INSTANCE = new SceneManager();

  private Scene currentScene;

  public static SceneManager getInstance() {
    return INSTANCE;
  }

  public Scene getCurrentScene() {
    return currentScene;
  }

  public void setCurrentScene(Scene scene) {
    currentScene = scene;
  }
}

```

You also have to implement the `onTouchEvent` in `GLSurfaceView` and pass the event to your scene to be able to handle touch events. This happens in separate thread, so it is not part of your loop.

This should be enough to create skeleton one-activity-multiple-scene model.
> 5 votes

---
Tags: android, rendering, opengl-es2, logic, levels
---


# Question
Title: How to check whether a ray cast hits a specific side of an object?
I am using Ogre3d to develop a 3d simulation/game. One task is to determine whether the user has focused the camera on a specific object. So I cast a ray from the camera to what is currently in the center of the screen. This check works fine, I can determine which object is currently in the focus (i.e. centered on the screen).

However, I also need to determine **which side** of this object is in focus (i.e. centered on the screen). So, for example, when I have a model/object of a human standing on the ground, I need to determine whether the user looks at this model from the front or from the back.

How can I determine which side of an object is currently in the focus of the camera?

# Answer
> 5 votes
Writing up an answer from my comments as I believe it's not such a crazy idea after all.

## Assumptions

* The "Up" direction should not matter in these calculations
* You have found the object in focus and you can ray cast from its front just like you did with the character
* The "Up" direction is Z. (This could be Y depending on who you are talking to or what engine you are using)
* Front is defined as front 180 degrees of the humans view.
* Back is defined as the back 180 degrees in back of the human model.

## Proposed Solution

1) cast a ray from the front of the object in focus. In the case of a human you have a definite front and back.

2) Find the diference in x and y so you can translate the ray from the object in focus on top of the players ray

3) Apply that translation. You should now have what is viewed in picture 3. This allows you to solve for the angle (theta in this case). There are details on solving for theta here: http://www.wikihow.com/Find-the-Angle-Between-Two-Vectors

Just some simple linear algebra. Nothing too bad I think.

## Results

1) Now, intuitively, you can see that if this angle theta is \>90 degrees then the player is facing the "front" of the object in focus.

2) If the angle is \<90 degrees then the object in focus is facing away from you, and the player is looking at its "back".

## More Thoughts

Remember the assumption mentioned before on "front" and "Back". Depending on your gameplay needs you may want to define this differently. WoW -seemed- to have this kind of setup when it came to calculating if the player was "in back" of the target. Playing as a rogue, if you are in the back 180 degrees you seemed to get the damage modifier for being "in back" of the target.

Good luck. Hope this helps.

# Answer
> 3 votes
bool front = dot( normalize( rayDirection ), normalize( objectForward ) ) \< -0.5f;

Does not break, simpler and faster than cross. Using acos you can calculate the exact angle.

# Answer
> 1 votes
The result of a cross can give you that answer. This is c#/xna but think of it as pseudo code.

```
bool lookingAtFront = false;
Vector3 result = Vector3.Cross(directionCamIsLooking, localRightOfLookedAtObject);

if(result.Y > 0) //assumes Y is up. else use result.Z
  lookingAtFront = true;

```

this may break if the camera is pitched severely (looking straight down or up at object). but otherwise the `result` vector will either be pointing somewhat upward or downward depending on which side of the `localRightOfLookedAtObject` the `directionCamIsLooking` is.

---
Tags: ogre, raycasting
---


# Question
Title: How to use/apply class inheritance in Enchant.js
You're developing a game using Enchant.js and you just need an Enemy class which multiple enemy classes derive from and every enemy has its own sprite and stuff.

# Answer
> 1 votes
This old Enchant.js blog entry talks about class inheritance and offers the following example

```
enchant();。

A = Class.create({
    initialize:function(){
        this.x=1;
    },
    method:function(){
        document.write(this.x);
    }
});

B = Class.create(A,{   //Inherits A
    initialize:function(){
    A.call(this);  // Calls up A constructor
        this.y=100;
    },
    anotherMethod:function(){
        document.write(this.x*this.y);
    }
});

var b = new B();
b.method();
b.anotherMethod();

```

So, using a Chess game example, in which you gotta pass parameters to the constructor in order to "build" the piece, what has worked for me is following those guidelines and taking advantage of the Sprite class like this:

```
var Piece = enchant.Class.create(enchant.Sprite, {
    /**
     * Class constructor
     *
     * @param   object (game object reference)
     * @param   point (JSON object)
     * @param   string
     * @param   string
     * @return  void
     */
    initialize: function(gameObj, position, color, type) {
        enchant.Sprite.call(this,g_SizeCell, g_SizeCell); // grid's cell size (global)
        this.image = gameObj.assets[g_ImgPieces]; // sprite sheet path (global)
        this.x = position.x;
        this.y = positino.y;
        // sprite sheet's frame selection
        switch (this.m_Type) {
            case "pawn":
            default:
                this.frame = 0;
                break;
            case "knight":
                this.frame = 1;
                break;
            case "bishop":
                this.frame = 2;
                break;
            case "rook":
                this.frame = 3;
                break;
            case "queen":
                this.frame = 4;
                break;
            case "king":
                this.frame = 5;
                break;
        }
        if (this.m_Color == "black") {
            this.frame += 6;
        }
    }
    // ... some other member functions
});

var Pawn = enchant.Class.create(Piece, {
    initialize: function(gameObj, position, color) {
        // this is the most important part
        // look that the current object is not in the parent's class signature
        Piece.call(this, gameObj, position, color, "pawn");
    }
    // ... some other member functions
});

// pawn creation for using in chessboard
for (i = 0; i < 8; i++) {
    point = {x:i,y:1};
    newpiece = new Pawn(gameObj, point, "black");
    scene.addChild(newpiece);
    point. y = 6;
    newpiece = new Pawn(gameObj, point, "white");
    scene.addChild(newpiece);
}

```

---
Tags: javascript, inheritance, enchant.js
---


# Question
Title: Important aspects to consider while making a technical design document
I'm working on a open world strategy game for which I'm planning to make technical design documentation.

How do we decide exactly what we need to include to ensure the design document is as complete as it can be?

# Answer
> 5 votes
First important aspect to consider is: **Who are you writing the documentation for?** Yourself, modders, map editors/campaign designers? And second, but equally most important: **What is the purpose of it?** What the documentation should contain in any case is:

## High-level overview

Write a short abstract what is your game about. List what have you used, programming languages, libraries, versions. System requirements. Screenshots. If you write for someone who is going to extend your game in any way, describe how to install your game in a way they can use it/mod it. Describe what your API can do.

## Extension tutorials/guides

If anyone is going to implement/extend anything in your game, write a typical example. Write a tutorial. How to create a map, how to write a simple extension. Make the tutorial easy enough for people to be able to try and complete in one easy sitting, but complete enough to show the capability of your system. This might be good for you as well, when you come to your game after some time. Write guides for typical tasks in your game.

## Architecture, Entities, Workflows

Draft few diagrams, how are different tiers connected. List or draft a diagram of basic entities in your game, their relationships, how are they stored (DB, ... ). If you use any custom file format, document that as well. If you use XML, don't forget to attach a and explain its schema. Create pageflows and workflows of activities in your game.

## TODOs and knows issues

If you know about anything that was left out, document it. Any errors that were not dealt with, write down possible workarounds.

## Detailed API documentation

Generate one from comments at least, but your comments must be good. Make sure you document all public methods and classes. Pay special attention to any publically available API you have created typically used for scripting etc.

## Get someone to read it

Someone who was not involved in making the game, but with sufficient technical level. If you are going to release the game with the technical document, get an editor and technical writer to proof read it.

# Answer
> 3 votes
The technical design document should include the details of the technology required to create your game. It shouldn't just list the technologies, you need to explain how they're used and why they were chosen for the project. You can provide use cases, or play examples, and describe the technology required to implement those examples.

Describe how the technologies will interact and why they should interact in that way. Include descriptions of the systems that will be implemented, their uses and what aspects of the game they'll take care of.

Visually, this would include a flowchart of the structure of the code. It would include annotations of the connections, and detailed descriptions of the blocks.

---
Tags: architecture, design-document
---


# Question
Title: How to deal with objects placed in the root nodes of a quad tree?
I've implemented a quad tree where points and axis aligned rectangles can be put. It works fine, except for one issue that I'll try to describe.
When you put a rectangle in the tree and this rectangle collides with quadtree's node borders, than your rectangle is put in parent node of that node. It's ok! That's how it should work!

Let's consider I have a small rectangle (red) laying in quadtree's center (x: 0, y:0).
**And I would like to retrieve other rectangles near my rectangle (blue rectangles).**
But here's the problem, when I do that the **algorithm will return all rectangles(blue + green)**, because my rectangle collides with quad tree nodes border and is put in quadtree's root node.
I don't need green rectangles and I can't allow myself to have such an overhead.

How can I avoid such problem? What would be the easiest way to implement solution to this problem?

The current Retrieve method recursively walks to each subnode of the node where red rectangle is positioned.

I've heard about overlapping node borders solution, but I guess it won't help in case if red rect would be 3x time bigger?!

# Answer
> 2 votes
If you re-implement your quadtree to insert objects on borders into all siblings of that border, then the result you'll get is exactly the result you are trying to achieve (with an overhead of `2n` per object where `n` is the number of borders the straddling object is in contact with.)

# Answer
> 4 votes
I don't understand why do you add the green ones? If you simply test in each step if the red overlaps with the child (simple test), it would look like this:

Let's say your rectangle `red` is located in `root` and you want to retrieve the neighbours and put them into `result`

```
child = root

procedure populateResult

  if red collides with child
    add all neighbours located directly in child to result
    if child.hasChildren
      for each child
        call populateResult(child)
      end
    endif
  endif

```

And this should only add the blue rectangles.

# Answer
> 0 votes
I have also implemented an open-source QuadTree with a friend, and we store all objects that don't completely fit into child quads in the parent quad. This can happen at any level of the quad tree. Any time an object straddles the boundary between two quads, it needs to be stored at the parent level. When you are querying the tree, even if you're looking at some obscure corner of the earth, you need to be checking these boundary objects all the way down the tree. Here's some very rough pseudocode for a quad:

```
List<object> storage;

// Note this is called with the root "quad" and is called recursively
Insert(object, quad)
{
    If the object fits completely inside the NE quad, Insert(NE), return
    If the object fits completely inside the NW quad, Insert(NW), return
    If the object fits completely inside the SE quad, Insert(SE), return
    If the object fits completely inside the SW quad, Insert(SW), return
    Else, insert it storage (specific to this quad)
}

List<object> Get(area, quad)
{
    Check each object stored in storage
    Check sub quads recursively (which will in turn check their own storage)
}

```

It might sound wasteful to store boundary objects like this, and you may get a number of these, but it's not that bad, and there's no choice if you want to store areas in your tree. You could store points in the tree, but then area-based queries break, and that's a more common use-case.

---
Tags: algorithm, quadtree
---


# Question
Title: How significant is the addition of multiplayer to a singleplayer game compared to starting with multiplayer in mind?
Especially for game designers or software engineers, I was wondering how significant of an increase in difficulty/frustration/workload it would be for multiplayer to be an afterthought of a singleplayer game, as opposed to putting in all of the work for the game to be "multiplayer ready" from the start.

This question is especially important when the question of "Will there be multiplayer?" is up in the air until after the game is developed.

I only ask because coding with multiplayer in mind from the start, I assume, is a hefty chunk of extra difficulty that one could otherwise skip. Of course adding in such a engine-changing feature, I assume, would be quite frustrating given a game already close to being finished. Both strategies seem burdensome, but if the extra workload of implementing a big feature after a game is already completely is extraordinary compared to the heavy workload of engineering it from the start, then obviously one would nearly always want to prepare for multiplayer.

I am also curious on a personal level as I have seen a few indie projects declare they will never add multiplayer, and then months later after the game has over a year in development, change their mind and say they will be adding it as a high priority feature due to the large demand for what is probably the most common core feature of any game.

# Answer
> 2 votes
There are software architecture patterns which make it quite easy to add multiplayer later. One is the Model-View-Controller pattern.

In a game, the model is the current game state (which game object is where and does what right now), the view is the graphic engine which visualizes the game state, and the controllers are the game mechanics and the player inputs which change the game state.

To add networking or multi-controller support to a game built around MVC, you just need to add a new controller (network input / 2nd player controls) and a new view (network output / 2nd player screen).

# Answer
> 13 votes
If you were to compare a list of all the systems that could be affected by the addition of multiplayer with a list of all the systems that need to be in the game, the lists are likely to be the same.

For example, adding multiplayer to a single player game can/will affect:

* **Enemy AI** (now the enemies have multiple enemies!)
* **Rendering/animation** (if you had a FPS before, now you need to also draw a character where the camera is, animations that look fine in first person may look horrible to another player in 3rd person)
* **UI** (lobbies, chat windows, etc.)
* **World structure** (that chunking system now needs to support multiple locations)
* **Save/load data** (changes to the world can come from other players and need to be saved)
* **Sound** (local multiplayer now has two listeners and Maik's other examples in comments)
* And so on...

So, how significant? **Very significant**.

However, I would purpose it's better to finish a single player game than to never finish a multiplayer game. If you have doubts about the added difficulty of completing a game that includes multiplayer, don't include it. You can find a middle ground along the way, by trying not to make architectural decisions that will shoot you in the foot later, if and when you update the game to be multiplayer.

# Answer
> 11 votes
This is one of those "it depends" questions. Does your game have a lot of physics objects that would be hard to replicate? How much would high latency bother your game? What kind of libraries are you using?

And on top of that, does the *design* of your game allow for multiplayer? Shoving co-op into a single player corridor shooter where you have your designers making assumptions about the numbers of players for things like traps and puzzles isn't likely going to work even if you solve the technical problems.

Some games go so far as to have separate single player and multiplayer executables and just share art content and style. So you can have multiplayer but you basically have two separate code bases.

Suffice to say, it can be incredibly difficult or fairly easy. Obviously the better you can plan the more you can do.

# Answer
> 5 votes
If your game architecture doesn't support info coming in over the wire, it is a real hassle to add MP later. Make the decision early whether or not your first published version will have MP or not, then develop toward that goal.

It's always easier to drop the MP later if it's going to be too expensive than to tack it on if you decide you want it.

---
Tags: multiplayer, project-management, planning
---


title: Playing movies with OpenGL in Java

text:
# Question
Title: Playing movies with OpenGL in Java
I am trying to play a movie file into an OpenGL texture in a Java application. I am using JOGL and have a basic OpenGL scene, but I have no idea how to play a movie into a texture.

The only thing I could find was this:

http://paulo.ragonha.me/blog/2008/08/java-movie-playback-jogl-fobs4jmf.html

It is quite old and uses JOGL 1.1 and Fobs4JMF, which is no longer maintained. I managed to get it to build in eclipse but it wasn't able to read my movie clip. I could probably convert the movie clip to an older codec to see if that works, but I would rather have a modern solution.

I am a professional game developer, so the OpenGL part is no problem, but I am new to Java (coming from a C++ background).

Is there any modern library that wraps this functionality in an easy to use package?

# Answer
You may use the JogAmp JOGL GLMediaPlayer class http://jogamp.org/deployment/jogamp-next/javadoc/jogl/javadoc/com/jogamp/opengl/util/av/GLMediaPlayer.html

GLMediaPlayer will use the operating system installed codecs to decode the movie, on Android it uses the Android media framework and on desktop systems such as Linux, Windows and Mac it dynamically links to and uses installed libav/libffmpeg libraries. GLMediaPlayer itself only expose a platform neutral API and renders to a texture.

Example code are found to playback a movie on all six sides of a cube and on a rotating rectangle inside the jogamp jogl test codebase:

http://jogamp.org/git/?p=jogl.git;a=blob;f=src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/av/MovieCube.java

http://jogamp.org/git/?p=jogl.git;a=blob;f=src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/av/MovieSimple.java
> 2 votes

---
Tags: opengl, java, jogl, eclipse
---


title: 3dsmax crashes when exporting

text:
# Question
Title: 3dsmax crashes when exporting
I'm trying to export a (.max) file to openCOLLADA (.dae). Whenever I do this, 3dsmax crashes and produces this error:

> An error has occurred and the application will now close. No scene changes have occurred since your last save.

3dsmax then crashes but the COLLADA file is still produced. Whenever I try opening this COLLADA file in other software though, it comes up with a bad mesh data error. This is leading me to think that it wasn't exported correctly out of 3dsmax. Any advice?

# Answer
> 1 votes
Exporters are often very finicky. Try exporting nothing but a basic cube mesh. If that works, you know the issue is something within your mesh.

Unfortunately, this part is hard to give a definitive answer on. Basically you have to go over your mesh and ensure there's no *weird* parts that could cause the exporter to crash. This could be disconnected vertices, duplicated vertices, too many vertices, strange windings on vertices, strange normals between vertices and the list goes on. Essentially, you need to make sure you follow good practices when creating the mesh.

If you can't export the basic cube mesh either, there's an issue with your exporter and you should update it.

Finally, your last alternative is to start from scratch. Follow good practices to reduce errors. Try exporting the model or running STL check frequently during creating to make sure you're not propagating errors further.

---
Tags: 3dsmax, collada, export
---


title: How to implement server side physics?

text:
# Question
Title: How to implement server side physics?
I am working on 2-player 2d sidescroller.

How should I implement the physics on the server? Use one world for every game or use a big world in which I add every 2 player that start a game?

I have looked into some source code of multiplayer games and I saw that they don't implement any kind of game loop on the server, instead they work with events. If the game has physics handled by the server shouldn't the server use a game loop to call the step method?

# Answer
> 2 votes
> How should I implement the physics on the server?

As per rasmuses answer to a similar question, you want to run the physics simulation on both the client and server. If the physics does not run on the client, then it will look very choppy. And if the physics does not run on the server, then clients could get out of sync.

> Use one world for every game or use a big world in which I add every 2 player that start a game?

You also mention in the comments: `Box2D has the ability to stop certain objects from interacting with others`. I think running a single Box2D simulation on the server would cause more issues than it would solve. It would be best to run one Box2D simulation per game.

---
Tags: java, box2d, physics, server
---


# Question
Title: how to ignore physics collision of some objects in box2d
I know this sounds silly but I would like some objects to follow physics while others not to collide each other.

I tried to achieve them by setting their position exclusively. But then it will ignore all physics.

Is what I am trying to do even possible?

# Answer
Read up on collision filtering in the Box2D manual:

> Collision filtering allows you to prevent collision between fixtures. For example, say you make a character that rides a bicycle. You want the bicycle to collide with the terrain and the character to collide with the terrain, but you don't want the character to collide with the bicycle (because they must overlap). Box2D supports such collision filtering using categories and groups.
>
> Box2D supports 16 collision categories. For each fixture you can specify which category it belongs to. You also specify what other categories this fixture can collide with. For example, you could specify in a multiplayer game that all players don't collide with each other and monsters don't collide with each other, but players and monsters should collide

Link to manual here. (Search for Filtering) .
> 12 votes

# Answer
If you have two kinds of objects that should not collide with another, then the following works.

```
var kindA = -1;
var kindB = -2;

var bodyDef = new b2BodyDef();
var body = world.CreateBody(bodyDef);
var fixtureDef = new b2FixtureDef();
fixtureDef.shape = new b2Shape();
fixtureDef.filter.groupIndex =
    entity instanceof EntityA
        ? kindA
        : kindB;
body.CreateFixture(fixture);

```
> 3 votes

---
Tags: physics, box2d
---


title: How to speed up AStar?

text:
# Question
Title: How to speed up AStar?
I have this AStar class, and at the movement it is INCREDIBLY slow. It takes waaay longer than I expected it too, and I'm not quite sure why. I added the generation part at the very beginning to speed it up somewhat, and all though it helped my game takes like 15 seconds to load.

If this isn't the right place to ask how to speed it up, just let me know. I'm not sure if this is too "debug my code" esq.

Thanks everyone! - tips

```
public class AStar {
    private final Tank tank;

    private Map<String, Node> nodes;

    public AStar(Tank tank) {
        this.tank = tank;

        this.nodes = new HashMap<String, Node>();
    }

    public void generate() {
        //long now = System.currentTimeMillis();
        for (int i = 0; i < TanksWorld.MAX_X; i++) {
            for (int j = 0; j < TanksWorld.MAX_Y; j++) {
                Node node = new Node(i, j);
                nodes.put(node.hash(), node);
            }
        }
        //System.out.println("Generate took " + (System.currentTimeMillis() - now));
    }

    public void reset() {
       // long now = System.currentTimeMillis();
        for (Node node : nodes.values()) {
            node.reset();
        }
        //System.out.println("Reset took: " + (System.currentTimeMillis() - now));
    }

    public Path pathTo(int xFinish, int yFinish) {
        int xStart = tank.getFloorX();
        int yStart = tank.getFloorY();

        if (xStart == xFinish && yStart == yFinish) {
            return new Path(true);
        }

        Node startNode = get(xStart, yStart);
        Node goalNode = get(xFinish, yFinish);

        PriorityQueue<Node> queue = new PriorityQueue<Node>();
        queue.add(startNode);

        Path bestPath = null;

        while (queue.size() != 0) {
            Node current = queue.poll();
            int xCurrent = current.getX();
            int yCurrent = current.getY();
            if (current.visited) {
                continue;
            }
            if (current.equals(goalNode)) {
                bestPath = reconstruct(current);
                break;
            }
            addNeighbors(current);
            current.visited = true;

            for (Node node : current.getNeighbors()) {
                if (node == null) {
                    continue;
                }
                if (node.visited) {
                    continue;
                }
                int xNode = node.getX();
                int yNode = node.getY();
                double distance = current.pathDistance + TanksGame.distance(xCurrent, yCurrent, xNode, yNode); // TODO distance
                if (node.parent != null && distance >= node.pathDistance) {
                    continue;
                }
                node.pathDistance = distance;
                node.heuristicDistance = TanksGame.distance(xNode, yNode, xFinish, yFinish) + distance;
                if (node.parent == null) {
                    node.priority = node.heuristicDistance;
                    queue.add(node);
                } else {
                    node.priority = node.heuristicDistance;
                }
                node.parent = current;
            }
        }

        return bestPath == null ? new Path(false) : bestPath;

    }

    private void addNeighbors(Node node) {
        int startX = node.getX();
        int startY = node.getY();

        // up
        node.addNeighbor(get(startX + Tank.MVMT_SPEED, startY));
        // down
        node.addNeighbor(get(startX, startY - Tank.MVMT_SPEED));
        // left
        node.addNeighbor(get(startX - Tank.MVMT_SPEED, startY));
        // right
        node.addNeighbor(get(startX + Tank.MVMT_SPEED, startY));
        // up left
        node.addNeighbor(get(startX - Tank.MVMT_SPEED, startY + Tank.MVMT_SPEED));
        // up right
        node.addNeighbor(get(startX + Tank.MVMT_SPEED, startY + Tank.MVMT_SPEED));
        // down left
        node.addNeighbor(get(startX - Tank.MVMT_SPEED, startY - Tank.MVMT_SPEED));
        // down right
        node.addNeighbor(get(startX + Tank.MVMT_SPEED, startY - Tank.MVMT_SPEED));
    }

    private Path reconstruct(Node goalNode) {
        Path path = new Path(true);
        Node node = goalNode;
        while (node != null) {
            path.addToFront(node);
            node = node.parent;
        }
        return path;
    }

    private Node get(int x, int y) {
        if (x < 0) {
            return null;
        }
        if (y < 0) {
            return null;
        }
        if (x > TanksWorld.MAX_X) {
            return null;
        }
        if (y > TanksWorld.MAX_Y) {
            return null;
        }
        String hash = Node.hash(x, y);
        return nodes.get(hash);
    }

    public class Path {
        private boolean finished;
        private List<Node> path;
        private int index;

        public Path(boolean finished) {
            this.finished = finished;
            this.index = 0;
            this.path = new ArrayList<Node>();
        }

        public boolean isFinished() {
            return finished;
        }

        public void addToFront(Node node) {
            path.add(0, node);
        }

        public Node get() {
            return path.get(index);
        }

        public void next() {
            index++;
        }

        public int getSize() {
            return path.size();
        }

        public boolean isDone() {
            return index >= getSize();
        }
    }

    public static class Node implements Comparable<Node> {
        private final int x;
        private final int y;

        private List<Node> neighbors;

        // TODO getters and setters
        public boolean visited = false;
        public double pathDistance = 0;
        public double heuristicDistance = Double.MAX_VALUE;
        public Node parent = null;
        public double priority = 0;

        public Node(int x, int y) {
            this.x = x;
            this.y = y;
            this.neighbors = new ArrayList<Node>();
        }

        public void reset() {
            parent = null;
            priority = 0;
            heuristicDistance = Double.MAX_VALUE;
            pathDistance = 0;
            visited = false;
        }

        public List<Node> getNeighbors() {
            return neighbors;
        }

        public void addNeighbor(Node node) {
            neighbors.add(node);
        }

        public int getX() {
            return x;
        }

        public int getY() {
            return y;
        }

        public int compare(Node one, Node two) {
            if (one.priority == two.priority) {
                return 0;
            }
            return one.priority > two.priority ? 1 : -1;
        }

        public int compareTo(Node two) {
            return compare(this, two);
        }

        public static String hash(int x, int y) {
            return "x_" + x + "_y_" + y + "_";
        }

        public String hash() {
            return "x_" + x + "_y_" + y + "_";
        }
    }
}

```

# Answer
For one, your node `priority` should be based on the total estimated distance from start to end: `current.pathDistance + node.heuristicDistance`. You want to pick the nodes that have best likely outcome.

For two, the priorityQueue documentation reads `The head of this queue is the least element`, which means that your compare will want to return smaller values for more desirable choices, a subtraction should suffice: `one.priority - two.priority`

Before these changes, your algorithm was selecting nodes that were furthest from the destination to calculate next, which would result in flood-filling the entire world before settling on a result. That could take a while, especially if you re-calculate the "shortest" distance to every node from every adjacent node.
> 3 votes

---
Tags: java, 2d, path-finding
---


# Question
Title: I am looking for a word to classify Game Objects (Trees, Rocks, even Bridges) but NOT include Items/Characters
I am looking for a SPECIFIC definition that includes environmental game objects but NOT other game objects. Trees, Rocks, or even Bridges. NOT items, NOT weapons, NOT Characters, NOT tiles. I'm looking for an answer that is extremely specific for certain entities but NOT most entities.

For my GameObjects, I have them stored as an ObjectType.

```
typedef enum
{
CHARACTER = 0,   //A PC or NPC
ENVIRONMENT = 1, //A tree, a Rock, a Bridge, a non-animate environmental object
ITEM = 2,        //A sword, bag of gold, pickup-able item
} ObjectType

```

Obviously, anyone would easily understand that a Character GameObject would be a Character (PC or NPC), and an item would be something like a Sword, bag of Gold, etc.

However, the word "environment" is obviously wrong. I thought of "foliage" to refer to any object that isn't a tile (grass, road, water, a floor) and isn't an item (can pickup, etc.)

Normally, I would call these things 'Objects', because a Tree, a Rock, a Bridge, a Bush, a collection of flowers- these are all objects. However, this is redundantly confusing when GameObjects are referred to as "Objects" and the term 'object' is so common in game engineering.

I couldn't help but think to myself, "There must be a term that is obvious, that I am just not seeing. A word that describes this very common type of game object."

Something that people could easily understand, so I don't have to resort to "EnvironmentObject".

# Answer
Something which is part of the set is a "fixture", or "landscaping".
> 4 votes

# Answer
I believe Prop ( See: http://en.wikipedia.org/wiki/Theatrical\_property and https://developer.valvesoftware.com/wiki/Prop\_Types\_Overview ) is commonly used. There are less ambiguous alternatives, for example Blizzard uses the word Doodad.
> 25 votes

# Answer
I would use the word **Doodad** for those environmental things as it's a standard. When editing in both Titan Quest and StarCraft's Map Editor, they're referred to as **Doodads**.

http://starcraft.wikia.com/wiki/Galaxy\_Map\_Editor#Terrain

I usually refer to objects an **Actor** can interact with as **Props**, just as if they were on a stage. Actors use Props to do actions, whereas the Doodads only complement the scene.
> 19 votes

# Answer
"Decoration" has always been the name I've given to non-interactive, non-collidable elements.

When using flixel I would have level data defined by three separate layers Solid, Interactive and Decoration. Solid and Decoration would then be loaded into Tilemaps, both would be rendered but collision checks would only be made against Solid.
> 3 votes

# Answer
Like Hatberg said I used to hear them called "Props" when I was younger but after I took a few game development classes in college (ironically taught by the founder for Iron Lore Entertainment (Brian Sullivan) who made/designed Titan Quest) I heard purely decorative game objects being called "Set Dressing". I guess it's just a synonym for Prop but I find most people prefer Set Dressing now a days.
> 1 votes

# Answer
You could call them Entities and give them an Environment tag as an enum. You could also go with a component based design and just attach a "Render" component so that all that happens to these environments is they sit there and look pretty.

Calling Trees and environments Entities may not sit well with people, but to me it makes sense to call them "entities" of the scene. It allows you to eliminate the need for more classes and thus making it more simplified to understand as long as you document your design.

## Edit1:

My original answer is trash and was a result of not properly reading the question. As other better answers have already mentioned, you can tag these items are 'props' 'Doodads' or even 'Decorations'.

Just for this answer I hoped to provide you with yet another word after looking at the Doom3 source code. I have ripped through it looking for how they tag their "Entities" or "GameObjects as you have decided to call them. From what I can see they do not have an obvious tag for it. They seem to just build an IdEntity and give it a RenderEntity which has the data for the renderer to render. They also have a Model class, but no obvious Environment Tags that I can see. I will edit this answer if I end up finding anything that is close to an "environment" tag.

## Edit2:

It looks like doom classic straight up built classes for "Wall" "Floor"(also functioned as ceiling) "Things" and even "sky". So I guess "Thing" could be used, although that seems vague. I guess it is similar to doodad.
> 0 votes

# Answer
Terrain works. You could also divide it into Terrain\_water and Terrain\_land
> 0 votes

# Answer
What about the word "Scenery"?
> 0 votes

---
Tags: gameobject
---