# Question
Title: Why does Unity use HLSL instead of GLSL?
I am beginner in shader programming. I got my introduction (few minutes ago) to shader programming via Unity.

I didn't know what HLSL was. So, I Googled and found this post: Difference b/w HLSL & GLSL

I can't understand one thing. Unity was initially developed for OSX & introduced at WWDC. Also DirectX is windows only API & HLSL is the shader programming language for DirectX. However, Unity3D for OSX is written in OpenGL. OpenGL uses a standard shader programming language called "GLSL".

So, I'm confused how Unity3D uses HLSL on OSX & why Unity didn't pick GLSL instead of HLSL.

> NOTE: I might be wrong somewhere. So please correct if something is wrong as I told I'm a beginner

# Answer
As far as I know, Unity uses Cg (which is deprecated by NVIDIA since 2012, I have no idea why they still use it) as its shader language (which is really similar to HLSL) instead of HLSL or GLSL as stated here:

> In Unity, shader programs are written in a variant of HLSL language (also called Cg but for most practical uses the two are the same).

Later on, Unity will convert the Cg shader into HLSL, GLSL or Metal based on what it needs (probably the target platform).

Then again, you can write GLSL directly as stated here and a note there:

> However, use of raw GLSL is *only recommended for testing, or when you know you are only targeting Mac OS X, OpenGL ES mobile devices, or Linux*. In all normal cases, Unity will cross-compile Cg/HLSL into optimized GLSL when needed.

Additionally, I found a really good answer for the deprecated Cg here (read there, there are some good answers):

> As NVIDIA is not supporting CG anymore, latest unity versions actually compile shaders using HLSL compiler and transform the resulting bytecode to GLSL.

Which also stated before and I missed it:

> OpenGL Core, OpenGL ES 3 and Metal **use Microsoft’s HLSL followed by bytecode translation into GLSL or Metal, using HLSLcc**.
> 8 votes

---
Tags: unity, glsl, hlsl
---


# Question
Title: Smoothly extend eased animation to new target value
I am implementing animated `double` property from scratch, currently with SmoothStep easing, however when new target value is set, there is visible "jump" in animation speed (probably due to applied easing). I would like `setTarget` to smoothly extend currently ongoing animation.
I have tried to calculate `originalValue_` and `remaining_` based on current `t` (offsetting those correctly, I think, will solve the problem), but haven't managed to find the correct formula.
How do I smoothly extend ongoing smoothstep animation to new target value?

```
void setTargetValue(double value, double duration = 1.0)
{
   originalValue_ = currentValue();
   targetValue_ = value;
   remaining_ = duration;
   duration_ = duration;
   t = 0.0;
}

double currentValue() const {
   return SmoothStep(originalValue_, targetValue_, t); //x*x*(3 - 2*x)
}

void update(double deltaT) {
   remaining_ = fmax(0.0, remaining_ - deltaT);
   t = clamp(0.0, 1.0, 1.0 - remaining_ / duration_)
}

```

# Answer
I was missing one important information - SmoothStep is a cubic spline interpolation with endpoints derivative being zero. There is well-known solution to cubic interpolation.
Luckily for case of animation there is no need to solve the linear equation system. Because the Di+1 is 0 by definition, all that is needed is first derivative Di at current `t` which is trivial for fixed order polynomial. Substituting to the equations we get new coeficients:

```
double derivative(double t) const {
   return coeff[0] + t * (2 * coeff[1] + 3 * t * coeff[2]); //b+2cx+3dx*x
}

//in setTargetValue compute new coefficients
double coeff[3];//a = 0 by definition
//note: in real implementation interval length compensation is also needed
coeff[0] = derivative(t);//b
coeff[1] = 3 - 2 * coeff[0];//c
coeff[2] = -2 + coeff[0];//d

```

and evaluate the SmoothStep `t` mapping as follows

```
double SmoothStepT(double t) const {
   return t * (coeff[0] + t * (coeff[1] + t * coeff[2])); //bx+cx*x+dx*x*x
}

double currentValue() const {
   return Lerp(originalValue_, targetValue_, SmoothStepT(t));
}

```

desmos graph demonstrating smoothness with two extensions:  *note: coefficient `a` and `x - t` is added to "move" the extended animation to place where the previous one left to demonstrate smoothness.*
*note2: I am not a mathematician, if you see an error in my math, please correct me*
> 1 votes

---
Tags: c++, animation
---


# Question
Title: How to create data driven effects/abilities for collectable card game
I'm trying to create cards for a ccg/tcg that are completely "data-driven" from an xml/json/external file. I've read multiple articles on this issue already, even here on stack exchange, but i can't figure out how to actually code this. I have a simple example:

My two cards have the following abilities

1) "Increase the value of all adjacent red cards by 1"

2) "Increase the value of this card by the amount of all adjacent red cards"

In my code i have the following functions (pseudo) that i need to accomplish these effects:

```
Increase(targetCards, byValue) // increases a card's value by another value
FindCards(filter=adjacent) // returns all adjacent cards
FilterCardsBy(filter=isRed) // returns only red cards
Count(targetCards) // counts the number of cards

```

To create effect 1 i would use the functions like this:

```
Increase(FilterCards(FindCards(adjacent), isRed), 1);

```

and to create effect 2 i would use:

```
Increase(this, Count(FilterCards(FindCards(adjacent), isRed)));

```

So here's the problem: I have no clue how i can describe these functions in my external file and also i have no clue how i actually tell my functions to work in this combination to achieve the desired effects. Maybe i'm misunderstanding the concept here but as far as i understood and described here i can create some pseudo script/code in my external file that then my code can interpret and execute on. But i feel i somehow missing the middle part where i write code to interpret these commands i'm defining in the external file.

Anyone with experience here that can give me some super simple starter ideas on how to takle this. Especially the part where i can combine several functions into one.

# Answer
When you have complex logic in the mechanics of individual cards, then it might be best to express that logic with a scripting language. But if you really want to go for a completely domain-driven approach, you might go for something in between: Markup which describes logic.

Both of the effects mentioned in the question could be called an "adjacency effect". It's an effect which triggers if an adjacent card fulfills a certain condition. The difference is that one is a bonus on the adjacent card, the other one on the card itself (which stacks for each card which fulfills the condition). In JSON, these two effects could be expressed as a triplet of `adjacencyCondition`, `self`-effect and `adjacent`-effect.

```
{
    "adjacencyCondition: { color: "red" },
    "self": { "value": 1 },
    // "adjacent": undefined
}

{
    "adjacencyCondition": { "color": "red" },
    // self: undefined
    "adjacent": { "value": 1 },
},

```

If you don't like JSON, feel free to use XML, YAML, INI or whatever markup language you prefer instead. But I would not recommend you to invent your own. When you use an existing markup language, you will likely find a well-tested library for parsing it. When you develop your own, you will have to spend countless hours writing your own parser. This will be far harder than it sounds at first. And subtle bugs in your parser can and will cause you frustration to no end.

Your program code to apply these would look like this (pseudocode):

```
if (card has 'adjacencyCondition') {
    foreach (adjacent card) {
        if (adjacent card has all attributes specified by 'adjacencyCondition') {
              increase adjacent card attributes by everything specified in 'adjacent'
              increase current card attributes by everything specified in 'self'
        }
    }
}

```

This system can easily be enhanced to have more conditions than just `adjacencyCondition` (where "adjacent" doesn't necessarily makes sense, but other fields might). Your should allow cards to have an array of effects to allow cards which have more than one effect. In that case you might also have an `unconditional` condition which allows you to define inherent attributes of cards. But I have no idea how your game mechanics look like or what the theme of your game is, so I could only guess what could be useful for you.

Anyway, here is an example of a red card with a value of 3 which counts as both a kitten and a zombie, which turns all adjacent space stations green and gets +1 for every blue card controlled by the opponent:

```
{   "name": "Bob the Zombie Kitten",
    "effects": [
         {
             "unconditional": true,
             "self": {
                 "color": "red",
                 "traits": [ "zombie", "kitten" ],
                 "value": 3,
             }
          },
          {
            "adjacentCondition": { "traits": "space_station" },
            "adjacent" : { "color": "green" }
          },

          {
            "allCondition": { "owner": "opponent", "color": "blue" },
            "self" : { "value": 1 }
          },
    ]
}

```
> 3 votes

# Answer
I will expand on this in a bit when I have more time but essentially, as you say, are going for a data driven design approach for your game.

This means you are defining your cards in XML or JSON format etc. What you should really do is pick one and stick with it (not necessarily forever, but for your first technical demos and understanding). Alternatively you can just create your own format and then write the code to interpret it. Imagine this inside a .txt file.

```
Card=
Name: Test
Value: 5
Color: Red
Endcard

```

Just a simple example, but now you have a defined piece of data that is more human readable and your designers can edit a text file instead of letting them have access to code.

So now you have a definition of the card and can separate data from code.

Your next step will be to write some form of interpreter (later you can change this to serializing/deserializing), a psuedo code of it may look like:

```
Card card = new Card();

var file = File.LoadFile("data.txt");
string line;
while (line != "Endcard")
{
line = file.ReadLine();
if (line == "Card=")
  {
    card.name = file.ReadLine().StripString("Name: ");
    /* this will read in name and strip the Name: part so the variable card.name
       now contains the string "Test". Please not you will have to implement
       the stripping part or use some in built language feature */
    card.value = file.ReadLine().StripString("Value: ");
    card.color = file.ReadLine().StripString("Color: ");
  }

}

```

So now your program has read in the data text file and converted it into a Card object.

I hope that helps you see it a bit clearer, sorry for poor formatting and again I will fix this up and write a fuller answer later with more time.

p.s. keep in mind the psuedoness nature of the code so far, the file reading employed is very error prone but I am just trying to communicate the idea across to you.
> 1 votes

---
Tags: c#, card-game, data-driven
---


# Question
Title: Generating a UV map for a procedural mesh
I have created a procedural low poly rock mesh and now I would like to apply textures on it.

I have the 3D-coordinates of every vertex of the mesh but that's about it. How would I automatically generate a UV map for this mesh, since this list of vertices will change every time I generate a rock? How do I get all these faces correctly mapped in a (1,1) square?

I am working in Unity3D if that helps.

Thanks,

Alex

**EDIT:** Preserving the face shapes/sizes is priority! I don't want distortion at all. The texture will be generally just the same color with some darker/lighter spots so every edge could be used as a seam. Faces can overlap! I just want all the faces in one 2D box (1,1), with the correct dimensions.

**EDIT 2:**

I have this code:

```
    Vector3[] verts = mesh.vertices;

Vector2[] uvs = new Vector2[verts.Length];

for (int i = 0; i < uvs.Length; i++)
{

    uvs[i] = new Vector2(Mathf.Abs(verts[i].x), Mathf.Abs(verts[i].z));

}

```

Which gives me the following UV map: \[!\[enter image description here\]\[2\]\]\[2\]

**EDIT 3:**

```
  float scaleFactor = 0.5f;

int[] tris = mesh.triangles;

Vector3[] verts = mesh.vertices;
Vector2[] uvs = new Vector2[verts.Length];

// Iterate over each face (here assuming triangles)
for(int index = 0; index < tris.Length; index += 3)
{
    // Get the three vertices bounding this triangle.
    Vector3 v1 = verts[tris[index]];
    Vector3 v2 = verts[tris[index + 1]];
    Vector3 v3 = verts[tris[index + 2]];

    // Compute a vector perpendicular to the face.
    Vector3 normal = Vector3.Cross(v3 - v1, v2 - v1);

        Debug.Log("surface " + index/3 + " : " + (normal*0.5f).magnitude);

    // Form a rotation that points the z+ axis in this perpendicular direction.
    // Multiplying by the inverse will flatten the triangle into an xy plane.
    Quaternion rotation = Quaternion.Inverse(Quaternion.LookRotation(normal));

    // Assign the uvs, applying a scale factor to control the texture tiling.
    uvs[tris[index]]     = (Vector2)(rotation * v1) * scaleFactor;
    uvs[tris[index + 1]] = (Vector2)(rotation * v2) * scaleFactor;
    uvs[tris[index + 2]] = (Vector2)(rotation * v3) * scaleFactor;
}

```

The red triangle on the left and the dark blue one on the right should be the same shape/size:

**EDIT 4:**

```
Mesh mesh = new Mesh();
mesh.name = "RockMesh";
List<int> Triangles = new List<int>();

var vertices = Vertices.Select(x => new Vertex(x)).ToList();

var result = MIConvexHull.ConvexHull.Create(vertices);
mesh.vertices = result.Points.Select(x => x.ToVec()).ToArray();
var xxx = result.Points.ToList();

foreach(var face in result.Faces)
{
    Triangles.Add(xxx.IndexOf(face.Vertices[0]));
    Triangles.Add(xxx.IndexOf(face.Vertices[1]));
    Triangles.Add(xxx.IndexOf(face.Vertices[2]));
}

mesh.triangles = Triangles.ToArray();

```

**EDIT 5:**

I had to move the code a bit but it finally works now! Like you guys predicted, the seems are not optimal, but I'm happy how it is now. Thanks!

# Answer
The real problem here is seams. Since the question remains underspecified, here are some contrived solutions, leaving implementation specifics to you.

**Don't let textural features cross triangle edges.** Ever. Simple.

You want to find the "fattest" triangles, i.e. tris where there is a lot of *room to work*, and start generating textural features from (near) their centres. Ignore long/slim triangles that won't accommodate a texture well.

How to know whether a triangle is fat? Should be easy - for each triangle, determine:

* the length `L` of its longest side.
* its area `A`.
* the ratio between these (`A:L`) - store this

If `A:L` (A divided by L) is low, it means it is a "fat" triangle.

Now order the triangles by this ratio, and choose say the best `n` triangles in terms of A:L, that you intend to generate on. Now generate texture features from their centres. On placement of every texel, you'll need to check whether you have crossed any of the edges - as you have a requirement for zero distortion, this is the best you can do.

Alternatively, **Let textural features cross just one edge**. This increases realism a bit, as you can have two nigh-coplanar faces sharing a feature. Then you can select 2 triangles at a time (based on average fatness of the 2 constituting triangles), which share a single edge, and overlay your tris onto your blank texture space in such a way as to minimise their distortion. Then knock yourself out generating a square texture for that, and just make sure your generated texels never get too near the tri-pair's outer edges; the easiest way to do this would be to simply fade into the regular colour (say mid-brown) as you approach the edges of the map being generated. Here you will, on every single texel draw, need to check you have not crossed one of the four tri-pair outer edges. Could be tedious and the tedium depends on your texel size relative to tri(s) area.

Or, you can avoid checking against edges of triangles on every single texel placement, if you simply morph your tri-pair to exactly fit the UV texture space (perfect square) - but this will then distort texels on application to the geometry.

Also note for this approach, that you need to be sure that any triangle that has already been chosen as part of a tri-pair / quad, must not become part of another tri-pair or you will have to use multi-texturing / multiple draw calls to achieve that.

**N.B.** Crucially, with either of these approaches you're going to need to make some attempt to keep texel scales similar between different faces / pairs. I would do that by ensuring that I *do not scale* the tris or quads *too much* to fit the UV quad. This is in line with your "no distortion" policy.
> 1 votes

# Answer
If we take as the requirements:

* no distortion
* no constraints on seam placement
* OK to overlap faces

then we can use a pretty simplistic approach, independently rotating each face into a 2D plane and more or less leaving it wherever it ends up.

```
// Iterate over each face (here assuming triangles)
for(int index = 0; index < triangles.length; index += 3)
{
    // Get the three vertices bounding this triangle.
    Vector3 v1 = verts[triangles[index]];
    Vector3 v2 = verts[triangles[index + 1]];
    Vector3 v3 = verts[triangles[index + 2]];

    // Compute a vector perpendicular to the face.
    Vector normal = cross(v3 - v1, v2 - v1);

    // Form a rotation that points the z+ axis in this perpendicular direction.
    // Multiplying by the inverse will flatten the triangle into an xy plane.
    Quaternion rotation = Quaternion.Inverse(Quaternion.LookRotation(normal));

    // Assign the uvs, applying a scale factor to control the texture tiling.
    uvs[triangles[index]]     = (Vector2)(rotation * v1) * scaleFactor;
    uvs[triangles[index + 1]] = (Vector2)(rotation * v2) * scaleFactor;
    uvs[triangles[index + 2]] = (Vector2)(rotation * v3) * scaleFactor;
}

```

This meets the above criteria, placing faces in the texture space with no distortion at all.

You may get faces outside the 0-1 range, but for a wrapping texture this won't be an issue. If you need to use a clamped texture or an atlas, then you can apply an offset to the UVs to bring the triangle back into the 0-1 square as long as your scaleFactor is small enough. Just note that you'll need to pay special attention to coplanar polygonal faces made up of multiple triangles - the method above will map them onto adjacent parts of the texture space, but if you start applying offsets then you either need to consider the whole multi-triangle polygon as a whole and move it together, or live with creating seams across the middle of these polygons.

As Arcane Engineer notes, seams will be very visible if texture features like those green blobs fall across a triangle edge, so you'll need to carefully evaluate whether that's acceptable for your use, or whether you need a more sophisticated layout algorithm that's aware of the texture content.
> 4 votes

---
Tags: unity, procedural-generation, vertex, uv-mapping, procedural
---


# Question
Title: Imported meshes can't be picked deterministically
Using BabylonJS, I have a grid of cylinder meshes created simply by

```
var tile = BABYLON.MeshBuilder.CreateCylinder("tile-" + i, { tessellation: 6, height: 0.1 }, scene);

```

then I have following event callback

```
window.addEventListener("click", function (evt) {
    // try to pick an object
    var pickResult = scene.pick(evt.clientX, evt.clientY);
    if (pickResult.pickedMesh != null){
         alert(pickResult.pickedMesh.name)
});

```

Then `mouse-click` on one of `tiles` raises `message box` with correct tile name.

When I add some new meshes (3D model inside `.babylon` file) by

```
var house;
BABYLON.SceneLoader.ImportMesh("", "../Content/"
                              , "house.babylon"
                              , scene
                              , function (newMeshes)
                                { house = newMeshes[0]; });

```

For better imagination it's texture of house created from four different meshes which is placed over `grid` of `cylinder` tiles.

It's displayed fine but when `mouse-click` it too much often behave as it would totally ignore there is such a mesh and so `pickResult.pickedMesh` is either `null` or `pickResult.pickedMesh.name` points to tile underlaying my imported mesh in point I've clicked.

Just approximately `5%` of mesh area corresponds properly to `mouse-clicks` (let's say in middle of roof, in middle of walls).

I've tried playing with setting some virtual (hidden) `house.parent` `mesh` for that which would not be created by importing meshes but seems as dead end.

Are you aware about some way how enforce that `scene.pick(evt.clientX, evt.clientY);` would respect mesh hierarchy and would consider all visible parts of overlaying texture?

Just for completeness I'm working with middle part of this 3D model (removed left and right house from that).

EDIT: Demo on BabylonJS playground

# Answer
Solution was to fix

```
var pickResult = scene.pick(evt.clientX, evt.clientY);

```

to

```
var pickResult = scene.pick(scene.pointerX, scene.pointerY);

```

as `evt` corresponds to whole page.
> 0 votes

---
Tags: javascript, babylonjs
---


title: Understanding Entity Component System

text:
# Question
Title: Understanding Entity Component System
I'm new in game development and I'm struggling to implement Entity Component System (ECS) properly, I have no idea whether I'm doing it right or completely wrong.

Basically, I try to implement ECS pattern with SceneGraph system, so here my current understanding:

> 1. `Entity` is nothing but a components bag, it has no logic but it may (or may not?) contain essential information to differentiate from the other `Entity` or grouping them as well, such as ID, Name, Tags, etc.
> 2. `Component` is a data container but contains no logic how to process the data but may contains function to manipulate the data, for example a `Transform` component may contains `Inverse()` function.
> 3. `System` is the implementation holder, it process `Entity` based on its `Component`. The `System` may define a "requirement". The `Entity` is processed if it match the requirement, for example `SpriteRendererSystem` only process `Entity` that contains `SpriteRenderer` and `Transform` component.

Currently, I have no idea if it's correct or completely mess. Therefore, I try to implement ECS along with SceneGraph as stated before, here my SceneGraph implementation:

> 1. `Node` is an object in the `Scene`, basically, everything that need to added into the `Scene` must implement this. The `Node` can add another `Node` instances as its child as well as parent. Currently, my `Entity` implement `Node`, meaning that all `Entity` can be added into `Scene`
> 2. `Scene` is the top most level of `Node`, it represent a root of `Node` and there can be only one active `Scene` at a time. The `Scene` basically implements `Node` and it has `Update()` and `Render()` functions, this functions is called by `SceneDirector`
> 3. `SceneDirector` is basically inherit game window, it manage the active Scene, passing `Render()` and `Update()` method to the active scene as well as updating the `Input` states to the `Scene`.

Now, I combine both pattern as follows:

> 1. The `Scene` has a list of `System` as well as list of `Node`. Depending the `System`, the `System` may called on `Render()` function if the `System` is Renderable, otherwise it will called on `Update()` function
> 2. Upon `Render()` / `Update()` function, the `Scene` will loop the entire `Entity`, it also loop the entire registered `System`. The `System` will check the `Entity` whether the requirement is match, if the requirement is fulfilled, the `Entity` will be processed by the `System`

---

**Now my questions:**

1. Can `Component` hold the logic? or it should not and stay as a bag of data?
2. Is it correct implement `Node` on `Entity`?
3. Is it correct to let every instances of `Scene` has their own `System`? or should I make it globally by storing the list of `System` in `SceneDirector`?
4. Is there any more efficient way to process the `Entity` rather than loop the `Entities` and the `Systems` completely?
5. Is my understanding correct about the ECS? Am I on the right track? or completely wrong?

Thanks in advance

# Answer
> 1. Can Component hold the logic? or it should not and stay as a bag of data?

That's how you like. I suggest to stick with the first implementation and finish your project, then see if it worked out for you or not.

If you do that, however, I suggest you drop the concept of System as you described it, as you'll have two lanes of doing things, which will, in the long run, add confusion ("where is the code that does this?").

Note that Unity has components where the logic is done, and no system in the way you described it.

> 2. Is it correct implement Node on Entity?

I don't think so.

You could have an entity which is not in your scene graph, or components that do not care at all where they are positioned (either in the world, or in the scene graph).

Think about composition over inheritance. I see ECSs as a tool which is parallel to a scene graph: an entity could have a Node component which would refer to a node in your scene graph. And a physics component which would hold a reference to it's physics representation in your physics engine.

This way, your systems are loosely coupled, and it favours reuse.

> 3. Is it correct to let every instances of Scene has their own System? or should I make it globally by storing the list of System in SceneDirector?

IMHO The System and the Scene should be two parallel structures, so you should not store the System in the Scene.

> 4. Is there any more efficient way to process the Entity rather than loop the Entities and the Systems completely?

Efficiency depends a lot on your implementation and your needs. I suggest you implement your architecture, work with it while keeping your classes as much decoupled as you can, and *profile* it often. If you find bottlenecks while profiling, fix these, and not non-existent ones. Maybe your rendering or your physics will be your bottlenecks, and not your ECS implementation.

> 5. Is my understanding correct about the ECS? Am I on the right track? or completely wrong?

Here is what an ECS is:

(Image source)

By this, I mean that every dev and every company has its own view of what an ECS is or should be.

Work with something you understand, keep your code clean, and as soon as you notice that there is something that's not right, *stop*, think about (but don't *overthink* about it), fix the issue, and carry on. Your architecture will evolve with your project and yourself as a dev.

And finish your project. Your second project awaits, and will be much better structured :)
> 10 votes

# Answer
I concur with Alexandre Vaillancourt on all except the 4th point.

> 4. Is there any more efficient way to process the Entity rather than loop the Entities and the Systems completely?

The goal with Systems is to process a specific set of components not necessarily the entity itself. The trick is to register an entity with a system only when it has the components required by the system.

---

I'd recommend reading the following articles. They give a solid overview of ECS architecture:

What is an entity system framework for game development?

Why use an entity system framework for game development?
> 2 votes

---
Tags: c#, architecture, entity-system, design-patterns
---


title: Vector for bullet direction XNA C#

text:
# Question
Title: Vector for bullet direction XNA C#
im creating a platform shooter. the gun can be rotated using the thumbsticks. i want to use a line of fire `newBullet.bulletVel` variable as a Vector 2. this variable will be used to send the bullet in the direction that the barrel of the weapon is pointed at. How could i do this?

for gun rotation i have declared a float named rotation and use spritebatch.draw method to show that the variable is for rotation of the image.

```
public float WMrotation;

public void UpdateMe(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).ThumbSticks.Right.Y < -0.1)
        {
            WMrotation += 0.03f;
        }
        if (GamePad.GetState(PlayerIndex.One).ThumbSticks.Right.Y > 0.1)
        {
            WMrotation -= 0.03f;
        }
    }

public void DrawMe(SpriteBatch sb)
    {
        sb.Draw(WMtxr, WMpos, null, Color.White, WMrotation, WMorigin, 1f, SpriteEffects.None, 0);
    }

```

ive set the bullet position when fired to be at the tip of the gun.

```
newBullet.bulletPos.X = player1.playerPosition.X + 15;
newBullet.bulletPos.Y = player1.playerPosition.Y + 15;

```

i think i need to use `newBullet.bulletVel` to calculate the vector in which the bullet travels

```
newBullet.bulletVel = i don't know what to put in here

```

Any help would be appreciated.

# Answer
> 2 votes
You can use trigonometry:

```
x = cos(angle)
y = sin(angle)

```

Make sure angle is in radian

---
Tags: c#, xna-4.0, vector
---


# Question
Title: Unity: Is there any way for a button to call a function of all clones?
I really don't know off hand. I've got a few ideas but I'm not at my PC to test it.

like ButtonisPressed \> Clone script etc()

```
//on every gameobject clone
void etc() {
  i = 2;
}

```

That way all i's in the clones will be 2. I want it to work like pacman, if all the clones(or ghosts) have i = 2 then they enter their blue state and they change colors. Except I want to call etc() function with a button Thanks in advance. If no one figures it out, I will report back later (~12hrs)

# Answer
This sounds like something where you would use the Controller pattern.

1. Create a script `GhostController` which has:
    * A `GameObject[] ghosts` to hold the game objects which
    * A public method `CreateGhost` which instantiates a new ghost and adds it to the `ghosts`-array
    * A public method `ChangeGhostState` which calls the function on all game-objects in the `ghosts` array.
2. Put this script into any persistent game object in your scene. A common way to handle this is having some invisible game object which holds all such controller-scripts.
3. Bind the event-handlers of your buttons to these two methods.
> 0 votes

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


# Question
Title: How do I program attacks and combos in a fighting game?
I'm working on a game a bit like *"Super Smash Bros."*, using C++ and SFML. I can't figure out a good way to program attacks.

First, I coded individual functions for each attack. The problem with this was that I needed three functions for each attack; one for dealing knock-back to other players, one for setting variables for the actual punch and one for checking for unique types of collision. This ends up being almost the same code for all the other attacks, and was also very messy for programming combos.

I then tried creating a class called `Attack`, and inherited classes like `Punch` and `Kick`. The problem with this was that I wasn't sure how to implement all of the methods in the `Player` class.

How do I program attacks and combos in a fighting game?

# Answer
> 5 votes
This advice is more general, rather than being specific to fighting games, but typically player behaviour in games with any reasonable level of complexity will be coded as a finite state machine, where the different actions that the player can perform (normal locomotion, climbing over objects, melee attacks), are encoded as mutually exclusive "states" that encapsulate that action.

https://en.wikipedia.org/wiki/Finite-state\_machine

(Edit: This article has a more game-specific explanation of how finite state machines are often used in player code http://gameprogrammingpatterns.com/state.html)

These states drive player animation and movement, and triggering the consequences of those actions (inflicting damage on enemies when you reach a certain point in the animation, triggering visual effects, etc). The player can be in one state, and only ever one state at a time, and each state can only transition to certain other states.

This kind of approach generally makes more sense than implementing as functions, because typically your player is going to be in one of these states for longer than a single frame, and this is a natural way to handle that more long-lived state. For example, if the player performs a heavy attack, you might want to keep them locked into that animation/state until a certain point has been reached, for balancing purposes but also to give the action a real sense of weight and consequence.

It also makes things easier to reason about, if you ever decide to implement networked multiplayer, because then it becomes much easier to think about what information you need to replicate to other players.

One thing I would caution against though, is making heavy use of class inheritance when writing this code. It becomes a massive pain if at some point in the future you want to share functionality between states that aren't otherwise related. Then you end up pushing functionality into some base class where it doesn't belong and messing up the code.. or having to duplicate bug fixes in several different player state classes that end up being almost complete copy-pastes of one another with a few things changed.

For a melee attack state for example, your different attacks might be conceptually similar enough to one another, that it makes sense to have one melee attack state, and just drive the different attack types based on the "start parameters" that the state was given when it started.

Consequences like inflicting damage, can usually be written into some kind of common utils function that's called from various places, and called internally from within your state.

If you're careful not to put too much player-input specific logic in your state machine code, it also comes in handy if you find you want to implement AI that can play your game at some point in the future, as they can reuse a lot of the same player state machine code to drive their animations/actions. (It's just that the actions being requested are coming from the AI now, instead of directly from an input device)

---
Tags: c++, 2d, software-engineering, sfml, fighting-game
---


# Question
Title: In a shader, how to know if a given 3D projected point is visible by camera?
In a shader, I would like to know for a given projected 2D pixel if the related 3D point is visible by camera (not especially the main camera, the projection and view matrix are provided to the shader as parameters).

By visible, I mean I can shoot a ray from that 3D point to the camera position without hitting any object.

The result should be similar to the camera being a light source and test would fail where there is shadows.

I think one possible solution would be to first render scene from camera view into a texture (eg : render texture) and then use than information later in the shader for the main rendering.

---

EDIT : I forget to mention what I want in the end is *Projective texture mapping*. I have tried to implement what Stormwind describe (I did not used a Surf but a render texture) It almost works, however shadows are not aligned correctly (like they are moved by a given offset).

Here is the shader that I wrote :

```
float4x4 _CameraMatrix;
sampler2D _MainTex;
sampler2D _DepthTex;

v2f vert (appdata_base v)
{
    v2f o;
    o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
    float4 cameraPos = mul(mul(_CameraMatrix, UNITY_MATRIX_M), v.vertex);
    o.scrPos = ComputeScreenPos(cameraPos);
    return o;
}

half4 frag (v2f i) : COLOR
{
    float4 cameraPos = i.scrPos;
    cameraPos /= cameraPos.w;

    if(cameraPos.x > 0.0f && cameraPos.x < 1.0f
    && cameraPos.y > 0.0f && cameraPos.y < 1.0f)
    {
        float depth = tex2D(_DepthTex, float2(cameraPos.x,cameraPos.y)).r;
        float cameraDepth = cameraPos.z;

        if(depth > cameraDepth)
        {
            return tex2D(_MainTex, cameraPos);
        }
        else
        {
            return float4(0.0f ,0.0f ,0.0f ,1.0f);
        }
    }
    else
    {
        return float4(0.0f ,0.0f ,0.0f ,1.0f);
    }
}

```

# Answer
> 2 votes
You could use the same technique as for Shadow Mapping

1. Have a float32 render surface (Surf) of suitable size (eg. 512x512). The surface must be depth-enabled.
2. Let the 3D point (P) be represented by a mesh with at least one triangle, sufficiently big to occupy at least a pixel on Surf.
3. With Surf's camera (Cam), render the mesh, ie. render a distance (a "depth") between Cam and P to Surf. Also render other objects of interest, that may hide P. Use a common depth shader for all rendering (ie. only write and care about the depth). Use Zenable and ZWriteEnable = 1.
4. Pass Cam's WVP matrix (WVP1) to this, current (main render?) shader (Shader2).
5. In Shader2, using WVP1 resolve the "hit point pixel" for P on Surf (Shader2 needs to know P:s world position). Then A) read that pixel value and B) "manually" calculate the distance between Cam and P (Shader2 needs to know Cam's world position too). Compare these two values, if they are practically equal, P is visible.

Note 1: One must use suitable tolerances and sizes because of numeric accuracy and surface resolution.

Note 2: From a vertex shader, output.Position is in range -1...1 (bottom -\> top and left -\> right), ie. mul(position, wvp) will be in that range. To then do a texture lookup with that info, one must convert it into texture coordinate addressing, ie. 0...1 (top -\> bottom and left -\> right) range.

---
Tags: unity, shaders, camera
---


title: What is OpenGL? I am new

text:
# Question
Title: What is OpenGL? I am new
What is OpenGL used for? Is it a game engine? If I were to program a game would I need to use Open GL with a game engine?

Also does OpenGL do animation? I am kinda of confused on what exactly OpenGL is. I know it's an Application Programming Interface. That's about it.

Is C++ used in OpenGL? For what exactly is C++ used for in OpenGL?

# Answer
> 3 votes
OpenGL is a graphics library. You can use it to draw shapes like triangles, quads etc.

OpenGL is not a game engine. It can be used as a part of a game engine.

If you were to program a game, you could use OpenGL to draw the sprites or 3D meshes.

OpenGL does not do animation by itself, but you can implement animation by modifying vertex positions etc.

OpenGL is a C API, so you can use it with languages that provide bindings for it, like C++ and many others.

# Answer
> 2 votes
In software you need a way to talk to hardware. That's called an interface. OpenGL is an interface to 3d graphics hardware.

A Game Engine includes, among other things, a graphics engine. The graphics engine needs to talk to the 3d graphics hardware (aka graphics card), and can use OpenGL to do that.

OpenGL is an interface and like most interfaces it can be used from several languages, altough C++ is one of the more popular languages for using OpenGL.

OpenGL, being an interface, doesn't "do" animation. Interfaces allow one side to talk with the other. As such you can write software that uses OpenGL to tell the 3d graphics hardware to display something that looks like an animation.

---
Tags: opengl
---


# Question
Title: How do games with a low tickrate but high framerate work?
How do games with a low tickrate make things work? I.e. how do they manage to stay responsive despite the fact that interpolating gamestates for rendering adds input delay? Is there some method besides simple interpolation that allows for fps above the tickrate? E.g. Minecraft seems to work very well with a tickrate of just 20hz.

# Answer
> 2 votes
Minecraft is pretty much the only game that has a lower physics frequency than rendering.

(As @DMGregory pointed out, this only applies to offline games, because most servers run on lower rates, and some Unity games also share this aspect, although with a smaller difference between update and render times)

In the case of minecraft, only updating happens 20 times a second. The rendering is still 60 fps. Between updates (or "ticks") the game doesn't do anything other than rendering. Because most of the things in the game don't go too fast, this is unnoticeable, but if you slow down some footage of minecraft, it may become noticeable, especially on falling entities. Because the game doesn't recalculate their positions very often, they only change positions 20 times a second.

The only updates, that happen 60 times a second are the camera and player updates.

---
Tags: frame-rate
---


title: SDF - indexing the folding space

text:
# Question
Title: SDF - indexing the folding space
I had been repetitively watching this part of the video just trying to understand his point:

> you can optionally use the return value as cell index ... as random seed to introduce some variation ...

at the near end of the video he stress that:

> don't use for loop ... anything can be achieved by repeating space ... I will make an operator to repeat an interval ... give it additional values like the first and the last cell index ... start by -2 and end at +2 then you get 5 objects ...

How can we achieve like what he say? Do we use `clamp()` to do that? Something like:

```
float a = clamp(pMod1(pos.x,2),start_value, end_value);

```

It is brilliant that everything he present is just like magic to me.

**Update01**

I dig deeper into `SDF` research and reading more codes from `shadertoy`, and discovered this interesting `capsule` code:

```
float sdCapsule( float3 p, float3 a, float3 b, float r ) {
    float3 pa = p - a,
    ba = b - a;
    float h = clamp( dot(pa, ba) / dot(ba , ba), 0.0, 1.0 );
    return length( pa - ba * h ) - r;
}

```

Basically, `length(x)-r` will get `sphere`, for `x` as the origin of the `sphere` and `r` is radius of the sphere. so the `sdCapsule` to some extend, is a variation of `sphere`, with the `clamp()`. That means my speculation might be correct. However, I still not sure what that `clamp()` do and how to adapt it to my use.

# Answer
Modulus is the operation that is used to repeat space.

If you take N mod 5, as you increase N, you'll get \[0, 5) over and over and over.

If you want to constrain it to just repeating a certain number of times, you can use clamp before modulus. When doing this, make sure that the value you clamp at is associated with empty space though, so you don't have geometry extending off into infinity.

Here is a link you are likely interested in (:

http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
> 1 votes

---
Tags: opengl, c++, signed-distance-field
---


title: Store static environment in chunks

text:
# Question
Title: Store static environment in chunks
I have terrain separated by chunks and I would like to put environment (For example, rocks, trees, etc..) in each chunk randomly.

My question is related to how to implement such system in OpenGL.

What I have tried:

1. **Solution**: Draw the environment with instancing once for *all* the terrain (not a specific chunk)

**Problem**: I except the chunk to sometimes take a bit to load and because I am using threads the environment will appear as floating.
2. **Solution**: Draw the environment with instancing for each chunk.

**Problem**: To draw each chunk, I will need to bind the VBO for the chunk, draw the chunk, bind the VBO for the environment (and the VAO probably) and draw it.

I don't want to put so many glBindBuffer functions because I heard it is slow (Please correct me if I am wrong)
3. **(Not tried) Solution**: Somehow merge the vertices of the terrain with its environment and draw them together.

**Problem:** My terrain is drawn with GL\_TRIANGLE\_STRIP so this is a first problem, the second problem(?) is that I don't know how well it will function (talking speed).

I tried looking up solutions on the internet but didn't seem to find any that relate to chunks.

Anyone know how other games that uses chunks do that? Is there a way to do it without causing a lot of speed decrease?

# Answer
The correct answer depends on the amount of chunks you have. If you have very few of them, the overhead of multiple drawing calls will be negigible and you should opt for better design instead. Otherwise, you could use the single call solution, maybe adding a sync point that would ensure no assets flying in the final rendering. The sweet spot where the amount of chunks is favourable to a specific solution is only known with proper profiling.
> 1 votes

---
Tags: opengl, c++, terrain
---


# Question
Title: Getting Bodies to go "Super Fast" in Box2D
I am making a breakout game in Android using the LibGDX version of Box2D. I have a ball that I am applying a force to with the following code...

```
getBody().applyForceToCenter(-10000000000.0f, -10000000000.0f);

```

This makes the ball move properly, but it never seems to gain a lot of speed (and I want to make it go super fast). I tried adding an accelerate method where I applied the force 40 times, but again it doesn't seem to move that fast. What is a good way to make a Body go "Super fast" in Box2D?

If there is acceleration I would like it to be as short as possible.

I tried adding the following....

```
World.setVelocityThreshold(1000000.0f);

```

But now the ball doesn't seem to "bounce" off walls, do I need to raise my restitution or something?

# Answer
> 10 votes
Tried also to create a breakout clone, but stopped for now, for some other reasons... anyway this is what I learned so far, during development.

1. Use Meters instead of Pixels, Box2D uses MKS (meters, kilograms, and seconds) so when you have a Viewport of e.g. 1280x720 , this would be a length 1,28km. Then your Ball must have an outrageous speed to be "fast" in this long distance. Better use meters e.g. 50x20 (or something like that) =\> http://box2d.org/2011/12/pixels/
2. If you don't use Meters, but a higher BOX\_STEP (e.g. 1/500f) and more BOX\_VELOCITY\_ITERATIONS during each render()-call, then you can speed up on a Desktop, but on Android it just gets down to 3FPS which isn't really "fast".
3. "Fix your timestep" =\> http://gafferongames.com/game-physics/fix-your-timestep/ (for this there are some other Stackoverflow Entries, which currently couldn't find)

The TL;DR-Version: Use Meters instead Pixels, then you don't have to use such an high force / velocity, and it will be fast on android and desktop.

Best Regards and hoping this helped a bit

# Answer
> 3 votes
I see that there is already an accepted answer to this question. While it is in my opinion a helpful answer, it is not an answer to the original question of how to get bodies to go "super fast" and it does not address the use of `setVelocityThreshold`.

**Regarding the question of how to make bodies go "super fast"...**

There are two parts to understand for making bodies go faster:

1. The obvious: give the body a "super fast" velocity by one of the ways recognized. I.e. by applying the force/impulse/velocity necessary for the body to go as fast as needed.
2. There is a maximum translation setting(s) (`b2_maxTranslation` and `b2_maxTranslationSquared`) that puts an upper bound on how fast any body will actually go **per time step**. This limit is not in meters per second but in meters per time step. So at world steps of 1/60th of a second, a max translation of 2, is 120 meters per second.

As for part two of how to make bodies go super fast, given that the maximum translation amounts are per time step, one can either increase the steps per second (and say do world steps of 1/120th of a second instead of 1/60th of a second), or increase these maximums. With increasing these maximums however, note that there's a comment from the C++ sources for Box2D on GitHub which says:

> The maximum linear velocity of a body. This limit is very large and is used to prevent numerical problems. You shouldn't need to adjust this.

Based on my experimenting with this setting in my own fork of Box2D where I've updated the Testbed to allow per-step configuration of things like the max translation amount, I can elaborate on this comment.

Within the suggested size ranges for Box2D, a maximum translation setting of 4 looked okay with a frame rate of 60 frames a second. As one increases the body's speed and the max translation that it's capped at, the image visually appears more jumpy as it moves across the screen. Short of increasing the frame rate and decreasing the per-step time simulated, jumpier and jumpier is how it will appear to anyone as the body's speed goes faster. Eventually a fast enough body won't show up on more than a single frame (if at all). A single frame of course can't make a body look like it moved at all - just that it suddenly appeared and disappeared in a single spot.

Insofar as numerical problems are concerned, there are **always** numerical problems when using limited-precission floating point arithmetic as Box2D does and other physics engines also do. It's whether or not the numerical problems are visually noticeable that's the bar, practically speaking, that we can be concerned with.

From this perspective, as speed is increased the visually apparent problems that I'd expect to increasingly occur are:

* Unexpected tunneling (even with bullet enabled or in collisions with static bodies).
* Having to go beyond the ranges that Box2D is "tuned" for and causing everything to need to be reconsidered from a scaling and visualization perspective.

Numerical problems is an area that I continue to look into with interest however.

Here's a relevant excerpt from the Box2D 2.3.2 manual regarding the library's tuning:

> In particular, Box2D has been tuned to work well with moving shapes between 0.1 and 10 meters. So this means objects between soup cans and buses in size should work well. Static shapes may be up to 50 meters long without trouble.

**Regarding using `setVelocityThreshold`...**

The velocity threshold has to do with the minimum speed a body has to be moving in order for the physics engine to have it bounce off of other bodies that it collides with; not with a maximum speed that bodies can go.

The comment for the velocity threshold settings reads as follows:

> A velocity threshold for elastic collisions. Any collision with a relative linear velocity below this threshold will be treated as inelastic.

Hope this answer adds usefully from what's already been accepted as the answer.

---
Tags: box2d, libgdx
---


# Question
Title: If (button.interactable) condition doesn't work - why?
I have a Typewriter script attached to the text, which is a child of a button.
I want this script to run only if the button is interactable.

I made a public variable to store the button and used GetComponent() method, but it doesn't work.

```
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

// attach to UI Text component (with the full text already there)

public class UITextTypeWriter : MonoBehaviour {

public Text txt;
string story;
public Button ParrentButton;

void Awake()
{
    txt = GetComponent<Text>();
    story = txt.text;
    txt.text = "";

        Button b = ParrentButton.GetComponent<Button>();
        if (b.interactable)
        {
            StartCoroutine("PlayText");
        }
}

IEnumerator PlayText()
{
    foreach (char c in story)
    {
        txt.text += c;
        yield return new WaitForSeconds(0.125f);
    }
}

}

```

Where is my mistake? I would be grateful for your help!

Thank you in advance!

# Answer
> 1 votes
The check is only made once: When this script first awakens it checks to see if the button is enabled, if it is, the entire typewriter effect will occur. If the button is not enabled, then the typewriter effect will *never* occur (unless the script *itself* is disabled and re-enabled).

If you want to wait for the button to become enabled, you need to use the `Update()` method. If you want to stop the typewriter effect after it starts, you'd have to restructure your code entirely.

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UITextTypeWriter : MonoBehaviour {

    public Text txt;
    private string story;
    public Button ParrentButton;
    private bool writing;

    void Awake()
    {
        txt = GetComponent<Text>();
        story = txt.text;
        txt.text = "";
        writing = false;
    }

    private void Update()
    {
        if (!writing)
        {
            Button b = ParrentButton.GetComponent<Button>();
            if (b.interactable)
            {
                writing = true;
                StartCoroutine("PlayText");
            }
        }
    }

    IEnumerator PlayText()
    {
        foreach (char c in story)
        {
            txt.text += c;
            yield return new WaitForSeconds(0.125f);
        }
    }
}

```

The `writing` boolean is so we don't check the button again after we've started (or the coroutine would run more often than we want).

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


# Question
Title: When the book talk about CreateSamplerState in D3d11, what I have to do in D3d12?
I want to build a virtual earth, so I read the book '3D Engine Design for Virtual Globes' by Patrik Cozzi and Kevin Ring. But the book talk the CreateSamplerState in D3d11.I havn't used D3d11, I just learn D3d12 from the book '3D Game Programming WITH DIRECTX 12'by Frank D.Luna. Does it mean the Sampler state in built root signature? I get some D3d12 sample code here,maybe it can help to understand my question:

```
    // A root signature is an array of root parameters.
CD3DX12_ROOT_SIGNATURE_DESC rootSigDesc(4, slotRootParameter,
    (UINT)staticSamplers.size(), staticSamplers.data(),
    D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);

```

# Answer
> 1 votes
With D3D12, you now have two options to provide a sampler state to a shader.

1. Just like in D3D11, the shader assume nothing, and will read a sampler from a descriptor table bound to the root signature. In code, you will have a descriptor heap for samplers to store them.
2. In the case the sampler is not a variable parameter but a constant, you can configure it in the root signature, either in the hlsl or by building a root signature description in code. This is useful for things that are not in the hand of an artist, like a shadowmap sampler or a post process.

The option 2 has the advantage to allow some extra shader optimisation, because instead of reading memory to get the sampler, it can be inline in the shader.

# Answer
> 0 votes
I find some article:

Tutorial: Migrating Your Apps to DirectX\* 12 – Part 3

in 3.6,it said: 3.6 Command List/Queue

D3D12 Command List/Queues are features transformed out of D3D11 Device Context. Command List is responsible for buffering rendering commands which are then built into hardware commands known by the driver and finally executed by the Command Queue. Since each Command List can independently fill rendering commands without any intermediate lock protection, it operates faster than its counterpart in D3D11.

---
Tags: directx11, directx12
---


title: Pathfinding for fleeing

text:
# Question
Title: Pathfinding for fleeing
As you know there are plenty of solutions when you wand to find the best path in a 2-dimensional environment which leads from point A to point B.

But how do I calculate a path when an object is at point A, and wants to get away from point B, as fast and far as possible?

A bit of background information: My game uses a 2d environment which isn't tile-based but has floating point accuracy. The movement is vector-based. The pathfinding is done by partitioning the game world into rectangles which are walkable or non-walkable and building a graph out of their corners. I already have pathfinding between points working by using Dijkstras algorithm. The use-case for the fleeing algorithm is that in certain situations, actors in my game should perceive another actor as a danger and flee from it.

The trivial solution would be to just move the actor in a vector in the direction which is opposite from the threat until a "safe" distance was reached or the actor reaches a wall where it then covers in fear.

The problem with this approach is that actors will be blocked by small obstacles they could easily get around. As long as moving along the wall wouldn't bring them closer to the threat they could do that, but it would look smarter when they would avoid obstacles in the first place:

Another problem I see is with dead ends in the map geometry. In some situations a being must choose between a path which gets it faster away now but ends in a dead end where it would be trapped, or another path which would mean that it wouldn't get that far away from the danger at first (or even a bit closer) but on the other hand would have a much greater long-term reward in that it would eventually get them much further away. So the short-term reward of getting away *fast* must be somehow valued against the long-term reward of getting away *far*.

There is also another rating problem for situations where an actor should accept to move closer to a minor threat to get away from a much larger threat. But completely ignoring all minor threats would be foolish, too (that's why the actor in this graphic goes out of its way to avoid the minor threat in the upper right area):

Are there any standard solutions for this problem?

# Answer
> 23 votes
This might not be the best solution, but it worked for me to create a fleeing AI for this game.

Step 1. Convert your Dijkstra's algorithm to A\*. This should be simple by just adding a heuristic, which measures the minimum distance left to the target. This heuristic is added to the distance traveled so far when scoring a node. You should make this change anyway, as it will boost your path finder significantly.

Step 2. Create a variation of the heuristic, which instead of estimating the distance to the target it measures the distance from the danger(s) and negates this value. This will never reach a target (as there is none), so you need to terminate the search at some point, perhaps after specific number of iterations, after specific distance is reached or when all possible routes are handled. This solution effectively creates a path finder that finds the optimal escaping route with the given limitation.

# Answer
> 33 votes
If you really want your actors to be smart about fleeing, just plain Dijkstra / A\* pathfinding won't cut it. The reason for this is that, in order to find the optimal escape path from an enemy, the actor also needs to consider how the enemy will move in pursuit.

The following MS Paint diagram should illustrate a particular situation where using only static pathfinding to maximize distance from the enemy will lead to a suboptimal outcome:

Here, the green dot is fleeing from the red dot, and has two choices for a path to take. Going down the right-hand path would allow it to get much further from the red dot's *current* position, but would eventually trap the green dot in a dead end. The optimal strategy, instead, is for the green dot to keep running around the circle, trying to stay on the opposite side of it from the red dot.

To correctly find such escape strategies, you'll need an adversarial search algorithm like minimax search or its refinements such as alpha-beta pruning. Such an algorithm, applied to the scenario above with a sufficient search depth, will correctly deduce that taking the dead end path to the right will inevitably lead to capture, whereas staying on the circle will not (as long as the green dot can outrun the red one).

Of course, if there are multiple actors of either type, all of these will need to plan their own strategies — either separately or, if the actors are cooperating, together. Such multi-actor chase/escape strategies can become surprisingly complex; for example, one possible strategy for a fleeing actor is to try to distract the enemy by leading it towards a more tempting target. Of course, this will affect the optimal strategy of the other target, and so on...

In practice, you probably won't be able to perform very deep searches in real time with lots of agents, so you're going to have to rely on heuristics a lot. The choice of these heuristics will then determine the "psychology" of your actors — how smart they act, how much attention they pay to different strategies, how cooperative or independent they are, etc.

# Answer
> 7 votes
You've got pathfinding, so you can reduce the problem to picking a good destination.

If there are absolutely safe destinations on the map (e.g. exits that the threat can't follow your actor through), pick one or more nearby ones, and figure out which one has the lowest path cost.

If your fleeing actor has well-armed friends, or if the map includes hazards which the actor is immune to but the threat isn't, pick an open spot near such a friend or hazard and pathfind to that.

If your fleeing actor is faster than some other actor that the threat might also be interested in, pick a point in the direction of that other actor, but beyond it, and pathfind to that point: "I don't have to outrun the bear, I only have to outrun you."

Without the possibility of escape, or killing or distracting the threat, your actor is doomed, right? So pick an arbitrary point to run to, and if you get there, and the threat is still following you, what the hell: turn and fight.

# Answer
> 7 votes
Since specifying an appropriate target-position might well be tricky in many situations, the following approach based on 2D occupancy grid-maps may be worth considering. It is commonly referred to as "value iteration", and combined with gradient-descent/ascent, it gives a simple and fairly efficient (depending on implementation) path-planning algorithm. Due to its simplicity, it is well-known in mobile robotics, in particular for "simple robots" navigating in indoor environments. As implied above, this approach provides a means of finding a path away from a start-position without explicitly specifying a target-position as follows. Note that a target-position can optionally be specified, if available. Also, the approach/algorithm constitutes a breadth-first search, and is to some degree related to potential field methods with attracting and repelling forces.

In the binary case, the 2D occupancy grid-map is one for occupied grid-cells and zero elsewhere. Note that this occupancy-value can also be continuous in the range \[0,1\], I'll get back to that below. The value of a given grid-cell *gi* is *V(gi)*.

### The Basic Version

1. Assuming that grid-cell *g0* contains the start-position. Set *V(g0)=0*, and put *g0* in a FIFO-queue.
2. Take the next grid-cell *gi* from the queue.
3. For all neighbors *gj* of *gi*:
    * If *gj* is not occupied and has not been visited previously:
        + *V(gj) = V(gi)+1*
        + Mark *gj* as visited.
        + Add *gj* to the FIFO-queue.
4. If a given distance-threshold is not reached yet, continue with (2.), otherwise continue with (5.).
5. The path is obtained by following the steepest gradient-ascent starting from *g0*.

### Notes on Step 4.

* As given above, step (4.) requires to keep track of the maximum distance covered, which has been omitted in the above description for reasons of clarity/brevity.
* If a target-position is given, the iteration is stopped as soon as the target-position is reached, i.e. processed/visited as part of step (3.).
* It is, off course, also possible to simply process the whole grid-map, i.e. to continue until all (free) grid-cells have been processed/visited. The limiting factor is obviously the size of the grid-map in conjunction with its resolution.

### Extensions and Further Comments

The update-equation *V(gj) = V(gi)+1* leaves plenty of room to apply all kinds of additional heuristics by either down-scaling *V(gj)* or the additive component in order to reduce the value for certain path-options. Most, if not all, such modifications can nicely and generically be incorporated using a grid-map with continuous values from \[0,1\], which effectively constitutes a pre-processing step of the initial, binary grid-map. For example, adding a transition from 1 to 0 along obstacle boundaries, causes the "actor" to preferably stay clean of obstacles. Such a grid-map can, for example, be generated from the binary version by blurring, weighted dilation, or similar. Adding the threats and enemies as obstacles with large blurring radius, penalizes paths that come close to these. One can also use a diffusion-process on the overall grid-map like this:

*V(gj) = ( 1/(N+1) ) × \[ V(gj) + sum( V(gi) ) \]*

where "*sum*" refers to the sum over all neighboring grid-cells. For example, instead of creating a binary map, the initial (integer) values could be proportional to the magnitude of the threats, and obstacles present "small" threats. After applying the diffusion-process, the grid-values should/must be scaled to \[0,1\], and cells occupied by obstacles, threats, and enemies should be set/forced to 1. Otherwise the scaling in the update-equation may not work as desired.

There are many variations on this general scheme/approach. Obstacles etc. could have small values, while free grid-cells have large values, which may require gradient-descent in the last step depending on the objective. In any case, the approach is, IMHO, surprisingly versatile, fairly easy to implement, and potentially rather fast (subject to grid-map-size/resolution). Finally, as with many path-planning algorithms that don't assume a specific target-position, there is the obvious risk of getting stuck in dead-ends. To some extent, it might be possible to apply dedicated post-processing steps before the last step to reduce this risk.

Here's another brief description with an illustration in Java-Script (?), though the illustration didn't work with my browser :(

http://www.cs.ubc.ca/~poole/demos/mdp/vi.html

Lots more detail on planning can be found in the following book. Value iteration is specifically discussed in Chapter 2, Section 2.3.1 Optimal Fixed-Length Plans.

http://planning.cs.uiuc.edu/

Hope that helps, kind regards, Derik.

# Answer
> 3 votes
How about focusing on predators? Let's just raycast 360 degrees on Predator's position, with appropriate density. And we can have refuge samples. And choose best refuge.

# Answer
> -1 votes
One approach they have in Star Trek Online for herds of animals is to just pick an open direction and head in that, fast, de-spawning the animals after a certain distance. But that is mostly a glorified de-spawn animation for herds you are supposed to scare away from attacking you, and not suitable for actual combat mobs.

---
Tags: path-finding
---


# Question
Title: Collision detection with Java streams and access of collisionable objects
I'm trying to learn some things about collision detection, and I've never known how to cleanly detect this for multiple objects in multiple classes without just copy pasting a lot of code.

I now came up with all collisionable/solid things implementing a class and then using Java streams to return whether one or more things in the list of solid things is colliding with the thing you are checking. Is this the way to do this? Or is this really performance heavy or unconventional? I also didn't know a good way of getting the collisionable objects to the player/other creatures, so I simply used a getter, but that means that player class will get access to all the things in the arraylist and I don't know if this is save.

And are there good resources on collision detection for Java(8)?

And if this were to be for a partially grid based game with unwalkable positions in the grid, but also moving objects that cannot be walked through, would something like this still be the correct way to go about it?

Relevant code:

GameScreen.java

```
class GameScreen implements Screen {
private Stage stage;
private Game game;
private Player player;
private ArrayList<Solid> solids;

GameScreen(Game game) {
    this.game = game;
    stage = new Stage(new ScreenViewport());

    solids = new ArrayList<>();
    solids.add(new Wall(500, 0, 200, 200));
    solids.add(new Rock(200, 600, 100, 100));

    player = new Player(this);
    stage.addActor(player);
}

public ArrayList<Solid> getSolids() {
    return solids;
}
}

```

Rock.java (Wall.java is exactly the same but with Rock replaced by Wall)

```
class Rock extends Group implements Solid {

private int x;
private int y;
private int width;
private int height;

Rock(int x, int y, int width, int height) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
}

@Override
public boolean collidesWith(float oX, float oY, float oWidth, float oHeight) {
    return (oX + oWidth > x && oX < x + width)
            && (oY + oHeight > y && oY < y + height);
}
}

```

Player.java

```
class Player extends Group {
private final float STEP = 10f;
private GameScreen gameScreen;
private int playerHeight = 130;

Player(Screen gameScreen) {
    setBounds(300, 300, playerHeight / 6.5f * 5, playerHeight);
    this.gameScreen = (GameScreen) gameScreen;
}

private boolean collidesWith(ArrayList<Solid> solids, float x, float y) {
    return solids.stream().filter(o -> o.collidesWith(x, y, getWidth(), getHeight())).findAny().isPresent();
}

@Override
public void act(float delta) {
    super.act(delta);

    if(Gdx.input.isKeyPressed(Input.Keys.W)) {
        if (!collidesWith(gameScreen.getSolids(), getX(), getY() + STEP)) {
            this.setPosition(getX(), getY() + STEP);
        }
    }
    if(Gdx.input.isKeyPressed(Input.Keys.S)) {
        if (!collidesWith(gameScreen.getSolids(), getX(), getY() - STEP))
            this.setPosition(getX(), getY() - STEP);
    }
    if(Gdx.input.isKeyPressed(Input.Keys.A)) {
        if (!collidesWith(gameScreen.getSolids(), getX() - STEP, getY()))
            this.setPosition(getX() - STEP, getY());
    }
    if(Gdx.input.isKeyPressed(Input.Keys.D)) {
        if (!collidesWith(gameScreen.getSolids(), getX() + STEP, getY()))
            this.setPosition(getX() + STEP, getY());
    }
}

```

}

Solid.java

```
interface Solid {
  boolean collidesWith(float oX, float oY, float oWidth, float oHeight);
}

```

# Answer
> 2 votes
> And are there good resources on collision detection for Java(8)?

TL;DR- when dealing with collisions, you're almost *always* better off using 3rd party engines like Box2D which is compatible with libGDX and have had the heck optimized out of them.

> I now came up with all collisionable/solid things implementing a class and then using Java streams to return whether one or more things in the list of solid things is colliding with the thing you are checking. Is this the way to do this? Or is this really performance heavy or unconventional?

It's not great because you're going to check the entire list. I'm not sure what the implementation of Stream is (I looked in the source code; not a lot of luck), but fundamentally if you need to check to see if each object has collided with another, it's a O(N^2) operation.

Physics engines get around this by saying that some entities (like your rocks) are "Static"- they can collide, but never move. If they never move, we don't need to check for collisions between them. Thus, if we can say we have **N** moving objects and **M** static objects, we get O(N*M + N*N), which often gets simplified to O(N\*M) if you have more static objects than moving ones.

Then you can simplify things further by dividing your world into "chunks"- if there aren't any moving parts in a chunk, you don't need to do collision checking against any of the static objects in that chunk.

Like I said, Box2D already does all of this for you (and more), so I would recommend you invest the time needed to learn it.

> I also didn't know a good way of getting the collisionable objects to the player/other creatures, so I simply used a getter, but that means that player class will get access to all the things in the arraylist and I don't know if this is save.

If you go the physics engine route this will become a moot point, but theoretically if you didn't, I would say if you're worried about the `Player` class messing with the list somehow, you could invert the dependency as shown in the pseudocode below:

```
interface Collidable {
  default boolean collidesWith(Collidable o) {
    return (o.getX() + o.getWidth() > getX() && o.getX() < getX() + getWidth())
        && (o.getY() + o.getHeight() > getY() && o.getY() < getY() + getHeight());
  }
  float getWidth();
  float getHeight();
  float getX();
  float getY();
}
class Player implements Collidable { ... }
class Rock implements Collidable { ... }
// ...
ArrayList<Collidable> rocks = ...
Player player = ...
// ...
public void render(delta) {
    // Without Streams
    for(Collidable rock : rocks)
      if(rock.collidesWith(player)
        // Your code here
    // With Streams
    rocks.filter(r -> r.collidesWith(player)).forEach(r -> // Your code here);
}

```

Maybe not the cleanest, but illustrates how you could make absolutely sure that rocks and players only know how to collide with each other.

---
Tags: java, libgdx, collision-detection
---


# Question
Title: Unity: How to take in multiple textures for Image Effect
I am trying to write a composite Image Effect shader with a script that works as such:

1. The camera texture is taken, and stored into two different variables. For examples sake they will be tex1 and tex2.
2. tex1 is modified by a shader.
3. Both tex1 and tex2 are taken into another shader, which composes them together. The result is stored as tex.
4. tex is printed to the screen.

I am not having an issue with the actual content of the shader manipulating the image-- But I do not know how to pass in both textures to one shader as needs to be done in step three. Thanks in advance if anyone can help.

# Answer
> 1 votes
Here's how I might approach it, using Graphics.Blit and two materials/shaders for the separate modification steps. You can call this from OnRenderImage to have it applied as a post effect once the camera's rendering is finished.

```
void CompositeTextures(RenderTexture tex1, RenderTexture tex2, RenderTexture output) {

    // Create/reuse a temporary RenderTexture as an intermediate
    // (this can be cheaper than reserving memory for it throughout).
    var temp = RenderTexture.GetTemporary(tex1.width, tex1.height, 0, tex1.format);

    // Perform the first shader operation, modifying tex1
    // and storing the result in a temporary buffer.
    Graphics.Blit(tex1, temp, firstOpMaterial, firstOpPass);

    // Assign tex2 as an auxiliary texture
    // to be sampled by our second shader operation.
    secondOpMaterial.SetTexture("_Tex2", tex2);

    // Perform the compositing step to populate the output,
    // with the modified tex1 piped through as _MainTex
    // and tex2 piped to a sampler called _Tex2.
    Graphics.Blit(temp, output, secondOpMaterial, secondOpPass);

    // Recycle the temporary render target we used.
    RenderTexture.ReleaseTemporary(temp);
}

```

---
Tags: unity, shaders
---


# Question
Title: What are some standard mathematical tests for projection matrices?
I'm trying to double check my math in my projection matrices. I'm thinking about "unit tests" when I ask this. I'm looking for 4 or 5 unit tests that would be appropriate to give one confidence that the projections are correct.

This is a little more than an obvious question. Let me explain... When I did this with a quaternion, the potential tests were very logical. The perspective transforms by comparison are somewhat non-intuitive. For a quaternion, if I start with the unit Y vector {0.0, 1.0, 0.0} and I rotate it a quarter turn about the x-axis, I know that the answer is the unit vector in the negative z direction. It's a logical answer. Is there something equally logical/obvious for orthographic and perspective projections?

I've gone through many math books and many tutorials over the years. I'd like to once and for all "prove" that my ortho and perspective matrices are always projecting correctly.

If I composed an ortho matrix using left, right, bottom, top, near, far as follows:

```
              0.0f, 1.0f,
              0.0f, 1.0f,
              0.0f, 1.0f

```

I might get the following matrix (right-handed / OpenGL style)

```
  2.000000,   0.000000,   0.000000,  -1.000000
  0.000000,   2.000000,   0.000000,  -1.000000
  0.000000,   0.000000,  -2.000000,  -1.000000
  0.000000,   0.000000,   0.000000,   1.000000

```

I'd like to know if that matrix is computed correctly.

Then for a test, I'd multiply a vertex such as {1.0f, 1.0f, 0.0f} against the matrix and get back {1.0f, 1.0f, -1.0f}. Is it correct? ...and I'd like to do that on several standard points.

I'm having trouble visualizing "standard" or "logical" tests for this. Something that at a glance, just makes sense. (like the quaternion example above)

# Answer
> 2 votes
A few ideas:

* Any point in front of the camera along its central axis should get mapped to (0, 0) after the perspective division.
* Any point selected on / outside the camera's view frustum/prism should map, after perspective division, to a value of 1 or greater, or -1 or less on at least one of the x, y, z axes.

Beyond that, you could use some linear algebra first principles to form the projection ray from an arbitrary point toward the camera, intersect this line with the image plane, and verify that the coordinates of the intersection point in the plane's local frame match the projected coordinates provided by your matrix.

I'll leave this answer as a community wiki so it's easy to expand on this initial sketch.

---
Tags: mathematics, projection-matrix
---


# Question
Title: Any Code Based Driver Optimizations for Far-Object Rendering?
***Are there any video card driver optimizations available to developers*** to mitigate considerable framerate drops (%50+) which may be caused by Draw Distance defects in a game?

For example, when using a dependency injection pattern - to inject DirectX or Vulkan dependencies into the game library after the fact. (A game engine that may be reused, inefficient, and locked.)

Which cross-API driver features are there - to optimize framerate issues due to rendering distant objects. (LoD, etc.)

**Example :**

In a game zone, when the camera is redirected - there is a significant / sharp drop in framerate (50%+), due to the number / complexity of objects far away.

A good example of this is in Dark Souls 3, the Ringed City, Dredge Heap Bonfire.

# Answer
No, there is nothing that can be done at that point.

A GPU driver has no idea about Draw Distance, that is controlled by the farclip of the camera.

Its up to the developer to implement many of the optimizations you just mentioned, while mipmapping is built into the GPU that's sort of something that every game will use but it hasn't really got anything to do with far away objects. When an IHV makes driver optimizations its normally to do with the way the API is used and any funky shaders\usage patterns.
> 1 votes

---
Tags: optimization, level-of-detail, nvidia, filtering
---


title: How to automate the game

text:
# Question
Title: How to automate the game
I am new to game development and I have a game where the car moves and picks the monster.But now I want to automate the game so it looks like it is played automatically. The control keys are given by the update function which is as below:

```
update(){
        if (keys.ArrowUp) { // Player holding up
            this.y -= this.speed * frameTime;
            this.dir = Math.PI * 0; // set direction
        }
        if (keys.ArrowDown) { // Player holding down
            this.y += this.speed * frameTime;
            this.dir = Math.PI * 1; // set direction
          }
          if (keys.ArrowLeft) { // Player holding left
            this.x -= this.speed * frameTime;
            this.dir = Math.PI * 1.5; // set direction
        }
        if (keys.ArrowRight) { // Player holding right
            this.x += this.speed * frameTime;
            this.dir = Math.PI * 0.5; // set direction
        }
        if(Math.sign(this.speed) === -1){ // filp directio of second car
            this.dir += Math.PI; // set direction
        }

```

So Eventually I need this update function to be automated.Automated in the sense you can think of the one car moves 3 seconds straight and 3 seconds right and so on.But the other car follows a different movement. Incase my code is not sufficient the working pen is here and I just want to automate the process so that the cars move in different directions and the game is automated.

Any help is appreciated

# Answer
> 1 votes
Your Update function holds too many responsibilities. It looks like it currently is responsible for:

* Handling a tick
* Processing user input
* Updating car position
* Updating car direction

By delegating responsibilities you can simplify things enough so that you can do more things, such as moving computer controlled cars.

```
update(){
    if (keys.ArrowUp)
       MoveUp();
    else if (keys.ArrowDown)
       MoveDown();
    else if (keys.ArrowLeft)
       MoveLeft();
    else if (keys.ArrowRight)
       MoveRight();
    else
       Stop();
}

```

From there you can make a car into an independent class with many instances. With a single instance, the function will then look like this:

```
update(){
    if (keys.ArrowUp)
       playerCar.MoveUp();
    else if (keys.ArrowDown)
       playerCar.MoveDown();
    else if (keys.ArrowLeft)
       playerCar.MoveLeft();
    else if (keys.ArrowRight)
       playerCar.MoveRight();
    else
       playerCar.Stop();
}

```

You can now split off the responsibility of handling input:

```
 MoveEnum = {
    Up: 0,
    Down: 1,
    Left: 2,
    Right: 3
    Stop: 4
 }

 update(){
    var direction = MoveEnum.Stop;
    if (keys.ArrowUp)
       direction = MoveEnum.Up;
    else if (keys.ArrowDown)
       direction = MoveEnum.Down;
    else if (keys.ArrowLeft)
       direction = MoveEnum.Left;
    else if (keys.ArrowRight)
       direction = MoveEnum.Right;
    playerCar.Move(direction);
}

```

... and hand off the input handling into it's own function so we get:

```
update(){
    var direction = GetMoveDirection(keys);
    playerCar.Move(direction);
}

```

or

```
update(){
    playerCar.Move(GetMoveDirection(keys));
}

```

At this point, introducing computer controlled cars becomes easier:

```
update(){
    playerCar.Move(GetMoveDirection(keys));
    computerCar.Move(FigureOutComputerDirection());
}

```

The content of `FigureOutComputerDirection()` is up to you. If you just want to randomly move the car, you could for example look at the time and chose a new direction every second.

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


# Question
Title: Unity: how to change runtime code for different platforms?
**In Unity, how can I programmatically control what source code is compiled?**

I have a script with various `BuildPipeline.BuildPlayer` calls, allowing me to build all versions of my game. However, I'm using the AVPro Video asset to play video, and it doesn't support 32bit Mac. As such, I need to fall back other video playing code on 32bit Mac. There's no preprocessor directive to differentiate 32bit OSX (like you can do for other platforms https://docs.unity3d.com/Manual/PlatformDependentCompilation.html ).

However, since I'm building each version in sequence, it seems like I should be able to set some state so that during compilation, the right code is used. I tried this:

```
VersionHandler.onMac32 = true;
BuildPipeline.BuildPlayer(levels, path, BuildTarget.StandaloneOSXIntel, BuildOptions.None);
VersionHandler.onMac32 = false;

```

And then checking that static variable in game. However, that static is "never set", presumably because the the state of the variable during compilation doesn't affect the value at runtime. **Is there any other way I can "get at" the compiled code and set a flag for certain builds?**

As a fallback, I can manually swap code in every time I build for OSX 32-bit, but I'd prefer not to do that.

# Answer
This solution feels a bit hacky, but it works:

```
using System;

public static bool IsMac32() {
    #if (UNITY_STANDALONE_OSX)
    return IntPtr.Size == 4;
    #else
    return false;
    #endif
}

```
> 4 votes

---
Tags: unity, macos, build-process
---


title: Unity vr device support

text:
# Question
Title: Unity vr device support
I have been looking for a list of VR devices that unity supports (or that you can use to develop VR games with).

However i have been unable to find a list. Currently im looking at **BOBO VR Z4**

But to make sure i do not make any incorrect purchases so it would be really helpful to know supported devices.

Also it is worth noting i'm going to be using the newest version of Unity. (which is currently version 5.6)

# Answer
> 1 votes
After some googling Bobo VR Z4 should be supported via the cardboard platform of unity. (this is just a guess since I didn't test it).

---

The reason why there is no list of devices (but a list of platforms) is that some platforms are open.

The currently supported platforms can be found here

Occulus Platforms is for the occulus device, Gear VR is for the gear VR devices and so on

In short that would be (too) easy.

It gets more complicated with the google familiy of Cardboard and daydream devices. Those platforms are supported by various devices. Some better, some not that good. For daydream also the used smartphone has to support the platform.

A year ago I tested a couple of cardboard headsets and experienced really big differences in the quality of the (same) app (on the same smartphone). The prices have been between 3 Euro and ~ 70 Euro. More expensive isn't actually better.

I used this for my personal vr experiences (Eimolife Virtual Reality Headset). There seem to be a couple of models looking the same with different brand names. But for the price (10 Euro) it was the best choice for me.

When choosing a platform 2 advices: \- Either stick to a closed platform (benefit: all your customers/players will have the same headset = same experience) \- When choosing cardboard: pick a headset where the manufactorer publishes a cardboard profile (the qr code on some of the devices). This allows you to configure cardboard by scanning this qr code and get a good quality visual experience (at least for the part of the cardboard settings).

---
Tags: unity, virtual-reality
---


# Question
Title: Why does my regular (XB360) joystick work but my virtual one won't?
I have my input manager setup properly before you ask. I am trying to get a virtual joystick working (notably this one and I've tried Unity's included ones in the SA's too) but it simply won't work for some reason.

The thing of it is is that the 360 controller works but not the virtual joystick doesn't. Why not and how do I get it to work?

Code:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine;

public class PlayerController : MonoBehaviour {

    public float moveSpeed;
    private Rigidbody myRigidbody;

    private Vector3 moveInput;
    private Vector3 moveVelocity;

    private Camera mainCamera;

    public GunController theGun;

    public bool useController;
    public bool useAndroidControls;

    // Use this for initialization
    void Start ()
    {
        myRigidbody = GetComponent<Rigidbody>();
        mainCamera = FindObjectOfType<Camera>();
    }

    // Update is called once per frame
    void Update ()
    {
        moveInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
        moveVelocity = moveInput * moveSpeed;

        //Rotate with mouse.
        if (!useController)
        {
            Ray cameraRay = mainCamera.ScreenPointToRay(Input.mousePosition);
            Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
            float rayLength;

            if (groundPlane.Raycast(cameraRay, out rayLength))
            {
                Vector3 pointToLook = cameraRay.GetPoint(rayLength);
                Debug.DrawLine(cameraRay.origin, pointToLook, Color.blue);

                transform.LookAt(new Vector3(pointToLook.x, transform.position.y, pointToLook.z));
            }

            if (Input.GetMouseButtonDown(0))
            {
                theGun.isFiring = true;
            }
            if (Input.GetMouseButtonUp(0))
            {
                theGun.isFiring = false;
            }
        }
        if (useAndroidControls)
        {

        }

        //Rotae with controller

        if (useController)
        {
            Vector3 playerDirection = Vector3.right * Input.GetAxisRaw("RHorizontal") + Vector3.forward * -Input.GetAxisRaw("RVertical");
            if(playerDirection.sqrMagnitude > 0.0f)
            {
                transform.rotation = Quaternion.LookRotation(playerDirection, Vector3.up);
            }
            moveInput = new Vector3(Input.GetAxisRaw("LHorizontal"), 0f, Input.GetAxisRaw("LVertical"));
            moveVelocity = moveInput * moveSpeed;
        }
    }

    void FixedUpdate()
    {
        myRigidbody.velocity = moveVelocity;
    }
}

```

Input Manager Screenshot:

Also I'm aware of third-party extensions that can help but I'd rather do this for free and not resort to that.

# Answer
> 1 votes
As the tutorial video says on their Unity page, you have to use the `CnInputManager` class in the `CnControls` namespace instead of the `Input` class:

```
CnInputManager.getAxis("yourAxis")

```

---
Tags: unity, c#, android, input, joystick
---


title: Why is the mana regenerating too fast?

text:
# Question
Title: Why is the mana regenerating too fast?
So I got this weird problem with regeneration - I decided to create a mana bar which is going down every time when character attack. When the bar is less than integer 100, it should regenerate 1 points per 9 seconds and then stop. The problem is that instead of it, mana regenerate rapidly after chosen time and then, with every attack it regenerate so fast, that is basically staying in same place.

```
        ////MANA REGENERATION
        currentTime += gameTime.ElapsedGameTime.Milliseconds;
        if (max_mana>=0 && max_mana <= 100 &&currentTime >= 9000)
        {
            max_mana += 1;
        }

```

that's the parameters for the mana:

in Initialize:

```
   //PLAYER MANA RECTANGLE

    Texture2D manabar;
    Vector2 posManaBar;
    Rectangle recManaBar;
    //REGENERATION TIME FOR MANA

    int max_mana;
    float currentTime = 0;

```

In drawGameplay:

```
        //PLAYER MANA
        spriteBatch.Draw(backBar, posManaBar, recBackBar, Color.Gray);
        spriteBatch.Draw(manabar, posManaBar, recManaBar, Color.Blue);
        recManaBar.Width = max_mana;

```

# Answer
> 4 votes
You forgot to reset your `currentTime` variable. Do it like this instead:

```
    ////MANA REGENERATION
    currentTime += gameTime.ElapsedGameTime.Milliseconds;
    if (max_mana>=0 && max_mana <= 100 &&currentTime >= 9000)
    {
        currentTime = 0;
        max_mana += 1;
    }

```

That way, you're resetting your timer every time you add a mana point to your `max_mana` variable.

---
Tags: c#, monogame
---


# Question
Title: How to remember a non-consumable Unity IAP the right way
I have implemented Unity 5's IAP system through Google Play. I read a few guides that mention not to store completed purchases in `PlayerPrefs` because it is clear text and easy to hack, but none mention the correct way to "remember" purchases. For example, when re-installing an Anroid app, purchases are restored the first time the app runs by individual calls to this method defined in the Unity IAP API.

```
public PurchaseProcessingResult ProcessPurchase (PurchaseEventArgs e)
    {
        //my Playerpref save that I want to avoid is here.
        return PurchaseProcessingResult.Complete;
    }

```

On subsuqent app runs, this method is not called again. Is there a way to query past purchases other than saving them in `PlayerPrefs`?

# Answer
> 3 votes
on Android the storeController has a list of purchased products when initialized successfully. So then you can use code that looks something like this and check if the item is bought :

```
Product product = storeController.products.WithID(productId);
 if (product != null && product.hasReceipt)
 {
     // Owned Non Consumables and Subscriptions should always have receipts.
     // So here the Non Consumable product has already been bought.
     itemBought = true;
 }

```

Restoring purchases is not needed on the Android platform. It is only needed on iOS.

---
Tags: unity, in-app-purchase
---


# Question
Title: How to assign game objects to a script without dragging and dropping into inspector?
So I have a script for getting into a car which, when mouse down is detected on the given game object it will teleport the player to the car, turn of the player's controller, and switch the player camera to the car camera.

The problem is I don't want to have to drag and drop the car game object, the player game object, and both cameras into the inspector for it to work.

Instead I would like it to have the script assign all those game objects based on the player who clicked on the car. Those game objects being the car the player, and the two cameras(one parented to the player and the other parented to the car). I have no clue how to go about this so I appreciate any help all the more.

Here is a picture of the inspector with the player script:

Also here is my C# code:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GetInCar : MonoBehaviour {
    public GameObject player;
    public GameObject car;
    public Camera CarCam;
    public Camera PlayerCam;

    void Start ()
    {
    }

    void OnMouseDown ()
    {
        if (Input.GetKey (KeyCode.Mouse0))
        {
            player.transform.position = car.transform.position;
            print("MovedToCar");
            GameObject.Find ("Player").GetComponent<CharacterController> ().enabled = false;
            PlayerCam.enabled = false;
            CarCam.enabled = true;
        }
    }
}

```

# Answer
> 1 votes
I would not use "OnMouseDown()" on the car script but instead use a raycast from the player script, e.g. in the player script:

```
void Update(){

    if(Input.GetKey(KeyCode.Mouse0)){

        RaycastHit rayInfo;
        if(Physics.Raycast(transform.position, transform.forward, out rayInfo)){

            GetInCar gic = rayInfo.collider.GetComponentInParent<GetInCar>();
            if(gic != null){ // If it is null, then it probably is the wrong object.
                // [...]
                // Here you can call some method like "gic.GetIn(CharacterController c)"
                // where c is the player script.
            }

        }

    }

}

```

Note that this example will have to be modified slightly if your player has a collider object (this can be achieved with layer-based collision detection)

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