# Question
Title: A star pathfinding and discrete/smooth positions
The A\* (A-star) algorithm usually represents a path on a grid.

Once a path has been found, however, the path looks blocky and is not suited if you move your units with floating point datatypes.

Here is an image describing the problem. The whites tiles represent the path found by A\*. The black line path is the path I want, the red line path is the one I don't.

One solution would be to select a corner when the path turns, and switch/keep side when the path turns the other way. Seems like the most logical and cleanest way to do this.

# Answer
> 4 votes
One option for path-smoothing is casting rays from the current position to the farthest visible node and go there. You could either do it in real time or just build a new path from the one you already have, so the navigation algorithm stays the same.

Starting from the current position, cast rays to each node in the path. When there is a node that cannot be reached by the ray, the previous node is the one to take into account. Considering the last node, repeat the process until the final node.

In the end, you'll have a result similar to the image below (green path) depending on the ray's width and extra parameters your game requires.

---

Also, there is this Valve's presentation about the AI used in L4D. It's worth taking a look at it and getting ideas from it.

# Answer
> 4 votes
As other option, you could split the path into straight parts. Then you only need to find the points where your original path leave a path part (no need to compute, just switch by direction of the next part). Only what remains it is connect points of your new smooth path!

**EDIT:** if you insist on the path you drawn, just compare the two extreme possibilities in which way path can leave a straight part (=point at one or the other end of the edge), and choose whatever produces shorter line segment (pythagoras theorem).

---

As for hero width, if you look closely - where is the path closest to edge? In the connection of last "tile" and the one before. Check path distance to the edge in that point(you will have to do math now, switch wont suffice), if it is less then hero width/2, add new point to the path at hero width/2 distance from edge.

*Sorry of image inconsistency, already deleted source of original image.*

# Answer
> 2 votes
The A\* Algorithm works with paths on a *graph*. The graph does not have to be a *grid*.

If you look at the paths you want, they go through the *corners* of the square tiles. Specifically, they go through the corners where three tiles are walkable and one tile is a wall. Instead of giving A\* a graph with the tile centers, you can build a graph with only these "exterior" corners, with graph edges from corner to corner (if there's line of sight). You may want to move the corners a few pixels away from the corners to handle the “hero size” problem.

If you build this corner-to-corner graph instead of the grid graph, A\* will be even faster than post-processing paths or using an any-angle algorithm (Theta\*). However, building the graph takes some time (mostly to process line of sight), so it might not be a great choice if the player can change the map while the game is running.

---
Tags: path-finding, grid
---


title: Energy Bar in Unity

text:
# Question
Title: Energy Bar in Unity
I want to display a debug message when the progress bar is loaded fully and I have a button "refresh", when I click this it should reload the progress bar. Here is the code I have tried:

```
var energyBar : GUIStyle ;
var bgImage : Texture2D; // background image that is 256 x 32
var fgImage : Texture2D; // foreground image that is 256 x 32
static var playerEnergy = 1.0; // a float between 0.0 and 1.0

function Start() {
}

function Update() {
    playerEnergy=Time.time *0.02;
    if(playerEnergy<=0)
    {
        Debug.Log("stopped working");
    }
}

function OnGUI () {
    // Create one Group to contain both images , the first two numbers define the on    screen placement
    GUI.BeginGroup (Rect (10,10,256,32));

    // Draw the background image
    GUI.Box (Rect (0,0,256,32), bgImage, energyBar);

    // Create a second Group which will be clipped
    // We want to clip the image and not scale it, which is why we need the second Group
     GUI.BeginGroup (Rect (0,0,playerEnergy * 256, 32));

     // Draw the foreground image
     GUI.Box (Rect (0,0,256,32), fgImage, energyBar);

     if(GUI.Button(new Rect(100,200,60,30),"Refresh"))
     {
         // code to Restart the progress bar
     }

    // End both Groups
    GUI.EndGroup ();
    GUI.EndGroup ();
}

```

From the above code I am able to display the progress bar, but the problem is that the "refresh" button is not getting displayed and I need help in reloading the progress bar when refresh button is clicked. I also need to print the debug message when the progress bar is fully loaded, but here the debug message is getting displayed when the progress bar starts loading. Can anybody please help me out.

Here I have attached the texture also

# Answer
> 1 votes
You should specify clearly what you are trying to accomplish. You speak about progress bar but use a `playerEnergy` variable. Are you trying to fill or to deplete the bar?

In any case this line looks suspicious.

```
playerEnergy=Time.time *0.02;

```

This line has two potential problems (that we cannot state properly until we know exactly what you want to do). The first one is that it ignores previous energy values, which *seems* is not what you want to do. Second, it relies on Time.time, which is a variable that always increases over time, which again *seems* is not what you want.

I am going to take a **wild guess** that what you want to do is something like this.

```
playerEnergy-=Time.deltaTime *0.02;

```

This line of code decreases the value of the variable playerEnergy steadily over time. Check deltaTime for details.

In order to reset the 'progression bar', just set playerEnergy back to 1.0 again.

---
Tags: unity, javascript
---


title: Isometric projection start point

text:
# Question
Title: Isometric projection start point
I have a question about isometric projection: Why did in all tutorials and examples start point for isometric is in left top corner ? For example in cocos2d 3.1 my start screen point in left bottom, so left top isometric position will nearly 1500,1500. So is it normal to make start isometric point in left bottom corner ? i mean :

```
x,y
0,3 1,3 2,3
0,2 1,2 2,2
0,1 1,1 2,1
0,0 1,0 2,0

```

or better

```
0,0 1,0 2,0
0,1 1,1 2,1
0,2 1,2 2,2
0,3 1,3 2,3

```

sorry for stupid question

# Answer
It's a question of semantics. How your local coordinate system is build is your own preferebly choice. In the web browser for example origo is located in the top-left corner, which usually adapts in web-based games.

So, to answer your qestion; no it doesn't matter. As long as you understand your code and are using the tools as they are intended. If you have (0,0) in the bottom-left, then go for it!
> 0 votes

# Answer
The direction of axes is really arbitrary, that is, a matter of convention.

Traditionally, in 2D graphics, the x-axis goes left to right and the y-axis top to bottom. This is because of the scanline of your monitor which follows the reading order of Western languages.

In 3D graphics, the coordinate systems typically have the x-axis like in 2D, but the y-axis going from bottom to top. This follows the mathematics tradition.
> 0 votes

---
Tags: cocos2d, isometric
---


# Question
Title: How to check in single event if two objects are clicked at the same time in libGDX?
I am newbie to libGDX and I have written two functions for touchdown,

```
    LockerKeyHalfImage.addListener(new InputListener() {
        public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
            System.out.println("clickrd Locker>>>>>>>>");
              return false;
        }
        });

    MasterKeyHalfImage.addListener(new InputListener() {
        public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
            System.out.println("clickrd Master>>>>>>>>");
              return false;
        }
});

```

My problem is to check if these two images are clicked at the same time (multi-touch detection). I tried to use the following lines without success:

```
 InputMultiplexer im = new InputMultiplexer();
      //  GestureDetector gd = new GestureDetector(ui);
         //   im.addProcessor(gd);
            im.addProcessor(ui);
            Gdx.input.setInputProcessor(im);

```

Can anyone point me in the right direction?

# Answer
In your listeners, instead of returning `false`, do something like this:

```
int numTouches = 0;

LockerKeyHalfImage.addListener(new InputListener() {
    public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
        System.out.println("clickrd Locker>>>>>>>>");
          numTouches += 1;
    }
 });

MasterKeyHalfImage.addListener(new InputListener() {
    public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
        System.out.println("clickrd Master>>>>>>>>");
          numTouches += 1;
    }
});

```

Now, to check for multi-touch, just expose and check that `numTouches >= 1`. That means there were two or more things touched at the same time.

Also, you should be returning `true`, not `false`, if you've already handled clicks in your multiplexer methods.
> 0 votes

---
Tags: android, libgdx
---


# Question
Title: Can I incorporate a small fraction of a song into my iOS game?
I was wondering if I can use a small portion of a song without running into any copyright issues. I would give full credit to the artist as well.

# Answer
> 2 votes
No, you need permission from the copyright holder.

Without explicit permission, you would be committing a copyright violation, even when you just use a small part of a song. Giving credit never makes an otherwise illegal copyright violation legal.

And you likely will get sued, because the music industry is constantly looking for reasons to sue people for the smallest infraction of the intellectual property they bought from the artists.

# Answer
> 1 votes
depends on the license the song is available under, Creative Commons license has many guises some of which allow for usage so long as you nominate artist.

the various licenses are explained quite well at 'open game art'

http://opengameart.org/content/faq

---
Tags: music, copyright
---


# Question
Title: Removing a previously rendered image on a canvas
I made a platformer using ctx.clearRect and ctx.fillRect, so each time the player moved I would just delete the previous position and draw him again.

Now I'm working on importing my own art into the game and I'm having problems removing the previously drawn image.

Example of some of the code I am using now to render the player:

```
var playerReady = false;
var playerImage = new Image();
playerImage.onload = function () {
    playerReady = true;
};
playerImage.src = "images/player.png";

var render = function () {
    if (playerReady) {
        ctx.drawImage(playerImage, player.x, player.y);
    }
};

```

So Im wondering if there is anything similar to ctx.clearRect for ctx.drawImage or what I could do, my current workaround is to render the whole background on top of the previously drawn background + player but this is not ideal for what I´m trying to do.

thank you!

# Answer
The HTML5 canvas works... well... like a canvas. It is a collection of RGBA pixels. When you draw something, it replaces whatever was there before. There is no "undo" functionality.

The usual approach is what you are doing right now: start each rendering frame by completely erasing the canvas and redrawing the whole scene from scratch.

When you have lots of static content which doesn't change per frame, some dynamic objects which move **and performance is *really* a concern**, you can also layer canvases. Create multiple `<canvas>`es and move them on top of each other using CSS positioning. That way you can work with each canvas separately without destroying the content of the others. Use the lower canvas for static content which is never erased and the upper canvas for any dynamic content which is erased and redrawn every frame.

Another more old-school trick is using **dirty rectangles**: In your logic loop, mark rectangular areas of the screen which need to be redrawn because their content changed. In your rendering loop, only draw the areas which are marked as dirty. This isn't easy to implement and will make your whole engine a lot more complex, but it can really improve graphic performance a lot when most parts of your screen don't change often *and* you implement it correctly.
> 2 votes

---
Tags: javascript, html-canvas
---


# Question
Title: How can I switch between texture atlases based on the iOS version?
How can I switch between atlases (with different resolutions) in Unity based on the runtime iOS version?

# Answer
> 1 votes
You could always use Screen.currentResolution or Screen.width/Screen.height if you're trying to switch based on the resolution of the version.

If you want to get the exact version of iOS use SystemInfo.operatingSystem on Unity 4.3+ and iPhoneSettings.systemVersion on older versions

---
Tags: unity, textures, texture-atlas
---


# Question
Title: How can I ensure character weapon is also included in collision detection?
I have two models, my player character and her weapon. Each can be controlled independently (that is, I allow the player to aim the weapon). The object hierarchy is:

* Character (with CharacterController)
    + Weapon
* Block

The character collides with the block correctly (both behave as solid objects), but the weapon passes through the block. What components does the weapon (or block) need so that it also behaves as a solid object? (In other words, it must not pass through the block. The block should stop the weapon from moving.)

I have tried adding rigid bodies to both weapon and block, including enabling and disabling Kinematics on each, to no avail. When they do collide, they move through each other rather than behaving as solid objects. If I tick *a few* constraints, they behave as solid objects, but affect each other's movement and/or rotation. If I tick *all* the constraints, then they no longer behave as solid objects and move through each other again.

# Answer
The usual tricks with weapons are:

1. Make your character's collider large enough that it contains your weapons, then simply ignore collisions between it and the weapon's raycasts.
2. Make it *appear* not to go through by drawing it on top of other objects. This works for FPS type games:

1. Put the weapon(s) on a new layer (for this example it will be named WeaponsLayer).
    2. Go the the main camera's settings, and click the culling mask (defaults to Everything), and uncheck your new layer (WeaponsLayer)
    3. Add a new camera (maybe name it Weapon Camera) and make it a child of the Transform that's holding your main camera.
    4. Change the culling mask of your new camera so that only your new layer (WeaponsLayer) is selected.
    5. Change the clear flag of your new camera to "Depth Only"
    6. Change the depth of your new camera so that it's larger than that of your main camera (the default Depth is -1, so 0 should be enough).
> 3 votes

---
Tags: unity, collision-detection, rigid-body-dynamics
---


# Question
Title: Loading TextureRegion with filter diff from that of texture it came from
I am using libgdx . While packing my texture atlas I have set the filter for mag and min to Nearest . But for just one region I wish to draw it with linear filter . Is it possible to have different filters for texture region than that of texture atlas it came from.

# Answer
> 1 votes
You should have a look at sampler objects, if is it a solution that would suit you. Basically a sampler object is openGL object which can store these kinds of settings for later use(binding) in shaders.
Example of usage: this tutorial.

---
Tags: libgdx, texture-atlas
---


# Question
Title: Unity: how highlight effect should be applied to terrain mesh
I have my game generate random voxel terrain, and then generate a mesh on only the visible parts of that terrain. I want it to be able to select some part of the terrain with the mouse, but I'm not sure how highlighting should be done properly. The only thing that comes to my mind is to recalculate whole chunks, updating selected voxels to brighter textures but it would by damn slow. I want to be able to change textures in that certain selected part of the mesh, without recalculating the whole chunk mesh. How to achieve that?

**Edit:** For better understanding, this is how the terrain looks: Voxels are kept in a 3d array and chunks are recalculated every time its voxels are affected, adding mesh to chunk by checking if the voxel is exposed to air.

```
Word object:
private void GenWorld()
{
    voxels = new Voxel[size * chunkSize, chunkHeight, size * chunkSize];

    for (int x = 0; x < size * chunkSize; x++)
    {
        for (int z = 0; z < size * chunkSize; z++)
        {
            int grass = PerlinNoise(x, 0, z, 100, 32, 0);
            grass += PerlinNoise(x, 0, z, 50, 16, 0);

            for (int y = 0; y < chunkHeight; y++)
            {
                if (y <= grass)
                    voxels[x, y, z] = new Voxel(new Vector3(x, y, z), VoxelType.Grass);
                else
                    voxels[x, y, z] = new Voxel(new Vector3(x, y, z), VoxelType.Air);
            }
        }
    }
}

private void GenChunks()
{
    chunks = new Chunk[size, size];

    for (int x = 0; x < size; x++)
    {
        for (int z = 0; z < size; z++)
        {
            GameObject tempChunk = Instantiate(chunkGO,
                new Vector3(x * chunkSize, 0, z * chunkSize),
                new Quaternion(0, 0, 0, 0)) as GameObject;
            tempChunk.transform.parent = transform;

            chunks[x, z] = tempChunk.GetComponent<Chunk>();
            chunks[x, z].worldGO = gameObject;
            chunks[x, z].posX = x * chunkSize;
            chunks[x, z].posY = 0;
            chunks[x, z].posZ = z * chunkSize;
        }
    }
}

Chunk object:
public void GenerateMesh()
{
    for (int x = 0; x < world.chunkSize; x++)
    for (int z = 0; z < world.chunkSize; z++)
    for (int y = 0; y < world.chunkHeight; y++)
    {
        Voxel voxel = GetVoxel(x, y, z);
        if (voxel.Type == VoxelType.Grass)
        {
            // Check if any face is exposed to air
            if (GetVoxel(x, y + 1, z).Type == VoxelType.Air)
                CubeTop(x, y, z, voxel);
            if (GetVoxel(x, y - 1, z).Type == VoxelType.Air)
                CubeBottom(x, y, z, voxel);
            if (GetVoxel(x + 1, y, z).Type == VoxelType.Air)
                CubeEast(x, y, z, voxel);
            if (GetVoxel(x - 1, y, z).Type == VoxelType.Air)
                CubeWest(x, y, z, voxel);
            if (GetVoxel(x, y, z + 1).Type == VoxelType.Air)
                CubeNorth(x, y, z, voxel);
            if (GetVoxel(x, y, z - 1).Type == VoxelType.Air)
                CubeSouth(x, y, z, voxel);
        }
    }

    UpdateMesh(); // Just passing data to unity mesh obj
}

void CubeTop(int x, int y, int z, Voxel voxel)
{
    vertices.Add(new Vector3(x, y, z + 1));
    vertices.Add(new Vector3(x + 1, y, z + 1));
    vertices.Add(new Vector3(x + 1, y, z));
    vertices.Add(new Vector3(x, y, z));

    BuildFace(voxel.TextureTop);
}

void BuildFace(TextureType type)
{
    triangles.Add(faceCount * 4);
    triangles.Add(faceCount * 4 + 1);
    triangles.Add(faceCount * 4 + 2);
    triangles.Add(faceCount * 4);
    triangles.Add(faceCount * 4 + 2);
    triangles.Add(faceCount * 4 + 3);

    Texture.SetTexture(uv, type);

    faceCount++;
}

public static void SetTexture(List<Vector2> uv, TextureType type)
{
    Vector2 texturePos = (Vector2)textures[type];

    uv.Add(new Vector2(textureOffset * texturePos.x + textureOffset, textureOffset * texturePos.y));
    uv.Add(new Vector2(textureOffset * texturePos.x + textureOffset, textureOffset * texturePos.y + textureOffset));
    uv.Add(new Vector2(textureOffset * texturePos.x, textureOffset * texturePos.y + textureOffset));
    uv.Add(new Vector2(textureOffset * texturePos.x, textureOffset * texturePos.y));
}

```

# Answer
A projector would work here. They're a little expensive because they cause the meshes they touch to be redrawn (essentially adds one more draw call in the manner certain shaders would), but that's something Unity internally during rendering, you won't have to do anything with the chunk's data.
> 1 votes

# Answer
Better than a projector you should be able to write a custom shader that highlights some quads given the mouse click world coordinates. Should be pretty cheap in resources if done right, and you can both use another texture or simply multiply by a color and avoid wasting unneeded memory.

I'm not a shader expert but I'm working on something similar and you can do this in the fragment shader with a single rectangle check for the mouse click and the fragment world position (I can provide more help with that if you're interested).
> 1 votes

---
Tags: unity, 3d-meshes
---


# Question
Title: Which input event is suitable for this game?
I am trying to clone this game:

http://www.ferryhalim.com/orisinal/g3/bells.htm

As i am using libgdx, so the game is both for Android and PC. I was wondering which input event would fit in nicely. SA you can see, bunny moves in accordance with the position of cursor. There is no cursor in android so i will have to do something different. Any help would be appreciated. Thanks in advance.

# Answer
This game is a good example why you can't always automatically port a game from one platform to another. Having the player-character follow the mouse cursor works well when the user has a mouse, but most Android devices have no mouse, so a different input method needs to be used. In this game, the gameplay is tightly connected to the input method. This means the gameplay will change during the transition from one platform to another.

The most straight-forward input choice would be the touchscreen. Just have the character follow the touch-events, so the user can move their finger on the screen and the character follows. The drawback of this method is that the players finger will cover a part of the screen. In the example game you posted the player only controls horizontal movement. This is good, because it means the player could move their finger along the lower edge of the screen to avoid covering the game action. When they would also control vertical movement, their own finger would certainly get in their way.

A more adventurous method would be to use the gyroscope sensors and have the player control the game by tilting their device. I once played a very similar game on Android which was controlled that way, and it played better than you would expect. However, this input method is less precise than finger or even mouse input, so you might want to make your game easier to combensate.
> 3 votes

---
Tags: java, libgdx
---


# Question
Title: What units is Box2d-AndEngine's velocity measured in?
I'm developing a game on AndEngine (with Box2d) and on iOS Sprite Kit **simultaneously**. I want the game's physics to be identical on both platforms. Sprite Kit uses Box2d internally for physics simulation and I'm using Box2d-AndEngine to use it in AndEngine.

In Sprite Kit, I use `physicsBody.velocity`.
In AndEngine's Box2d, I use `body.SetLinearVelocity(x,y)`.

In Sprite Kit, a physics body's velocity vector is measured in *meters per second*.

What is the corresponding unit of `SetLinearVelocity` in Box2d-AndEngine?

# Answer
> 0 votes
You have to convert screen pixels (or screen points) to meters and vice versa when you are using Box2D for your game physics. Please read section 1.7 of the Box2D documentation for more information on Box2D units and the scale to use for the best results.

In our current game (iOS, universal app), we use a scale of `1.0 / 64.0` for points-to-meters conversion. Works great.

*Example using the above scale:*

If your sprite is supposed to move at 200 pixels per second, its Box2D body has to move at 200.0 / 64.0 meters per second (i.e. its velocity vector has the magnitude 3.125).

If your sprite is located at pixel position (64, 64) on the screen, its body is located at (1, 1) in meters.

If possible, you set the Box2D body position and velocity (and other simulated properties) once (or at least rarely) and read back the position every frame in order to update the position of the sprite.

---
Tags: android, box2d, andengine, cross-platform
---


# Question
Title: FLIXEL: hexagonal tiles not seamlessly tiling with each other
I'm making a hex grid for our project using as3. I wonder why my hex grid isn't tiling properly.

Running my code within Flash CS6 produces seamless tiling

but on FlashDevelop it looks like this

Here is my code (in FlashDevelop):

```
    public class PlayState extends FlxState {
    private var player:PlayerSprite;
    private var hexMap:GenerateGrid;

    protected var hexagonWidth:int = 128;
    protected var hexagonHeight:int = 132;
    protected var hexagonNumber:Number = 0;
    protected var gridX_Size:int = 7;
    protected var gridY_Size:int = 10;

    public function PlayState() {

    }

    override public function create():void {
        FlxG.mouse.show();

        for (var yPos:int = 0; yPos < gridY_Size; yPos++) {
            for (var xPos:int = 0; xPos < gridX_Size; xPos++) {
                var hexagonX_Pos:Number = hexagonHeight * xPos + (yPos % 2) * hexagonWidth / 2;
                var hexagonY_Pos:Number = hexagonHeight * yPos / 4 * 3;
                hexagonNumber = xPos + yPos * gridX_Size;
                hexMap = new GenerateGrid(hexagonX_Pos - hexagonWidth, hexagonY_Pos - hexagonHeight);
                this.add(hexMap);
            }
        }

```

And for the class where the hex tiles are drawn

```
    public class GenerateGrid extends FlxSprite {
    [Embed(source = "../res/hextile_grass.png")] private var HexGrassPng:Class;

    public function GenerateGrid(X:Number = 0, Y:Number = 0):void {
        super(X, Y);

        var hex:FlxSprite = new FlxSprite();
        hex = loadGraphic(HexGrassPng, false, false);
        hex.x = X;
        hex.y = Y;
    }

    override public function update():void {
        //super.update();
    }
}

```

Any help would be greatly appreciated.

**EDIT** : EDIT: I have noticed my mistake a while ago. Code should be `var hexagonX_Pos:Number = hexagonWidth * xPos + (yPos % 2) * hexagonWidth / 2;`

# Answer
My guess would be it's a floating point precision difference (do the two environments use different runtimes/sandboxes? I'm not very familiar with flash).

It looks like yPos is always turning out fine. My suspicion is that it has something to do with "(yPos % 2)", try yPos as a float instead of an int. A little hack that could fix it if that doesn't work is to negate a small constant off of your resultant xPos, tweak it untill it looks just right. Something like:

```
var hexagonX_Pos:Number = hexagonHeight * xPos + (yPos % 2) * hexagonWidth / 2 - 0.4;

```

This isn't very flexible if hexagonHeight/hexagonHeight can change though. You would have to derrive the value to negate based on hexagonHeight, that's if my fix even helps :)
> 1 votes

---
Tags: flixel
---


# Question
Title: Is there a difference in these two ways of rendering sprites?
I use an OrthogonalTiledMapRenderer:

```
renderer = new OrthogonalTiledMapRenderer(world.getMap());

```

and I wonder if there is a differnce between this call:

```
renderer.getSpriteBatch().draw(sprite, sprite.getX(), sprite.getY());

```

and this:

```
sprite.draw(renderer.getSpriteBatch());

```

If there is a difference, what is it?

# Answer
I found this in the libGDX source code, in class Sprite.java

```
public void draw (Batch batch) {
    batch.draw(texture, getVertices(), 0, SPRITE_SIZE);
}

```

So no, no difference. It shows Sprite.draw is only syntactic sugar for the longer version you posted.
> 2 votes

---
Tags: libgdx
---


title: HLSL Pixel Shader Sematics

text:
# Question
Title: HLSL Pixel Shader Sematics
I have a HLSl pixel shader that I'm using to create a deferred buffer, I have simplified the code to show you:

```
struct PS_INPUT
{
    float4 PosWVP                   : SV_POSITION;
    float4 NormalWorld              : NORMAL2;
};

struct PS_OUTPUT
{
    float4 PosWorld                 : POSITION;
    float4 NormalWorld              : NORMAL2;
};

PS_OUTPUT main(PS_INPUT input) : SV_Target
{
    PS_OUTPUT output = (PS_OUTPUT)0;

    output.PosWorld = input.PosWorld;
    output.NormalWorld = input.NormalWorld;

    return output;
}

```

When I compile this code, I get this warning `warning X3576: semantics in type overridden by variable/function or enclosing type`, what is this warning and how can I fix it?

# Answer
I think the problem is that your pixel shader returns a structure, so each element of that structure need to have an SV\_TARGET semantic and not the whole struct, so:

```
struct PS_OUTPUT
{
    float4 PosWorld                 : SV_TARGET0; //changed sematic
    float4 NormalWorld              : SV_TARGET1; //changed sematic
};

PS_OUTPUT main(PS_INPUT input) //there is no semantic here
{
    PS_OUTPUT output = (PS_OUTPUT)0;

    output.PosWorld = input.PosWorld;
    output.NormalWorld = input.NormalWorld;

    return output;
}

```
> 1 votes

---
Tags: shaders, directx, hlsl
---


# Question
Title: How can I achieve a bullet tracing effect similar to the one in Planetside?
I've noticed that bullet tracers in Planetside 2 don't show up close -- every time I see them, it came from a barrel a ways away. I don't believe Planetside traces every bullet either, because then it'd look really weird.

I'm not sure what the exact parameters are, so how can I achieve a similar affect?

# Answer
> 1 votes
**referencing a video clip here** i imagine there are a few things going on:

* not every bullet is being drawn with a "tracer" - just like you said

in theory i think you could accomplish this effect rather simply, when firing bullets you could create every Nth bullet with a different type. you can have the visual appearance of that bullet be an illuminated tracer whether using some form of shader or particle effect to draw a glow or animated "trail".

there is also a similar question related to machine gun tracer rounds in unity, if you are up for additional reading

---

* to actually see the tracer rounds, you need to be far from them

this could be accomplished by setting some sort of minimum view distance logic on the visual appearance of the bullets themselves. (or even from their source)

food for thought: this also leaves the possibility for a separate appearance for rounds fired at any given time of day / night. and additionally an alternative appearance for rounds fired "near" the player, if you wanted to use more detailed textures and effects when the player is nearby

---
Tags: 3d, first-person-shooter
---


# Question
Title: Why does my ship look like it's going backwards instead of fowards?
I'm making an *Asteroids*-clone based on this tutorial. I'm stuck on the 5th part of the tutorial.

For some reason my ship is going backwards instead of forward or it looks like its going forward, but in the tutorial the ship gos toward the asteroid. In the debug log, the z axis increments in a positive value. so I assume it is going forward but for some reason the ship it self doesnt go towards the asteroid like it does in the tutorial. The ship itself is an fbx export from Maya 2014.

Here's an annotated screenshot:

Full size version

It's probably something really stupid, but I just can't figure out why this is happening.

# Answer
> 0 votes
The code is good and Unity it's working correctly (look at the arrows on the screenshot, they're pointing in the right direction). As far as the screenshot helps me to debug, you just need to rotate the object and go torwards th

# Answer
> 0 votes
As it currently stands, his positive z direction is equivalent to your negative z direction.

Notice in the top right corner of the scene view, you have an axis indicator to tell you where the camera is currently facing (it says Persp, and shows x, y and z). Also notice how in the tutorial, his axis is aligned in the opposite z direction than yours. If you click the z part of it, the camera will flip around, giving the the correct view that you want to be editing from. You'll have to turn your ship around and move the asteroid over to the over side of your ship in order to be in sync with the tutorial's setup.

---
Tags: unity, movement, transformation, fbx
---


# Question
Title: XNA Library DrawPrimitives throwing primitiveCount error
I downloaded the project from here http://silverlight.bayprince.com/tutorials.php?tutorial=13 and tried adding a new OBJ file with a few thousand vertices listed.

The classic teapot works but when I tried loading a different model with alot more vertices included, it suddenly throws this primitiveCount error when the DrawPrimitives gets called.

EDIT:

The code includes a class that would read the data from the OBJ file. This will then return a `VertexBuffer` object back to the main program. The drawing starts when the Draw event is called.

There are 417936 vertices created from the OBJ file and since I'm using a trianglelist, I divided the vertices by 3 to get the total primitives count.

here's the code for the draw event:

```
private void DrawingSurface_Draw(object sender, DrawEventArgs e)
        {
            GraphicsDevice device = GraphicsDeviceManager.Current.GraphicsDevice;

            device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, new Microsoft.Xna.Framework.Color(0, 0, 0, 0), 10.0f, 0);

            device.RasterizerState = new RasterizerState()
            {
                CullMode = CullMode.None
            };

            device.SetVertexBuffer(_vertexBuffer);

            foreach (EffectPass pass in _effect.CurrentTechnique.Passes)
            {

                    pass.Apply();
                    device.SamplerStates[0] = SamplerState.LinearClamp;
                    device.DrawPrimitives(PrimitiveType.TriangleList, 0, _vertexBuffer.VertexCount / 3);
            }

            // set camera
            _effect.World = Matrix.Identity;
            _effect.View = Matrix.CreateLookAt(new Vector3(_x, _y, _z), Vector3.Zero, Vector3.Up);
            _effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, 2.0f, 1.0f, 100.0f);

            // move camera along a circumference
            _x = (float)(_radius * Math.Sin(_hAngle * (Math.PI / 180)));
            _z = (float)(_radius * Math.Cos(_hAngle * (Math.PI / 180)));

            // move camera along a circumference
            //_y = (float)(_radius * Math.Cos(_hAngle * (Math.PI / 180)));

            e.InvalidateSurface();
        }

```

then the error occurs on the DrawPrimitives.

Any clues about this?

# Answer
> 0 votes
According to the reference page for GraphicsDevice.DrawPrimitives(), it can throw one of two exceptions - ArgumentOutOfRangeException and InvalidOperationException - and only the former has anything to do with `primitiveCount`.

When you say the error only says "primitiveCount", that's must be the exception's description, while the type is ArgumentOutOfRangeException.

In other words, you're passing a number less than or equal to 0 as the third parameter, which means `_vertexBuffer.VertexCount` is less than or equal to 2 (probably 0), which means that .obj file with 417936 vertices probably didn't get loaded properly.

Either the .obj file is corrupt, your loader doesn't support something in the file, or there's another possible exception that's not listed in the reference. I'll put my money on the broken loader.

---
Tags: xna, c#, 3d, silverlight
---


# Question
Title: The XNA redistributable isn't in the prerequisites list; how do I include it when publishing?
So I created a small project in XNA 4.0, and wanted to try and publish it, and so I did. Yet when attempting to install it on a different computer it didn't seem to work.

I've read and studied about how the process of publishing works, and I saw someone in a different thread asking the same question as me, then I realized that inside the prerequisites list which is in `PROJECT -> PROPERTIES -> Publish`, the XNA redistributable wasn't there therefore it wasn't checked, and when attempting to install it on a different computer they needed to install redistributable on their own to make it work.

Any idea why isn't the redistributable in the list? Maybe this isn't even the problem and if that's case any ideas of what IS the problem? Thanks ahead.

# Answer
XNA things aren't in the prerequisites list for me either. Instead of that, go to the same location and click "Application Files", then make sure the Publish Status of the XNA libraries are set to "Prerequisite". To demonstrate, here's a screenshot of my settings for a new XNA project.

(Click image for full size.)
> 4 votes

# Answer
According to the EULA you can't simply include the XNA DLLs with your game - you need to add a link to the installer for the redist.

Here's the XNA FAQ on installers/prerequisites etc http://xboxforums.create.msdn.com/forums/t/1989.aspx
> 0 votes

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


# Question
Title: Java2D Shooting in a line tangent to mouse coordinates
I am making a top down shooter in Java and I need to be able to shoot in a line tangent to the mouse coordinates. In other words I need to be able to click my mouse and have a projectile spawn from my player, then move its position in a straight line in the direction of where I clicked. I have tried this already and I have failed miserably, and after looking into it for a while I haven't found a good answer. The code is pasted below, any ideas on what I'm doing wrong?

The mouse angle is calculated like this:

```
mouseAngle = (float) Math.toDegrees((float) Math.atan2(e.getY() - Player.getY(), e.getX() - Player.getX()));

```

# VectorMath class

```
package vector;

public class VectorMath {

    public VectorMath() {

    }

    public static void copyVector(Vector2f v1, Vector2f v2){
        v1.setX(v2.getX());
        v1.setY(v2.getY());
    }

    public static void printVector(Vector2f v){
        System.out.println("x: " + v.getX() + " y: " + v.getY());
    }

}

```

# Projectile Class

```
package projectile;

import java.awt.Color;
import java.awt.Graphics2D;

import player.Mouse;
import player.Player;
import vector.Vector2f;
import vector.VectorMath;

public class Bullet {

    private Vector2f pos = new Vector2f(0, 0);
    private float x,y, xVel, yVel, moveSpeed = 0.1f, dX, dY;;
    private float mouseAngle;

    public Bullet(Vector2f pos) {
        VectorMath.copyVector(this.pos, pos);
        VectorMath.printVector(this.pos);
        x = Player.getX();
        y = Player.getY();
        mouseAngle = Mouse.getMouseAngle();
    }

    public void update(){
        xVel = pos.getX() + (((float)Math.cos(mouseAngle)) / moveSpeed);
        yVel = pos.getY() + (((float)Math.sin(mouseAngle)) / moveSpeed);

        dX = x + xVel;
        dY = y + yVel;

        x = dX;
        y = dY;

    }

    public void render(Graphics2D g2){
        g2.setColor(Color.green);
        g2.fillRect((int)x, (int)y, 10, 10);
    }

}

```

# Answer
If you don't mind bullets coming from the center of the player, then you should make the mouse location into a vector, subtract the player's location vector, giving you the translation from the player's current position to the mouse cursor. Then, divide that by however many frames as you want it to take to reach the target (or normalize it to a unit vector and multiply by a given speed scalar) and set the result as a velocity vector.

If I understand your naming correctly, the following should replace your constructor and update functions:

```
public class Bullet {
  private Vector2f pos = new Vector2f(0, 0);
  private float x,y, xVel, yVel;
  private float moveSpeed = 2;
  public Bullet(Vector2f pos) {
    VectorMath.copyVector(this.pos, pos);
    VectorMath.printVector(this.pos);
    x = Player.getX();
    y = Player.getY();
    float tX = x-Mouse.getX();
    float tY = y-Mouse.getY();
    float mag = (float) java.lang.Math.hypot(tX, tY);
    tX/=mag;
    tY/=mag;
    tX*=moveSpeed;
    tY*=moveSpeed;
    xVel = tX;
    yVel = tY;
  }
  public void update(){
    x += xVel;
    y += yVel;
}

```

... rest of your code as before.
> 0 votes

---
Tags: java, shooter
---


# Question
Title: How do I translate a spherical coordinate to a Cartesian one?
Could someone point me in the right direction as to how this might be achieved? 3D math / geometry often throws me.

I'm looking for something like this (ideally in C#):

```
public Vector3 getCartesianFor(float elevation, float asimuth, float polar)
{
   return ????;
}

```

# Answer
> 5 votes
http://blog.nobel-joergensen.com/2010/10/22/spherical-coordinates-in-unity/

```
public static void SphericalToCartesian(float radius, float polar, float elevation, out Vector3 outCart){
    float a = radius * Mathf.Cos(elevation);
    outCart.x = a * Mathf.Cos(polar);
    outCart.y = radius * Mathf.Sin(elevation);
    outCart.z = a * Mathf.Sin(polar);
}

public static void CartesianToSpherical(Vector3 cartCoords, out float outRadius, out float outPolar, out float outElevation){
    if (cartCoords.x == 0)
        cartCoords.x = Mathf.Epsilon;
    outRadius = Mathf.Sqrt((cartCoords.x * cartCoords.x)
                    + (cartCoords.y * cartCoords.y)
                    + (cartCoords.z * cartCoords.z));
    outPolar = Mathf.Atan(cartCoords.z / cartCoords.x);
    if (cartCoords.x < 0)
        outPolar += Mathf.PI;
    outElevation = Mathf.Asin(cartCoords.y / outRadius);
}

```

# Answer
> 10 votes
* `r`: radial distance
* `θ`: inclination
* `φ`: azimuth

*via Wikipedia*

```
public Vector3 getCartesianFor(float radius, float inclination, float azimuth)
{
   return new Vector3(radius*Sin(inclination)*Cos(azimuth), radius*Sin(inclination)*Sin(azimuth), radius*Cos(inclination));
}

```

# Answer
> 0 votes
If by `polar` you mean the magnitude of the vector, and `elevation` is defined as the angle between vector and the xy plane (as the name implies), the function would be:

```
public Vector3 getCartesianFor(float elevation, float asimuth, float polar)
{
   return new Vector3(polar*Cos(elevation)*Cos(asimuth),
                      polar*Cos(elevation)*Sin(asimuth),
                      polar*Sin(inclination));
}

```

Note that this is very similar to MLM's answer, it all depends on how you define your `elevation` angle. I've also respected your function template signature, but I suggest a few changes:

* `asimuth` is a typo, the correct spelling would be `azimuth`
* `polar` usually refers to the 2D coordinate *system* (r, θ). The magnitude of the vector is commonly referred to as `radius`
* A more conventional order would have `radius` as the first parameter.

---
Tags: c#, geometry, coordinates
---


title: How to texture a VBO?

text:
# Question
Title: How to texture a VBO?
I'm not sure which way is the best way to do this for my purposes.
My purposes being having a textured (with an image) cube.

Also, I've been following a blend of tutorials, so I'm not sure which way is the most right and what I'm doing wrong (currently I haven't had the texture fit right).

1. Do I use glDrawArrays or glDrawElements?
2. For pointers, do I say `gl.glVertexPointer(3, GL.GL_FLOAT, 0, vertices);` and `gl.glTexCoordPointer(2, GL.GL_FLOAT, 0, textureData);`
or
`gl.glVertexPointer(3, GL.GL_FLOAT, 0, 0);` and `gl.glTexCoordPointer(2, GL.GL_FLOAT, 0, 0);`
3. When do I bind/unbind the buffers? (`gl.glBindBuffer(GL.GL_ARRAY_BUFFER, VBOVertices); gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vboTextureCoordHandle);`) Before I establish the pointers or not in my drawing method at all?
4. Do I need to specify the UV coordinates/Texture Coordinates in the shader? If I'm getting a weirdly stretched texture, does that mean my fragment shader and setting the uniforms is working correctly?

Thank you!
I can supply more code, but I think I just need more information on the basics.

# Answer
1. Depends whether you use indices(elements) or not (arrays).
2. niether, you should use gl.glVertexPointer(3, GL.GL\_FLOAT, stride, (const GLvoid \*) offsetOfFirst), unless you lib overrides it ofcourse.
3. no idea, sorry, I use attributes
4. means you pass wrong UVs. To shader you pass only sample location. (make sure UVs are in range 0.0 - 1.0)
5. you really should find alternative tutorial if you dont understand part of one
> 0 votes

---
Tags: textures, shaders, vbo, jogl
---


# Question
Title: How do I take Direct3D9 full screen using SlimDX?
I'm writing a Direct3D9 application wrapped by SlimDX. I'm trying to take my application full screen but I am having problems. I can reset the device so that it covers the entire screen, however, it seems as though the device window loses focus. The cursor belongs to that of the window beneath my device window. When I click on the screen(while in full screen mode) the window beneath my device window gets focus. This shouldn't happen.

In my c# code for managing the device I have converted DXUT(from the DirectX SDK) to c#...There is a lot of code to cover but I was hoping for a theoretical answer.

What is happening to the device as I take the app full screen? Why does the window beneath the device window get focus while the device window continues to render and cover the screen?

Could my problem have anything to do with the fact that Windows Forms draws with GDI? I found a post here that describes a problem that differs in result but may be along the same lines wrt cause.

# Answer
> 1 votes
The problem was due to the nature of controls found in Windows Forms. From MSDN:

*A control can be selected and receive input focus if all the following are true: the Selectable value of ControlStyles is set to true, it is contained in another control, and all its parent controls are both visible and enabled.*

The device window in my application belongs to a parent window and the parent window becomes nonvisible once fullscreen is enabled. Its possible that a conflict arose due to the 'focus rules' above. To test the theory I examined the return value from DeviceWindow.Focus()(derives from Control.Focus())...which returned false.

My solution was to create a form used for the sole purpose of fullscreen mode changes. Now, when I want to go fullscreen I reset the device with the handle to the new device window. All problems solved...

---
Tags: c#, directx9, slimdx
---


title: Detecting walls or floors in pygame

text:
# Question
Title: Detecting walls or floors in pygame
I am trying to make bullets bounce of walls, but I can't figure out how to correctly do the collision detection. What I am currently doing is iterating through all the solid blocks and if the bullet hits the bottom, top or sides, its vector is adjusted accordingly. However, sometimes when I shoot, the bullet doesn't bounce, I think it's when I shoot at a border between two blocks.

Here is the update method for my Bullet class:

```
def update(self, dt):
    if self.can_bounce:
        #if the bullet hasnt bounced find its vector using the mousclick pos and player pos
        speed = -10.
        range = 200
        distance = [self.mouse_x - self.player[0], self.mouse_y - self.player[1]]
        norm = math.sqrt(distance[0] ** 2 + distance[1] ** 2)
        direction = [distance[0] / norm, distance[1 ] / norm]
        bullet_vector = [direction[0] * speed, direction[1] * speed]

        self.dx = bullet_vector[0]
        self.dy = bullet_vector[1]

    #check each block for collision
    for block in self.game.solid_blocks:
        last = self.rect.copy()
        if self.rect.colliderect(block):
            topcheck = self.rect.top < block.rect.bottom and self.rect.top > block.rect.top
            bottomcheck = self.rect.bottom > block.rect.top and self.rect.bottom < block.rect.bottom
            rightcheck = self.rect.right > block.rect.left and self.rect.right < block.rect.right
            leftcheck = self.rect.left < block.rect.right and self.rect.left > block.rect.left
            each test tests if it hit the top bottom left or right side of the block its colliding with
            if self.can_bounce:
                if topcheck:
                    self.rect = last
                    self.dy  *= -1
                    self.can_bounce = False
                    print "top"

                if bottomcheck:
                    self.rect = last
                    self.dy  *= -1 #Bottom check
                    self.can_bounce = False
                    print "bottom"

                if rightcheck:
                    self.rect = last
                    self.dx  *= -1 #right check
                    self.can_bounce = False
                    print "right"

                if leftcheck:
                    self.rect = last
                    self.dx  *= -1 #left check
                    self.can_bounce = False
                    print "left"

            else:
                # if it has already bounced and colliding again kill it
                self.kill()

    for enemy in self.game.enemies_list:
        if self.rect.colliderect(enemy):
            self.kill()
    #update position
    self.rect.x -= self.dx
    self.rect.y -= self.dy

```

This definitely isn't the best way to do it but I can't think of another way. If anyone has done this or can help that would be awesome!

# Answer
If you try and do the X and Y collision at the same time, you will find it troublesome to implement any kind of bouncing; it's more effort to calculate which way the object will need to bounce.

To remedy this, we can split up the X and Y collision calculation, and the velocity reversing calculation. some pseudocode:

```
move(int x, int y){
    pos.x += x;
    checkHorizontalCollision();
    pos.y += y;
    checkVerticalCollision();
}

```

the checkXCollision methods simply reverse the velocity and maybe remove some depending on your requirements.
> 1 votes

# Answer
Pygame has a built in and very good collision detection function for sprites. If you have one sprite, and want to tell if it is colliding with members of another group of sprites, you can do this:

```
collisions = pygame.sprite.spritecollide(<sprite>,<group>,False)     #argument one is the sprite, argument two is the group to test collisions with the sprite for, and the final argument should almost always be False, because when it is True, colliding sprites will automatically get deleted.
for item in collisions:                                              #Spritecollide returns a list of colliding sprites. This will iterate through them.
    if item != <sprite>:                                             #spritecollide will also always return that the sprite is colliding with itself. this will filter that out, because you don't want this information.
        print "collision detected, insert code to run on collision here or return True from a function"

```

This should work fine.
> 0 votes

---
Tags: collision-detection, vector, python, pygame
---


title: cocos2d-x "immediate mode"?

text:
# Question
Title: cocos2d-x "immediate mode"?
I have some c++ game code that draws the game state on each game-loop cycle in "immediate mode". By that I mean that the game code does not add the sprites to be drawn to any sort of "scene graph" or other data structure. It just starts from a blank slate on each game loop cycle, and piles on the sprites from back to front. (I know you might wonder *what* API this c++ code is actually using. Well, it's written in Marmalade, which I'm moving away from. Marmalade provides an abstraction layer and the essence of this question is about replacing that abstraction layer.)

I am having trouble understanding what "immediate mode" really means in opengl es, and how it relates to the "fixed function" vs. "programmable" pipeline. Some things I read say, don't use the old immediate mode functions, use the modern shader-based programmable API instead." But at the same time, I believe glDrawArrays() is fine to use in opengl es 2.0, right? So that's an "immediate mode" function.

(I believe what's going on here is that "immediate mode" means different things at different levels. My understanding is that a library like cocosd2-x is "retained mode" in that you add sprites to a scene graph that's managed by the engine. But at the opengl level itself, I think "immediate mode" means something a bit different, namely whether you keep the vital drawing structures in CPU space until you draw them with a begin() end() sandwich, versus uploading them ahead of time to the GPU. So it that sense the GPU "retains" your data across calls. But still, you can draw a frame in "immediate" mode in the sense of piling on sprites one at a time using glDrawArrays() as many times as necessary.)

In the "hello world" example of cocos2d-x, we see

```
// add the sprite as a child to this layer
this->addChild(sprite, 0);

```

That is exactly what I *don't* want to have to do, because as I say, my code base is set up not thinking of the sprites as objects, but just as drawing a bunch of rectangles from texture sheets (atlases) stacked on top of each other. I don't want to think of adding sprites to some scene graph and "letting the engine take care of it." That may be a fine way of thinking in general, but it would involve a huge rewrite of my existing code.

On the other hand, I *think* I like the idea of cocos2d-x because it gives me a convenient way to develop a code base that I can develop on Windows and run on iPhone, Android, and elsewhere.

So what I'm trying to understand is: Can I use cocos2d-x in some "immediate mode" fashion?

Basically, in opengles 2.0, I am allowed to call glDrawArrays(), correct? And if I batch up my sprites in a reasonable way, I can limit the number of calls to glDrawArrays() in each frame. So I want to do that, and I'm fine writing that gl code myself. But I *think* even though perhaps this defeats some of the point of using cocos2d-x in the first place, there are still huge portability and not-reinventing-the-wheel advantages of using cocos2s-x vs writing things from scratch myself?

So can I use cocos2s-x in that "immediate mode" way, and still retain the write-once/run-everywhere benefits?

# Answer
Cocos2d-x can draw in immediate mode, it's way easier to be done in 2.x but it's possible in 3.x as well. basically you have two ways of doing that:

* The easiest route is to create your own class inherited from CCNode (or Node if you are using v3.x) and override it's `void draw()`(or for v3.x `void draw(Renderer *renderer, const Mat4& transform, uint32_t flags);`) function.
This is how most of cocos2d classes are implemented themselves. For example that CCSprite you mentioned, does the same thing behind the hood.
* A more complex method is to override 'void visit' (or for v3.x `virtual void visit(Renderer *renderer, const Mat4& transform, uint32_t flags);`) function. Normally this function does all this nodes transformations, then start rendering all it's children from the least zOrder to the highest. Also it calls it's draw function before it's first child with zOrder=0.
* In case you are using cocos2d-x v3.x you should use CustomCommand.

So when should you override each of those functions? Think of it this way, is this class of yours going to integrate inside cocos2d code flow, or are going to break everything, and implement your own stuff all over? If it's the former, I suggest you go with overriding draw method, and if it's the later overriding visit is wiser.

If you want more exact information on how is each frame processed in cocos2d-x, take a look at `Director::drawScene()`, you'll basically find, in each frame, these are done in specified order:

1. Compute delta\_time
2. Process input (aka. touch events, key events, ...)
3. Update functions & actions
4. call visit function on the running scene
5. (in case of v3.x) do actual rendering stuff
> 1 votes

---
Tags: opengl-es2, cocos2d-x
---


title: Swiching screen at collision LIBGDX

text:
# Question
Title: Swiching screen at collision LIBGDX
I am programming with LIBGDX and I am working with a piece of code. What I want to happen is that when the BUCKET collides with a DROP the game switches screens back to the menuScreen. I have tried to do it as you will see in the code but when the bucket collides with a drop nothing happens. Please Help me on how to fix this. Here is all the code:

DROP CLASS:

```
public class Drop extends Game{

public SpriteBatch batch;
public BitmapFont font;

public void create() {
    batch = new SpriteBatch();
    //Use LibGDX's default Arial font.
    font = new BitmapFont();
    this.setScreen(new MenuScreen(this));
}

public void render() {
    super.render(); //important!
}

public void dispose() {
    batch.dispose();
    font.dispose();
}

}

```

MENU SCREEN CLASS:

```
public class MenuScreen implements Screen {

final Drop game;

OrthographicCamera camera;

public MenuScreen(final Drop gam) {
    game = gam;

    camera = new OrthographicCamera();
    camera.setToOrtho(false, 800, 480);

}

@Override
public void render(float delta) {
     Gdx.gl.glClearColor(0, 0, 0.2f, 1);
     Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        camera.update();
        game.batch.setProjectionMatrix(camera.combined);

        game.batch.begin();
        game.font.draw(game.batch, "Welcome to Drop!!! ", 100, 150);
        game.font.draw(game.batch, "Tap anywhere to begin!", 100, 100);
        game.batch.end();

        if (Gdx.input.isTouched()) {
            game.setScreen(new GameScreen(game));
            dispose();
        }
}

@Override
public void resize(int width, int height) {
    // TODO Auto-generated method stub

}

@Override
public void show() {
    // TODO Auto-generated method stub

}

@Override
public void hide() {
    // TODO Auto-generated method stub

}

@Override
public void pause() {
    // TODO Auto-generated method stub

}

@Override
public void resume() {
    // TODO Auto-generated method stub

}

@Override
public void dispose() {
    // TODO Auto-generated method stub

}

}

```

GAME SCREEN CLASS:

```
public class GameScreen implements Screen {

Texture dropImage;
Texture bucketImage;
Sound dropSound;
Music rainMusic;
MenuScreen menuScreen;
Drop game;
OrthographicCamera camera;
SpriteBatch batch;
Rectangle bucket;
Array<Rectangle> raindrops;
long lastDropTime;
boolean isBucketJumping;
float bucketYSpeed = 1;
float GRAVITY = 1;

public GameScreen(final Drop gam) {
    this.game = gam;
    // load the image for the droplet and the bucket, 48X48 pixels each
    dropImage = new Texture(Gdx.files.internal("cloud100.png"));
    bucketImage = new Texture(Gdx.files.internal("plane100.png"));

    //load the drop sound effect and the rain background "music"
    dropSound = Gdx.audio.newSound(Gdx.files.internal("drop.wav"));
    rainMusic = Gdx.audio.newMusic(Gdx.files.internal("rain.mp3"));

    //start the playback of the background music immediately
    rainMusic.setLooping(true);
    rainMusic.play();

    menuScreen = new MenuScreen(game);

    camera = new OrthographicCamera();
    camera.setToOrtho(false,800,480);

    batch = new SpriteBatch();

    bucket = new Rectangle();
    bucket.x = 250;
    bucket.y= 200;
    bucket.width = 100;
    bucket.height = 100;

    raindrops = new Array<Rectangle>();
    spawnRaindrop();
}

@Override
public void render(float delta) {
    Gdx.gl.glClearColor(0x64/255.0f, 0x95/255.0f, 0xed/255.0f,
             0xff/255.0f);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

    if(Gdx.input.isTouched())
    {
    bucketJump();
    }
    moveBucket();
    camera.update();

    batch.setProjectionMatrix(camera.combined);
    batch.begin();
    batch.draw(bucketImage,bucket.x,bucket.y);
    for(Rectangle raindrop: raindrops){
        batch.draw(dropImage,raindrop.x,raindrop.y);
    }
    batch.end();

    if(TimeUtils.nanoTime() - lastDropTime > 2000000000) spawnRaindrop();

    moveRainDrop();
}

public void bucketJump(){
    isBucketJumping = true;
    bucketYSpeed = 7;
}

public void moveBucket(){

       bucket.y += bucketYSpeed;
       bucketYSpeed -= GRAVITY;

}

@Override
public void dispose() {
    dropImage.dispose();
    bucketImage.dispose();
    dropSound.dispose();
    rainMusic.dispose();
    batch.dispose();
}

private void moveRainDrop() {
    Iterator<Rectangle> iter = raindrops.iterator();
    while(iter.hasNext()){
        Rectangle raindrop = iter.next();
        raindrop.x -= 200 * Gdx.graphics.getDeltaTime();
        if(raindrop.x + 48 < 0) iter.remove();

        if(raindrop.overlaps(bucket)){
            dropSound.play();
            menuScreen.show();
        }
    }
}

private void spawnRaindrop(){
    Rectangle raindrop = new Rectangle();
    raindrop.y = MathUtils.random(0,450-48);
    raindrop.x = 800;
    raindrop.width = 110;
    raindrop.height = 100;
    raindrops.add(raindrop);
    lastDropTime = TimeUtils.nanoTime();
}

@Override
public void resize(int width, int height) {
}

@Override
public void pause() {
}

@Override
public void resume() {
}
@Override
public void show() {

}
@Override
public void hide() {
}
}

```

# Answer
> 0 votes
In your `GameScreen` class do not initialize a new `MainMenuScreen` object in the constructor. Instead, when the drop collides with the bucket, call a method called `returnToMain()` or something like that, and within that method, initialized a new `MainMenuScreen` object and assign it to the game's screen: `this.game.setScreen(new MainMenuScreen(game))`. This is how I would do this, given your project's setup.

---
Tags: java, android, libgdx, screen, eclipse
---


# Question
Title: Play animation when click on each player with in maincamera unity3d
I have 3 gameobjects (`player1`, `player2`, `player3`). I attached a script "playerscript" to these game objects. In the main camera, I have added another script called "testscript". Clicking on a player should play the animation. For that, I need to call the `update()` of "testscript.cs" in maincamera to the `onMouseDown()` of "playerscript.cs".

*testscript.cs*:

```
public class testscript : MonoBehaviour {
public bool selected;
public GameObject player1;
public GameObject player2;
public GameObject player3;

void Update () {
    //animation PickRightAndLeft
    player1.animation.Play("PickRightAndLeft");
}

```

*playersscript.cs*:

```
public class Playersscript : MonoBehaviour {
     void OnMouseDown () {
         Debug.Log (gameObject.name);
      }
}

```

# Answer
so if i understand you correctly you actually have the test script attached to the player object not the camera?

if so you'll need to make sure you have done 3 things:

1. ensure the player game objects have `Animation` components
2. get the Animation component into a variable in your script ( i prefer to do this when accessing objects from across scripts but it may not be always necessary )

`public anim = GameObject.GetComponent<Animation>();`
3. on mouse down of the `testscript` you can now play the named animation

`OnMouseDown(){ anim.Play("walk"); }`

---

you want to access your camera's script component from within the player scripts. once you have access to that, as long as the scope is set properly, you should have access to calling the methods from the other script.

so within your `Playerscript.cs` : `OnMouseDown()` method you will want to start somewhere like this:

```
YOURCAMERA.GetComponent<YOURSCRIPT>().YOURMETHOD();

```

this structure should access the camera, look for the script youve attached to it and then attempt to call a method defined within that script.

obviously you may want to be more specific about your camera, the script, and method names. and i would recommend to use an exact reference to your camera in case your game is using multiples - which will cause this to fail from the get go. (replace Camera.main, with your actual camera).

you will also need to reference your script name and the method you wish to call like so:

```
Camera.main.GetComponent<testscript>().Update();

```

## reference material

GameObject.GetComponent documentation

Unity "accessing other scripts"
> 1 votes

# Answer
I'd say a more modular option than referencing your main camera is simply adding a public field to hold a reference to TestScript. Also you should change the name of the `Update` method, as it has a special meaning in Unity:

```
 public class Playersscript : MonoBehaviour
 {
   public TestScript MyTestScript; //Set this in the inspector
   void OnMouseDown ()
   {
       Debug.Log (gameObject.name);
       MyTestScript.MyUpdate();
   }

}

```
> 0 votes

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


title: How to make healthbar decrease in unity

text:
# Question
Title: How to make healthbar decrease in unity
I want to build a health bar which show's the energy of the player.I have two buttons "PLAY" and "IDLE" to show the animation.when I click on the "PLAY" button the character start running along with that the health bar should decreases it's energy.Here is the code written for the two button clicks

```
void OnGUI()
{
            if (GUI.Button (new Rect (100, 200, 50, 50), "PlAY")) {
                    animation.Play ("run");
            }
    if (GUI.Button (new Rect (100, 500, 50, 50), "IDLE")) {
        animation.Play ("idle");
    }
    }

```

Now I need to create a health bar to show the decreasing of energy when the player starts its animation.Could you please help me in coding out creating energy bar.

Done the code for creating the progress bar,but the bar is not getting decremented.Here is the code

```
private float loadBarProgress = 0.0f;
private const float loadBarSpeed = 0.25f;
public Texture loadBarTexture = null;
void OnGUI()
{
    //Draw loading bar with offset texture coordinates
    GUI.DrawTextureWithTexCoords(new Rect(Screen.width * 0.4f, Screen.height * 0.4f, Screen.width * 0.2f, Screen.height * 0.1f), loadBarTexture, new Rect(loadBarProgress, 0.0f, 1.0f, 1.0f), false);
}
// Use this for initialization
void Start ()
{

}

// Update is called once per frame
void Update ()
{
    //Move the bar along; keep it's position between zero and one for best float point precision
    loadBarProgress += Time.deltaTime * loadBarSpeed;
    if (loadBarProgress >= 1.0f) loadBarProgress -= 1.0f;
}

```

# Answer
> 1 votes
To normalize a value divide it by the maximum amount allowed. So if your character can have a maximum energy amount of 100 and has a current energy level of 30.... 30/100=0.3

Same works for any numbers Max energy 340 current energy of 50.... 50/340 = 0.147 Be aware if your doing this math in c# on integers you'll need to cast them to float before the operation like this,

```
scale = (float)currentEnergy / (float)maxEnergy;

```

if current and max are already floats you can skip the casting into floats

So your `Rect` should be made using this multiplier.

```
GUI.Button(new Rect(10, 40, 100 * scale, 20), "Energy");

```

So simply update your `currentEnergy` variable somewhere in your code and the bar will scale accordingly.

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


# Question
Title: Algorithm for texture blending modification
Im currently writing a terrain editor for my game (for the record: no commercial intentions) and after having implemented the terrain morphing to my liking im now working on the texturing of said terrain. One chunk of terrain can consist of up to 4 different layers of textures which are blended together using a 4-byte rgba texture with alpha values. The alpha values are 0-255 and together add up to 255, so the blending on the gpu happens like this:

```
float4 finalColor = color0 * alpha.r + color1 * alpha.g + color2 * alpha.b + color3 * alpha.a;

```

In a first approach ive been doing very simple modification of that blending (pseudocode):

```
selectedLayer.alpha += amount;
allOtherLayers.alpha -= (amount / numOtherLayers);

```

This doesnt work all too bad but it creates a lot of artifacts or sharp lines between chunks. Here is an example image:

Now im looking for different, better algorithms. The brush currently consists of an inner and an outer radius (as seen in the image). Inside the inner radius no interpolation depending on the distance to the center happens, between inner and outer radius linear interpolation between the pressure on the inside and 0 is created.

I hope my question is clear enough, please leave a comment if there has to be more information. Thank you in advance.

# Answer
I think I understand what you are trying to do. You want the sum of all layers' alpha to be 1 so that there the total color is overdrawn.

You are on the right track. But your error seems in the way you compute the alphas.

Take for example this starting point:

```
1: 0.7
2: 0.3
3: 0.0

```

Now you apply 0.5 on layer 3, the result should look something like:

```
1: 0.35
2: 0.15
3: 0.5

```

You wan the original ratio between layer 1 and layer two preserved. The sum of remainder should be `1/amount`.

So the correct way should be:

```
allOtherLayers.alpha *= 1/amount;

```

or

```
allOtherLayers.alpha /= amount;

```
> 1 votes

---
Tags: c++, textures, terrain, blending
---


title: Water silhouette shader using GLSL

text:
# Question
Title: Water silhouette shader using GLSL
I have this problem to solve using Cocos2d-x 3.x: In my game there is water represented by rectangle texture, modified by the code on the go. I also have a character moving around, rotating etc.

I would like to achieve silhouette effect when he goes into the water - so if pixel of character texture is not transparent and pixel of water texture is not transparent, color should be changed lets say to gray. I would like it to work as fragment shader added to character sprite.

The problem is that I have no idea how to go from character UV coords to water texture coords (positions, rotations and dimensions of textures are different). I am also not sure the approach proposed by me is the correct one, maybe there is better way to do it?

Could you please give me some thought how it should be done? Any code is welcome too!

Edit: here is a visualization, red triangle is character, it changes color as it submerges

# Answer
I would implement it as a multipass algorithm, a bit similar to shadow maps. You render the character to a frame buffer, color(RGBA) and depth(Z). Now you simply apply the frame buffer to the regular buffer (with depth). Then you render the watter, you sample from the frame buffer. If the value A=0, you render the watter normally. If A!=0 and Z\>=current depth, you take RGB and do whatever effect you want to do.
> 2 votes

# Answer
An easy way would be to first render the object and then render the water using multiplicative rendering (i.e. modulate the frame buffer color with water color). Not quite sure if it gives you the result you want though (you could test it in Photoshop for example). If you want more control you would have to first render the object, copy the result to a texture and then render the water using the texture as an input for the water fragment shader that does some custom color composition with it.
> 0 votes

---
Tags: opengl, shaders, glsl, cocos2d-x, fragment-shader
---


# Question
Title: Why does my object instantiation work, but return null?
For some reason, the `LogError` runs:

```
Player clone = Instantiate(player, this.transform.position,
    Quaternion.identity) as Player;

if(!clone) { Debug.LogError("WTF"); }
else       { Debug.Log("WE GOT IT"); }

```

My object appears, but if I try to do anything with it afterwards its value is `null`, and the `if(!clone)` triggers.

Why is this happening?

The player is a gameobject and is assigned (its my player prefab) and Player is what my prefab is called. I also have a `Player.cs` script. Is Unity confusing my prefab and script or something?

# Answer
The Instantiate function returns an abstract Object reference, that's why it effectively instantiates the object but it is also gives you a type error.

What you need to do, in order to access your Player script, is something similar to the following

```
GameObject obj;
obj = Instantiate(playerPrefab, Vector3.zero, Quaternion.identity) as GameObject;
Player player = obj.GetComponent<Player>();

```

And that's it.
> 3 votes

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


# Question
Title: Why can't I load an image with a relative path in SDL2 on Linux?
When loading a texture in SDL2 the general procedure is this:

```
SDL_Texture* texture = IMG_LoadTexture(renderer, "resources/images/image.png);

```

However this doesn't work and I have to supply the WHOLE path to the specific image. The code that I have to use is:

```
SDL_Texture* texture = IMG_LoadTexture(renderer, "/home/user/programs/game/resources/images/image.png);

```

This issue doesn't occur in a Windows Mingw32 environment.

Any suggestion on how to fix this issue?

# Answer
It's possible that you're running the executable in a different directory than the one that contains your `resources` folder.

If you need to change the directory from, say, a makefile, just `cd` to the desired base directory and run the executable from there.
> 2 votes

# Answer
You can get this information with the following code:

```
char buffer[256];
char *getcwd( buffer, 256 );

```

One hint: when the working directory differs from the place where the binary is stored: do you start the app from an IDE like QtCreator. If yes: please change the working directory for the run in your IDE.
> 1 votes

---
Tags: c++, sdl, linux, sdl2
---


title: Rendering a mesh in image viewport

text:
# Question
Title: Rendering a mesh in image viewport
I have a mesh made of nearly half to a one million vertices. I also have some 6-DoF camera poses around this mesh. At these poses I'd like to find out which of the 3D points of this mesh get projected inside the image viewport of size 640x480. Basically I'd like to get the indices of the 3D points that fall inside this image window at a given pose. What is the best way to do it? Are there any shader functions or OpenGL functions that can allow me to do this quickly?

# Answer
The term you're looking for is Frustum Culling. The problem is this doesn't work too well on individual vertices, because a vertex may be required for a face that is inside the frustum even if the vertex itself isn't. It would be too slow to do that every frame anyway.

If neither the mesh or cameras move, or they move predictably so you can precalculate everything, you can probably do the culling per-face. But then I'm not sure why you wouldn't just make renders of the thing in some 3D modelling software.

So if you really need culling in real-time, I recommend splitting the mesh into multiple parts that can be culled individually.

Other than that, this link can get you started, and Google should help with the rest, now that you know what it's called.
> 2 votes

---
Tags: opengl, shaders, rendering, frustum, frustum-culling
---


# Question
Title: Where can I get DirectX headers for Mingw?
I have downloaded the latest Mingw toolchain from mingw.org, but it seems DirectX headers are missing. Where can I get those?

I assume there are open source compatibility headers out there, in particular for ddraw.h, which is deprecated by Microsoft.

# Answer
> 1 votes
The MAME development site recommends using these headers from WINE; the particular zip they link is from a year ago, so you may be able to extract more recent (and presumably, somehow better) headers from WINE itself.

# Answer
> 1 votes
Are you sure you have installed mingw's dist of the win32 api? I do believe the dx headers are part of that package. Do note that dx9 is the latest dx version available with mingw and that it is not complete (if you're hoping to use d3d, however, you should be good to go).

# Answer
> 1 votes
You won't find ddraw in this one, but google dx9mgw for the directx 9 ones. Then, when you build your release, be sure to disable strict aliasing by either not doing speed optimization above -0 or -1 or by disabling strict aliasing optimizations with a compiler directive. Or I guess update the headers if you want to.

---
Tags: directx, windows, c, mingw
---


# Question
Title: How can glass breaking effect from Smash Hit be achieved?
I saw Smash Hit the other day and was amazed by the physics of the game, specially the shattered glass effect:

I've read other posts about this subject but I still feel that they don't share enough details to let me get started on implementing this on my own with OpenGL/GLSL.

**Is it possible for somebody with an enhanced perception and graphics understanding to watch the gameplay and give some pointers on how this effect could be replicated?**

I rather not use 3rd party physics engine and do the entire thing on my own for educational purposes, so could you mention some of the physics that goes behind this as well?

References to other documents and demos are highly appreciated.

# Answer
> 5 votes
This is a pretty advanced topic. Generally people like to use Boolean Set Operations implemented with a BSP tree for this kind of destruction, which revolves around splitting polygons over planes. Take a look at this paper by Naylor to learn how.

This will let you overlay one mesh upon another and perform a subtraction. The results of the subtraction can give you the mesh with a carved out volume.

You'll also perform an intersection to find the carved out volume itself. Given this intersection volume, you can use any sort of approximation to simulate a shatter effect. Generating random planes and slicing the volume can work! The sliced up intersection can then be simulated as a bunch of rigid bodies, and you can just let them all fall.

Since all of these operations work with meshes you'll need some kind of boundary representation of your geometry. Generally people like half-edge mesh the most (myself included).

Here the author briefly talks about his technology for the destruction in this game.

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


title: Emscripten code and three.js

text:
# Question
Title: Emscripten code and three.js
I would like, if it's possible, to use Emscripten code generated from C/C++ with the Javascript library three.js. For example, from emscripten code I want to pass rendering information to the three.js that will be showed in the browser.

So, can someone give me an idea of how to do that?

# Answer
> 2 votes
You have multiple ways to interact from c++ to javascript. I can show you one way I find quite handy:

in the js library file

```
// here you write JS "handlers"
mergeInto(LibraryManager.library, {

   new_cube: function(size, color) {
      var cube = new THREE.Mesh(
         new THREE.BoxGeometry(size, size, size),
         new THREE.MeshBasicMaterial({ color: color })
      );
   }

});

```

in c++

```
extern "C" {
    extern void new_cube(const int size, const char* color);
}

int main() {
  new_cube(10, "red");
  return 1;
}

```

in the build command

```
emcc source.cpp --js-library src/library.js

```

for easy debugging (but very slow)

```
#include <emscripten.h>
void emscripten_log(const char* string, bool escape = true)
{
    char buff[1024];
    sprintf(buff, (escape ? "console.log('%s');" : "console.log(%s);"), string);
    emscripten_run_script(buff);
}
void emscripten_debugger()
{
    emscripten_run_script("debugger");
}

```

---
Tags: c++, c, three.js
---


# Question
Title: How do I get the number of online players in a Minecraft server from outside the client?
I know that the Minecraft client can query the server for number of players and maximum players, even when the server properties has `enable-query` set to `false`, but how do I do this outside of the client? I am trying to implement this as part of a mobile (Android) app.

# Answer
This is actually quite well-detailed at this page. Please note that I am going to detail the common protocol introduced in version 1.7. Additionally, a new protocol was introduced in 1.9pre4 that contains additional information not found in the previous protocol. Let me detail how to get the basic server information in 1.7+:

1. Send a "handshake" packet with the layout:

* 0x00 (Packet ID)
    * 0x04 (Protocol Version)
    * Length of server address. This is a VarInt, which means that it has a variable length. The last bit of each byte that would normally indicate the sign instead indicates if the next byte is part of the VarInt.
    * Server address (Host Name or IP Address)
    * Server port (as a Short, Big-endian)
    * 0x01 (Next State)
2. Send a blank "Status Request" packet with the layout:

* 0x00 (Packet ID)
3. Reading the response, you will get a JSON-encoded object with the following format:

* Version
        1. Name
        2. Protocol
    * Players
        1. Max
        2. Online
        3. Sample
    * Description
        1. Text
    * Favicon
        1. Mime-type;encoding,

Since you are writing this for Android, I presume you are using Java. Luckily for you, there is already an open-source Java project that details these steps already made for you. Even better, it shows proper use of VarInt when formatting your packets.
> 5 votes

---
Tags: java, mobile, minecraft-modding
---


# Question
Title: Unable to draw single particle effect at two places
I am using Libgdx ParticleEffect to draw a fire particle effect .

The issue I have is that when I try to render a ParticleEffect at two different locations within single game loop, only the last draw call has the effect drawn on screen. I update the Particle effect only once per game loop but set its position to two distinct locations and draw it. Is this a trivial problem with Libgdx ParticleEffect:

```
ParticleEffect effect = new PartcleEffect();
effect.load(gdx.files.internal("data/effect.particle"),atlas,"");
effect.start();

```

In render :

```
effect.update(deltaTime);

effect.setPosition(x1,y1);
effect.draw(batch);

effect.setPosition(x2,y2);
effect.draw(batch);

```

Can someone tell me why it isn't working?

# Answer
> 1 votes
When you call `effect.setPosition(...)`, it changes the position of all the **emitters**, but **not of the particles**. In libGDX, there is currently no way of changing the position of a single particle, so in order to draw particles at 2 locations, you must do the following:

```
// Pseudo-code
move effect at position 1
add particles
move effect at position 2
add particles
update effect
draw effect

```

You must create particles at the 2 different locations to achieve the effect you want.

# Answer
> 1 votes
you have to create an array of pooled effects

```
Array<PooledEffect> effects = new Array<PooledEffect>();

```

so, in render(), you draw all effects from array.

```
for(int i = 0; i < blocos.size();i++){
            if(obj.colision(block.get(i),config)) {

                PooledEffect effect = block.get(i).getEffectPool().obtain();
                effect.setPosition(block.get(i).getX(), block.get(i).getY());
                effects.add(effect);

                blocos.remove(i);
            }

        }

```

---
Tags: libgdx, particles
---


# Question
Title: Data structures for territories in a 2D map
I am diving into game development with a 2D game. The game will display a territorial map (borders, capitals, etc.).

What is a common data structure to use for storing and manipulating the data in such a game? I'm considering using a graph (as in Graph Theory, not graphing).

Also, what are common file formats for storing the "polygon data" for each territory? Are there any standard or semi-standard formats?

# Answer
# Data structure

## Vector of vectors (a.k.a. array of arrays)

Using this data structure allows you to consider vertices and edges (specially useful when dealing with one-way streets or roads) and it also let's you consider more efficient maps, leaving out obstacles.

In this case you would use at least two vector of vectors; one for storing the vertices and the edges and the other one for storing node membership to regions (countries, for example).

An extra vector of vectors could be use to store cities that belong to a country, for example. It depends on the specific problem you're targeting.

# Data representation for tactical analysis

## Influence maps

This technique is great when dealing with grids in order to develop tactical analysis and tag each location as part of a region and such.

## Map flooding

Now that you're thinking about graph theory, and developing your graph using Dirichlect domains, this technique comes in handy for tactical analysis and is very similar to having influence maps on a grid.

# Saving data

Nowadays developers are more inclined into these standard formats and there are several file handlers for your platform of choice.

* JSON
* XML
* YAML

It's good that you research them in depth and decide which one is more suitable to your project.
> 2 votes

---
Tags: 2d, maps, data-structure, file-format
---


title: How do I make a fiery particle system?

text:
# Question
Title: How do I make a fiery particle system?
I added a particle system to the flame-emitting object in my Unity scene. But it's just little white balls, and I can't figure out how to make it fiery.

Anyone?

Everything I see on the internet involves buying some asset pack that somebody put together. Does Unity really not have any built in flames stuff?

# Answer
> 1 votes
Unity has a built-in fire particle effect package. Just import the 'Particles' standard asset package. It will include small and large flames (and they even have a smoke element to them). You can toy with that to get what you want.

# Answer
> 0 votes
Fire is colored like this:

HOTTER ---------------\> WARMER

BLUE -\> WHITE -\> ORANGE -\> RED

Have you tried to change the particle color over time? Maybe start with orange to red and fade the alpha over time.

# Answer
> 0 votes
Unity preinstalled assets arent too great to see but they are just as exemple!

If you'd like to make more realistic fire emitter i suggest you to search in assets store, and also I'm not so sure that the particle emitter would be the better choise for you.

I suggest you to use an Halo like base for your flame (a very little halo could give a great visual support) an than use a third part program to make the fire, Unity isnt the best tool for doing graphical stuffs. :)

You can check this, maybe it can help: http://forum.unity3d.com/threads/2875-Smokey

# Answer
> 0 votes
Ok, So look at the menu in the inspector that says Particle system. Scroll down and click renderer. click on material then search for the fire particle. **SORRY FOR SO LATE ANSWER**

---
Tags: unity
---


title: Designing a scriptable questing system

text:
# Question
Title: Designing a scriptable questing system
I'm currently working on a scriptable questing system. As for scripting, I will probably use JavaScript, but I'd appreciate some help with the design of the system. My first attempt essentially resulted in something which was way too complicated to script, and wasn't plausible at all.

My objectives for the system are as follows:

* Branchable (probably not a real word) - So there can be multiple different outcomes for the same objective depending on what the player chooses, and their choices will affect which quests they move onto next.
* Not ridiculously complicated.

Obviously, I'm not here to be given a list of everything I need to do. Ideally, I'd like some tips on how to store progression and a basic idea of how branching would work.

Some details: I'm writing in Java, and I ideally want there to be many options in terms of types of objectives. I can implement these easily enough - my problem is more the structure of a quest. I'm writing the quest system on top of an already existing game - said game uses LWJGL and does it's own engine-stuff, it doesn't use an engine.

# Answer
> 6 votes
A common way to implement states and branching in a quest is through quest variables. I have witnessed this technique in many RPG titles from companies like Bioware or Bethesda. This is also what I am doing in my current project, and so far it works really well.

Just add a script binding which allows scripts to store values in variables and later retrieve them. Also allow events in the game to set these variables (entering an area, killing a specific enemy etc).

This already allows you to do some nice things. In javascript, this could look like this:

```
function talkToDragonQuestGiver(user) {
     var dragonQuestState = user.getVar("DragonQuest")
     switch (dragonQuestState) {

         case null:
             say("Go, slay the dragon and I will reward you.");
             user.setVar("DragonQuest", "active");
             break;
         case "active":
             say("What are you doing here? You have a dragon to slay!");
             break;
         case "dragonDead":
             say("You have slain the dragon. Here, have this bragging rights reward.");
             user.giveItem("Sword of Awesomeness +10");
             user.setVar("DragonQuest", "over");
             user.setVar("isKiller", true);
             break;
         case "dragonHugged":
             say("You were supposed to slay the dragon, not hug it. Have this piece of junk.");
             user.giveItem("Headband of the lame Hippie +5");
             user.setVar("DragonQuest", "over");
             user.setVar("isHippie", true);
             break;
         case "over":
             if (user.getVar("isKiller")) {
                 say("Because you like killing things, I have another thing for you to kill...");
                 /* ... */
             }
             if (user.getVar("isHippie")) {
                 say("Because you hate violence so much, I have another peaceful task for you...");
                 /* ... */
             }
             break;
     }
}

```

# Answer
> 4 votes
I want to say, one of the other answers at the time of writing are suggesting "hard-coding" these events in your language. An alternative approach that can be pretty powerful is using an external format like XML, or a DSL (this is somewhat similar to the script binding approach) to define these events. Then you can easily an editor that outputs it. An example (this example would probably have a matching XSD document, but for simplicity it's left out):

Define a quest in the editor, and it saves something like:

```
<quest name="FirstQuest">
    <unlocks condition="dragonSlayed">
        <newquest name="SecondQuest"/>
        <item name="Good Sword" quantity=1/>
    </unlocks>
    <unlocks condition="goodGuySlayed">
        <newquest name="OtherQuest"/>
        <item name="Evil Sword" quantity=1/>
    </unlocks>
</quest>

```

Define a dialogue sequence and it saves something like:

```
<dialogue name="Bystander Dialogue">
  <messagetree condition="dragonSlayed">
     <event type="Message">Thanks for the help!</message>
     <event type="Message">You have a good sword!</message>
     <event type="AddKarma">100</event>
  </messagetree>
  <messagetree condition="goodGuySlayed">
     <event type="Message">What have you done?</message>
     <event type="Message">You have a good evil!</message>
     <event type="AddKarma">-100</event>
  </messagetree>
</dialogue>

```

The benefits of something like this is that you can make changes outside of your programming language, but I'd still recommend a simple editor to validate something like this.

# Answer
> -1 votes
Actually I think your question is first too broad, so is hard to provide any valuable feedback, and second primarily opinion based. Still, I will pitch my ball.

Are you familiar with Formal Grammars in the context of computer science? If you organize terminal symbols as missions or objectives, non-terminal symbols as decisions and production rules as outcomes, I think you can create a system able to procedurally create quests in a minimal coherent sense.

Sorry for not being too specific, broad questions make for broad answers.

**EDIT**: A little background to elaborate.

Formal Grammars describe how to form words in a language based on rules. For instance you have a language formed by the letters 'a' and 'b', and a set of rules describe how to form valid words in that language. The key point is that at an abstract level this is a very powerful concept.

In you case your symbols are steps in a quest, and the 'words' are complete quests. For instance if symbol 'a' means 'kill monster x' and b means 'get item y', the word 'abb' would mean 'first kill monster x, then get items y and z'.

By using production rules you can generate meaningful quests comprised of individual steps. With rules you can control that the steps are performed in an order that makes sense, and by choosing what rules to apply randomly, you make sure that you always get different variations on the quest. Also by using some more advance concepts such as contextual grammars, you can make a quest system that actually accounts for the outcomes of the steps and diverges based on that, but maybe you won't need to go that far.

# Answer
> -1 votes
I'm not exactly sure if this would fit in with JavaScript, I'm always on C++ so there will be differences.

Since it's a quest system then I'll just assume it's a RPG and give an answer with that theme.

quest: "press A or B"

Rewards: A-100 gold; B- 200 gold

The scenario now has 2 outcomes, pressing A get's you into branch 1 while pressing B get's you into branch 2.

I'm not that familiar with javascript so I can't give you a sample code from that language.

I usually make a boolean, let's name is alpha and beta, and let's make another one namely, check.

Oh we also have an integer to act as the storage of gold.

I suppose you're already familiar as too how reading inputs would work.

```
if(input press for A from the keboard && !checked)
{
alpha = true;
checked = true;
gold += 100;
}

else if(input press for B && !checked)
{
beta = true;
checked = true;
gold += 100;
}

```

Let's start discussion with alpha, to get alpha to become "true", there are 2 pre-requisites. One is to press "A" on the keyboard while the other is to have checked = false.

```
checked = false;

```

is the most important part, if you don't have that then the program won't understant if the player has already the other button, thus, making a glitch and allowing the player to press the button again and again while reaping the rewards.

Now, you have the basics. You can further branch this off by using booleans or by nesting the branches inside the original branch, though I would recommend using some sort of boolean, int, etc. to make the script more organized.

```
if(input press for A from the keboard && !checked)
{
alpha = true;
checked = true;
gold += 100;
second = true;
}

```

As you can see, there is another bool there named "second".

```
if(second) //will only start if second == true
//you can now fill in the events here

```

---
Tags: java, quests
---


title: Effect culling on uneven terrain

text:
# Question
Title: Effect culling on uneven terrain
I'm trying to integrate a "ground particle" effect (like a fire-circle or similar) in Unity3d, however since i'm using uneven terrain as my terrain mesh, the effect gets culled behind terrain parts that above it.

To better ilustrate it I created an image as attachment : I want for the effect to always be displayed regardless of it's "depth". How can this undesired effect be avoided/resolved properly ?

# Answer
I would recommend an animated Projector.

You'd simply configure the IgnoreLayers property to ignore your player. And you could animate the effect with a simple script to modify the UV offsets of the material you use.

One thing to remember is for every object a projector is projected onto an extra draw call is issued (just like a light), so use them sparingly.
> 1 votes

# Answer
If the effect is simply a quad being created at the player's feet, then you will have to change the way your effect is implemented. Projecting the effect onto the surface like a decal is one way to get things looking a bit better. Of course, it won't help with extra particles, or other more complex effects. Here is a link describing this idea.

http://blog.wolfire.com/2009/06/how-to-project-decals/
> 0 votes

---
Tags: unity, particles, graphic-effects
---


# Question
Title: How to make progress bar adapt to various aspect ratios in Unity3d
Can anyone help me with this problem: I want to make a time progress bar in my game. I have two textures: `progressBarFrame` and `progressBar`. Currently I'm doing the following:

```
void OnGui() {
    GUI.DrawTexture ( Rect(x,y,width,height), progressBar );
}

```

It works, but it doesn't adapt to different screen sizes.

I also tried this: Create `GUITexture` in the hierarchy and add a texture to it, after adjusting its size and location as I need, progress bar stretches/squishes with different aspect ratios and keeps its position relative to other GameObjects (that's what I want). But I don't know how to animate it properly because the figure of the textures is not a simple line.

# Answer
If you don't want your progress bar to be distorted when scaling, you'd need something like a 9-slice sprite (also sometimes referred to as 9-patch). Here's an article that explains the technique (the examples in the article are for Cocos2D, but it should be clear how it works).

When you create a GUITexture in Unity, you have 4 properties in the inspector called `Left Border`, `Right Border`, `Top Border` and `Bottom Border`. This is effectively a 9-slice implementation.. so if your progress-bar image has a border of 3 pixels that should remain intact, set all 4 border-properties to `3`.

Then you can just scale the GUITexture to your desired size and the progress-bar should adapt nicely.

Unity 4.6 will also provide this in their new GUI system, so do some of the popular GUI Frameworks/Toolkits (2dToolkit, NGUI, etc.).
> 2 votes

# Answer
You don't need a 9-slice unless you're doing some much more extreme scaling than what's implied here (it's used when you need the borders to stay a constant size while the interior changes \[ie. a window\]).

The simplest solution here is to modify the dimensions based on the screen resolution:

```
void OnGui() {
    var aspectRatio = Screen.width/Screen.height //This can be gotten from the camera too
    var scaledWidth = height * aspectRatio;
    GUI.DrawTexture ( Rect(x,y,scaledWidth ,height), progressBar );
}

```
> 0 votes

---
Tags: unity
---