# Question
Title: Convert linear velocity to angular velocity for a ball / sphere (Rolling Ball Maths)
I have a ball moving on a flat plane. I cannot use RigidBody physics, so my object in Kinematic and I am manually handling speed/acceleration. The linear movement of the ball is fine, however as the ball does not rotate, it looks odd.

Given a speed Vector3, where I am moving on the X & Z, I need to figure out how to make the ball "roll".

I think I a running into Euler / Gimbal lock issues by trying this:

```
transform.Rotate(
  180.0f *  speed.z / (Mathf.PI * radius) * dt,
  0,
  -180.0f * speed.x / (Mathf.PI * radius) * dt
);

```

This formula is loosely based on the angular velocity formula and converting to degree's per second, with dt (deltaTime).

My gut instinct says that the solution may lie in Quaternions somewehere...?!

# Answer
From http://answers.unity3d.com/answers/880349/view.html

```
  Vector3 axis = Vector3.Cross(speed, Vector3.down);
  float angle = (speed.magnitude * 360 / circumference);
  transform.Rotate(axis, angle * dt, Space.World);

```

(where speed is a Vector3 and circumference is... well.. the circumference of your ball).

The `Cross` part gives you the axis on which you need to rotate around. The Space.World part is important too.
> 1 votes

# Answer
Feels like there should be a better way than this?

```
transform.LookAt(transform.position + speed);
r += 180.0f * speed.magnitude / (Mathf.PI * radius) * dt;
transform.Rotate(Vector3.right, r);

```

(`r` is a `protected float` on the `GameObject` which I can simply increment to rotate "to" the right angle)
> 0 votes

---
Tags: unity, physics, rotation, movement, gimbal-lock
---


title: Collision detection C++

text:
# Question
Title: Collision detection C++
I'm currently trying to make a small ball-like game in C++. I have two disc-like objects with varying radii. Let's say Disc 1 is on coordinates (100,0) and Disc 2 is on coordinates (400,0). Now Disc 1 has a velocity vector of (300,0) and Disc 2 has a velocity vector of (-300,0). In my program, the Discs just swap places and no collision happens.

Now how do I program in the collisions? Do I have to program my own manual raycasting or something?

# Answer
This is a continuous collision problem. The "bullet through paper" problem as most refer to it. I'm not sure how you implemented your system, your question could use more details. But it sounds like you're discretely checking collision. Basically in the example below:  The ball never intersects the rectangle since it's doing a basic intersection test every iteration. There's lots of ways to battle this. It's called continuous collision detection. Raycasting can produce some results. But there are many use cases where unless you shot infinite rays out of the circle you wouldn't be able to use it. Consider the examples below:

This is where shooting one ray or even two would break. What you need is too model the area the shape will take as it moves. Like so:  Above shows the blue area that needs too be checked. So calculate the area to be checked and then if it is intersecting you need to calculate where to resolve the ball too on the rectangle. The resolve is the hard part.

Obviously CCD (continous collision detection) is costly and in fact not used in many games/applications. But sometimes it is needed to produce acceptable results.

You can get around using CCD by using smaller velocities ensuring none of your objects are able to pass through one another.
> 1 votes

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


title: Ball bounce in 3d

text:
# Question
Title: Ball bounce in 3d
I cannot get my bounce equations right. I have 2 spheres, that can colide at any angle. One is forever stationary, other one is moving though the space.

I have X,Y,Z speed of the moving ball and a nomalised vector in direction of stationary ball.

Obvious idea was

ballSpeedX \*= -1;

ballSpeedY \*= -1;

ballSpeedZ \*= -1;

Ofcourse that only works with head on colisions, but with side colisions, it bounces in wrong direction.

ballSpeedX \*= -vectorX;

ballSpeedY \*= -vectorY;

ballSpeedZ \*= -vectorZ;

Also wrong :D

# Answer
> 2 votes
Flipping the velocity vector across a normal alone is not a very good way to model velocity after a collision but if you'd like to do it anyways. All you need is the reflection vector. Here's the vector d reflected across some normal n to get r. (Note the difference between dot product and component product.)

In your case d is v and r is the resulting velocity. Getting n is entirely based off the surface that is hit. For two spheres you can just subtract the centers of the circles and normalize it to get a unit vector n.

Like I said this is not a good way to respond to the collision as it doesn't account for the mass of the objects in the collision, the velocity of the objects in the collision, or the energy lost in the collision. I'd look into momentum if I were you. In fact the type of collision modeled in the above example assumes no energy loss, the same masses, and the same velocities in equal and opposite directions.

This equation represents all the variables you would need in a collision like this.

p is change in momentum, m is mass, e is elasticity (energy loss/bounciness), and n is the collision normal.

---
Tags: 3d, vector, collision-resolution, sphere
---


# Question
Title: Raycasting to AddForceAtPosition goes to the wrong direction
I'm trying to get my coin object's Rigidbody to move whichever way it was swiped on by the user through RayCast

```
void Awake()
{
    coinRigidBody = coin.GetComponent<Rigidbody>();
}

void Update()
{

    foreach (Touch touch in Input.touches)
    {
        if (touch.phase == TouchPhase.Began)
        {
            firstTouchPos = new Vector3(touch.position.x, touch.position.y, Camera.main.nearClipPlane);
        }
        if (touch.phase == TouchPhase.Moved)
        {

            lastTouchPos = new Vector3(touch.position.x, touch.position.y, Camera.main.farClipPlane);
        }

        if (touch.phase == TouchPhase.Ended)
        {

            Vector3 firstTouchWorldPos = Camera.main.ScreenToWorldPoint(firstTouchPos);
            Vector3 lastTouchWorldPos = Camera.main.ScreenToWorldPoint(lastTouchPos);
            Vector3 diffWorldPos = lastTouchWorldPos - firstTouchWorldPos;
            direction3D = diffWorldPos.normalized;
            power = diffWorldPos.magnitude * (force / Time.deltaTime);

            Ray firstTouchRay = Camera.main.ScreenPointToRay(firstTouchPos);
            Ray lastTouchRay = Camera.main.ScreenPointToRay(lastTouchPos);

            RaycastHit hit;
            Debug.DrawRay(firstTouchRay.origin, lastTouchRay.direction - firstTouchRay.direction, Color.red, 50.0f);

            if (Physics.Raycast(firstTouchRay.origin, lastTouchRay.direction * 100, out hit))
            {
                Vector3 hitLocation = hit.point;
                if (hit.collider.tag == "Coin")
                {

                    projectedVector = Vector3.ProjectOnPlane(direction3D, plane.normal);
                    coinRigidBody.AddForceAtPosition(projectedVector * power, hitLocation * 5);
                    throwCoinObject.throwWithForce(power, hitLocation, direction3D);
                }
            }
        }
    }
}

```

The Code is working but my only problem is that it goes only in a certain direction? And it seems that direction is manipulated by how the camera is facing the objects. I just want it to hit the first touch origin then move to the direction the swipe was made.

Help would be really appreciated

# Answer
Worked when i changed

```
lastTouchPos = new Vector3(touch.position.x,touch.position.y,Camera.main.farClipPlane);

```

to

```
lastTouchPos = new Vector3(touch.position.x,touch.position.y,Camera.main.nearClipPlane);

```
> 0 votes

# Answer
1. lastTouchRay.direction - firstTouchRay.direction does not do what you assume it does. ScreenPointToRay draws a ray from the camera to the point you specify. I'm assuming those directions are not what you want. The debug ray will be wrong.
2. Your raycast uses the lastTouchRay direction, although it should use the first one if you're only interested in seeing if the first touch "touched" the coin.
3. The Direction3D should be fine as is since both points are already on a plane ( z is nearClip for both ). You could get rid of the ProjectOnPlane. And in your case, you probably only need the z components to match so they end up as 0.0 in the Direction3D.

Hope this will at least put you on the right track:

```
if (touch.phase == TouchPhase.Ended)
{

        Vector3 firstTouchWorldPos = Camera.main.ScreenToWorldPoint(firstTouchPos);
        Vector3 lastTouchWorldPos = Camera.main.ScreenToWorldPoint(lastTouchPos);
        Vector3 diffWorldPos = lastTouchWorldPos - firstTouchWorldPos;
        direction3D = diffWorldPos.normalized;
        power = diffWorldPos.magnitude *(force /Time.deltaTime);

        Ray firstTouchRay = Camera.main.ScreenPointToRay(firstTouchPos);
        RaycastHit hit;
        Debug.DrawRay(firstTouchRay.origin,direction3D ,Color.red,50.0f);

        //! check if first touch hits the coin
        if(Physics.Raycast(firstTouchRay.origin,firstTouchRay.direction,out hit))
        {
            Vector3 hitLocation = hit.point;
            if(hit.collider.tag == "Coin")
            {

                  coinRigidBody.AddForceAtPosition(direction3D *power, hitLocation );
                  throwCoinObject.throwWithForce(power,hitLocation,direction3D);
            }

        }
    }

```
> 0 votes

---
Tags: unity, c#, raycasting, touch, rigid-body-dynamics
---


# Question
Title: How to change the sprite of an object from another's script?
I have an object A and an object B, I want that when object B is in a certain position, the sprite of object A changes to that corresponding to that position, how do I change the sprite of object A from the script of object b?

The image may give them an idea of what I want to do, object B is the glove, And the object A is the viewer.

Tansk form any help.

# Answer
> 1 votes
If you have only one instance of the object A then you can use `with` statement or object's name:

```
with objA
{
    sprite_index = YourSprite;
}

```

or

```
objA.sprite_index = YourSprite;

```

It won't work when you have more than one instance of the object A (then all instances will be changed). In this case you can use the name of the instance (press RMB on the instance in the room editor and select `Copy Instance Name` (also you can rename it). Then code will be like this:

```
inst_FD70AA4D.sprite_index = YourSprite;

```

or

```
inst_YourName.sprite_index = YourSprite;

```

There are couple examples:

using instance's creation code (if you don't understand what it is, check the documentation (see `Creation Code`).

using automatic creation

I made it lot time ago in GM8, you can just import them to GMS.

---
Tags: sprites, game-maker
---


# Question
Title: Mechanim "Hand Closing / Opening" Animation control with trigger
I wish to control any given Animator state "Playhead", with a variable - rather than have it play automatically with time. This is for an animation of a hand making a "clench gesture" which will be bound to an analog controller trigger output value.

I have considered the following:

1. Inside: `StateMachineBehaviour.OnStateUpdate` method (State machine behavior script attached to a state in the Mechanim graph)

Call `Animator.Play` or `Animator.CrossFade` to play a given clip from a given time with speed set to 0. This should get called every update while in the state.

The issue with this is that the whole state will stop, then start again which means `OnStateEnter` and `OnStateExit` continually fire, rather than just the `OnStateUpdate` method to control the "Playhead".
2. Animator.ForceStateNormalizedTime(time)

This would be fine but it has been depreciated.
3. Use timers and the `Animator` speed variable to calculate when to toggle playing a clip at a certain speed such to match the displacement of the trigger. Seems the wrong way to go about it.
4. Use the legacy animation system

This works fine but you don't get the perks of Mechanim FSM eg. blend trees.

Since Unity seem to have removed the ability to manipulate the time of a running clip or Mechanim state, it makes me think it's something I shouldn't be doing. Am I going about this the wrong way? Why does it seem difficult to play an animation via something other than the time domain?

# Answer
It sounds like what you really want to use are Blend Trees. Specifically look at 1D Blending, and the Unity tutorial here.

I'm not an animation expert by any stretch, but from my experience with blend trees I would assign a variable for hand clench which you can feed from your controller via a script. Then create 2 static animations (one of a closed hand and another of an open hand) and blend the 2 together based on the variable.
> 0 votes

---
Tags: unity, animation
---


# Question
Title: What is the best way to draw outline of object using OpenGL
I want to select the best way to draw outline of 3d human like object and what would be the best way to draw outline for this kind of objects. I found about stencil buffer based methods, geometric shader based methods and toon shader based methods is one if this is good if so which method. or is there any other best way to draw a outline.

# Answer
> 2 votes
One way would be to draw the object or character you wish to outline by itself into a depth-only buffer. Then you could run an edge detector on the depth buffer to find the edges of the object. Finally, take the resulting edge image and overlay it on the scene.

# Answer
> 0 votes
Apart from your suggestions about the geometry shader, stencil buffer, and the previous answer's edge detection methods, there are other methods which could work for you.

* Draw your object into a texture with a single color, which will be your outline color, blur it, and draw it behind your object. This will produce a smooth outline.
* Just draw your object twice. The first time it is with a single colored shader which also extrudes vertices along the normal vector, and front face culling (keep the back faces). The second time you draw it, use the normal shaders. This can produce incorrect results (holes in the outline) when there are per-face normals instead of per vertex normals.

---
Tags: opengl, geometry-shader, shading, stencil, outline
---


# Question
Title: What way to draw random sprite from spritesheet in SFML?
I have a spritesheet(900x100) with of different colored shapes each size 100x100. I am trying to code a program such that, after every 2 seconds, one random sprite appears on screen. If I click, it should disappear and after 2 seconds another random shape should appear. If I don't, it should continue to show that image.

Using IntRect, I am able to cut out individual shapes out of the spritesheet and display them. I thought that in the IntRect parameters:

```
Shape.setTextureRect(sf::IntRect(0, 0, 100, 100));

```

I could replace the first 0, like this:

```
Shape.setTextureRect(sf::IntRect(((rand() % 8) * 100), 0, 100, 100));

```

and after 2 seconds, it would show me a new random sprite. However, after 2 seconds, the window shows what looks like a bunch of random shapes playing really fast one after the other, nothing and then 2 seconds later it repeats.

If I can't get the random images to work properly I don't think I'll be able to do the mouse events.

Here is my code so far: main.cpp

```
#include <SFML/Graphics.hpp>
#include <iostream>
#include <stdlib.h>
#include <time.h>

int main()
{
    sf::RenderWindow window(sf::VideoMode(640, 480), "Tile Game");

    sf::Clock clock;
    sf::Time timer;

    sf::Texture shapeSpriteSheet;
    sf::Texture Background;

    sf::Sprite bg;
    sf::Sprite Shape;

    srand(time(NULL));

    Background.loadFromFile("bg.png");
    bg.setTexture(Background);

    shapeSpriteSheet.loadFromFile("shapes.png");
    shapeSpriteSheet.setSmooth(true);

    Shape.setTexture(shapeSpriteSheet);
    Shape.setPosition(sf::Vector2f(192, 146));

    while (window.isOpen())
    {
        sf::Event event;
        window.draw(bg);

        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        timer = clock.getElapsedTime();

        if (timer.asSeconds() >= 2)
        {
            Shape.setTextureRect(sf::IntRect(((rand() % 8) * 100), 0, 100, 100));
            window.draw(Shape);

            if (timer.asSeconds() > 2.1)
            clock.restart();
        }

        window.display();
    }

    return 0;
}

```

**Update:**

I've finally made it so that, every 2 seconds a sprite appears, on click it disappears. Now Im working on making every sprite randomly selected

New code:

```
if (clock.getElapsedTime().asSeconds() >= 2)
        {
            shapeVisible = true;
            Shape[0].setPosition(sf::Vector2f(192, 146));
            window.draw(Shape[0]);

            if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
            {
                if (Shape[0].getGlobalBounds().contains(window.mapPixelToCoords(sf::Mouse::getPosition(window))))
                {
                    clock.restart();
                }
            }

        }

```

# Answer
```
if (timer.asSeconds() >= 2)
{
    // { code here to choose a new sprite and draw it to the screen }

    if (timer.asSeconds() > 2.1)
        clock.restart();
}

```

*(this is a snippet of your provided code)*

What's the behaviour of this code in between time 2 and time 2.1?

Remember that at 60fps, there's 0.016 seconds between each frame, so there'll be about six frames in that interval. If you're running at higher than 60fps, there could be far more.

So think through just this little bit of your code; what is the program going to do when it executes this part of your program's main loop when it reaches this 'if' statement during the six frames between those two times, if it's following your instructions exactly as you've written them?
> 1 votes

---
Tags: c++, sfml
---


title: Dynamic Difficulty Adjustment

text:
# Question
Title: Dynamic Difficulty Adjustment
Isn't there any algorithms for Dynamic Difficulty Adjustment? like a universal algorithm. Or is it made depending on the game that it will be implemented to?

# Answer
> Is there a universal algorithm for dynamic difficulty adjustments?

No, there is not.

> Or is it made depending on the game that it will be implemented to?

That's it!

Chess and Mario Kart are not played the same, the same rules do not apply, etc. There is no way to have the same algorithm for dynamic difficulty for both games.
> 3 votes

---
Tags: dynamic-difficulty
---


# Question
Title: How do I get the instance of my tiles from the game class?
I have a c++ problem.

So I have a base GAME class. In this class I have an instance of the player class. I want to check this player for collision with tiles. Tiles are also stored in the game class. How do I get the instance of these tiles.

I tried passing in an instance of the game class into the constructor of the player class and accessing it that way, but no success.

So for example:

```
Class game()
{
     Player p(x, y);
     Tile t(x, y);

     //game loop
     p.update(); //check collision

     p.render();
     t.render();
}

Player::Player(int x, int y)
{
    this.x = x;
    this.y = y;
}

Player::update()
{
     //get an the instance of tile to check the collision
}

```

# Answer
> 0 votes
Simply pass a reference to the tile to the update function:

```
Class game()
{
     Player p(x, y);
     Tile t(x, y);

     //game loop
     p.update(&t); //check collision

     p.render();
     t.render();
}

Player::Player(int x, int y)
{
    this.x = x;
    this.y = y;
}

Player::update(Tile* tile)
{
     //You now have a pointer to tile
}

```

# Answer
> -1 votes
There is definitely a level of guesswork in understanding your question, but a couple things that may be of note.

1. your player has no reference to your tileset and would need to have access to it if you wanted to brute force detection - iterating through all of them and acting once you find the tile(s) she is touching.
2. your player could use space partitioning, as with a BSPTree, QuadTree or OctTree, to run queries against subsets of valid elements. You may want to reach into wikipedia for more details on this and to think through how to implement it in your context.

Both solutions would likely work, the second being a better, albeit more involved, approach.

Here is a discussion of some of the techniques used in 2D.

Hopefully this is helpful.

---
Tags: c++
---


title: GetCurrentAnimatorStateInfo(0)

text:
# Question
Title: GetCurrentAnimatorStateInfo(0)
I want to get the current state from Animator. The reason I do this is because I want my sprite can approach multiple Idle state. For example, when sprite move left, when it go to idle state, it should go for leftidle instead of front idle. And

However when I type

```
theanim.GetCurrentAnimatorStateInfo(0).IsName("charactersbackwalk"))

```

"GetCurrentAnimatorStateInfo" the code is in red line which Visual Studios indicate that

> 'Game object' does not contain a definition GetCurrentAnimatorStateInfo and no extension method accpeting a first argument of type 'Game object' could be found (are you missing using a directive or an assembly reference)

Below I attach my code:

```
if (!Input.GetKey("up") && !Input.GetKey("down") && !Input.GetKey("left") && !(Input.GetKey("right") && (theanim.GetComponent<Animator>().GetBool("BackIdle") == true)))
        {
            theanim.GetComponent<Animator>().SetBool(charactersfrontwalk, false);
            theanim.GetComponent<Animator>().SetBool(charactersbackwalk, false);
            theanim.GetComponent<Animator>().SetBool(charactersleftwalk, false);
            theanim.GetComponent<Animator>().SetBool(charactersrightwalk, false);
            theanim.GetComponent<Animator>().SetBool(charactersidlewalk, false);
            theanim.GetComponent<Animator>().SetBool(charactersbackidle, true);
            theanim.GetComponent<Animator>().SetBool(charactersrightidle, false);
            theanim.GetComponent<Animator>().SetBool(charactersleftidle, false);
        }

```

Below I attach my Unity Animator:

# Answer
> 1 votes
First i apologize for my previous wrong answer ;) .

It was simple , to make an object work with other function , you need to take the component from it first , like you want to make a clay and water become vase then you need to get carving tools first .

What i was trying to tell is that your object don't have the " tools " to do your what you say , and to fix it , you must give it the " tools " by adding GetComponent\<\>() :

```
theanim.GetComponent<Animator> ().GetCurrentAnimatorStateInfo (0).IsName ("characterbackwalk");

```

It is worked well here :) and if it solve your problem , then mark it ;) .

**!! -- EDIT -- !!**

I know your real problem , and i have tested that if G**etCurrentAnimatorStateInfo will always return false in Update()** , instead of using that , you can use GetBool() :

https://docs.unity3d.com/ScriptReference/Animator.GetBool.html

Then your script should be like this :

```
if(theanim.GetComponent<Animator> ().GetBool ("charactermovedown") == true ) {

// do your function

}

```

# Answer
> 0 votes
```
Animator m_anim = ...;
m_anim.Play("GenericSpinReveal");
m_anim.Update(Time.smoothDeltaTime);
m_anim.Update(Time.smoothDeltaTime);
// Assert test passes only if I have the two  updates above.
DebugUtils.Assert(m_anim.GetCurrentAnimatorStateInfo(0).IsName("Base.GenericSpinReveal"));

```

and see this link:https://forum.unity3d.com/threads/getcurrentanimatorstateinfo-0-isname-returns-false-immediately-after-playing.224489/

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


# Question
Title: Multiple IF statements on Update (Unity)
**Background**

I am testing out a "Pause" system for my game. I have a Game Manager script and figured as it's the GM, it's a good place to stick a Pause system.

My pause works that on pressing "P" key, the `timeScale` is switched between 0 and 1. Due to the nature of the game, if the game is paused *and then unpaused* I want the `timeScale` to not "jump" to 1 but to gradually increase, taking half a second to reach "normal" game speed again.

*This aspect is NOT my issue. This is just background.*

**My Code**:

I have the pause detection in the `Update` script. I figured two if statements to check Timescale values and then to take appropriate action.

(`SloMoTime` is a timescale that kicks in when the player wins or looses the level)

My Code:

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

public class GManager : MonoBehaviour
{
    public float sloMoTime = 0.2f;
    public bool ballInPlay = false;

    ....

 void Update()
     {
     if(Input.GetButtonDown("PauseGame") && ballInPlay == true)
     {
         if (Time.timeScale == 0)
            {
            //Game is already paused, so now continue...
            // dactivate "paused" text notice
            paused.SetActive(false);
            /***
             * Becauase we are speeding time up we can't use deltaTime
             * Easy as the timescale we want is 0.5f so 1/0.5 == 2. So use 2.
             ***/
            Time.timeScale = Mathf.MoveTowards(Time.timeScale, 1.0f, 2f);
            }
        if (Time.timeScale > slowMoTime)
            {
            //Pause the game.
            Time.timeScale = 0;
            // Show "paused" Text notice.
            paused.SetActive(true);
            }
        }
    } //end Update.
} //close class.

```

Now, Can you see any major issues here?

**My Issue**

I found running my script from above, that the game did not pause.

I expected every frame to load `Update`, then to check IF number 1, and then check If number 2 (hence in that order). then continue.

I found using error logs that by swapping the If statments around that *only the first if statement was ever executed*. So the game would alternatively *always* pause but then never unpause. I additionally found with error logs that the values of TimeScale where not causing this inconsistency.

What I have trouble with is understanding **why this happens**. Why do two completely mutually exclusive IF statements not both fire, when in the same method?

FAILS:

```
Class {
    void Update () {
       if(){
          //works
       }

       if(){
         //never works
       }
   } //close method.
}

```

**A Solution**

*BUT* putting the second IF statement within an `else` solves this issue.

WORKS:

```
Class {
    void Update() {
       if(){
          //works
       }
       else if(){
         //works
       }
   } //close method.
}

```

Obviously this is impractical for more than a few ifs at once and I find it hard to understand why this logic works and the previous logic never did.

I havn't yet dug into if this is `Update` or `timeScale` (entity rather than value) specific but **Why does this happen?**

# Answer
A few things:

* Altering the timescale inside a conditional that requires the timescale to be zero only works on the first Update. (And using `== 0` is a bad practice for floats anyway).
* Due to point one, your code does this:
    1. Update
        1. `Time.timeScale == 0` = false
        2. `Time.timeScale > slowMoTime` == true
            + Set timescale to 0
    2. Update
        1. `Time.timeScale == 0` = true
            + Set timescale to slightly more than 0
        2. `Time.timeScale > slowMoTime` == false
    3. Update
        1. `Time.timeScale == 0` = false
        2. `Time.timeScale > slowMoTime` == false
    4. Update
        1. Both are false forever.

So, your game is actually unpausing, it's just moving very, very slowly. You should use boolean flags to determine the state you want to be in, instead of relying on the state of the thing you're actively changing.

Further, you wouldn't want this in the update like it is. Even if this was working as you expected, it would just toggle back and forth between paused and unpaused.

And, with your update, `Input.GetButtonDown` is only going to trigger the very first frame you press the button. So, you can take the steps above and everytime it says Update, is the same as you pressing the pause key once.
> 2 votes

---
Tags: unity
---


title: OpenGL Texture Loading

text:
# Question
Title: OpenGL Texture Loading
I've been using OpenGL for a bit so I have a general idea of what I'm doing. Recently, I've been working on a framework to let me test stuff more easily. As part of the framework, I split up loading images into OpenGL into two parts, one where I load the data (ie from a file) and another part where I actually send the data to OpenGL. However, when I use the system I designed, only a black triangle is displayed. When I bypass the system I created and load the texture directly into OpenGL using SOIL's SOIL\_load\_OGL\_texture function, everything works with no other changes. Here's the relevant sections of code:

Main.cpp

```
// Section commented out to test loading a texture using SOIL instead
/*
Texture::Texture2DSource texData;
texData.loadTextureFromFile("Background.png", Filesystem::FOLDER_TEXTURES);
auto texture = Texture::Interface::getSingleton().loadTexture(texData);
// Debugging function I added to access the texture ID directly
GLuint textureID = texture->getTextureID();
*/

// Load the texture using SOIL as opposed to my texture loading classes
GLuint textureID = SOIL_load_OGL_texture(
    "C:\\Users\\Username\\AppData\\Roaming\\Test\\Textures\\Background.png",
    SOIL_LOAD_RGBA, SOIL_CREATE_NEW_ID, SOIL_FLAG_INVERT_Y);

glActiveTexture(GL_TEXTURE0);
// This line is used when the SOIL texture loading is used
glBindTexture(GL_TEXTURE_2D, textureID);
// I hardcoded in 0 as the uniform ID just for testing; normally I query the
// uniform ID and use that
glUniform1i(uniformID, 0);

```

Vertex Shader:

```
#version 440

layout(location = 0) in vec2 vertex;
layout(location = 1) in vec2 uvData;
out vec2 uv;

void main()
{
    gl_Position = vec4(vertex, 0.0f, 1.0f);
    uv = uvData;
}

```

Fragment Shader:

```
#version 440

in vec2 uv;
out vec4 color;
uniform sampler2D textureSampler;

void main()
{
    color = texture(textureSampler, uv);
}

```

C++ code for loading a texture into memory:

```
// Create variables to store the image dimensions and properties
int width = 0;
int height = 0;
int channels = 0;

// Load the image
auto data = SOIL_load_image(fileLocation.c_str(), &width, &height, &channels,
    SOIL_LOAD_RGBA);

// Resize the texture's vector to the same size as the array returned from SOIL
m_data.resize(width * height);
// Copy the data from SOIL's array to the vector
const uint32_t BYTES_PER_PIXEL = 4;
memcpy(&m_data[0], data, width * height * BYTES_PER_PIXEL);
// Set the dimensions
m_x = width;
m_y = height;

// Flip the image
// Code omitted as irrelevant

```

C++ code for loading the texture data into OpenGL:

```
// Set up the texture storage
GLuint textureID = -1;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
// Load the texture data
glTexImage2D(
    GL_TEXTURE_2D,      // Texture Target
    0,                  // Level of Detail level
    GL_RGBA,            // Internal Format
    data.m_x,           // Width
    data.m_y,           // Height
    0,                  // Border (must be 0)
    GL_RGBA,            // Pixel Data Format
    GL_UNSIGNED_BYTE,   // Data Type
    &data.m_data[0]     // Texture Data
    );

// Set texture filtering options
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);

// Create a Texture object and load the texture ID into it, then return it
Texture<GL_TEXTURE_2D> texture;
texture.m_textureID = textureID;
return texture;

```

Here's some more images:

This is what the window shows when using my texture loading process.

This is what Nvidia NSight shows for the Fragment shader.

This is what the window shows when bypassing my texture loading process.

This is what Nvidia NSight shows when bypassing my texture loading process.

NSight shows the texture as loaded properly for both texture loading processes, and everything else seems to be the same. Any ideas on what's causing the issue?

# Answer
> 1 votes
This answer is late, but the problem is because you do not generate mipmaps but you set the texture filter to use a mipmap filtering option.

use

```
 glGenMipMaps(...)

```

or change

```
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);

```

to

```
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR / GL_NEAREST);

```

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


title: SDL: Certain bitmap not displaying

text:
# Question
Title: SDL: Certain bitmap not displaying
I have come across a very wierd problem. Here is my code:

```
#include <iostream>
#include "SDL.h"

using namespace std;

class MyGame
{
public:

    SDL_Surface* image;
    SDL_Surface* window;
    SDL_Event* e;

    void Start()
    {
        SDL_Init(SDL_INIT_EVERYTHING);

        window = SDL_SetVideoMode(800,600,32,SDL_SWSURFACE);

        image = SDL_LoadBMP("Bitmap.bmp");
        SDL_BlitSurface(image,NULL,window,NULL);
        SDL_FreeSurface(image);

        SDL_Event evt;

        bool programrunning = true;
        while(programrunning)
        {
            SDL_WaitEvent(&evt);
            if(evt.type == SDL_QUIT) programrunning = false;
        }

        SDL_Quit();
    }

    void Update()
    {
        SDL_Flip(window);
    }
};

int main(int argc,char* args[])
{
    MyGame obj;
    obj.Start();
    while(true)
    {
        obj.Update();
    }

    return 0;
}

```

Whenever I run this code on Code::Blocks, no errors appear and everything works except for the bitmap. For some reason it doesn't display. However, I once tried replacing Bitmap.bmp with cb.bmp (the Code::Blocks logo that came with the IDE) and it rendered perfectly fine. Also, whenever I close the program Windows gives me this error: "2DGame.exe not responding", no matter what bitmap I use. This is one of the strangest coding problems I have come across ever, please tell me why Bitmap.bmp is being a jerk and how to fix it and also how to fix the error I get whenever I close my program. Thanks!

P.S: You guys asked for the image, here it is:

# Answer
> 1 votes
As you haven't supplied the particular bitmap you are having trouble with, I cannot guess what is wrong with the bitmap. Your rendering code seems fine on that part.

When it comes to the program hanging, the cause is quite clear. When an `SDL_QUIT` event is received, you quit your loop that is waiting for that particular event, and call `SDL_Quit();`. However, the while loop inside your `main` still keeps trying to update the window. As of currently, your application can't be exit, because the while loop inside `main` is an infinite loop. All in all, your game loop seems a little ill-formed. You might want to try a simpler approach, where there is only one game loop, and where you use `SDL_PollEvent` for receiving events.

# Answer
> 1 votes
`SDL_LoadBMP` can only load bitmap images (i.e. extension `.bmp`). Images from the internet are rarely of this format; they are usually formats like JPEG, PNG or GIF.

For that, you want to look at **SDL\_image** instead. It's a helper library for SDL that handles loading various image types into SDL. It has a different loading function: `IMG_Load`.

And please, **always check errors in your code.** Your problem could have been caught earlier if you had checked the output of `SDL_LoadBMP`, which would have been null. Like most SDL functions, you can then get a description of the error using `SDL_GetError`.

---
Tags: c++, sdl
---


# Question
Title: LibGDX: Shader files in assets - Access is Denied
I stored the glsl files in `android -> assets -> shaders` directory, but when I run the app, an error is displayed:

```
Error:Gradle: Execution failed for task ':android:mergeDebugAssets'.
Error: java.io.FileNotFoundException: ...android\assets\shaders (Access is denied)

```

But the problem goes away if I put those files in assets root folder. Can I not store shader files in asset subdirectories? Using Gdx v1.9.3.

EDIT: The issue is not there when running on Desktop, but only on Android. Didn't check others.

---

**UPDATE:** Apparently the issue got resolved today. I didn't make any changes but it's working now!

# Answer
> 1 votes
I assume you use `Android Studio` or `IntelliJIdea` (don't know how `Eclipse` works).

These errors happen because of Windows administrative permissions. All you have to do is to open the parent folder (this one where your 'access denied' folder is in) in a windows file explorer. You need to rename the folder to anything you want and name it back with a previous name. If it was folder named `shaders`, rename it to `shaders2` and go back with `shaders`. `IntelliJ`/`Android Studio` will refresh the project itself and it will work.

This is caused by adding files directly to the project, but not to the folder itself ;) Happens to me on `Windows10` when running `Android Emulator` or a normal mobile phone plugged in.

---
Tags: opengl, libgdx, shaders, glsl
---


title: Unity car AI with navigation mesh

text:
# Question
Title: Unity car AI with navigation mesh
I made a car AI that works by raycasting for obstacle avoidance to steering and accelerate. I want to know how can I implement a navigation mesh for better obstacle avoidance.

How do I implement a navigation mesh, and use my car as the navigation agent?

# Answer
> 0 votes
What you're looking for are NavMesh Obstacles. These obstacles aren't baked into the Navmesh, but instead sit on top of it providing dynamic obstacles that should be avoided.

A good tutorial and introduction can be found here

---
Tags: unity, ai
---


# Question
Title: Unity - Texture on Plane fades at angle - Generating mipmaps?
Good day, I seem to have run into a problem which I can't find an answer to. I'm making a World Editor for my project, and generating a grid plane which the user can modify. **Whenever I rotate the camera as seen below, to a more side view angle, the grid texture fades out.**

I have changed Aniso levels, tried at different quality settings, also different shaders for the texture.

At the moment, I'm using the `Unlit/Transparent Cutout` shader which gives a crisp look on the grid. The texture resolution is for `width` and `height` `mapSize(64 > 254)*gridDetail(4>32)`. The same results is given no matter the detail size on the texture.

It does appear that the center of the plane gets the most faded as opposed to the sides.

EDIT: Okay, so I found out what's the problem, now here's my question, how can I generate mipmaps for the texture? (The texture is created with the following code(unoptimized I know):

```
using UnityEngine;
using System.Collections;

public class MyScript: MonoBehaviour
{
    public int sizeX,sizeZ;
    public int gridDetail;
    public Color smallGridColor = Color.white;
    public Color largeGridColor = Color.yellow;
    public bool drawSmallGrid,drawLargeGrid;

    Texture2D gridTexture()
    {
        Texture2D gridTex = new Texture2D(sizeZ * gridDetail + 1, sizeX * gridDetail + 1);
        Color[] gridColor = new Color[gridTex.width * gridTex.height];
        Color[,] gridColor2 = new Color[gridTex.width, gridTex.height];
        for (int i = 0; i < gridTex.width; i++)
        {
            for (int x = 0; x < gridTex.height; x++)
            {
                gridColor2[i, x] = Color.clear;
            }
        }

        if (drawSmallGrid)
        {
            for (int i = 0; i < gridTex.height - 1; i += gridDetail)
            {
                for (int j = 0; j < gridTex.width - 1; j++)
                {
                    gridColor2[i, j] = smallGridColor;
                }
            }
            for (int i = 0; i < gridTex.width; i++)
            {
                for (int j = 0; j < gridTex.height; j += gridDetail)
                {
                    gridColor2[i, j] = smallGridColor;
                }
            }
        }

        if (drawLargeGrid)
        {
            for (int i = 0; i < gridTex.height - 1; i += gridDetail * 4)
            {
                for (int j = 0; j < gridTex.width - 1; j++)
                {
                    gridColor2[i, j] = largeGridColor;
                }
            }
            for (int i = 0; i < gridTex.width; i++)
            {
                for (int j = 0; j < gridTex.height; j += gridDetail * 4)
                {
                    gridColor2[i, j] = largeGridColor;
                }
            }
        }

        for (int i = 0; i < gridTex.height; i++)
        {
            for (int j = 0; j < gridTex.width; j++)
            {
                gridColor[i * gridTex.width + j] = gridColor2[i, j];
            }
        }

        gridTex.SetPixels(gridColor);
        gridTex.filterMode = FilterMode.Point;
        gridTex.wrapMode = TextureWrapMode.Clamp;
        gridTex.alphaIsTransparency = true;
        gridTex.Apply();

        return gridTex;
    }
}

```

Any ideas?

# Answer
> 1 votes
So, upon further research, I found this: http://answers.unity3d.com/questions/10292/how-do-i-generate-mipmaps-at-runtime.html

Which pretty much answers my question. In order to generate mipmaps for the newly created texture. One should make a second texture, and then just set the pixels for the new texture to the originally created one. (Same goes for loading textures in through code from various places) Here's what I changed:

```
    ...
    // Modified at the bottom of my script just before the return.
    gridTex.SetPixels(gridColor);
    gridTex.filterMode = FilterMode.Point;
    gridTex.wrapMode = TextureWrapMode.Clamp;
    gridTex.alphaIsTransparency = true;
    gridTex.Apply();

    Texture2D gridTex2 = new Texture2D(gridTex.width, gridTex.height);
    gridTex2.SetPixels(gridTex.GetPixels(0, 0, gridTex.width, gridTex.height));
    gridTex2.Apply();
    return gridTex2;

```

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


# Question
Title: How do I make a progress bar with letters that get "filled in"?
I want to make a progress bar made of text! I have two images: One with the text in gray, the other coloured:

As my game is loading, I want the letters to "fill up" with color:

They would start out gray, then fill in.

I was thinking of overlaying a transparent rectangle over the gray image, then stretching the transparent rectangle to match the progress. But then the background will be coloured too. I want *only the letters* to be coloured!

How can I do this?

# Answer
I don't know how this feature would be implemented in your specific development environment, but the solution to the problem you describe is masking.

Basically, apply a mask to the progress bar in the shape of your letters and then the stretched rectangle won't be rendered outside the mask.
> 6 votes

# Answer
If your ui system uses a layering concept you can do this:

1. Have an image with the letters having alpha of 0 (front layer).
2. Have a quad which is the "unloaded" colour, scaled to the same dimensions as your front image(back layer)
3. In the middle layer, have a quad with the "loaded" colour, scaled to some suitably small value on the x axis, then scale it up as the percentage of loaded resources increases up to 100% of the width of the front image.

Note, if you are doing this with opengl, you will need to do some translation work too.

Hope that helps.
> 2 votes

---
Tags: graphics, loading
---


# Question
Title: Entity component system - game progression
I'm quite new to game development (but not to programming) and I'm trying to figure out what would be the best way to handle inter-world communication. What I mean is this:

I've been reading about entity component systems (ECS) and how people suggest using different worlds/spaces (http://gamedevelopment.tutsplus.com/tutorials/spaces-useful-game-object-containers--gamedev-14091) for a subsection of a game. For example a HUD, inventory or combat/movement each get a seperate world/space (because they have different graphics and underlying logic.

However, I was wondering how the inventory, or the HUD knows about the health of a player when the health is handled by a different space/world, for example when in combat?

This also applies to game progression in general, for example dialog with NPC (a dialog would be a separate space since it's a popup screen) but how would you convey the choices made in (or the state of) the dialog to other spaces/worlds. Or basically any other type of event that influence the game progression in different spaces/worlds (health, mana, quests, dialog, combat, inventory, hud, etc)

How would one handle this kind of design? Does it need a (in implementation) singleton object that holds all this kind of information? That would be weird because then the `components` need to convey each change to this singleton object which feels like doing things twice (going against the main DRY of programming)...

I'm kind of at a loss here in terms of design, any pointers?

---

***---EDIT---***

So I've read a few other posts suggested by comments and got a general idea about possibilities, however each of them seems to have one major downside which makes them just not right. It's is very possible that I'm overseeing details that would solve these downsides so feel free to correct me. I'll try to give an overview as well as some answers to some questions.

I'm seeing three major options to 'share' data between spaces. Even though most posts are about sharing data between systems, I feel like the same can be applied to sharing data between systems.

**1. Querying**

*Example*: If the HUD world needs to know the current health of the player it can query another world and ask for the current health.

*Downside*: Worlds need to know about each other which is a major dependency issue and goes against decoupling.

**2: Direct messaging (sync and async)**

*Example*: If during combat the health of a player changes it can send messages (sync and async, whatever is needed) to other worlds that need to know about this change.

*Downside*: Still the decoupling issue: worlds need to know about eachother.

**3: Indirect messaging (sync and async)** \<-- best option

*Example*: If during combat the health of a player changes it can send messages (sync and async, whatever is needed) to general message hub. Other worlds/systems that need to know about this change are subscribed to the particular message channel and read the messages.

*Upside*: Completely decoupled, easily manageable and extendable.

*Downside/unclear*: When does the message channel know that the messages need to be deleted? Or maybe the system that is subscribed marks (only for itself) the message as read and waits for new messages -\> messagebox becomes enormous after a while. How do worlds/systems handle order? For example during a frame: if the HUD already polled the health message and after that the health changes, the next frame the HUD gets updated. For some applications this might not be the right way.

*Q: A single game object can exists in multiple spaces*

I'm using Artemis ECS framework which comes with build-in spaces (called worlds). Each entity (and with it, the data in the form of components) is created on a world and thus cannot be shared between worlds.

# Answer
> 1 votes
One way to look at it is that you're possibly putting too much into your game objects.

There's no reason that code that actually hooks up the HUD to your in-world game *needs* to be in a component/system that lives in some particular space. That code will perhaps be better off living in a central manager or global script that has access to all spaces and all objects, and can then interact with the code that knows when to actually create a space and what to put in them (e.g. the code that spawns the player, saves its state between levels, etc.).

You could also just have a "master space" that holds game objects with logic or data that needs to persist past or manipulate the spaces used for levels and UI. That approach is common in engines that force developers to put all scripts/logic onto components/objects (e.g., in Unity, you'd make a global Main object and set it to persist across scene unloading; if Unity actually had spaces, you'd use those instead of the flag).

Remember, abusing your ECS is the same as abusing design patterns; just because you have some nifty new tool doesn't mean that you're supposed to use it to solve every problem you encounter. Evaluate your problem space and select the best-fit solution, even if it's the old dingy thing your ancestors used back in the dark ages of the 90's. :p

# Answer
> 0 votes
I did create a few prototypes but nothing too big and the way I used to handle multiple spaces was simply create a game object which contains, world, player etc and than I'd setup some properties that are required by some other spaces for example health, in the game object

Whenever called it will get the player's health. that way I could send it to the HUD and display the health bar.

It is not the cleanest but it gets the job done, I did some performance testing back in 2013 and everything seemed to work smoothly. to avoid such dependencies you could always drop the health bar when player health is null.

Usually when player doesn't exist it means that the user is in either a menu or a cut-scene.

Code Example:

```
public float PlayerHealth {
  get {
    if (player !+ null)
      return player.Health;
    return -1;
  }
}

```

Hope this is what you were looking for.

# Answer
> 0 votes
this is something that I'm actually working on in the past couple of weeks. I'm working on my own ECS library (wanted to do that for experience and just to try it out, cause I've wanted to do so for quite some time).

This is the github link: https://github.com/gioragutt/xna-ecs

For your problem, I've always written a small pubsub library, which you can see here

Basically, I have an `EmsClient` class, which stuff can derive from. Currently, my components don't do that, but the more higher level classes, although there's not reason not to. I subscribe to Names of messages, and provide a callback with the following signature: `Action<JObject>`. As you've already understood, I'm using Json Objects as means to transfer messages. I've done this after I've before used just `byte[]`'s, and I found that I needed something more general, and since I'm used to something like that from my workplace (we have an IPCD that works similarly, except the callback method is always the same, since usually we separate responsibility to different handlers).

There's an `EmsServer` (one on the server, and one on each client) that's responsible for moving messages between `EmsClient` on it's realm (`EmsServer` on the server side moves messages between `EmsClients` on the server side, vice versa for the client side).

For messaging between the Client and the Server, I created an `EmsServerEndpoint` which is an `EmsClient` himself, he just does the logic of buffering the sent messages on it's realm, and flushing them to other realms (F.E the client sends the message to the server, whereas when the server transfers each message to all clients connected.

You can see usage in a lot of places, f.e: `ClientGameManager`, `ServerGameManager`.

Whereas, for your example, if I want to add a GUI component for a player, you can look HERE, at the `BeginAllocateLocal` and `BeginAllocateRemote` methods, which are responsible for building the `GameObjects` of the players. Each `GameObject` contains an `Entity` (from the ECS lib) and an `IComponentContainer` (which is too, from the ECS lib). Each `GameObject` automatically gets a transform (like in `Unity`, from which I took inspiration).

My code pretty much speaks for itself, and if you get to it, I'm looking for criticism for it, so I would like some constructive criticism :)

Hope that my code would help you with some ideas!

# Answer
> 0 votes
Consider observer/subject pattern components for your game components and ui components. You plug them together upon creation/load up and then forget about them. If the character's health changes, it notifies all observers, which can do whatever they want with the information.

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


# Question
Title: why are my client and server physics not syncing up? node.js and html5
My server looks like this -

```
    var timestep = 1000/30;
    var delta = 0;
    var lastFrameTimeMs = 0;

    function panic() {
        delta = 0;
    }

    var update = function(){
        currentTime = Date.now()

        if (currentTime < lastFrameTimeMs + (timestep)) {
            setTimeout(update);
            return;
        }

        delta += currentTime - lastFrameTimeMs;
        lastFrameTimeMs = currentTime;

        let numUpdateSteps = 0;

        previousTime = currentTime;

        while (delta >= timestep) {
            player.update(timestep/1000)

        }
        delta -= timestep;

        if (++numUpdateSteps >= 240) {

            panic(); // fix things
            break; // bail out
        }
        setTimeout(update, 60)
    }
    setTimeout(update, 60)

```

and then my client looks like -

```
var timestep = 1000/30;
var delta = 0;
var lastFrameTimeMs = 0;

function panic() {
    delta = 0; // discard the unsimulated time
    // ... snap the player to the authoritative state
}

function mainLoop(timestamp) {
    // Throttle the frame rate.
    if (timestamp < lastFrameTimeMs + (timestep)) {
        requestAnimationFrame(mainLoop);
        return;
    }
    delta += timestamp - lastFrameTimeMs;
    lastFrameTimeMs = timestamp;

    let numUpdateSteps = 0;

    while (delta >= timestep) {
        if(player != undefined) {
            player.update(timestep/1000);
        }
        delta -= timestep;

        if (++numUpdateSteps >= 240) {
            panic(); // fix things
            break; // bail out
        }
    }

    requestAnimationFrame(mainLoop);
}
requestAnimationFrame(mainLoop);

```

I've been trying to get this work for days. I'm trying to have a fixed time step on both the client and server so they both simulate physics exactly the same down to the decimal point. But for some reason my client is moving much faster than my server. I used this article as a reference.

https://www.isaacsukin.com/news/2015/01/detailed-explanation-javascript-game-loops-and-timing

Where am I doing something wrong in one of my loops? They both use a .033333333333 timestep like I want them to, but they move at different speeds. What am I doing wrong?

# Answer
In addition to @Nat's answer, you should find a way of calculating when the server got the info from client and using that info to predict the new position. Or even better using extrapolation.

There's a whole wikipedia page about this.
> 1 votes

---
Tags: javascript, networking, node.js
---


title: How to use Unity to slice sprite

text:
# Question
Title: How to use Unity to slice sprite
The polygon slice function of TexturePacker Pro is very nice, it suit the size of the sprite. However my TexturePacker Pro trial had finished, and by using Unity Sprite Editor will make my sliced sprite tremble, I don't know why.

How can I use Unity Sprite Editor to slice my sprites correctly?

# Answer
> 4 votes
If you are seeing trembling in your sprite animations the problem is the pivot point on the sprite sheet. In Unity, the pivot point looks like a blue circle on each sliced sprite in the editor (see screenshot). The pivot point acts as the point of rotation and also the starting point for where the sprite will be rendered in the scene. To fix the problem click the pivot point and on each sliced sprite and drag it to a position that you know will stay constant, like an eyeball or a foot.

---
Tags: unity, spritesheet
---


# Question
Title: How do I manage persistence in a 2d tile-based world that uses a chunking algorithm?
Suppose I have a game that operates on a procedurally generated world that is made of 2D tiles. To save computer resources a chunking algorithm is implemented that slices the entire world in chunks of 32x32 tiles and loads/unloads them based on the position of the player character. Info about chunks is serialized to files. Suppose a 3x3 grid of chunks with the player character in the middle of the grid are loaded and managed at any given time.

The player finds an animal in a forest, but it runs away. They then decide to chase the animal, but it is at least five times as fast as the player and after a while of following its tracks, the distance between becomes too large to ever catch up with it. If the distance is big enough, the animal could have moved itself out of the chunks that are loaded around the player.

Because the animal leaves tracks, it has followed a certain path, avoiding obstacles like trees and rocks, through unloaded chunks.

How is this being managed by the game? I am trying this myself but I am stumped as to coming up with a way to manage, modify and read chunks that aren't loaded so that an animal that ran off screen still moves around sensibly and leaves tracks, or a town that gets flooded while the player is away.

I know that sometimes they calculate what should have changed in a chunk since the player's last visit, but that would mean I'd have to save an incredible amount of data if, say, a pack of 5 animals ran away.

I am not sure if an answer to a question like this requires more (technical) details about my game or project but I will provide these if wanted.

# Answer
> 1 votes
Let each chunk track the last time the player observed it. The next time the player observes a chunk, calculate the delta & simulate that period of time.

In order to keep the simulation reasonably scoped, this solution requires some trade offs. First, minimize actions between chunks. Second, use hierarchical design for things like pathfinding, world simulation & AI. Finally, scale the simulation based on the order of magnitude of the time delta. For instance, with your animal tracking example, if it's been a few turns, do regular low level pathfinding. If it's been many turns, perform regional pathfinding. If it's been very many turns, randomly decide if the animal stuck around.

The basic idea is to simulate big things for big blocks of time & small things for small blocks. Don't simulate the daily weather for a region that hasn't been seen for months - instead simulate the current season. The rational is that more often than not, things the player cannot directly observe or make direct inferences about may as well have never happened.

# Answer
> 0 votes
*Because the animal leaves tracks, it has followed a certain path, avoiding obstacles like trees and rocks, through unloaded chunks.*

**Basically the entity should freeze, If it is not in a loaded chunk.**

You are dividing world in chunks to save resources. Also you are mentioning that Animal should path find in unloaded chunks. these 2 statements are contradictory. Because to path find in any area you need data describing surrounding area. While unloading chunks you actually delete this data from RAM. so you cannot pathfind and travel while in unloaded chunk

---
Tags: procedural-generation, world-design
---


title: Draw a point in world coordinate space

text:
# Question
Title: Draw a point in world coordinate space
How do I draw a point in world coordinate space (where the camera is currently looking at, so that would be view\*projection correct?)

I would think I would need to do something like:

```
PositionInWorld = MousePositionInNDC * view * projection?

```

# Answer
If you want exactly in the center of the camera's field of view, then what you can do is to take a 3d vector pointing in the monitor (aka. (0; 0; -1)), create a 3x3 rotation matrix with the same angles your camera has and multiply these together, this results in a 3d vector rotated to match the camera's ditection. To get a point `x` distance from the camera, you multiply this vector with `x` and you add it to the camera's position.

If you only have access to 4x4 matrices (for example if you use unity), then do everything as above but with a 4d vector and a 4x4 matrix, and before you add the vector to the camera's position, downgrade it to a 3d vector.
> 1 votes

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


title: Synchronizing over UDP

text:
# Question
Title: Synchronizing over UDP
I have two apps communicating over `UDP`. One of the apps is a **remote control** and the other is a **robot**.

When the robot has some new data, for example a new sensor reading or GPS coordinate, I simply put this in an `UDP` packet on it's way to the remote for display and that is that. Since the sensor data has a short time span of validity it does not matter when the packet is lost, because a new one will follow with more updated data shortly anyways.

Similarly when the remote wants the robot to change behavior, I put the new desired behavior in an `UDP` packet on its way to the remote for execution. The only difference now is that this time I also send an "acknowlegement" packet back to the remote so that it will know that the the command was well received. Still this is a simple case.

However in the case where there is a state in the robot that BOTH the robot itself and the remote may change, for example if there is a "panic button" that can both be operated from the remote and the robot, how can the state be kept in sync? Since there is no guarantee the `UDP` packets will reach their destinations, I imagine there needs to be set up some kind of acknowledgement scheme that does not effectuate a command unless it knows that both remote and robot know what is about to happen. But to me this seems impossible to accomplish.

# Answer
> 3 votes
When the user presses the button to enter panic mode, generate a sequential ID to tie to that event of wanting to enter panic mode.

You then periodically send a message to the robot "Activate Panic Mode" with that sequence ID value you generated.

Whenever the robot receives an "Activate Panic Mode" message, have it respond with "Panic Mode Activated" with the same ID sent back. It can actually start doing panic mode behavior the first time it receives this message.

On the remote control side, keep sending that "Activate Panic Mode" message until you receive a message from the robot that it has entered panic mode, at which point you can stop sending them.

This works because the robot doesn't need confirmation from the remote control that it got the message, so you break the chain of infinite confirmation messages needed.

If you have a panic mode indicator on the remote, it's up to you if you want to activate that indicator as soon as the user presses the panic mode button, or if you want to wait til you get confirmation of panic mode from the robot.

Hopefully you can see how you'd do the same thing for deactivating panic mode once it's activated!

The sequence ID may be over kill, but I'm betting it will come in handy for dealing with more complex logic issues.

Lastly, if you are worried about facing twice the amount of unreliability, by having the remote periodically ask the robot for confirmation, you could have the robot send 2 or more confirmations in response to an "Activate Panic Mode" message, instead of just the one. Each side of the communication should be able to gracefully handle 0 to N copies of duplicate network messages with the same sequence IDs.

# Answer
> 1 votes
A common solution I use to send safe messages over UDP is the following :

When the state is changed on one side, send the message periodically (the more important, the shorter the period) until the receiver sends it back to you (or sends an acknowledgement). On the receiver side, send the acknowledgement everytime you receive it. This way, it is 100% reliable and as fast as UDP in most of the cases.

# Answer
> 0 votes
Thanks to ideas in the other answers I have been pondering this and came to the following protocol:

1. Keep *two copies* of the parameters to sync in a registry in *both* **robot** and **remote** memory.
2. Whenever one node initiates a change to a parameter, the local copy is changed *instantly* and a stream of UDP packets is sent to the other node until it responds with an ack for the change.
3. Whenever the other node initiates a change to a parameter, the remote copy of the parameter is changed once the UDP packet arrives, before ack is returned.
4. Whenever there are NO changes, send a continuous stream of UDP packets indicating "no change".
5. Each parameter in both the local and remote copies of the registry holds in addition to their value, a *timestamp* of last confirmed sync (for local, it's the last received ack, for remote its the last change), and the value is considered *confirmed* when less time than the estimated UDP round trip time + margin has passed since the sync was recorded.
6. Each UDP packet for both change and ack will have a serial number to allow multiple packets of the same serial to be ignored.

So you might ask with *two* copies of the parameters on both sides, how do we know what value should be used? The "best" value for each parameter is simply then the one with the last timestamp, however it will be up to the application to decide what to do with the extra "uncertainty" and "knowledge about the other side" data, and to decide when to use which value in the registry.

For example in the panic button case, the robot should be conservative and say as long as at least one of the panic values is TRUE then the time since sync does not matter, panic will be enabled either way.

Another example would be *robot throttle*, which would be lowered or even completely stopped in the case of lost sync (to avoid the robot running away).

In the case of UI in the remote, it can give all sorts of useful feedback to the user such as "grayed out" when fallen out of sync, or a tiny bar graph that shows sync lag etc.

If we cannot afford such high bandwidth usage, we can slow down by simply sending packets with higher delay while at the same time expect slower round trip times.

This protocol will under good network conditions let both sides know that sync is confirmed with a delay of UDP round trip time + margin, and under bad network conditions they will know by the "lack of ack" that the sync status is unconfirmed.

It will also let both sides know what the other side thought to be the current value of each parameter last time the network was in good condition.

---
Tags: networking, synchronization, udp, protocol
---


title: Why is the camera view pink in Unity 5?

text:
# Question
Title: Why is the camera view pink in Unity 5?
I am a beginner. I created a 3D project with a cube object, and I am getting this pink display, in the camera view.

Why is the camera view pink?

# Answer
> 3 votes
You seem to have created a cube as a child of the camera, thus taking up the entire view port. Imagine placing a thumb in front of a camera's lens. Since the cube's material is pink (you seem to have deleted the default material), all you see is one side of a giant pink cube.

You can either:

* Change the hierarchy of the cube. Click on the cube, hold the click, and drag it *outside* of Main Camera.
* Set the Camera's "Near Clipping Pane" property to a different value, superior to 1 (which seems to be the depth of the cube).

# Answer
> 2 votes
What you see is a *default material*. It is nothing to be overly concerned about; it serves as a *placeholder*. The only problem appears to be the *colour*; In my experience, the default material is usually a light grey. In the recent version of Unity I downloaded, version 5.5.0f3, it is black.

If you wish to try resetting your default material colour, I found other users who have experienced similar issues, on *installing* Unity. One user has found a solution, which seems to work, most of the time:

> **Answer** by Javier\_8 · Jun 23, 2015 at 10:59 PM
> I fixed it.
> Edit-\>Preferences-\>GI Cache-\>\[Clear Cache\]
> <sub>\- "Unity 5 default shaders are pink" @ Unity Answers</sub>

Remember that this is the *default material*. Pink or not, you should still aim to replace this material at your earliest convenience, if only to a more suitable prototype material. My recommendation would be to simply *ignore* the pink; pink is far more noticeable than grey, making it much easier to tell if a particular mesh needs an actual material. You can find information on creating and making materials at the Unity manual.

---

As for *what* is being displayed, I can only speculate, given the information that has been provided.

First and foremost, *it is not the cube*. We know this for *two* reasons:

1. In the inspector, your cube has its `MeshRenderer` disabled. This is the part that *renders* the mesh of the cube. While disabled, your cube is not rendering, and you will not be able to see it from the game view.

2. From the inside of a cube, all normals (values that tell us the *facing direction* of each face) face *away* from the camera. When a normal faces *away* from you, the face does not render, *even when the `MeshRenderer` is enabled*, as you can see in the following animation.

Given that the only other object in the scene is a directional light, I would speculate that it is the *Clear Flags* setting, on your camera. You might have this set to *Skybox*, with the default shader interfering with the default skybox. It is entirely possible that you might simply have it set to *Clear Colour*, and actually have the colour manually set to pink.

---
Tags: unity
---


# Question
Title: How do you remove the default sky in Unreal?
I'd rather texture/animate my own sky. How do I remove the default sky?

# Answer
> 1 votes
The "standard" sky that comes with a new, non-empty level is just an object in the level. It's a `BP_Sky_Sphere` Blueprint instance, and you can find it in the World Outliner (right-hand list view in a default viewport arrangement) and delete it. It's probably called "Sky Sphere."

Once gone, you can replace it, either with your own custom solution or with some middleware, et cetera. You may also want to investigate if tweaking the existing Blueprint will serve your needs, as it has a few options.

---
Tags: unreal-4
---


# Question
Title: LibGDX - Box2D, world, bodies and deltaTime
Can somebody tell me how to correctly handle Box2D "deltaTime"? When I have non-Box2D objects it's sufficient to multiply `velocity` by `deltaTime` but what should I do when I use Box2D world and bodies? multiply for example `linearVelocity` by delta or `timeStep`?

# Answer
You shouldn't multiply the *delta time* by anything for **Box2D**, just pass it in to the `World` when you do the time step.

```
// Somewhat condensed...
public class YourGameplayClass {
    private World world;
    private int velocityIterations = 4;
    private int positionIterations = 6;

    public void update() {
        world.step(Gdx.graphics.getDeltaTime(), velocityIterations, positionIteration);
    }
}

```

**Box2D** will move your objects according to the stepped delta time and take their velocity into account for you.
> 2 votes

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


# Question
Title: What is the best way to animate a jumping motion in Unity 3D?
I am creating a a simple 3D game in Unity with a character who runs, walks, jumps, swims, shoots etc. I am pretty satisfied with my results in all the motions except jump. I need to know at what height my character is at in relation to the ground at all times (The height of my terrain varies) in order for me to be able to tell the Animator Controller when to transition. I have done some research on the matter and I found out about Raycast but I'm not sure how to use it. Any help would be great, thanks!

# Answer
> 1 votes
If you were dealing with plain terrain, it would be easier to calculate, but with a complex terrain such the one you have starting height that differs from the landing height gives you very limited choices, and RayCasting is probably the best among them.

The idea is simple, on every frame of your animation you have to RayCast from the bottom of your character (or its collider, it's up to you the distance you want to calculate), in direction Vector3.down and use the distance from that point to the terrain surface to speed up your animation the way you like. **Unity raycasting class already provides you with the distance from the point you have raycasted from and the point you have hit**, the code is therefore very short:

```
Vector3 characterBottomPosition; //initialize this with thebottom position of you character or its collider
    void Update(){
        RaycastHit hit;
        Ray downRay = new Ray(characterBottomPosition, -Vector3.up);
        // if the raycast hits something
        if (Physics.Raycast(downRay, out hit)) {
            float distanceFromGround = hit.distance;
            // do your animation stuff here
        }
    }

```

**Please be aware of two things:** the terrain object must have a collider in order to "be hit", otherwise you might have to implement your own raycasting system (which could be extremely time consuming and painful), and also Raycasts will not detect Colliders for which the Raycast origin is inside the Collider, be sure to stop your animation in time before the point from which you are raycasting gets below the terrain.

Hope this helps :)

# Answer
> 0 votes
I'm not sure if this is the answer that you are looking for as I could use some more specifics, however, the best way to actually go about animating a jump animation is to break it into 3 parts; the "Jump Start", the "Jump Loop" and the "Jump End". The Jump Start is where the character is animated jumping into the air, the loop is the movement he makes while "falling" and the Jump End is the impact with the ground. The reason this is the best approach is because it allows you to vary the height of the jump without having to preemptively know how long the player is going to be in the air for. For example, if the player jumps off the top of a building to land on the ground, versus jumping from the ground to a medium height platform. The hold time is different for each.

Hopefully this is what you were asking.

---
Tags: 3d, animation, unity
---


# Question
Title: How to use MaterialPropertyBlocks to randomly change the color of multiple materials on an object?
I have a character prefab for a civilian with 5 materials. Each one should be a random color but I don't want a new material for every civilian in the game. I asked a question earlier and had a good answer. However I was pointed towards this question with MaterialPropertyBlocks. This is the code I currently have:

```
void Start () {
    Color newShirtColor = shirtColor[Random.Range(0, shirtColor.Length)];

    MaterialPropertyBlock props = new MaterialPropertyBlock();
    props.AddColor("_Color", newShirtColor);
    GetComponent<SkinnedMeshRenderer>().SetPropertyBlock(props);
}

```

It works really well but the color is assigned to the whole mesh. How can I do this for each of the 5 materials on the object so that it only changed the color for the assigned parts of the mesh, with only one material for each section?

# Answer
I had a great answer over here at the unity forums. In short he basically said to use a texture with different colors on each channel and use that as a factor for each section of the character, thus sort of separating out the mesh, without actually separating it.
> 0 votes

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


title: Passing Matrix to shader

text:
# Question
Title: Passing Matrix to shader
I am learning HLSL and having trouble understanding how to pass matrices into the shaders to be able to perform the necessary operations within the shader to have the position values sent to the shaders placed in the correct place according to the view and projection matrices. I was going to place the viewMatrix and projMatrix data into the INPUT\_ELEMENT\_DESC array but then found that there is not a DXGI\_FORMAT value to support a 4x4 float matrix. What is the correct way to pass the values of projMatrix and viewMatrix into the shader?

Thanks in advance

**windowSource.cpp**

```
    void BuildD3D(HWND hWnd){

    // create a struct to hold information about the swap chain
    DXGI_SWAP_CHAIN_DESC scd;

    // clear out the struct for use
    ZeroMemory(&scd, sizeof(DXGI_SWAP_CHAIN_DESC));

    // fill the swap chain description struct
    scd.BufferCount = 1;                                    // one back buffer
    scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;     // use 32-bit color
    scd.BufferDesc.Width = 800;
    scd.BufferDesc.Height = 600;
    scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;      // how swap chain is to be used
    scd.OutputWindow = hWnd;                                // the window to be used
    scd.SampleDesc.Count = 4;                               // how many multisamples
    scd.Windowed = TRUE;                                    // windowed/full-screen mode
    scd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;

    // create a device, device context and swap chain using the information in the scd struct
    D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, NULL, NULL, NULL, D3D11_SDK_VERSION, &scd, &swapchain, &dev, NULL, &devContext);

    // Get Back Buffer information
    ID3D11Texture2D *pBackbuffer;
    swapchain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackbuffer);

    // Target rendering to the backbuffer that was just defined
    dev->CreateRenderTargetView(pBackbuffer, NULL, &backbuffer);

    // Release the data that was rendered to the backbuffer.
    pBackbuffer->Release();

    // Define the backbuffer as the rendering target
    devContext->OMSetRenderTargets(1, &backbuffer, NULL);

    // Define Viewport
    D3D11_VIEWPORT viewport;
    ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));
    viewport.TopLeftX = 0;
    viewport.TopLeftY = 0;
    viewport.Width = 800;
    viewport.Height = 600;

    devContext->RSSetViewports(1, &viewport);

    // Set Up Projection Matrix
    projMatrix = DirectX::XMMatrixPerspectiveFovLH(DirectX::XMConvertToRadians(45.0f), 1920.0f, 1.0f, 200.0f);

    // Set Up View Matrix
    DirectX::XMVECTOR eyePos = {0.0f, 10.0f, 0.0f};
    DirectX::XMVECTOR focusPos = {0.0f, 0.0f, 0.0f};
    DirectX::XMVECTOR upPos = { 0.0f, 1.0f, 0.0f };

    // Bind LookAt matrix to viewmatrix
    viewMatrix = DirectX::XMMatrixLookAtLH(eyePos, focusPos, upPos);

    BuildPipeline();
    ParseGraphics();
}

void RenderFrame(void) {

    // Clear BackBuffer to a color
    devContext->ClearRenderTargetView(backbuffer, D3DXCOLOR(0.0f, 0.2f, 0.4f, 1.0f));

    // select which vertex buffer to display
    UINT stride = sizeof(Vertex);
    UINT offset = 0;
    devContext->IASetVertexBuffers(0, 1, &pVBuffer, &stride, &offset);

    // select which primtive type we are using
    devContext->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

    // draw the vertex buffer to the back buffer
    devContext->Draw(6, 0);

    // swap buffers
    swapchain->Present(0, 0);
}

void ParseGraphics() {

    // Create Vertex Buffer
    D3D11_BUFFER_DESC bd;
    ZeroMemory(&bd, sizeof(bd));

    bd.Usage = D3D11_USAGE_DYNAMIC;
    bd.ByteWidth = sizeof(Vertex) * 6;
    bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;

    dev->CreateBuffer(&bd, NULL, &pVBuffer);

    // copy vertices into buffer
    D3D11_MAPPED_SUBRESOURCE msr;
    devContext->Map(pVBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &msr);
    memcpy(msr.pData, square, sizeof(square));
    devContext->Unmap(pVBuffer, NULL);

}

void BuildPipeline() {
    // Load and Compile Shaders
    ID3D10Blob *VS, *PS;
    D3DX11CompileFromFile(L"shaders.shader", 0, 0, "VShader", "vs_5_0", 0, 0, 0, &VS, 0, 0);
    D3DX11CompileFromFile(L"shaders.shader", 0, 0, "PShader", "ps_5_0", 0, 0, 0, &PS, 0, 0);

    // Create shaders from the data in the Blobs Buffer
    dev->CreateVertexShader(VS->GetBufferPointer(), VS->GetBufferSize(), NULL, &pVS);
    dev->CreatePixelShader(PS->GetBufferPointer(), PS->GetBufferSize(), NULL, &pPS);

    // Apply Shaders to the device context
    devContext->VSSetShader(pVS, 0, 0);
    devContext->PSSetShader(pPS, 0, 0);

    // Define the layout of the input given to the shaders
    D3D11_INPUT_ELEMENT_DESC ied[] =
    {
        {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
        {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 3 * sizeof(float), D3D11_INPUT_PER_VERTEX_DATA, 0},
        // Maybe pass projection matrix into shader here???

    };

    dev->CreateInputLayout(ied, 2, VS->GetBufferPointer(), VS->GetBufferSize(), &pLayout);
    devContext->IASetInputLayout(pLayout);

}

```

**shader.shaders**

```
    struct VOut
{
    float4 position : SV_POSITION;
    float4 color : COLOR;
    float4x4 fMatrix;
};

VOut VShader(float4 position : POSITION, float4 color : COLOR)
{
    VOut output;

    output.position = position;
    output.color = color;

    return output;
}

float4 PShader(float4 position : SV_POSITION, float4 color : COLOR) : SV_TARGET
{
    return color;
}

```

# Answer
Yes, there is no way to pass a float4x4 to an input description. By doing that you'd be passing a matrix for every vertex to your vertex shader. This is bad practice unless you need to bind a different matrix for every vertex that you input. It's a better idea to create and bind a constant buffer that has that matrix. You only have to bind that constant buffer once per frame and it will be a lot faster since you'll be reusing that matrix.

Here's a straightforward example from Microsoft on creating and using a constant buffer: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476896%28v=vs.85%29.aspx

Here's some more advanced reading on buffers in DX11 in general: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476898%28v=vs.85%29.aspx
> 3 votes

---
Tags: c++, directx11, hlsl, matrix
---


# Question
Title: FInd out if AABB is left/right/below or obove a ray
What algorithms are there to find out in which quadrant of the ray an AABB is given a roll value? My idea was to rotate the cube by the negative rotation of the ray and move it by the negative position and then find out in which part of the coodinate system it is, however this seems to be kind of complicated to be since there are less complicated ray/AABB intersection algorithms and what I am looking for is way less specific. It should return an array of bools for all the quadrants, since a box can be in multiple quadrants at a time.

# Answer
> 2 votes
If your ray `Z` is, as I understand from your comments, the forward vector of your camera, then it plus the up vector `Y` of the camera provide sufficient information to construct the basis vectors for the camera's coordinate system. Assuming a right-handed system, `cross(Z, Y)` will give the sideways-pointing vector `X`.

The vectors of this coordinate frame can be used to define the XZ and YZ planes of the coordinate system. The `Y` vector is the normal, and thus provides the `A`, `B` and `C` components of the XZ plane; `D` is 0, and so on.

These two planes describe your 'quadrants:' any point on the positive half-space of both planes is in quadrant 0. Any point on the positive side of XZ but negative side of YZ is in quadrant 1. And so on:

```
XY sign | YZ sign | quadrant
   +         +      0
   +         -      1
   -         +      3
   -         -      2

```

With this, you can test each of the box's corners against both planes and determine which quadrant that corner is in. The box itself can be considered to be in all of the quadrants any of its points are in.

---
Tags: collision-detection, raycasting, aabb, raytracing
---


title: Turn Based Game- Determining turns

text:
# Question
Title: Turn Based Game- Determining turns
I am developing a Checkers game and need to implement players' turn, particularly after "Capturing". Changing turns after single steps work properly but not correctly after capturing.

In the drag and drop code below a Checker GameObject is selected and dropped at a position.

In order to successfully complete a move, we verify whether it is that Player's turn. If it is that player's turn the Checker GameObject's transform position is updated with the position of the object called 'targetObject' and other arrays are updated to reflect the changes.

These steps work as expected when making a single step move. When capturing, which requires different rules, things do not work correctly. After every capture, the Checker GameObject should detect whether another move is required. If yes, the game should not change turn. Same player must play again. If no, it is the other player's turn.

Sadly, although in Debug.Log "isCapture" is indicating the player is not required to capture and that it is the opponent's turn, the game still accepts the wrong player's move.

```
void LateUpdate ()
{
    //select
    if ( Input.GetMouseButtonDown(0) )
    {
        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if ( Physics.Raycast(ray, out hit) )
        {
            if ( hit.transform.gameObject.tag == "Checker" )
            {
                int team = hit.transform.gameObject.GetComponent<CheckerSeed>().team;
                if ( team == myTurn )
                {
                    hitObject = hit.transform.gameObject;
                    current = hitObject.GetComponent<CheckerSeed>().GetID();
                }
                else hitObject = null;
            }
        }
    }

    //Hold Object
    if ( Input.GetMouseButton(0) )
    {
        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if ( Physics.Raycast(ray, out hit) )
        {
            if ( hit.transform.gameObject.tag == "Position" )
            {
                targetObject = hit.transform.gameObject;
                target = targetObject.GetComponent<PositionInfo>().index;
            }
        }

    }

    //Drop Object
    if ( Input.GetMouseButtonUp(0) )
    {
        bool isCapture = hitObject.GetComponent<CheckerSeed>().MustCapture(current);
        SwitchTurn(hitObject, targetObject, isCapture);
        Debug.Log("UP: Play again is " + isCapture.ToString() + " It's Team " + myTurn.ToString());

        if ( hitObject != null && targetObject != null )
        {
            {
                int difference = target - current;
                int a = hitObject.transform.gameObject.GetComponent<CheckerSeed>().GetID();
                int b = targetObject.GetComponent<PositionInfo>().index;
                team = hitObject.GetComponent<CheckerSeed>().team;

                //single step
                if ( ( difference == 5 ) || ( difference == 6 ) || ( difference == 4 ) || ( difference == -5 ) || ( difference == -6 ) || ( difference == -4 ) )
                {
                    if ( team == myTurn )
                    {
                        if ( Rules.instance.RegularMovePossible(team, a, b) )
                        {
                            Successful();
                        }
                        if ( hitObject.GetComponent<CheckerSeed>().moved )
                        {
                            myTurn = myTurn == 2 ? 1 : 2;
                            hitObject = null;
                            targetObject = null;
                        }
                        Debug.Log("It's Team " + myTurn.ToString() + "'s turn.. Single step.");
                    }
                    return;
                }
                else
                {

                    if ( Rules.instance.CapturingPossible(team, a, b) )
                    {
                        //Capturing step... only take multiple steps if actually capturing an opponent
                        if ( hitObject.GetComponent<CheckerSeed>().Capturing(b) )
                        {
                            Capture(team, a, b);
                            Successful();
                        }
                        else Debug.Log("Jumping is not allowed except when capturing");
                    }
                    //              }
                    return;
                }
            }
        }
    }
}

```

# Answer
> 0 votes
So after some debugging, I was able to trace the issue and resolve the problem. I my code to determine whether a piece could capture another piece, I was searching from the current Checker position, which became invalid by the time the Checker changed position. I need to "Look ahead", search from the future position to determine whether a capture was possible from the target position and return a boolean. After some tweaking the the affected portion of my LateUpdate method looks like this: else {

```
                    if ( Rules.instance.CapturingPossible(team, a, b) )
                    {
                        bool PlayerTurn = true;
                        //Capturing step... only take multiple steps if actually capturing an opponent
                        if ( hitObject.GetComponent<CheckerSeed>().Capturing(b) )
                        {
                            Capture(team, a, b);
                            PlayerTurn = Successful(playAgain);
                            if(!PlayerTurn)
                            {
                                myTurn = myTurn == 2 ? 1 : 2;
                                hitObject = null;
                                targetObject = null;
                            }
                        }
                    }
                    return;
                }

```

---
Tags: unity, c#, game-loop
---