title: Game AI. Behavior Trees struggles

text:
# Question
Title: Game AI. Behavior Trees struggles
I'm writing a bot for a MOBA game as final project. Game status is read directly from the screen (that's the requirement).

Now I have come to the AI part. On the first steps it started as some basic IFs, then I tried using a state machine, but there were too many jumps between states. Google lead me into Behavior Trees.

My current tree looks like this

It looks like it would work... And it does mostly... Except for the fleeing part. The fleeing part consists of setting a "safe point" as the current target for the navigator... But because of it being SUCCESSFUL (it has to flee), the selector does not traverse to the Navigation Behavior.

Solutions i'm thinking of

1. I could make it return FALSE when it's not successful, but then it would check the combat behavior even though it's already fleeing.
2. I could make a fleeing behavior. Really, that seems like the most logical thing, but it would be *some* redundant navigation code. I could extract the a branch from the Nav Behavior into a separate object. I'm not sure that's the right way though.

P.S. I'm using apocdev's Tree Sharp as the base for the tree. I don't think it really matters(it acts as it should), but just in case.

# Answer
In my experience, navigation should not be handled explicitly in the behavior tree. BTs are great at stateless reactive behavior, while navigation is inherently stateful: you find your path, than you follow it, check whether you should replan... If you need to handle jumps, elevators etc. thnigs get crazy and are difficult to handle in a BT. In all games I worked on, navigation was written in native code.

I see two ways you may implement navigation outside your BTs:

1) Current navigation target and navigation state may be part of the character's "body". The BT has action node to set current navigation target (succeeds immediately) and possibly also senses to query the navigation state (DestinationReached, PathFindingFailed,...). After every update to the BT, the navigation is updated, possibly replanning path, if the target has changed.

Solution 1 allows you to react quickly to any change in the world state - your BT is constantly reevaluated and if you realize you want to advance instead of fleeing, the change happens immediately. This however leads to higher risk of oscillations and things like random navigation target selection need special care to not reset the navigation on every update.

2) You may have a navigate node that handles the navigation for you and contains all navigation-related state. In this case, the target location is a parameter of the node or is prepared by another node. To implement this, your BT needs to support nodes that not only "Fail" and "Succeed" but may also be "Running" and maintain a little state for you. Tree Sharp is unknown to me, so I do not know what is the BT variant you are dealing with and whether this is an option. The idea is that both composite nodes (Selectors and Sequences) return "Running" when any of the children return "Running". Decorators also remember which node was "Running" in the last update. Sequences resume their update with the running node on the next tick. Selectors on the other hand reevaluate their children from the left, but if different branch than what ran the last time should be updated, the branch running previously is notified with a "End" signal which lets them cleanup whatever is necessary -e.g. stop movement.

The latter solution is IMHO more versatile but more difficult to implement and with higher requirements on your BT implementation. However, keep in mind, that you might need longer running nodes anyway if you plan to do anything more complex in your BTs. If you do so, remember that your BT engine should enforce a Init - Work - End lifecycle on all your nodes or you will just go crazy debugging the mess.

If you have not yet seen AIGameDev.com coverage of BTs (this one has free access, and hopefully covers the topics I discussed here: http://aigamedev.com/insider/presentation/behavior-trees/) you should check it out.

Some ideas are also nicely put in answer by Byte56: Behavior Trees :: Actions That Take Longer Than One Tick
> 3 votes

# Answer
A solution could be dealing differently with the Navigator Behavior; if its only purpose is telling your bot where to go if its current status is "flee", then you could incorporate it in the Flee Behavior and remove the Navigator Sequence. Otherwise, if Navigator Behavior is used to achieve different results, you could incorporate its functions in the same Selector as Flee and Fight Behaviors.

In "Handling Complexity in the Halo 2 AI, GDC 2005" (link), Bungie shows how they dealt with multiple gameplay behaviors in the same sub-tree of Root. I am suggesting a similar solution, incorporating Navigation within the "what shall I do now?" part of behavior tree.
> 0 votes

---
Tags: c#, ai, behavior, tree, bot
---


# Question
Title: Dynamic body in Box2D with fixed position
I need to fix the dynamic body position so that it would not rotate and would not move even if there are other forces, collisions and so on. Let me first explain why I need this.

I have a dynamic body which is the game character. There are non-moving objects that the game character should land on and get some energy as long the character is in contact with those bodies. As these bodies are non-moving it would be natural to make them `Static` or `Kinematic`. But in my case I cannot do that, as far as there is another Kinematic body with which all the game items should be collided and on `EndCollision` event those items should be removed. But in Box2D static and kinematic bodies don't collided with each other. So I have to make my game item on which the character should land `Dynamic` but still should be sure that it will not move. How should I do this?

# Answer
> 1 votes
One way to do this is create a kinematic body for each dynamic body as a 'shadow' body, with exactly the same fixtures. After very time step, set the position, angle, linear velocity and angular velocity of the kinematic body to match that of the dynamic body it is shadowing.

The original dynamic fixture should be set to not collide with its own shadow fixture, and not to collide with the original fixtures for bodies that have a shadow body.

When two sets of bodies like this collide, their shadow bodies will prevent the opposing dynamic body from pushing them, but they can still collide normally with other fixtures in the world.

Keep in mind that Box2D tries really hard to replicate the physics we see in the real world, and what you are asking for here is not realistic at all. You will probably see some VERY weird behavior, especially if you try to pile these bodies up together, even though they follow your rules. However, for a top-down scenario where piling of bodies is not needed, it might be ok.

---
Tags: box2d, physics
---


title: Unity: Smooth collision

text:
# Question
Title: Unity: Smooth collision
I'm making a topdown 2D RPG in Unity. All moveable objects have Rigidbody2D-components with gravity set to 0, linear drag set to 5 and different masses. Walls are stationary boxes with BoxCollider2Ds.

Here's my problem: http://a.pomf.se/nifmcn.webm The rock is not particularly easy to see, but if you watch when I'm trying to walk into a wall, the player kind of jags in and out of the wall.

Of course, this is because I'm moving the player by moving it's Rigidbody2D, for example:

```
rigidbody2D.transform.position += Vector3.up*Time.deltaTime*speed;

```

The box then throws the player in the opposite direction of what he was going.

---

What's a good way of stopping a player from moving in the direction he's trying to go? More specifically, how do you detect which way he's going? Do you find the angle between the player and the object/wall?

This is kind of an open question, but I think it's extremely important.

# Answer
> 4 votes
Don't set the position explicitly.

When you set properties like `position` and even `velocity`, you do so outside the physics loop, so it has no chance to correct itself within the current frame, so you see jittering behaviour. In other words, in the current frame you'll reposition the body, possibly colliding into another body, and the physics system must correct this in the next frame. Consider this passage from the Rigidbody.velocity manual page:

> In most cases you should not modify the velocity directly, as this can result in unrealistic behaviour. Don't set the velocity of an object every physics step, this will lead to unrealistic physics simulation.

If possible, always try to do it the recommended way - by adding forces by using functions like `AddForce`. This lets the physics system apply the right transformations, without temporary collisions.

This answer also contains similar advice.

---
Tags: unity, collision-detection, collision-resolution
---


# Question
Title: Adding materials to a Line Renderer through code?
I have a material that I am using to add a glowing effect to my line renderer. I can add this as a 2nd material to the line to give it a glowing effect.

I want to be able to add/remove this material through code, so I can essentially enable/disable the effect. I have no clue how to access the current materials of the line renderer in a way that allows me to add/remove elements from the materials array. How can I do that?

Pseudocode:

```
private void SetGlow()
{
    line.materials.Length = 2;
    line.materials[1] = "/new/material/directory/material.mat";
}

```

# Answer
You can have 2 public materials, assign the materials to them from the inspector and alternate between them.

```
LineRenderer line;
public Material mat1, mat2;

// Use this for initialization
void Start()
{
    line = GetComponent<LineRenderer>();
}

private void ToggleGlow()
{
    if (line.material == mat1)
        line.material = mat2;
    else
        line.material = mat1;
}

```

Refer to Line Renderer for more info.
> 1 votes

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


title: Basic Monster Movement

text:
# Question
Title: Basic Monster Movement
I'm new to game development. Specifically server side. Currently I am trying to implement movement of monsters. From point A to point B.

I have used an a\* pathfinding library to calculate the path to be taken but I do not know the logic on how to update the movement where the monster moves in 30 frames.

I am using javascript/node.js and currently I am doing something like:

```
// in game.update()
if (!monster.isMoving) {
  var steps = char.getPathTo(83, 213);
  steps.forEach(function (cell) {
    char.move(cell[0], cell[1]);
  });
}

```

Which of course is very wrong because it will evaluate all the movements first. So what are the possible approaches for this?

I followed this game loop:

```
var gameLoop = function () {
  var now = Date.now()

  actualTicks++
  if (previousTick + tickLengthMs <= now) {
    var delta = (now - previousTick) / 1000
    previousTick = now

    game.update(delta)

    actualTicks = 0
  }

  if (Date.now() - previousTick < tickLengthMs - 16) {
    setTimeout(gameLoop)
  } else {
    setImmediate(gameLoop)
  }

```

# Answer
> 1 votes
Simple, give the monster a hspeed, vspeed speed components, after that find the direction to the next point in the path with the tangent, which if I recall correctly would be y2-y1/x2-x1, being x2 and y2 the point of the next position and x1 and y1 the monster one. After that use the cosine*speed to find the x component or hspeed and -sine*speed for the y component or vspeed (negative because mathematical cartesian graphs and functions have the y oppositive to the computer's).

In a summary, you create a "follow point", get the direction of it, get the components for each by finding first the direction, then multiply each component by your desired speed. After reaching the current point increment it so it starts following the next one.

And one trick more. For checking wether it has reached or not do this: if distance\_to\_next\_point \< speed { x = follow\_point.x y = follow\_point.y follow\_point++ } Basically if the speed is bigger than the distance let's jump directly onto it, that way you avoid overlapping it and making your monster return back to it.

Hope this helps or gives you ideas :)

---
Tags: movement, path-finding, game-loop
---


# Question
Title: Rendering lighting only on specific objects
I have done something similar to this in monogame:

My question is, what would I have to do to draw that lighting effect **only on the pillar** and not the background ? Is there something like ignoring certain sprites when using BlendState.Additive ? How would that work ? Here is how i'm drawing it now.

```
//draw background
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Opaque);
spriteBatch.Draw(Background, Vector2.Zero, Color.White);
spriteBatch.End();

//draw pillar
spriteBatch.Begin(SpriteSortMode.Deferred);
spriteBatch.Draw(Texture, new Rectangle(PillarX, PillarY, Width, Height), Color.White);
spriteBatch.End();

//draw lighting sprite in additive mode
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive);
spriteBatch.Draw(LightTexture, pos, null, Color.OrangeRed, 0f, Vector2.Zero,
    scale, SpriteEffects.None, 0f);
spriteBatch.End();

```

Edit: Also, apart from the pillar I have as an example, I need to do that for 3D models as well, so would the Stencil Buffer work here ?

# Answer
Re-psuedo-coded:

```
//draw pillar
LightMapTexture.Clear(0,0,0,0); //Transparent everywhere
spriteBatch.Begin(Immediate, Alpha);
spriteBatch.Draw(Texture, new Rectangle(PillarX, PillarY, Width, Height), Color.White);
//Still transparent everywhere except texture; texture may be partially transparent also

customBlendState = new BlendState();
customBlendState.ColorSourceBlend = Blend.DestinationAlpha; //0 everywhere but Texture
customBlendState.AlphaSourceBlend = Blend.DestinationAlpha; //0 everywhere but Texture
customBlendState.ColorDestinationBlend = Blend.One; //Plus what's already there
customBlendState.AlphaDestinationBlend = Blend.One; //Plus what's already there
spriteBatch.Begin(Immediate, customBlendState);
spriteBatch.Draw(LightTexture, pos, null, Color.OrangeRed, 0f, Vector2.Zero, scale, SpriteEffects.None, 0f);
//Still transparent everywhere except texture
spriteBatch.End();

//draw background
spriteBatch.Begin(Immediate, Opaque);
spriteBatch.Draw(Background, Vector2.Zero, Color.White,,,,,,,,1); //Draw at Z=1
spriteBatch.End();

```

The preceeding may not be 100%, but should get you well on your way.
The purpose is to only use LightTexture where DestinationAlpha \> 0 (Texture has colored the pixel already).
Be back soon.

Edit: Just for learning, please look at the members of BlendState. Use each of them and explain the result of each to yourself. i.e. why you are having the problem you have
> 1 votes

---
Tags: xna, c#, shaders, lighting, monogame
---


# Question
Title: Unity provides wrong Input value if game is started with bumpers pressed down
As the title states I am having an issue with the following. It is a pretty specific edge case but it is something I can't work around.

In Unity I have created two Axes to allow me to check the value of the of the left and right bumpers on an Xbox controller. The problem I am having is the controller I am using is a special product where by default the left and right bumper are always on. This is intended on the controller and is definitely not changeable. The issue here is that because the controller has the bumpers pressed in by default when Unity is launched it reads the input of those buttons with a value of 0 instead of 1 (as I have the controllers set to provide a positive input).

I've tested this with a normal Xbox controller by manually pressing the trigger in before I launch the game and I get the same results so I can confirm that it is a Unity thing and not a controller issue. The only way to fix the controller's input is to manually refresh the bumpers (which are attached to sensors in this case).

This is currently not an acceptable way for me to refresh the device I just need to get the devices correct input immediately. Is there a way I can, in code, not have the game recognize the controller until I specify? The reason for this is if I plug my device in AFTER the game starts I get the correct values.

This game will only ever be run on Windows so I would be open to coding up an OS level script that utilizes some of the Windows functions.

EDIT: I thought I should add I have tried sending visualized input to the device via code and this has not fixed the issue.

# Answer
> 2 votes
I've found that using XInput.Net fixed the immediate problem for me. As what I need to do is fairly simple I think this is going to be a good solution.

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


title: Non deterministic dice rolls

text:
# Question
Title: Non deterministic dice rolls
Are there any algorithms out there for non deterministic dice rolls?

For example, I'd like to make a small mini-game: Liars dice. But the biggest issue here is dice rolling. When the cups are turned the result of the dice should be determined by the game rather than physics (if I were using unity for example). How can I ensure that the model behind it provides random results acute to an actual dice role?

# Answer
> 5 votes
A computer is a deterministic machine, there is no way to get non-deterministic random numbers from a computer barring some extra source of non-deterministic random numbers (which no PC has).

Just use a bog-standard pseudo random number generator. It's more than close enough.

# Answer
> 1 votes
Use random and seed with the time. Here is some C# code just as an example. Not tested so there might be missing some ";" or similar :).

```
using System;

Random randomizer = new Random(); //Uses system clock as seed value so every run will give different number each run.
int diceResult = randomizer.Next(1,6);

```

Then you just use the diceResult to decide which side is up on the dice. In other words just simulate the dice role by random and then adjust the physical representation to match. The player cant see the physical dice any way during the "roll".

---
Tags: random
---


# Question
Title: 2D game with angled top-down camera perspective
I want to create a game similar to binding of isaac, a slightly angled top-down 2D game. In binding of isaac, the character moves and shoots along a 4-way path, so when he is shooting towards East, the character is facing East, same for North, West and South. In my game I need to shoot at any given angle, so it will look pretty bad if the character is facing East but the bullet is going North-East, I considered creating 8 or even 16 sprites with the character facing at different at different angles. But I don't know if it will look good either.

I would like to know if anyone encountered this problem and if there is any solution beside switching to 3D, because is not a solution at this moment.

In this image(Binding of Isaac) it may look like the player shoots at any given angle but it's not, he moved to the left immediately ofter shooting.

# Answer
Simply choose the facing for the character that is closest to the angle of the shot. 8 sets of sprites would be nice for that, but I imagine just the 4 cardinal directions would look fine too. Character faces North for any shots between NW to NE, character faces East for any shots between NE to SE, etc.
> 1 votes

---
Tags: 2d, camera, perspective, third-person-view
---


title: Box 2d Level Editor for AndEngine

text:
# Question
Title: Box 2d Level Editor for AndEngine
I am getting started with Box2d in AndEngine. I need to know if there is any level editor to be used with box2d and gives output capatable with AndEngine.

Is there any tool which can help me building complex body with joints like a bike or car?

What do you suggest which is the best way to do this kind of stuff.

# Answer
I think the RUBE editor might be what you're looking for. It does however export the box2d bodies in a JSON format, so you'll probably need to figure out yourself how to load these. It is very well documented tough.
> 6 votes

# Answer
Here I provide a link for physics editor that I use regularly and very much easy for use. This editor creates xml file that you can use directly with andengine level parsing easily.

http://www.codeandweb.com/physicseditor

Also for level creating purpose you can use Macromedia Flash, that editor directly return x and y position using scripting. So user have to directly parse that information.
> 2 votes

# Answer
I've been using Level Director which was designed for the Corona SDK (which uses Box2d) but it now allows you to export the data using a template. The possibilities are now endless and I love it.
> 0 votes

# Answer
I am working on my own level editor Fire Ant Box2d Level editor, is free, please feel free to try it out, it exports your work to ios code as well as xml so you only write a small xml processing routine and you should be able to use it in andengine. It also generates optimized texture tiles out of the box.

http://www.freefable.com

http://www.estebon.mx/fable

Any comment and feedback will be very apreciate.
> 0 votes

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


# Question
Title: What is the performance impact of rendering a larger quad?
Lets say I have two planes and I textured them in blender with a `512*512` tiled texture. One plane is bigger than the other (for example, one plane tiles the texture 60 times but another only six times). I've import the planes in to Unity and assign that same `512*512` texture to them.

What is the difference in performance in-game? Because both of those objects use one draw call and same `512*512` texture, therefore same texture space, so what is the difference in performance?

# Answer
> 3 votes
If the only difference between the quads is their physical size in window coordinates ("one is bigger than the other on-screen"), and all other things (shader, textures, et cetera) are equal, then the only significant difference in the pipeline will be that the rasterizer must fill more fragments for the quad that is larger on-screen.

This means that if the fragment shader being used is expensive, the larger quad may be more expensive in terms of fillrate.

It is, however, unlikely that this is going to create a noticeable performance differential, especially in the shaders you are *likely* to be using to simply paint a quad with a texture.

While there are a few other potential avenues for performance issues, they depend on factors that you having elaborated on. With only the information you've provided, fillrate is going to be the only technical difference, and even that won't likely be measurable.

---
Tags: unity, textures, performance, blender, uv-mapping
---


title: Path finding for Vector Based System

text:
# Question
Title: Path finding for Vector Based System
I understand that typical path algorithms are based on nodes in a graph (not tiled nodes or whatever), but i can't get my head around to find an idea how to implement a path finding algorithm for a grid with endless possibilities (my mapdata is based on vectors so for example an rectangle could be the 1000th of one unit wide but still an obstacle). I basically have a map with 1 or more fixed sized units and need them to travel the shortest path through a field of rectangles and circles which are not passable. The question is is there a way to use normal pathfinding algorithms with that mapsceme (how do i calculate the nodes then?) or do i have to use a special one?

# Answer
> 9 votes
Welcome to the wonderful world of continuous state motion planning. A few years ago I wrote a Gamasutra article on this topic.

Here are some solutions to your problem:

**Navigation Meshes**

This works by constructing a graph of nodes and edges of your scene based on some simple rules. For instance, you can construct a Visibility Graph of the scene, which is just the graph of all rays that pass through free space from each vertex of each obstacle to each other vertex. By running A\* on the Visibility Graph, you get optimal path length solutions in polygonal environments. If you're concerned about things other than length, such as "naturalness", you might want to try another navigation mesh algorithm such as a Voronoi Graph, which puts nodes such that they are equidistant from obstacles, and then adds edges between the nodes. Even simpler than all of these is the Probabalistic Road Map, which just places the nodes randomly and connects them to their nearest neighbors. In all of these cases, A\* is usually used to plan a path through the nodes on the grid.

**Lattice Grids**

Another option is to simply *discretize* your space into a simple grid. Put a node at the center of each grid cell, and connect nodes to each other if the ray between the nodes doesn't intersect an obstacle. Then, use A\* as usual to plan through the grid. This has some advantages over navigation meshes in that it is easy to implement and modify, but it is much more memory intensive, and produces lower quality paths.

One more way of using a lattice grid is to discretize the *actions* the agent can take (the edges in the graph) rather than the obstacles (the nodes in the graph). This suffers from many of the same problems as discretizing the obstacles, but allows the agent to, for instance, move a half square instead of a whole square as part of its path.

**Sampling-Based One-Shot Planning**

An interesting motion planning algorithm called the Rapidly Exploring Random Tree (RRT) randomly grows a tree graph structure from the start to the goal using a set of simple heuristics. The paths it produces are often quite terrible, but it has the advantage of working with very high-dimensional planning problems, such as those involving a *rotating* character (like a car or boat), and with joints. It can also be faster than the other algorithms when you expect the environment to change very often (such as with the case of moving obstacles).

**Flow Fields**

Another option is to create what's called a **policy** instead of a **plan**. Just create a virtual force toward the target, and forces away from all of your obstacles. Then, move the agent in response to the forces. Even though this sounds very simple, it works for *many* kinds of environments. If you add a little more cleverness to the simulation (such as a flood-fill like heuristic), you can get very natural motion -- but again you aren't guaranteed to find the solution. One advantage of flow fields is that they can be made extremely efficient, allowing for many thousands of agents to path plan simultaneously.

**Trajectory Optimization**

There is another branch of motion planning called Trajectory Optimization which tries to directly find the path through mathematical optimization. Basically, you start with a straight line path from the start to the goal, and then you keep modifying it until it is both short, and has the fewest number of collisions. If you can also compute the distance to obstacles, you can very quickly find a locally optimal path. One caveat is that trajectory optimizers are not guaranteed to find a feasible path (they do particularly badly in mazes) -- but the paths they do find are often beautiful, continuous, and very natural-looking.

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


title: XNA Distortion Shader problem

text:
# Question
Title: XNA Distortion Shader problem
So I came up with a distortion pixel shader in hlsl, but it has some issues. First of all, here is how it works:

The shader uses another texture generated by the program as a distortion "map" (if that's the correct term) I called this map a "mask".

The shader uses the red values in the mask for horizontal distortion and the blue values as vertical distortion. The green values are not used.

It subtracts 0.5 from the red and green values so that they have a range from -0.5 to 0.5 instead of 0 to 1. This lets the distortion go in any direction using only two color values.

I let the shader "push" pixels up to 128 pixels.

```
sampler s0;
texture textu;
sampler tex_sampler = sampler_state{Texture = textu;};
float2 screenSize;

float4 PixelShaderFunction(float2 coords: TEXCOORD0) : COLOR0
{
    float4 tex_color = tex2D(tex_sampler, coords);

    if (tex_color.a)
    {
        float distX = (tex_color.r - 0.5f) * (256.0f / screenSize.x) * tex_color.a;
        float distY = (tex_color.b - 0.5f) * (256.0f / screenSize.y) * tex_color.a;

        return tex2D(s0, float2(coords.x + distX, coords.y + distY));
    }
    return tex2D(s0, coords);
}

technique Technique1
{
    pass Pass1
    {
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

```

"textu" being the mask, "tex\_color" is the color value from the mask. It also multiplies the distortion by the alpha value in the mask.

This seemed to work perfectly at first, but I started noticing some issues. I was using a completely white texture (as the mask) that was blurred around the edges. I set the color of this texture based on its rotation. Here is the method I used for that:

```
private Color GetDirectionColor(float rad)
{
    Vector2 v = new Vector2(
        (float)Math.Cos(rad + Math.PI),
        (float)Math.Sin(rad + Math.PI)
        );

    float r = (v.X * 0.5f) + 0.5f;
    float b = (v.Y * 0.5f) + 0.5f;

    return new Color(new Vector3(r, 0, b));
}

```

This allows the texture to "push" pixels in whatever direction it is facing. This method seems to work fine.

The problem is, when the texture is rotated more than 135 degrees and less than 315 degrees (as in, the texture is pointing into the upper left half of a circle if you cut it in half at a 45 degree angle) it does something strange. Where the texture is blurred (the alpha values become less than 1) it starts to "push" the pixels in the opposite direction that it should be.

I suspect this has to do with my shader and not something else in the program. Possibly the -0.5f part???

I'm terribly sorry if this is confusing... I could not find a better way to word it.

Thanks a lot for your help!

# Answer
Ok I was able to fix the issue on my own!

I figured out that all color values become less as the mask blurs. So where the mask was fading out, not only were the A values fading, but the R G and B values were fading too! I'm not sure why that is, but here is the change that fixed it:

```
sampler s0;
texture textu;
sampler tex_sampler = sampler_state{Texture = textu;};
float2 screenSize;

float4 PixelShaderFunction(float2 coords: TEXCOORD0) : COLOR0
{
    float4 tex_color = tex2D(tex_sampler, coords);

    if (tex_color.a)
    {
        float resolver = (1.0f - tex_color.a) * 0.5f;

        float distX = ((tex_color.r + resolver) - 0.5f) * (256.0f / screenSize.x) * tex_color.a;
        float distY = ((tex_color.b + resolver) - 0.5f) * (256.0f / screenSize.y) * tex_color.a;

        return tex2D(s0, float2(coords.x + distX, coords.y + distY));
    }
    return tex2D(s0, coords);
}

technique Technique1
{
    pass Pass1
    {
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

```
> 1 votes

---
Tags: xna, c#, shaders, hlsl
---


# Question
Title: How do I calculate the path of something in orbit around one or more bodies?
I need to figure out how to calculate the orbit of an object around one or more bodies for a game that I am making (built on Cocos2D-Swift). The game is in two dimensions, so it's a two-dimensional orbit I am calculating. I currently have it set up so that, in the update loop, it calculates the force of each of the bodies on the object, the acceleration due to that force, and the change in velocity due to that acceleration. This would probably work fine if I were going through the update loop a thousand times per second, but on the iPhone 6+ simulator, I'm going through it approximately thirty times per second, which is a discretization so wide that it makes the orbit of the object very unstable.

As a result, I am looking for an equation that tells me the position of the orbiting object as a function of time; therefore, the force, acceleration, and velocity are not discretized, so the simulation is accurate. An example of what I am looking for is how Kerbal Space Program calculates the orbital paths ahead of time. Any thoughts? Thanks.

# Answer
> 1 votes
For one body, you can use Kepler's laws to create an elliptical equation paramaterized by time.

For two or more bodies, you're out of luck in terms of a nice closed-form solution. See the N-body problem. However, you can still solve this problem numerically. Instead of doing what you're doing now (which is called Euler Integration), you can instead use a more stable method like Runge-Kutte 4. Here is a tutorial on how to use the RK4 method to compute orbits.

---
Tags: cocos2d
---


# Question
Title: Responding to mouse input on game objects
I'm trying to make a simple button in unity using a cube. My plan is for when the cube is highlighted that it will move towards the camera and be highlighted in a specific color and then when it is clicked it will move back and change to a different color. I would also like to know how to make events happen when clicking an object.

# Answer
> 1 votes
Unity provides a number of features you can use here.

* `OnMouseOver()` would be used when you want that highlight effect. This method will be called every frame that the mouse is over your object. Inside this method you'd change the color of your cube and move it however you like (perhaps using some simple harmonic motion to have it bob closer/farther from the camera).
* `OnMouseExit()` is used to detect when the object no longer has the mouse over it. You'll need this to re-position an object that is no longer selected.
* `OnMouseDown()` is activated when an object is clicked. This would be used to trigger an event when your object is clicked by the user.

These methods require that the object have a `Collider` of some kind attached to it (the default Cube in Unity already has a Box Collider attached).

As an example, here is a simple script that moves an object towards the camera and slowly rotates it while the mouse is hovered over it. Then prints a debug message when the object is clicked.

```
public class NewBehaviourScript : MonoBehaviour {

    public Vector3 defaultPosition;
    public Quaternion defaultRotation;

    public float moveTowardsCameraDistance = 3;

    public void Start() {
        defaultPosition = this.transform.position;
        defaultRotation = this.transform.rotation;
    }

    public void OnMouseOver() {
        Vector3 headingToObject = this.transform.position - Camera.main.transform.position;
        this.transform.position = defaultPosition - (headingToObject.normalized * moveTowardsCameraDistance);
        this.transform.Rotate(Vector3.up, 45 * Time.deltaTime, Space.Self);
    }

    public void OnMouseExit() {
        this.transform.position = defaultPosition;
        this.transform.rotation = defaultRotation;
    }

    public void OnMouseDown() {
        Debug.Log(this.name + " was clicked!");
    }
}

```

* Most of this code was taken from my course on Unity 3D, you can have 10 days to check it out.

---
Tags: unity, events, mouse
---


# Question
Title: Exported FBX Blender Model not showing up in XNA
I really do apologise if this question has been asked before, but I recently created a model in Blender 2.63, exported it to an FBX file, and tried to display it in XNA (using 4.0 Refresh), but all that shows up is the standard XNA blank screen. My code for drawing the model is:

```
    void RenderModel(Model model, Matrix world, Matrix view, Matrix projection)
    {
        foreach (ModelMesh mesh in model.Meshes)
        {
            foreach (BasicEffect fx in mesh.Effects)
            {
                fx.World = world;
                fx.View = view;
                fx.Projection = projection;
                //fx.Texture = untagged;

                //fx.EnableDefaultLighting();
            }

            mesh.Draw();
        }
    }

```

where

```
    world = Matrix.CreateTranslation(Vector3.Zero);
    view = Matrix.CreateLookAt(new Vector3(0, 0, 10), Vector3.Zero, Vector3.UnitY);
    projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45), 800f / 600f, 0.1f, 100);

```

The above code worked for some other models I tried, so I'm pretty sure it's something wrong with the exported model. I exported the model from Blender using the XNA strict settings, and there are no animations, just a texture, which seems to be connected properly to the FBX from the text in the FBX file.

If anyone can tell me how I can create a simple model in Blender and make it usable for XNA, that would be great. Thanks a lot!

EDIT: Added program versions for Blender and XNA

# Answer
Assuming that the sample tutorial from MSDN here http://msdn.microsoft.com/en-us/library/bb203933.aspx works, you might want to look at this from Blender http://wiki.blender.org/index.php/Extensions:2.6/Py/Scripts/Import-Export/Blender-toXNA on exporting to XNA
> 1 votes

# Answer
The article linked by Jason Coombes says this:

> -All the model objects (meshes) and the armature must be centred at the same location, ideally zero (X = 0.0, Y = 0.0, Z = 0.0 in the Object properties.) Set the locations to zero in Object mode and make all changes in EDIT mode.
> -All the model objects must have a scale of 1.0 (one.) Set all the scales to 1.0 in Object mode then do all changes in EDIT mode.
> -The model objects must not use rotation. Set all the rotations to 0.0 in Object mode then do all changes in EDIT mode.

A round-about way of saying:
Create it however you want, but be sure to bake rotation, translation and scale into the final geometry before you export it.
> 0 votes

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


title: How to move a car model on a plane?

text:
# Question
Title: How to move a car model on a plane?
I want to create a 3 dimensional car game. But i have a problem in moving a car in other directions and accelerating.

I have a car model and a road model placed appropriately. To move car forward, I translate the road model to negative X-axis so my car looks like it moving forward in my case as my car and road track is along the positive X-axis. Now, in the middle I want to turn left or right and for that I rotate the road model, (let's 90 degree). When I do that the car should move away from the road in sideways direction (or, we can say road to be moved), but it does not. As road was being translated to negative x-axis, after rotating the road I thought to be translated along negative x-axis relative the camera but I think the X-axis of the road object is fixed. So what should I do to solve it?

I just want to move a car which can go forward and when it turns left or right it should move forward accordingly.

P.S. I know, my question may not be clear but that's all I could elaborate it. Anyone can notify me if it's not clear and I will try again to clarify my question again.

# Answer
You should be moving the car positive X axis instead of the environment around the car negative X axis. Then move the camera with the car.
> 1 votes

---
Tags: mathematics, physics, car
---


# Question
Title: What is the purpose of integration in physics engines?
All online resources seem to assume that you know what this means and/or state that this is related to object movement in some way.

How does this differ than just `position.x++` and `position.y++` and how does integration allow us to simulate movement? (calculus integration?)

I understand there are a few different methods, namely Euler explicit, RK4, and Verlet. These methods I read are meant to solve ODE's, what are we solving for when we solve these equations?

# Answer
The Euler method as applied to games is pretty much just the naive `Position + (Velocity * TimeSinceLastUpdate)` formula I think you were getting at. The other methods (without getting into the calc too much) are just more accurate ways of estimating velocity and position based on multiple simultaneous forces, like friction, gravity, air density, etc. It's probably most noticeable in accurate flight simulators, where the aircraft actually needs to behave according to different forces across the wings' control surfaces.

So, referring back to the Euler method, an integral is essentially a repeated sum.

`Position += Velocity * TimeSinceLastUpdate; // for every frame!`

Which in graph form might look like

where the width of each rectangle is the time, and the height is the velocity. Obviously we can get better estimations the more rectangles we use, but that means doing more processing each frame. If we can do the job of several integrations in one step by, say, using sloped rectangles, then our physics will be just that much more accurate.

Of course, this isn't always necessary - accurate isn't always interesting.
> 3 votes

---
Tags: mathematics, physics, integration
---


title: Multiple Vertex Layouts

text:
# Question
Title: Multiple Vertex Layouts
I have different vertex layouts I'm using to render things in DirectX and as of now I've just used the same vertex layout for every mesh I load in. But now I want to have the vertex layout change according to the mesh loaded in. If the mesh has a normal map I would like to have an vertex layout with tangents so I can render with the normal map. If I don't I would like to have an vertex layout without tangents to save me some time on my rendering. Right now in my mesh class I have...

```
std::vector<Vertex::PosNormalTexTan> vertices;

```

where PosNormalTexTan is the vertex layout. Then I have...

```
void Construct(ID3D11Device* device, UINT vCount, std::vector<Vertex::PosNormalTexTan> vertices, std::vector<UINT> indices);

```

Called when constructing the mesh. I would like the possibility of using

```
std::vector<Vertex::Basic32> vertices;

```

How could I do this without creating an overload for every vertex layout?

# Answer
Edit:
This compiles (C#):

```
void createVertexBuffer<T>() where T : struct, IVertexType
{
  List<T> vertexList = new List<T>();
  VertexBuffer vb = new VertexBuffer(OpenCityComponent.GraphicsDevice, typeof(T), 10, BufferUsage.None);
  vb.SetData(vertexList.ToArray());
}

```

To move `List<T>` into the class, I'd have to move `<T>` to the class and enumerate them all, which is what you are wanting to avoid. Using an untyped list, I would have to know `T` ahead of time to be able to re-cast correctly....

I am "discouraged" from using pointers in C#, so there may just not be a C# analogue I can answer with. I will continue thinking on this while I read the DirectXMesh link.
> 0 votes

---
Tags: c++, 3d, directx
---


# Question
Title: Is there a way to start with OpenGL 3.0+ without need to write my own shaders?
I'm starting with OpenGL and found out that after OpenGL 3.x you must write your own shaders (think it's obligatory). Am I right here?

I have made some research but I can't seem to find the answer. If it's necessary to write the shaders for OpenGL 3 the I still can use 2.x right? Just because I'm just starting and OpenGL seems a little bit more level than I'm accustomed to. So I think I'll have a really hard time writing a shader myself.

P.S. My GPU only supports up to OpenGL 3.0. I think it's because of the drivers, I'm running a Linux distro that only has FLOSS (no proprietary software).

# Answer
> 2 votes
In the OpenGL 3+ Core profile, the fixed function pipeline is deprecated or removed. However, all drivers by default give compatibility profiles which still have glVertex, glBegin and friends. You won't get as much performance out of these old functions (which is why they were removed), but they still work. You may use "OpenGL 3" with these old ways, but you'd be essentially writing an OpenGL 2 program. OpenGL only adds things in later revisions.

That being said, shaders are a core part of modern rendering, and learning how to use the old fixed function pipeline is mostly a matter of understanding how to setup the data the way OpenGL expected it back in the day. If you follow a tutorial like this one, you should be set up with a basic framework that replicates most of the old OpenGL fixed-function pipeline. What that pipeline did was:

1. Set up the appropriate matrices, using functions like `glRotate`, `glTranslate`, and `gluLookAt`. This part of the tutorial uses the `glm` library to make this just as simple as OpenGL 2.
2. Handle the transforms in the vertex shader. This is really rather simple. Using the common matrix setup, it is just `glVertex = projection * modelview * vertex`;
3. Apply texturing/lighting automatically, *assuming you set up everything correctly*. Getting this to work is probably equivalent in difficultly to writing your own shaders and getting the textures & light data set up. This part explains lighting and this part explains textures.

The only tough part about shaders is that there is a lot of magic commands to get them compiled and the data for them loaded, but once you are through that boilerplate it really isn't that complicated.

---
Tags: opengl, shaders, glut
---


# Question
Title: SNES Limitations: Number of stored Graphics?
There are plenty of resources that tell you how many sprites can appear on a screen for a SNES game and how many per scanline. There is even answers for the number of tilemaps.

But when I ask the question "How many texture pages could a SNES store on a cartridge? And what size approx.?", that is when there is silence. I appreciate there were no such thing as texture pages back then (it was just a way to explain the question) but surely someone must how many tiles and sprites a SNES cartridge could store on a game?

Any documents/articles that can help me is highly appreciated. Perhaps I missed something while looking on google.

# Answer
From wikipedia (http://en.wikipedia.org/wiki/Super\_Nintendo\_Entertainment\_System#Game\_cartridge)

> The largest games released (Tales of Phantasia and Star Ocean) contain 48 Mbit of ROM data

That's 6MBytes.

The smallest tile/sprite you could easily store is a 8x8 1bpp tile, giving you (6\*1024\*1024/8) 786,432 tiles without any space for code and other data. **196,608 tiles for 8x8 4bpp** and 262,144 tiles for 8x8 3bpp.

That is without using compression or custom ROM controller. Using a ROM banking controller there is no theoretical limit.
> 2 votes

---
Tags: sprites, storage
---


# Question
Title: How do you capture keyboard and mouse input for an HTML5 game?
Is there an accepted method for capturing player input in HTML5 games? I have seen several methods, and the browsers seem to be in varying states of implementation; On MDN they tell you not to use both the newer and older implementations. I'm open to methods utilizing various libraries, but I would also like to see a pure JavaScript and DOM version as well.

# Answer
What "several methods" have you seen? AFAIK, there's one method, which involves listening for the appropriate DOM Level 2/3 events like `keydown` via the `addEventListener` function. There might be some inconsistencies with the way you retrieve key codes, which you can deal with by using `var keyCode = event.keyCode || event.which`. There are also some inconsistencies with mouse button numbers, only the higher ones though. That's about it.

The only reason why, i see, you could be confused is if you were looking at old IE APIs. You want HTML5, so that's IE9+ and those browsers conform to the standards i described above.

For the keyboard events, you can probably just listen to the document object, though this depends on how you serve your game. For mouse events, you can listen to the canvas object directly.
> 2 votes

# Answer
As @dreta said there's only one way and it's by using a `keypress` event handler just like this:

```
var keyInput = document.getElementById("keyInput");

function inputFunc(e) {
    If (e.keyCode == 82) {// 82 = R
        //Do Something
    };
};
keyInput.addEventListener("keypress", inputFunc);

```

You can also visit this website where you can check the keyCode char keyCode char
> 2 votes

---
Tags: html5, input
---


title: Libgdx Hud with two stages

text:
# Question
Title: Libgdx Hud with two stages
I have an app that's currently working with a single stage but i need to add a side display/section as a HUD, with scores/lives etc on it, so that the HUD is on the left, and the main hand screen on the right. The main game screen will be fixed and will not move around.

From researching I've found a couple of solutions.

1 - two stages 2 - a group with two groups to it, possibly using a horizontalgroup 3 - two cameras one stage 4 - one stage, one camera, but changing the position of the camera for each set of actors.

I think, option 1 is my preference, but i have some questions.

Do stages always fill the whole screen, or can i start then where i want? This would make it easier for the right hand screen to calculate positions based on 0,0 of that screen rather than always having to add the width of the HUD on to any calculations. Do i need to work about viewports? Currently I'm not using one (which i think means my stage is set to scaling by default) but nothing looks stretched as a result of this. I don't know much about viewports, but there always seems to be a compromise to be made with them, i.e. black bars top or sides. If I have two stages, do they each have their own camera? Do I need to with about this? Can I possibly aim the right hand camera at an offset so i can still draw things from 0,0 with that being the bottom left corner of the right stage, not the whole screen? Finally, off topic, I am a little confused about spritebatch. I'm not currently using one, because I use a stage. Is that OK, or should i still be using one in conjunction with a stage somehow? And add all my actors to that?

# Answer
> 1 votes
* LibGDX has `Viewport`, which helps you do exactly what you are trying to achieve. You use the `Viewport` to specify where the `Stage` should be drawn and how big it is.
* The `Viewport` does not change the local coordinate system of the `Stage` itself, so you don't have to add an x offset to everything you want to include in the right hand stage (everything starts at `(0, 0)`).
* And yes, each `Stage` has its own `Camera` and its own `SpriteBatch`.

---
Tags: android, libgdx, hud
---


# Question
Title: How can I run a Unity game in a window larger than the desktop resolution?
I am exploring a research problem using Unity. I require a game resolution of at least 4096 x 786. There seems to be no option under build settings for setting a fixed screen size window. (The default screen width and height options are unhelpful here.)

How can I make a window even larger than the desktop?

# Answer
As we can see in the documentation here on `Screen.SetResolution`:

> A width by height resolution will be used. If no matching resolution is supported, the closest one will be used.

So what it will do is downgrade that to a supported width/height. This applies even if it's in windowed mode as opposed to full screen (at least in the version I'm using: 4.5.2). It should, however, work just fine as long as the monitor you're using supports that resolution.

The code used to programmatically change resolution is:

```
Screen.SetResolution(4096, 786, false);

```

Note also that on the build settings you can disable the resolution dialog that pops up before your game runs and you can define the aspect ratios and such that your game supports AND that resolution functions like this will usually have limited/no effect if running within the editor.
> 2 votes

# Answer
You can't make one bigger than your monitor.
> -3 votes

---
Tags: unity, resolution, screen, viewport
---


# Question
Title: Storing Type/Game Data Within A Unity 3D Game Using An Offline Flatfile Database
I've read several documents on how to manage game type data:

Would it be better to use XML/JSON/Text or a database to store game content?

How to choose how to store data?

Im developing an offline RPG game in Unity3D. I've made online games before, but with online we had an edge for the database. For the online game we used a MySQL database each time the player loaded the game, they would download the database (JSON setup) and we would parse it on the client side and it would be good to go.

However for an offline RPG I don't have the luxury of storing my game type data online. To be clear when I say type data I mean things like: -Monster tables -Item tables -Ability tables etc

What I liked about the MySQL database was that it was tabluar and I could edit rows and columns easily and not need to create hundreds of classes/subclasses to manage the type data.

My question is how can I mimic the MySQL database in Unity3D?

I considered using an excel file but I feel that would be so easy for the user to hack. Just change the excel data and boom, you've hacked the game.

Is there a way I can create an offline (secure-ish) flatfile database that will let me avoid having to create tons of type data class files to manage all my game data?

# Answer
Depending on your needs, you could just serialize a Dictionary to a binary file. I can post some code after I get home, but this link explains the serialization features of C#.

This is only secure-ish (a binary file is harder to hack than an excel spreadsheet) but that's all you requested. I can't tell from your question if this is data generated during the game or data you created ahead of time, but if the latter then you could just write an editor within Unity itself.

Alternatively, you could simply not care if the user hacks this data. If this is a single-player game, then let the player do what they want. If this is a multiplayer game, then you need more security anyway.

EDIT: Here's a Unity specific resource about saving a serialized object: http://gamedevelopment.tutsplus.com/tutorials/how-to-save-and-load-your-players-progress-in-unity--cms-20934

This most important Unity-specific thing mentioned there is Application.persistentDataPath
> 3 votes

# Answer
There's a few variables that aren't mentioned like how big you expect it to be, what platform the games are going to go on, etc so as usual there's a lot of "it depends" on any answer.

One option is to serialize the data out to JSON. If you store some sort of checksum against the data you'll immediately know if the data has been changed. You can also encrypt the data. The JSON can be serialized into classes and collections and you can use LINQ to query them.

This does add overhead of deserializing the data (and decrypting if you go that route) upon startup and making sure both the data and any checksum is versioned. The biggest thing is you'll probably be sucking in the entire dataset into RAM which is something you may not want to do.

Inventory can be serialized to PlayerPrefs.

**EDIT**: I stand corrected. It was pointed out to me in comments that PlayerPrefs shouldn't be used for inventory and the following video provided. It provides plenty of info that pertains to this question (though it's pretty long and rambles on a bit): http://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/persistence-data-saving-loading
> 1 votes

---
Tags: unity, rpg, data-structure, databases, storage
---


# Question
Title: Am I allowed to name a game after some song?
Just to ask a quick question, which I don't know where to ask: If I were to make a game, would I be allowed to call it "Buffalo Soldier \[some more words\]"? Since it's a song by Bob Marley I am not sure if this would get me into all kinds of legal trouble because of copyrights, which I obviously want to avoid.

By the way, the game doesn't have anything to do with Bob Marley or the music industry. I just thought a game about a buffalo soldier would be nice!

# Answer
Short answer, yes.

Of course, only *your* lawyer can advise you of *your* legal risk in civil matters like this. However, a reasonable person should not be at risk of brand confusion - which is the question a court would have to answer in that case, as this more aptly falls under trademark which protects symbols identifying things with business value, as opposed copyright which protects the content.
> 10 votes

---
Tags: legal
---


# Question
Title: Drawing Projected Vertices/Faces In Order
I recently created a 3d engine, and have gotten to what is (as I've found) the hardest part so far. I need to sort the objects and then draw them. I've looked at sorting algorithms, but my case is rather specialized. I have an array of vertices stored inside the Face3D object which I've created, and need to draw faces correctly when overlapping, Firstly, am I thinking about this correctly? Draw the back vertices first? Secondly, How would I sort this? Here's my code for the Face3D file:

```
package me.dylan.ThirdDimension.src;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.Shape;
import java.awt.geom.Point2D;
import java.util.ArrayList;

public class Face3D {
    Polygon face=new Polygon();
    ArrayList Lines = new ArrayList();
    ArrayList Vertices = new ArrayList();
    Color color;
    public Face3D(int x,int y, int z, int width, int height, int depth,Main m,Color c) {
        color=c;
        Vertices.add(new Point3D(x, y, z, m));
        Vertices.add(new Point3D(x, y+height, z, m));
        Vertices.add(new Point3D(x+width, y+height, z+depth, m));
        Vertices.add(new Point3D(x+width, y, z+depth, m));
        for(int i=0;i
            Vertices.get(i).update();
            Point2D tmp = new Point2D.Double();
            tmp.setLocation((int)Vertices.get(i).x2d, (int)Vertices.get(i).y2d);
            face.addPoint((int)Math.round(tmp.getX()),(int)Math.round(tmp.getY()));
        }

}

public void paint(Graphics g) {
    g.setColor(color);
    Graphics2D g2d = (Graphics2D)g;
    face=new Polygon();
    for(int i=0;i<Vertices.size();i++) {
        Vertices.get(i).update();
        Point2D tmp = new Point2D.Double();
        tmp.setLocation((int)Vertices.get(i).x2d, (int)Vertices.get(i).y2d);
        face.addPoint((int)tmp.getX(),(int)Math.round(tmp.getY()));
    }
    g2d.fillPolygon(face);

}

```

}

I'd just like to apologize if my question is unclear, it's difficult for me to explain this.

# Answer
> 2 votes
It appears that you are trying to write a 3D render engine, and you want the faces to be rendered from front to back so you don't get an x-ray effect. Your current method would not work with intersecting faces.

---

# Z-Buffering

A Z-buffer is an array that stores the z-distance of every pixel in the viewport:

Image from Wikipedia: Original page.

When you are rendering, you calculate the Z-distance of the current pixel. You then compare that to the corresponding Z-distance in the buffer for that pixel. If the distance is less than that of the Z-buffer, you draw the pixel, and write the distance to the Z-buffer. If, however, the distance is greater, you skip that pixel and continue rendering.

For example:

```
drawPixel(int x, int y, int zDist, Color c)
{
    if(zDist < zBuffer[x][y])
    {
        pixel[x][y] = c;
        zBuffer[x][y] = zDist;
    }
}

```

I'm sure there are optimizations you could make, but this is the general way of doing it.

---
Tags: java, 3d, projection
---


# Question
Title: In Unity, how do I dynamically manipulate parts of a mesh?
I'm trying to achieve mesh manipulation of any mesh based on user input (mostly sliders). Here's an example of what I want. I am not sure whether to call this "morphing", as I am trying to change one part of the mesh without modifying the other parts.

How does this work?

# Answer
> 2 votes
Unity allows you to easily edit the vertices in a mesh.

The problem would be the *editing only some parts of the mesh*. You could edit vertices based on how close they are to an origin, like Blender's "proportional edit".

# Answer
> 0 votes
I haven't done this myself, but I know where you might want to look or start.

You would need to come up with some type of algorithm, I would look at the latest Game Programming Gems or GPU Gems to see if there is some insight. I do not think EA will part with their code. I have seen this sort of stuff you want to do work at a basic level in Spore. The earlier form of the technology might be publicly available.

I would find a method in Unity3D to get the local vertices of a control point on the mesh. Then you could apply some scaling function, after the scaling pass, you might need a clean up pass. You would need to clean up vertices, and shape fragments, especially if the geometry you wish to scale extends into the geometry you didn't want to change.

Also, if you're growing an animating object on moving parts, you may run into some issues with the rig.

You may need to define a scaling curve depending on the type of geometry you're optimizing.

Some sort of tessellation would allow you to work with less vertices and optimize your algorithm.

You might be able to define your own bones in Unity3D, and use that for some type of scaling.

Lastly, you could request an update to the Unity3D engine with this sort of feature.

# Answer
> 0 votes
You can use Blend Shapes for this, which would allow you to account for possibly animation problems in your modeling tool rather than further down the workflow, but if you want

## Finer Control

Identify the regions you want to morph and assign weights to each vertex within those regions so that your modifications can taper off. That part is no different from regular vertex weighting for animation.

Next, you'll define the transformation matrix that will be applied to each vertex, where the minimum would be the identity matrix.

```
class BlendTarget
{
    public Vector3 Translation;
    public Quaternion Rotation;
    public Vector3 Scale;

    // The "center" of the transformation - used for rotation/scaling
    public Vector3 Origin;

    // Vertex indices to modify
    public int[] Indices;
    // Amount to modify the vertex - from 0 to 1
    public float[] Weights;

    public Matrix4x4 Matrix
    {
        get { return Matrix4x4.TRS(Translation, Rotation, Scale); }
    }

```

Such that, for each vertex in your predefined region:

```
    public void Apply(Mesh baseMesh, Mesh meshResult, float amount)
    {
        if (baseMesh == null)
            throw new ArgumentNullException("baseMesh");
        if (meshResult == null)
            throw new ArgumentNullException("meshResult");
        var identity = Matrix4x4.identity;

        var morphTarget = Matrix;
        // Matrix applied overall, weighted by "amount"
        morphTarget = MatrixLerp(ref identity, ref morphTarget, amount);
        for (var i = 0; i < Indices.Length; i++)
        {
            // Matrix applied to this vertex by its respective weight
            var vertexMatrix = MatrixLerp(ref identity,
                                          ref morphTarget,
                                          Weights[i]);
            var index = Indices[i];
            // Applying the transformation from the base mesh vertex
            // Additional calculations would be necessary if some regions overlap
            meshResult.vertices[index]
                = vertexMatrix.MultiplyPoint3x4(baseMesh.vertices[index] - Origin) + Origin;
        }
    }

    public static Matrix4x4 MatrixLerp(ref Matrix4x4 from, ref Matrix4x4 to, float s)
    {
        var ret = new Matrix4x4();
        for (var i = 0; i < 16; i++)
            ret[i] = Mathf.Lerp(from[i], to[i], s);
        return ret;
    }
}

```

What you do beyond that is up to your imagination!

---
Tags: unity, 3d-meshes, procedural, vertex-arrays, face
---


# Question
Title: How can I use graph traversal to generate a round region?
I was playing a tile-based game and noticed it used what appeared to be a circular shape for the light sources.

How can I generate something similar?

My understanding of cellular automata is that each cell's value is generated based on its neighbours. I had always assumed that every node had to have the exact same behavior, but it looks like the 4's have different behavior.

# Answer
In the context of *cellular automata* in second picture, it looks as though the 5 cell might represent a different cell type such that other cells recognize it as a source even if they are separated diagonally. (as @david van brink has shown).
In the context of *procedural-generation*, it looks rather that the the 5 tile has different behavior from the rest, propagating to not only adjacent tiles but also diagonals while all the rest propagate to just adjacent tiles.

Simple cellular automata might have a simple set of rules where each cell follows a given global behavior but there's nothing that says you must implement your propagation calculations in such simple terms. This is why the idea of cellular automata might not be what you actually want to ask about but just procedural generation in general.
To answer your question, you could define a separate type of tile, say a source tile, which propagates more strongly than just a normal tile. Instead of propagating to just strictly adjacent tiles, it would also propagate to diagonals as well and the rest would carry to adjacent tiles like normal.
> 3 votes

# Answer
IF this were generated by cellular automata -- It probably wasn't. But the question is sort of interesting, so -- then a plausible algorithm would be:

```
 start with a field empty but for a single cell marked "5".
 each iteration apply the following algorithm to every cell simultaneously:
   if not blank, do nothing,
   // omit next line to get output on left, include for output on right
   else, if you have a diagonal neighbor "5", mark yourself "4"
   else
     let N = max(non-diagonal neighbors) - 1
     if N > 0, mark yourself N
     else do nothing

```

Every cell can follow this algorithm, and end up with the pattern posted. And yeah... having a friend called "5" is special, but all cells follow the same rule.
> 1 votes

---
Tags: procedural-generation
---


title: Depth write and depth test in Unity

text:
# Question
Title: Depth write and depth test in Unity
*Scenario*: several objects (o1, o2,.., on) have to be rendered with the z test disable, but the z values must be written to the depth buffer. In another pass, some other objects (t1, t2,..., tm) need to be rendered considering with the z test enabled, and considering the prior values from the previous pass.

Is it possible to achieve this with Unity's material script? The goal is to support a custom order for the rendering of transparent objects (the o1,..,on in the scenario description) alongside with matte objects (t1,..., tm). I tried using the features mentioned here, but the results were incorrect, i.e. as if the z values were completely discarded inbetween passes. Can anyone, perhaps, share a code stub for this scenario?

# Answer
Yes you can do this.

Check out this other question which I asked and then answered myself. Specifically the 2nd half that talks about the depth buffer.

Unity3D sprites vs Mesh Quads - Depth, Blending, Shadows

The trick is going to be to use a custom shader and set in the shader the render que (to determine draw order) and the depth buffer settings.

Your earlier objects need to be rendered with `ZWrite On`, but with `ZTest` to either `Always` or to some other setting that will make it draw according to your needs. Possibly `LEqual`.

Then your later objects will need to be rendered with `ZTest` also appropriate. Possibly also `LEqual`. I don't know where your objects are in 3d space. But you can use the ZTest to control culling here.

The **trick** though is to make sure you are using `"Queue" =` to force the drawing in a specific order. Check this page: https://docs.unity3d.com/Manual/SL-SubShaderTags.html for info on how the queue works. Essentially the Queue is set to a constant that equates to a number. And you can add `+1` (or `+100`) to that constant to make it higher. Or set it to any number manually. And then rendering is done sorted in this queue order.

To be clear: you can write and test, not write and test, write and draw always.. any combination of writing to the depth buffer and using it to cull.
> 1 votes

# Answer
As far as has been determined currently, writing to the depth buffer does not work. Unity allows the use of depth textures for many screen effects, though it seems that your issue is most likely a problem with using the depth flags correctly. Do you have any code you post or more information about your use case?
> 0 votes

---
Tags: unity, transparency, depth-buffer, materials
---


title: Rendering many similar objects

text:
# Question
Title: Rendering many similar objects
I am writing an city builder. The graphics should look pretty simple, there are no fancy models or textures. Something like Synekism. Thus I have only simple models for buildings and splines for roads.

What is a good way to render that? I heard about instanced rendering, but my objects are all slightly different (different height/width/depth).

Right now I have a VBO and VAO for each object, and I know I can already speed things up by only using one VAO for all objects, right? But what then?

# Answer
Look into "Hardware Instancing." This let's you store multiple transform matrices in a buffer. However, if nothing is particularly changing with these meshes I would have them all in a few VBO's. http://www.gamedev.net/page/resources/\_/technical/opengl/opengl-instancing-demystified-r3226
> 2 votes

# Answer
Use multiple World matrices to draw the same geometry over and over.

I come from XNA, but was able to Google my way to this point in a few minutes. Someone that knows what their doing could post a much better answer in a similar number of minutes, *if they wanted*. I don't know how to write the commented parts...

```
glClear(GL_COLOR_BUFFER_BIT);
glBindVertexArray(vao);
GLint world = glGetUniformLocation(shaderProgram, "World" );
for(int i = 0; i < 5; i++) //Foreach(object)
{
  glUniformMatrix4fv(world, 1, GL_FALSE, glm::value_ptr(World)); //WorldMatrix for each object
  glDrawArrays(GL_TRIANGLES, 0, 12);
}
glfwSwapBuffers();

```
> 2 votes

# Answer
If what you have is indeed are the same models, just scaled differently, then you can create just one of each models/shapes. Then, at render, pass a model transformation matrix that will move/rotate/scale the model in vertex shader as it should be.
> 1 votes

---
Tags: opengl, rendering
---


# Question
Title: How to retrieve vertex information from ID3DXMesh
I need to know the position of each vertex (and triangles) from a mesh (a pointer to `ID3DXMesh`, created by calling functions like `D3DXCreateBox`, `D3DXCreateTeapot` and `D3DXCreateSphere`) to perform some collision detection.

I've tried using `GetVertexBuffer()` and `GetIndexBuffer()` but I don't know how to use the structures to retrieve point data in the world coordinate system. How can I achieve that?

# Answer
You can look at the legacy DirectX SDK Direct3D 9 sample *Pick* or the Direct3D 10 sample *Pick10*.

Generally you don't actually want to use the same geometry to render as you do for doing collision detection. Most games will first use simple bounding geometry like spheres, axis-aligned boxes, oriented-boxes or cylinders and make decisions from that.

If after bounding volume tests you determine a possible intersection and you need face-level intersection testing, then you'd ideally do a face-by-face collision using a simplified mesh rather than the original complex geometry that is often made to avoid issues with convexity. For CAD and editors, you would likely do a face-by-face collision test of the 'true' geometry, but you'd maybe do that with a system memory copy rather than the render copy in the VB/IB for efficiency. With Direct3D 9, you can generally read `POOL_MANAGED` resources but that's because there is already a system-memory copy in addition to the video memory copy. With Direct3D 10.x/11.x you'd want to maintain the collision data yourself outside the IB/VB rather than force the IB/VB to be in a 'DYNAMIC' mappable location.

And you can of course use various GPGPU techniques to try to accelerate collision detection, but that's quite complicated to get robust.
> 1 votes

---
Tags: collision-detection, directx9, mesh, vertex-buffer, index-buffer
---


# Question
Title: Can one sell the game made in unity free version?
I'm just getting into it and soon my first project will be done. Can I sell it afterwards?

# Answer
Yes.

http://unity3d.com/unity/faq

> Yes you can create and sell a game with the free version of Unity, without paying royalties or any revenue share. However, Unity Free, which includes the free platform add-on products, may not be licensed or used by a commercial entity with annual gross revenues (based on prior fiscal year) in excess of US$100,000, or by an educational, academic, non-profit or government entity with a total annual budget for the entire entity (based on prior fiscal year) in excess of US$100,000.
> 1 votes

---
Tags: unity
---


title: Possible A* Optimizations

text:
# Question
Title: Possible A* Optimizations
I have implemented A\* in my game. However, I am not happy with the performance and need some help deciding what to do next.

**I have already done the following optimizations:**

* Not having a closed list (a `Node` just stores a `bool onClosedList()`)
* Not iterating through the open list to check if a `Node` is on it (I have a `bool onOpenList()` too)
* Using a `std::priority_queue` to store the what is on the open list
* Using a heuristic that just adds up the difference in x and y coordinates
* If the zombie is targeting the player, it only updates if the player moves tiles
* If the zombie is targeting an object other than the player, it only finds the path once as objects(i.e turrets) don't move.

**Some questions about my pathfinding:**

* Zombies will eventually position themselves directly horizontally or vertically to to the player, and then follow the same path. Can I make it more random?
* I've heard about pre calculating every possibly path, but I feel like that will be extremely memory intensive as my map size is 257 x 257 tiles.

**How my pathfinding works:**

1. Create a multi-dimensional vector (matrix?) of Nodes
2. Put the starting node into the `openList`
3. Pop the top of the openList and set that node's `onOpenList` value to true.
4. Get its neighbors (`!onOpenList && !onClosedList && walkable`) into the `openList`after calculating their values. If the neighbor is the target, put it on the stack and stop.
5. Set its `onClosedList` value to true
6. Repeat 3-5 until you find the target
7. Stack the parent of the top `Node` on the stack until it is the root node.
8. The zombie will keep moving to the top `Node` in the stack and then pop it.

**My code:**

```
void Zombie::findPath(std::vector< std::vector<Tile> >* pVTiles)
{
    //Creates a matrix of nodes
    std::vector< std::vector<Node> > mNodes_(257, std::vector<Node>(257, Node(sf::Vector2i(0, 0))));

    //Clears the stack
    while (!sPNodes_.empty())
        sPNodes_.pop();

    if (targetPosition_ != sf::Vector2i(0.0f, 0.0f))
    {
      readyToRepath_ = false;

        //Initiates lists
        std::priority_queue<Node*, std::vector<Node*>, compNode> openList;
        Node* currentNode;
        bool pathFound = false;

        //Initiates the great journey
        Node* pStartNode = &mNodes_.at((int)(positionGlobal_.x / 32)).at((int)(positionGlobal_.y / 32));
        pStartNode->setPosition(sf::Vector2i(positionGlobal_.x - fmod(positionGlobal_.x, 32.0f) + 16, positionGlobal_.y - fmod(positionGlobal_.y, 32.0f) + 16));
        pStartNode->setIsStartNode(true);
        pStartNode->setIsOnOpen(true);
        openList.push(pStartNode);

        while (!pathFound)
        {
                //Gets the a pointer to the top item in the openList, then moves it to the closed list
            currentNode = openList.top();
            currentNode->setIsOnClosed(true);
            currentNode->setIsOnOpen(true);
            openList.pop();

            //For the eight neighboring tiles/nodes
            for (int i = 0; i < 8; ++i)

              {
                int xPos;
                int yPos;

                //xPos
                if (i == 0 || i == 4)
                    xPos = 0;
                else if (i > 0 && i < 4)
                    xPos = 1;
                else
                    xPos = -1;

                //yPos
                if (i == 2 || i == 6)
                    yPos = 0;
                else if (i < 2 || i > 6)
                    yPos = 1;
                else
                    yPos = -1;

                sf::Vector2i nodePosition = currentNode->getPosition() + sf::Vector2i(xPos * 32, yPos * 32);

                //Creates a node for the tile
                Node node(currentNode, sf::Vector2i(xPos, yPos));

                //Checks to see if it is the target adds node to stack and breaks if so
                if (node.getPosition() == targetPosition_)
                {
                    pathFound = true;
                    sPNodes_.push(node);
                    break;
                }

                //Stop working if the node/tile is a wall or contains a tree
                  if (pVTiles->at(nodePosition.x / 32).at(nodePosition.y / 32).getType() == "unwalkable")
                    continue;

                //If it's not the target
                if (!pathFound)
                {
                    float parentDistanceValue = node.getParentNodePtr()->getDistanceValue();

                    //Distance is 1.4f x 32 if diagonal, 1 x 32 otherwise
                    if (xPos == yPos)
                        node.setDistanceValue(parentDistanceValue + 44.8f);
                    else
                        node.setDistanceValue(parentDistanceValue + 32.0f);

                    //Gets the distance to the target(Heuristic) and then gets the total(Distance + Heuristic)
                    node.setHeuristicValue(abs(targetPosition_.x - nodePosition.x) + abs(targetPosition_.y - nodePosition.y));
                    node.setTotalValue();

                    //If the node is not already on the open/closed list
                    Node listCheckNode = mNodes_.at((int)(node.getPosition().x / 32)).at((int)(node.getPosition().y / 32));
                    if (!listCheckNode.isOnClosed() && !listCheckNode.isOnOpen())
                    {
                        mNodes_.at((int)(node.getPosition().x / 32)).at((int)(node.getPosition().y / 32)) = node;
                        openList.push(&mNodes_.at((int)(node.getPosition().x / 32)).at((int)(node.getPosition().y / 32)));
                    }
                }
            }
        }

        //Keeps stacking parent nodes until the start is reached
        while (!sPNodes_.top().isStartNode())
        {
            Node parent = *sPNodes_.top().getParentNodePtr();
            sPNodes_.push(parent);
        }
        //Pops the top node as the zombie is already on it
        sPNodes_.pop();
    }
}

```

**Thanks!**

If you need more information or have any questions, just ask!

# Answer
> 4 votes
Rather than pre-calculating every distance, simply pre-calculate the distances to and from each corner of the map to every node(perfect use-case for Dijkstra's algorithm) and then use this information and the Triangle inequality to generate a heuristic. This algorithm modification is referred to as **ALT**, or A-star with Landmarks and Triangle inequality. I have implemented this on a hex-grid (along with a Heap-On-Top Priority Queue and Bi-Directional search) and it calculates paths in under 100 ms on a 750 * 450 terrain grid. Pre-calculation (for 10 landmarks and 335,000 nodes using 6 of 8 processors on a 3-year old Intel i7 notebook) takes about 3 seconds.

One point to note that took me a while to unravel, is that each travel direction from each landmark generates an admissible heuristic for only one direction of the bidirectional search.

Additional Links:

The Hex-Grid utility linked to is Open Source under the MIT Licence.

**Update**:

Sample C# code for the parallel calculation of the Landmark distances:

```
public static ILandmarkCollection CreateLandmarks(
  IHexBoard<IHex> board,
  IFastList<HexCoords> landmarkCoords
) {
  if (landmarkCoords==null) throw new ArgumentNullException("landmarkCoords");

  ILandmarkCollection tempLandmarks = null, landmarks = null;
  int withCores = Math.Max(1, Environment.ProcessorCount - 2);
  try {
    tempLandmarks = new LandmarkCollection( (
                      from coords in landmarkCoords
                      where board.IsOnboard(coords)
                      select Landmark.HotPriorityQueueLandmarkWithoutReset(coords,board)
                ).ToList<ILandmark>() );

    ( from landmark in tempLandmarks
      from direction in Landmark.Directions
      select new {
        Landmark  = landmark,
        Direction = direction
      }
    ).AsParallel().WithDegreeOfParallelism(withCores)
     .ForAll(item => item.Landmark.Reset(item.Direction));

    landmarks     = tempLandmarks;
    tempLandmarks = null;
  } finally { if (tempLandmarks != null) tempLandmarks.Dispose(); }
  return landmarks;
}

/// <summary>TODO</summary>
public ParallelLoopResult ResetLandmarks() {
  return Parallel.For(0, Count, i => { var l = this[i]; if (l!=null) l.Reset(); } );
}

```

and

```
  [DebuggerDisplay("Coords={Coords}")]
  public sealed partial class Landmark : ILandmark, IDisposable {
    /// <summary>TODO</summary>
    public enum Direction {
      /// <summary>TODO</summary>
      ToHex,
      /// <summary>TODO</summary>
      FromHex
    }
    /// <summary>TODO</summary>
    public static IList<Direction> Directions { get {return _directions;} }

    // other stuff
 }

```

# Answer
> 2 votes
```
std::vector< std::vector<Node> > mNodes_(257, std::vector<Node>(257, Node(sf::Vector2i(0, 0))));

```

This isn't optimal, a more efficient structure would be a

```
std::vector<Node> mNodes_(257*257, Node(sf::Vector2i(0, 0)));

```

and index with `x*257 + y`. You can possibly keep it allocated statically (or thread locally when multithreading) and reset when you need to.

Also instead of recalculating the *entire* path when the player moves prefill the open list with the previous path (returning if the player is already on it) as it is very likely the first part (until clearing obstacles) will remain the same.

# Answer
> 0 votes
Another possible optimization would be to not use priority\_queue...

Using priority queue won't let you update each node distance individually (which is needed for A\*). Using a custom implementation of min-heap, you can fix that issue. This way pushing, and popping nodes into the heap would be of O(logn), and so will updating be. But size of your heap will always be equal to the number of your open nodes.

---
Tags: c++, path-finding, optimization
---


# Question
Title: How to make a scrolling background in Delphi with FireMonkey?
I'm making a scrolling background game alike classic Mario 2D games.

How do I make a scrolling background in Delphi XE7 using FireMonkey?

# Answer
I found this nice tutorial on DelphiGameDev.net:

" So, the first thing we need to do is actually add our background. Previously we set this up in our DXTimer component, redrawing it before each animation. This limits us however and to be able to effectively scroll our background we need to set up a special class of sprite called TBackgroundSprite, much as we did with our pacman and ghost sprites. So, we're going to call our background sprite type, TScrollingBackground. The following code therefore needs to be placed just after we've set up our pacman and ghost sprites near the beginning of our code.

```
TScrollBackground = class(TBackgroundSprite)
public
 procedure DoMove(MoveCount: Integer); override;
 end;

```

Now that we've done that we need to actually give our TScrollBackground it's own variable with the following line in our var section of the code just after the Ghost : TGhost; line. Background: TScrollBackground; To finish setting up our background we need to add the following lines at the beginning of our FormCreate procedure before the existing lines.

```
Background := TScrollBackground.Create(DXSpriteEngine1.Engine);
with Background do
 begin
  SetMapSize(640, 480);
  Image := DXImageList1.Items.Find('NewBackground');
  Y := 10;
  Z := -13;
end;

```

This code assumes that you've set up the DXImageList component with a background called NewBackground and that it is of size 640x480.

So far so good. We now no longer need to have the line DXImageList1.Items\[1\].Draw(DXDraw1.Surface,0,0,0); in our OnTimer procedure any more as this is now handled automatically by TBackgroundSprite. So, once you've deleted this line, compiling the code will give you a program much the same as before, but with a background of image 'NewBackground'. We of course want to be able to scroll our background so let's deal with this now. We need to alter our DXTimer.OnTimer code to take into consideration this change. Before we do that though let's bring in the DXInput component.

In the last tutorial we had our sprites controlled purely by our program, but we obviously would want to have at least one sprite controlled by the user in our game to make it, well a game. This is where the previously introduced component DXInput comes in useful, and only a few changes are needed to our previous code in order to get this working.

Once you've added this DXInput component to your form you need to change the DXTimer.OnTimer code to contain the following. DXInput1.Update;

```
if isLeft in DXInput1.States then begin
  Pacman.AnimStart := 2;
  Ghost.AnimStart := 2;
  Background.X := Background.X + 1;
end;

if isRight in DXInput1.States then begin
  Pacman.AnimStart := 0;
  Ghost.AnimStart := 0;
  Background.X := Background.X - 1;
end;

if isUp in DXInput1.States then
  Pacman.Y := Pacman.Y -1;

if isDown in DXInput1.States then
  Pacman.Y := Pacman.Y +1;

 DXSpriteEngine1.Move(2);
 DXSpriteEngine1.Draw;
 DXDraw1.Flip;

```

Compared to the code we had before in our OnTimer code, the last three lines still exist. All the code we now see before this, deals with controlling our sprite's movement. With our program we want our sprite to appear as though it is moving by scrolling the background instead of moving the sprite every time the user presses the left or right arrow. To do this we just need to increase or decrease our background's X coordinate depending on whether we want to go left or right. You can see we've done that above with the line Background.X := Background.X + 1; and in the similar code a few lines down from that. When it comes to the user pressing the up or down arrow we've just set our pacman sprite to move up and down, but you could always place some code here to get our sprite to jump. We could have also placed the code for scrolling our background in a TScrollBackground.DoMove procedure as we did with the sprites.

Before you run the program now, all you need to do is get rid of the lines PixelCheck := True; and Pacman.X := Pacman.X + 1; in our TPacman.DoMove procedure so that the code is like this:

```
procedure TPacman.DoMove(MoveCount: Integer);
begin
  inherited;
  if PacmanDead = False then begin
    Collision;
  end else
 end;

```

This stops our sprite running off. Obviously with our program the way it is just now, no collision will ever occur but keep it here for just now so that when you need it, it's there. "

via http://www.delphigamedev.com/tutorials/dxtut4.htm
> 1 votes

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


title: Loading Texture2d content in Monogame

text:
# Question
Title: Loading Texture2d content in Monogame
I am using Monogame and following this tutorial series: https://www.youtube.com/watch?v=agt9-J9RPZ0

I am trying to load a Texture2d into the window and despite not getting any error messages the image is not shown.

Can anyone tell me what I am doing wrong?

Code @: https://github.com/blivori/TestGame

Solution setup:

# Answer
You load the texture perfectly, but I don't see any code regarding the drawing of it. Add this:

`spriteBatch.Draw(image, new Vector(0f, 0f), Color.White);`

into your SplashScreen's Draw function.
> 1 votes

---
Tags: xna, monogame, xna-content-pipeline
---


# Question
Title: Most efficient way to hide out of bounds object in tile based environment
I am working on a desktop game in C#, with Monogame framework. I am storing the tile instances in a 2D Array, for the sake of easy collision detection. But the levels are big (often 100x100 or bigger) and there are lots of tiles out of the screen bounds all the time which I should not draw. At the moment I'm running through the arrays and checking whether they are in the screen bounds or outside, but that may not be too efficient due to the big count of the tiles.

Is there any better way to hide out of bounds tiles?

# Answer
> 0 votes
You can determine the range of files you need to draw at first. It will be much faster than check every tile.

```
Rectangle screenRect = new Rectangle(100, 100, 400, 300);
int tiles[,] = new int[1000, 1000];
int tileSize = 16;

int startCol = (int)(screenRect.X / tileSize);
int endCol = (int)((screenRect.X + screenRect.Width) / tileSize);

int startRow = (int)(screenRect.Y / tileSize);
int endRow = (int)((screenRect.Y + screenRect.Height) / tileSize);

for (int row = startRow; row <= endRow; row++)
{
    for (int col = startCol; col <= endCol; col++)
    {
        // draw
    }
}

```

Also, if you have realy big world you can split world on chunks (64x64 tiles, for example) and predraw tiles to the render targets. Then refresh it only when tiles changed and check collision of screen bounds with chunk.

---
Tags: xna, c#, algorithm, tiles, monogame
---


# Question
Title: NavMeshAgent.CalculatePath - how to use properly?
I seriously can't figure out how to use this function, and the documentation doesn't help at all.

Here's the documentation code:

```
public class ExampleClass : MonoBehaviour {
 public Transform target;
 private NavMeshAgent agent;
 void Start() {
     agent = GetComponent<NavMeshAgent>();
     NavMeshPath path;
     agent.CalculatePath(target.position, path);
     if (path.status == NavMeshPathStatus.PathPartial) {
     }
   }
}

```

Here's my code:

```
public class Movement : MonoBehaviour {
 NavMeshAgent agent;
 NavMeshPath path;

 void Start () {
     agent = GetComponent<NavMeshAgent>();
 }

 void MoveToTargetLocation() {
     agent.SetDestination(targetLocation); <-- being set somewhere else

     NavMeshPath path;
     agent.CalculatePath (targetLocation, path);

     if (path.status != NavMeshPathStatus.PathPartial) {
         if (Vector3.Distance (curLocation, targetLocation) > 0.55) {
             animation.CrossFade (animationRun.name);
             moving = true;
         } else {
             animation.CrossFade (animationIdle.name);
             moving = false;
         }
      }
   }
}

```

The error I'm receiving is:

> Assets/Movement.cs(59,54): error CS0165: Use of unassigned local variable \`path'

Am I supposed to be setting the path somewhere else?

# Answer
Your problem is not with the NavMesh. You've defined `path` at two different scopes. Look at your code for two instances of `NavMeshPath path;` Try removing the local instance and add `= new NavMeshPath();` to the other one.

I'm not sure why the documentation is the way it is. The method `CalculatePath` is clearly looking for an initialized `NavMeshPath` object. If it was to work as stated in their example, they'd need the `out` parameter option in the `CalculatePath` method to show that object will be initialized inside the method.
> 1 votes

---
Tags: unity, navmesh
---


title: OnMouseUpAsButton not always called

text:
# Question
Title: OnMouseUpAsButton not always called
I'm working on a 2D implementation of Free Cell in Unity 4.6.1, and I'm having trouble getting my click-detection code working consistently. The code below should be called every time a card is clicked (they all have `BoxCollider2D` components) but it doesn't always happen.

```
// Handle Clicks on Card
void OnMouseUpAsButton()
{
    print ("test");

    int cardLayerMask = LayerMask.GetMask("Cards");

    RaycastHit2D[] hit = Physics2D.RaycastAll(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero, Mathf.Infinity, cardLayerMask);

    print ("Hit length: " + hit.Length.ToString());

    if (hit.Length > 0)
    {
        print ("Hit");

    }
}

```

Even the "Test" print statement doesn't get called consistently, so it's not a problem with the raycast. If it manages to print the test, the raycast always works.

Each time the game runs, the cards get dealt onto the playing field randomly into stacks. On each run, some subset of the cards don't call the above code. The number of cards that work correctly varies, as does their position on the field. It's not consistent with any particular card.

I'm wondering if maybe there's an issue with the `BoxCollider2D` instances overlapping. The other colliders in the scene, like the one on the "table", always trigger `OnMouseUpAsButton()` successfully.

I need to be able to register clicks on every card, so I need to find a way to make this work.

Have any of you run into a similar issue before? If not, is there a way for me to work around this? Maybe a different way to detect the clicks on the cards?

Here's a screenshot of an example card from the inspector. Aside from transform position & script property values, all of them are identical (from a prefab):

**Update w/ Solution from Accepted Answer**

Using @Byte56's solution, I was able to take care of this pretty easily. I've included sample code below.

Note that to get the sample to work, the "top" object has to have the highest transform.position.z out of all the objects the raycast hits. I also put all the possible hit objects into their own layers so I can trigger different behavior based on what type of object is clicked.

```
// Handle clicks
    if (Input.GetMouseButtonDown(0))
    {
        // Cast a ray, get everything it hits
        RaycastHit2D[] hit = Physics2D.RaycastAll(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero, Mathf.Infinity);

        if (hit.Length > 0)
        {
            // Grab the top hit GameObject
            GameObject lastHitObject = hit[hit.Length - 1].collider.gameObject;

            // Determine layer of last hit object, take next steps as appropriate
            switch (LayerMask.LayerToName(lastHitObject.layer))
            {
            case "Cards":
                print ("Hit card!");
                break;
            case "Table":
                print ("Hit Table!");
                break;
            case "Cells":
                print ("Hit cell!");
                break;
            }
        }
    }

```

# Answer
It's hard to know exactly what's happening without hands on but:

1. `OnMouseUpAsButton` is only ever fired after Unity has performed its own successful ray cast (this happens in the background, during each frame so that Unity knows which objects to call the various `OnMouse????` methods on).
2. `OnMouseUp()` is called when releasing the mouse button over a collider. `OnMouseUpAsButton()` is called when releasing the mouse button over the same collider that you started the click on. If your colliders are stacked in the same 2D plane, it's entirely possible the ray cast is hitting different objects on the down and the up. This would explain the "sometimes" part of your problem, as your code only triggers when it happens to get both the down and the up.

I recently answered another question here that describes how to handle mouse input using the `OnMouse???` methods.

I might also recommend not using those methods and just having an input handler script that inside it's `Update` method is just watching for mouse clicks and casts its own ray to choose which object has been clicked. This will not only give you more control over which object is actually selected (perhaps getting all hit objects and choosing the one you've marked as "on top"), but it'll put all of your input handling in one place (making it easier than spreading out all the `OnMouse????` events for each card object).
> 5 votes

---
Tags: unity, 2d, collision-detection
---


title: How do I share my Game Maker games?

text:
# Question
Title: How do I share my Game Maker games?
I'm using GameMaker Studio and I want to put my game on my website.

I need help with saving a game in a exe file or anything that will make my game to open normally. How do I do that?

# Answer
> 4 votes
You can export to Windows PC and Mac OS with the free edition of Game Maker (other export types, like web or mobile, require paid versions).

To create an executable, just open your project, select File-\>Create executable

The latest version of Game Maker Studio (1.2), the option you want is "Create Application":

From there, you can save it as an installer, a compiled exe or a zip.

In this case, you could use the "Single runtime executable" and distribute that.

# Answer
> 0 votes
If you want to share your games online after making the exe, you can make an account on Gamejolt and upload it there.

---
Tags: game-maker, export
---