# Question
Title: How to stop sinking bodies in physics engine C++
I'm writing a rigid body simulation in C++, and have come across a problem when an object *should* come to rest on the ground.

Because gravity is being applied to it's velocity, the object starts sinking through the ground, or whatever else it's resting on.

To combat this, I am adjusting the position of the object, by moving it along the collision normal by the penetration depth. This has the drawback of making the object look like its vibrating, so it never comes to rest.

I read somewhere ages ago, that there is a way to counter this, by generating a force along the normal which will cancel out the force which is causing it to sink. A google search did not return any useful answers however. I suspect this is because I'm not asking the right question, but I don't know a more concise way to word it, so I'd appreciate if someone here has solved this, and could steer me in the right direction.

# Answer
> 4 votes
You need to detect when the object has come to "rest" and turn off the physics (gravity included) on it until some force gets applied to it again.

You'll have to pick a threshold of "rest" that's larger than most cases of vibration but small enough to let objects bounce a few times and slide a bit.

How to do this exactly depends on the physics engine and the objects in question. Weight, bounciness, friction, physics frame rate, and personal taste will change what threshold values are acceptable.

---

There isn't a solution that works 100% due to rounding errors and the odd cases where the object is bouncing off multiple walls.

Often people have to change their level design a bit to alleviate the odd cases such as avoiding creating very concave corners or by placing invisible collision planes to stop objects from getting into those corners.

With game physics it's not a question of getting it perfect but getting it to a point where it's acceptable and doesn't ruin the fun.

# Answer
> 1 votes
I finally found a solution, which does not involved the rather crude method of correcting positions.

This completely eliminated both the sinking and the jitter.

## Sinking

Sinking is caused by the resultant force being insufficient to push the objects apart, in the case of an object coming to "rest" on a stationary object. So we need an additional force to help. This is the normal force, and is proportional to the amount the two bodies are interpenetrating, and the density of the bodies: i.e. the more the objects interpenetrate, the harder they push back:

```
penetrationMultiplier = 1 + penetrationDepth * density;
Ft = F * penetrationMultiplier;

```

Density is a value for each body between 0.0 and 1.0. With very low penetration depths, the magnitude of the penetration value will not be much over 1.0, but will increase in magnitude as penetration depth increases.

## Jitter

Jitter is caused by a body never fully coming to rest, and keeps bouncing until the you reach the limits of floating point precision. To solve this, we must set a minimum limit on motion of bodies, below which, the body can be deemed to be "at rest". Let us call this value `epsilon`. When a body is at rest, only a force of magnitude greater than `epsilon` will cause the body to no longer be at rest.

The calculation to place a body at rest, or "asleep" applies to both linear and angular motion, and is applied at the point of updating positions by `velocity * deltaTime`:

```
void update(float deltaTime)
{
    if(m_awake == true)
    {
        if ( length(velocity) < epsilon )
        {
            velocity = vec3(0.0);
            m_awake = false;
        }
        else
        {
            position += (velocity * deltaTime) * damping;
            rotation += (angularvelocity * deltaTime) * damping;
        }
    }
}

```

Damping is value which will sap a tiny amount of energy from a bodies angular and linear velocities over time, which will allow a body to eventually lose energy to the point of epsilon coming into effect.

Then when a force is applied, to potentially wake it up:

```
void applyForce(vec3 force, vec3 contactPoint)
{
    if (length(force) > epsilon)
    {
        m_awake = true;
        // apply force as normal, calculating new linear and angular motion
    }
}

```

Eventually, due to energy losses via restitution, damping and inertia/momentum calculations, the magnitude of the impulse will be insufficient to cause a noticeable change in linear or angular velocity, and thus the body will go to, and remain, asleep.

---
Tags: c++, physics, bug
---


title: 2D Soccer Goal Net

text:
# Question
Title: 2D Soccer Goal Net
I want to make a 2D soccer game on iOS, I started with SpriteKit and got the ball physics working. Now, I could make the goal simple and static, but I'd love to make it make it elastic like a real one when the ball hits the net. I started creating the goal with the post, two ropes (on the top and rear side). The ropes are basically like the ones in https://github.com/DigitalBuckeye/SKSwiftRopeDemo.

My problem is, when I hit the ball fast enough against the ropes, it will pass through them (even with usesPreciseCollisionDetection enabled).

I couldn't find any 2D sample for a good goal net on the web, tried searching in the box2d and chipmunk communities.

I wonder if I'll have to use a 3D engine for that.

# Answer
> My problem is, when I hit the ball fast enough against the ropes, it will pass through them (even with usesPreciseCollisionDetection enabled).

This is probably because it's moving so fast that:

* Frame n: Ball is still in front of net, not colliding with net.
* Frame n+1: Ball is on the different side of net, not colliding with net.

This problem has it's own question, so I'll just summarize possible options:

1. Limit ball speed.
2. Check in every frame if ball had passed trough net.
3. Do collision test in each frame ( before moving ball ) with some raycast to check if path in front of ball is clear ( no obstacles, eg. net ).
4. *"Create a minimal bounding box that contains \[ball position in\] Frame n and Frame n+1 and see if the goal intersects \[with this box\]"* \- as suggested in comment by Erno de Weerd
> 1 votes

---
Tags: ios, spritekit
---


title: Change Camera Contrast in VR Game

text:
# Question
Title: Change Camera Contrast in VR Game
Hello there Firends ,

I'm developing a Virtual Reality game in Unity. As in every VR game , i have 2 cameras for stereo rendering. I want to show the same object in each camera having different color/contrast ratio\> The effect is similar to the one shown in this image :

the grid in the center here is the same in each side but each camera is seeing it differently.i.e. its grey in the left and black in right (you will notice the black grid if you look closely)

here is another example :
<sub>(source: wired.co.uk)</sub>

How do i get this effect ? Any suggestions ?

# Answer
As an alternative solution:

```
camera.SetReplacementShader();

```

Manual and API reference.

You'd have to create a custom shader for the one side, but it would be pretty easy to get the default shader being used for the left (there's a download for the default shaders here) and modifying it so that the color/brightness/lighting is altered so that it has the effect you desire.

Replacement shaders operate on the *camera* level, so the entire scene is rendered a second time (as is normal) but with the override shader being used in place of the object's default shader (with some simple rules involving shader tags). Your shader will probably need two subshaders, one with a tag that renders objects in the original manner, the other that renders them darker. It'll take a little tweaking and experimentation on your part, but it's not hard. `material.SetOverrideTag()` may come in handy.

I use it to achieve a wall-hack effect in a game I'm working on. The two cameras are placed at the same point (as I'm not dealing with VR) with the second camera (the one that has the replacement shader set) rendering second and on top of the previous camera.

My replacement shader only renders the edges of the model meshes, rather than faces, but if you set yours to use a different lighting model and darken the result, you'll achieve the effect you desire. Both screenshots were achieved during a single program execution by manipulating the object inspector to swap override tags (this may come in handy if you wish to have a control that allows the user to turn the diplopia effect on and off).
> 1 votes

# Answer
You could duplicate object that you want do render with different colours/brightness and place them in seperate layers. Then you set each of the cameras to ignore one of the layers (layer culling).

But why would you want that? The brain will have problems making sense of such wierd images presented to the eyes - this will almost certainly end in disorientation/headaches/nause for many users. What do you want to achieve - maybe it can be achieved in a less immersion-breaking manner?
> 0 votes

---
Tags: unity, android, mobile, virtual-reality
---


# Question
Title: Vertex normals in the geometry shader using directx
I'm in directx 11 with the geometry shader.

Is is possible to calculate vertex normals? Just one like segment per vertex? In the geometry shader?

I did vertex normals per face, this is what I got,

My exercise in the book wants something like

# Answer
> 1 votes
Computing vertex normals is a complex process as you need to have all incident faces available, and the ability to "split verts" when needed. This is not really something well suited to the Geometry Shader. Face normals do fit well with Geometry Shader because you only care about the primitive itself.

Is there some reason you have to do this on the GPU?

The DirectXMesh library implements a number of different vertex normal calculations, but works on the CPU. In particular, see ComputeNormals. Typically all your geometry data is conditioned at build time to include needed things like vertex normals, tangents or bi-tangents (if needed).

Here are some references as well:

* S Jin, R R Lewis, and D West; "A comparison of algorithms for vertex normal computation". link
* Nelson Max, "Weights for Computing Vertex Normals from Facet Normals" link
* Max Wagner, "Generating Vertex Normals" link

---
Tags: shaders, directx, directx11, hlsl, geometry
---


# Question
Title: Terrain Generation - Only draws first sprite and last row on the X axis
So, I have a problem where I'm trying to loop trough columns of sprites, that later will be drawn to fill a specific area.

But it only renders the first sprite and the last row of sprites on the X axis.

Like this :

As you see it doesn't fill the entire "screen".

---

This is how I try to loop trough all the sprites and draw them :

```
void EntityManager::GenerateMap(float xSize, float ySize, int texture)
{
    // Generates a series of rooms connected so eachother with random positions and size.
    Random randomGen;

    roomTextures.push_back(sf::Texture());

    if (!roomTextures[texture].loadFromFile("Resource/Images/Test.png"))
        std::cout << "Failed to load texture from file." << std::endl;
    else
    {

        for (int y = 0; y < ySize; y++)
        {
            std::cout << "y : " << y << std::endl;
            for (int x = 0; x < xSize; x++)
            {
                std::cout << "x : " << x << std::endl;
                roomSprites.push_back(new sf::Sprite());
                roomSprites[x]->setPosition(sf::Vector2f(x * 32, y * 32));
            }
        }

        std::cout << roomSprites.size() << std::endl;

        for (int i = 0; i < roomSprites.size(); i++)
        {
            roomSprites[i]->setTexture(roomTextures[texture]);
            //std::cout << "x : " << roomSprites[i]->getPosition().x << " y : " << roomSprites[i]->getPosition().y << std::endl;
        }
    }

}

```

Where `xSize = 10`, and `xSize = 10` and `texture = 0`.

And here's the "definitions" of the array list things :

```
std::vector<sf::Sprite*> roomSprites;
std::vector<sf::Texture> roomTextures;

```

---

Update :

So, I tried looping trough the sprite positions which resulted in this :

There were more positions below those, all of them being `x: 0 y: 0`

# Answer
> 2 votes
Your problem is this line:

```
roomSprites[x]->setPosition(sf::Vector2f(x * 32, y * 32));

```

What do you think will happen in the second row? `x` will start at 0 again and you'll set the position of the first 10 sprites. In the third row, `x` will start at 0 again and you'll set the position of the first 10 sprites. See where this will end? You either have to calculate the correct offset into your 1d-array from your 2d-coordinate:

```
roomSprites[y * xSize + x]->setPosition(sf::Vector2f(x * 32, y * 32));

```

or you'd set the position **before** you `push_back` the sprite:

```
sf::Sprite* sprite = new sf::Sprite();
sprite->setPosition(sf::Vector2f(x * 32, y * 32));
sprite->setTexture(roomTextures[texture]); //No need for another iteration over the vector to set the texture...
roomSprites.push_back(sprite);

```

---
Tags: c++, procedural-generation, sfml
---


# Question
Title: Architecture for game character movements with user input and a finite state machine
I have a JavaScript canvas game setup using Phaser framework. When I first made my character able to run, jump, and crouch, I used lots of if/else conditions and ended up with an ugly, buggy mess. I have read some articles about finite state machines and that seems to be the solution I need.

I am using javascript-state-machine and can't work out what kind of logic belongs where. My old logic looked something like this:

```
function update() { // ticks every frame
  if (cursors.right.isDown && !jumping && !crouching) {
    runRight(); // set character velocity and animation
  } else if( // more absurd complexity
}

```

What should be my first thought when trying to add a movement to the character? Do I think about the input first or define a state on the state machine first?

What exactly is a state? You can be moving right and jumping, but also moving to the right and not jumping. How are those movements described in terms of states?

What checks the user input for keys that are pressed or released and how does that interact with the changing of states?

A very helpful answer would include a psuedo code example of running and jumping that uses `javascript-state-machine`. I've read this interesting article that addresses character movement with an FSM, but I'm unable to apply those principles in JavaScript, with Phaser, and with this FSM library.

Here's some code from my most recent refactoring attempt in case it helps. I doubt it's even on the right track.

```
hero.sm = StateMachine.create({
  initial: 'standing',
  events: [
    {name: 'move', from: ['standing', 'jumping'], to: 'running'},
    {name: 'jump', from: ['standing', 'running'], to: 'jumping'},
    {name: 'stop', from: ['running', 'jumping'], to: 'standing'},
  ],
  callbacks: {
    // onEVENT
    onmove: (event, to, from, direction) => {

    },
    // onSTATE
    onrunning: () => {

    },
    // onSTATEleave
    onrunningleave: () => {

    }
  }
})

hero.update = () => {
  if (cursors.right.isDown || cursors.left.isDown) {
    hero.sm.move(cursors.right.isDown ? 'right' : 'left');
  } else {
    hero.sm.stop();
  }
}

```

# Answer
> 3 votes
I prefer not to use FSMs for movement, but it can work in certain cases. One of the things FSMs are great for is animations, which is what the linked example would easily tie into. The key thing to notice about the code you are working from is that lateral motion is considered in every one of their states using their function agent:getMovement(). Even in the Falling and Jumping states, the x position is updated based on if the player has one of the movement buttons pressed.

If you want to implement the system in that article, you will have to implement their update function and at the end when they call self:updateState(dt).

```
function update(currentState, dt) {
    if (currentState == "running") {
        var xv, yv = agent.getVelocity();
        var xm, ym = agent.getMovement();
        agent.setVelocity(xv + 4000 * xm * dt, yv);
    } elseif (currentState == "jumping") {
        ...
    }
}

```

Interestingly enough, you shouldn't have to implement any of the callback functions for the state machine (unless you want them to start playing an animation or something). The state machine in this case is a simple structure that your update loop uses to keep track of what it should be doing.

```
hero.sm = StateMachine.create({
  initial: 'standing',
  events: [
    {name: 'move', from: 'standing', to: 'running'},
    {name: 'jump', from: ['standing', 'running'], to: 'jumping'},
    {name: 'stop', from: 'running', to: 'standing'},
    {name: 'fall', from: ['standing', 'running'], to: 'falling'},
    {name: 'hitroof', from: 'jumping', to: 'falling'},
    {name: 'hitground', from: 'falling', to: 'standing'},
  ]});

```

Again, you should only need callbacks if you need something specific to happen when the state is first entered (such as playing a sound or animation).

---
Tags: javascript, movement, state, character, control
---


title: Unity3D 5 Personal?

text:
# Question
Title: Unity3D 5 Personal?
I want to make a game in Unity3D and I am planning to launch it to Android using the free license. However, if the game becomes a huge success and earns more than $100k, does (a) unity take the money for the pro license by themselves? or (b) do I need to pay for pro license myself? If (b) is applicable, how do I upgrade to the pro license and make sure my app is integrated with the pro license not the free version?

# Answer
http://unity3d.com/unity/faq

> **What happens if I/we make a game with Unity Personal Edition that earns more than $100,000?**
>
> To continue using Unity you would have to purchase a Unity 5 Professional Edition license, which you can do in the Online Store or through your regional Unity sales representative.
> 1 votes

---
Tags: unity
---


title: Format of bumpmaps

text:
# Question
Title: Format of bumpmaps
I have a height map I am generating in memory, just an array of floats from 0 to 1. I want to turn this into a bumpmap to be used in Unity3D. I believe I just need to create a Texture2D with the appropriate data in the RGB channels but I do not know what the format is for bump maps.

# Answer
> 2 votes
This page of the Unity Manual explains the format: http://docs.unity3d.com/Manual/StandardShaderMaterialParameterNormalMap.html

> The RGB colour values are used to store the X,Y,Z direction of the vector, with Z being “up” (contrary to Unity’s usual convention of using Y as “up”). In addition, the values in the texture are treated as having been halved, with 0.5 added. This allows vectors of all directions to be stored. Therefore to convert an RGB colour to a vector direction, you must multiply by two, then subtract 1. For example, an RGB value of (0.5, 0.5, 1) or #8080FF in hex results in a vector of (0,0,1) which is “up” for the purposes of normal-mapping - and represents no change to the surface of the model. This is the colour you see in the flat areas of the “example” normal map earlier on this page.

To convert your bump map into a normal map you take each pixels and compare their height to their neighbors in both X and Y direction.

You can use 2 neighbors in only one direction or average both sides (-1 and +1, shown below). Assuming a function texel(x,y) does proper wrap-around or clipping and returns the height of a texel, a cheap way to do it:

```
diff_x = Texel(x-1, y) - Texel(x+1, y);
diff_y = Texel(x, y-1) - Texel(x, y+1);

color.x = Clamp(diff_x * scale, -1, 1);
color.y = Clamp(diff_y * scale, -1, 1);
color.z = SquareRoot(1.0 - Clamp(color.x * color.x + color.y * color.y, 0, 1));

color = Normalize(color);

color = color * 0.5 + 0.5;

```

It's not quite right but it gives sharp edges and is quick to calculate.

The correct one uses

```
color.x = Normalize(Vec2(1, diff_x * scale)).y;
color.y = Normalize(Vec2(1, diff_y * scale)).y;

```

to calculate x & y properly.

---
Tags: unity, graphics
---


title: Slick & LWJGL Flickering Problem

text:
# Question
Title: Slick & LWJGL Flickering Problem
I have an flickering problem with rendering tiles. Rendering Method.

```
int tileSize = TileManager.tileSize;

    for(int y = 0 ; y < mapHeight ; y++){
        for(int x = 0 ; x < mapWidth ; x++){
            TileManager.tiles[tileIDs[y][x]].render(x * tileSize + xOffset, y * tileSize + yOffset, g);
        }
    }

```

TileManager

```
public static Tile[] tiles = new Tile[256];

public static final int tileSize = 32;

public static void loadTiles(String path){

    Image tileSet = GeneralUtils.getImage(path);

    int row = (int)Math.floor(tileSet.getWidth() / tileSize);
    int col = (int)Math.floor(tileSet.getHeight() / tileSize);

    for(int y = 0 ; y < col ; y++){
        for(int x = 0 ; x < row ; x++){
            tiles[x + y * row] = new Tile(tileSet.getSubImage(x * tileSize, y * tileSize, tileSize, tileSize));
        }
    }

}

```

Finally Tile

```
private Image tileImage;

public Tile(Image tileImage){
    this.tileImage = tileImage;
}

public void render(int xPix, int yPix, Graphics g){
    g.drawImage(tileImage, xPix, yPix);
}

```

If i render like this there is no flickering. I couldnt understand why ?

```
img = new Image("Res/blabla.png");
----------------------------------------------------
int tileSize = TileManager.tileSize;

    for(int y = 0 ; y < mapHeight ; y++){
        for(int x = 0 ; x < mapWidth ; x++){
            g.drawImage(img, x * tileSize + xOffset, y * tileSize + yOffset);
        }
    }

```

# Answer
Solved by using vsync.

```
private static AppGameContainer gameApp;
gameApp.setVSync(true);

```
> 1 votes

---
Tags: java, rendering, lwjgl, slick
---


# Question
Title: Decoupling input from game states / entity behavior
I'm looking for a way or general best practice advices for decoupling the architecture of my game, in the example below the input from the current game state workflow / entity behavior. While I'm all in for certain game development (or general) patterns such as an event- or component-driven design, I'm failing to understand how a decoupled architecture can work in a case where e.g. an entity actually needs to know a little bit more.

Take for example this little (bad) example:

```
// some component attached to an entity
void Update(long elapsedTime) {
    var keyboardState  = _keyboardDevice.State;
    var gameState      = _gameStateStack.CurrentState;

    if(keyboardState.IsPressed(Keys.Enter) {
        if(gameState.GetType == typeof(MenuState))
            ((MenuState)gameState).ExitMenu();
        } else {
            parent.Jump();
        }
    }
}

```

The requirements are pretty simple: If we're in the game menu, pressing enter closes the menu. However if the menu is not active, pressing enter causes the entity to jump. If I'm going to decouple the menu and the entity component using an event-driven approach...

```
// menu state
class MenuState : IHandle<KeyCommand>() {
    void Handle(KeyCommand keyCommand) {
        if(keyCommand.Key == Keys.Enter && keyCommand.IsPressed)
        ...
    }
}

// entity component
class EntityControllerComponent : IHandle<KeyCommand>() {
...
}

```

... the concerns are clearly separated. But what happens now if I press the ENTER key? Who decides which part of the game is allowed to actually receive and handle the event?

# Answer
Input is hard. Most of the simple patterns you see frequently in game dev just don't work well for input, at least at the low level.

Typically, for any kind of GUI, you need to have some concepts of focus and possibly also bubbling. The HTML/DOM model here is a good resource.

In such a setup, there is a sorted queue of event listeners. For a GUI, this would be a stack of widgets starting from where focus lies. For games, this might be the stack of game states or overlay panels. The input event is either only delivered to the top-most listener (so any overlay implicitly "blocks" all others from receiving input) or is handed to each in turn (giving each a chance to optionally block the remaining listeners from receiving the event).

There are weird complexities with input handling, too. For instance, in many input designs, you differentiate between `KeyPressed` and `KeyReleased` events. However, if you just deal with those naively, it becomes possible for one listener to receive the `KeyPressed` for a particular key and a completely different one to receive the `KeyReleased`. The first system might have some important logic that must be run after the release but it never finds out about it. You can see this in some games where you start moving, a dialog pops up, and the character continues moving even though you've let go of the movement key.

A solution for the above then is to remember which listener received any particular `KeyPressed` or `ButtonPressed` event and ensure that it receives the corresponding release events independent of which listener has priority. Likewise, if the whole app is unfocused (say via alt-tabbing away) then the input module can be sure to send simulated release events to any listeners that had received press events.

I can't stress enough: you basically *have* to use a pattern like that for handling the input at an application level.

Now, within the game itself, that is all inconvenient and wrong. You don't want your character controller to be dealing with input priorities and event canceling. In fact, you almost certainly don't want your character controller even handling low-level input events: the controller shouldn't have to figure out whether a key was `Space` or `RightArrow`. It just wants to know that the user pressed the JUMP key or that the right wants to move right.

This generally means you have an intermediate high-level gameplay input module. It registers into the input event priority list and then translates the low-level input events that it actually receives (individual key presses and the like) into generic gameplay-relevant events. It handles key mapping and rebinding, it handles abstraction gamepad input from keyboard input, and so on. The entire rest of the gameplay systems can then just deal with simple events while all the complexity of input focus is localized to that one gameplay input module.

TL;DR: use a priority list of input event listeners for low-level input and simple game events for high-level abstract gameplay controls.
> 10 votes

# Answer
One possible way to decouple this example would be to use a stack of event handlers. Your program can iterate the stack in order, trying each listener until one handles the event:

```
class MenuState : public IKeyListener {
    ...
    boolean OnKeyEvent(const KeyEvent& keyCommand) {
        if (keyCommand.Key == Keys.Enter && keyCommand.IsPressed) {
            CloseMenu();
            return true;
        }

        // The engine calls the next IKeyListener
        return false;
    }
    ...
};

class PlayerState : public IKeyListener {
    ...
    boolean OnKeyEvent(const KeyEvent& keyCommand) {
        if (keyCommand.Key == Keys.Enter && keyCommand.IsPressed) {
            player.Jump();
            return true;
        }
        return false;
    }
    ...
};

```

But in order to retain flexibility in situations where multiple handlers may need to observe the event, "Bubbling" can be applied so that all handlers get to see the event:

```
class MenuState : public IKeyListener {
    ...
    boolean OnKeyEvent(const KeyEvent& keyCommand, boolean eventHandled) {
        if (eventHandled) return false;

        if (keyCommand.Key == Keys.Enter && keyCommand.IsPressed) {
            CloseMenu();
            return true;
        }

        // The engine calls the next IKeyListener
        return false;
    }
    ...
};

class PlayerState : public IKeyListener {
    ...
    boolean OnKeyEvent(const KeyEvent& keyCommand, boolean eventHandled) {
        if (eventHandled) return false;

        if (keyCommand.Key == Keys.Enter && keyCommand.IsPressed) {
            player.Jump();
            return true;
        }
        return false;
    }
    ...
};

class CheaterState : public IKeyListener {
    ...
    boolean OnKeyEvent(const KeyEvent& keyCommand, boolean eventHandled) {
        buffer += keyCommand.Key;
        if (buffer.Length > LongestCheat) {
            buffer = buffer.Substring(1);
        }
        if (TryCheatCode(buffer)) {
            buffer = "";
            return true;
        }
        return false;
    }
    ...
};

```
> 2 votes

---
Tags: c#, game-design, software-engineering, game-mechanics
---


title: Mouse Aiming Causing Rotation Jitter

text:
# Question
Title: Mouse Aiming Causing Rotation Jitter
When our game's ships move around, mouse aiming causes them to shake around a lot. The body being aimed is moved kinematically. I think we've narrowed it down to this block of mouse tracking code.

Demonstration of the glitch

You can see around 0:35 where I disable the mouse tracking code momentarily, the ship stops shaking.

```
    public static Quaternion RotateToMouse(this Ship ship, Transform transform, float ShipRotateSpeed)
    {
        // Generate a plane that intersects the transform's position with an upwards normal.
        Plane playerPlane = new Plane(Vector3.up, Vector3.zero);

        // Generate a ray from the cursor position
        Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);

        // Determine the point where the cursor ray intersects the plane.
        float hitdist = 0.0f;
        // If the ray is parallel to the plane, Raycast will return false.
        if (playerPlane.Raycast (ray, out hitdist))
        {
            // Get the point along the ray that hits the calculated distance.
            Vector3 targetPoint = ray.GetPoint(hitdist);

            // Determine the target rotation.  This is the rotation if the transform looks at the target point.
            Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);

            // Smoothly rotate towards the target point.
            transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, ShipRotateSpeed);
            transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0);
        }
        return transform.rotation;
    }

```

We've got no idea whats going wrong, any help will be greatly appreciated. thanks.

# Answer
Something i forgot to include was the fact the camera was moving with the ships. When I made the Camera stationary it seamed to work perfectly, so i simply created another camera and kept it at **Vector3(0,30,0)** and used it to track the mouse instead.

Changing the code slightly to be:

```
    public static Quaternion RotateToMouse(this Ship ship, Transform transform, float ShipRotateSpeed)
    {
        Vector3 MousePos = Input.mousePosition;

        // Generate a plane that intersects the transform's position with an upwards normal.
        Plane playerPlane = new Plane(Vector3.up, Vector3.zero);

        // Generate a ray from the cursor position

        Ray ray = Vitals.MouseCam.ScreenPointToRay (MousePos);

        // Determine the point where the cursor ray intersects the plane.
        float hitdist = 0.0f;
        // If the ray is parallel to the plane, Raycast will return false.
        if (playerPlane.Raycast (ray, out hitdist))
        {
            // Get the point along the ray that hits the calculated distance.
            Vector3 targetPoint = ray.GetPoint(hitdist);
            targetPoint += transform.position;
            // Determine the target rotation.  This is the rotation if the transform looks at the target point.
            Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);

            // Smoothly rotate towards the target point.
            transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, ShipRotateSpeed);
        }
        return transform.rotation;
    }

```

Something about the Camera moving caused the calculations to be slightly different every tick? Ideas ?
> 1 votes

# Answer
There is simpler solution. That jittering happens because GUI is updated more frequently than the Update or LateUpdate. Just move the code related to raycasting from **moving** camera through cursor position into the *OnGUI()* function instead of *Update()* or *LateUpdate()*. Everything runs smoothly. Just remember that it may be called more than one time per frame so do there only what is necessary.
> 0 votes

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


# Question
Title: Global PostProcess in UnrealEngine 4.10.2
I am new to UnrealEngine and following few tutorials to get started with.

I am trying to find "Global PostProcess" (in World Outliner) in UnrealEngine 4.10, but I am not able to find it. Has it been changed compared to previous version of UnrealEngine? If so whats the alternative of it?

Thanks.

**Update**

This is what I have:

And it doesn't look anything like whats there in this link (see Assigning to a Post Process Volume)

https://docs.unrealengine.com/latest/INT/Engine/Rendering/PostProcessEffects/PostProcessMaterials/PostProcessDemoMaterialOverview/index.html

# Answer
I think that what you need, it's to add a Post Process Volume to your map and set it up to Unbound. This will make your PPVolume "global", affecting everthing boundless.
> 2 votes

---
Tags: unreal-4, post-processing
---


# Question
Title: Is flowchart correct way to visualize gameplay?
I made the following flowchart in draw.io. it's just a simple arcade shooter. cardboard zombie pops up, bang, or not. I don't have any official education in game production.

So, are there other chart styles, or UML diagrams that would be better suited for drafting this type of simple game play?

# Answer
> 5 votes
Flowcharts and diagrams are very often used to represent game mechanics or game-play. I would dare to say that most visual assessment of game mechanics are indeed based on some given type of flowchart or diagram.

Now, there is no specific standard on the specifics of what should be represented in such diagrams. But of course there are quite a few suggestions on how to think about game mechanics in an organized manner.

At GDC 2005, there was a presentation called "Game Design Atoms, Can Games Be Diagrammed?" that might be of interest. Later on, Stéphane Bura proposed an elaboration to that use of diagrams in representing games: http://www.stephanebura.com/diagrams/

A great article on that is also Gamasutra's "Game Design Tools for Collaboration". There you will find more on diagram-based approaches, the suggestion of using tokens, a quick summary of Daniel Cook's Game Alchemy for Skill Atoms that was already suggested in the comments, and also some mention to a more recent interesting paper called "MDA: A Formal Approach to Game Design and Game Research", that is surely worth reading.

Lastly, if you don't know of it yet, there is a very nice paid software that allows for integrated story-telling, preparation of game-play diagrams and so on: Articy:draft2. While it is paid, there is a trial version available. Its trailer can be seem in youtube at https://www.youtube.com/watch?v=JaKkHHjVPtU.

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


# Question
Title: Scalling down libgdx game to fit a smaller screen appears only the half of the stage?
Hello I have made a game in 1280x720, but I want it to fit devices with smaller size, so far no luck with the current code it only shows the left half of the screen, it also does not work with bigger sizes, there it shows the scene in the left corner and the remaining is black screen, here is my code:

```
public class MenuStage extends Stage implements Screen {
private PlayStage playStage;
private UVeggFruit uVeggFruit;
private OrthographicCamera orto;
private Viewport vport;

public MenuStage(UVeggFruit uvf) {
    uVeggFruit = uvf;
    initMenu();

}

private void initMenu() {
    ButtonClickListener buttonClickListener = new ButtonClickListener();
    SceneLoader sc = new SceneLoader();
    CompositeItemVO sceneComposites = new CompositeItemVO(sc.loadScene("MainMenu").composite);
    CompositeActor UI = new CompositeActor(sceneComposites, sc.getRm());
    addActor(UI);
    UI.getItem("playbutton").addListener(buttonClickListener);
    UI.getItem("playbutton").addListener(new ClickListener() {
        @Override
        public void clicked(InputEvent event, float x, float y) {
            super.clicked(event, x, y);
            playStage = new PlayStage(uVeggFruit);
            uVeggFruit.setScreen(playStage);
        }
    });
    orto = new OrthographicCamera();
    vport = new ScalingViewport(Scaling.stretch, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), orto);
    vport.apply();

}

@Override
public void show() {
    Gdx.input.setInputProcessor(this);
}

@Override
public void render(float delta) {
    orto.update();
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    this.act();
    this.draw();
}

@Override
public void resize(int width, int height) {
    vport.update(width, height);
}

@Override
public void pause() {
}

@Override
public void resume() {
}

@Override
public void hide() {
     }
  }

```

Is it wrong that I put viewport in every stage, or I should put it in the application adapter and it will work for all stages? So basically what I want is that my stage renders as it would in 1280X720, but with smaller size, so how is this possible so I can see my whole stage no mater the screen size which is the general goal?

# Answer
OK so I don't understand why you are extending *`Stage`* but lemme provide an exemple of how to use the View port to fit your needs what ever the screen size:

lets start with your show method you can get rid of `this` keyword and remove `extend stage` and do something like so instead :

create a public static attribut stage :

```
public static Stage stage;

```

then inside your show method :

```
stage = new Stage();
Gdx.input.setInputProcessor(stage);

```

I know it's the same but this is more readable, also you dont have to use `OrthographicCamera()` stuff if your UI mainMenu is structured inside a `Table` `object` like so :

```
 table.add(MenuUIStuff).top().spaceLeft(60).row();
 table.add(MenuUIStuff);
 table.add(MenuUIStuff).bottom().right().expandX();

```

and then in your `show method` dont forget to add your table to the actual stage:

```
stage.addActor(table);

```

all this needs to be in your show method ( again for better readability if you want to respect Libgdx style )

then in your render method :

```
stage.act(delta); // instead of this
stage.draw(); // same here

```

now to answer your question the solution will be :

```
@Override
    public void resize(int width, int height) {
        stage.getViewport().update(width, height);
        table.invalidateHierarchy();
    }

```
> 0 votes

---
Tags: libgdx, screen, viewport
---


title: Set default values by script?

text:
# Question
Title: Set default values by script?
Insted of Inspector, I want to set default values by script because there is `MeshRenderer`, a `RigiBody` etc. I don't know how to write this in script. These are not numerical values.

# Answer
> 0 votes
If the component is on the same game object as your script, you can do:

```
void Awake()
{
    Rigi = GetComponent<Rigidbody>();
}

```

This will search the game object this script is attached to for a component of the given type(and return the first one found if there are multiple.)

If you want something that's in the same scene as this gameobject you can use:

http://docs.unity3d.com/ScriptReference/Object.FindObjectOfType.html

Correct me if I'm wrong, but I think that will only get scene objects since assets are not active.

If you want something that exists as only an asset then it's a little harder. You'll need to use a combination of:

http://docs.unity3d.com/Manual/editor-CustomEditors.html

And: http://docs.unity3d.com/ScriptReference/AssetDatabase.LoadAssetAtPath.html

You could create a custom editor in order to use AssetData.LoadAssetAtPath(with a hard coded path). Assign this reference to a serialized field and it'll be available and valid in a build.

I don't recommend doing any of this. Just drag a drop the references. It has a lot of problems, but it's far better than the alternatives.

# Answer
> 0 votes
Inside your script where you have method void Start(), add there your default values for properties, for example:

```
void Start()
{
     Pop = 10;
     Bolly = true;
}

```

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


# Question
Title: Why can't I sample a texture in a vertex shader?
I'm old in Game Development but very new in shader writing. I just want a shader that transform from 1 texture to another. So I did start learning shader writing and wrote my desired shader. But during writing one thing I cannot understand as I am very dumb in shader writing that if I assign `fixed4` color with `COLOR` semantic in `vertex` method then compiler gives the following error.

> Shader error in 'Hamza/TwoTextures': cannot map expression to vs\_4\_0 instruction set at line 39 (on glcore)
>
> Compiling Vertex program Platform defines: UNITY\_ENABLE\_REFLECTION\_BUFFERS UNITY\_PBS\_USE\_BRDF1 UNITY\_SPECCUBE\_BOX\_PROJECTION UNITY\_SPECCUBE\_BLENDING SHADER\_API\_DESKTOP UNITY\_TEXTURE\_ALPHASPLIT\_ALLOWED

Here is the not working shader code,

```
Shader "Hamza/TwoTextures"{
    Properties{
        [NoScaleOffset]
        _Texture1 ("Texture 1",2D) = "white"{}

        [NoScaleOffset]
        _Texture2 ("Texture 2",2D) = "white"{}

        _Mixer ("Mixer", Range(0,1)) = 0
    }

    SubShader{
        Pass{
            CGPROGRAM

            #pragma vertex vert
            #pragma fragment frag

            sampler2D   _Texture1;
            sampler2D   _Texture2;
            float       _Mixer;

            struct appdata{
                fixed4 vertex   : POSITION;
                fixed2 tex      : TEXCOORD0;
            };

            struct v2f{
                fixed4 pos      : SV_POSITION;
                fixed2 tex      : TEXCOORD0;
                fixed4 col      : COLOR;
            };

            v2f vert(appdata i){

                v2f o;
                o.pos = mul(UNITY_MATRIX_MVP,i.vertex);
                o.tex = i.tex;

                // Giving error on this line
                o.col = (tex2D(_Texture1,i.tex) * _Mixer) + (tex2D(_Texture2,i.tex) * (1 - _Mixer));
                return o;
            }

            fixed4 frag(v2f v) : COLOR
            {
                return v.col;
            }

            ENDCG
        }
    }
}

```

And if I write same expression to throw it as return `fixed4` value in `fragment` method then everything is working fine.

Here is working shader code,

```
Shader "Hamza/TwoTextures"{
    Properties{
        [NoScaleOffset]
        _Texture1 ("Texture 1",2D) = "white"{}

        [NoScaleOffset]
        _Texture2 ("Texture 2",2D) = "white"{}

        _Mixer ("Mixer", Range(0,1)) = 0
    }

    SubShader{
        Pass{
            CGPROGRAM

            #pragma vertex vert
            #pragma fragment frag

            sampler2D   _Texture1;
            sampler2D   _Texture2;
            float       _Mixer;

            struct appdata{
                fixed4 vertex   : POSITION;
                fixed2 tex      : TEXCOORD0;
            };

            struct v2f{
                fixed4 pos      : SV_POSITION;
                fixed2 tex      : TEXCOORD0;
            };

            v2f vert(appdata i){

                v2f o;
                o.pos = mul(UNITY_MATRIX_MVP,i.vertex);
                o.tex = i.tex;
                return o;
            }

            fixed4 frag(v2f i) : COLOR
            {
                // It is giving me no error
                return (tex2D(_Texture1,i.tex) * _Mixer) + (tex2D(_Texture2,i.tex) * (1 - _Mixer));
            }

            ENDCG
        }
    }
}

```

**Can anyone explain me that why it is happening? And what is the difference between them?**

As I mentioned that I did start learning only two days before. I'm sort of noob in this.

# Answer
> 13 votes
The error here is that you're trying to sample from a texture in a vertex shader the way you would in a fragment or pixel shader.

Vertex texture fetches are a little bit special. They're only supported in Shader Model 3 and up, and they're unable to use the `tex2d()` function.

That may sound odd, but `tex2D()` is really a shortcut that says "figure out the right mip level to sample automatically" - in a fragment shader this is done using implicit derivatives, but those aren't available at the vertex stage.

So, we need to use the more explicit `tex2dlod()` form (which works at both the vertex and fragment stages). This takes a 4-component vector, whose `x` and `y` are the familiar texture coordinates in uv space, and `w` indicates which mip level to sample from (0 being the highest resolution available).

---
Tags: unity, shaders, cg, shaderlab
---


# Question
Title: giving to object velocity to the direction it facing (unity)
I making 2d game on unity5 .I want to give to an object starting velocity to the direction it is facing(looking).(I put it in the "start" method) how can i do it?

# Answer
> 1 votes
Well, on **DMGregory's** pointing, I did realize that you want this work done in 2D. So, I did some work on this, here I'm pasting the code which should be attached to your object which you want to accelerate.

Here are some assumptions I made,

* Your object is not child. (Otherwise it will be not a big deal though, you have to play with `+ 90` factor)
* Your object should have attached `Rigidbody2D`.
* Wrote this script with getting input from keyboard. Do change it according to your needs.

Code,

```
// Rotation Speed
public float _rotationSpeed = 1;

// Speed
public float _velocity = 1;

// Attached Rigidbody2D
Rigidbody2D _rb;

void Start ()
    {
        _rb = GetComponent<Rigidbody2D> ();
    }

void Update ()
    {
        // Getting input from keyboard (w,d / Left arrow,Right arrow)
        float horizontalInput = Input.GetAxis ("Horizontal");

        // Applying rotation according to inputs
        transform.localEulerAngles = new Vector3 (transform.localEulerAngles.x, transform.localEulerAngles.y, transform.localEulerAngles.z - (horizontalInput * _rotationSpeed));

        // Getting angle which will help to move object to forward
        // + 90 is the factor as 2d sprites have z rotation of -90 degrees while it look visually as angle with 0 degrees. PLay with it if your object is child of another.
        float theta = transform.localEulerAngles.z + 90;

        // Getting new X direction
        float newDirX = Mathf.Cos (theta * Mathf.Deg2Rad);

        // Getting new Y direction
        float newDirY = Mathf.Sin (theta * Mathf.Deg2Rad);

        // Applying velocity according to current angle
        _rb.velocity = new Vector2 (newDirX, newDirY) * _velocity;
    }

```

I wrote it in hurry, if you still find any problem then let me know

# Answer
> 0 votes
We want to simulate wind resistance.

There is some restoring torque $\tau$ that will align your velocity $\vec{v}$ with your attitude $\vec{a}$ (where *attitude* is the direction you are pointing, and *you* means the projectile.

A torque pointing into the page will push youe body clockwise, and out of page will push your body counter-clockwise.

$\tau = k\_{air} * \vec{a} \times \vec{v}$ will push the projectile's attitude to line up with its velocity. Where k is a number you make up that makes the projectile swing at an acceptable rate.

---
Tags: unity
---


# Question
Title: Should I store game settings in my game data class?
I'm working on a small-ish 2d fixed shoot 'em up for iPhone.

I have a master Game object that stores lives, score, current level, etc...

The game will have some other persistent attributes like Music and Sound mute state, difficulty level (easy, medium, hard).

Should I put those attributes in the Game class or should they be on their own?

What's the rule of thumb to decide how to partition attributes among classes?

# Answer
It's all subjective, but consider the Single Responsibility Principle as a "rule of thumb". If you break them up now then you can potentially do things with the separate classes later without worrying about messing it up. Maybe you'll want the game object to be deleted and recreated every level, and if you split them up you won't have to worry about the design needs of one affecting the other.
> 6 votes

# Answer
This is a relative question and I'd say it depends on how you feel would be easier to maintain. If your game would grow 2, 3 or 10 times its size. Would it get lost outside the Game object? Or would it be lost inside the Game object? You just have to put it where you feel it belong, I don't think there are any rule of thumb here.
> 1 votes

# Answer
A common approach is to have a central "Settings" object which is implemented as a class which follows the Singleton pattern. When another class needs to look up the value of a setting, they obtain the instance of the Settings class and look it up.

The Settings class should also include the necessary code to persist and retrieve the settings. Any values which are not supposed to be persisted between runs of the game (like the game state, extra lifes, score etc.) should not be stored in that class. If you want to persist these in form of savegames, you should write separate functionality in your "master Game object" to serialize it to a savegame file and to initialize it from a savegame file.

The reason for the separation between settings and savegames is that players usually expect that their settings are global and not bound to a specific savegame.
> 0 votes

---
Tags: game-design, architecture, iphone, settings
---


# Question
Title: Layering with slopes in Unity 2D isometric scene
I'm newer to Unity so bear with me. I'm using `Unity2D` and so far I have my character up and walking around, colliding properly with his surroundings, and I've implemented an effective `"isometric sorting"` script which swaps the order of sprites based on their y coordinate. What I'm trying to do now is create a slope that exists in the middle of the stage or front (bottom of screen). I'll illustrate what I'm trying to do as explaining it is bound to be confusing.

Right now, I have the ability to move the player up the slope, and in front of the slope (using the isometric sorting script), but it seems maybe impossible to *also* be able to have the player walk behind the slope.

Here's my idea for how this could be accomplished, but I certainly would need some direction.

Basically, I'm thinking if I can detect that the player has crossed the green line in the image, I could use that information to flip a switch ON which would lower the slopes sorting priority (thus lowering it beneath the players feet), then I would need it to deactivate when the Player exits the slope.

Here is the Isometric Rendering script:

```
    using UnityEngine;

    [ExecuteInEditMode]
    public class IsometricSpriteRenderer : MonoBehaviour {

    void Update ()
    {
         GetComponent<Renderer>().sortingOrder = (int)(transform.position.y *       -1000);
    }
}

```

Thank you to anyone who bothers to take the time to help me! I really appreciate it!

# Answer
It looks like a wrong approach. Check this tutorial: https://unity3d.com/learn/tutorials/modules/beginner/2d/sorting-layers

In order to sort your stuff properly and automatically you can use depth (*z*) and/or sorting layers within objects at the same depth and/or order in layer within objects in the same sorting layer. It's probably reasonable to have objects representing fixed features of the game world (like the slope) use fixed depth/layer/order and have objects representing moveable features of the game world (like the characters) use variable depth/layer/order.

Keep colliders for actual collisions.
> 1 votes

---
Tags: unity, 2d, isometric, depth
---


# Question
Title: How to make ranked matches in a head-to-head multiplayer game?
I am working on a field hockey like game for Android and iOS. Currently I support being able to play against another player online in a client/server fashion where one device host and the other provide an IP address.

I would like to be able to have ranked matches that are recorded in something like Amazon's GameCircle or something similar.

For recording the win/loses I thought having one leaderboard for wins, one leaderboard for loses and perhaps another leaderboard for amount of games in progress...

That is assuming I can read the leaderboard result for each player which I think I can.

Other than that, there are many issues in how to have ranked matches. I am guessing the biggest difficulty is actually being able to have a client/server session since most devices are not set up to have a direction communication with another device?

What are your suggestions for having ranked matches given no extra server? And what are your suggestions given my own server?

# Answer
You will need a server handling the match-making. If a device or player connects to the server, the player needs to deliver its player-statistics which are crucial for finding a fair opponent. You could store the active connections (connected players) in an array or database to find the right one.
> 1 votes

# Answer
I would do a copy of something like the ELO system with steam or trophies with Clash of Clans, personally I would make an algorithm where depending on your score to the enmies' score each goal, win, body check, or whatever that involves skill would gain you a certain amount of score, as well as getting scored on, losing, getting body checked, etc. makes you lose score determined by the other player's rank and yours. Take the score and put a rank on top of it like. 1-100 score is considered novice, 100-300 is Seasoned, 300-700 is NHL, and 700-100 is professional or something along those lines. Players also need to be ranked with players close to their score to ensure fair gameplay, I would make it so there is a limit to how far away the score can be before not being allowed to be matched up together. This is just how I would do it though, be original and have fun making your game.
> 0 votes

---
Tags: android, networking, multiplayer, google-play, google-play-services
---


# Question
Title: Optimize algorithm: finding all possible moves for a turn based game
I am working on the ai for a turn based game. To illustrate my problem this are the simplified rules of the game:

The game takes place on a tiled map with obstacles (black quads) like this:

* The player has several tokens (like the two colored dots in the example picture)
* The player can move all his tokens in his turn
* the tokens move in a straight line until they hit an obstacle, the border of the map or another token
* each token could move two times in each turn.
* the player can move his tokens in any order he likes

The AI needs a list of all possible turns it could make of one game state. My first attempt was to recursively go through all tokens and move them in any possible direction and order. that works of course but the problem is that with just four tokens there are several millions of possible turns (if each token could move two times). Most of the outcomes of these turns are the same (the tokens end in the same place). In the example above the tokens could move like this:

No matter in which order the four move actions (A,B,C,D) are made, the end positions of the tokens are the same. I am only interested in the possible end turn situations. So I implemented a transposition table in the turn generation algorithm to negate all of the equal turns. That works and in the end I have only several hundred of possible turns with four tokens rather than several millions. The problem is that the algorithm takes too much time because it has to calculate every possible turn. Does anybody has a hint how to prune the turn generation tree? Or any other idea how to calculate only the different possible turn outcomes?

Note: In the real game the map is slightly bigger (30-40 free cells) and there are up to 6 tokens.

# Answer
> 2 votes
I don't have a complete answer for you, just a few lines of thought...

**1) Construct a dependency graph**

As you consider each move each token can make, store a reference to that move with each cell it passes through.

When a later move ends in one of the marked cells, we've identified a potential new dependency: performing move B before move A can change the outcome of move A. Then you can recursively check the outcome of the modified move A...

This requires some care to ensure you don't follow cycles of mutually-exclusive moves (ie. performing move A first modifies the outcome of move B which modifies the outcome of move A... but no it doesn't, because A already happened!)

Hypothetically this could get you some savings in the event that your tokens are separated from each other, so that many of the outcomes are independent of one another (your dependency graph ends up sparsely-connected). You can separate a turn into clusters, where each cluster contains multiple mutually-affecting moves (where you need to consider order, but of a smaller subset of moves) and clusters minimally affect one another (so you can ignore order between clusters, or consider fewer ordering cases).

However, my suspicion is that mutual interactions are much more common, and that you'd be introducing a lot of complexity to the algorithm for comparatively little pruning.

**2) Consider a goal-based approach**

A human player won't visualize every possible move. They'll usually have a strategy in mind, like "I want to get my red token in position to do X" then they'll look for a sequence of moves that accomplish this goal, often by working backwards from the goal state and considering only interactions that move them towards it.

So if your aim is to get a reasonable-performing adversary rather than one which always finds the best possible move, structuring it around goal-seeking behaviours rather than minimax tree search may reduce your problem space to a more manageable size.

Since I don't know much about the rules of your game, I can't speculate on what your goal logic might be, and generally they require more sophisticated AI design than search-based approaches.

You can even try a hybrid approach, where you do a minimax search over a set of goals rather than individual moves, pruning goals which turn out to be unfeasible once their move sequence is examined.

**3) Consider sampling**

If none of the above work, a fallback is to just try to search as much of the tree as you can within your available time & performance budget. This means trying to optimize your exhaustive search inner loop as much as possible, making sure you're using your transposition table to save redundant work on intermediate states and not just final configurations.

You'll want to randomize the order in which you consider moves, to avoid biasing the AI to search moves for the first token more exhaustively than the last, for example.

Whenever you hit your limit, stop, and use the best result you've found so far. You'll likely want to frame this limit in terms of steps rather than realtime, so that players on faster machines don't have to contend with stronger AI than those closer to the minimum spec. ;)

---

Overall, my algorithmic spidey sense is giving me that tingly feeling that there might not be any easy shortcuts here, and that a good approximation that's achievable with clear and maintainable code and scalable performance might be a better target to aim for than a complex algorithm that's provably optimal.

# Answer
> 1 votes
I would start from the end positions, because this is what matters.

There are 2 tokens and 21 blank squares in your example, which means that in the worst case (all ordered pairs of squares represent reachable outcomes) there are 420 valid outcomes.

Check each of these possible outcomes to look for one valid way of reaching it, once you find one way of moving your tokens there mark the outcome as valid and move to the next possible outcome to check. If you don't find any, mark it as invalid and move on.

At the end of the process you have your list of reachable outcomes and you have avoided computing duplicate ways of reaching the same outcome.

No free lunch though, of course. Now the problem becomes how to search for one way of taking all tokens in each ordered set of end positions. But you have a lot of information to use for making the algorithm smarter than "Check all possible moves and turns and verify whether they end up there". For instance, no need to turn left if the required end position is on the right; or, in your example, the green end position cannot be reached in any other way than coming from the left.

It's going to be tough but it's feasible IMHO. And a fun algorithm to code.

# Answer
> 1 votes
For such problem I'd rather go for a Montecarlo algorithm. For each possible move make `N` random plays and count the number of computer wins. Let the computer do the move with the higher number of wins.

`N` should be sufficiently large. The larger that number, the strongest the computer will be

Doing this way the computer will force the game into the ''path'' in which it has the best chances of winning.

No need to implement a minmax algorithm nor to explore all the possible branches. Just pick a random move, do the simulation until either the human wins, the computer wins or it is a draw. Repeat.

---
Tags: ai, turn-based-strategy
---


# Question
Title: where can I download unity assets without opening it in in unity.
I'm browsing through my mobile phone and I need to download unity assets but unity asset store demands that I open the assets in unity directly. How or which site can I download it on my mobile and send it to my PC.

# Answer
It isn't possible to do it outside of Unity3D. However, you could write a script that can pull the data from URLs of your choice in a Unity project and save it to a specific folder on your computer, that way you have the assets for later. Or, you could just have a dummy project and download all the assets that look useful for your current and possibly future projects as a means of storage for later use. This isn't exactly what you want, but as far as I know, these are the only ways you could do it.
> 1 votes

---
Tags: unity, assets, asset-management
---


# Question
Title: Unity Shader Material Only Activates when Clicked
I am currently programmatically settings some shader textures, related to a Mesh Filter. The Mesh Filter is using a standard shader, and I am merely generating and setting the Bump and Height maps, via code.

```
Sphere.materials [0].mainTexture = biome;
Sphere.GetComponent<MeshRenderer> ().materials [0].SetTexture ("_BumpMap", bump);
Sphere.GetComponent<MeshRenderer> ().materials [0].SetTexture ("_ParallaxMap", heightTexture);

```

This is fine. The issue is that the shader only seems to activate itself once it is clicked in the inspector. Is there some sort of Activate() function I need to call in order to apply the shader effects to the Mesh?

Notice in the example (this is running in Play mode), that the shader only activates once I click the expand button on the Shader in the inspector.

What is going on here?

# Answer
OK, So taken from http://docs.unity3d.com/Manual/MaterialsAccessingViaScript.html :

> The Standard Shader has some extra requirements if you want to modify Materials at runtime, because - behind the scenes - it is actually many different shaders rolled into one.
>
> These different types of shader are called Shader Variants and can be thought of as all the different possible combinations of the shader’s features, when activated or not activated.
>
> For example, if you choose to assign a Normal Map to your material, you activate that variant of the shader which supports Normal Mapping. If you subsequently also assign a Height Map then you activate the variant of the shader which supports Normal Mapping and Height Mapping.

If you do not set a default image for the Height Map of your shader, it will not activate the shader feature.

By setting a default HeightMap (just a blank image for example), the Shader activates on run as expected.
> 1 votes

---
Tags: unity, shaders
---


# Question
Title: Android libGDX FreeTypeFontGenerator exception
I am working on a libGDX project for Android. Since I added the following code, running the game on my Android phone produces an exception:

```
final FreeTypeFontGenerator generator = new FreeTypeFontGenerator(fontFile);
final FreeTypeFontParameter parameter = new FreeTypeFontParameter();
parameter.size = 36;
this.font = generator.generateFont(parameter); // line 43
generator.dispose();

```

I am using libGDX version 1.7.0. Here is the gradle.build:

```
buildscript {
    repositories {
        mavenCentral()
        maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
        jcenter()
    }
    dependencies {
        classpath 'de.richsource.gradle.plugins:gwt-gradle-plugin:0.6'
        classpath 'com.android.tools.build:gradle:1.2.3'
        classpath 'org.robovm:robovm-gradle-plugin:1.8.0'
    }
}

allprojects {
    apply plugin: "eclipse"
    apply plugin: "idea"

    version = '1.0'
    ext {
        appName = "unicorn"
        gdxVersion = '1.7.0'
        roboVMVersion = '1.8.0'
        box2DLightsVersion = '1.4'
        ashleyVersion = '1.6.0'
        aiVersion = '1.6.0'
    }

    repositories {
        mavenCentral()
        maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
        maven { url "https://oss.sonatype.org/content/repositories/releases/" }
    }
}

project(":desktop") {
    apply plugin: "java"

    dependencies {
        compile project(":core")
        compile "com.badlogicgames.gdx:gdx-backend-lwjgl:$gdxVersion"
        compile "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-desktop"
        compile "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-desktop"
        compile "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-desktop"
    }
}

project(":android") {
    apply plugin: "android"

    configurations { natives }

    dependencies {
        compile project(":core")
        compile "com.badlogicgames.gdx:gdx-backend-android:$gdxVersion"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi-v7a"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-x86"
        compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi-v7a"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-x86"
        compile "com.badlogicgames.gdx:gdx-freetype:$gdxVersion"
        natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-armeabi"
        natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-armeabi-v7a"
        natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-x86"
    }
}

project(":core") {
    apply plugin: "java"

    dependencies {
        compile "com.badlogicgames.gdx:gdx:$gdxVersion"
        compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"
        compile "com.badlogicgames.gdx:gdx-freetype:$gdxVersion"

        compile 'org.apache.commons:commons-lang3:3.4'
        compile 'org.projectlombok:lombok:1.16.4'

    }
}

```

And the Exception:

```
F/art     (20518): art/runtime/check_jni.cc:64] JNI DETECTED ERROR IN APPLICATION: capacity must be greater than 0: 0
F/art     (20518): art/runtime/check_jni.cc:64]     in call to NewDirectByteBuffer
F/art     (20518): art/runtime/check_jni.cc:64]     from java.nio.ByteBuffer com.badlogic.gdx.graphics.g2d.Gdx2DPixmap.newPixmap(long[], int, int, int)
F/art     (20518): art/runtime/check_jni.cc:64] "GLThread 1777" prio=5 tid=14 Runnable
F/art     (20518): art/runtime/check_jni.cc:64]   | group="main" sCount=0 dsCount=0 obj=0x64d26b40 self=0x48e27b48
F/art     (20518): art/runtime/check_jni.cc:64]   | sysTid=20548 nice=0 cgrp=apps sched=0/0 handle=0x48e27e98
F/art     (20518): art/runtime/check_jni.cc:64]   | state=R schedstat=( 0 0 0 ) utm=7 stm=3 core=1 HZ=100
F/art     (20518): art/runtime/check_jni.cc:64]   | stack=0x48e41000-0x48e45000 stackSize=1040KB
F/art     (20518): art/runtime/check_jni.cc:64]   native: art::Thread::DumpStack(std::ostream&) const+87 [0x416f7cc8] (libart.so)
F/art     (20518): art/runtime/check_jni.cc:64]   native: ??? [0x415a49ae] (libart.so)
F/art     (20518): art/runtime/check_jni.cc:64]   native: art::JniAbortF(char const*, char const*, ...)+51 [0x415a5340] (libart.so)
F/art     (20518): art/runtime/check_jni.cc:64]   native: ??? [0x415b05f4] (libart.so)
F/art     (20518): art/runtime/check_jni.cc:64]   native: Java_com_badlogic_gdx_graphics_g2d_Gdx2DPixmap_newPixmap+92 [0x48def790] (libgdx.so)
F/art     (20518): art/runtime/check_jni.cc:64]   at com.badlogic.gdx.graphics.g2d.Gdx2DPixmap.newPixmap(Native method)
F/art     (20518): art/runtime/check_jni.cc:64]   at com.badlogic.gdx.graphics.g2d.Gdx2DPixmap.<init>(Gdx2DPixmap.java:94)
F/art     (20518): art/runtime/check_jni.cc:64]   at com.badlogic.gdx.graphics.Pixmap.<init>(Pixmap.java:114)
F/art     (20518): art/runtime/check_jni.cc:64]   at com.badlogic.gdx.graphics.g2d.freetype.FreeType$Bitmap.getPixmap(FreeType.java:613)
F/art     (20518): art/runtime/check_jni.cc:64]   at com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator.createGlyph(FreeTypeFontGenerator.java:475)
F/art     (20518): art/runtime/check_jni.cc:64]   at com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator.generateData(FreeTypeFontGenerator.java:402)
F/art     (20518): art/runtime/check_jni.cc:64]   at com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator.generateFont(FreeTypeFontGenerator.java:163)
F/art     (20518): art/runtime/check_jni.cc:64]   at com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator.generateFont(FreeTypeFontGenerator.java:156)
F/art     (20518): art/runtime/check_jni.cc:64]   at org.tobinet.unicorn.Unicorn.create(Unicorn.java:43)
F/art     (20518): art/runtime/check_jni.cc:64]   at com.badlogic.gdx.backends.android.AndroidGraphics.onSurfaceChanged(AndroidGraphics.java:243)
F/art     (20518): art/runtime/check_jni.cc:64]   at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1514)
F/art     (20518): art/runtime/check_jni.cc:64]   at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1242)

```

What can I do to fix this?

# Answer
> 1 votes
Are you using the ART runtime in KitKat?

If this only happens when you run on run device, and not when run in desktop mode, and if you're using ART then I'd suggest trying to switch back to use DALVIK.

On your device;

* Go into Settings/Developer options
* Find Select runtime,
* Tap DALVIK and then OK to reboot

Make sure you do this when the device is charging.

# Answer
> -3 votes
Make sure that the font file string ends in .TFF not .tff

---
Tags: java, android, libgdx, fonts
---


title: saving script state

text:
# Question
Title: saving script state
I'd like to ask you, since most of you have some or a lot of experience in writing games. What is your approach to running scripts and saving game state when script is executing when there is a chance that some resources (in worst case - a script that is executing) are changed (new mod installed or game is updated)?

From what I gather most prevalent approach is to prevent saving in such cases (for example in Skyrim one can't save if some long running script is executing, e.g. when one of daedra princes (or princesses or whatever) speaks his/her lines) and organize all other things (AI in particular) in a small, atomic functions.

But maybe there are other approaches?

EDIT:

I think that there is a misunderstanding here. Assume the following: \- when new game is started, a script is run. It reads as follows in hypothetical language:

```
func main() {
    i = 0;
    while (true) {
        i++;
        if (i < 100) {
            yield();
        } else {
            i = 0;
            user.write("Hi, 100 frames passed!");
        }
    }
}

```

Script is started once, it calls 'yield()', it's state is saved and other things are done. Now next frame starts. Script is called again and continues (so next line after yield() is executed) and continues until yield() is called again. After some time user saves game and exits program. I assume that scripts state is somehow serialized ('how' is a separate issue, but it's definitely doable). Later, user starts game again, installs mod downloaded from the internet, launches game and loads saved game state. But mod changed this very script that was currently restored.

Now, my question is: what are common solutions to this problem? I assume that such long-running scripts could be serialized in their binary form (that is, list of opcodes and state of virtual machine, it's stack and registers) which would mean that changing them has no effect, but this is only my own approach. From your practice, how is it solved/approached/mitigated?

# Answer
If there is a chance that a script can update and change a value while you're saving, your application is not thread safe.

You would have to synchronize and pause all threads/activities/simulation while you perform a serialize of all relevant information. Only after the serialization is done can you let the simulation progress, although you are free to write to the disk after resuming, you may wish to wait for it to complete.

Ideally all game logic will ultimately be called from a single thread, the "main game loop." In Unity this would be `Update()` (and I think, `FixedUpdate()`). As long as the save action happens *between* executions of these methods, then there is no need to pause the game (set timeScale to 0, or whatever) as the entire serialization process will occur between steps.

For other engines, other tactics may be necessary. But a good method would be to pause the game via some global flag that every update function goes "oh, its paused" and *does nothing* (I've done this in Flash), which combined with some kind of user-friendly GUI (main menu, etc.) that already pauses the game, you're free to serialize the game's state without having to worry about those "chance updates." Unless, of course, your game is not thread safe. ;)
> 1 votes

---
Tags: scripting, modding, savegame
---


# Question
Title: Level of Detail algorithm(s) and texture coordinates
I'm playing with LOD these days and trying a couple of implementations, specifically quadric mesh simplification, there is a link.

I don't have problem simplifying my models but i do have problem finding the correct texture coordinates after simplification. *None* of the implementations i found (many) cover texturing, they only handle flat colored triangles, and i was wondering if it's possible anyhow to preserve coordinates.

Is there an approach to handle texture coordinates on quadric simplified meshes? I tried storing the original texture coordinates into their faces before passing them to simplifier, then restore them but the results are clearly wrong.

# Answer
> 3 votes
The reason is usually these mesh simplifications are done before texturing.

Then the reduced mesh is UV unwrapped.

And finally using the original mesh as the source, the materials are baked into the target textures by raycasting from the reduced mesh into the original mesh to figure out the color maps and normal map.

A completely new texture and UV set is generated for the reduced mesh.

---
Tags: level-of-detail
---


# Question
Title: Frustum Culling: How to calculate if an angle is between another two angles
I am trying to implement frustum culling but got stuck on how to determine if the angle that the object is from the player is in the FOV of the player. So basically I have the following information:

1. FOV
2. Player's 3D position (x1, y1, z1)
3. Object's 3D position (x2, y2, z2)
4. Player's turning angle with turning left being positive and right negative

How do I determine if the player should be rendered (in the player's field of view) or not?

I tried using this, but it will cull at certain player turn angle and not work in other player turn angle. Ex, work at 0 - 90, but doesn't work at 90 - 180.

```
    float turn = player.getTurn();
    float FOV = this.FOV;
    if (square(entity.getPosition(), player.getPosition()) < FAR_PLANE / 6) {
        double playerz = player.getPosition().z * -1;
        double playerx = player.getPosition().x;
        double entityz = entity.getPosition().z * -1;
        double entityx = entity.getPosition().x;
        double degrees = Math.toDegrees(Math.atan((playerz - entityz)
                / (playerx - entityx)));
        double sinfz = Math.asin((playerz - entityz)
                / square(player.getPosition(), entity.getPosition()));
        double cosfx = Math.acos((playerx - entityx)
                / square(player.getPosition(), entity.getPosition()));
        /*
         * if(sinfz > 0 && cosfx > 0) degrees = degrees; else
         */
        if ((entityz - playerz) > 0 && (entityx - playerx) < 0)
            degrees = 180 - Math.abs(degrees);
        else if ((entityz - playerz) < 0 && (entityx - playerx) < 0)
            degrees = Math.abs(degrees) + 180;
        else if ((entityz - playerz) < 0 && (entityx - playerx) > 0)
            degrees = 360 - Math.abs(degrees);
        if(betweenAngle(90 + turn - FOV / 2, (float) degrees, 90 + turn + FOV / 2))
            return true;
    }
    return false;

```

# Answer
The best way to solve this is not with trigonometry, but with vector math!

I'm going to write some quick pseudocode of what you need to check for difference in angles, if you want the juicy details of the why and how scroll further down.

**Summary:**

```
float l1x = entity.getPosition().x - player.getPosition().x;
float l1y = entity.getPosition().y - player.getPosition().y;
float l1z = entity.getPosition().z - player.getPosition().z;
float l1mag = Math.sqrt(l1x*l1x + l1y*l1y + l1z*l1z);
float l2x = Math.sin(turn);
float l2y = 0;
float l2z = Math.cos(turn);
float dot = l1x * l2x + l1y * l2y + l1z * l2z;
float angle = Math.acos( dot / l1mag);
return Math.abs(angle) <= FOV/2;

```

*Copy code at own risk, it was written completely freestyle and I give no guarantees it will actually function straight off the bat.*

**Explanation:**

I'm going to assume you know what a vector is, if not the answer might not make a lot of sense but I'll try to be pedagogical.

Getting the angle of two points is utterly nonsensical, two points are connected with a line, an alone line has no angle, but there is an angle between *two lines*.

So our first line will be the line through the two points but what will the second line be, we could pick an arbitrary direction but then we'll have to figure out absolute degrees inte relative degrees and as you noticed that's just a mess we want to stay clear of.

Since we're only interested in where the second object is relative to the players FOV it makes much sense for the second line to always be from where the player is to where the player is looking, this way 0° will always be right in front and 180° will always be behind, much simpler to get our heads around wouldn't you say?

Now we come to the tricky part, how do we know where the player is looking? The best would be to have a unit vector denoting direction that gets transformed whenever the player turns, this is something I would highly recommend to implement in the future but for now we'll stick to something relatively more simple using only what you posted.

Assuming 0° means the player is facing +z and he can only turn around the y-axis the equation for figuring out the points position in the world is:

> pointX = player.x+sin(player.turn)
>
> pointY = player.y
>
> pointZ = player.z+cos(player.turn)

Notice we didn't multiply the sin or cos with anything, this is because the the point will always be 1 unit in front of the player meaning the line from player to point will always be 1 in length, why 1? Because it's easier to work with.

Now we have two lines, *l1* from the player to the object and *l2* from the player to where the player is looking, but how do we represent the lines? Should we have three different points? No, we use vectors! Vectors are excellent for representing lines, they contain both direction and magnitude.

So now that we have two separate vectors there is a very simple way to get the angle between them; we use their dot product! The dot product of two vectors is defined as:

$$A \cdot B\sum\_{i=1}^n A\_i B\_i = A\_1 B\_1 + A\_2 B\_2 + ... + A\_n B\_n$$

Which means:

> dot = *l1.x* * *l2.x* \+ *l1.y* * *l2.y* \+ *l1.z* * *l2.z*

Now you might find yourself asking "*What does this have to do with angles?*" Well it all comes down to the second definition of the dot product namely:

$$A \cdot B = \Vert A \Vert\Vert B \Vert cos\theta$$

Translated this says that the dot product of two vectors is equal to the product of the two vectors magnitude(length) and the ***cosine of the angle between them*** the last part is important because it means that if we know the length of the vectors we can figure out the angle with a simple equation.

We know the length of the vector *l2* is 1 and to calculate the length of *l1* we take square root of the sum of the squares of its components.

> l1.mag = sqrt(*l1.x*^2 + *l1.y*^2 + *l1.z*^2

And the pivotal equation that figures out the angle would then be:

> angle = acos(*dot* / *l1.mag*)

And then we compare the absolute value of the angle to the FOV/2.

```
if( abs(angle) <= FOV ) return true

```
> 2 votes

---
Tags: java, mathematics, lwjgl, frustum
---


title: When do I copyright a game?

text:
# Question
Title: When do I copyright a game?
I don't know how to copyright a video game idea.

I don't know if I should make a game document and get that copyrighted first or make the game then copyright it.

The main gist is.. I am lost.

# Answer
> 27 votes
You're confusing patents, copyrights, and trademarks here.

Without going too deep into details:

* Whatever you create, code, assets, or anything else, automatically has you as the copyright owner. No further actions required. It just has to require significant amount of work (depends on legislation). For example, you can't claim rights on blue rectangles, but a logo consisting of multiple rectangles.
* Trademarks are protected logos, taglines, etc. Like patents, but not on ideas.
* Patents are protected ideas, e.g. to prevent others from profiting off things you've put lots of time, money, and research into. Sometimes they're just trolling stuff though.
* The copyright and trademark symbols, i.e. © and ™, are really just hints. The © informs people that your work is protected by copyright, and the ™ informs them that you are using a name or symbol as a trademark. Even without them, stuff is *yours*. It just makes it harder for others to claim they didn't know about these being your trademarks or property. (Some jurisdictions might require them, though.) In contrast, the ® symbol is restricted to trademarks which have been registered with a governmental trademark office. These trademarks have a greater degree of protection, since they've been reviewed and approved to determine that they're unique or distinctive.

So, if you write a game or story or whatever, you don't have to do anything. You might want to file a trademark with the title or main characters, but that's it. If you've got a new way to interact with the player or do something special, you might be able to patent it, but that's really on a very specific case by case basis.

# Answer
> 10 votes
Usual disclaimer: I am not a lawyer and in this site questions about these issues have to be always taken as ideas, thoughts or experiences, never as technical advice.

That said, in the US you hardly would be able to copyright (or hold a patent over) a game idea in itself. Actually, the US Copyright office says that:

> Copyright does not protect the idea for a game, its name or title, or the method or methods for playing it. Nor does copyright protect any idea, system, method, device, or trademark material involved in developing, merchandising, or playing a game. Once a game has been made public, nothing in the copyright law prevents others from developing another game based on similar principles. Copyright protects only the particular manner of an author’s expression in literary, artistic, or musical form.

Of course, this is a bit too vague. Consequently, the interpretations at the Courts have been diverging a bit. There is an excellent article on Gamasutra, from 2013, that discusses that: "Clone Wars: The Five Most Important Cases Every Game Developer Should Know". Still, it's quite the standard that game ideas are not patent-able per se.

What you might be able to do is:

1. to copyright specific code implementations that make your game unique/hard to copy (in case you happen to have implemented something unique in terms of coding, that is essential to your game). I say that because code can be copyrighted similarly to literary works, although there is also quite a debate on to which extent code can/should be patented.

Besides that, what you can surely do is:

2. trademark game titles, logos, characters, etc;
3. copyright the assets (art and sound) as audiovisual. **Note of caution:** while you *don't have* to copyright them because once you create those you own them, *yes there are quite a few arguments* in favor of specifically filing copyrights on them. For more on that, see the other question on this site: Questions on the legal protection of games and their parts (assets, sounds, title)).

---

Lastly, take a look at the article \["Video Games and the law: Copyright, Trademark and Intellectual Property"\]\[4\] for further detailing on the matters of game trademarking and copyrighting.

\[4\]: https://www.newmediarights.org/guide/legal/Video\_Games\_law\_Copyright\_Trademark\_Intellectual\_Property# Are video game titles copyrightable?

---
Tags: game-design, copyright, intellectual-property
---


# Question
Title: What should be the code design for interactions management in a game with lots of object?
I'm writing a 2d game for Android in Java using LibGDX. The game consists many interactions between different types of objects. Most of them happen between enemies and bullets. At the beginning, I needed to check every moment if any enemy collide any bullet (if their masks overlaps each other). The code for checking overlap is clear to me. My question is how should I make the interactions be checked between everyone every moment?

What I did is creating a class called InteractionsManager which takes the array of all enemies and the array of bullets and checking in every step collision between each other (if collision happens, it calls the object's onCollision(Object object) method).

My problem got bigger when I needed to check other interactions types (like if enemy is in a specific distance from other type of object and other stuff like that).

I thought about passing to each object the InteractionsManager object and it should tell it whatever interaction it needs.

# Answer
I'm not sure if its a good solution but i use to add x, y and z (gonna call this XYZ from now) and store it in a linked list with an object identifier and the average side size (we gonna asume that, in this example the object is a cube of 20x20x20 so 20\*3/3 = 20).

```
//PSEUDOCODE
MYOBJECT ob(/*id*/ 1, /*size*/ 20, /*x*/ 30, /*y*/ 12, /*z*/ 4);

forward_list<float[3]> control;

control.push_back([1 /*ID*/ , 46 /*sum of all axis*/, 20 /*size*/]);

```

And, in every iteration, loop through the control list and check for collisions only between the object's who has XYZ equal or greater than his own XYZ (+/-) his own size\*2.

```
//PSEUDOCODE
obj A
check B if
    (A.XYZ - (A.S * 3) >= B.XYZ + (B.S * 3)) &&
    (A.XYZ + (A.S * 3) <= B.XYZ - (B.S * 3))
if true add [A,B] to check_if_collide

```

I use this approach cause it doesn't check for collisions in objects too far and does not asume two objects are colliding when they aren't cause, after this "filter" you would have to check the collision as you would normally, but you gonna have a much short array of objects that are probably hitting each others.

hope it helps
> 2 votes

# Answer
**Disclaimer: This answer is 100% subjective, it is related to code design personal preferences and might not be the best answer.**

I would delete InteractionsManager class.

The idea of having 2 lists (arrays) and checking for collision in a loop is nice, but you can do that on your Screen class. (just create a checkCollisions() method and call it on render()). The code will remain the same, no performance increase, but usually having too many classes might make the code hard to understand.

If you need more interaction types, you can follow the same idea: create a new function in your Screen class and call it on render().

I can´t really help you with performance without seeing the code.
> 0 votes

---
Tags: java, android, collision-detection, libgdx, game-design
---


title: Manager classes benefits

text:
# Question
Title: Manager classes benefits
I am wondering if there are any other advantages to using new classes for managers, eg game state managers, other than readability/organization.

# Answer
> -3 votes
If you mean performance (Speed, Memory,...), then No.

However, It is still worth it. Imagine you stop working for 6 months on your application/program and then come back to improve it, would you prefer named and ordered classes or one Main with 15k lines of code?

KISS

---
Tags: java
---


# Question
Title: Using timestamp as a random seed returns identical results
And here is the random number generator again.

I work on a game, where a user can create and schedule some levels to player later. For simplicity, let's say I play chess.

I create a new game with AI or an opponent for specific datetime in the future.

The random number generator gets as seed the current timestamp when the user create the game and put the pawn in random positions.

If the user creates too many games at once, the results on pawns positions are identical.

So, I was wondering, what other strategies are out there on picking the right seed number instead of the timestamp.

# Answer
> 1 votes
Some aspects of your issue are a little unclear, but it appears you're using a windows very not-so-precise time, and calling it many times in a row.

There are a couple of ways to work around this:

* Use a more precise timer: Make sure that the timestamp value you get is really the most precise that your system can offer.
* Take the timestamp at the start of your game, and create a unique counter of times the generation has been called. Add the value of the counter to the timestamp and use that as the seed for each generation. This will ensure that the seed will be different for each generation.

---
Tags: random
---


# Question
Title: Static body bridging two other static bodies
I have two box2d bodies like below,

What I need is to create another body that kind of bridges this two bodies. I am not looking for a box2d joint, but a body that will be like a bridge touching the rightmost point of the first body and the leftmost point in the second body, like in this image (excuse my paint skills).

Problem is, looks like I am not getting the co-ordinates and angles on how to create the third (bridge) body. Here's my code below,

```
  Body body1, body2, bridge;

BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.StaticBody;
bodyDef.position.set(350 / Constants.PIXELS_TO_METERS, 0 / Constants.PIXELS_TO_METERS);

body1 = world.createBody(bodyDef);

PolygonShape shape = new PolygonShape();
shape.setAsBox(300 / Constants.PIXELS_TO_METERS, 300 / Constants.PIXELS_TO_METERS);

FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.density = 1f;
body1.createFixture(fixtureDef);

BodyDef bodyDef2 = new BodyDef();
bodyDef2.type = BodyDef.BodyType.StaticBody;
bodyDef2.position.set(1600 / Constants.PIXELS_TO_METERS, 0 / Constants.PIXELS_TO_METERS);

body2 = world.createBody(bodyDef2);

PolygonShape shape2 = new PolygonShape();
shape2.setAsBox(300 / Constants.PIXELS_TO_METERS, 500 / Constants.PIXELS_TO_METERS);

FixtureDef fixtureDef2 = new FixtureDef();
fixtureDef2.shape = shape2;
fixtureDef2.density = 1f;
body2.createFixture(fixtureDef2);

BodyDef bodyDef3 = new BodyDef();
bodyDef3.type = BodyDef.BodyType.StaticBody;

Vector2 a = new Vector2(body1.getPosition().x + 300 / Constants.PIXELS_TO_METERS, body1.getPosition().y + (300 + 50 / 2) / Constants.PIXELS_TO_METERS);
Vector2 b = new Vector2(body2.getPosition().x - 300 / Constants.PIXELS_TO_METERS, body2.getPosition().y + (300 + 50 / 2) / Constants.PIXELS_TO_METERS);

float distance = a.dst(b);
Vector2 bridgePos = new Vector2(a.x + distance / 2, a.y + 50 / 2 / Constants.PIXELS_TO_METERS);

bodyDef3.position.set(bridgePos);

float angle = (float) Math.atan2(a.y + 50 / Constants.PIXELS_TO_METERS, b.x);
bridge = world.createBody(bodyDef3);

PolygonShape shape3 = new PolygonShape();
shape3.setAsBox(distance / 2, 50 / Constants.PIXELS_TO_METERS);

FixtureDef fixtureDef3 = new FixtureDef();
fixtureDef3.shape = shape3;
fixtureDef3.density = 1f;
bridge.createFixture(fixtureDef3);
bridge.setTransform(bridgePos, angle);

```

This doesn't give the correct position or angle for the bridge, as it works for some body sizes and sometimes don't (yes, I have accounted for the hardcoded values for every change). I am not exactly sure what I am doing wrong. Any help?

# Answer
One way to approach this would be to represent the definition of the first bodies as `Rectangle`s, then the problem of figuring out the position and rotation of the *bridges* goes aways as the bridge is always made up as a polygon touching the top corners of the `Rectangle`.

The above image was generated using this approach, full source code below. It uses `setAsBox` for the boxes, but uses an array of `Vector2`s to describe the polygon that is the bridge between boxes.

```
package com.bornander.androidstudiosandbox;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.Shape;
import com.badlogic.gdx.physics.box2d.World;

public class MyAndroidStudioSandboxGame extends ApplicationAdapter {
    World world;
    OrthographicCamera camera;
    Box2DDebugRenderer renderer;

    @Override
    public void create () {
        camera = new OrthographicCamera(24, 24);
        camera.position.set(0, 0, 0);

        world = new World(Vector2.Zero, true);

        renderer = new Box2DDebugRenderer();

        Body box1 = createBox(new Rectangle(-10, 0, 1, 4));
        Body box2 = createBox(new Rectangle(-8, 0, 1, 4));
        Body box3 = createBox(new Rectangle(-6, 1, 4, 2));
        Body box4 = createBox(new Rectangle(2, -1, 2, 2));
        Body box5 = createBox(new Rectangle(6, -3, 2, 2));

        buildBridge(box1, box2, 0.5f);
        buildBridge(box2, box3, 0.5f);
        buildBridge(box3, box4, 0.5f);
        buildBridge(box4, box5, 0.5f);
    }

    // This will only work for bodies where the userData has been set to a rectangle
    // describing the body
    private Body buildBridge(Body leftBox, Body rightBox, float thickness) {
        Rectangle lr = (Rectangle)leftBox.getUserData();
        Rectangle rr = (Rectangle)rightBox.getUserData();

        Vector2 v1 = new Vector2(lr.x + lr.width, lr.y + lr.height);
        Vector2 v2 = new Vector2(rr.x, rr.y + rr.height);
        Vector2 v3 = new Vector2(rr.x, rr.y + rr.height - thickness);
        Vector2 v4 = new Vector2(lr.x + lr.width, lr.y + lr.height - thickness);

        BodyDef nodeBodyDefinition = new BodyDef();
        nodeBodyDefinition.type = BodyDef.BodyType.DynamicBody;

        //nodeBodyDefinition.position.set(temp.x, temp.y);

        PolygonShape shape = new PolygonShape();
        float density = 1.0f;
        shape.set(new Vector2[]{v1, v2, v3, v4});

        Body body = world.createBody(nodeBodyDefinition);
        final FixtureDef nodeFixtureDefinition = createFixtureDefinition(shape, density);

        body.createFixture(nodeFixtureDefinition);
        shape.dispose();

        return body;
    }

    private Body createBox(Rectangle rect) {
        Vector2 temp = new Vector2();
        BodyDef nodeBodyDefinition = new BodyDef();
        nodeBodyDefinition.type = BodyDef.BodyType.DynamicBody;

        rect.getCenter(temp);
        nodeBodyDefinition.position.set(temp.x, temp.y);

        PolygonShape shape = new PolygonShape();
        float density = 1.0f;
        shape.setAsBox(rect.getWidth() / 2.0f, rect.getHeight() / 2.0f);

        Body body = world.createBody(nodeBodyDefinition);
        body.setUserData(rect);
        body.setTransform(temp.x, temp.y, 0);
        final FixtureDef nodeFixtureDefinition = createFixtureDefinition(shape, density);

        body.createFixture(nodeFixtureDefinition);
        shape.dispose();

        return body;
    }

    private static FixtureDef createFixtureDefinition(final Shape shape, final float density) {
        final FixtureDef nodeFixtureDefinition = new FixtureDef();
        nodeFixtureDefinition.shape = shape;
        nodeFixtureDefinition.friction = 1;
        nodeFixtureDefinition.density = density;
        nodeFixtureDefinition.restitution = 0.1f;
        return nodeFixtureDefinition;
    }

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

        world.step(Gdx.graphics.getDeltaTime(), 4, 4);
        camera.update();

        renderer.render(world, camera.combined);
    }
}

```
> 1 votes

---
Tags: java, libgdx, box2d
---