# Question
Title: In a grid based system, where users can build their own walls to create buildings, how do you determine which parts are indoors?
I've looked around for an algorithm to solve this problem, but I can't seem to find anything.

In a game I am working on, data is held in a grid. Certain squares within that grid can be set as walls, so that the user can create buildings. What I am wondering is how could I write an algorithm to determine which parts of the grid were indoors, that is to say, within a building, and which parts are outdoors. Thank you in advance for any advice.

# Answer
> 1 votes
Essentially you are looking for some sort of graph traversal. In your case, a flood fill may work.

In choosing a starting point, you could either use a point you know is outdoors (if the entire outdoor section is connected, or keep track of all the walls and test their neighbors.

If their neighbor is "not visited," do a flood fill on it and mark all the flooded points with a visited flag. Going through all the neighbors will give me multiple fills, all of which are indoor fills except 1 (or more if you have multiple outdoor sections).

# Answer
> 1 votes
Draw a straight line from the point of interest to a point of known location (indoor or outdoor) - usually traversing one of the four axes is sufficient. Then simply count the number of wall traversals and modulo it by 2. If the number of wall traversals is even then the point of interest is in the same location; if odd it is in the opposite location.

Note that this will count an enclosed Quadrangle as being outdoors, but usually that is the desired result.

---
Tags: algorithm, grid
---


title: Render to Texture Using Multisampling

text:
# Question
Title: Render to Texture Using Multisampling
I have a DirectX11 application, which has multisampling / anti-aliasing enabled. However, I want to add an effect that requires a render-to-texture step. When I add this extra step, I lose all anti-aliasing. Here's basically what I'm doing:

1) render scene to texture

2) render texture to screen (with some effect, say blurring or something).

I've tried enabling multisampling on the render texture, but i'm not sure how to get it to work. I've made it use 8 samples and specified `D3D11_DSV_DIMENSION_TEXTURE2DMS`, but apparently that step required me to use `Texture2DMS` in the shader. But now I don't know how to sample a `Texture2DMS` in the shader, because I can't just pass in the textures coordinates, I have to pass in a *sample index*, which I don't know how to calculate.

How to I use render to texture effects while preserving multisampling / anti-aliasing?

# Answer
> 4 votes
The idea behind multisampled textures is to let you explicitly fetch each of the individual samples in a shader. You can gather all 8 samples and implement the MSAA resolve (the process by which multiple samples are resolved into a single sample) yourself, but I do not think that is what you want.

In OpenGL, you work around this problem by *blitting* a multisampled source texture into a singlesampled destination, which takes care of MSAA resolve for you. Then, in your shader you use the anti-aliased singlesampled result instead of the original multisampled texture.

D3D has this same functionality, in the form of `ID3D11DeviceContext::ResolveSubresource (...)`. Unfortunately, all I can do is point you to that function because I have no experience actually using it.

---
Tags: c++, directx, directx11
---


# Question
Title: Second pass in multipass effect is ignored
I am trying to render my vertecies in 2 passes, but it seems I am doing something wrong, because only one pass applying. I cannot make the second one work despite that second pass is applying.

Here is my code:

```
var effectByteCode =            ShaderBytecode.CompileFromFile(@"Content\Effects\SpriteBatchEffect.fx", "fx_5_0");
spriteBatchEffect = new Effect(this.graphicsDevice, effectByteCode);
pass = spriteBatchEffect.GetTechniqueByName("SpriteBatch").GetPassByIndex(0);
//Layout from VertexShader input signature
var passSignature = pass.Description.Signature;
layout = new InputLayout(graphicsDevice, passSignature, inputElements);

```

Effect code:

```
    Texture2D Texture;
    SamplerState TextureSampler;

matrix OrthoMatrix;

struct VertexInputType
{
   float4 position : SV_POSITION;
   float4 color: COLOR;
   float2 tex : TEXCOORD0;
};

struct PixelInputType
{
   float4 position : SV_POSITION;
   float4 color: COLOR;
   float2 tex : TEXCOORD0;
};

PixelInputType SpriteVertexShader(VertexInputType input)
{
   PixelInputType output;
   output.color = float4(0, 0, 0, 0);
   output.position = float4(0, 0, 0, 0);

   // Change the position vector to be 4 units for proper matrix calculations.
   input.position.w = 1.0f;

   output.position = mul(input.position, OrthoMatrix);

   // Store the texture coordinates for the pixel shader.
   output.tex = input.tex;
   output.color = input.color;
   return output;
}

float4 SpritePixelShader(PixelInputType input) : SV_TARGET
{
   return Texture.Sample(TextureSampler, input.tex)* input.color;

}

float4 SpritePixelShader2(PixelInputType input) : SV_TARGET
{
   /*return Texture.Sample(TextureSampler, input.tex)+ input.color;*/
   return float4(1,0,0,0);
}

technique10 SpriteBatch
{
   pass P0
   {
      SetGeometryShader(0);
      SetVertexShader(CompileShader(vs_4_0, SpriteVertexShader()));
      SetPixelShader(CompileShader(ps_4_0, SpritePixelShader()));
   }

   pass P1
   {
      SetGeometryShader(0);
      SetVertexShader(CompileShader(vs_4_0, SpriteVertexShader()));
      SetPixelShader(CompileShader(ps_4_0, SpritePixelShader2()));
   }
}

```

And how I am using it:

```
graphicsDevice.SetVertexBuffers(0, vertexBufferBinding);

     var technique = tempEffect.GetTechniqueByName("SpriteBatch");
     for (int i = 0; i < technique.Description.PassCount; i++)
     {
        var localpass = technique.GetPassByIndex(i);
        //if (localpass.IsValid)
        {
           localpass.Apply(graphicsDevice);
           graphicsDevice.DrawIndexed(indexCount, 0, 0);
        }
     }

```

Could someone point me why second pass is not apply? What I am missing here? Note that I am not using SharpdDX toolkit - just plain SharpDX + C#

# Answer
Seems I found an issue - I had to change my depth stencil state to make second pass enabled, because by default second pass discarded by depth stencil state.
> 1 votes

---
Tags: shaders, directx, sharpdx
---


# Question
Title: How do I efficiently send RTS unit selections over the network?
I have a multiplayer RTS game with every unit assigned an ID.

How can I efficiently send across a network the units selected by a player? For example, *Starcraft 2* has upwards of 200 units per player and each player can select a maximum of 255 units at a time. How can I implement such a system with reasonably low response time and bandwidth?

Should I bother sending IDs? Should I perhaps send a bitmask with each bit defining whether each unit is selected?

# Answer
There is no reason to communicate over the network when the player *selects* units, because in most games just selecting a unit has no game-mechanical consequences. So this is an information which isn't relevant to the server or to the other players.

But what would be important is when the player gives a *command* to one or more units. When issuing a move-command to a bunch of units, the client would send the IDs of the units and the locations to which they were sent. When we assume that a unit has a 2byte ID (allowing up to 65000\* units in the game), the target coordinates are in tiles and the maximum width and height of a map is less than 65000\*, we have 6 bytes per unit move command. When the player sends a move-command for 200 units at once, we have 1200 bytes.

The best RTS players perform up to 200 actions per minute, which would be about 3 actions per second. When each of that actions is a command to 200 units, this would require a bandwidth of 3600 bytes/s. Let's round this up to 4 kByte/s with overhead.

4 kByte/s is half the bandwidth of a 56k analog modem which was a standard consumer-grade internet connection in the 90s when Starcraft 1 was released. Assuming that the incoming bandwidth is about the same, we see that a duel between two world-class Starcraft players was just within the bandwidth capabilities of the average household when Starcraft 1 was released. Considering that not every action will be a command to 200 units at once and that the average player performs much less than 200 ApM, we see that an 8 player online match between casual players was definitely possible that way.

<sub>\*65536 when you want to split hairs</sub>
> 13 votes

# Answer
Most of RTS game like starcraft / warcraft etc only transmit player input between clients. After the game engine does the simulation with the input received. It's lighter for the network to only send the player's inputs.

look at this post : How to implement lockstep model for RTS game?
> -1 votes

---
Tags: networking, multiplayer, rts, selection
---


# Question
Title: Getcomponent(), GameObject, and Component issues
I have been trying for over 2 hours now to get over these problems :

1. I have 2 GameObjects in my hierarchy, but I do not have them anywhere in any script. I would very much like to add those 2 objects into a script of mine. I used

GameObject thing1 = new GameObject("name of object");

but unfortunately this didn't work, gave me errors about how I can only create objects from main script? I pasted my code into game.cs, and added the game.cs script to the 2 objects I want, but I get the exact same errors.

2. So the reason for this problem is that I need to actually add those 2 objects in my lines of code, so I can use GetComponent(); to be able to modify the enabled status of my script. So the other problem here, is that when I use GetComponent on the 2 objects, I get a nullreference exception. I am very sure that I added the script to both the objects, and I'm pretty sure I didn't mistype them, so can anyone give me a hand please?

# Answer
> I have 2 GameObjects in my hierarchy, but I do not have them anywhere in any script. I would very much like to add those 2 objects into a script of mine. I used
>
> ```
> GameObject thing1 = new GameObject("name of object");
>
> ```

That would create a *new* GameObject. If you want to get an object by name, you'll need to call

```
GameObject thing1 = GameObject.Find("name of object");

```

That will locate the first object by that name. However, if you have multiple objects named that then you're in trouble. It would be better to expose a `GameObject` field on the component you're writing and link the object in the editor. Just drag the object from the hierarchy into the field on your component in the inspector.

> So the reason for this problem is that I need to actually add those 2 objects in my lines of code, so I can use GetComponent(); to be able to modify the enabled status of my script. So the other problem here, is that when I use GetComponent on the 2 objects, I get a nullreference exception. I am very sure that I added the script to both the objects, and I'm pretty sure I didn't mistype them, so can anyone give me a hand please?

If you're trying to get a *component* named "name of object", then that will return a null because there cannot be a component named such. As above you need to *Find* the *GameObject* with that name. Then, to access their components, you'll call

```
SomeComponent component = thing1.GetComponent<SomeComponent>();

```
> 1 votes

# Answer
First off, there's this function http://docs.unity3d.com/ScriptReference/GameObject.Find.html

But this may not be the ideal approach in your situation; it's hard to tell. The more typical approach to referencing objects in code is to link them in the Editor. To do that, declare a variable for the object at the top of your code, and then that variable will appear in the Inspector. Now drag your object onto the Inspector.
> 0 votes

# Answer
```
        Instantiate(prefab, new Vector3(0, 0, 0), Quaternion.identity) as Transform;

```

Believe you want to instantiate a game object. Create a prefab, assign it, and use this command. As far as making a new new object, just make an empty game object, from there you can instantiate all components/renderers/colliders and whatever else
> 0 votes

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


# Question
Title: Unity 2D Prevent knockback effect from 2D Translation
I've just started looking into developing with Unity, and read through the tutorials and introductions. For my first project, I decided to try something simple - so a breakout clone. However, when the ball hits the player, the player gets knocked down a few pixels.

The player and ball have BoxCollider2D attached to them, and the player also has a RigidBody2D attached to it. The player is also checked as a "static" object. The ball moves towards the player using transform.translate().

Here is the balls script:

```
using UnityEngine;
using System.Collections;

public class BallScript : MonoBehaviour {

    public float speed;
    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        this.transform.Translate (Vector3.down * speed * Time.deltaTime);
    }

    void OnCollisionEnter2D (Collision2D col) {
        this.speed = -speed;
    }

}

```

# Answer
> 3 votes
What you want to do for this kind of game, is not directly change the transform of the ball but change the velocity of the rigidbody.

Set friction to 0 in the rigidbody of the ball and lock the movements of the panels.

Have a script that detects if the ball collides with the panel, on collision delete the panel and let the physics response do the work.

Set the physics material of the ball/walls/panels to an elastic collision.

If you want to add some speed when the ball hits a panel/player, increment/alter the velocity or apply a force to the rigidbody.

The player should not be static. Static is used to optimize non moving GameObjects. The player should have a its rigidbody x and y positions locked and moved with a script on user input. Lock the rigidbody under constraints in the inspector.

Hope this helps!

Here is a Tutorial that might help!

---
Tags: unity
---


# Question
Title: Need some help with math steering behavior stopping on destination point
I have implemented a movement system based on steering behaviors: http://gamedevelopment.tutsplus.com/series/understanding-steering-behaviors--gamedev-12732 where each object has vec2 position, velocity, desiredPosition with 2 constants: maxspeed and acceleration. In each game step, the object's position is updated as follows:

```
vec2 desiredVel = this.desiredPos - this.position;
desiredVel.truncate(this.maxSpeed);

vec2 steeringForce = desiredVel - this.velocity;
steeringForce.truncate(this.acceleration);

this.velocity += this.steeringForce * dt;
this.velocity.truncate(this.maxSpeed);

this.position += this.velocity * dt;

```

The problem is stopping. I have been stopping by using a scaling factor that reduces the desiredVel when the object is within a certain distance of the target position:

```
var dist = desiredVel.length;
if (dist < this.maxSpeed * this.maxSpeed / this.acceleration){
    this.desiredVel *= dist/this.maxSpeed;
}

```

This goes between the desiredVel calculation and steering force calculation.

Unfortunately, this method is not very exact. Sometimes the object will overshoot its destination and sometimes it will slow down way before the destination is reached. Is there a way to make the object stop on the destination point? That is, it should not overshoot nor slow down prematurely.

Edit: and yes I have seen the arrival section in the link I posted above and it shares this same inexactness. What I want I guess is for the path to look more realistic. That is the object accelerates at the start of path to its max speed then it decelerate at the right timing so that it stops at the destination exactly. (or close enough)

**And 2ndly**, I also want to know the **time** it takes for an object to reach from pointA to pointB before the object takes its path. The maxspeed and acceleration is constant and there are no other forces acting on the object within the path. How can i calculate the time?

# Answer
When acceleration a is constant, use the High School kinematics equations:

1. v = u + a t
2. delta-d = u t + a t ^2 / 2
3. v^2 - u^2 = 2 d (delta-d)
4. delta-d = (v + u) / 2 t

where:

* u is the unitial velocity (sic)
* v is the vinal velocity (sic)
* t is the elapsed time
* delta-d is the displacement from starting position to ending position.
> 1 votes

# Answer
The two equations you are looking for are:

```
t * v_0 - 0.5 * a * t^2 = d
v_0 - a * t = 0

```

where `t` is the elapsed time, `v_0` is the optimal velocity, `a` is maximum acceleration, and `d` is the distance to the target.

The trick is in interpreting these formula. First, we assume we are in 1D by applying and acceleration to zero any component of velocity that does not lie along the line to the target. Thus our character will move directly towards the target. However, if it just went at maxspeed, it would not be able to stop when it reached the target, would overshoot and thus "orbit".

The solution to these formula tells us `v_0` (and `t`, but ignore that for now), such that if we were to immediately start decelerating at rate `a`, starting from speed `v_0` and at distance `d` from our target, then we would arrive exactly there with velocity zero. We call this the optimal speed because it is the fastest we can move at distance `d` and still be able to slow down enough to arrive at velocity zero. Any slower, and we are wasting time not going as fast as we should be, and (crucially) any slower and we will be going too fast to slow down in time. This justifies our use of the term "optimal velocity".

This suggests an algorithm to control our character: look at the current distance, and use it to compute the optimal velocity. If we are far from our target, this may be much higher than our maximum speed, in which case just set the desired velocity to `min(v_0, maxspeed)`. Then, apply an acceleration to bring our velocity to the desired velocity, something like:

```
accel = constrain((desired_vel - current_vel)/timestep, -maxaccel, maxaccel)

```

recalling that `desired_vel`, `current_vel`, and `accel` are all 1D quantities along the line between the target and the current position. You need to convert the acceleration back to 2D before you apply it by multiplying by a unit vector pointing towards the target. The division by timestep is *required*, both to ensure the correct physical units, and to ensure the character accelerates as quickly as possible.

Pragmatically, the solutions are `v_0 = sqrt(2 * d * a)`, `t = sqrt(2 * d / a)`, and this formula might result in slightly too high of a speed due to inexact integration (Euler isn't very exact). Thus as a tweak you might do `desired_speed = min(maxspeed, v_0) * 0.98`, to ensure you have a little bit of slack in the speed. This results in the character taking a tiny bit more time to reach the target, but also results in fewer overshoots due to integration error. You might consider expanding the definition of what it means to be "at" the target by some small radius to get the character to stop making tiny corrective accelerations, especially if some logic or behavior depends on them "reaching" their destination.

The time estimate is a bit trickier, because the maximum speed and any motion not toward the target complicate things. If you are close enough to the target that you can go `desired_vel`, then `t` is the time to arrive. If you are further away, the total time depends on how long it will take to get to maxspeed, how far you travel at maxspeed, and how long you decelerate for. Starting from a stop, the path will actually be symmetric in velocity, so for two points that are far apart (long enough for the character to accelerate to maxspeed), the time can be calculated as:

```
T = t_a * 2 + (D - 2 * d_a) / maxspeed
t_a = solve for t when v_0 = maxspeed
d_a = solve for d when v_0 = maxspeed

```

For shorter distances, when `D < 2 * d_a`, `T = 2 * (solve for t when d = D/2)`, because we accelerate for half the time and distance, then decelerate for the other half of time and distance. Each half effectively has the same `d`, `t`, and `v_0`. Note both of these time calculations rely on solving the first set of equations in different ways.
> 1 votes

---
Tags: mathematics, vector, steering-behaviors
---


# Question
Title: How can I verify if there is no object between 2 others?
I have 2 characters in my 2D game, I would like that if both of them are on the same Y axis, and there is no collider/object between them, for an animation to happen. I can't figure out how to check for the last one though... Thanks for the help!

EDIT :

Hello, I have used MrCranky's code and it seemingly looks like it should work, but I am having a problem with the syntax I think. Physics.Raycast((x,y) of the 1st player, new Vector3 (1,0,0), distance between them -2) So this code, if there is nothing between the player and the other character, it should give me a false. And it worked, but the problem is, even after I added an object between them, it stayed on false through every update, could you assist me with what am I doing wrong please?

# Answer
> 3 votes
The brute force solution would be to iterate over all objects which **might** be in between the two characters and test them each individually (GameObject.FindObjectsOfType is probably your friend here).

However a much simpler and cheaper solution would be to do a ray-cast from one character's position to the other. If any results are returned they'll be in the way of the two characters. Bear in mind that will draw a thin ray from the local origins of the characters though, if you need partial collisions (e.g. a collider just off to one side of that ray but which the character would hit if they tried to move towards the other character) then you'd need a sweep test (moving the character's collision volume along the path towards the other character) of some sort. You might be able to get away with 5 raytests instead - one in the centre and one for each corner of the character's AABB.

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


# Question
Title: What would be a good way to implement a large 2d map?
I'm thinking of a way to implement a large 2d map which can be easy to handle a certain area of the map to update. I've seen many 2d map using double array like `int[][] gameMap = {
{#,#,#,#,#},
{#,o,o,o,#},
{#,o,o,o,#},
{#,#,#,#,#}
};`

However editing (fixing) the map by hand would be troublesome when it gets for example 1000\*1000.

so what would be a good way to do so? I heard FF14 has a map uses grid to organize each small area.

# Answer
height map can be the solution? A big b/w image to manipulate the map heights easly wilth an image editor (gimp?). A (selfmade) tool that transform a B/W image (i've done one in c#) into a matrix of floats and save/load it to file concerning your needs.

If you need a memory buffer to keep a small part of your big file map , you can consider an aproach like this :

It's a sequenzial file that rappresent your (virtual) space. From the x,y you are interested in , you calculate the page number that rappresent a portion of your map that you load in memory. You can implement also a cache , keeping the last pages accessed in memory.
> 2 votes

# Answer
You can use an image.

Each pixel will be a tile and each 32bit color will encode several values like alpha=0 means impassible. Then you can use any image editor that allows you to save in a lossless format and choose the exact color values.
> 1 votes

# Answer
Use tile editor to create the map. Normally those allow you to export the map in some format. Then create map loader for that map, that reads the exported file and create object from it, to your game.

If you have to use ascii, split those to sections so that "first town" would be saved to txt file "firstTown.txt" and that would contain the number-to-tile thingie. Then just load whatever file you need and consume it.

Examplefile.txt

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

```

---

This is example structure, that could be loaded from file. Layer1 is the base tile and layer2 would be trees, rocks and other stuff that should be drawn on top.

```
int[,] layer1 = new int[5,5]{
    {1,1,1,1,1},
    {1,2,2,2,1},
    {1,2,3,2,1},
    {1,2,3,2,1},
    {1,2,3,2,1}
}
int[,] layer2 = new int[5,5]{
    {0,0,0,0,0},
    {0,0,4,0,0},
    {0,4,0,0,0},
    {0,0,0,0,0},
    {0,4,0,0,0}
}

```

So, don't hardcode that map to your source files, edit map with editor, load it, make runtime changes if necessary. Actual tiles could be saved to "two dimensional array" that is int\[,\] and it could contain number that is mapped to certain tile image. For example number 1 could be grass and 1337 could be tiny rock.

---

Tiled ( IMHO the best too for this job)

Community wiki answer - List of tools for mapping
> 1 votes

---
Tags: 2d, game-design
---


title: Faster 2D Collision detection

text:
# Question
Title: Faster 2D Collision detection
Recently I've been working on a fast-paced 2d shooter and I came across a mighty problem. Collision detection. Sure, it is working, but it is very slow. My goal is: Have lots of enemies on screen and have them to not touch each other. All of the enemies are chasing the player entity. Most of them have the same speed so sooner or later they all end up taking the same space while chasing the player. This really drops the fun factor since, for the player, it looks like you are being chased by one enemy only. To prevent them to take the same space I added a collision detection (a very basic 2D detection, the only method I know of) which is.

```
Enemy class update method
    Loop through all enemies (continue; if the loop points at this object)
        If enemy object intersects with this object
            Push enemy object away from this enemy object

```

This works fine. As long as I only have \<200 enemy entities that is. When I get closer to 300-350 enemy entities my frame rate begins to drop heavily. First I thought it was bad rendering so I removed their draw call. This did not help at all so of course I realised it was the update method. The only heavy part in their update method is this each-enemy-loops-through-every-enemy part. When I get closer to 300 enemies the game does a 90000 (300x300) step itteration. My my~

I'm sure there must be another way to aproach this collision detection. Though I have no idea how. The pages I find is about how to actually do the collision between two objects or how to check collision between an object and a tile. I already know those two things.

tl;dr? How do I aproach collision detection between LOTS of entities?

Quick edit: If it is to any help, I'm using C# XNA.

# Answer
You already hit your problem right on the head, you are having every entity check against every other entity. What you will want is some type of 'Level of Detail' system (its pretty much a very simple scene graph, you are just using it for things other than rendering :)) where possible collision candidates are better selected.

I generally do three collections for systems like this. And when you are talking about the number of entities you are aiming to have you might even need to go with a full blown scene graph for this as the tracking data (3 lists per entity with an entry for every other entity) can quickly get out of control.

Basically though you have three lists. The first one should be a very small list of entities that you are going to check with interactions every frame. You determine this because they are within X range of the entity in question. As mentioned the point of this list is to contain every entity that can reasonably collide with another this frame.

The next list are ones that would be in a buffer range that Could move into range of the entity with out too much effort.. We will call this range X * 1.5 just for sake of argument. This is a time sliced list where you will only update a handful of them per frame but ensure that you are going through them fast enough to keep up appearances of things working smoothly.

The third list is the 'everything else' list and a way to avoid having this one might be worth while (Scanning the entire entity list and maybe checking to see if its in one of the other lists before progressing maybe? Depending on list sizes this might work, or it might make things a lot worse.) Objects in this list get checked least of all as it should definitely take more than a few frames to be placed into one of the other two lists.

What you will also need to do to maintain this is when you are doing the collision tests, make sure you update which list the entities are in. Ones that move out of range should be downgraded and likewise ones that move closer should be upgraded into a more actively checked list.

Assuming you are keeping things simple enough this should suit your needs. If you can tac in extra information to an existing rendering scene graph (assuming you have one) so you can query it to get a list of entities that are reasonably within range that would be even better as that is the entire point of a scene graph anyways (fast access to a list of relevant data based on a position). This would just potentially take more work to do and you should always consider what you need to do vs what you should practically do.

Hope this helps.
> 11 votes

# Answer
You have to handle collisions with a sorted data structure, so you can have n\*log(n) times instead of the terrible n^2. And n\*log(n) is almost linear as you might know. One (classical) example is a quadtree, there's a quite simple and well written tutorial here, with graphics and code (Java) :

http://gamedev.tutsplus.com/tutorials/implementation/quick-tip-use-quadtrees-to-detect-likely-collisions-in-2d-space/

Rq : it is quite easy to find an implementation for QuadTrees in any language. Still, you have to have to think about the right 'granularity' for the tree, and the bigger the tree size, the more we have entities that does not fit inside a node.
Rq 2 : since your space partitioning is done for collision detection only, you have perfect freedom to divide space as you like. For instance, i would not divide into four egal parts but rather i would use the baricenter of current level entities as a center for the new divide. 1) the algorithm is still n\*log(n), 2) you loose the possibility to 'rebuild' the scene out of the tree -but you don't care- and 3) you have a much more balanced tree, less overhead.
Rq3 : Once you have your tree, a 'collision' between the screen and the entities give you... the visible entities !! in a time more like log(n), so why not if n is big ? (worst case is obviously a time in n for this approach.)
> 6 votes

# Answer
binary space partition tree, quadtree, octree(for 3D) are possible trees you can generate (or maintain, if you're ambitious) at every update call for every object you want collision to apply.
> 0 votes

# Answer
I am quite naive when talk comes about quad or oct tree. But I think that this method should do:

You will need to modify the player structure/class. Add an array/vector of pointers to other player structure.

Every second check distance between each two players. If it is so low that it is possible to reach within 1 sec then add that player's pointer to current player's collision array.

Now only check the collision between players in each others list.
> 0 votes

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


title: Libgdx getting screen size

text:
# Question
Title: Libgdx getting screen size
I'm working on libgdx project. I basically recreate my game which I coded in xna to make it available for android. Here's the problem android has many screen resolutions, and I want to know how to get them.

i tried `Gdx.graphics.getWidth()` or `getHeight()` but it gives me null pointer exceptions.

# Answer
```
camera = new OrthographicCamera();
camera.setToOrtho(false,800,400);

```

Above code will draw everything in your game on 800\*400 virtual screen (in pixel) and fit, stretch, fill etc (see viewports ) on device's screen, independent of device screen size.

https://github.com/libgdx/libgdx/wiki/Orthographic-camera

https://github.com/libgdx/libgdx/wiki/Viewports
> 3 votes

# Answer
once there's a valid screen loaded Gdx.graphics must have a valid width and height defined, i think you're just asking for something null that's not related

i.e. float\[\] size; size\[0\] = Gdx.graphics.getWidth(); ...

which it will give you a nice NPE
> 3 votes

# Answer
You dont need to specify android screen fix size if you want you Libgdx project on all android Devices. I have test this. Just specify screen size that you can get from Gdx.graphics.getWidth() and also for Height. You can give some fix value to Camera.. Test it on different android devices and this will work same on all.
> 1 votes

---
Tags: libgdx, screen
---


title: Collision detection using gluunproject

text:
# Question
Title: Collision detection using gluunproject
I recently came across the game turbo tunnel. I want to make a similar game.

only thing that stands in my way is the collision detection. I first thought of learning plane line collision detection. But I didn't understand that stuff as I am too small(11th grade). I know gluunproject that uses coordinates on screen to world coordinates.

Things I thought about collision detection: -

1. getting a physics library. (But I am not sure how do I use bullet).
2. using box collision. (This solution may not work for irregular shaped doors) .
3. third method is given below:-

1) render the whole scene by plane's view.(no lightning, no textures)

2) get the depth buffer at pixel at centre of screen.

3) use gluUnproject for getting realworld coordinates of centre pixel. Let's say this point M.

4) if the distance between plane and M is less than certain value then aeroplane blasts off.

5) clear buffer bits and re render the scene with textures and lightning.

The third method is my idea. I am not sure if it is good to render the scene 2 times. But since only one object requires collision detection it may be a choice for me.

I am asking **is using 3rd method to check for collision is good idea?** if not So I should think something other.

# Answer
> 0 votes
When I made my first game as a kid I didn't know trigonometry but wanted my player to turn and move freely in a plane, so I used a method that drew an arc onto the backbuffer (I also didn't know what to use the backbuffer for) which returned at what point the last pixel was drawn at, then I knew where to position my player on the front buffer.

In short, your third option would probably work just fine, you don't have to worry about drawing extra frames, most games today draw the screen multiple times for different 3D effects and still manage to get 60 fps or more. Don't worry about it until you see your game performance drop. And personally I think experimenting and playing around with things like you are doing is one of the best way to learn.

Your second option would work too, you just have to make each object you want to check collisions for have a list of collision boxes instead of a single one, this way you can have complex shapes like walls with holes in them simply by only putting boxes where there is a wall to collide with, leaving gaps where there should be.

The first option is a little overkill, physics engines work well but they are intended for having objects flying/rolling/falling freely, without being directly moved. They can certainly be used for collisions as well but unless you use the other features you won't gain much by using it.

Line and plane intersections would, again, work just fine. I'm not sure how much math you have learned yet though, but this video explains it fairly well as long as you know vectors and programming variables.

---
Tags: collision-detection
---


# Question
Title: Should I update VAO when I update a VBO?
My VAO/VBO/IBO work fine on iPad and other devices on Android excepted two (A Samsung galaxy S4 and a Sony Xperia S).

A problem is present when I start my application on this devices, every elements move everywhere and start to blink on each frame, the problem is present on every element updated during the simulation.

I have a SpriteRenderer who share a VBO, so I need to update this VBO on each frame for each sprite (change color, uvs, …).

The visual glitch is not present on static element (like text).

**So my question his:**

* Did I have to do something with my VAO on each frame?

Here is what I've got:

```
Init part:

 - bind vao
     -> Bind vbo
     -> Bind ibo
 - unbind vao

Rendering part:

for( sprites )
{
     // Update (Need to bind VAO here?)
     bind vbo (lock)
     update vbo data
     unbind vbo (unlock + bind)

     // Draw.
     bind vao
     drawElement
     unbind vao
}

```

Thanks!

# Answer
> 0 votes
A Vertex Array Object (VAO) is an object which contains one or more Vertex Buffer Objects and is designed to store the information for a complete rendered object.

You can think of it as being just a sort of parent to you VBO's, which are what store the real data. Binding a VAO just makes it easy for you, otherwise you would have to bind the buffers associated with that VAO separately. A VAO's job is to just remember which VBO's are to be bound when it itself is bound.

In your case, I don't think not binding the VAO is causing any problems. The problem might be you continuously locking and unlocking the buffer. Consider that.

---
Tags: opengl, opengl-es2
---


# Question
Title: Client Tells Server What Gamestate Data to Send Back
I'm just stepping into the world of MMORPGs and how they function, so assume I know very little.

in a game, a client doesn't see everything that the server does. For example, the client can't see through mountains, walls, etc. So why send them data that's not relevant?

My question is: \- If the Client was designed to tell the server what gamestate data would be relevant to them, then the server sent back only what was relevant, could you minimize lag / amount of data downloaded?

You would have to find a way for the server to discern what data the client needed, maybe this is where it becomes inefficient?

Thanks for your time!

# Answer
First of, don't ask client "what is your interest", that equal to just send them the knowledge about every object. Instead, when server updates the world, check where the player is, decide "area of interest" for that client, gather data for it and send it.

In very simple example, that is no where fast enough for object amounts that MMORPG's have, it could go something like this:

```
// List of all objects in the world
List<MyObject> allWorldObjects;

// Max distance to objects, which data is sent to client
int clientInterestDistance

updateClientWorld(Client client)
{
    List<MyObject> clientInterestObjects;
    for(MyObject obj in allWorldObjects)
    {
        if(DistanceBetweenClientAndObject(client,obj) < clientInterestDistance)
        {
            if(obj.IsHidden)
                continue;
            if(!CheckLineOfSight(client,obj))
                continue;

            // ETC

            clientInterestObjects.add(obj)

        }
    }
    sendWorldUpdateMessage(client,clientInterestObjects);
}

```

So, in this example, we update would gather client data, making it as compact as we can so that we don't send huge amounts of data AND to make it little harder to cheat. Obviously List is not the best way to go, if object count moves up to hundreds or thousands. Preferable, you should always keep objects categorized so, that they are easy to fetch as a group. Meaning, that when you update object, you check position and add it to somekind of collection that helps you to get objects around coordinates x,y. Thus, avoiding you the performance problems, when looping 10000 objects for each client, 20 times in second.
> 1 votes

# Answer
The client and server have two different notions of visibility, by the way.

The sever is generally going to avoid visibility checks using actual geometry and at the most naive level may not implement visibility at all. In past work, I have re-used parts of the graphics engine's dynamic PVS system to implement agent (AI) pathing on the server, however position update filtering is not something that would benefit from that sort of complexity. More than likely, relevant game state updates will be established based on a simpler metric such as distance.

EverQuest sends position updates for every PC and NPC in a zone, but it varies the frequency of these updates for mobs that are distant from the player. In EverQuest, the client will resort to delta prediction much of the time to figure out where distant mobs are and that is usually adequate unless the player is moving extremely fast (e.g. on a boat). Even then, there is next to no gameplay that goes on at hyper speed so the lack of state updates will only affect rendering. So distance turns out to be an extraordinarily simple and effective metric.

As a point of trivia, EverQuest did not always work that way. For about the first year of its existence it sent out updates in equal frequency regardless where the player was in relation to everything else. This made cheating programs like ShowEQ (which displayed a radar with every mob in the zone) extremely effective, and also did not balance bandwidth effectively.
> 0 votes

---
Tags: models, optimization, client-server, game-state, lag
---


# Question
Title: How can I store tile maps as PNG images?
I want to let players of my top-down game save, load and share worlds as PNG images. How do I read the colors in a PNG file or change them?

I imagine something like this:

```
BufferedImage mapImg = ImageLoader.loadImage(path);

// (then, later)

for(x = 0; x < mapImg.width; x++) {
    for(y = 0; y < mapImg.height; y++) {
        // Look up the color at this position
    }
}

```

Here is my ImageLoader class:

```
public class ImageLoader {

    public static BufferedImage loadImage(String path) {
            try {
                return ImageIO.read(ImageLoader.class.getResource(path));
            } catch (IOException e) {
                e.printStackTrace();
                 System.exit(1);
            }
            return null;
    }
}

```

# Answer
> 1 votes
That is right idea for reading/writing images but you'll want to get your "ImageLoader" class from a library, which will then give you a regular bitmap in memory to work with. The layout of that bitmap class is going to depend on the library you use.

To see why, or what you need to handle if you want to write your own, see the W3C PNG Specification.

---
Tags: java, tilemap, image, file-format
---


# Question
Title: Skyrim Creation Kit - Call External DLL Method
I've been developing for a few years now but I'm fairly new to creating Skyrim mods. I'm wanting to build a custom DLL and call the methods from scripts in Skyrim. Can I do this and if so, how do I import the DLL and make a call to one of it's methods?

# Answer
> 1 votes
The Creation Kit doesn't support external libraries, which is great from a mod safety perspective.

There has been attempts to extend the editor by hooking the process via a proxy d3d9.dll, resulting in products like the Skyrim Script Extender. You may find that the script language that SKSE exposes is sufficient to do what you want to do, otherwise you may clone their work and inject your own code of interest into the process.

---
Tags: c#, modding, skyrim-modding
---


# Question
Title: How to change chance of spawn based on distance?
I am trying to make a cellular automate cave but want to keep the middle empty.

How should I change the chance based on the distance from the middle?

I don't want to completely deny it just want a small enough chance to keep it almost empty.

# Answer
> 1 votes
You need to think along the lines of uneven distribution. For example squaring the random value:

```
if Sqr(Random) > (1 - NormalizedDistanceFromCenter) then AddMonster

```

will give you a nice squared distribution:

```
Distance | Chance
---------|------
0        | 0%
0.2      | 11%
0.4      | 23%
0.6      | 37%
0.8      | 55%
0.9      | 69%
1.0      | 100%

```

---
Tags: procedural-generation, random
---


title: Pre-calculating skeletal animation data

text:
# Question
Title: Pre-calculating skeletal animation data
I'm working on skeletal animation and so far I've got the skeleton drawn with interpolated animation working (just on the cpu still). I was thinking about changing my file format for my skeleton and animations to have fully calculated matrices stored.

Right now I calculate my matrices recursively by multiplying the parent's world matrix(absolute matrix) by the childs joint matrix, same thing with each frame of animation. I think it would be a good idea to just export all of this pre-calculated to my model format so I could just send these matrices to the shader for skinning.

Is there any reason I should not do this?

Edit: Calculating the matrices is negligible by itself on a rather small skeleton anyway but is there any reason I should calculate them at run time or just pre-calculate in my file format? I think this sums up my question better.

# Answer
> 2 votes
This seems like an optimization question. As such the answer, as always is to profile it. If generating the matrices doesn't take too much time on the fly, then it is simply easier to do on the fly, as you don't have to write and export/import of matrices, and add it to your file format.

And perhaps you could simply use other file formats natively and not have to bake your resources.

On the other hand if your application is very very animation intensive, it may be worth it to move the matrix calculation to the baking stage.(Tough I would seriously doubt that.)

In the end this looks like a premature optimization to me. If you are interested, then you should profile it first, and if the results say you spend too much time calculating matrices, then do it.

PS: If you do profile it, don't forget to post the results.

---

**EDIT:**

To answer your comments, there is no reason to precalculate the matrices. But I see no problem in doing so. But if you also want to interpolate... It doesn't look straightforward. Maybe you could store a matrix for every frame but that would be quite a lot of data.

Well To expand on this here is some calculation: Assuming 4x4 matrices of float(4byte) data. Lets assume you have 16 bones in your model. And you want 200 animation frames. And you want interpolation so you do 2000 animation frames instead(10 subframes)(Assuming a bad case scenario). This would require 2000kB of memory/disk space.

Thats not a lot.(Except if you are doing skinning on GPU, then if you consider 100 different models, this is 200MB animation data, which is quite significant.) But you could just easily calculate it on the fly with even more accuracy, and don't need to have larger files.

And mainly: write, test and maintain the extra code to do it the other way around.

So the more I think about it the less feasible reasonable it seems.

---
Tags: animation, matrix, skeletal-animation, skinning
---


title: How many directional lights in Unity

text:
# Question
Title: How many directional lights in Unity
In Unity, how many directional lights can be active at once? 1, 2, 4, or 8? I thought 2, but I have searched and cannot confirm.

# Answer
> 1 votes
here there's a general answer to the question

http://answers.unity3d.com/questions/434512/limit-to-number-of-lights.html

"Pixel Light Count, which is settable in Edit-\>ProjectSettings-\>Quality.

..there is a "priority" variable on the lights which determines which show and which hide. The highest priority also become Pixel-shaded lights. And I'm assuming the closest get higher priority if they match."

plus

http://answers.unity3d.com/questions/27212/lighting-in-unity-indie-limited.html

" Use vertex lights (max 8 per object, unlimited per scene) or increase the number of pixel lights in the quality settings (max 8 total)."

plus

http://answers.unity3d.com/questions/437215/is-there-a-maximum-number-of-lights.html

"The maximum number of lights used on a single renderer depends on the shader being used and also on the quality settings for the number of point lights: Edit \> Project Settings \> Quality. Normally you don't allow more than 4 to affect an object:"

---
Tags: unity
---


# Question
Title: How can I make player move on array of GameObjects in Unity?
I am making a board game where the players hit a dice and move on an array of GameObjects according to the number they got.

So I declared a Gameobject array and added to it all the objects I need.

The problem is that when the player moves, he is going immediately to the target.

What I want is to make the player move through the Gameobject array, object by object, till it reaches the target(which is defined according to the dice number).

Here is what I am trying (using C#):

```
for(int i=0;i<spaces.Length;i++)
{
    transform.position = Vector3.MoveTowards(transform.position,
    spaces[currentPosition+diceResult].transform.position,Time.deltaTime / smooth );
}

```

**spaces** is the name of GameObject\[\] array.

**currentPosition** is the position of player before hitting the dice.

**diceResult** is the number he got in the dice.

---

**EDIT :**

I solved it!

Here is how it worked:

```
 if (index < spaces.Length)
 {
       transform.position = Vector3.MoveTowards(transform.position,
       spaces[index].transform.position, Time.deltaTime *smooth);

       //If we've reached the destination, move to the next one
       if (transform.position == spaces[index].transform.position)
            index++;
 }

```

# Answer
the problem with your "for" code , that I think you placed inside the Update(), is that it get executed in one update cicle. In Unity you must think the Update as a 'frame' execution. Plus, that for seems useles. Where do you use the "i" variable?

So you must do something like this into the Update(), (I missed the starting and end management)

```
//small dist is a float value greater of 0 but not to big that you must initialize in the //Start()
if ((transform.position - spaces[currentPosition+i].position).magnitude < smalDist)
{
 // I reached next element

 if (i==diceResult){
   //reached destination
   // STOp The movement
 }
 i++;
 transform.position = Vector3.MoveTowards(transform.position,
    spaces[currentPosition+i].transform.position,Time.deltaTime / smooth );
}

```
> 0 votes

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


# Question
Title: Estimate the time it takes for an object to travel from point A to point B
I have an object with vec2 position, velocity, and destination with 2 variables maxspeed and acceleration. In each step, its position is calculated as follows:

```
vec2 desiredVel = destination - position;

var dist = desiredVel.length;
if (2 * dist * acceleration < currentSpeed*currentSpeed)
    desiredVel.zero();

vec2 steering = desiredVel - velocity;
steering.setLength(acceleration);

velocity += steering * dt;
velocity.truncate(maxspeed);
currentSpeed = velocity.length();

position += velocity * dt;

```

Basically the object will accelerate to its maxspeed towards destination, then maintains speed until the a certain distance to destination. At that distance, the object will decelerate at the -max acceleration rate so that it stops approximately to the destination point.

My question is that if I have an object with an initial velocity and I set a destination point, how can I estimate the time it will take to reach the destination point? Assuming its maxspeed and max acceleration doesn't change and no other force/acceleration applies to the object in the path.

# Answer
Distance `d` is the *integral* of velocity `v` (calculus). Velocity `v` is the integral of acceleration `a`. If you start at velocity `s`, and you travel for time `t`, then distance will be `d = s * t + 1/2 * a * t^2`.

You will have two cases.

1. If the object does *not* reach maxspeed, then you'll have one part where you're accelerating and one part when you're decelerating. You'll have to solve the equations for the velocity you reach, and then from velocity you can tell the first part takes time (velocity-initialspeed)/acceleration and the second part times velocity/acceleration. I believe it ends up being velocity = sqrt((totaldistance * acceleration + initialspeed^2) / 2) but I haven't double checked this.
2. If the object *does* reach maxspeed, then you'll have three parts. For the third part, from maxspeed to 0, the time it takes will be maxspeed/acceleration, and from the time you can calculate the distance traveled. For the first part, from initialspeed to maxspeed, the time it takes will be (maxspeed-initialspeed)/acceleration, and from the time you can calculate the distance traveled. The second part will have to travel the remaining distance, so the time it takes will be (totaldistance-firstdistance-thirddistance)/maxspeed.

I've not tested this - sorry. :-(
> 4 votes

---
Tags: mathematics, physics, vector
---


# Question
Title: Matrix Rotation Only Works On one Axis At A Time
I have this function in my vertex shader. It makes a transformation matix out of a transformation matrix, a rotation and an intensity. It works just fine when setting the rotation of one of the axis (Vector3f rotation = new Vector3f(90, 0, 0);), but when rotating it on multible axis it gives a strange result, that is basicly rotated, but the higher the rotation, the flatter it gets and the model inverts inverts itself if it's too high. this is the function:

```
void createTransform(in mat4 bone,in vec3 bone_rotation,in float intensity, out mat4 transform)
{
//norm is the identity matrix.
transform = norm;

//rotation
vec3 rot = vec3(bone_rotation.x * intensity, bone_rotation.y * intensity, bone_rotation.z * intensity);
mat4 rotation = norm;

transform[1][1] = 1+cos(rot.x);
transform[2][1] = -sin(rot.x);
transform[1][2] = sin(rot.x);
transform[2][2] = 1+cos(rot.x);

transform[0][0] = cos(rot.y);
transform[2][0] = sin(rot.y);
transform[0][2] = -sin(rot.y);
transform[2][2] = cos(rot.y);

transform[0][0] = cos(rot.z);
transform[1][0] = -sin(rot.z);
transform[0][1] = sin(rot.z);
transform[1][1] = cos(rot.z);

//translation
transform[3][0] += bone[3][0] * intensity;
transform[3][1] += bone[3][1] * intensity;
transform[3][2] += bone[3][2] * intensity;

//scale
transform[0][0] = 1 + (bone[0][0] - 1) * intensity;
transform[1][1] = 1 + (bone[1][1] - 1) * intensity;
transform[2][2] = 1 + (bone[2][2] - 1) * intensity;

}

```

# Answer
> 1 votes
This is a plain old bug, you're reassigning different values to the same spots, like

```
transform[1][1] = 1+cos(rot.x);
...
transform[1][1] = cos(rot.z);

```

What you need to do is combine the rotations in the order you want them applied, like

```
transformX[][]... assigned only from rot.x
transformY[][]... assigned only from rot.y
transformZ[][]... assigned only from rot.z
transform = transformX * transformY * transformZ

```

You could pack this down into fewer assignments, but that's the concept.

---
Tags: rotation, matrix, axis
---


title: Level loading philosophy in MMO games

text:
# Question
Title: Level loading philosophy in MMO games
I've been working on project for quite a while, and I've returned to dilemma about level loading. The problem is i trust the client with it's local level loading, when it's done loading it tells the server to join it to server room data stream and server start to send data.

My current setup

1. Client logs in, on login server sends the characters.
2. Client chooses the character and start to load level locally.
3. When client scene done loading, it request to add to room.
4. Client receives the data he needs.

I fear that user could hack the client and actually load other scene, that would result in players and characters going through props and models, it could also be an exploit to see hidden data and items.

Instead, after server sends the chosen character it could "wait" for user to send response that level has finished loading. After that, server joins the character to room and send data to the user. That way client doesn't know anything about rooms or it's names.

Any suggestions?

# Answer
> 1 votes
What you have described is roughly how we did it in Reclamation (Underlight sequel). The client sent a room change request and started loading the level, but before the client was allowed to move around after loading finished there was an acknowledgment required from the server.

The game had a major PvP element to it, so this syn/ack system was as much to prevent cheating as it was to make sure other players in the vicinity were informed about the new player entering the area *before* they were allowed to be attacked. Players in the room that had not yet acknowledged the new player's entry were invulnerable (invisible, actually) so as not to give the entering player an unfair advantage.

The server also had a graph of connectivity between all rooms in the game. It knew trivially if a compromised client tried to jump to an invalid room. A system that combines both of these things should take care of the problems you have described.

---
Tags: mmo, loading, scene
---


# Question
Title: LibGDX/Java - Trying to find the vector from one object to another
I want to add springs in my game that work like the ones in sonic - i.e. if you can't get over an obstacle you have to hit a spring which sends the main character flying towards another spring that gets him over that obstacle. I drew a little diagram below to demonstrate what I mean (yellow arrows represent the direction the player will go towards and the red - are the springs).

In my Spring class I have created a method:

```
//The detection area (blue rectangle in the diagram)
public Rectangle broadPhaseDetection() {
        broadPhaseRectangle = new Rectangle(getxPos() - broadPhaseLength, getyPos(),
        broadPhaseLength, broadPhaseLength);
        return broadPhaseRectangle;
    }

```

If the Player collides with a Spring, I check to see if there's ANOTHER Spring within the blue area and if there is - calculate the vector that takes you towards that spring and send the player in that direction.

This seems like a very simple concept which has probably been done loads of times before, but I couldn't find any good examples online for some reason. Does anybody know how I can get the vector I need?

Any insight is highly appreciated, thanks.

# Answer
> 2 votes
Calculating the vector that points from a spring at point A = (x0, y0) to a spring at point B = (x1, y1) is simply:

v = (x1 - x0, y1 - y0)

Assuming no other forces acting on the player, then changing the player's velocity to some scalar multiple of v when they hit spring A would direct them to spring B.

If another force like gravity is involved, then, depending on the type of movement you're looking for, you might want to disable gravity for the duration of travel from spring A to B, or adjust their new velocity vector to account for gravity.

---
Tags: java, 2d, libgdx, graphics, vector
---


title: RayCast method always outputting False

text:
# Question
Title: RayCast method always outputting False
I am having trouble executing a raycast to check if there is anything between the player sprite and a second sprite. This is my code :

```
    void Start () {

        play1 = GameObject.Find("player");
        game1 = GameObject.Find("lightidle_0");
    }

    // Update is called once per frame
    void Update () {

        Vector3 playpos = play1.transform.position;
        Vector3 gamepos = game1.transform.position;
        Vector3 defvector = new Vector3 (1, 0, 0);

        Ray playray= new Ray (playpos, defvector);

        float distance = playpos.x - gamepos.x;

        if (distance > 0) {
            Debug.Log (Physics.Raycast(playray,distance));
        }
        else {  defvector = -defvector;
Debug.Log (Physics.Raycast(playray,distance));
}

```

So supposedly, if there is anything between both objects, Raycast should return true. But it is always stuck on false, I have debugged, and tried everything, its value never changes, no matter where both objects are located, I added 2 huge colliders on both sides of the scene and it still outputs false.

I also added a `Debug.DrawRay (playpos, defvector * distance);` but the ray isn't drawn at all, so it means that is the reason of the error, but why? I can't figure it out.

# Answer
> 0 votes
I don't quite know what was the problem here, but as a fix i changed the `Physics.Raycast` command to

```
Physics2D.Linecast(startposition, endposition);

```

This fixed the problem. I also made 2 new objects childs of the player, and the npc, and fixed it all up.

Reference to how I did it all in this video : https://www.youtube.com/watch?v=cJj7-Sy03HQ

# Answer
> -1 votes
tried:

```
Physics.Raycast(playpos ,playpos - gamepos,  (playpos - gamepos).magnitude)

```

or

```
Physics.Raycast(playpos ,gamepos-playpos ,  (gamepos -playpos ).magnitude)

```

?

plus keep in mind: "Raycasts will not detect colliders for which the raycast origin is inside the collider"

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


# Question
Title: AStar for isometric game with overlapping walkable areas
We're developing an isometric game that so far has had a single ground level (y = 0) for the avatar to walk on. Pathfinding for this can be solved with a relatively simple 2D AStar tile map.

We're now looking to add objects in the world that can elevate the avatar. There will be overlapping walkable areas, thus creating a problem of pathfinding in 3D space. These objects are distributed sparsely in the room, so I want to avoid keeping an entire 3D map of the room for a 3D AStar implementation. I've attached screenshots to illustrate.

What is the best way to accomplish this?

# Answer
> 2 votes
It depends. If the elevated surfaces could lead to other rooms, it could get very complicated unless the A\* optimization function you are running is tailored with information specific to that room layout, it may need to search every possible path (like BFS).

How to handle this issue:

## Complexity:

You need a meta graph that represents rooms; i.e to get from room A to room D I go through A =\> E =\> B =\> D. Each room has a few exit nodes, so instead of searching the whole map, I first search the meta graph that represents each room as a single node and then inside each room, I only need to search from the entrance to the closest relevant exit.

## Sparsity:

To represent the sparse 3d matrix of surfaces, use a hash table, every elevated surface in a room will have a vector key position in the hash (x, y, z). Each surface will be able to access any other surface in (x +/- 1, y +/- 1, z +/-1). Since you separated the world into rooms or sections, the A\* graph hash for each room will be reasonably sized.

# Answer
> 0 votes
As long as there are no overlapping walkable areas, you can keep 2D A\*. You just need to add a height info to tiles and make a rule, that character can walk from tile to tile if height difference is less than X.

If there are overlapping areas you need to go *kind of 3D*. You can get away with several separate layers for your room, where each layer contains info about walkable areas on given height. Then to use A\* you need to check not only direct neighbors of the tile, but also tiles in +/-1 layer above/below.

# Answer
> 0 votes
I can suggest to transform your "2d space with heigth" into a graph. Them use an A\* on that graph . Example each walkable tile become a graph "node", and then add an "arc" for each "adiacent tiles" (even at different heigths)

# Answer
> 0 votes
I would prefer to reuse the data structure you already have. So basically a 2D grid that is the floor with a bunch of entities that are put over it.

A\* actually works over a graph, so the trick is to make a decent abstract programming interface (API) for a graph. 2D or 3D grid A\* is a trick by implicitly converting a grid into a graph with the shape of a *lattice graph*, where the nodes correspond to the cases of the grid and where the edges connect neighbouring cases of that grid.

In your modified graph,

* Like a lattice graph, each case of the floor is a node, connected to its four neighbours *"by default"*.
* However, each entity/object is also a node, connected to neighbour entities provided they have sufficient height so a character can walk across.
* A case or entity with another entity stacked right on top of it have its connections removed (because you cannot walk onto it since you cannot go through the entity stacked right over it). A node without any connections is a pointless as no node on the graph in the computation of A\*, so you can keep it alive (and possibly reconnect it later).
* ... *(Depending on your game rules, you may wish to alter this interface, like adding weight on edges, ... )*

Now, all you have to do is to implement A\*, but not by following regular 2D or 3D neighbours to travel, but by following *connections* (a.k.a *edges*). Two nodes are neighbours if and only if they are connected. You may wish to learn how to do A\* on a general graph structure.

---
Tags: path-finding, isometric, layers
---


# Question
Title: Unity5 TextAsset not functioning in WebPlayer
# Preface

I am working on a 2D Platformer in Unity5 utilizing TileMap techniques. I have a working system to read "Room Tile Data" from `JSON` files with the Unity `TextAsset` Class and the Newtonsoft JSON.Net library. My level files are within a folder inside of the Resources Directory and the `Resources.Load` is working on the json files with and without their `.json` file extension.

# Code

```
FileName = "MapFiles/room_three";
TextAsset mapDataFile = Resources.Load(FileName) as TextAsset;
string text = mapDataFile.text;
Map thisLevel = new Map();
thisLevel = JsonConvert.DeserializeObject<Map>(text);

```

# Problem

This works in the standalone builds for win + mac as well as in the Unity Editor. But a unity Web player Build entirely fails to load the TextAsset and my characters are left falling endlessly.

The only error I receive is a reference to `mapDataFile.text` being null. Leading me to believe my `TextAsset` is failing to load from the web player. The documentation says nothing I could find about using the `TextAsset` differently in the web player. Is there a different technique I must use to solve this issue for the Web Player? I'm certain I could change things to grab files on the web using `WWW`, but I want this data to be loaded from within the application.

# Thanks in advance!

---

# (edit) Updates:

* Created a public property for the `TextAsset` and drag dropped the file into it. Still fails to load from the web player and worked in the standalones + editor. Assuming this means we can rule out `Resources.Load` as our culprit.
* Tried the same functionality with `Resources.LoadAssetAtPath` which was only intended for use in the editor. When running this in the web player I received a similar verbose message. Nothing like this appears with `Resources.Load`
* Updated "sample code" containing `FilePath` variable with file path string value being used in my application
* Tested web player in FireFox / Chrome / Safari on Mac OSX 10.8 Yosemite
* Pursued a potential cause found here: LINK TO ARTICLE I copied this technique implementing a scene 0 menu and the problem persisted with a weird flickering in Scene 0
* Deleted Project "Library", "Temp" & "Project Settings" directories and let them be regenerated in conjunction with a few of these other attempts for good measure. Also removed / regenerated user preferences
* Ran a "Reimport All" Assets by unity, Unsuccessful.
* For posterity, I tried "Turning it Off and On Again" (Rebooting my Machine)
* Uninstalled and Reinstalled newest Unity WebPlayer, unsuccessful.

# Answer
> 1 votes
I tried to reproduce the situation, but it works regardless of what I do. Try to create a new playground project and repeat your situation, but stripped of irrelevant code and content.

P.S.: This should be a comment instead of an answer, but I don't have enough reputation here yet.

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


# Question
Title: How can I implement triple buffering using Direct3D 9?
I am creating an application using Direct3D 9. I want to implement triple buffering with vsync. I can successfully create a graphics device object with 2 back buffers. How do I know which buffer to draw to?

EDIT:

Here is how I retrieve a pointer to the back buffer onto which I will draw using a deferred shading technique:

```
// graphics device object
IDirect3DDevice9 *pd3dDevice = GetDevice();

// back buffer pointer
IDirect3DSurface9 *pBackBuffer = null;

// get pointer to back buffer
pd3dDevice->GetBackBuffer(0, 1, D3DBACKBUFFER_TYPE_MONO, &pBackBuffer);

```

UPDATE: The application appears to run faster when I use a pointer to the first back buffer like so:

```
// graphics device object
IDirect3DDevice9 *pd3dDevice = GetDevice();

// back buffer pointer
IDirect3DSurface9 *pBackBuffer = null;

// get pointer to back buffer --- NOTICE THE Back Buffer Index parameter is now 0 ---
pd3dDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &pBackBuffer);

```

When using the back buffer at index 1 the frame rate falls to 30fps while using vsync. This produces artifacts and Horizontal Shearing. Using the back buffer at index 0 seems to be correct. When using this buffer the application presents a frame at the refresh rate of the monitor. Therefore in order to correctly implement triple buffering using Direct3D 9 you should draw to the back buffer at index 0.

# Answer
> 1 votes
> How do I know which buffer to draw to?

You don't. Direct3D will automatically manage this for you and correctly rotate the back buffers at Present time.

---
Tags: c#, c++, directx9, vsync, double-buffering
---


# Question
Title: How can I put my game into a cheap portable console?
I've seen some cheap gaming consoles on Amazon, and I was wondering if it would be terribly difficult to put my RPG Maker game on it. Basically, a while ago, the creator of a never-solidifying game called Bob's Game had this idea to invent a cheap little console for indie developers. It was going to be called the nD. Well, the project never went anywhere, but it has left me with the itch to package my game in a cheap little gaming machine. How can I go about this?

# Answer
> 4 votes
That depends entirely on which cheap gaming console it is and what system it runs. There are a few popular choices and people have made plenty of homebrew games for such platforms, so it is a possible, albeit difficult task.

No matter what option you go with though, **you will need to rewrite the game**. This is because I'm guessing you're using a Windows version of RPG Maker. There are versions of RPG Maker that are for other systems like SNES or DS but they are very different products.

These days cheap Chinese gaming consoles fall under the following categories:

* Some weird system with a hacked up emulator for consoles like NES, which can run little else even if you could get a hold of their SDK
* Some version of Linux, with a custom SDK / build chain
* Android-based system

This leads to the following options:

* Write an Android game, obviously only possible on an Android-based system. This is a little harder than it sounds though; chances are the hardware is based on an old Android phone running an ancient version of the OS like 1.6 or 2.1, so you will need to dig up an old version of the SDK. Performance will be poor, but depending on your game it may be acceptable. Quality varies a lot though; there are high-end Android devices that run very new versions of the OS, with enough performance to run most games on the Play store, but these won't be cheap either, as they are comparable to "proper" Android microconsoles like OUYA or Shield.
* Write a native game. This is only a realistic option if the console happens to have a publicly-available SDK, as a lot of these makers are only after a quick buck and don't bother nurturing a development community. You will probably use SDL, or some flavour of OpenGL if you're lucky. Other frameworks or engines are probably out of the question because they will need to be ported first, by an active developer community. Be prepared to deal with issues like broken floating point or dodgy device drivers.
* Write a console game, and played using the built-in emulator. The NES for example is surprisingly popular these days, with new (homebrew) games being released in recent years. Although this approach might have the best chance of success, writing games for old systems like NES will be much harder than other approaches, due to many limitations with the console, so it's not for the faint of heart.

---
Tags: console
---


# Question
Title: How do I destroy a Unity prefab when it goes off-screen?
I made an infinite path using `prefab.Path` moving in the negative x direction. I want to destroy the path clone once it goes offscreen.

My path move script is:

```
var Speed:float = 5;
var hasseen:boolean;
function Start () {
    rigidbody2D.velocity.x = -1 * Speed;
    hasseen=false;
}
function Update() {
    if(renderer.isVisible) {
        hasseen=true;
    }
    if(hasseen) {
        if(!renderer.isVisible) {
            Destroy(gameObject);
        }
    }
}

```

and my prefab script is this:

```
var path_pre:Transform;
var i:long = 0;
function Update() {
    if(i<1000000) {
        Instantiate(path_pre, Vector3(i*25, -3, 0), Quaternion.identity);
        i++;
    }
}

```

# Answer
> 0 votes
Create a game object with a box-collider which exactly covers your screen. Make the collider a trigger and attach a script to the object which implements the OnTriggerExit method. The documentation article for OnTriggerExit has an example which covers exactly this use-case:

```
function OnTriggerExit(other) {
    // Destroy everything that leaves the trigger
    Destroy(other.gameObject);
}

```

This example destroys all game objects which leave the screen. When you want to limit this only to specific objects, make it check the `other`'s name, tag or check if it has a specific component to identify it as an object it is supposed to destroy.

---
Tags: unity, viewport, visibility-determination
---


# Question
Title: Custom shadowmapping in Unity not working properly
To experiment with a certain technique, I'm implementing my own shadow mapping in Unity. I'm using a camera for the light "view", which is rendered to a RenderTexture after being post-processed with the following shader:

```
Shader "Custom/DepthGrayscale" {
  SubShader {
     Tags { "RenderType"="Opaque" }

     Pass{
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        #include "UnityCG.cginc"

        sampler2D _CameraDepthTexture;

        struct v2f {
           float4 pos : SV_POSITION;
           float4 scrPos:TEXCOORD1;
        };

        //Vertex Shader
        v2f vert (appdata_base v){
           v2f o;
           o.pos = mul (UNITY_MATRIX_MVP, v.vertex);
           o.scrPos=ComputeScreenPos(o.pos);
           //for some reason, the y position of the depth texture comes out inverted
           o.scrPos.y = 1 - o.scrPos.y;
           return o;
        }

        //Fragment Shader
        half4 frag (v2f i) : COLOR{
           float depthValue = tex2Dproj(_CameraDepthTexture, UNITY_PROJ_COORD(i.scrPos)).r;

           return fixed4(depthValue, 0.0, 0.0, 0.0);
        }
        ENDCG
     }
  }
  FallBack "Diffuse"

```

}

With a width and height of `2048` for the Render Texture and the color format `R Float` for 32-bit precision.

The objects in the scene then have the following shader that takes the `projection * view` matrix of the light and "depth" texture as input. (Basic shadow mapping with bias)

```
Shader "Tutorial/Display Normals" {
    Properties {
        _CameraTex ("Camera texture", 2D) = "white" {}
    }
    SubShader {
        Pass {

            CGPROGRAM

            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            uniform float4x4 lightMatrix;

            struct v2f {
                float4 pos : SV_POSITION;
                float3 worldPos : COLOR0;
                fixed3 color : COLOR1;
            };

            v2f vert (appdata_base v)
            {
                v2f o;
                o.pos = mul (UNITY_MATRIX_MVP, v.vertex);
                o.worldPos = v.vertex.xyz;
                o.color = v.normal * 0.5 + 0.5;
                return o;
            }

            uniform sampler2D _CameraTex;

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 coords = mul(lightMatrix, fixed4(i.worldPos, 1.0));
                coords /= coords.w;

                coords.x = (coords.x + 1.0) / 2.0;
                coords.y = (coords.y + 1.0) / 2.0;
                coords.z = (coords.z + 1.0) / 2.0;

                //return fixed4(coords.z, 0.0, 0.0, 1);
                float lightDepth = tex2D(_CameraTex, fixed2(coords.x, 1.0 - coords.y)).r;
                float depth = coords.z;

                if (depth < lightDepth + 0.005) {
                    return fixed4(1.0, 1.0, 1.0, 1.0);
                } else {
                    return fixed4(0.1, 0.1, 0.1, 1.0);
                }
            }
            ENDCG

        }
    }
}

```

The result of this is perfect with a plane and cube:

The red plane displays the shadow map and the camera represents the light.

However, when using a more complex model like Sibenik, the following happens:

When I move it slightly, the shadow on the plane is suddenly correct, but the shadow on the church model itself is still wrong:

What could be the problem?

# Answer
> 0 votes
I solved the problem by using the model matrix:

```
o.worldPos = mul(_Object2World, v.vertex).xyz;

```

---
Tags: unity, shaders, shadow-mapping, lighting
---


# Question
Title: Creating a 2d look sprite sheet and textures out of 3d models
I'm trying to make a 2d game (rpg top down), and I've got no 2d artists help me out making 2d characters and textures, but I have one who can make 3d stuff (using Blender and 3d Max), I was wondering if there's a way to make these 3d models look 2d so I can capture some poses to make a sprite sheet.

Is it possible to make 3d models look 2d?

Edit: Here are examples

Sly Crooper (Playstation 2 Game) http://static.gamesradar.com/images/mb/GamesRadar/us/Features/2009/02/Sneaky%20History%20of%20Stealth%20Games/Screens/slycooper3--article\_image.jpg

Legend Of Zelda Wind Waker: http://www.zeldadungeon.net/images/News/Folder/10-05-06/Screen1-Large.jpg

I wish for sucha similar art.

# Answer
> 1 votes
The first thing that comes to my mind would be to render your 3d graphics with a cel shader. I'm not too familiar with the technique, but basically, it makes your 3d models look cartoonish.

I think some game companies put a lot of effort in this kind of technique to really give a nice look to their game and they really make it part of the artistic process.

In any case, if you decide to go with that kind of technique, you'll have to work with your artists and give them tools to rapidly view the result of their work. You could do that with you writing the exporter/converter and giving it to them.

Another way you could get some results would be to render your models to images, then edit them manually in photoshop by applying filters. I know photoshop can be scripted so you could automate the process there.

---
Tags: 2d, 3d, art
---


title: Spherical Collision

text:
# Question
Title: Spherical Collision
I have a made spherical collision system which creates a major problem, the balls gets stuck to each other on high speed and sometime with low speed collisions. I researched a lot but I couldn't found a single useful information.

Here's the logic code.

```
DetectCol(ball1, ball2)
{
    float x1, y1, z1, x2, y2, z2;
    center(ball1, x1, y1, z1);
    center(ball2, x2, y2, z2);
    float colr = ball1.rad+ball2.rad;
    float dist = (((x2-x1)*(x2-x1))+((y2-y1)*(y2-y1))+((z2-z1)*(z2-z1)));
    if(dist <= (colr*colr)) return true;
    return false;
}

```

The balls gets stuck together for few milliseconds.

```
updater
{

loop (i) for all balls
{
        getposition(i, tx1, ty1, tz1);
        loop (j) for all balls
        {
            if(i!=j)
            {
                getposition(j, tx2, ty2, tz2);
                delx = tx2-tx1;
                dely = ty2-ty1;
                if(DetectCol(i, j))
                {
                    angle = atan2(dely, delx);
                    nx1 = (firstBall.speed.x * (firstBall.mass – secondBall.mass) + (2 * secondBall.mass * secondBall.speed.x)) / (firstBall.mass + secondBall.mass);
                    ny1 = (firstBall.speed.y * (firstBall.mass – secondBall.mass) + (2 * secondBall.mass * secondBall.speed.y)) / (firstBall.mass + secondBall.mass);
                    nx2 = (secondBall.speed.x * (secondBall.mass – firstBall.mass) + (2 * firstBall.mass * firstBall.speed.x)) / (firstBall.mass + secondBall.mass);
                    ny2 = (secondBall.speed.y * (secondBall.mass – firstBall.mass) + (2 * firstBall.mass * firstBall.speed.y)) / (firstBall.mass + secondBall.mass);

                    newx1=nx1*cos(angle) - ny1*sin(angle);
                    newy1=ny1*cos(angle) + nx1*sin(angle);

                    newx2=nx2*cos(angle) - ny2*sin(angle);
                    newy2=ny2*cos(angle) + nx2*sin(angle);

                    firstBall.speed.x = newx1;
                    firstBall.speed.y = newy1;
                    secondBall.speed.x = newx2;
                    secondBall.speed.y = newy2;

                }
            }
        }

        velx = firstBall.speed.x/700.0;
        vely = firstBall.speed.y/700.0;
        velz = firstBall.speed.z/700.0;

        getposition(i, px, py, pz);
        updateposition(i, (px+velx), (py+vely), (pz+velz));
    }
}
return 1;
}

```

# Answer
> 2 votes
The intent of your code is unclear; adding comments would help us know what you're trying to do, and making sure that we don't have to scroll horizontally would really help.

The first thing I notice, though, is that you check your system AND your update it at the same time, which could result in the behaviour you have:

For balls A and B, if you inspect a collision between ball A and B, and there is a collision, you change the behaviour/state of A *immediately* without changing the behaviour/state of B, that is, you make A bounce off B, then you inspect a collision between B and A, there is no longer any collision (because you've just moved A in the same loop execution) so you don't change it's behaviour/state. They will still collide the next frame because B is keeping on going on its trajectory and it's going to keep pushing A away in an unexpected manner.

Maybe what you could do is two passes:

1. Check everything that collide and store the pairs into a list. You should avoid checking A with B, then B with A, as the result will be the same.
2. Parse the list you build in the previous pass and resolve the collisions by modifying the position/velocity of each ball of the collision.

Now if A and B collide, and B and C collide, and A and C collide, you have a more complex collision. What do you do?

Collision detection and physics simulation are quite complex subjects in their own. You can do some in simple ways in your implementation, you'll have to leave some more complex situation out for the sake of simplicity (for instance, don't manage the A and B and C intersection as a single collision, but 3 separate ones).

Or you could try and find and integrate a collision/physics engine that is readily available and integrate it to your software for increased realism.

---
Tags: physics, game-mechanics
---


# Question
Title: To what extent are video game bots & NPCs “artificial intelligence”?
Wikipedia says:

> In video games, this usually means a character controlled by the computer through artificial intelligence.
> ~https://en.wikipedia.org/wiki/Non-player\_character
>
> In video games, a bot is a type of weak AI expert system software which for each instance of the program controls a player \[...\]
> ~https://en.wikipedia.org/wiki/Video\_game\_bot

However as far as I know such bots & NPCs are way too hard-coded or explicitly coded to be accurately called "artificial intelligence".

Mainly most often they lack the ability to learn dynamically from the player. Arthur Samuel calls "artificial intelligence" The "*field of study that gives computers the ability to learn without being explicitly programmed*" (1959).

So to what extend can bots and/or NPCs be called "artificial intelligence" if they (or a subset of them) can be designated as such?

# Answer
*Artificial Intelligence* is a very fuzzy idea without clear boundaries. The Oxford English Dictionary just defines it as:

> the theory and development of computer systems able to perform tasks that normally require human intelligence, such as visual perception, speech recognition, **decision-making**, and translation between languages.

The definition of "normally requiring human intelligence" has changed in meaning over time. Obviously, during the birth of AI, *everything* from simple addition upwards required human intelligence. Since them, the goal post has moved to be more and more complex. I highlighted "decision making" because to me it is the clearest example of NPCs being artificially intelligent. In my opinion, almost all software today is artificially intelligent in the sense described by the OED.

Also note that in Arthur Samuel's time, "learning" meant something entirely different than it does today. Samuel was referring to "expert systems" that determine answers to queries by deducing them using fundamental logic. This was considered "learning" back then, because the answer was not hard coded into the machine. Rather, the computer had to *learn* the answers by generalizing existing facts. Today, "learning" is generally considered to mean "statistical inference from data" -- an entirely different concept; wheras symbolic manipulation using fundamental logic is considered "programming." In 30 years, "learning" will probably mean something totally different as well. Already, "deep learning" is re-defining what we mean when we say a program has "learned" a concept.
> 1 votes

# Answer
The earliest, broadest definition of artificial intelligence included (what we now call) calculators. This was refined to exclude calculators because they could not be "taught" how to perform new calculations. Then, (what we now call) computers were invented, which could be reprogrammed to perform any conceivable algorithm. Again, we excluded computers on the basis that they could not program themselves but had to be instructed. We therefore assume that once a system is created which can learn to perform a task on its own (like this program which can learn to play certain classic NES games), we will have conquered AI.

Machine learning is its own highly developed domain, but it's usually hard to implement or is very slow. For games where it can be easily run in real time, it often makes games so difficult that they become unbeatable.

So to protect our own ego, let's call it a problem of definition.
> 0 votes

# Answer
"Artificial Intelligence", as you have already guessed from the other answers, is only loosely defined, and does not have much to do with intelligence. Personally I would not count learning as a requirement to call something an AI.

In Artificial intelligence, the common goal is to produce rational agents. Rational, because rational can be defined and achieved, and intelligent cannot. Rationality is defined as making the optimal choice, given the available information, to achieve some goal. The model is one of an "agent", an acting entity that receives some kind of sensory input, and can act. What is in-between can be anything from a rule-based hard-coded system, to planning systems and machine learnings. An agent could be a robot (with cameras for sensors, lots of motors for actuators), a security system, a wikipedia bot, a poker AI, or a game NPC.

Yes, NPCs are artificial intelligences, but the focus is on artificial and not intelligence.

An excellent book on the topic is "Artificial Intelligence: A Modern Approach" by Russel and Norvig http://aima.cs.berkeley.edu/
> 0 votes

# Answer
As someone who has worked on artificial intelligence applications outside the domain of gaming, I can tell you that what Hollywood convinces people AI is supposed to be is completely wrong. Anything that makes decisions based on learned heuristics is an application of AI. So bots, who are taught some rudimentary gameplay rules, objectively qualify as artificial intelligence.

Traditionally the rulesets used by game AI have been very simple and have been devised through human means. However, with the emergence of cloud computing, we are starting to see sophisticated game AI that uses data collected from massive samples of real-world players to generate many novel rules that humans probably never would have thought of. Forza 5 and Forza Horizon 2's "drivatar" system is the only concrete example I can give at this time. However, EverQuest Next is said to be using "emergent AI," which will also use data mining on a per-server basis to establish independent AI behavior on every server.
> 0 votes

---
Tags: ai, npc, bot
---