# Question
Title: Could neural networks be used in order to build a better AI system?
Currently, I am researching both about Finite State Machines and Neural Networks in order to design AI for my game. I have searched a lot and I see that people usually use FSM because they are predictable and easier to implement. But should one discard the power of neural networks at all in game development? I am well aware of the intelligent systems that are made with the help of neural networks outside the game development area and for me it raises a curios flag about whether these could be used in order to achieve a much more complex and challenging AI in games.

In my vision, this is how one could think about using them. The developer could create the neural network system and train the AI for a time in prototype project. Once the AI becomes good enough, the developer could move the system and its most recent network data ( for example the weights of the connections and the neurons themselves) into the main project.

I have not built any serious AI up to this moment, but I think this could an imaginative development exercise. So, what is your take on this subject? Are developers using neural networks at this moment or could these really yield some outstanding AI systems?

# Answer
I tried doing just this. I found that FSM's are much nicer because you can't tell why a NN does what it does or tweak it that well unless you have in fact discovered why. But things like this have already been said so let me focus on something new:

A thing that people seem to forget is that a neural network is not some trivial thing to pop into existence, it takes time to train it properly unless your inputs are very minimalist. In a game environment, depending on how complex it is you could end up with some training time issues.

We haven't even discussed proper statistics collections. Talk to any ML researcher and they will tell you that the difference between a good and bad AI designer is that the statisticians know what data to collect, whereas the inexperienced will not (or feed it data that might better to not be sent).

Also seeing people go completely with neural nets has shown some results that are not that great. There was a competition recently and I was disappointed with the result (especially when one team had supercomputers to train them on). The results showed it was not the holy grail I thought it would be.

If your AI goes buggy on the client due to a neural network doing something unexpected, it's likely a lot more irritating to debug. Suppose you change a level or want it to adapt to a new level, do you have to discard all your trained data and start fresh? How can you make it scale to different skill levels?

I don't think we're quite there with neural networks but there are somethings you can extract from it though.
> 2 votes

# Answer
There were quite a lot of experiments with *actual* AI here and there, but besides a few gimmicky games (like the Creatures series), few made it to actual release. Other games like Black&White started out with the vision of neural network based AI, but in the end resorted to decision trees.

The main problem is that your usual objective when you develop video game AI is not to develop an unbeatable AI. You want an AI actor to play a specific role in your game. That means you want an actor who is interesting to play with, which is usually *not* the most ideal behavior. And that's something you will have a very hard time teaching to a neural network.

In the few cases where you *do* want an AI which is as effective as possible, for example in a turn-based strategy game, "traditional" solutions like MiniMax or Monte Carlo Tree Search usually still outperform neural networks.
> 1 votes

# Answer
Short Answer : Yes, not should be hard.

Long Answer ;

**Finite State Machine**

In fact, FSM and NeuralNetowrk are different things depending on where you look. In theory, FSM usually control your logic in asynchronous.

Give an example for this ;

```
BootState : State (When your app is booting)

GameState -> State (inheritance) (For only OOP logic)

MenuState : GameState (When your app state changed from boot to menu)
MainState : GameState (Your main logic)

GameStatusState -> GameState (inheritance) (For control some status)

WinState  : GameStatusState (When won a game)
LoseState : GameStatusState (When lose a game)

bla. bla. bla...

```

**Neural Networks**

A very complex and detailed subject. You can research from many sources on internet. Our subject isn't to explain it how to work, how to make etc.

https://en.wikipedia.org/wiki/Artificial\_neural\_network

Let's go to our actual subject.

**Neural Networks With Finite State Machine**

You can look like the example I gave you first. I have worked a little on this subject. Even if it is not a very detailed answer, I can give my own examples used in my games.

Some scripts are required ;

* `StateMachine` -\> Main FSM class to control some things like ;

1. CurrentState, PreviousState, Transition etc.
* `StateMachineController` -\> Control to StateMachine. A singleton, An Instance.
* `State` -\> Main base state class. We will use it for inheritance and some functions like ;

1. void Initialize(StateMachine stateMachine, StateMachineController controller);
    2. Enter, Exit, Update etc.
* `StateComponent` -\> A base class for other states.

1. We need to store come variables like : State, OldState, StateMachine, SharedStates (For other states) etc.
* `AIStateBehaviour` -\> We realy need this for control main logic. Like ;

1. Transform, Rigidbody, Positions, Speed, Animations, Movement, Control bounds, virtual effects like freeze, poison, stunned and everything that might come to mind... !I.M.A.N.I.G.A.T.I.O.N!

Note: `AIStateBehaviour` needs a controller class for control sometings. We can say "Neural States".

I found a picture, showing how it should be structured like a neural networks.
* Now, you can inheritance everythink like AIPerson, AIMonster (AIBird and AIBirdInterFaces, AIFish and AIFishInterfaces, etc... ) from AIStateBehaviour.
* As a result, We can control every AI action with neural networks. All neural transitions have to be chosen best way according to the values coming from anythings.
* Some useful keywords you can searh from Google ;

1. `State Machine Design`
    2. `Neural Network Design`
    3. `Finite State Machine`
> 0 votes

---
Tags: game-design, ai, game-mechanics
---


# Question
Title: Are there any way to stop Unity from upgrading a shader?
A projector shader using the `_Projector` attribute will be changed to use `unity_Projector`, instead, in Unity 5.5. I'm writing an editor plugin that works on multiple versions of Unity. Such upgrading will make the shader not work in earlier version of Unity.

Is there any way to stop such upgrading?

# Answer
You can prevent Unity from upgrading a shader by adding `UNITY_SHADER_NO_UPGRADE` somewhere in the shader, like in a comment at the top of the file. This was added in Unity 5.4.
> 3 votes

---
Tags: unity, shaders
---


# Question
Title: How to make this generated terrain flat-shaded?
I'm generating a relatively low-poly terrain for my game using the code below:

```
for (int z = 0; z < VERTEX_COUNT; z++) {
    for (int x = 0; x < VERTEX_COUNT; x++) {
        final float posX = x / ((float) VERTEX_COUNT - 1) * SIZE;
        final float height = generateHeight(x, z);
        final float posY = height;
        final float posZ = z / ((float) VERTEX_COUNT - 1) * SIZE;
        final Vector3 nor = getNormals(x, z);
        final float norX = nor.x;
        final float norY = nor.y;
        final float norZ = nor.z;
        final float texU = x / ((float) VERTEX_COUNT - 1);
        final float texV = z / ((float) VERTEX_COUNT - 1);

        // Create vertex
    }
}

for (int z = 0; z < VERTEX_COUNT - 1; z++) {
    for (int x = 0; x < VERTEX_COUNT - 1; x++) {
        final int topLeft = (z * VERTEX_COUNT) + x;
        final int topRight = topLeft + 1;
        final int bottomLeft = ((z + 1) * VERTEX_COUNT) + x;
        final int bottomRight = bottomLeft + 1;

        //Triangle 1: topLeft - bottomLeft - topRight
        //Triangle 2: topRight - bottomLeft - mottomRight
    }
}

private Vector3 getNormals(final int x, final int z) {
    final float heightL = generateHeight(x - 1, z);
    final float heightR = generateHeight(x + 1, z);
    final float heightD = generateHeight(x, z - 1);
    final float heightU = generateHeight(x, z + 1);
    return new Vector3(heightL - heightR, 2f, heightD - heightU).nor();
}

```

This works perfectly fine and generates a smooth terrain mesh. The problem is I want this mesh to use flat shading; i.e. I don't want vertices to be shared between triangles. But I don't know how I would duplicate the vertices and find the appropriate indices to properly index the mesh. Any help?

Here's in image from google in case it wasn't clear (left shading is what I want, right is what I have):

---

P.S. I found this code for the Unity scripting language:

```
Vector3[] oldVerts = mesh.vertices;
int[] triangles = mesh.triangles;
Vector3[] vertices = new Vector3[triangles.Length];
for (int i = 0; i < triangles.Length; i++) {
    vertices[i] = oldVerts[triangles[i]];
    triangles[i] = i;
}
mesh.vertices = vertices;
mesh.triangles = triangles;

```

Perhaps this is the solution I'm looking for? If so, how can I translate this code to using `float[]` instead of `Vector3[]` array for my vertices? And what is the `triangles` array, the indices?

# Answer
> 2 votes
This can be achieved in 2 ways.

The first is very simple, and is how ThinMatrix did it in his game. When you pass the normal from the vertex shader to the fragment shader, apply the `flat` attribute to it:

```
flat in vec3 normal;

```

The second way is harder and uses more resources, but it's more flexible. You basically have to insert every triangle separately. Your VBO should look something like this:

```
0, 0.5, 0,  // pos1  }
0, 0.6, 1,  // pos2  }  first triangle
1, 0.7, 0,  // pos3  }

1, 0.7, 0,  // pos 4 }
0, 0.6, 1,  // pos 5 }  second triangle
1, 0.7, 1   // pos 6 }

```

You don't need an index buffer if you do this, you can use `glDrawArrays`.

---
Tags: java, 3d, terrain-rendering, shading
---


title: GL_CLAMP_TO_BORDER - OpenGL ES 3

text:
# Question
Title: GL_CLAMP_TO_BORDER - OpenGL ES 3
W want to use `GL_CLAMP_TO_BORDER` in my GL ES 3 app. Based on documentation (https://www.khronos.org/registry/OpenGL-Refpages/es3/html/glTexParameter.xhtml), it seems to be supported, however, on iOS this `#define` is not present. Is it named differently? Maybe some extension?

# Answer
GL\_CLAMP\_TO\_BORDER became legal in GL ES 3.2 (link to specification), but may otherwise be available by one (or more) of the following extensions:

In the absence of one (or more) of these extensions, or if using an earlier version of GL ES, GL\_CLAMP\_TO\_BORDER mode is *not* specified, and specifying a non-zero *border* value with your glTexImage parameters is documented to generate a GL\_INVALID\_VALUE error.

You are evidently working from an out-of-date header file, but you should also check that your hardware and driver are compatible.
> 3 votes

---
Tags: ios, opengl-es
---


# Question
Title: Unity 3d C# - Can’t move through the air while jumping
The code below allows my character to jump and move which works fine, except I can't move while jumping. I can jump in one place or jump in a certain direction but nothing else. I can't fix it, can someone help?

```
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;

public class PlayerMotor : MonoBehaviour {

private CharacterController controller;

public float speed = 1.0F;
public float jumpSpeed = 1.0F;
public float gravity = 1.0F;
private Vector3 moveDirection = Vector3.zero;
void Update() {
    CharacterController controller = GetComponent<CharacterController>();
    if (controller.isGrounded) {
        moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
        moveDirection = transform.TransformDirection(moveDirection);
        moveDirection *= speed;
        if (Input.GetButton ("Jump")) {
            moveDirection.y = jumpSpeed;
        }
    }
    moveDirection.y -= gravity * Time.deltaTime;
    controller.Move(moveDirection * Time.deltaTime);
}

```

Thanks in advance :)

# Answer
What you've implemented is called ballistic jumping. It's a perfectly realistic way to handle jumping — after all, in real life we can't change direction in mid-air after jumping — but it turns out to be awful for gameplay. The problem is that, in real life, we can pretty accurately control our direction and speed *before* jumping, and thus land more or less where we want. A game controller or, worse yet, a keyboard doesn't provide such fine motor control, making ballistic jumps really hard to predict and control.

The usual solution is to cheat physics a bit, and allow some degree of steering even while jumping or falling. This turns out to be really intuitive to players, even if they haven't encountered it before (which, of course, is pretty rare nowadays, except for small children): when you notice that your jump isn't going to land where you want, the instinctive impulse is to try and steer in the direction you want to go, even if real-life physics says it should be useless.

Some games go so far as to leave the player with full horizontal movement control while jumping, and letting physics only control the vertical movement. You could implement such jumping e.g. like this (warning: untested code, may contain bugs or typos!):

```
private float verticalVelocity = 0;
void Update() {
    CharacterController controller = GetComponent<CharacterController>();
    if (controller.isGrounded) {
        if (Input.GetButton ("Jump")) {
            verticalVelocity = jumpSpeed;
        } else {
            verticalVelocity = 0;
        }
    } else {
        verticalVelocity -= gravity * Time.deltaTime;
    }
    Vector3 moveDirection = new Vector3(Input.GetAxis("Horizontal") * speed, verticalVelocity, Input.GetAxis("Vertical") * speed);
    moveDirection = transform.TransformDirection(moveDirection);
    controller.Move(moveDirection * Time.deltaTime);
}

```

Alternatively, you can keep jumping mostly ballistic, but allow limited directional control in air:

```
private Vector3 jumpVelocity = Vector3.zero;
void Update() {
    CharacterController controller = GetComponent<CharacterController>();
    Vector3 moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
    moveDirection = transform.TransformDirection(moveDirection);
    if (controller.isGrounded) {
        moveDirection *= groundSpeed;
        if (Input.GetButton ("Jump")) {
            jumpVelocity = moveDirection;
            jumpVelocity.y = jumpSpeed;
        } else {
            jumpVelocity = Vector3.zero;
        }
    } else {
        moveDirection *= midairSpeed;
        jumpVelocity.y -= gravity * Time.deltaTime;
    }
    controller.Move((moveDirection + jumpVelocity) * Time.deltaTime);
}

```
> 1 votes

# Answer
It is because your horizontal movement is managed inside the controller.isGrounded block. to handle horizontal movements when jumping you should remove that block from there and for the sake of better air movements, i've added an air friction parameter so the player movements are slower while in air. Also put the CharacterController reference in the start, because GetComponent() shouldn't be used in Update():

```
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;

public class PlayerMotor : MonoBehaviour {

private CharacterController controller;

public float speed = 1.0F;
public float jumpSpeed = 1.0F;
public float gravity = 1.0F;
public float airFriction = 0.5f;

private Vector3 moveDirection = Vector3.zero;

void Start(){
    controller = GetComponent<CharacterController>();
}

void Update() {
    moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
    moveDirection = transform.TransformDirection(moveDirection);
    moveDirection *= speed;
    if (controller.isGrounded) {
        if (Input.GetButton ("Jump")) {
            moveDirection.y = jumpSpeed;
        }
    } else {
        moveDirection *= airFriction;
    }
    moveDirection.y -= gravity * Time.deltaTime;
    controller.Move(moveDirection * Time.deltaTime);
}

```
> 1 votes

---
Tags: unity, c#, 3d
---


title: View Matrix FINDING U

text:
# Question
Title: View Matrix FINDING U
T\<----------------------Q

While making a view matrix, I usually cross product a (0,1,0) with W TO GET U W = (T-Q)/||T-Q|| U = (W X (0,1,0)/||W X (0,1,0) v = w x u this works most of the time. But what about when I want to go y axis and look straight down at 0,0,0

What would be the value of the vector? (0,1,0) does not work. Tried every combination even negatives and didn't work.

# Answer
You can't. You have to change your "up" vector (0, 1, 0) to something else when you're pointing down or up.

There are many solutions to this that all depend on how you want it to look.

One solution is to "unlock" your camera's up vector once you reach a certain threshold and keep replacing (0, 1, 0) with your last up vector. When to transition between unlocking and re-locking your camera's up vector to (0, 1, 0) or (0, -1, 0) is up to you.

Some games just prevent you from getting too close to your up / down vector.
> 1 votes

---
Tags: mathematics, vector, matrix
---


title: Instantiated object can't be parented

text:
# Question
Title: Instantiated object can't be parented
I'm writing a script (in C#) which, on mouse down, will spawn a gun and parent it to a game object. But for some reason the gun is instantiated just fine, but it doesn't parent. I have an empty game object called "Hands" and I'm trying to have the gun become a child and be moved to the position of "Hands".

To test what was going on I made two scripts, one which would parent the object upon pressing `P`, while the other script would just instantiate the item on mouse down. It worked, I first spawned the gun with mouse down, and then pressed `P` and it was parented. So my only guess is that you can't instantiate and parent in the same script all at the same time.

I have absolutely no clue what's going on, so I really appreciate any help I can get.

This is my code:

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

public class GiveWeapon : MonoBehaviour {

  public GameObject Weapon;
  public GameObject Hands;

  void OnMouseDown ()
  {
    Instantiate(Weapon);
    Hands = GameObject.Find ("Hands");
    Weapon.transform.parent = Hands.transform;
    Weapon.transform.position = Hands.transform.position;
  }
}

```

# Answer
This will fix your problem:

```
public class GiveWeapon : MonoBehaviour {

  public GameObject Weapon;
  public GameObject Hands;

  void OnMouseDown ()
  {
    Instantiate(Weapon, Hands.transform.position, Quaternion.identity, Hands.transform);
  }
}

```
> 3 votes

# Answer
You are trying to parent the "source" you used in the Instantiation, not the "clone" or "new object" in other words.

What you need to do is store the new object in a local variable, and use that when you do parenting.

So here is the correct form:

```
var newWeapon = Instantiate (Weapon) as GameObject;
Hands = GameObject.Find ("Hands");
newWeapon.transform.parent = Hands.transform;
Weapon.transform.position = Hands.transform.position;

```

But, there is an easier way. You can specify the parent explicitly in the arguments of `Instantiate` method. Check out the documentation of `Instantiate` method and you will see the appropriate overload for your case.

Here is a link to the documentation page of Instantiate method.
> 2 votes

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


# Question
Title: How To Animate Skeletal Interactions (Hugging, Handshakes etc.)
I am fairly new to animating and IK systems, but I've got the basics down to some extend. Now I am looking into how to go about skeletal actor animation interactions such as handshakes, fighting, horse riding, hugging or sex animations and such, to be used in unreal engine 4. I would like someone to point me into the right direction on how to go about this.

As I am new to this, if the question is too broad or vague please do let me know.

# Answer
Example: Character A is touching with the hand on character B's Head. In content, you need to define **the offset** to your attachment. So you would create a bone under Character's A's hand, and then constrain it to the Head of character B.

In the engine, you then IK the hand from character A to the Head of character B, but you add the (inverted) offset that is stored (and animated) with your offset bone. That way it is attached but animated.

This is a general answer - the exact clicks/code-pieces you need to do in Unreal Engine 4 I can't answer.
> 1 votes

---
Tags: animation, unreal-4, skeletal-animation, 3dsmax
---


# Question
Title: Box2D : rotate and set position to a static body with another origin
I try to rotate a static body of a `PolygonShape`, from another origin, and set the position regarding this new origin.

Why ? Because I create bodies from TiledMapEditor object. And origins of objects in this editor are in the left upper corner.

Regarding the documentation, I can set origin using the `setAsBox` method. But then when I set the position, the body is not where it is supposed to be. (an offset is apply between the current position and the expected position)

I assume that the origin is used for the rotation, but not the position.

How can I set the position from another origin, and rotating from this same origin ? (the upper left corner and not the center of the shape)

My attempt :

```
  val rotation = 45f // rotation angle (in degree)
  val shape = PolygonShape()
  shape.setAsBox(rectangle.width*0.5f, // half width
                rectangle.height*0.5f, // half height
                Vector2(0f, rectangle.height), // new origin
                rotation * MathUtils.degreesToRadians) // angle to radians

   val bodyDef = BodyDef()
   bodyDef.type = BodyDef.BodyType.StaticBody
   bodyDef.position.set(rectangle.x, rectangle.y) // set the position

```

Regards

# Answer
> 1 votes
Simple! Use a kinematic body!

> "A dynamic body is a body which is affected by world forces and react to collisions. And you already met a million of them."
>
> "A static body is a body which isn’t affected by world forces it does not react to collisions. It can’t be moved. Fullstop."
>
> "A kinematic body is an hybrid body which is not affected by forces and collisions like a static body but can moved with a linear velocity like a dynamic body."

-Source: http://www.emanueleferonato.com/2012/05/11/understanding-box2d-kinematic-bodies/

To put it another way, kinematic bodies are very similar to static bodies, however, you can't translate, rotate, move, etc. static bodies because static bodies are... **static**! It should be very simple to update your code, just replace *StaticBody* with *KinematicBody* and then the objects should be moveable.

Kinematic bodies are the in-between of dynamic bodies and static bodies. Static bodies are frozen and unaffected by outside physics, while dynamic bodies are affected by forces, gravity, angular momentum, etc. Kinematic bodies should be used only when necessary for an object to be manipulated through code. Remember that you can't apply a force to a kinematic body but it can be translated and rotated.

# Answer
> 1 votes
> Regarding the documentation, I can set origin using the setAsBox method. But then when I set the position, the body is not where it is supposed to be. (an offset is apply between the current position and the expected position)

Seems like there's some confusion going on about what does what.

> I assume that the origin is used for the rotation, but not the position.

To quote a line from a movie I love: "get specific Bob"!

> How can I set the position from another origin, and rotating from this same origin ? (the upper left corner and not the center of the shape)

Allow me to explain...

In Box2D 2.3.2, there is a notion of **world** coordinates and there is the notion of **local** coordinates.

World coordinates are just that. They're 2-D cartesian coordinate locations within an instance of a Box2D world. As cartesian coordinates, they have an *origin*. In Box2D the world *origin* is at location (0, 0). In a sense, this origin can be shifted by calling the `b2World::ShiftOrigin(const b2Vec2& newOrigin)` C++ method. But in another sense, that's just moving everything within the world over by the `newOrigin` amount and the origin is essentially still and always at (0, 0). For the sake of this answer though, lets agree to say that the **world origin** is at (0, 0) in the 2-D world space.

Local coordinates meanwhile, are coordinates that are relative to a Box2D body's location. Specifically they're relative to the location returned by the `b2Body::GetPosition()` C++ method (which is given by the positional portion of the body's transformation). Thus the *origin* of local coordinates is effectively the world location of the body the local coordinates are relative to. Let's then agree to call this origin the **local origin** of that body, say that it's values are also (0, 0), and recognize that this *local origin* is relative to the world location of the body.

With these understandings and definitions, recognize that the third and fourth parameters to `shape.setAsBox` are relative to the transformation of the body (the body's combined translation and rotation matrices) that the shape is associated with. In the Box2D 2.3.2 C++ sources for the polygon shape you're using, is the following documentation that goes with this method:

```
/// Build vertices to represent an oriented box.
/// @param hx the half-width.
/// @param hy the half-height.
/// @param center the center of the box in local coordinates.
/// @param angle the rotation of the box in local coordinates.
void SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle);

```

In your code example that reads as:

```
shape.setAsBox(rectangle.width*0.5f, // half width
               rectangle.height*0.5f, // half height
               Vector2(0f, rectangle.height), // new origin
               rotation * MathUtils.degreesToRadians) // angle to radians

```

Here you are configuring a rectangle that's centered at *local* coordinates of (0, `rectangle.height`) and rotated about this center by `rotation` radians. And this is all relative to the transformation of the associated body.

So now let's move on to a later piece of code you provided:

```
bodyDef.position.set(rectangle.x, rectangle.y) // set the position

```

Now you're setting the world location of the body to be at (`rectangle.x`, `rectangle.y`). This means that the rectangular polygon shape that you set up is - in terms of world coordinates - now centered at (`rectangle.x`, `rectangle.y + rectangle.height`). It also means, that if the body's angular orientation is changed, the rectangle will be both translated and rotated since the rectangle is vertically offset from the center of the body. You can think of the rectangle as being like the metal head of a hammer that's swung about the end of its handle now.

It sounds however like what you want is to have the rectangle centered on the local origin of the body but you also want the rectangle initially angularly oriented by 45 degrees counter-clockwise from the local X axis. Taking care of the center should then just be a matter of calling `shape.setAsBox` with the third parameter - the "center" - set to `Vector2(0f, 0f)`. As to the angular orientation then, you have two choices:

1. Set the angular orientation of the rectangle via the fourth parameter to `shape.setAsBox` (like you're doing); or
2. instead set the angular orientation of the body via the angle parameter of your `bodyDef` structure.

Personally, I prefer choice #2 for bodies that are only going to have a single associated shape. That way when the body has an angular position of 0 radians, everything is level like I'd expect it to be.

So lets revisit the three parts I quoted from your question:

1. The body is where you told it to be and the shape associated with that body is where you told it to be as well. The shape however isn't where you expected it to be presumably because the interfaces you're using didn't make it clear enough for you to use them correctly. While I'm not the original author of Box2D nor the author of the port of Box2D that you're using, I can empathize with any frustration anyone has with unknowingly misusing an API. I agree with Scott Meyer's assertion of "Make interfaces easy to use correctly and hard to use incorrectly". I'm not sure how this API could be changed however to make it harder to use incorrectly insofar as body and shape positioning is concerned.
2. The **local origin** is used for local locations or local angles except in this case where the local center is changed making it effectively the new local origin as far as the local angle is concerned.
3. The world coordinate location of a shape can be set by either setting its body's location or by setting the center of the rectangle to be offset from the body's location enough so that in sum the location of the rectangle is where you want it. Regarding "rotating" the shape, it can be rotated about its center using the fourth parameter of `shape.setAsBox` or if it's center is (0, 0) then it can also be rotated about its center by rotating the body's angular position.

Lastly, people have suggested that static bodies can't be rotated or moved. That's not necessarily correct. That depends on what people expect from this rotation or movement. There's nothing in the Box2D 2.3.2 implementation of the `b2Body::SetTransform` method for instance that will reject changing a body's transform based on it being a static body (nor other type). The body's linear and/or angular position can be changed regardless of what type of body it is. The problem however is like the comment for this method states:

> Manipulating a body's transform may cause non-physical behavior.

In practice, calling this method is like making the body go through a Star Trek like transporter. The body is instantly at the new linear and angular position it's told to be at. If we think of a straight line between where it was and where it is after setting its transform, physical behavior would have required anything in this path to have been collided with but that won't happen when using the set transform method.

If you don't want non-physical behavior however, then like has been suggested, you'll want to use one of the other body types as others have addressed.

Hope this makes things clearer and addresses what it seems you were really wondering about.

---
Tags: libgdx, box2d
---


# Question
Title: Why is my Unity scene prefab auto-changing?
I have some prefabs which are instantiated in game. There are some attributes of prefabs such as size(width, height), text string and color which are changed from code. Well, it is working fine. However, some prefabs changed attributes are being applied permanently.

For example, one prefabs color is changed to red while playing the game. Then, I stop the game using the Editor's "Play" button, and if run the game again, that prefab is still instantiated with the red color.

It happens when I stop the game in the middle of running from the Editor, and the game object in the scene Hierarchy replaces the main game object in the prefab folder.

Why is my Unity scene prefab auto-changing?

# Answer
> 0 votes
Actually I was passing the GameObjects to a function by reference. In that I function several objects are instantiated and changed according to logic. As a reference of main GameObject was instantiated and Changed, it also changed the folders' prefabs. Now, I've declared a Global array and am not passing any parameter to that function. Instantiating direct from that Global array solved the problem. Thanks to @Tartle Wizard

---
Tags: unity, gameobject
---


# Question
Title: How can I architecture the cards and boards of this board game?
I want to create a board game (at least it's structure and engine, not the graphics), and since It's the first time I do this I don't know where to start.

It's a turn based strategy card game where cards that act differently, some are placed and moved on the board, some are placed but don't move, and some are played from the hand but not placed on the board.

Well, I don't know how to translate this to code. I thought that I should have a `interface` for the Cards, but since there are various types of cards that act very differently it doesn't make sense . Then I thought that there should be a `class` for each `Player` which stores which of his cards are played, which are left etc.. Something like this:

```
public Class Player
{
 private List<Card> PlayableCards;
 private List<Card> OutOfGameCards;
}

```

But there's a fixed amount of cards of each type, so its useless to have a `List<T>` (besides as I said I don't think I'll have a `Card` class). Then How should I approach this? Having the cards as individual variables? It doesn't sound right.

The next thing is the Board, it's formed by 8x8 squares where the cards are placed. How do I identify each placed card with a card in the code?

Maybe something like this:

```
public Class GameBoard
{
 private Square[][] SquareGrid;
}

```

If I do it this way its easy to separate each square and access it by it's position (`SquareGrid[3][4]=3x4`). But do I store which card is in each Square? Or do I store in which square is each card? After that there's a "special zone" outside this board and everything gets more messy.

# Answer
If you look at a lot of the verbs in card games, like *draw*, *discard*, *play*, *shuffle*, these can all be generalised as **moving cards between zones**. I used these concepts in a card game, which had these core types:

* **Cards**, which describe the card in isolation
* **Zones**, which contain cards and dictate how you can move or use cards within them

Anything that holds cards is a **zone**, and most zones will have special rules:

* A **Hand** is a zone that is only visible to a single **Player**
* A **Deck** is a zone that is invisible, and only permits drawing (removing) cards from the top
* (In poker) the **Community Cards** is a zone that is visible to all players, but, depending on the game, has a maximum card limit, and can only be added to, or shuffled back into the deck at the end of a round

I would argue that it's easier for the zones to store which cards are in them, and not the other way around, because it's more natural to examine zones and find all the cards within them.
> 1 votes

# Answer
The answer is going to depend on some more specifics about the design of the game, so I'll be making some assumptions:

1. Discarded cards are no longer relevant to the game. Unlike games similar to Magic the Gathering, where the "graveyard" can come back into play. This also doesn't mean we can't reshuffle a deck if cards run out, e.g. Monopoly Chance cards.
2. The cards themselves aren't actors. Again, something we'd see in Magic the Gathering. There's a lot of card games where cards have meta effects, changing game mechanics.
3. As a turn based game, we don't need to over optimize for performance.

With those, here's some suggestions on how to organize your data.

## The Deck

Create a class for your Deck. If you are certain what cards will be used, for example a standard poker deck, feel free to hard code them in there. Otherwise, maybe have the Deck object take a list of cards in its constructor.

We'll need some form of a "shuffle" to ensure players get random cards. The basic approach is to hold some flag that tells you if a card has already been chosen. Then each draw is as follows:

* Select a random index
* Check if the index hasn't been drawn, if so select again
* Draw that card
* Mark that index as chosen

There's a chance of those first two steps repeating quite a bit when the number of cards left gets low.

I'd suggest Deck having a Shuffle method, that produces a list of cards by selecting at random until all cards have been chosen. Then each turn you just move one ahead in that list. This will also help you keep count how many cards are left, and let you do some look ahead if you want to make a cheating AI or anything.

## Player's Hands

Keep this simple, just a list of cards that they have. This is where the assumption of the discard no longer being important makes our lives simpler.

## Game Board

A matrix should work fine for this. We're assuming the cards don't change the board. I think you'll find that most of the time, you just need to know what cards are where. Player plays a card at 3,3 is there a card to the left or right of it, 3,2 3,1.

The assumption that the cards don't have behaviors makes this simple. If you aren't running unique code per card, then the code isn't being run from the card and it doesn't need to know where it is. Even if you do, it's still possible to have some lookup code Board.findCard(cardId) that gives the coordinates.
> 0 votes

---
Tags: c#, architecture, data-structure
---


# Question
Title: Do game engines put all interpolation onto the GPU?
Is it considered standard to push all the vertices and an interpolation of the next position onto the GPU?

Suppose a sector is moving up every game tick at 50 units per second. You could put on the shader something like (good old parametric equation-like formulas):

```
pos.x = a*x1 + (1 - a)*x0;

```

Where you'd calculate `a` as a uniform and only send this value to the GPU in an uncapped fashion, like so:

```
while (true) {
    a = percentage of the way between frames [in range from 0.0 to 1.0]
    updateGLUniform(..., a);
    render();

    // Rest of stuff

    delay();
}

```

The other way of doing it was to manually set each entity and sector every single time you loop, but then you might have to update the position of *a lot* of things every game cycle. Just setting one value seems way more efficient.

However, I don't know if there's any downsides to this. Are there any negatives to shoving interpolation off to the GPU to save computation time in the game? Or is there something that I'm missing? What do major games do?

# Answer
As written, your formula for `pos.x` always returns `x` no matter what value `a` takes:

```
pos.x = a*x + (1 - a)*x;

```

To get meaningful interpolation, we need to tell the GPU two positions to interpolate between,`x0` and `x1`, yielding:

```
pos.x = a*x1 + (1-a)*x0;

```

So now that's three variables we need to tell the GPU about, instead of just one position for this frame.

So if our `x0` and `x1` change frequently (as is the case for many types of motion we want to represent in games - think dynamic physics, nonlinear animations, anything with player input or AI), then we haven't really saved ourselves any bandwidth this way. In some cases, doing the interpolation GPU-side might require sending double the transformation data compared to computing a single set of interpolated transforms CPU-side.

This transform data also tends to be fairly sparse - one matrix per dynamic object - so compared to the massive workloads GPUs handle projecting, rasterizing, and shading every pixel of the scene, interpolating movement on the CPU is usually not a major bottleneck.

That's not to say there aren't many cases where interpolating a value on the GPU makes sense - there are indeed many. It's just not quite as universal a solution for all movement as it might appear at first.
> 3 votes

# Answer
This is a trade off.

With interpolation on the CPU you get to use a smaller vertex format, but you must dynamically update your vertex buffers from system memory to GPU memory every time.

With interpolation on the GPU you have a fatter vertex format but your vertex buffers can remain static.

In *general* the latter will be the more performant option. The amount of data transferred from system memory to GPU memory is unlikely to be an arbiter of performance, but on the other hand being able to avoid CPU/GPU synchronization is very important; particularly with APIs like older versions of OpenGL which are especially prone to synchronization.

As always, this is simple enough to code up both options and benchmark with your own workload and data.
> 2 votes

---
Tags: opengl, rendering, optimization
---


# Question
Title: Why does my libGDX TextureRegion.split code not work properly?
I am using scene2d in libGDX on Android as part of a game I am working on. I have a simple splash screen, which I am trying to display a single image on. The image comes from a file with two tiles in it, and I am using TextureRegion.split() to access it. My problem is, the entire image gets displayed instead of just the first tile.

Here are code snippets to illustrate what I am doing. You should be able to put this in a basic libGDX app to test it out. The image I am using is a png with dimensions of 460 width X 342, (2 tiles of 460X171). I am using the latest libGDX, as obtained from the libGDX setup tool.

What is wrong with my code?

```
TextureRegion[][] tiles =
    new TextureRegion(
        new Texture( Gdx.files.internal( "foo.png" ) ) )
            .split( 460, 171 );

Stage stage;
Table table;

stage = new Stage();
table = new Table();

table.setFillParent(true);
stage.addActor(table);

Texture fooTex = tiles[ 0 ][ 0 ].getTexture();

Image fooImg = new Image( fooTex );
fooImg.setPosition(
    ( Gdx.graphics.getWidth() / 2 ) - ( fooImg.getWidth() / 2 ),
    ( Gdx.graphics.getHeight() / 2 ) - ( fooImg.getHeight() / 2 ) );

stage.addActor( fooImg );

```

# Answer
> 1 votes
`TextureRegion#getTexture()` returns the *original* texture; i.e. the texture that it was split from. Use the actual `TextureRegion` (in your case, `tiles[0][0]`, not `tiles[0][0].getTexture()`). Your code should then become this:

```
TextureRegion fooTex = tiles[0][0];
Image fooImg = new Image(fooTex);

```

You can also use a static method to split your texture instead of creating a new texture region to do it for you:

```
TextureRegion[][] tiles = TextureRegion.split(new Texture(Gdx.files.internal("foo.png")), 460, 171);

```

---
Tags: java, android, libgdx, scene2d
---


# Question
Title: How do I make planet move slower the further away they are?
I got this code from somewhere else, I want to implement Kepler's third law to make the simulation look more realistic, the simulation is a 2D satellite orbiting around a planet, the satellite(Planet) script here is :

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

public class Planet : MonoBehaviour {
private float alpha; //will use for cos & sin (as angle)
private float distance;//distance from center
private float Rotation;//rotation angle
private float currentTime;//Time start when Instantiated
//input values
public float speed;
public Vector2 RotationValues;
public Vector2 distanceValues;
public Vector2 sizeValues;

void Start () {
    //Initialize with Random rotation & distance & size

    //Random Rotation between -2 & 2
    Rotation = Random.Range(RotationValues.x, RotationValues.y);
    //Random distance  between -1 & 2
    distance = Random.Range(distanceValues.x, distanceValues.y);
    //Random Size between 0.2f & 0.7f
    var Size = Random.Range(sizeValues.x, sizeValues.y);
    //Set localScale with random size
    transform.localScale = new Vector3(Size, Size, Size);

    //calculating current time by subtraction Time.time and lastTime
    currentTime = Time.time - Generator.lastTime;

    //GetComponent<MeshRenderer>().material.color = new Color(Random.value, Random.value, Random.value); //Random Color
}

void Update () {
    //Timer
    currentTime += Time.deltaTime;

    var X =  (distance * Mathf.Cos(currentTime)); //X
    var Y =  (distance * Mathf.Sin(currentTime)); //Y
    var R = (Rotation * Mathf.Cos(currentTime)); //Rotation
    //give earth from generator class
    var Earth = Generator.Earth;
    transform.position = Earth.transform.position + (new Vector3(X, R, Y));// RotateAround Earth

}
}

```

also I have this other script which generates the planets:

```
using UnityEngine;
using System.Collections;

public class Generator : MonoBehaviour {
public GameObject prefab;
public static GameObject Earth;
public static float lastTime;
public int numerOfSatellites;

void Start() {
    Earth = GameObject.FindGameObjectWithTag("MainPlanet");//Find Earth
    for (int i = 1; i <= numerOfSatellites; i++) {
        lastTime = Time.time;
        GameObject sat = Instantiate(prefab, Earth.transform.position, Quaternion.identity);
        Physics2D.IgnoreCollision(sat.GetComponent<CircleCollider2D>(), Earth.GetComponent<CircleCollider2D>());
    } }
}

```

I know that the main part here is

```
void Update () {

    //Timer
    currentTime += Time.deltaTime;

    var X =  (distance * Mathf.Cos(currentTime)); //X
    var Y =  (distance * Mathf.Sin(currentTime)); //Y
    var R = (Rotation * Mathf.Cos(currentTime)); //Rotation

    //give earth from generator class
    var Earth = Generator.Earth;
    transform.position = Earth.transform.position + (new Vector3(X, R, Y));// RotateAround Earth

}

```

The main problem is that whatever distance the planets have from the mainPlanet (called earth) they move at the same angular velocity, how would I change this?

Those are the basic 4 steps of every orbit, the problem here is that they all align in the center, which shouldn't be possible because of the random distances they have

# Answer
Kepler's third law states that the square of the period of revolution is proportional to the cube of the distance

or equivalently

Now, the function has a period of .

You can change the period by changing . If you want it to satisfy Kepler law, you have introduce a dependence on the distance

so that

where C is a constant that physically should make the argument of the cosine dimensionless. You do not need to worry about it in the code though, so you can set it to 1.

In conclusion, just change your update function in this way

```
void Update () {

   //Timer
   currentTime += Time.deltaTime;

   var prefactor = Mathf.Pow(distance, -2/3);
   var X =  (distance * Mathf.Cos(prefactor * currentTime)); //X
   var Y =  (distance * Mathf.Sin(prefactor * currentTime)); //Y
   var R =  (Rotation * Mathf.Cos(prefactor * currentTime)); //Rotation

   //give earth from generator class
   var Earth = Generator.Earth;
   transform.position = Earth.transform.position + (new Vector3(X, R, Y));// RotateAround Earth

}

```
> 3 votes

# Answer
You have a fixed angular velocity for each planet.

**The easiest way** to fix this without changing much of your current code is to modify the code so that the angular change per `Update()` is *inversely proportional* to the orbital radius of the planet.

Let's assume Earth is at radius 2. Let's assume Jupiter is at radius 10. 10/2 = 5, thus you need to divide the angular change for Jupiter by 5 to get it to have roughly the same linear velocity as earth; this works because the formula for circumference, `c = 2πr`, is linear. Of course you may not want the *same* linear velocity; but this at least gives you a basis to work from, and you can then (randomly) adjust velocity of each heavenly body, from there.

**The more difficult but also more rigourous way** would be to use physics to correctly update the position of each planet on each `FixedUpdate()`, using vectors. This ranges from quite simple to pretty complex, depending on how much of the physics you want to explicitly control, for example, going as far as calculating mass per body may not be necessary, but adjusting the motion vector each update according to the gravity force being applied, would seem to be a sane requirement.
> 1 votes

---
Tags: unity, 2d, physics, orbit
---


title: ECS - Components inside components?

text:
# Question
Title: ECS - Components inside components?
Reading up on ECS, I've tried to implement a simple 'game', if you can call it that. Basic concepts :

You have planets(entity), they produce gold. (**gold** is a component inside planet)
Planets can build buildings on themselves(**Buildings** component)
A building(entity) has associated gold costs(**Costs** component)

But costs component has **Gold** in it(or it needs to anyway)

As to my question :
Am I close with my interpretation of ECS(Should components be inside other components?)
Are resources a valid Component? if not, where would it make sense to place them?

Edit for clarity :

ECS - Entity-Component-System.
My entities are empty hash tables of components.
My components are used inside systems for game logic, the Treasury entity has a Gold component and the IncomeSystem updates that component.

Other components (Buildable, Population, Moveable)

# Answer
First of all, there is no "right" or "wrong" way to structure a game's software architecture. Just ways which work or don't work for you.

*Usually* you wouldn't nest components. What you would do instead is nest entities by making them parents and children of each other.

* The `Universe` entity has many `Planet` child-entities
* A `Planet` entity has many `Building` child-entities

I am not sure if it makes sense to make `Gold` a full-fledged component. Is it really more than just a number? Does "gold" have any behavior or interaction with components of other entities? If not I would rather expect it to be a simple variable in the `BuildCost`-component, the `ResourceProducer`-component and the `Treasury` \- component.

The only situation where you might have components with components is if you have some game feature which is so complex that you would implement it with a completely independent EC-System inside the component which hosts it.
> 3 votes

---
Tags: javascript, entity-system, component-based, entity-component
---


# Question
Title: AABB 2D Collision response teleports player when hit on wrong edge
I'm currently breaking my head with collision detection and resolving in C++ for my 3D game engine. But currently I'm trying to get resolving to work in 2D. The problem is that when I hit the solid object with my moving object on a specific side, it teleports the player to the edge. It's a bit hard to explain, so I gave my artistic skills a run:

Here you see, if my moving object travels from the bottom up and hits on the right side, everything works. But even if there is a little bit of an overhang on the left side, it teleports the player completely to the edge. And it does that on every side of the AABB.

I also made a short video visualizing the problem.

**This is my function to return the overlapping values:**

```
glm::vec3 Collider::getOverlapping(AABB &other, AABB &aabb) {
    glm::vec3 overlappingAxis;

    if( (std::abs(aabb.first()->x - other.first()->x) * 2 > (aabb.size()->x + other.size()->x)) ||
        (std::abs(aabb.first()->y - other.first()->y) * 2 > (aabb.size()->y + other.size()->y)) ||
        (std::abs(aabb.first()->z - other.first()->z) * 2 > (aabb.size()->z + other.size()->z))){
        return overlappingAxis; //No collision occured
    }

    overlappingAxis.x = sign(aabb.center()->x - other.center()->x) * ((other.size()->x/2 + aabb.size()->x/2) - std::abs(aabb.center()->x - other.center()->x));
    overlappingAxis.y = sign(aabb.center()->y - other.center()->y) * ((other.size()->y/2 + aabb.size()->y/2) - std::abs(aabb.center()->y - other.center()->y));
    overlappingAxis.z = sign(aabb.center()->z - other.center()->z) * ((other.size()->z/2 + aabb.size()->z/2) - std::abs(aabb.center()->z - other.center()->z));

    for(int i = 0; i < 3; i++){ //Add a bit of an offset so that it actually moves out of the collision
        overlappingAxis[i] += sign(overlappingAxis[i]) * 0.0005;
    }

    return overlappingAxis;
}

```

**My method(s) to figure return if there is actually an collision:**

```
bool Collider::isColliding(AABB& other, glm::vec3& axis, AABB& aabb) {
    axis = getOverlapping(other, aabb);
    return !(axis == glm::vec3(0, 0, 0));
}

bool Collider::isColliding(AABB &other, glm::vec3 &axis) {
    return isColliding(other, axis, *m_aabb);
}

```

**My collision resolving method:**

```
void Collider::resolveCollisions(AABB& other, glm::vec3 *position) {
    glm::vec3 overlapping;

    if(isColliding(other, overlapping)) {
        Logger::info(glm::to_string(overlapping), 2);

        if(overlapping.x < overlapping.z){
            position->x += overlapping.x;
        }else{
            position->z += overlapping.z;
        }
    }
}

```

**And my move method of the Physics Object:**

```
void PhysicsObject::updatePosition() {
    AABB testAABB(glm::vec3(0.0f, 0.0f, 0.0f) + glm::vec3(3.0f, 0.0f, 1.0f), glm::vec3(1.0f, 1.0f, 1.0f) + glm::vec3(3.0f, 0.0f, 1.0f));

    m_transformation.getPosition().setPosition(*m_transformation.getPosition().getPosition() + velocity * glm::vec3(DeltaTime::getBigDeltaTime()));
    updateAABB();
    collider->resolveCollisions(testAABB, m_transformation.getPosition().getPosition());

    updateAABB();
    collider->resolveCollisions(testAABB, m_transformation.getPosition().getPosition());
}

```

Just to be clear: Because it's actually a 3D Engine, the Z-Axis represents the Y-Axis, if that makes sense! I just want to get 2D to work and then I extend to 3D!

I'm pretty sure I'm wrong in my resolveCollisions() method. I tried many things, but I just cannot figure out whats wrong.

# Answer
Okay, I figured out what was wrong!

I needed to change

```
if(overlapping.x < overlapping.z){
  position->x += overlapping.x;
}else{
  position->z += overlapping.z;
}

```

to

```
if(std::abs(overlapping.x) < std::abs(overlapping.z)){
  position->x += overlapping.x;
}else{
  position->z += overlapping.z;
}

```
> 1 votes

---
Tags: c++, collision-detection, aabb
---


# Question
Title: Passing Gameobject to another script in unity 3d
I'm trying to pass a gameobject from one script to another runtime attached script. My fisrt script is attached to the FirstPlayerController and the gameobject is not dragged in the editor, but is picked up and carried in the script. All i want is to pass the gameobject to the CameraController class to as make the second camera follow that object. Below is what i've tried so far. I dont want to access the gameobject with the tag, because there are more gameobjects that can be picked up. I want to access the carried object to the cameracontroller class.

Thanks!

**Pickupobject.cs**

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

public class pickupobject : MonoBehaviour
{
    GameObject mainCamera;

    bool carrying;

    public GameObject carriedObject;

    public float distances;

    public float smooth;

    float speed = 1000f;

    new Camera camera;

    // Use this for initialization
    void Start()
    {

        mainCamera = GameObject.FindWithTag("MainCamera");

        camera = GameObject.FindWithTag("secondCamera").GetComponent<Camera>();

        camera.enabled = false;

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.T) && carrying)
        {
            carrying = !carrying;

            ThrowBall();
        }
        if (carrying)
        {
            carry(carriedObject);

        }
        else
        {
            pickup();
        }

    }

    private void pickup()
    {
        if (Input.GetKeyDown(KeyCode.E))
        {

            int x = Screen.width / 2;

            int y = Screen.height / 2;

            Ray ray = mainCamera.GetComponent<Camera>().ScreenPointToRay(new Vector3(x, y));

            RaycastHit hit;

            if (Physics.Raycast(ray, out hit))
            {
                pickupable p = hit.collider.GetComponent<pickupable>();

                if (p != null)
                {
                    carrying = true;

                    carriedObject = p.gameObject;

                    //camera.enabled = true;

                   // camera.gameObject.AddComponent<CameraController>();

                    //carriedObject.AddComponent<MovingBall>();

                }
            }
        }
    }

    void carry(GameObject o)
    {
        o.GetComponent<Rigidbody>().isKinematic = true;

        o.transform.position = mainCamera.transform.position + mainCamera.transform.forward * distances;

    }

    //void CheckDrop()
    //{
    //    if (Input.GetKeyDown(KeyCode.U))
    //    {
    //        Drop();
    //    }
    //}

    //void Drop()
    //{
    //    ThrowBall();

    //}
    void ThrowBall()
    {

        mainCamera.SetActive(false);

        camera.enabled = true;

       // carriedObject.AddComponent<CameraController>();

        camera.gameObject.AddComponent<CameraController>();

        carriedObject.AddComponent<MovingBall>();

        carriedObject.GetComponent<Rigidbody>().isKinematic = false;

        carriedObject.GetComponent<Rigidbody>().AddForce(0f, 0f, speed);

     }

}

```

**CameraController.cs**

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

public class CameraController : MonoBehaviour {

   public GameObject icosphere;

    public GameObject abc;
    Vector3 offset;

    // Use this for initialization

    void Start () {

        icosphere = GameObject.FindWithTag("purpleball");

        offset = transform.position - icosphere.transform.position;
        }

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

            transform.position = icosphere.transform.position + offset;
    }
}

```

# Answer
> 1 votes
When you `AddComponent<CameraController>()` store that result in a variable like `CameraController temp` and then call a method on the camera controller to pass in the object. That means you need to add a new public method to CameraController to call, something like:

```
public void SetCarriedObject(GameObject obj) {
  // do whatever
}

```

Now in the first script you can write `temp.SetCarriedObject(carriedObject);`

---
Tags: unity, camera
---


title: Text anti-aliasing Unity

text:
# Question
Title: Text anti-aliasing Unity
I am trying to implement a game like BBTAN with Unity5, the point I got stuck on is drawing numbers onto the boxes in a proper way. I have done it by adding `Canvas` and `Text` elements on each boxes and set the following properties of them in order the fit the text inside to the canvas:

Render Mode: World Space Dynamic Pixels Per Unit = 1250 Reference Pixels Per Unit = 100

Even though the text fits into the box, its being rendered without antialiasing. And it looks like this (The box is on the right hand side is the Screen Space Overlay Canvas, for comparison purpose):

I have two questions to ask:

1. Is adding canvas to each block an efficient way? If not how should I implement drawing dynamic numbers (Changing when got hit) onto these boxes?
2. Is "changing the dynamic pixels per unit" the correct way to achieve this goal? If so, how can I fix this anti-aliasing problem?

Thanks in advance for any help!

# Answer
Per #1: Yeah, it's fine. More canvasses is better than too few (because of the way theyhave to sort *everything* when something changes). Don't worry about it.

Per #2: What I do for canvas text items is set the scale to `(0.5,0.5,0.5)` and double the font size. But that's for screenspace text. I haven't messed with worldspace text yet. Try doing the *reverse*: double the scale and halve the font size. That will probably be too extreme, but if it looks more-better, see if you can find a value in between that works for you (maybe 1.5 scale and 0.66 on the font).
> 1 votes

---
Tags: unity
---


title: Word game - board implementation?

text:
# Question
Title: Word game - board implementation?
I'm working on a boggle type game for android, using libgdx. The user is presented with a 4x4 grid of letters and must find words by dragging their finger over the letters.

Unlike boggle I want used letters to disappear. Remaining letters will fall down (to the bottom of the board, screen orientation is fixed) and the board is refilled from the top. Users can rotate the board to try and put hard to use letters in a better place by strategic word selection.

An example:

```
d g a o
u o r T
h v R I
d G n a

```

If i selected the word GRIT, those letters would disappear and the remaining fall down:

```
d
u g a
h o r o
d v n a

```

and then get replaced by new letters

```
d w x y
u g a z
h o r o
d v n a

```

I'm stuck figuring out how to represent the board and tiles.

I tried representing the board as a matrix to keep track of tiles selected and valid moves and the tiles stored in a matrix as well so that there was an easy mapping. This works, but I had to write some convoluted code to rotate the board.

How do other games handle this problem?

EDIT: So thinking about it, I should really just process my touch point according to the board rotation so cells stay constant. Attached an image of what I'm thinking.

# Answer
I would not use arrays for this at all because managing it will get more and more complex. Make a custom Board data-structure with Nodes that have references to their neighbors. This is essentially a multi-dimensional LinkedList of Nodes. In that way, if a node's letter is removed, other nodes can view this in an encapsulated way. This avoids complicated array arithmetic. You will need one big function to get everything connected correctly, but once linked the logic should be much easier to work with.

Your edge nodes will have neighbors set to `null`, so make sure to handle that accordingly in your methods in the Node class that need to refer to neighbors.

I have used this approach for implementing *Conway's Game Of Life* and once you get it set up, it drastically decreases the complexity of adding logic that changes the state of a Node based on neighbors.

Depending on how you are manipulating the nodes in the board, you may need one board method to iterate through and determine the next state or action and save that within each node. Then follow that by iterating and committing each node to the new state. This avoids having nodes determining their next state by looking at nodes that have already changed.
> 1 votes

# Answer
Yes the solution is you get value from your matrix or array and set That value for temp array or matrix and Then set value from there this is show you your rotate value gird. I added code below i think its help you

```
    int MAX_GRID = 4;
    int[][] main_array = new int[MAX_GRID][MAX_GRID];
    int[][] temp_array = new int[MAX_GRID][MAX_GRID];

    /** This method for clockwise **/
    int mainRow = MAX_GRID - 1;
    for (int c = 0; c < MAX_GRID; c++) {
        for (int r = 0; r < MAX_GRID; r++) {
            temp_array [mainRow][c] = main_array [r][c];
            Log.i("TAG", "R C : [ " + mainRow + " " + c + " ]" + " => [ "
                    + r + " " + c + " ]");
            mainRow--;
        }
    }
    main_array = temp_array;

    /** This method for anti-clockwise **/
    int mainCol = 0;
    for (int c = MAX_GRID - 1; c >= 0; c--) {
        for (int r = MAX_GRID - 1; r >= 0; r--) {
            temp_array [r][mainCol] = main_array [c][r];
            Log.i("TAG", "R C : [ " + r + " " + mainCol + " ]" + " => [ "
                    + c + " " + r + " ]");
        }
        mainCol++;
    }
    main_array = temp_array;

    // Now you can set main_array value then its rotate

```
> -2 votes

---
Tags: android, libgdx
---


# Question
Title: Checking if bullet collides with enemy when I know the start X & Y, the angle, the speed and dist traveled of the bullets
This is the bullet I create when a player clicks to attack

```
var angInRadians = Math.atan2(data.y - playerArr[i].y, data.x - playerArr[i].x);//data.y & data.x is mouseY and mouseX
var temp = angInRadians * (180/Math.PI);
        function newBullet() {
          this.attack = temp;
          this.playerX = playerArr[i].x;
          this.playerY = playerArr[i].y;
          this.speed = 10;
          this.traveled = 0;
        }

```

Then in my game loop I do this

```
for(var j = 0;j<playerArr[i].bullets.length;j++)
    {
      playerArr[i].bullets[j].traveled += playerArr[i].bullets[j].speed;
    }

```

Then to draw the bullet I am doing this

```
ctx.translate(playerArr[i].bullets[j].playerX, playerArr[i].bullets[j].playerY);
        ctx.rotate(playerArr[i].bullets[j].attack * (Math.PI/180));
        ctx.fillStyle = 'black';
        ctx.fillRect(playerArr[i].bullets[j].traveled, 0, 4, 1);

```

Then for the players I just have a usual player X and Y and I can't figure out how to check if the bullet is within the area of the player, if you need any more code just ask/If you want to see how the game is working here.

# Answer
> 1 votes
To check if the bullet is currently inside a player, you can test the distance between the player and the bullet. If they are closer together than the radius of the player circle, then the bullet is inside the player.

```
for each player
    for each bullet
        for each OTHER player
            if (distance between bullet and player < radius of player)
                // score a hit
                // destroy the bullet or note that it shouldn't damage this player again

```

I do not recommend that method, though. The bullet travels some distance, let's call that `A`, each update. If `A` is larger than the width of the target player *at the point where the bullet's path crosses it*, then the bullet could "tunnel" through the player between frames. Since a bullet could just clip a little sliver at the edge of a player, this is possible even with fairly slow-moving bullets and players.

Instead, I would check if the bullet's path has intersected the player object during the last frame. It's more complicated, but it is a fairly optimal process that shouldn't be noticeably slower than the less accurate method.

```
// for each player
    // for each bullet
        // set up some variables

        var x0 = bullet.playerX;
        var y0 = bullet.playerY;
        var radians = bullet.attack * Math.PI / 180;
        var dX = bullet.traveled * Math.Cos(radians);
        var dY = bullet.traveled * Math.Sin(radians);
        var sShotSqr = bullet.traveled * bullet.traveled;

        // you'll need to track the last bullet position, or integrate this code
        // into the bullet update code so you can use both the previous and
        // current 'traveled' values.

        var tMin = bullet.traveledPrev / bullet.traveled;

        // for each OTHER player
            var dXTarget = playerArr[k].x - x0;
            var dYTarget = playerArr[k].y - y0;
            var t = (dXTarget * dX + dYTarget * dY) / sShotSqr;
            // check for the bullet moving away from the player
            if (t < 0)
                continue;

            var radius = playerArr[k].radius;
            var deltaTMax = radius / bullet.traveled;
            // check coarsely for the player and bullet not crossing paths this frame
            if (t + deltaTMax < tMin || t - deltaTMax > 1)
                continue;

            var xSpoke = x0 + dX * t;
            var ySpoke = y0 + dY * t;
            var offsetSqr = radius * radius - xSpoke * xSpoke - ySpoke * ySpoke;
            // check for the bullet's path not touching the player
            if (offsetSqr < 0)
                continue;

            var deltaT = sqrt(offsetSqr / sShotSqr);
            // check for the bullet not yet reaching the player or the player
            // moving across the path after the bullet has passed
            if (t + deltaT < tMin || t - deltaT > 1)
                continue;

            // score a hit

```

Caveat: I wrote this up here on the site, so it probably contains syntax errors. There may be transcription errors also - x instead of y or something like that.

The process is pretty straightforward, though it's a bunch of code. It calculates the little segment of the player's circle that crosses the bullet's path, then checks whether the bullet has touched that segment during the time since the previous update.

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


# Question
Title: Validate single player game packet on a server
I am building a game in Unity and store data on a .NET server. I was wonder what the best approach to validating the game data before posting the scores to the .NET server.

The game is somewhat deterministic and I know I have to simulate the game on the server to some extent to properly validate the game. This simulated game would have to run extremely quick as well.

This is where I am having trouble. In unity I have various colliders that are used to determine things like range and when to take damage and I have no idea how to "simulate" this in a .NET enviroment. I was wondering if there are any resources out there or tutorials out there. I have tried to find one but I don't think I am using the right keywords.

I am guessing this would be similar to how games like Clash of Clans validates their attacks.

# Answer
> 1 votes
If you are using Unity colliders and use collisions from them to control the simulation, chances are you don't have a deterministic simulation. You have a few options to deal with that:

* Make it deterministic. Generally this means a fixed timestep and doing all calculations with fixed-point math instead of floating-point. This probably means writing your own physics engine, so unless the simulation is really simple it's probably going to be a lot of work, but here are a few resources that might be helpful: Floating Point Determinism, Lockstep Implementation in Unity3D.
* Minimize non-determinism and hope for the best. I don't have much experience with this, but I'm sure lots of people have tried. You'll probably need to have generous leeway to avoid false positives when trying to detect cheaters, which means some might slip through, and the butterfly effect means you'll likely never be able to prevent all false-positives.

If you do manage to solve the determinism problem, you may still be left with a server performance problem. Luckily, the solution for that is simple. Just let the server randomly decide whether to validate a particular "round" of gameplay. If you don't validate it, you can just assume that the player is honest. Some additional layers of complexity you might want to consider:

* Increase the chance of validation for a particular player every time the server skips doing it (but it should still be mostly random to prevent hostile players being able to predict which ones will be validated).
* If a player fails a validation, place them on probation and validate every subsequent event for that player for a certain amount of time.
* If a player repeatedly fails validation, just permaban them.
* Vary the chance to do a validation based on server load. During off-peak hours, you can afford to spend more server time validating.
* Store data for unvalidated actions in a database, and provide a tool to do validation and remediation of previous results.
* Make a tool that allows a human to replay what the player did. This helps triage reported abuse even if your simulation isn't deterministic at all; data from cheaters is probably going to look really obvious.
* If you can't make the entire simulation deterministic, just validate the parts that are deterministic. For example, if a unit normally does 50 damage, but in the replay it does 10,000...

In the end it's up to you how much time, effort, and money you want to spend dealing with cheaters.

---
Tags: unity, .net
---


# Question
Title: Euler (right-handed) to Quaternion (left-handed) conversion in Unity
I'm having trouble figuring out the proper conversions from Euler angles to Quaternions. The Eulers come from BVH files, which use a right-handed coordinate system (Y is up, Z is forward) and can have any rotation order specified. The Quaternions are in Unity, which is left-handed (Y is up, Z is back).

I'm composing the Quaternions from three `AngleAxis` rotations, but messing up the order somewhere. So far I can't find understandable and generalized information for doing these types of conversions.

```
public enum AxisOrder
{
    XYZ, XZY, YXZ, YZX, ZXY, ZYX, None
}

public Quaternion EulerToQuat(Vector3 eulerAngles, AxisOrder rotationOrder)
{
    // I've tried various combinations of axis angles here, but would
    //  like to understand what's wrong rather than brute-force
    //  every combination
    var xRot = Quaternion.AngleAxis(eulerAngles.x, Vector3.left);
    var yRot = Quaternion.AngleAxis(eulerAngles.y, Vector3.down);
    var zRot = Quaternion.AngleAxis(eulerAngles.z, Vector3.back);

    switch (rotationOrder)
    {
        case AxisOrder.XYZ: return (xRot * yRot) * zRot;
        case AxisOrder.XZY: return (xRot * zRot) * yRot;
        case AxisOrder.YXZ: return (yRot * xRot) * zRot;
        case AxisOrder.YZX: return (yRot * zRot) * xRot;
        case AxisOrder.ZXY: return (zRot * xRot) * yRot;
        case AxisOrder.ZYX: return (zRot * yRot) * xRot;
    }

    return Quaternion.identity;
}

```

...and converting translation data like so (I believe this is working):

```
public static Vector3 BvhToUnityTranslation(float xPos, float yPos, float zPos)
{
    return new Vector3(xPos, yPos, -zPos);
}

```

If anyone can help me better understand how to conceptualize coordinate system conversions, and where I'm going wrong, I'd greatly appreciate it.

# Answer
Three points we need to consider:

1. Matrices and quaternions in Unity multiply from right to left, if we think of each subsequent rotation being applied with regard to the world axes:

```
output space or vector = <-- transformation * <--- input space or vector

```

As discussed below, if BVH's "XYZ" order means "rotate about the world X axis, then the world Y axis, then the world Z axis" you'd stack your rotations in Unity right-to-left: Z * Y * X

But, it sounds like BVH's XYZ means "rotate about the local X axis, then the local Y axis, then the local Z axis" which means in Unity we'd match the order left-to-right: X * Y * Z
2. When switching the handedness of the coordinate system, all rotation angles are negated (if we keep the axis of rotation consistent)
3. The axes map up like so, based on the conversation above:

```
direction    Unity       BVH
----------------------------
right         x+         x-
up            y+         y+
forward       z+         z+

```

So we should be able to get correct conversion between the two spaces with a few small changes:

```
public Quaternion BvhToUnityRotation(Vector3 eulerAngles, AxisOrder rotationOrder)
{
    // BVH's x+ axis is Unity's left (x-)
    var xRot = Quaternion.AngleAxis(-eulerAngles.x, Vector3.left);
    // Unity & BVH agree on the y & z axes
    var yRot = Quaternion.AngleAxis(-eulerAngles.y, Vector3.up);
    var zRot = Quaternion.AngleAxis(-eulerAngles.z, Vector3.forward);

    switch (rotationOrder)
    {
        // Reproduce rotation order (no need for parentheses - it's associative)
        case AxisOrder.XYZ: return xRot * yRot * zRot;
        case AxisOrder.XZY: return xRot * zRot * yRot;
        case AxisOrder.YXZ: return yRot * xRot * zRot;
        case AxisOrder.YZX: return yRot * zRot * xRot;
        case AxisOrder.ZXY: return zRot * xRot * yRot;
        case AxisOrder.ZYX: return zRot * yRot * xRot;
    }

    return Quaternion.identity;
}

```

And:

```
public static Vector3 BvhToUnityTranslation(float xPos, float yPos, float zPos)
{
    // Flipping x axis instead.
    return new Vector3(-xPos, yPos, zPos);
}

```
> 3 votes

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


title: Generate Random Integers

text:
# Question
Title: Generate Random Integers
I am trying to make a dice rolling game. I want to generate a random integer in the range of the number of dice I have multiplied by the number of sides the dice has. For example, if two dice were played with three sides, then there could be any number between 2 and 6.

Here is my code; when I put in, for example one dice and two sides, it prints numbers upwards of 13. The problem is that it doesn't create an integer between the amount of sides and dice.

```
condition = "Start"
while condition == "Start":
Dice = int(input("Please select number of dice you would like to use (atleast 1)"))
Sides = int(input("Please select number of sides on dice you would like to use (atleast 2)"))
if Dice <= 0 and Sides <= 1:
    condition = "Start"
elif Dice >= 1 and Sides >= 2:
    print("You have selected", Dice," dice and", Sides,"Sides")
    condition = "play"
    Roll1 = 0
    Roll2 = 0
    Score1 = 0
    Score2 = 0
while condition == "play":
        Roll1 += randint(Dice,Sides)
        Roll2 += randint(Dice,Sides)
        print (name1,"'s Roll", Roll1)
        print (name2,"'s Roll", Roll2)

```

# Answer
You seem to be missing a loop to simulate the number of dice there are to roll, and you seem to be using the `randint` function incorrectly.

*I haven't tested this code* but it should get you started:

```
condition = "Start"
while condition == "Start":
    Dice = int(input("Please select number of dice you would like to use (atleast 1)"))
    Sides = int(input("Please select number of sides on dice you would like to use (atleast 2)"))
    if Dice <= 0 and Sides <= 1:
        condition = "Start"
    elif Dice >= 1 and Sides >= 2:
        print("You have selected", Dice," dice and", Sides,"Sides")
        score = 0
        for i in range(Dice):
            roll = randint(1,Sides)
            score += roll
            print ("Die # ", i + 1, "'s Roll :", roll)
        print ("Score: ", score)

```

Basically, the `for` loop there will iterate over the number of dice roll that the user expected. With that, you don't need to create a variable for each roll.

And the `randint` method needs the min and max values. In the code you provided, you are mixing apples and oranges; `Dice` and `Sides` are not really related. What you want is the minimum value of one (the minimum value will be one for any dice), and the max value, as you could see, is the `Sides` variable, as you used.
> 2 votes

---
Tags: python
---


# Question
Title: Are DirectX coordinates spaced out in meters?
Are the DirectX coordinates spaced out in meters? I am just wondering, so I can add some realism to my game.

# Answer
## They are just Units

The units in DirectX (or OpenGL for that matter) does not correspond to any physical measure.

For consistency and your mental health, you can define them to be whatever unit you prefer. Certainly, meters is a good candidate for that.

Let us imagine that for whatever reason the coordinates were not meters, but - let us say - centimeters. Good, all you would have to do is scale everything. Ok, but, if everything is scale equally, how do you distinguish that from the original? Let me answer that for you: you cannot.

**Addendum**: With this example I attempt to say that an inherent physical scale is meaningless on a virtual world.

---

## The apparience of big and small is in the camera

By the way, if you are thinking about properties of the virtual camera such as focal length and depth of field (which you could implement with shaders and can be used to give the impression that something is small or big). Well, those can scale too.

**Addendum**: I'm also saying these are all virtual camera effects, and have nothing to do with the actual units. It is the psychology of a very narrow depth of field that suggest that the camera lens must be huge in comparison to the objects it shows, and we tend to think the camera lens are about the same (order of maginitud of) size than our eyes.

---

## Other physical properties

You may perhaps consider density or mass... these are not concerns of DirectX (or OpenGL for that matter). Once you start using a physics engine, it will be up to you to define a scale that makes sense.

Note: the closest to a physical measure they get is when they get to screen space, there and then they have some size that depend on the size of your screen. You may theorize of what the size of the things is from there if were only using identity matrices for all the transformations... but the result would be that the size of the world depends on the size of the screen of the user. That is not useful.

---

## Importing models

If you are working on a team, it is a good idea to get everybody on agreement on the scale to use.

Yet, if you are using third party models, you may find them to be too big or too small for the world you are building. The reason is that the author of the model may have intended for the units in the model to be something different to what you are using. In that case, you will have to scale the model to fit your world.

---

## Abstract

> Is the DirectX coordinates spaced out in meters?

If you want it to be.
> 4 votes

---
Tags: directx
---


title: Simple Chiptune software for game music

text:
# Question
Title: Simple Chiptune software for game music
I'm looking for the "Microsoft Paint" equivalent of chiptune music creation software.

Something very simple (I use Bfxr for sound effect generation which has been perfect for me) where I could save in .wav file format or something similar.

By "chiptune" I mean old school (8-bit or 80s era) sounds like what the SID chip could do on the Commodore 64.

The only software I've come across so far has been just too complex, the learning curve too high, or the price tag too high.

Any advice is welcome!

# Answer
> -1 votes
Shrinking Planet - Brackeys

The developer of this game used Bosca Ceoil, to create chiptunes for his game. The developer has a YouTube channel called "Brackeys" where he teaches Game Development.

---
Tags: music
---


# Question
Title: How do I avoid users hacking my network games from the client side?
I've decided to make an online game; the server sends packets of information to the client application, which is going to simulate what it gets from the server. The client makes a part of the design of the game, and sends the new state back to the server for processing.

The clients can send fake information to the server, and inform the server that I've done the task successfully, without trying. Assume a Counter-Strike game; the client may send a fake packet to the server and tell the server that I've defeated someone. How can I avoid this violation?

# Answer
---

## Introduction

As with any security question, it is useful to think about every step in the protocol. From the user pressing a key to the server response.

---

Before we go into that, I must say that the only way to remove a risk is to remove the asset that is at risk. For example, the only way to make sure a cable will not break is to use a wireless connection. If we are talking about using stronger cables, hiding them from view, etc. Those are mitigations.

In your case, if you are worried that by some cheat the client may say X to the server, removing the risk means to disallow the client to say X in any circumstance. Not as a forbidden thing to say, but as something that cannot be encoded in the communication.

*I am using the word mitigation a bit loosely here. If we were to talk about risk management we would talk about other forms of "mitigation" such as having a backup connection (minimizing the impact) or getting insurance (externalizing the risk), etc.*

The kind of mitigation we want to focus are *deterrents*. To put a wild example, if somebody wanted to enter your room, a door with a lock is usually enough to stop them. However, if we were talking about a murderer decided to get you, you can imagine they could break the lock, chop the door down, etc. Therefore, the door and lock does not really remove the risk of people entering, it *deters* them.

---

## Making it harder to cheat

For the solution I present the below, the idea is to make it too hard to make it not worth it.

I will go from the server to the client, because the closer we get to the user input, the crazier the schemes the attacker will have to use.

1. Of course, we start at the server. A compromised server is off topic for this question. Anyway, just want to say that it happens, but rarely to cheat on the game and most likely to steal credentials.
2. The connection from server to client is the next spot.

Aside from using a secure channel (**Use a secure channel**), I am more interested in the design of the protocol the client uses to talk to the server.

Consider that if the attacker can make a rogue client capable of connecting to the server, it would be free from any security part of the official client. Yet the attacker will probably not go into the trouble of creating a fully functional rogue client (instead they would prefer to modify the official one). Therefore, the intents of rogue clients are often to inject resources, items, or some form of boost into an account.

I advise to remove this risk. Do not let the client tell the server what are the rewards they get, and do not let the clients exchange items without server authorization. Be careful with the design and implementation of coupon codes (if you ever decide to have) or any similar opportunities.

You may also want to have the server authorize drops and other loot. Instead letting the client decide, have the client ask the server for drops and loot.

For example, if there is a chest and the player tries to open it, the client can request to the server the contents of the chest while it start making the animation of opening it.

Alternatively, if you may get a compromise in which the client is able to generate drops and loot, but only from an authorized set and amounts dictated by the server.

Otherwise, a rogue client would be able to create items, resources, money, etc.

That reminds me, when it comes to aim bots, one way to mitigate them is have an accuracy value that deviates the bullets. That is, the client says it shoots to X direction, but it has to ask the server if it hits. The server still may say if they miss (given an accuracy value known to the server) and how much damage it does. It sounds like the game is cheating, because it rather is, so this is not a solution for every game, it works best if shooting is secondary.

Nevertheless, aim bots are only effective because they access game memory to know where to aim. Will see below how to prevent them from tampering with game memory.
3. The attacker may try to alter the client on permanent storage (e.g. disk) or on ram.

3.1. Permanent Storage

Your first line of defense will be self-diagnostics: any decent online game will have a launcher capable of detecting corrupted files and patching them as part of the auto update functionality.

Aside from that, if you can afford to, **add digital signatures to your executables**.

The attacker can usually bypass these measures, yet it is often enough deterrent from altering the game in permanent storage. You can make it harder to bypass by using Hash and Decrypt, but ultimately not impossible, in fact, I would say it is not worth to go that length.

The attacker will just move to the next weak point. In this case, altering the program in ram.

3.2. RAM

*I am outdated when it comes code injection in RAM, I will talk about the methods I know.*

First, let us get the obvious out of the way: attach a debugger. It is possible to **detect if your code is running under a debugger**, to detect a debugger is a common anti-crack protection. To bypass it, they will have to modify the code in permanent storage... if they can find it. The usual approach is code obfuscation, some solutions will have that code under a cipher. It if is too hard, the attacker will probably not bother, they move to the next thing.

To inject code in RAM the basics are as follow: Get a handle of the game process, allocate memory for it, give executing permission for the memory you allocated, write code there (if the code you want to inject is not short, write code that will load a library with the code you want). Assuming you have root privileges, the above is possible (baring new security measures in modern OS of which I am not aware of, *as I said, I am outdated*), but that is not enough for that code to run on the game process.

To get it to run, you may register it as a hook, so that the OS will call it on a certain event. You may also suspend a thread, get the execution pointer, append a jump back to that position at then of the injected code, override the execution pointer to the injected code, then resume the thread. In some environment, it may also be possible to inject code to error handlers, and I am confident there are other ways that I am not aware.

To defend yourself from this:

1. Add a routine check that will scan all allocated pages and see they are what they should be. If you find a page you did not allocate, something is up. Enumerate all the loaded libraries, if an unknown library is loaded, something is up. There is a chance that the attacker will suspend the thread doing the check, update the expected value and then resume the thread. To mitigate that: 1) have your code run from the thread pool, 2) add a check that if the time it takes to verify is too long (presumably because the thread was suspended) something is up. Note: they may use the injected code to override your check. 3) Store the expected value as a hash or as a signature, to make it harder to tamper with.
    2. Have a companion service or application scan the running executables. Read their code (in machine language) for calls to functions used to allocate memory in another program and to suspend threads. If it has them, consider the program to be dangerous, close the game. You may have a white list of programs known to be ok and a black list of programs not so ok. If you find a new dangerous program, have the local setup remember it. If you have the means, send a copy of the software for investigation (to you or to a security company providing this service) and potentially add it to the black list - you may have to mention that in Eula.

    Note: Have your game check the companion is running and not suspended. So that the attacker cannot simply close the companion to bypass it.

See also:

Note: there are commercial Anti-Cheat solutions that package this functionality.

On the other hand, instead of trying to stop others from reading memory, we can give them a harder time using it. To do that, randomize the order in which you load information to memory in your program. This is common to prevent buffer overflow exploits. This does not make things impossible for the attacker, but it means that they will have to scan the whole memory of your game to find where they have to read the data they need - which is perfectly doable.
4. Going beyond memory injection, the attacker may be using virtualization to run the game, or could have made his bot a rootkit. Either way this makes it possible to mock the system calls the game makes. This gives them a proverbial back door to run code in your process. I am not aware of solutions for this... At least there is code to **detect if you are running under virtualization**, you will want to take the Red Pill, Neo.
5. Perhaps the attacker is not messing with the game at all. Perhaps all the bot of the attacker is doing is reading memory, taking screen shots (I have seen demos that use Computer Vision), and sending input.

The technique of having a companion looking for other software that may exhibit a particular behavior is useful here. In this case, you are looking for functions used to send input and messages to other applications.

*I think at this point you will be in a more traditional arms race, where they come up with a new cheat, and you add it to the black list. If your game is a success to the point where cheats start to become popular, it might be worth to have an employee (again, we are assuming the game is a success) go online and search as hard as possible for any cheat for your game, try them, and add them to your black list.*
6. *Tinfoil hat on*. The attacker may use custom hardware designed to cheat the game. *Ok, that is enough. If they have the means, I would say they earned it.*

Note: Actually, for a e-sport, in an official tournament, you want to have approved hardware. In addition, there is a point 7 that applies in that case: doping.

---

## Other measures

Coming around to deterrents, there are three ways to deter (aside from fearmongering). 1) Increase the cost of cheating, 2) increase the likelihoods of are caught and 3) increase the downside of being caught. Since I did not talk about getting cough, I will briefly go over it here.

The problem is incorporating a Turing test in the game. That is, the game must expect something from the players that only players could do. You can play this in three ways:

1. Make the game hard for bots: The game itself requires some skill that is easy for humans, but hard for machines. Now, be careful, because bots are good at using the correct answer once and again, even if they cannot figure it out. Therefore, this will require some level of unpredictability to increase the complexity of the tasks for the bots. Procedural generation can be useful here.

In addition, bots are also good at reading the memory and taking data from there that would not be available to humans. Your tactic should not be overwhelm the bot, because that overwhelms players too... instead use problems known to be hard. For example, bots can't play Foldit because if they could, there would have had the need to create Foldit in the first place.

Of course, this does not match every game concept, and it may be harder to implement depending on the genre you want. This approach is not for every game.

This is not exactly getting the bots caught, but making them perform badly / harder to develop.
2. Have a sort of Automated Public Turing test to tell Computers and Humans Apart. Sadly a straightforward CAPTCHA will not work in a game, because the player solves it and then lest the bot take control. Moreover, if you keep giving CAPTCHA to players, you annoy them.

Instead, you can analyse the behavior of players - in fact, you probably should, it is useful data - see what do they buy, how often, what gear do they use, how many hits they miss, what is their reaction time, etc. Aside from telling you what gear they prefer, and how good they are at the game, this may help you find outliers, also spot who has instant reflects and perfect aim.

There are two hurdles with this: The first one is that you cannot anonymize the data if you want to be able to do any punishment based on this. You will have to mention that in your Eula (it may have people wonder what evil things you do with their data). The second is that this is data mining on "big data". You have data, but you don't have a clear line that separates bots from humans, that is a good scenario to apply machine learning.

What behavior would you have to try to identify? See below. If successful, the bot developers would have to adapt the bots to perform worst in order to avoid detection. You will not eliminate them anyway.
3. Have people apply the Turing test. Machines are not good at identifying bots, but humans are. Therefore, if you turn identifying bots in part of the (meta) game you will be able to identify the bots. That is a convoluted way to say "have player denounce other players".

In multiplayer games, it is relatively easy to identify because they have the following behavior:

* As soon as an enemy appears, they turn around (often even if the enemy is outside of the field of view) and shoot. With no delay, with perfect aim.
    * They rarely respond to chat, or socialize. For example in an MMORPG if another player comes along and salutes, they do not respond. If the other player takes drops (if your game allows for a player that did not kill to get the drop) or kills everything, the bot does not complain and does not move to another area.
    * They show no fatigue. They do not start to slow down, and they do not take brakes. In fact, cheaters may leave them running across the night, so they (at least the most "harmful") will be running for hours. Sometimes the cheater plays during the day, and leaves the bot at night. In fact, if an account is has the game open for many days without logging out, they are cheating or the game is taking a toll in their health. Red flag either way.

For punishment, we would probably be talking about bans, or in the worst-case account removal. I consider the punishment off topic, if in doubt; take a hint from what other games or platforms do.

---

## Motivations of cheaters

At the point where the bot has a similar performance than human, the only reason a person have to use it is that the bot does not get tired.

Using the bot instead of playing is... well, it is not playing. One would expect that if the game is fun, a person would prefer to play. If the player doesn't like to play, why don't they play something else? Therefore, if a user is leaving the game run with the bot (even if only during the night), it raises the question: WHY?

Why would they prefer to have a bot play? Consider if your game has become tedious. Perhaps the market is suffering from inflation, prices are too high and people has to farm for too long. Perhaps you have boring parts in your game, and so people use bots to get over them to reach the fun parts.

Why would you want an aim-bot? It sounds like they do not care about the gameplay. They may only be interested in exploring the world, or opening a game option they are interested in, or know the lore of the game. Perhaps they are archivers and only want the rewards. Perhaps they are only interested in the social aspects of the game♪.

♪: Maybe they use it to meet people, maybe they want to rush the content to write about it on the web, perhaps they know somebody who plays and want to catch up quickly, perhaps they want to rank up fast to be able to help somebody they know.

If your game is mainly competitive... Perhaps they find amusement in the reactions of players defeated by the bots. Alternatively, perhaps you are not providing players with a way to play against other players on the same skill level, resulting in new players facing up against veterans... and new players look for aim-bots to make things even.

For abstract: the game has other flaws beside the cheaters. Cheaters aggravating the situation, but are not the only problem. At some point, for somebody, the game is not intrinsically fun, and they need to resource to a bot to fix it. So, **make the game fun** so they do not resource to that.
> 4 votes

---
Tags: networking, anti-cheat
---