# Question
Title: Unproject mouse position to tile -- extremely jumpy position?
I'm trying to unproject the mouse position to get the position on the X-Z plane of a ray cast from the mouse. The camera is fully controllable by the user. Right now, the algorithm I'm using is...

```
    private bool getHoveredCorner(ArcBallCamera camera, System.Windows.Point m, out int tx, out int ty)
    {
        tx = -1; ty = -1;
        Ray ray = camera.unproject((float) m.X, (float) m.Y);
        Vector3 p = ray.Position + (-ray.Position.Y / ray.Direction.Y) * ray.Direction;
        float u = p.X / totalWidth;
        float v = p.Z / totalHeight;
        if(u < 0 || u > 1 || v < 0 || v > 1) return false;
        tx = (int) Math.Round(u * tileWidth);
        ty = (int) Math.Round(v * tileHeight);
        return tx >= 0 && tx <= tileWidth && ty >= 0 && ty <= tileHeight;
    }

```

And camera.unproject is...

```
    public Ray unproject(float x, float y)
    {
        Matrix m = viewProj;
        Vector3 p1 = Vector3.Unproject(new Vector3(x, y, 0), 0, 0, width, height, nearPlane, farPlane, m);
        Vector3 p2 = Vector3.Unproject(new Vector3(x, y, 1), 0, 0, width, height, nearPlane, farPlane, m);
        Vector3 dir = p2 - p1;
        dir.Normalize();
        return new Ray(p1, dir);
    }

```

The problem is that the projected position is "jumpy". As I make small adjustments to the mouse position, the projected point moves in strange ways. For example, if I move the mouse one pixel up, it will sometimes move the projected position down, but when I move it a second pixel, the project position will jump back to the mouse's location. The projected location is always close to where it should be, but it does not smoothly follow a moving mouse. The problem intensifies as I zoom the camera out. I'm not sure what's causing the problem, but I'm thinking it might be numerical instability?

**EDIT 1:** Video showing the problem

**EDIT 2:** A little snooping around in .NET Reflector on SlimDX.dll:

```
public static Vector3 Unproject(Vector3 vector, float x, float y, float width, float height, float minZ, float maxZ, Matrix worldViewProjection)
{
    Vector3 coordinate = new Vector3();
    Matrix result = new Matrix();
    Matrix.Invert(ref worldViewProjection, out result);
    coordinate.X = (float) ((((vector.X - x) / ((double) width)) * 2.0) - 1.0);
    coordinate.Y = (float) -((((vector.Y - y) / ((double) height)) * 2.0) - 1.0);
    coordinate.Z = (vector.Z - minZ) / (maxZ - minZ);
    TransformCoordinate(ref coordinate, ref result, out coordinate);
    return coordinate;
}

// ...

public static void TransformCoordinate(ref Vector3 coordinate, ref Matrix transformation, out Vector3 result)
{
    Vector3 vector;
    Vector4 vector2 = new Vector4 {
        X = (((coordinate.Y * transformation.M21) + (coordinate.X * transformation.M11)) + (coordinate.Z * transformation.M31)) + transformation.M41,
        Y = (((coordinate.Y * transformation.M22) + (coordinate.X * transformation.M12)) + (coordinate.Z * transformation.M32)) + transformation.M42,
        Z = (((coordinate.Y * transformation.M23) + (coordinate.X * transformation.M13)) + (coordinate.Z * transformation.M33)) + transformation.M43
    };
    float num = (float) (1.0 / ((((transformation.M24 * coordinate.Y) + (transformation.M14 * coordinate.X)) + (coordinate.Z * transformation.M34)) + transformation.M44));
    vector2.W = num;
    vector.X = vector2.X * num;
    vector.Y = vector2.Y * num;
    vector.Z = vector2.Z * num;
    result = vector;
}

```

...which seems to be a pretty standard method of unprojecting a point from a projection matrix, however this serves to introduce another point of possible instability. Still, I'd like to stick with the SlimDX Unproject routine rather than writing my own unless it's really necessary.

# Answer
> 1 votes
You might want to try rendering both the snapped to grid and unsnapped positions to help you see where it's going wrong.

You should also check that the near and far plane values that you're using aren't too far apart. Most notably the bigger far/near ratio is the less accuracy you'll get both for rendering and for the calculations.

Having said that the values of 1 and 500 you said you were using seem to be well within a reasonable range to give decent accuracy to me.

When you're looking for precision issues in floating point maths, the main thing to watch out for is subtraction. If the numbers you're subtracting are close together then you'll have less precision in the result. Have a read of at least the cancellation section of http://docs.oracle.com/cd/E19957-01/806-3568/ncg\_goldberg.html for more details.

# Answer
> 0 votes
I found that I needed to tighten the near and far values and ensure that the unproject function's near/far plane input matches the projection matrix that is also fed into the unproject function. Remember, the projection matrix which helped form your 'viewProj' variable also contains near and far plane values.

For me, this resolved the exact symptoms you describe.

---
Tags: c#, mathematics, projection, slimdx, picking
---


# Question
Title: How to create a delay/timer and fire an action once it expires in C# Monogame?
First off I'm somewhat new to C# but I'm working on a game in C# Monogame and I'm trying to get timers working. There was a similar question answered around here a while back but I found that the solution doesn't work for me, perhaps an older version or I'm missing something, so I wrote similar timer and timer manager classes myself.

I ended up with a `wait(time)` function (that seems to work from looking through the debugger but not sure) now I'm wondering how can I get an action to be executed when the timer created by that expires.

Ideally I'd like something like

```
timerManager.Wait(10)
{
    //do stuff once done waiting
}

```

Here's my timer classes - Timer.cs and TimerManager.cs

TimerManager gets instantiated in my player class and wait is called in the update function by keyboard input.

```
if(keyState.IsKeyDown(Keys.Space))
{
    if(canJump)
    {
        vAccel = jumpSpeed * -1;
        stripManager.setCurrentAction(PlayerActions.jump);
        timerManager.Wait(1);
    }
}

```

So my question is how can I get an action to trigger, ideally with a set of {} as shown above. I'm aiming to having a class I can reuse for any sort of delay I need in my game.

# Answer
> 2 votes
Perhaps something like the following might work for you or at least give you new ideas to handle your problem:

```
float delay = 0;
bool trigger = false;

public Update()
{
    if(keyState.IsKeyDown(Keys.Space))
    {
         if(canJump) //this line is specific to the OP code
         { //this line is specific to the OP code
             vAccel = jumpSpeed * -1; //this line is specific to the OP code
             stripManager.setCurrentAction(PlayerActions.jump); //this line is specific to the OP code

             WaitTime(10);

         } //this line is specific to the OP code
    }

    if (delay > 0) delay -= Time.deltaTime;
    if (delay <= 0 && trigger)
    {
        DesiredActionAfterTimer();
        trigger = false;
    }
}

void WaitTime(float amountoftime)
{
     delay = amountoftime;
     trigger = true;
}

void DesiredActionAfterTimer()
{
    //Here you put the action you want to perform when time-waiting is over
}

```

What the above code does is the following.

When you call function WaitTime() passing a float value to it (let's call it X), that function only sets the delay variable to X and sets the trigger to "true". It is in the Update() loop function that the real timer works: every frame, if variable delays is greater than zero and trigger is "true", we subtract a Time.deltaTime from the delay variable. Then, when delay reaches zero, the function DesiredActionAfterTimer() is called to perform whatever action you want to be performed after the timer reaches zero. Also, the trigger variable is then set back to "false". Note that the trigger variable is important to assure that DesiredActionAfterTimer() is only called when WaitTime() was called first - not all the times delay is equal or lower than zero.

Lastly, for further ideas, does the question posted a couple of days ago help you a bit? See: How do I wait to execute code?

# Answer
> 1 votes
A problem is that wait blocks. I suspect what you actually want to do is when the key is pressed store the total time in a variable and then decrement it every tick by your delta-t and check if it's less than or equal to zero.

# Answer
> 1 votes
I would use something like TaskScheduler, you can probably find dozen of implementations. If you insist on implementing it yourself here is rough sketch:

```
class PriorityQueue<T> where T: IComparable
{
   private List<T> _list;
   void Enqueue(T item) { _list.Add(item); }
   T Peek() { return _list.Min();}
   T Pop() {
     var tmp = Peek();
     _list.Remove(tmp);
     return tmp;
   }
}
class ScheduledTask : IComaparable
{
  public Action Action { get; set; }
  public TimeSpan Time { get; set; }
  //constructor, implementation of IComaparable, etc.
}

class TaskScheduler {
  private PriorityQueue<ScheduledTask> _queue;
  public void Schedule(Action a, double seconds)
  { _queue.Enqueue(new ScheduledTask(a, gameTime.TotalGameTime.AddSeconds(seconds))); }

  public void InvokeAll()/*make sure you call this once each frame*/
  {
    while(_queue.peek().Time < gameTime.TotalGameTime )
     _queue.pop().Action.Invoke();
  }
}

```

Note that provided PriorityQueue is *far* from optimal, but I wont go into details of proper implementation of PriorityQueue as there are dozens implementations around, and it is well-defined ADT.
And usage:

```
TaskScheduler ts; //single instance is for all actions
if(keyState.IsKeyDown(Keys.Space))
{
    if(canJump) {
        ts.Schedule( ()=>
          {
              player.Jump(); /*or whatever code here*/
          }, 1.0 );
    }

    if(canFire) {
        ts.Schedule( ()=>
          {
              player.Fire();
          }, 0.5 );
    }
}

```

This is the closest you can probably get - to use lambda expression as Action - as far as I know you cannot implement own scopes (code blocks). Upside of this solution is you dont need add new named function for each action.
*note: I did not checked syntax, if you see syntax error feel free to edit or comment the correction.*

---
Tags: c#, xna, monogame, timer, source-code
---


title: Adding class to Game

text:
# Question
Title: Adding class to Game
I work on a little project, and in the past, I used `SpriteManager : DrawableGameComponent` as my `SpriteManager` class.

I have been told that `DrawableGameComponent` is not so recommended to use, so I decided to make my own custom methods in a new class called `SpriteManagerGeneral`. Now I try to acces that class via `Game`. In the past I used this in `Game`:

```
spriteManager = new SpriteManager(this);
Components.Add(spriteManager);

```

But now I can't do this with `SpriteManagerGeneral` because it's not a `GameComponent`.

Do I just change my class (and edit my methods) to `SpriteManagerGeneral : GameComponent` or is there another way (that is better than `GameComponent`) to do this?

NOTE: I'm a beginner in programming.

NOTE2: Yes I know why `DrawableGameComponent` is not so recommended.

# Answer
Your SpriteManager class would not derive from anything. You would write in your own Update and Draw functions:

```
public class SpriteManager
{
    GraphicsDevice GraphicsDevice;

    public SpriteManager(GraphicsDevice graphicsDevice)
    {
        GraphicsDevice = graphicsDevice;
        LoadContent();
    }

    private void LoadContent()
    {
        //Use GraphicsDevice to load content here
    }

    public void Update(GameTime gametime)
    {
         float elapsed = (float)gametime.ElapsedGameTime.TotalSeconds;
    }

    public void Draw(SpriteBatch spriteBatch)
    {
         spriteBatch.Draw(foo);
    }
}

```

Don't forget to call Update() in your Update, and Draw() in your Draw from the main Game class:

```
...

SpriteBatch SpriteBatch;
SpriteManager SpriteManager;

protected override void LoadContent()
{
     SpriteBatch = new SpriteBatch(GraphicsDevice);
     SpriteManager = new SpriteManager(GraphicsDevice);
}

protected override void Update(GameTime gameTime)
{
    SpriteManager.Update(gameTime);
}

protected override void Draw(GameTime gameTime)
{
    SpriteBatch.Begin();
    SpriteManager.Draw(SpriteBatch);
    SpriteBatch.End();
}

...

```
> 2 votes

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


title: Unable to rotate GameObject properly?

text:
# Question
Title: Unable to rotate GameObject properly?
My GameObject is able to jump towards a moving target (another GameObject), thus adjusting its trajectory - while simulating gravity (as in the .gif).

I want to make the "jumper object" rotate. But I am unable to rotate my GameObject properly. When the GameObject jumps, it doesn't complete its rotation and rotates abruptely. How can I fix this? How can I properly rotate the cube GameObject you see in the .gif? Any fixes are appreciated.

Wanted rotation:

What I get:

# Answer
**The code structure you want:**

```
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, lerpFactor);

```

**A more adjusted version for your script:**

Change the line

```
transform.Rotate (new Vector3 (a, b, c) * Time.deltaTime);

```

with

```
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(a, b, c), Time.deltaTime);

```

**Also,**

```
        void Update()
        {
            if(Input.GetMouseButtonUp(0))
            {
                //this is only called when button gets relased.
            }

            if (Input.GetMouseButton (0))
            {
                //this is called constantly if button is holding down.
            }
        }

```

---

**Edit:**

This code piece should do what you want:

```
    Quaternion targetRot = Quaternion.identity; //try not to modify this directly, or do it, it's up to you.
    bool doRotate = false;
    float lerpLimit = 10; //the degrees you want lerp to stop at. set higher than 0 (i suggest higher than 1)

    public void SetRotationTarget(Vector3 eulerAngles) //call this method to update the rotation target.
    {
        targetRot = Quaternion.Euler (eulerAngles); //building a quaternion from given vector3
        doRotate = true;
    }

    void Update()
    {
        if (doRotate)
        {
            if (Quaternion.Angle(transform.rotation, targetRot) > lerpLimit) //if angle between our rotation and target rotation is not below limit
            {
                transform.rotation = Quaternion.Slerp (transform.rotation, targetRot, Time.deltaTime); //Slerp to target rotation
            }
            else
            {
                transform.rotation = targetRot;
                doRotate = false;
            }
        }

        if(Input.GetMouseButtonUp(0)) //when mouse button 0 is relased
        {
            SetRotationTarget(new Vector3(a, b, c)); //set new rotation target with values of (a, b, c)
        }
    }

```
> 2 votes

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


title: create a seamless room

text:
# Question
Title: create a seamless room
I'm trying to create the effect of the second picture below where there is no seam between the floor or wall. An effect that is typically used in studios by having a curved wall. This way it looks like the model is standing in an infinite space while still being able to cast a shadow on the floor for example.

There are probably different ways to create this. But how would you do it? I was thinking of a using a curved wall that starts from the floor and curves up. Then simply use a gradient texture on it. To create the curved wall I was planning to use this package that allows me to use splines directly in unity, instead of creating a curved wall in Blender and then importing it in unity for example.

I haven't bought the package yet because I would like to know if there are any better ways to create something like this. As you see here in the image below there is this gradient background effect. https://www.assetstore.unity3d.com/en/#!/content/7038

# Answer
> 1 votes
In the end I went for the Blender solution. Modeled a curved wall and imported it into unity. It gave the desired effect.

---
Tags: unity
---


# Question
Title: How To Find Out Which Package That Asset Belongs To?
I have just messed up my project with some conflicting plugins, so i need to clean all plugins and reimport them, but i can't make sure which files to delete.

So how can i find out which package an asset belongs to?

Thanks in advance.

# Answer
> 1 votes
~~Do like reimporting the package, but stop at the last step. It will list you all the files which get imported by the package; clean this files manually. Unfortunately I do not know a way to unimport Unity packages.~~

Well, after some reasearch I could find this package. I do not know if this plugin rewrites old (Standard Asset) data etc., but it is definitely worth a shot!

Advice for the future: If it is an important / time-intensive project add source control to your project! SVN works great if you are a part of a small team or no team at all. It is easy to Setup. I can recommend TortoiseSVN as client, and VisualSVN as server (for windows). Do not forget to exclude the library folder ;)

---
Tags: unity
---


# Question
Title: ResolutionException: Cannot find candidate artifact for com.google.android.gms:play-services-games:8.1+
Getting this error:

> ResolutionException: Cannot find candidate artifact for com.google.android.gms:play-services-games:8.1+ Google.JarResolver.PlayServicesSupport.DependOn (System.String group, System.String artifact, System.String version) GooglePlayGames.BackgroundResolution.AddDependencies () (at Assets/GooglePlayGames/Editor/BackgroundResolution.cs:53) GooglePlayGames.BackgroundResolution..cctor () (at Assets/GooglePlayGames/Editor/BackgroundResolution.cs:45) Rethrow as TypeInitializationException: An exception was thrown by the type initializer for GooglePlayGames.BackgroundResolution System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor (RuntimeTypeHandle type) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Runtime.CompilerServices/RuntimeHelpers.cs:101) UnityEditor.EditorAssemblies.ProcessEditorInitializeOnLoad (System.Type type) (at C:/buildslave/unity/build/Editor/Mono/EditorAssemblies.cs:123) Rethrow as TargetInvocationException: Exception has been thrown by the target of an invocation. System.Reflection.MonoCMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object\[\] parameters, System.Globalization.CultureInfo culture) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Reflection/MonoMethod.cs:519) System.Reflection.MonoCMethod.Invoke (BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object\[\] parameters, System.Globalization.CultureInfo culture) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Reflection/MonoMethod.cs:528) System.Reflection.ConstructorInfo.Invoke (System.Object\[\] parameters) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Reflection/ConstructorInfo.cs:77) System.Activator.CreateInstance (System.Type type, Boolean nonPublic) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System/Activator.cs:372) System.Activator.CreateInstance (System.Type type) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System/Activator.cs:254) UnityEditor.AssetPostprocessingInternal.GetMeshProcessorVersions () (at C:/buildslave/unity/build/Editor/Mono/AssetPostprocessor.cs:145) UnityEditor.AssetPostprocessingInternal:GetMeshProcessorVersions()

How to solve this?

# Answer
Open SDK manager and make sure you have the latest versions of following packages:

1. Extras / Android Support Repository
2. Extras / Google Repository

This solved the problem for me.
> 13 votes

---
Tags: unity, google-play-services
---


# Question
Title: How to render transparent meshes without sorting?
Let's assume we have some arbitrary triangle manifold meshes which are transparent.

How real guys effectively render it?

Is it possible todo it without sorting faces back to front (e.g. via bsp) and then render it with blending?

# Answer
> 6 votes
Yes, it's possible. The general idea is called order independent transparency (OIT).

OIT often relies on some form of sorting still (you in fact *must* having some form of sorting for certain types of blending!) but pushes the work out into the GPU, perhaps sorting per-pixel rather than per-face.

The more advanced and actually feasible forms of OIT require relatively modern hardware to pull off, though. Features like GPU atomics are required.

There's also techniques like weighted, blended order independent transparency and a few others.

# Answer
> 1 votes
There are also some kinds of transparency which can be done without any sorting at all (even at the per-pixel level)!

In these two cases you still need to draw the transparent items last, but any order will product the same result:

1. Using blend-mode "multiply" -- this would simulate materials that are perfectly transparent but reduce the amount of light which passes through them, like colored glass with no refraction.
2. Using blend-mode "add" -- this doesn't correspond to any actual physical materials, but makes a sort of layered, glowing effect.

---
Tags: graphics, rendering, transparency
---


# Question
Title: How to keep the camera view to within room dimensions
```
    me = self;
    view_yview[0] += ( me.y-(view_hview[0]/2) - view_yview[0]) * 0.1;
    view_xview[0] += ( me.x-(view_wview[0]/2) - view_xview[0]) * 0.3;

```

This is the code I use to smooth camera movement in game maker. But it's going beyond the room dimensions; showing stuff that shouldn't be shown, as the camera should stop following the player at a point.

How do I achieve this?

# Answer
> 1 votes
Try adding:

```
view_xview[0] = round(median(0, room_width - view_wview[0] - 1, view_xview[0]));
view_yview[0] = round(median(0, room_height - view_hview[0] - 1, view_yview[0]));

```

and you need not use `me` and `self`:

```
view_xview[0] += (x - view_wview[0] / 2 - view_xview[0]) * 0.3;
view_yview[0] += (y - view_hview[0] / 2 - view_yview[0]) * 0.1;

```

---
Tags: camera, game-maker
---


# Question
Title: How can I create background images in OpenSceneGraph?
I'm trying my hand at using OpenSceneGraph for graphics in my game. I'm having a hard time trying to figure out how to get a background image up. The relevant piece of code that I have can be found in this gist. Does anyone here have an idea of what I'm doing wrong/missing?

BTW:

1. I know that the image is getting loaded because the logs says so
2. The log says that it managed to add the camera as slave to the viewer

# Answer
> 1 votes
I was able to solve my issue. The second revision of my gist has the solution. In a nutshell, this was what I did:

1. Create a camera
2. Set the view matrix of the camera to identity so that there are no view transforms made to the children
3. Set the projection matrix of the camera to be of an orthogonal matrix with width and height equal to 1
4. Set resize policy on projection matrix to be fixed
5. Set render order to be `NESTED_RENDER` (I previously had this as `PRE_RENDER` and that didn't work. I still have to dig into why).
6. Create a textured quad with width and height of 1 unit
7. Add the textured quad to an instance of `osg::Geode` and add that geode to the camera
8. Extract the first window from the camera. Set the graphics-context and viewport of the camera
9. Add the camera to the scene and you have a background image

I was unable to find a good working code for this simple thing. Luckily I got this working. I hope this helps someone else who's trying to do the same.

**P.S.**: If you want to displace the background image on the screen, think of doing that in relative values; \[0, 1\]. So if you want the background image to be on the top-right of the screen, create the `texturedQuad` like so:

```
auto texturedQuad = osg::createTexturedQuadGeometry(
    osg::Vec3(0.5f, 0.5f, 0.f), // Corner
    osg::Vec3(0.5f, 0.f, 0.f),  // width
    osg::Vec3(0.f, 0.5f, 0.f),  // height
    0.f,
    0.f,
    backgroundImage->s(),
    backgroundImage->t());

```

---
Tags: c++, openscenegraph
---


# Question
Title: How do I organize and sync multiple animated sprites in Unity2D?
I have a human with three parts: legs, body and head, 2D, top down view (GTA 1-2 alike). Head does nothing, legs have walking animation and body has 2 animations: walking animation (moving hands which match with legs animation) and some additional animation. I have 3 `gameObjects` with `SpriteRenderer`, for each part, stored in parent. How do I animate all parts synchronously so that if human walks, then does additional body animation while legs are walking and returns to body walking animation so that if e.g. legs play 5th frame of its animation, body also plays its 5th frame, not 1st. Is it possible and if yes, then how? Also, do I need separate `Animator`s for each body part or only one?

# Answer
I think rather than having separate animations for each body part and then trying to sync the whole animation cycle. Its better to have one single animation for walk cycle where all the parts are moving in sync. And then add additional layers of animation on top of base layer which can override animation on some part of the body ex. waving hands while walking, nodding head etc. You can also use IK to get a specific result depending upon the environment.

Follow these links you will get some idea
> 2 votes

---
Tags: unity, 2d, animation, sprites, pixel-art
---


title: Increase Y position on MouseButtonDown?

text:
# Question
Title: Increase Y position on MouseButtonDown?
How can I increase the altitude of a GameObject as long as `if (Input.GetMouseButtonDown(0))` is activated? "The longer the button is pressed the higher the GameObject goes." **I also want to show the gained altitude.** And when the gained altitude has reached a specfic value, stop the movement. How can I do this?

Here's non-working a pseudo code, so you can understand better:

```
if(Input.GetMouseButtonDown(0))
    {
         smoothly increase y position (lerp maybe?)// transform.position.y + 1?
         Debug.Log(gainedHeight)
         if(gainedHeight == 10)
            {
                 stop movement and stay at reached position //transform.position.y + 0?
            }
   }

```

# Answer
> 2 votes
> "The longer the button is pressed the higher the GameObject goes."

---

**Here is how Input button returns functions:**

**A** = Input.GetMouseButtonDown

**B** = Input.GetMouseButton

**C** = Input.GetMouseButtonUp

1. Frame 1 (**Not pressed yet**): All three are false.
2. Frame 2 (**Pressed**): Only A is true.
3. Frame 3 (**Holding**): Only B is true.
4. Frame 4 (**Relase**): Only C is true.
5. Frame 5 (**After relase**): All three are false.

---

**To sum up:**

You need to use ***GetMouseButton***, not ***GetMouseButtonDown***.

# Answer
> 1 votes
Use `transform.Translate` multiplying the direction by `Time.deltaTime` ensures smoother movement.

```
if(Input.GetMouseButtonDown(0))
    {
       currentHeight=transform.position.y;
       gainedHeight=currentheight-initialHeight;
        if(gainedheight<10)
           transform.Translate(Vector3.up * Time.deltaTime);

   }

```

Edit: added code to measure gainedheight.

```
float initialHeight,currentheight,gainedHeight;

void Start()
{
   initialHeight= transform.position.y;
}

```

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


title: New textblock after click on button

text:
# Question
Title: New textblock after click on button
I have made a box where you can type in your name in unity. After typing your name you can click on the button. Clicking on the button it will copy the string that you typed in within a sentence. so like: "The name" + stringToEdit + "is the name that your parents gave you!" . Now I used debug.log so that the text will show up in the debug. Is there a way to make the button add a text in a specific position in the scene that copies the string plus the sentences after being clicked???

I Used JS script by the way.

# Answer
> 1 votes
using a c# script you would have to call something like this:

```
OnGUI()
{
    //check that the text has been added
    if(text != null)
    {
        //width and height of the text box pop-up
        int width = 60,
            height = 20;
        Vector2 boxPosition = new Vector2((Screen.width / 2) - (width / 2), (Screen.width / 2) - (width / 2)),
            boxSize = new Vector2(width, height);

        //draw the text on scrren
        GUI.Label(new Rect(boxPosition, boxSize), text);
    }
}

```

I've simplified it so that it is easy to read but you could make it way more compact once you have it working

---
Tags: unityscript, text
---


# Question
Title: C++ : Library for creating 3d view picture
I've got a numerical simulation, where I have as an output 3d matrix of billion elements - the visualisation of data is 2d flat image:

When I was starting I was just outputting 2d data to gnuplot, now I generate png file in program itself (to cut generation time). I would like now to get a 3d picture (in flat png) from my billion elements 3d matrix - in isotropic view etc. I found on the Internet things like ImLib3d for image processing, but I am afraid it's not what I am looking for.

# Answer
> 1 votes
I think, the easiest way here is to just learn some more advanced math and render needed isometric image into `.png` pixel by pixel.

Of course, you can learn something like OpenGL for this, but this library can be hard to learn. Also, using it will require more code, you will get your results faster.

---
Tags: c++, data, image-processing
---


title: Scoping my first project

text:
# Question
Title: Scoping my first project
So I'm writing my first game which is a RTS and one of my main ideas for it is multiplayer deception however I'm finding it hard to control the scope of my project. Yes im thinking pretty small but because a key element of the game is multiplayer I'm wondering if its a good idea for a first game I know APIs such as appwarp exist and allow easier multiplayer integration but is this realistic for a first game or is it a better idea to go single player?

# Answer
> 3 votes
RTS's are probably one of the hardest game genres to make because of the huge amount of balancing that has to be done between different units, then on top of that multiplayer adds another layer of complexity...

for example look at GreyGoo an RTS made by a proper development studio, they had the experience to balance the game but because of networking trouble in the early release most of the players left quickly and never looked back.

I'm not saying that it is impossible to do as a first game it is just very unlikely to become anything playable. Your first game will probably be something that nobody will ever play (because you will most likely never release), it will be the project that teaches you the basics.

For a good place to start into looking what your first (few) game(s) will take the form off, look at Extra Credits "Making Your First Game" series (starting here). Watch all 4 the episodes on it and by the end you will have a rough plan on what to do. Hope this helps :)

---
Tags: java, libgdx
---


# Question
Title: Using Content.Load<>() in a class that is not derived from Game
I have a class (`SpriteManager`) that is not derived from `Game` || `DrawableGameComponent` || `GameComponent` so I use my custom methods.

When my game starts, it runs that class. My question is, how to use `Game.Content.Load` in a class that is not derived from any of the classes above.

I tried declaring a variable in my `SpriteManager` of type `Game` but when I use it, it returns `null` or an `InvalidOperationException`.

My variable `Game`:

```
Game game

```

This is my `LoadContent()` method:

```
spriteBatch = new SpriteBatch(GraphicsDevice);

//my player sprite
player = new PlayerMovement(game.Content.Load<Texture2D>(@"Images/collisionPlayer"), game.Content.Load<Texture2D>(@"Images/" + body[0]), new Vector2(150, 150), new Point(20, 35), 0, new Point(0, 0), new Point(0, 0), new Point(1, 11), 2f, 2f, 65f);

```

This is my `SpriteManager` constructor:

```
public SpriteManagerGeneral(GraphicsDevice graphicsDevice)
{
    GraphicsDevice = graphicsDevice;
    LoadContent();

}

```

And this code is in my `Game` class:

```
protected override void LoadContent()
{
    spriteBatch = new SpriteBatch(this.GraphicsDevice);
    spriteManager = new SpriteManager(GraphicsDevice);
}

```

# Answer
If you plan to have a separate content manager in your spritemanager class, you can create one.

```
ContentManager myManager = new ContentManager(Game.Services, Content.RootDirectory);

```

This way you can handle the load and unload of sprites in your own manager. Note how the 2nd parameter is the path to the content directory, so you can have your own dir if you want.

You can pass the content manager in your constructor:

```
protected override void LoadContent()
{
    spriteBatch = new SpriteBatch(this.GraphicsDevice);
    spriteManager = new SpriteManager(GraphicsDevice, Content);
}

```
> 2 votes

# Answer
You have to pass the Game instance to the SpriteManager. For example:

```
class MyGame : Game {
 void LoadContent(ContentManager content){
   ...
   this.spriteManager = new SpriteManager(this);
 }

void Update(...)
void Draw(...)
}

```
> 1 votes

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


# Question
Title: When handling key input, I'm getting a negative timeout value in my thread. What's going on?
So I'm programming a game using Swing and AWT and I'm getting a weird error. As I check for input in my MenuState, which is just my Menu screen, it is telling me that the timeout value in my game loop.

MenuState.java:

```
package GameState;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;

import Handlers.MyInput;
import TileMap.Background;

public class MenuState extends GameState {

    private Background bg;

    private int currentOption = 0;
    private String [] options = {
            "Start",
            "Help",
            "Quit"
    };

    private Color titleColor;
    private Font titleFont;

    private Font font;

    MenuState(GameStateManager gsm) {
        super(gsm);

        try {
            bg = new Background("/Backgrounds/Menu.gif", 1);
            bg.setVector(-0.1, 0);

            titleColor = new Color(128, 0, 0);
            titleFont = new Font("Jokerman", Font.PLAIN, 22);
            font = new Font("Times New Roman", Font.PLAIN, 12);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public void update() {
        bg.update();
        handleInput();
    }

    public void draw(Graphics2D g) {

        bg.draw(g);

        //draw title
        g.setColor(titleColor);
        g.setFont(titleFont);
        g.drawString("Suddenly, Cold Pizza", 55, 70);

        g.setFont(font);
        for(int i = 0; i < options.length; i++) {
            if(i == currentOption) {
                g.setColor(Color.BLACK);
            } else {
                g.setColor(Color.RED);
            }
            g.drawString(options[i], 145, 140 + i * 15);
        }
    }

    public void init() {

    }

    private void select() {
        switch (currentOption) {
        case 0:
            //start
            break;
        case 1:
            //help
            break;
        case 2:
            //close
            System.exit(0);
        }
    }

    public void handleInput() {
        if(MyInput.isPressed(MyInput.BUTTON6)) {
            select();
        } else if(MyInput.isPressed(MyInput.BUTTON2)) {
            if(currentOption > 0) {
                currentOption--;
            }
        } else if(MyInput.isPressed(MyInput.BUTTON4)) {
            if(currentOption < options.length - 1) {
                currentOption++;
            }
        }
    }

}

```

And then the function that contains my game loop:

GamePanel.java:

```
public void run() {
    init();

    long start;
    long elapsed;
    long wait;
    boolean first = true;

    //game loop
    while(isRunning) {

        //start time
        start = System.nanoTime();

        update();
        draw();
        drawToScreen();

        //time elapsed
        elapsed = System.nanoTime() - start;

        //frame wait
        wait = targetTime - elapsed / 1000000;

        if(wait < 0) {
            wait = wait + 20;
        }

        try {
            Thread.sleep(wait);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

```

I'm getting the error in the Thread.sleep(wait). It says I have a negative value for wait, but in debugging, the value never appears to be negative.

If you need any more information, let me know and I'll post it.

# Answer
The simplest solution is to guarantee that wait \>= 0. Instead of adding 20 to it if it's not, why not just set it to 0?

A wait value of -8400 makes sense, on some frame you may take much longer in one of your update functions so elapsed time is much larger than your target time. I don't think it's an error in your calculations.
> 2 votes

---
Tags: java, swing
---


title: Finding vector from a vertex to a plane

text:
# Question
Title: Finding vector from a vertex to a plane
I am trying to implement Dual Contouring, following serveral sources, mainly http://www.sandboxie.com/misc/isosurf/isosurfaces.html but now I want to implement finding the feature point as explained in this post https://gamedev.stackexchange.com/a/83757/49583

It begins with

> The QEF you are minimizing is simply the total distance to each of the planes that are defined by the intersection point/normal pairs for that cell.

I do have the intersection point, which is just the edge vertices averaged by their densities. I got the normal by averaging the normal of the edge vertices. I do it like this :

```
        //calculate normals by gradient of surface, d(x,y,z) = density function, d0 = density at p0, d1 = density at p1
        Vector3 n0 = new Vector3(d((int)(p0.x+1),   (int)p0.y,      (int)p0.z       ).Value - d0,
                                 d((int)p0.x,       (int)(p0.y+1),  (int)p0.z       ).Value - d0,
                                 d((int)p0.x,       (int)p0.y,      (int)(p0.z+1)   ).Value - d0);
        Vector3 n1 = new Vector3(d((int)(p1.x+1),   (int)p1.y,      (int)p1.z       ).Value - d1,
                                 d((int)p1.x,       (int)(p1.y+1),  (int)p1.z       ).Value - d1,
                                 d((int)p1.x,       (int)p1.y,      (int)(p1.z+1)   ).Value - d1);

        this.normal = Vector3.Lerp(n0,n1,m);

```

My plane is this :

```
Vector4 plane = new Vector4(edge.normal.x, edge.normal.y, edge.normal.z, Vector3.Dot(edge.point, edge.normal));

```

And I have a vertex at (x,y,z),

> Basically, you start the vertex in the centre of the cell. Then you average all **the vectors taken from the vertex to each plane** and move the vertex along that resultant...

How do I get the vector from the plane to the vertex?

# Answer
> 4 votes
First of all, your plane representation is wrong. It should be

```
Vector4 plane = new Vector4(edge.normal.x, edge.normal.y, edge.normal.z, -Vector3.Dot(edge.point, edge.normal));

```

since the general representation for a plane is `ax + by + cz + d = 0`.

To get a vector from the plane to the vertex, you'll first have to find the perpendicular signed distance from the plane to the vertex and multiply it by the normal. The formula for this is `n.AB` where n is the normal of the plane and A is a point on the plane and B is the input point. Using the above representation of a plane, this formula becomes `n.B + d`. So in this case the signed distance will be

```
float distance = Vector3.Dot(edge.normal, vertex) + plane.w;

```

To get the *vector* from the plane to the vertex, just multiply the signed distance by the normal:

```
Vector3 planeToVertex = edge.normal * distance;

```

With this formula, the resulting vector will point in the direction of the normal if the point is above the plane and opposite the normal if the point is below the plane.

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


# Question
Title: OpenGL won't interpret attributes correctly when trying to apply textures
I'm going through open.gl tutorials. I'm at the point where I want to apply textures. The tutorial first introduces texture coordinates to the `vertices[]` array, and then adding the corresponding `in`, `out` and `uniform` variables accordingly on each shader. The issue I'm having with is OpenGL cannot interpret the vertex attributes correctly with the given stride and offset parameters when I change the structure of the `vertices[]` array, as seen on the second half of the code below.

```
float vertices[] =
{//   X      Y     R     G     B
    -0.5f, +0.5f, 1.0f, 0.0f, 0.0f, // Top-left
    +0.5f, +0.5f, 0.0f, 1.0f, 0.0f, // Top-right
    +0.5f, -0.5f, 0.0f, 0.0f, 1.0f, // Bottom-right
    -0.5f, -0.5f, 1.0f, 1.0f, 1.0f  // Bottom-left
};

GLuint elements[] = {
    0, 1, 2,
    2, 3, 0
};

GLint posAttrib = glGetAttribLocation(_shaderProgram.program, "position");  // handle to vert shader argument
glEnableVertexAttribArray(posAttrib);
glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE,
    5 * sizeof(float), 0); // how to interpret input array
// position, vec2, type, normalize mode, stride, offset

GLint colAttrib = glGetAttribLocation(_shaderProgram.program, "color");
glEnableVertexAttribArray(colAttrib);
glVertexAttribPointer(colAttrib, 3, GL_FLOAT, GL_FALSE,
    5 * sizeof(float), (void*)(2 * sizeof(float)));

 // Draw call
 glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

```

---

**vert.glsl**

```
#version 150

in vec2 position;
in vec3 color;

out vec3 Color;

uniform mat4 model;
uniform mat4 view;
uniform mat4 proj;

void main()
{
    Color = color;
    gl_Position = proj * view * model * vec4(position, 0.0, 1.0);
}

```

**frag.glsl**

```
#version 150

in vec3 Color;

out vec4 outColor;

uniform sampler2D tex;

void main()
{
    outColor = vec4(Color, 1.0);
}

```

---

However, when I want to introduce texture coordinates in the `vertices[]` array like this, I get weird shapes. OpenGL for some reason cannot interpret the `vertices[]` array correctly.

```
float vertices[] =
{//   X      Y       R     G     B       S     T
    -0.5f, +0.5f,   1.0f, 0.0f, 0.0f,   0.0f, 0.0f      // Top-left
    +0.5f, +0.5f,   0.0f, 1.0f, 0.0f,   1.0f, 0.0f      // Top-right
    +0.5f, -0.5f,   0.0f, 0.0f, 1.0f,   1.0f, 1.0f      // Bottom-right
    -0.5f, -0.5f,   1.0f, 1.0f, 1.0f,   0.0f, 1.0f      // Bottom-left
};

GLuint elements[] = {
    0, 1, 2,
    2, 3, 0
};

GLint posAttrib = glGetAttribLocation(_shaderProgram.program, "position");  // handle to vert shader argument
glEnableVertexAttribArray(posAttrib);
glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE,
    7 * sizeof(float), 0); // how to interpret input array
                // position, vec2, type, normalize mode, stride, offset

GLint colAttrib = glGetAttribLocation(_shaderProgram.program, "color");
glEnableVertexAttribArray(colAttrib);
glVertexAttribPointer(colAttrib, 3, GL_FLOAT, GL_FALSE,
    7 * sizeof(float), (void*)(2 * sizeof(float)));

GLint texAttrib = glGetAttribLocation(_shaderProgram.program, "texcoords");
glEnableVertexAttribArray(texAttrib);
glVertexAttribPointer(texAttrib, 2, GL_FLOAT, GL_FALSE,
    7 * sizeof(float), (void*)(5 * sizeof(float)));

 // Draw call (same as before)
 glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

```

---

**vert.glsl**

```
#version 150

in vec2 position;
in vec3 color;
in vec2 texcoords;

out vec3 Color;
out vec2 TexCoord;

uniform mat4 model;
uniform mat4 view;
uniform mat4 proj;

void main()
{
    Color = color;
    TexCoord = texcoords;

    gl_Position = proj * view * model * vec4(position, 0.0, 1.0);
}

```

**frag.glsl**

```
#version 150

in vec3 Color;
in vec2 TexCoord;

out vec4 outColor;

uniform sampler2D tex;

void main()
{
    // i know the pixel color computation doesn't make sense here, as I also
    // do not provide the texture uniform variable. But I'm aware of the
    // glsl compiler optimizations stripping away unused attributes, so here
    // I use it in a meaningless way so that its not optimized out. I just
    // want to make sure the interpretation of the vertex attributes are
    // correct, so that I can start getting the texture right on the correct geometry.
    outColor = vec4(Color, 1.0) + texture(tex, TexCoord);
}

```

---

From the output I get, I conclude that OpenGL somehow having hard time interpreting the vertex array with the given attribute stride and offset parameters. What causes this - what am I missing - and how do I get this right?

# Answer
As /u/slime73 pointed out, you are missing `,` after your `T` coordinates.

```
float vertices[] =
{//   X      Y       R     G     B       S     T
    -0.5f, +0.5f,   1.0f, 0.0f, 0.0f,   0.0f, 0.0f     // Top-left
    +0.5f, +0.5f,   0.0f, 1.0f, 0.0f,   1.0f, 0.0f      // Top-right
    +0.5f, -0.5f,   0.0f, 0.0f, 1.0f,   1.0f, 1.0f      // Bottom-right
    -0.5f, -0.5f,   1.0f, 1.0f, 1.0f,   0.0f, 1.0f      // Bottom-left
};

```

should be

```
float vertices[] =
{//   X      Y       R     G     B       S     T
    -0.5f, +0.5f,   1.0f, 0.0f, 0.0f,   0.0f, 0.0f,     // Top-left
    +0.5f, +0.5f,   0.0f, 1.0f, 0.0f,   1.0f, 0.0f,     // Top-right
    +0.5f, -0.5f,   0.0f, 0.0f, 1.0f,   1.0f, 1.0f,     // Bottom-right
    -0.5f, -0.5f,   1.0f, 1.0f, 1.0f,   0.0f, 1.0f,     // Bottom-left
};                                           //   ^ commas.

```
> 3 votes

---
Tags: opengl, textures, vertex-attribute
---


title: Construct 2's Scroll-to too small?

text:
# Question
Title: Construct 2's Scroll-to too small?
I'm making a platformer that wants the screen to closely follow the player, and I know I need the Scroll TO behavior.

However, when I tried to make the screen move to the player, I get this:

As seen in the picture, the player's sprite is (I think) too small. Is there any way to increase the 'zoom-ness' of the Scroll-to behavior?

Below is the code's snippet:

Do you know what I have to do, or is there something wrong with my code?

Thanks in advance,

JamieK

# Answer
> 0 votes
The `ScrollTo` behaviour only moves the camera to the centre of your object.
The *Zoom Level* of a layout can be changed via the `Set Layout Scale` `System` parameter.

**Example:**

Image is a screenshot of Camera Zoom Tutorial | "Construct 2"

---
Tags: sprites, platformer, behavior, construct-2
---


title: Refill lives after application exit

text:
# Question
Title: Refill lives after application exit
I try to implement refilling lives functionality after exit application. Every live is refilling after 25 minutes, but unfortunately only if the user is in the game. Here is the sample code:

```
private void ResetOneLive()
    {
        if (currentLives < MAX_LIVES)
        {
            if (!resetLiveTime.HasValue || DateTime.Now < resetLiveTime.Value)
            {
                if (resetLiveTime.HasValue)
                {
                    TimeSpan remaining = resetLiveTime.Value - DateTime.Now;
                    string timerCountdownText = string.Format("{0:D2}:{1:D2}", remaining.Minutes, remaining.Seconds);
                    timeToNextLive.text = timerCountdownText;
                    if (timerCountdownText == "00:00" && resetLive)
                    {
                        this.currentLives += 1;
                        Debug.Log("+1 live");
                        PlayerPrefs.SetInt(PLAYER_PREFS_LIVES, this.currentLives);
                        resetLive = false;
                    }
                }
            }
            else
            {
                //for develop purpose set 10 sec
                resetLiveTime = DateTime.Now.AddSeconds(10);
                resetLive = true;
            }
        }
    }

```

In the game I call this function in `Update()`. I tried to call it `OnApplicationQuit` and `OnApplicationPause` but it does not work.
Can someone tell me how i can implement that functionality?

# Answer
I think you need to do more than what you have already. Did you try:

* When the user exits the game, save the time somewhere.
* When the user restarts, look at the time they exited.
* Based on the difference, refill as many lives as necessary.

You can figure out the number of lives with simple math -- if the user refills a life every 10 minutes, and they were gone 53 minutes, they get five lives back.
> 3 votes

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


title: Apply delta time to physics correctly

text:
# Question
Title: Apply delta time to physics correctly
So I'm trying to create a simple physics engine for the game I'm creating. I'm trying to add jumping to the game. To do this I used (where jumpPower is 30000):

```
impulses.emplace_back(0.0f, mass * World::getGravityForce() + jumpPower, 0.0f);

```

This creates a nice jump effect when using vsync, but when I turn vsync off the jump is low. This is caused by the fact that in lower fps rates, the velocity is less affected by gravity. In the code below, how could I fix this issue? (In a generalized way, so not just using the velocity vector instead)

A possibility could be updating physics at a fixed rate, but I don't know if that is the best solution.

At the moment forces is filled with a downward gravity, applied each frame and impules is filled with a jump force as soon as the player presses Space. No other forces are used and only this code affects force/velocity/acceleration.

```
for (vec3f& f : forces)
    force += f;

for (vec3f& f : impulses)
    force += f;

impulses.clear();

//Add movement forces
velocity += movementVec/mass * delta;

vec3f new_acceleration = force / mass;
velocity += delta * (acceleration + new_acceleration) * 0.5;
acceleration = new_acceleration;

```

# Answer
The best solution was to Use a fixed timestep:

Fix your timestep
> 1 votes

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


# Question
Title: Playing an animation relative to current Transform in unity?
I have an animation created with the built-in dope sheet. It plays correctly but I would like it to be played relative to current object transformation. For example I have a palm tree that moves its leaves. If I rotate the palmtree and then start the animation leaves does not play animation relative to its new position/orientation. I know it is playing this way because of the animation being absolute. Is there any way to make it realtive to current transformation?.

Thanks in advance.

# Answer
The only way to do this is to make an empty gameobject and then put the object you wish to animate inside it, then putting an animator on the new parent.

For example, here you would put the tree and leaves in a parent object, and transform the parent object as needed while the animation plays relative to the parent.
> 15 votes

# Answer
Another way to handle this, which works well if your objects don't move, is to save the position of the object before you start the animation.

Like so:

```
        startPosition = transform.localPosition;
        animation.Play("testAnim");

```

Then during LateUpdate, you jus add that position on top of the position of your object, which effectively shifts it by it's original position. Since htis happens in LateUpdate it happens AFTER the animation offset was applied, maintaining the animation.

Like this:

```
void LateUpdate() {
    transform.localPosition += startPosition;
}

```

Since this offset is static this only works with non-moving objects. Of course you could modify this startPosition to move the object but it get's a bit more roundabout then.

Hope this helps :)
> 8 votes

# Answer
You can also :

* On the animator of the object you want to animate check "Apply root Motion"
* in the inspector of the animation, click "Generate Root motion Curves"

Et voilà :)
> 6 votes

---
Tags: unity, animation
---


title: Get local coords from global coords

text:
# Question
Title: Get local coords from global coords
I need to get local coords from global coords. I did not find ready-made examples.

Please help me how to do it on the example image. Thank you!

## UPDATED:

Here's the method in the java, created thanks to your help! It works for me :) Thank you!

```
public static double[] getLocalFromGlobal(int pointX, int pointY, int localX, int localY, float angle) {
    float px = pointX - localX;
    float py = pointY - localY;

    double cos = Math.cos((Math.PI / 180) * angle);
    double sin = Math.sin((Math.PI / 180) * angle);

    double finalX = (px * cos) + (py * sin);
    double finalY = -(px * sin) + (py * cos);
    return new double[]{finalX, finalY};
}

```

# Answer
> 8 votes
The point P to be transformed is, in homogeneous coordinates:

$$ \begin{pmatrix} 50 \\ 40 \\ 1 \end{pmatrix} $$

The homogeneous transformation matrix M is (using \\$cos(\frac{\pi}{4}\\$) = sin(\\$\frac{\pi}{4}) = 0.7071)\\$:

$$ \begin{pmatrix} 0.7071 &0.7071 &-42.426 \\ -0.7071 &0.7071 &14.142 \\ 0 &0 & 1 \\ \end{pmatrix} $$

noting that \\$(40+20) * 0.7071 = 42.426\\$ and \\$(40-20) * 0.7071 = 14.142\\$ and using the identity proved in my answer here

Applying M to P with matrix multiplication yields

$$ \begin{pmatrix} 35.35 &+ &28.28 &- &42.42 \\ -35.35 &+ &28.28 &+ &14.14 \\ 0 &+ &0 &+ &1 \\ \end{pmatrix}= \begin{pmatrix} 21.21 \\ 7.07 \\ 1 \\ \end{pmatrix} $$

Note that normal vectors, such as for position and velocity, are *contra-variant*; this means that for a transformation T of the basis vectors, the components transform by the inverse transformation, T\*. Only *dual vectors* such as gradient are co-variant, with their components transforming by T.

---
Tags: 2d, mathematics, coordinates
---


# Question
Title: How do you rotate all the objects around the camera?
If I'm correct, the way that you can "look around" in an environment is that you rotate all the objects around the camera. This is the code that I've created using JavaFX 3D. So what's the algorithm?

```
package com.rtek.main;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.Box;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;

public class Walk extends Application {
    private Group root = new Group();
    private PerspectiveCamera camera = new PerspectiveCamera();
    private CameraGroup cameraX = new CameraGroup();
    private CameraGroup cameraY = new CameraGroup();
    private CameraGroup cameraZ = new CameraGroup();
    private static final double CAMERA_INITIAL_DISTANCE = -450;
    private static final double CAMERA_NEAR_CLIP = 0.1;
    private static final double CAMERA_FAR_CLIP = 10000.0;

    public void start(Stage primaryStage) throws Exception {

        Scene scene = new Scene(root, 800, 600, true);

        buildScene();
        buildMouse();

        loadMouse(scene);

        primaryStage.setTitle("Walk Around");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void loadMouse(Scene scene) {
        scene.setOnMouseMoved(event -> {
           ???
        });
    }

    private void buildMouse() {
        root.getChildren().add(cameraX);
        cameraX.getChildren().add(cameraY);
        cameraY.getChildren().add(cameraZ);
        cameraZ.getChildren().add(camera);

        camera.setNearClip(CAMERA_NEAR_CLIP);
        camera.setFarClip(CAMERA_FAR_CLIP);
        camera.setTranslateZ(CAMERA_INITIAL_DISTANCE);
    }

    private void buildScene() {
        PhongMaterial material = new PhongMaterial();
        material.setDiffuseColor(Color.RED);
        material.setDiffuseColor(Color.GREEN);

        Box cube = new Box(100, 100, 100);
        cube.setMaterial(material);

        root.getChildren().add(cube);
    }

    private class CameraGroup extends Group {
        private Rotate x = new Rotate();
        private Rotate y = new Rotate();
        private Rotate z = new Rotate();

        public CameraGroup(){
            x.setAxis(Rotate.X_AXIS);
            y.setAxis(Rotate.Y_AXIS);
            z.setAxis(Rotate.Z_AXIS);

            getTransforms().addAll(x, y, z);
        }
    }
}

```

# Answer
The way to "look around" in a 3d environment is to "rotate your camera".

Your assumption to "move the objects around the camera" probably comes from the fact that when you *render* your scene, the MVP (model-view-projection) matrix stack transforms all your objects.

Human beings like to think in what they figure out. And their world is in 3d, and when they move a camera, they like to think that they actually move the camera.

So 3d engines mimics real world objects, with their "real" positions and orientations. So when you use/program a 3d engine, you have to make the camera as if it were an actual real world camera.

Then under the hood, if your graphics pipeline requires it (like OpenGL) you do the transformation at that level.
> 2 votes

---
Tags: java, 3d, mathematics, algorithm, javafx
---


# Question
Title: Slope polygon collider 2D causing box collider 2D to 'bump' while sliding on it
I'm doing procedural terrain generation. So far I've created the mesh, and attached a 2D polygon collider to it. The terrain is made up of hills going up and down.

After doing so, I put a 2D rigid body, along with a 2D box collider to represent the player. When I put the player on top and let him slide all the way down, sometimes he doesn't slide properly, and instead bumps on the hill, jumping all of a sudden on his own as if he tripped on something (even though there's nothing there). What's weird is that it doesn't happen all the time, just sometimes. Even when I make him slide on the same spot he bumped before again, he wouldn't do it again except on rare occasions.

What could be causing this?

# Answer
> 1 votes
I had similar issue, but my character stopped at some points. After adjusting rigidbody mass and physics material friction, it worked. Maybe it will work in your case.

# Answer
> 0 votes
Try detect the collision and set the vertical velocity to zero.

```
void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.name.StartsWith("block"))
            rigidbody2d.velocity = new Vector2(rigidbody2d.velocity.x, 0);
    }

```

---
Tags: 2d, collision-detection, unity, physics, terrain
---


title: Setting the cursor's location in JavaFX

text:
# Question
Title: Setting the cursor's location in JavaFX
Is there a way to set the cursor's location in JavaFX while the window is in focus? I've searched the possibility of the Scene's cursor object, but that leads to a dead end.

# Answer
> 1 votes
Have you tried the function `mouseMove(int x, int y)` like this:
`new Robot().mouseMove(150, 200);` ?
Source: Robot (Java 2 Platform SE 5.0)

---
Tags: input, javafx
---


# Question
Title: Add them as submodules from Git Shell or remove their .git folders. I tried the latter, but don't know to do the former. How do I do that?
I'm trying to set up version control for my group, but I'm having trouble getting GitHub to work (I'm brand new to it, and version control in general). It keeps saying "Could not commit sub-modules: \[project\] Add them as sub-modules from Git Shell or remove their .git folders to add the as directory's instead." I tried the latter, but not the former (I don't know how to).

If it helps I"m working with Unity, and trying to do it like that. How do I make this work?

# Answer
> 1 votes
Your problem is that you're trying to include a git repository within your git repository. Git has a functionality called submodules that serves this purpose, it basically allows you to specify a remote and a commit for each submodule that git will then clone and checkout for you. I've personally found the submodule feature of git to be rather cryptic and sometimes counter-intuitive, if you can avoid including the other repo in your repo I would go that route.

If not, take a look at this page. Instead of copying the submodule into your repository, you should be calling a `git submodule add <remote>`. Now the submodule will get added to your working directory and be kept track of within the parent repository.

---
Tags: unity, version-control, git
---


title: Version 320 is not supported, SDL C++

text:
# Question
Title: Version 320 is not supported, SDL C++
I have the following four lines before I create the window.

```
SDL_Init(SDL_INIT_VIDEO);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);

```

My shaders are of `#version 320 core` but I get these errors, the first from the vertex shader and the second from the fragment shader.

> ERROR: 0:1: '' : version '320' is not supported ERROR: 0:1: '' : syntax error: #version ERROR: 0:2: '' : #version required and missing. ERROR: 0:4: '0' : syntax error: integers in layouts require GLSL 140 or later
>
> ERROR: 0:1: '' : version '320' is not supported ERROR: 0:1: '' : syntax error: #version ERROR: 0:2: '' : #version required and missing.

I am on OS X El Capitan but this setup worked before with Java.

# Answer
> 4 votes
Wikipedia says that OpenGL 3.2 uses GLSL 1.50.11. Thus, you need to use `#version 150 core`.

https://en.wikipedia.org/wiki/OpenGL\_Shading\_Language

---
Tags: opengl, c++, shaders, sdl, macos
---


title: Smooth GameObject Rotation

text:
# Question
Title: Smooth GameObject Rotation
I want to rotate a 3D GameObject from 0 degrees to 180 degrees on the Z axis ***smoothly*** at a speed that I can define. How can I do this?

# Answer
> 2 votes
An option for your case would be to try an approach similar to the following. Just copy and paste the whole code in a new C# script in Unity and *assign the script to the object you want to rotate.*

Notice that the rotation is triggered by pressing "Space bar", but of course you can change that.

```
using UnityEngine;
using System.Collections;

public class RotationLerping : MonoBehaviour {

    float rot_duration = 500F; //or the amount you find more suitable for the duration of the rotation
    float rot_speed = 0.25F; //or the amount you find more suitable for the rotation speed
    Quaternion final_rot;

    // Use this for initialization
    void Start () {
        Vector3 initial_rot = transform.rotation.eulerAngles;
        final_rot = Quaternion.Euler(new Vector3(initial_rot.x,initial_rot.y,180)); //here you choose the final rotation. Currently it is set to end up with the same X and Y rotation as the initial one, but with Z=180, as requested
    }

    IEnumerator rotateOBJ ()
    {
        float rot_elapsedTime = 0.0F;
        while (rot_elapsedTime  < rot_duration)
        {
            transform.rotation = Quaternion.Slerp(transform.rotation,final_rot,rot_elapsedTime);
            rot_elapsedTime  += Time.deltaTime*rot_speed;
            yield return null;
        }
    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKeyDown("space")) StartCoroutine("rotateOBJ");
    }
}

```

Hope it helps.

# Answer
> 2 votes
This is a pretty basic implementation and should get you on the right path to how you would want to implement in your own project. There are many examples on rotation you can find but this is pretty straight forward.

```
Quaternion rotationMax;
void Start () {
    rotationMax = transform.rotation * Quaternion.AngleAxis(180, transform.forward);
}
void Update () {
    transform.rotation = Quaternion.Slerp(transform.rotation, rotationMax, Time.deltaTime * 2);
}

```

if you are not fond of a slerp then you could also do a Rotate pretty easily like so. you could add a check if you need to make sure it is exactly 180 each completion.

```
float degrees = 180;
float speed = 30;

void Update () {
    if(transform.localEulerAngles.z<degrees)
    transform.Rotate(Vector3.forward, speed * Time.deltaTime);
}

```

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


# Question
Title: Overcoming float limitations for planet-sized worlds in Unity
As far as I know, going further than 1M units from the world origin in Unity is hardly possible due to floating point precision issues.

Making a world more than 1M units in radius would require either using `double` vars for coordinates or utilizing some space division technique to divide a massive scene into hierarchical chunks with the smallest of them being around 10 000 units, i.e. each world-space position would be expressed by the chunk hierarchy the object's in and a bunch of `float` vars representing its local position (and possibly rotation and scaling) inside the last chunk.

Either way, doing this would require implementing a completly new coordinate system, so I'd like to know whether or not that is possible in Unity, and if so, how may I make it work with existing Unity systems like physics and so on.

P.S I can't just move the world into origin as the player moves since I want to have things going on simultaneously around the planet.

Thanks!

# Answer
You're thinking in very static terms.

Just because an object is half a world away doesn't necessitate any issues. **If entity coordinates are stored relative to chunk rather than relative to world, this is trivial to achieve.** Welcome to the way you'd have to do it if you were writing a voxel world in native code.

So let's assume a concept called *locales*. It's a set of chunks that are in close proximity to one another. What matters is the float space internal to a given locale never exceeds the safety limit. You need to determine what your discrete processing locales are, start by taking all chunks that fall within a radius of the position of entity n (could be the player or something else). In my current engine, I make sure that if even one chunk of two different locales is overlapping, that these locales merge into one locale / set of unique chunks. This ensures that you never process all the entities in any single chunk more than once, in a given frame.

Now that you have your locales/chunk-sets, you can perform game logic on them and their contents. And it doesn't matter how *far* they are away from the player or from origin. What matters is that you get a chunk that is roughly central to each set, treat that as the origin i.e. `float` \[0.0,0.0,0.0\], and work your way outward from there. Given typical view range in a game, I guarantee you that you will never need to see more than a few kms, which is very doable with `float`, without serious issues.

Aside from Unity, one option is to write an engine from scratch, I guess, and use something like libfixmath, where you can still use decimal points but because they do not *float*, they will never have these accuracy issues. But I guarantee you will need chunks and locales for other reasons, so it's probably not worth the effort.
> 7 votes

# Answer
That's a question that frequently pops up. I will take the liberty to forward you to another fairly detailed answer I already gave to the same issue, instead of just repeating it here: Is a custom coordinate system possible in Unity

From there, what I would suggest the most is that you read the amazing paper at: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.471.7201&rep=rep1&type=pdf. It compares some of the ways to tackle the problem you describe (including local coordinates, as described by Arcane Engineer in his answer) and go into details about the nowadays famous float-origin solution. Which is, in fact, what I would go for in most cases (in fact, that's what I'm using in my application).

Sure, you mentioned the float origin solution does not suit your needs. But that may not be the case even if you want things to keep happening in very distant parts of the world. You can have pretty much any AI happening wherever you want - you just shouldn't be doing collision checks or precise positioning too far from the player (i.e. beyond the float inaccuracy threshold). But anyway, frankly, in real applications you probably would never be able to have that many collision and positioning in a game due to processing limitations. And still, there might be solutions even to that limitation you see on the float origin solution, depending on the characteristics of your game. Again, I suggest you do not discard that solution before a more thorough reading about it.

Still, if you decide that you should try local coordinate systems (which can become quite a complex solution depending on where you go with it), then the second item in my linked answer is for you. The most important piece there is the paper wrote by the guy who first implemented that solution in the pioneering game Dungeon Siege: http://scottbilas.com/files/2003/gdc\_san\_jose/continuous\_world\_paper.pdf

There is also a video from a couple of years ago, where people from Unity comment on that solution and even explain a modern implementation of the concept in Unity:

https://www.youtube.com/watch?v=VKWvAuTGVrQ

Hope it helps.
> 9 votes

# Answer
Not sure if you have already settled for a solution, but I'd like to mention two other resources that might be useful to you and other readers in the future.

* This recent CppCon talk: "Demystifying Floating Point", which is very relevant regardless of programming language. One very interesting point presented about precision is that the sweet-spot of float accuracy is between the \[-1,+1\] range. So normalized floats are the best way to go if you can use them.
* Another place you might want to look into to get some ideas is in the classic *Dungeon Siege* game. The game used a continuous world system that was node/tile based and every position was relative to the current node. There's very detailed description of the system used by the game in this whitepaper. I also wrote a few paragraphs about it in my blog. This setup was novel at the time, but it is probably not as useful today, the paper linked above mentions a few of the issues they had. Nevertheless, it is interesting from a historic perspective and might still serve you as a source of ideas and inspiration.
> 3 votes

---
Tags: unity, c#, architecture, procedural-generation, coordinates
---


# Question
Title: Move two different objects to two different destinations so they arrive at the same time without using lerp
I might be missing some simple thing but I'm not I am able to wrap my head around this. Normally, if I want to move two objects to different positions so they arrive at the same time I would use a lerp like so:

```
var speed = 2.0f;
var amount = Math.Min(1f, this.elapsedTime * speed);

var obj1NewPosition = Vector2.Lerp(this.obj1Start, this.obj1End, amount);
var obj2NewPosition = Vector2.Lerp(this.obj2Start, this.obj2End, amount);

this.obj1Position = obj1NewPosition;
this.obj2Position = obj2NewPosition;
this.elapsedTime += dt;

```

But I want to do this in a way where I only add to their positions:

```
var speed = 2.0f;

this.obj1Position += obj1Vector * speed * dt;
this.obj2Position += obj2Vector * speed * dt;

// obj1Vector is a normalized vector headed to obj1End
// obj2Vector is a normalized vector headed to obj2End

```

How do I make the second approach work such that each object will arrive at the destination I choose at the same time by only adding to their positions?

I don't have to consider acceleration or deceleration, simply: have two objects arrive at their respective destinations at the same time and then stop.

# Answer
You need something like this?

```
//first get their distances between their destinations. E.g:
var d1 = 150.0f;
var d2 = 200.0f;
var speed1 = 2.0f;

/* Extra part */
//------------------------------------------------------------------
if(d1 == 0 && d2 != 0) d1 = d2;          // To avoid 'divide zero' error.
if(d1 == 0 && d2 == 0) ShutDownYourPC(); // ;) No need to explain
//------------------------------------------------------------------

var speed2 = speed1 * d2/d1;        // This is the important point

this.obj1Position += obj1Vector * speed1 * dt;
this.obj2Position += obj2Vector * speed2 * dt;

```
> 6 votes

---
Tags: c#, movement
---


# Question
Title: How do I deal with collision resolution causing another collision?
I'm making a simple 2D, top-view simulation of an evacuation, sprites running around, looking for exits, going at it, all that good stuff.

I have no control over them when the simulation is running, I just program their behaviour.

I'm using the simulation space provided by JADEX, but I'm just using the simplest of what it provides, so it comes down to Java and OOP.

I already have collision detection working, each person has a radius and I search for objects within that radius, so my question is focused on the aftermath.

Say two people collide and one gets pushed to the ground while the other keeps going. No problem so far, but in the cicle after the collision they will again register a collision - since they are still close enough to each other - and trigger a confrontation.

Is there any general or already known technique to deal with this?

Or should I instead focus on another way of detecting a collision?

EDIT:

The expected cases are, when two people collide:

1. They are both up
2. One is up (D0) and the other one is down (D1).

In case 2, there are two outcomes:

1. D0 helps D1
2. D0 tramples D1

In case 1 there are 3 outcomes:

1. Both are aggressive. Dices are rolled, one keeps going the other one goes down and his physical condition deteriorates.
2. Both are non aggressive. Physical condition is compared, winner keeps going, loser is pushed but not to the ground, physical condition does not suffer.
3. Only one is aggressive. He will always be the winner. Rest as in 1).

As suggested, I will start by having people maintain a list of objects they just collided with and add an extra comparison to that list in the collision detection to filter them and also make sure that when they are no longer colliding to remove them from that list and see how far that takes me.

# Answer
> 3 votes
Usually, (ok, maybe not *usually*, but at least for ODE (Open Dynamics Engine)) the physics engine does 2 different things:

1. *Detect* the collision
2. *React* to the collision

And they are done in two distinct phases, and let the user do something in between. The "something" is generally creating a 'contact joint' between the two bodies so that they physically react one to another.

That is, if you want them to react. If you only want to detect that there has been a collision, you don't add a joint, and the solver does not push them around.

So in your situation, what I'd do:

Frame x:

1. Detect the collision between Dude0 and Dude1.
2. Is Dude0 or Dude1 having his flag `isDownOnTheGround` set?
3. No? Decide who's going down (confrontation) and set the flag `isDownOnTheGround` for the 'losing Dude'.

Frame x + 1:

1. Detect the collision between Dude0 and Dude1.
2. Is Dude0 or Dude1 having his flag `isDownOnTheGround` set?
3. Yes? Go on detecting collisions.

---

Note that another option would be just to remove the 'losing Dude' from the collision detection set.

---
Tags: java, collision-resolution
---


title: How to avoid Walls in A*

text:
# Question
Title: How to avoid Walls in A*
Well I had a problem with the implementation of my A\* algorithm in C# for unity, and I don't realize how to prevent the diagonal movement and the cross walls, I had the next code, the print line's are for debug purposes:

```
public void FindPath(Vector3 startPos, Vector3 targetPos)
{
   List<Transform> openSet = new List<Transform>();
   HashSet<Transform> closedSet = new HashSet<Transform>();
   openSet.Add(begin.GetComponent<Transform>());

   while (openSet.Count > 0)
   {
      Transform currentNode = openSet[0];

      for (int i = 0; i < openSet.Count; i++)
      {
          if (openSet[i].GetComponent<Cell>().fCost < currentNode.GetComponent<Cell>().fCost || openSet[i].GetComponent<Cell>().fCost == currentNode.GetComponent<Cell>().fCost && openSet[i].GetComponent<Cell>().hCost < currentNode.GetComponent<Cell>().hCost)
              currentNode = openSet[i];
          print("Todo bien despues de agregar el actual al set");
      }

      openSet.Remove(currentNode);
      closedSet.Add(currentNode);

      if (currentNode == end) {
          print("LLEGUE AL NODO FINAL");
          RetracePath(begin,end);
          return;
      }

      foreach (Transform neighbour in grid.GetNeighbours(currentNode.GetComponent<Cell>()))
      {
          if (closedSet.Contains(neighbour.GetComponent<Transform>()) || !neighbour.GetComponent<Cell>().IsOpened)
              continue;

          int newMovementCostToNeighbour = currentNode.GetComponent<Cell>().gCost + GetDistance(currentNode, neighbour.GetComponent<Transform>());
          if (newMovementCostToNeighbour < neighbour.GetComponent<Cell>().gCost || !openSet.Contains(neighbour.GetComponent<Transform>()))
          {
              neighbour.GetComponent<Cell>().gCost = newMovementCostToNeighbour;
              neighbour.GetComponent<Cell>().hCost = GetDistance(neighbour.GetComponent<Transform>(), end.GetComponent<Transform>());
              neighbour.parent = currentNode;
              print("Pase hasta definir los costos");

              if (!openSet.Contains(neighbour.GetComponent<Transform>()))
              {
                  openSet.Add(neighbour.GetComponent<Transform>());
                  neighbour.GetComponent<Renderer>().material.color = Color.blue;
              }
          }
      }
   }
}

```

The Getneighbours list is in here:

```
public List<Transform> GetNeighbours(Cell node)
{
    List<Transform> neighbours = new List<Transform>();
    for (int x = -1; x <= 1; x++) {
        for (int y = -1; y <= 1; y++) {
            if (x == -1 && y == -1)
                continue;

            if (x == 0 && y == 0)
                continue;

            if (x == 1 && y == 1)
                continue;

            int checkX =(int)node.Position.x + x;
            int checkY =(int)node.Position.z + y;

            if (checkX >= 0 && checkX < GridSize.x && checkY >= 0 && checkY < GridSize.z)
                neighbours.Add(GridArr[checkX, checkY]);
        }
    }
    return neighbours;
}

```

I use a Prefab and I really don't know to put the restiction of walls to prevent the algorithm pass over them, to destroy the other prefab walls I use a RayCastHit function.

this return the next image:

The problem with this is it cross my walls and I don't know how to avoid that

Any help?

Thanks

# Answer
Add a restriction to the tiles your A\* algorithm is able to consider and this will eliminate the undesired diagonals.

You wish to remove prevent two things from occurring, the first is you do not wish your algorithm to travel through walls and the second is that you do not wish the algorithm to travel along diagonals.

Let us suppose your maze is represented a graph where nodes represent rooms and edges represent a hallway between the rooms. So create a maze with only valid pathways and then allow A\* to process the edges until it reaches the destination node. This works because if a wall exists you do not create a path and if a path would be diagonal you do not create a path.
> 6 votes

# Answer
In your GetNeighbours() function, check if there is a wall between the current node and the neigbouring node. If there is, do not add it to the 'neighbours' list.

I'm not sure what your 'Cell' data structure looks like, or how you connect between the two, but a wall is a barrier between a pair of cells - a cell doesn't have a wall, two cells have a potential wall between them. If you have a 'Cell' reference, how do you figure out the walls that surround it? You have to solve that in order to decide whether to return the neighbour or not. Unfortunately you have not given me enough information to deduce that.
> 4 votes

---
Tags: c#, algorithm, unity, unityscript
---


# Question
Title: multiple contacts for SAT collision detection
I have implemented SAT algorithm for obb-obb intersection and I am able to generate a contact for this collision type. My problem is that SAT only generate ONE contact and in many situation I need more than one contact. For example, If I have a big cube and above it I have a small cube I need two contact (two contacts in 2D and 4 contacts in 3D) one for each bottom vertex of small cube.

My question is how can I generate more than one contacts with SAT?

Thanks.

# Answer
When performing OBB-OBB intersection using SAT, the suggested approach for generating multiple contacts is to find the coincident features and perform clipping - either edge against edge, or face against face, using the sutherland-hodgman clipper, after the SAT returns the intersecting features. This will return one (edge-edge) or more (face/face) contacts.

Dirk Gregorious of Valve covers this really well in his GDC2013 presentation. You can find one here: http://twvideo01.ubm-us.net/o1/vault/gdc2013/slides/822403Gregorius\_Dirk\_TheSeparatingAxisTest.pdf

I would recommend reading his paper, but essentially he suggests the following steps for face-face (his words not mine)

1. Identify the axis of minimum penetration using the SAT (this defines the reference face)
2. Find the most anti-parallel face on the other shape (this defines the incident face)
3. Clip incident face against the side planes of reference face
4. Keep all vertices below reference face

For edge-v-edge he suggests:

"If the axis of minimum penetration is realized by an edge pair compute the closest points between the two edge segments and are done."
> 3 votes

# Answer
An efficient SAT test is "Exit Early" meaning if you're just testing for collision, you see the collision and end the algorithm. Of course for the situation you've presented exiting early is no good; you need more information. I ran into this problem too.

The solution is fairly simple. You need to test ALL axes during your SAT test and not exit when you find one collision. I end up returning a "Collision" object from my SAT test which stores a vector of points where the objects collided. Of course this can turn out to be a big time waster since there may be some collisions where you care about resolution and some where you don't. There may be some cases where you DO want to exit early and others where you don't so keep that in mind.
> 0 votes

---
Tags: collision-detection, physics, physics-engine
---


# Question
Title: Triggering animation in character OnTriggerEnter?
I've been stuck on this for hours.

I have a character whose animations are based in mecanim to transition based on the `bool` variable `ShivaEnter`. One invisible cube is set to change the `bool` value from `false` to `true` and vice-versa `OnTriggerEnter`.

The code is as follows:

```
using UnityEngine;
using System.Collections;

public class PontyAnimations : MonoBehaviour {

  //[SerializeField]
  private Animator animator;
  //private GameObject ponty;
  //private GameObject ponty;

  void Awake () {
    animator = GetComponent <Animator>();
  }

  void OnTriggerEnter (Collider other) {
    if (other.gameObject.tag == "Player") {
      animator.SetBool ("ShivaEnter", true);
    }
  }

  void OnTriggerExit (Collider other) {
    if (other.gameObject.tag == "Player") {
      animator.SetBool ("ShivaEnter", false);
    }
  }
}

```

# Answer
I changed the code as following and edited the transitions to be more sudden! It worked.

```
using UnityEngine;
using System.Collections;

public class boxponty : MonoBehaviour {

  public bool ShivaEnter;
  private GameObject player;
  private Animator anim;
  private AudioClip pontysound;

  // Use this for initialization
  void Start () {
  }

  // Update is called once per frame
  void Update () {
    anim = GetComponent<Animator>();
  }

  void OnTriggerEnter (Collider other){
    anim.SetBool ("ShivaEnter", true);
    GetComponent<AudioSource>().Play();
  }

  void OnTriggerExit (Collider other){
    anim.SetBool ("ShivaEnter", false);
  }
}

```
> 1 votes

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


# Question
Title: Bitmap Font Displays in Center Always Without Coding it Manually (Fix Coordinate Problem onText)
Is there a way on how to stay the texts in center without manually coding it or something, especially when making an update? I'm making a display for the highest score. Let's say that the score is 9. However, if the score is 9,999,999, the text displays still only at the fixed X and Y coordinate. Is there really a way to stay the text in center especially when there is changes when a player beats the new world record?

Here's my code inside Sprite Batch:

```
        font.setScale(1.5f);
        font.draw(batch, "HIGHEST SCORE:", (900/10)*1 + 60, (1280/16)*10);
        font.draw(batch, "" + 9999999 + "", (900/10)*4, (1280/16)*8);

        batch.draw(grid_guide, 0, 0, 900, 1280); // --> For testing purpose only.

        // Where 9999999 is a new record score for example.

```

Here's the image shown as example. I add it some red grid so that I could check if the display of score when updated will always display on center no matter how many digits takes place in. However, it is fixed, so I have to figure it out how to display it automatically on center regardless of the number of digits while updating for the new highscore. I have used the LibGDX preferences very well though to save and load records for the highscore.

# Answer
I don't know about the platform you're using, but there are mostly three ways to center text. Not all of them are available on all platforms, so you should check your platform documents and see which one of these is available.

1. The font rendering system has a flag or option to draw centered text. Look for something like `font.textAlignment`.
2. The font rendering system has a way to measure the size a rendered string will take before you render it. Look for something like `font.measureText`, and subtract half the width of the measurement to the coordinate where you want the text to be centered.
3. Render to an intermediate target, measure the rendered text and copy the rendered data into your canvas. Look for rendering targets, but this is probably the most difficult and hackish solution, so I wouldn't recommend it.

Have you tried googling "libgdx center text" or something like that?

Edit: The first google result leads to your answer.
> 3 votes

# Answer
You could determine the width of the text by the amount of characters of the string, its length, with constant values for the height and width of individual characters. This way, if you have a font in which, at a certain scale, letters have an average of 5 pixels of width, and you have a string of 4 characters (say, "1000"), the width of it would be 20 pixels.

With this in mind, you can determine the X coordenate of the string (assuming its point is at its absolute top-left) with the following formula:

```
    locationToPrint.X = (screenWidth - stringWidth) / 2;

```

All in pixels as the unity.

Of course, because in most fonts characters have variated widths, this is not absolutely precise. But don't worry, it would go unnoticed by your average human eye, so unless you're up to map the width of every character of your font of preference, keep things simple.
> 2 votes

# Answer
I know this question is a bit old, and newer libGDX versions don't even have getBounds anymore, but the font draw method now comes with an horizontal align parameter, so you now just have to use something like:

font.draw(batcher, "my text", 0, y coord, screen witdh, Align.center, false);

The parameter list from the docs is:

draw(Batch batch, java.lang.CharSequence str, float x, float y, float targetWidth, int halign, boolean wrap)
> 1 votes

---
Tags: java, libgdx, fonts, leaderboards
---


title: Network game syncing

text:
# Question
Title: Network game syncing
I'm creating a networked game and I have a huge problem understanding how to keep everything in sync. Right now I have a server and a client and the client can log in and move a character around using the keyboard arrows.

When a arrow key is hit I send data to the server, that then sends that data out to all the clients and then it moves the appropriate character in a specific direction.

However if I keep on hitting arrow keys eventually the result on two different clients will look different and they fall out of sync. So what is the best way to stop this from happening?

I've read that 1 method is to send data back and forth to figure out the latency between each client and then to include that into the movement, is that really the best method around at dealing with this? In which case would anyone be kind enough to explain in more detail how that works exactly?

Thanks

# Answer
> 1 votes
The simple answer is that you should not send key input, but rather their absolute position. This will make sure that the entities are always the exact same place on both your own client, other clients and the server.

To get smooth movement, you might want to consider adding additional client code that smooths it. A technique could be: If your game syncs every 50 ms(20 times a second), and the player moved 1 meter, estimate how much it should move, so that it's at the position at next sync. Heres a picture to describe it:

Ps. This a technique I just made up, so theres probably other techniques that will give you even smoother movement, but this is pretty easy to implement.

# Answer
> 1 votes
Your goal is to have a stable game state across all clients and server. There are many ways to approach this, I will suggest one.

Let us consider a simple case, the position of a single object. Suppose we have 2 clients and 1 server.

Let the server hold the last position each client reported for the object. When the server receives a position update from client 1 it updates the value it has for the object reported by client 1 and then it sends a correction back to client 1 based on the difference from the average of client 1 and client 2. I think this should always converge, but no proof provided. This is a running average play. Recalculation each update isn't cheap but it should result in smoother movement as opposed to giant leaps the next method creates.

In this method the server is an arbiter ensuring that all client have the same state. Let the server retain 1 value for the objects position. The server then updates it's game state and notifies other clients. Periodically the server will request a hash each clients game state to ensure each client has the correct state.

Suppose client 2 has a much slower connection than client 1. Client 1 moves the object left 100m and client 2 moves it right 100m. Client 1 see's the object move left then move right as client 2's changes are applied. Client 2 might not even see the ball move at all as it receives the sum of both changes because it's initial game state is out of sync with the server.

---
Tags: networking
---


title: Rotation Continuity help

text:
# Question
Title: Rotation Continuity help
First the issue im having: Basically its the fact that the angles of a circle aren't continuous, they rise from 0 to 2pi then immediately fall back to 0.

I want to make a game where the player controls a tank and ive got a tank drive working but i want to implement a "Directional Drive" where the player can push a joy stick(XBOX360) in a certain direction and the tank will move forward and turn towards this direction. heres the code i have to do that:

```
if (Math.Abs(controllerCOORD.Y) > Deadzone || Math.Abs(controllerCOORD.X) > Deadzone)
        {
            decimal intended_angle = (decimal)Math.Atan2(controllerCOORD.X, controllerCOORD.Y);

            double correction = (double)Decimal.Round((intended_angle - (decimal)this.BaseAngle_Rad), 1, MidpointRounding.AwayFromZero);

            this.BaseAngle_Rad += (correction / demultiplier_rot);

            this._x_pos += ((float)Math.Sin(this.BaseAngle_Rad) * multiplier_pos); //x component vector of movement
            this._y_pos -= ((float)Math.Cos(this.BaseAngle_Rad) * multiplier_pos); //y component vector of movement
        }

```

Unfortunately with this code, when the player pushed the joystick downwards(0,1), the angle it calculates approches pi from the right side and negative pi from the left side causing it to make a full turn in the wrong direction instead of like a few degrees in the correct direction.

How do i make the rotation continuous all the way around? Ive already found these two questions on here but neither is helping me:

360+ degree rotation skips back to 0 degrees when using Math.Atan2(y, x)

Turning a sprite such that it rotates in the direction that's most efficient

Thanks

# Answer
> 1 votes
I misread one of the links I posted and it turned out to be more helpful than I thought.

The working code sample:

```
if (Math.Abs(controllerCOORD.Y) > Deadzone || Math.Abs(controllerCOORD.X) > Deadzone)
{
    double intended_angle = Math.Atan2(controllerCOORD.X, controllerCOORD.Y);
    double current_angle = this.BaseAngle_Rad % MathHelper.TwoPi;
    double difference = ((intended_angle - current_angle + MathHelper.Pi) % MathHelper.TwoPi) - MathHelper.Pi;
    if (intended_angle > current_angle + MathHelper.Pi)
    {
        intended_angle -= 2 * MathHelper.Pi;
    }
    else if (intended_angle < current_angle - MathHelper.Pi)
    {
        intended_angle += 2 * MathHelper.Pi;
    }
    this.BaseAngle_Rad = MathHelper.Lerp((float)current_angle,
                                         (float)intended_angle,
                                         2.5f * (float)gametime.ElapsedGameTime.TotalSeconds);
    this._x_pos += ((float)Math.Sin(this.BaseAngle_Rad) * multiplier_pos); //x component vector of movement
    this._y_pos -= ((float)Math.Cos(this.BaseAngle_Rad) * multiplier_pos); //y component vector of movement
}

```

---
Tags: c#, xna, rotation, monogame
---


# Question
Title: How do I render Unicode characters that my font doesn't support?
How would I go about rendering all Unicode characters?

Most font files don't include characters like these.

# Answer
My approach is to do the following:

1. Convert your font file to an image
2. Store each character as a VAO (use a loop to store them all - array index = unicode number)
3. Use a sprite batch to draw the text whenever its needed

Below is a snippet of my Java sprite batching code, used to draw the text.

```
public void draw(final String text, final float sx, final float y, final int layer) {
    float x = sx;
    for (final char c : text.toCharArray()) {
        this.draw(CHARACTERS.get(c), x, y, layer);
        x += 7 * this.scale;
    }
}

```

As for the font files not including the characters: if you don't have the characters to draw, you can't draw them, so you'll have trouble finding a sheet with all of these different characters.
> 4 votes

# Answer
If you cannot find a single font containing all glyphs you want, you will have to have multiple fonts.

Some text rasterisation APIs have "font linking" or "font substitution" in which they use more than one font as fallback for missing glyphs. This tends to result in a sub-optimal result in terms of character advances, relative glyph size, and kerning - but it at least shows something that may be recognizable as a glyph.

If you do your own rasterisation of individual glyphs, gather enough fonts with suitable licenses, rank then in order of preference and gather glyphs from them.

You may have to restrict yourself to a subset of character ranges -- do you really *need* every current codepoint in existence in your game?
> 4 votes

---
Tags: fonts
---


# Question
Title: How to deal with inconsistent network delay caused by packets arriving at different times in the frame?
I'm developing a multiplayer game that does not have prediction. It implements client-side interpolation. The problem with this is that input delay can be perceived. I've measured the various times involved in calculating the delay(packet arrival time, server respond time, time spent interpolating), and it seems about 50ms is spent on interpolating(correct), and 60ms is spent on ping and what I can only assume to be unfortunate message arrival time.

The ping is 18ms, which leaves 42ms. If the message arrives at the server immediately after the server has finished reading it's incoming messages this frame, we suffer at least a 16ms delay(at 60fps) that wouldn't be there if the message arrived right before the reading. If this happens with both the server and the client, the delay really adds up, especially at lower frame rates.

How can posts like this http://pastebin.com/ekk07PKn claim to have exactly 50ms delay with 0 ping if this is an issue?

If it's relevant, this is being developed with Unity3d and the Lidgren networking library in C#. I've moved the server snapshot writing to a different thread with a lock around the game world update method. This helped a lot, but from what I understand moving the reading to a different thread won't help in the same way, because the client won't be able to use the new information until the next frame anyway.

# Answer
To be honest, I can't even imagine a single scenario, where with well implemented client interpolation an input lag would be perceivable.

Just to counter check - Client Interpolation summarized

2 Concepts meet up

1) The Interpolation itself - let the client live in the past (ae 100ms)

2) The client sends every data with a timestamp, and the server has to keep the data of all entities for some time (ae 500ms). Now for actions, that depend on other entities, like shooting, the server now can verify the position of the other entities via the timeline and the send timestamp of the client.

With these 2 concepts merged together, you have a working, well implemented client interpolation.

So first of, if your current implementation doesn't meet the mentioned requirements then change it.

If you have both methods working fine, I will need more information to assist you in locating the problem.
> 1 votes

---
Tags: unity, networking
---