title: Load 3D model from external directory

text:
# Question
Title: Load 3D model from external directory
I am developing a desktop application that want to load the 3D model from desktop. Using file explorer user wants to choose the 3d model then it want to show in the application scene.I tried to find the object, the path is detecting but if i tried to Instantiate it on unity it showing this error.

> **ArgumentException: The Object you want to instantiate is null.**

here the code is used

```
public class ReadData : MonoBehaviour {
string path;
GameObject go;
public void OpenExplorer(){
    path = EditorUtility.OpenFilePanel("Overright with model", "", "dae");
    Debug.Log(path);
    GetObj();
}

void GetObj()
{
    if(path!=null)
    {
        UpdateObject();
    }
}

void UpdateObject()
{
    WWW www = new WWW("file:///" + path);
    go = GameObject.Find(path);
    Instantiate(go);
}}

```

Anybody please help me to do this. Thanks in Advance.

# Answer
> 1 votes
`GameObject.Find(path)` searches the currently loaded scenes for an *existing* GameObject with a specific *name*. It does not create a new GameObject using data loaded from a file path.

So, this line would only do something useful if, inside your scene, you had a GameObject named "file://C:/path/to/my/model/file.dae" - then you'd instantiate a copy of that existing scene object, not create a new mesh using the data at that file path on your hard drive.

The more fundamental problem is this: Unity's model loaders are part of the Editor, not part of the runtime. When you build your application, Unity "bakes" its assets into an internal binary format that's convenient for runtime use, so when you start the application it can drop the assets straight into video memory without taking extra time to parse a complicated text or xml-based file format.

So,if you want to load a new model file from a non-pre-digested format at runtime, it's up to you to parse the file's contents and populate an appropriate instance of the `Mesh` class.

Your spawning method would then be a coroutine that looks a bit like this:

```
IEnumerator SpawnMeshFromPath(string path) {

   WWW www = new WWW("file:///" + path);

   // Wait until the file is loaded before trying to read it.
   yield return www;

   // Use some library code to parse the COLLADA XML into Unity data types.
   var colladaData = SomeColladaLibrary.Parse(www.text);
   var colladaMesh = colladaData.GetMesh(0);

   // Populate a new Unity Mesh instance with the data loaded from the file.
   Mesh mesh = new Mesh();
   mesh.vertices = colladaMesh.vertices;
   mesh.uv = colladaMesh.textureCoordinates;
   mesh.triangles = colladaMesh.triangleIndices;

   // Create a GameObject in the scene to use to render this mesh.
   var go = new GameObject("Loaded mesh");
   var filter = go.AddComponent<MeshFilter>();
   var renderer = go.AddComponent<MeshRenderer>();

   // Reference the mesh to render from the MeshFilter component.
   filter.sharedMesh = mesh;
}

```

The tough part is that `SomeColladaLibrary.Parse(www.text)` line - this is a placeholder for whatever you use to do the heavy lifting of reading the XML data structures in the COLLADA file you're opening and digesting them to arrays of `Vector3`s and the like that you can use in Unity.

You may be able to find existing libraries for Unity, or port one from one of the open source COLLADA-reading libraries out there, being mindful of the licence the code has been released under. You can find the complete spec for the file format here if you want to write your own loader routine from scratch, but it will be a significant undertaking, as COLLADA files are very complex and flexible.

---
Tags: unity, c#, streaming-assets
---


title: Prevent tile layout gaps

text:
# Question
Title: Prevent tile layout gaps
I'm making a map viewer where you can specify where tiles go in a map and then see it on the screen, translate it, and zoom in and out.

Here's a picture showing the tiles used to make my example map

Here's the tiles connected together, more or less my desired result.

The problem is that at particular combinations of translations and zoom levels the spacing is off. Here's an example picture of the problem.

In order to arrange the tiles I'm using a Perspective projection matrix parametrized by the zoom level, a camera matrix which just translates the scene based the camera's 2d position, and finally each tile is translated using another matrix derived from its x and y position.

`tile * camera * projection`

How can I avoid this weird spacing issue at particular positions? I'm guessing this is some kind of floating point precision issue, but I'm not sure.

(for those interested, the tiles I'm using are from this collection)

EDIT:

I was using the following parameters for the standard openGL perspective projection matrix:

```
let near = 0.5;
let far = 1024.0;

let scale = zoom * near;
let top = scale;
let bottom = -top;
let right = aspect_ratio * scale;
let left = -right;

```

where `aspect_ratio` is the window width divided by the window height, (in pixels,) and `zoom` in the error case above was set to `8.0`. I read some more on perspective projection and floating point errors but couldn't find anything sensible to change so I resorted to adjusting the parameters. Specifically I tried setting `near` to `1.0` and now I can't replicate the weird spacing. So I guess my problem is solved?

But this is a mysterious and unsatisfying answer, so I would still appreciate it if someone could explain what went wrong, and how I can avoid it in the future without fiddling with numbers until it "magically" works!

EDIT responding to amitp

Here's a screenshot from the same version as above (with `near` still set to 0.5), with the background set to red as suggested. This seems to indicate that it's something wrong with the tile layout, not image bleed.

# Answer
> 1 votes
When using pre-packed tile maps like that. It should be noted that it is best to ensure that the 'zoom' or scaling level is maintained at even integer increments: ie 1x, 2x, 4x, 8x, etc..

When the GPU is asked to divide by numbers that generate floating point numbers (ie: using odd numbers or fractions), the resulting numbers' accuracy can (and will) result in imprecisely positioned textures. Resulting in uneven lines appearing.

A well know workaround is used in texture packing tools suck as TexturePacker: the setting is under Advanced Settings -\> Sprites -\> Extrude.

It is usually only necessary to extrude by 1 pixel, this ensures that when the texturing part of the GPU tries to place the texture at a certain point, that there is some 'buffer pixels' just in case the position needs to be approximated (which is in the case of not using even scaling factors.

So I suggest the following:

1. Use even scaling factors
2. Re-pack the texture with "Extrude" \>= 1px

# Answer
> 0 votes
As recommended in Sebastian's answer, what worked for me was to make sure the sprites in my sprite atlas were all **extruded**. To extrude a sprite you need to add pixels to the left, right, top, and bottom of the sprite by duplicating those pixels already at those edges of the original sprite. You should also add extra corner pixels using the colour of the original sprite corner pixels. This results in an `n+2` by `n+2` pixel sprite, basically whose new edges and corners have been copied from the original sprite's borders and corners.

However, you only record the coordinates of the sprite to include the "centre" `n` by `n` pixels. That way, if the `u-v` coordinates are slightly out then instead of mapping the next sprites's pixels or transparent pixels if you have a gap between sprites, you get the pixels for the sprite you want.

Doing this eliminated the pixel gaps between adjacent tiles. Note that, it is not actually necessary to perform this for all your sprites, just the ones that you know might be adjacent in your game. However, applying to all sprites is probably the quickest route. I found extruding by 1 pixel around the sprite perimeters worked fine.

Secondly, I then observed unwanted "merged" edges between adjacent tiles. On further investigation I found this to be due to the fact I was using `WebP` as the texture format, which is lossy and lossless. Switching back to `PNG` solved this problem.

Now I observe seamless tiles with no weird artefacts whatsoever.

---
Tags: opengl, mathematics, matrix, tilemap, floating-point
---


# Question
Title: How to give individual tiles their own collider in Unity's tilemaps?
My floor tile is a 2D drawing of a 3D platform, for lack of a better description. I want my player character to stand not on the top of the tile but a little inside it, as the red circle does in the picture.

How do I give this tile its own collider that would fit this shape, while letting others have a normal, square one?

# Answer
> 1 votes
For your colliders on your tiles, reduce the offset from the top of the box. So while it will render the whole image, only part of it will detect collision.

Before:

After:

---
Tags: unity, sprites, tilemap, collider
---


# Question
Title: What is the standard C# / Windows Forms game loop?
When writing a game in C# that uses plain-old Windows Forms and some graphics API wrapper like SlimDX or OpenTK, how should the main game loop be structured?

A canonical Windows Forms application has an entry point that looks like

```
public static void Main () {
  Application.Run(new MainForm());
}

```

and while one can accomplish *some* of what is neccessary by hooking the various events of the `Form` class, those events don't provide an obvious place to put the bits of code to perform constant periodic updates to game logic objects or to begin and end a render frame.

What technique should such a game use to achieve something akin to the canonical

```
while(!done) {
  update();
  render();
}

```

game loop, and to do with minimal performance and GC impact?

# Answer
> 50 votes
The `Application.Run` call drives your Windows message pump, which is ultimately what powers all the events you can hook on the `Form` class (and others). To create a game loop in this ecosystem, you want to listen for when the application's message pump is empty, and while it remains empty, do the typical "process input state, update game logic, render the scene" steps of the prototypical game loop.

The `Application.Idle` event fires once every time the application's message queue is emptied and the application is transitioning to an idle state. You can hook the event in the constructor of your main form:

```
class MainForm : Form {
  public MainForm () {
    Application.Idle += HandleApplicationIdle;
  }

  void HandleApplicationIdle (object sender, EventArgs e) {
    //TODO: Implement me.
  }
}

```

Next, you need to be able to determine if the application is *still* idle. The `Idle` event only fires once, when the application *becomes* idle. It does not get fired again until a message gets into the queue and then the queue empties out again. Windows Forms doesn't expose a method to query the state of the message queue, but you can use platform invocation services to delegate the query to a native Win32 function that can answer that question. The import declaration for `PeekMessage` and its supporting types looks like:

```
[StructLayout(LayoutKind.Sequential)]
public struct NativeMessage
{
    public IntPtr Handle;
    public uint Message;
    public IntPtr WParameter;
    public IntPtr LParameter;
    public uint Time;
    public Point Location;
}

[DllImport("user32.dll")]
public static extern int PeekMessage(out NativeMessage message, IntPtr window, uint filterMin, uint filterMax, uint remove);

```

`PeekMessage` basically allows you to look at the next message in the queue; it returns true if one exists, false otherwise. For the purposes of this problem, none of the parameters are particularly relevant: it's only the return value that matters. This allows you to write a function that tells you if the application is still idle (that is, there are still no messages in the queue):

```
bool IsApplicationIdle () {
    NativeMessage result;
    return PeekMessage(out result, IntPtr.Zero, (uint)0, (uint)0, (uint)0) == 0;
}

```

Now you have everything you need to write your complete game loop:

```
class MainForm : Form {
  public MainForm () {
    Application.Idle += HandleApplicationIdle;
  }

  void HandleApplicationIdle (object sender, EventArgs e) {
    while(IsApplicationIdle()) {
      Update();
      Render();
    }
  }

  void Update () {
    // ...
  }

  void Render () {
    // ...
  }

  [StructLayout(LayoutKind.Sequential)]
  public struct NativeMessage
  {
      public IntPtr Handle;
      public uint Message;
      public IntPtr WParameter;
      public IntPtr LParameter;
      public uint Time;
      public Point Location;
  }

  [DllImport("user32.dll")]
  public static extern int PeekMessage(out NativeMessage message, IntPtr window, uint filterMin, uint filterMax, uint remove);
}

```

Furthermore, this approach matches up as close as possible (with minimal reliance on P/Invoke) to the canonical *native* Windows game loop, which looks like:

```
while (!done) {
    if (PeekMessage(&message, window, 0, 0, PM_REMOVE)){
        TranslateMessage(&message);
        DispatchMessage(&message);
    }
    else {
        Update();
        Render();
    }
}

```

# Answer
> 3 votes
I understand that this is an old thread, but I’d like to provide two alternatives to the techniques suggested above. Before I go into them, here are some of the pitfalls with the proposals made so far:

1. `PeekMessage` carries considerable overhead, as do the library methods that call it (SlimDX `IsApplicationIdle`).
2. If you want to employ buffered RawInput, you’ll need to poll the message pump with `PeekMessage` on another thread other than the UI thread, so you don’t want to be calling it twice.
3. `Application.DoEvents` is not designed to be called in a tight loop, GC problems will quickly emerge.
4. When using `Application.Idle` or `PeekMessage`, because you’re only doing work when Idle, your game or application will not run when moving or resizing your window, without code smells.

To work around these (except 2 if you’re going down the RawInput road) you can either:

1. Create a `Threading.Thread` and run your game loop there.
2. Create a `Threading.Tasks.Task` with the `IsLongRunning` flag, and run it there. Microsoft recommends that Tasks be used in place of Threads these days and it’s not hard to see why.

Both of these techniques isolate your graphics API from the UI thread and message pump, as is the recommended approach. The handling of resource/state destruction and recreation during Window resizing is also simplified and is aesthetically much more professional when done (exercising due caution to avoid deadlocks with the message pump) from outside the UI thread.

Do not be afraid of using another thread. I recognise that it's a topic most would prefer to avoid but in this instance, it's easy to employ. By simply using a `Threading.Thread` with the `IsBackground` property set to true, along with something like an "While IsRunning" style loop, you can control the flow of the main loop and gracefully exit when your application concludes.

# Answer
> 2 votes
Agreed with the answer from Josh, just want to add my 5 cents. WinForms default message loop (Application.Run) could be replaced with the following (without p/invoke):

```
[STAThread]
static void Main()
{
    using (Form1 f = new Form1())
    {
        f.Show();
        while (true) // here should be some nice exit condition
        {
            Application.DoEvents(); // default message pump
        }
    }
}

```

Also if you want to inject some code into message pump, then use this:

```
public partial class Form1 : Form
{
    protected override void WndProc(ref Message m)
    {
        // this code is invoked inside default message pump
        base.WndProc(ref m);
    }
}

```

---
Tags: c#, architecture, game-loop, windows-forms
---


# Question
Title: Minecraft Bedrock behaviors: drop items for player/owner?
I'm making a simple behavior pack for Minecraft's Bedrock Edition for my own experimenting - the aim is to get tamed wolves to play fetch. The behavior pack is valid and loading, as it sort of works, but the part that isn't working is what I've been banging my head against for hours.

As per the tutorial on the official wiki, I've copied `entities/wolf.json` and `entities/player.json` from the vanilla behavior pack to my pack and added to them, borrowing cues from the villager's behavior file and referring to the reference for BE's entity components. I've also modified the priorities of the tamed wolf's behaviors so picking up items (i.e. sticks) and sharing them are a higher priority than following the owner or breeding.

wolf.json:

```
{
    "minecraft:entity": {
        "format_version": "1.2.0",
        "component_groups": {
            ...
            "minecraft:wolf_tame": {
                ...
                "minecraft:behavior.pickup_items": {
                    "priority": 7,
                    "max_dist": 16,
                    "speed_multiplier": 1.5,
                    "track_target": true
                },
                "minecraft:inventory": {
                    "inventory_size": 1,
                    "private": true
                },
                "minecraft:shareables": {
                    "items": [
                        {
                            "item": "minecraft:stick",
                            "want_amount": 1,
                            "surplus_amount": 1
                        }
                    ]
                },
                "minecraft:behavior.share_items": {
                    "priority": 6,
                    "max_dist": 16,
                    "speed_multiplier": 2,
                    "goal_radius": 2.0,
                    "entity_types": [
                        {
                            "filters": {
                                "test": "is_owner",
                                "subject": "other"
                            },
                            "must_see": true
                        }
                    ]
                }
                ...
            }
       }
   }
}

```

player.json:

```
{
    "minecraft:entity": {
        "format_version": "1.2.0",
        "components": {
            ...
            "minecraft:shareables": {
                "items": [
                    {
                        "item": "minecraft:stick",
                        "want_amount": 2304,
                        "surplus_amount": 2304
                    }
                ]
            }
        }
    }
}

```

Currently, a tamed wolf will run over to pick up a dropped stick within 16 blocks of it, but after that it simply resumes following me (its owner) and never drops/shares its sticks. I've messed with the `want_amount` and `surplus_amount` of the sticks for both the player and wolf, but with absolutely no results.

# Answer
Try the spawn entity portion. From what I understand (I havent tested it yet myself) you can use that to "spawn" shareable items.

Not an ideal solution, but it may be a workable workaround for you.
> 0 votes

# Answer
Have you tried setting the priority of shareing higher than that of pickup? It might happen where it drops and immediately picks up the stick, due to priorities. It doesn't seem like that is what's happening, but it's worth a shot.
> 0 votes

---
Tags: minecraft-modding, modding, behavior
---


title: Server moving slower than client

text:
# Question
Title: Server moving slower than client
I am implementing a pretty straightforward client/server multiplayer architecture with Socket.IO and am having an issue where my client framerate seems to be faster than the servers. I have both interval loops set at `1000 / 30` yet they quickly diverge, even on my local machine. The code is simple in the example (just increase `position.x` by a constant on each tick), so there is no heavy computation that should slow it down. I expect them to be off but I don't expect this distance to increase over time.

Is this minor tick difference something that's inescapable? I can do server reconciliation but there is snapping every few seconds. This is how it looks without any reconciliation:

*(red is the client, blue is the server)*

I know there is an alternative implementation where I would multiply the constant (which is added to position) by the timestep on each frame, thereby syncing the two. This actually more or less works, but the problem with that approach is that the game logic I am implementing has the players moving on a fixed/precise grid, and when the position updates by long floats this is difficult to enforce.

Any suggestions?

Link to full example code: here.

# Answer
I notice you're using `setInterval` to time your game loop. Javascript's timing functions are imprecise, depends on the browser and prone to drift.

It's best if you use an accumulator in your time step. Accumulate the amount of time elapsed since the last update, and update depending on whether your timestep is fixed or variable. That is:

If your game has a fixed timestep:

```
while(timeSinceLastUpdate > frameDuration) {
    update()
    timeSinceLastUpdate -= frameDuration;
}

```

If your game has a variable timestep:

```
update(timeSinceLastUpdate)

...

player.position.x += PLAYER_SPEED * timeSinceLastUpdate

```

I encourage you to use a good game framework which should have handled this complexity for you. For example, here's Phaser's time step implementation: https://github.com/photonstorm/phaser/blob/master/src/boot/TimeStep.js

With this your server and clients should be more or less synced. But it's good practice to perform server reconciliation anyway, as it minimises the damage misbehaving clients can cause (overloaded client, or cheating).

Here's some useful reading: Fix Your Timestep! on Gaffer On Games
> 1 votes

---
Tags: client-server, node.js, websocket
---


title: Render Stutter - OpenGL or loop timing?

text:
# Question
Title: Render Stutter - OpenGL or loop timing?
For some time now i have no been able to pinpoint the nature of the rendering stutter shown above(by not clearing the screen, not using SwapBuffers and drawing only to the front buffer). See the big spaces between some balls?

---

## UPDATE 2

By putting the FixedUpdate on another thread(which seems like a good idea on it's own) and using Sleep(1) the loop no longer have the random stutters(which means it not longer stutters when using vsync for the loop timing). Now only the batch of stutters that come on a timing are present. They come in roughly 9 second periods and last for something between 2 and 3 seconds.

So the last culprit must be the sleep timing portion of the code. Right now it looks like this:

```
    if(!isVSyncEnabled)
    {
        QueryPerformanceCounter(&sleepStart);

        sleepAccumulator += (updateStep - ((sleepStart.QuadPart - loopNewTime.QuadPart) * 1000.0f
                           / counterFrequency.QuadPart));

        while(sleepAccumulator > 0)
        {
            QueryPerformanceCounter(&sleepStart);

            Sleep(1);

            QueryPerformanceCounter(&sleepEnd);

            sleepAccumulator -= ((sleepEnd.QuadPart - sleepStart.QuadPart) * 1000.0f
                                            / counterFrequency.QuadPart);
        }
    }

```

I tried removing the Sleep, but then instead of 60 the game would lock on 22 fps. Due to the fact that startTime - endTime will give 0 as result since there is no padding in between those. What else can i use as padding for a busy loop?

---

## UPDATE

After some more tests including free movement with a joystick with varying speeds. I managed to gather a more appropriate description of the problem:

**SOLVED \> This is a monitor thing** \- *It seems like i can see the "ghost" of the last frame in the current frame. This becomes more prominent the faster the object moves. Also it does not get captured in screenshots. So this makes me suspect that the problem must be related to the way i'm using (or not using)double buffers/swapping/something of the sort. Maybe even a monitor problem?*

Some big stutters still happen, but i believe that part is related to the game loop.

---

---

---

Here is the game loop:

```
u32 loopOldTime = timeGetTime() * 1000;
u32 loopNewTime = loopOldTime;

u32 loopDuration;

// fixedUpdateFrequency and displayDevices[currentDisplayDevice].frequency are 60 in my tests
u32 loopFixedUpdateStep = (u32)((1000.0f / fixedUpdateFrequency) * 1000);
u32 renderStep = (u32)((1000.0f / displayDevices[currentDisplayDevice].frequency) * 1000);

u32 loopAccumulator = 0;

s32 sleepAccumulator = 0;
u32 sleepStart = 0;

u32 framerateTimeThreshhold = 0;
u8  framerateCount = 0;

deltaTimeFixed = loopFixedUpdateStep  / 1000000.0f;

while(isRunning)
{
    loopOldTime = loopNewTime;
    loopNewTime = timeGetTime() * 1000;

    loopDuration = Min(loopNewTime - loopOldTime, 250000);
    deltaTime = loopDuration / 1000000.0f;

    loopAccumulator += loopDuration;

    if((acceptInputWithoutFocus && canRunWithoutFocus) || isFocused)
    {
        -- Input Stuff --
    }

    while(loopAccumulator >= loopFixedUpdateStep)
    {
        if(canRunWithoutFocus || isFocused)
        {
            -- FixedUpdate Stuff --
        }

        loopAccumulator -= loopFixedUpdateStep;
    }

    timeInterpolation = (r32)loopAccumulator / (r32)loopFixedUpdateStep;

    if(canRunWithoutFocus || isFocused)
    {
        -- Update Stuff --

        -- Render Stuff(calculating vertexes and putting those in place) --

        glClear(OPENGL_CLEAR_BITS);

        glBufferSubData(GL_ARRAY_BUFFER, 0, spriteFactory.verticesSize, spriteFactory.vertices);
        glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, spriteFactory.indicesSize, spriteFactory.indices);

        glDrawElements(GL_TRIANGLES, spriteFactory.spriteLimit * 6, GL_UNSIGNED_SHORT, (void*)0);

        SwapBuffers(deviceContext);

        framerateTimeThreshhold += loopDuration;
        ++framerateCount;

        if(framerateTimeThreshhold >= 1000000)
        {
            framerate = framerateCount;
            framerateCount = 0;
            framerateTimeThreshhold -= 1000000;
        }
    }

    sleepStart = timeGetTime() * 1000;

    sleepAccumulator += (s32)(renderStep - (u32)(sleepStart - loopNewTime));

    if(sleepAccumulator > 0)
    {
        Sleep((u32)(sleepAccumulator / 1000));

        sleepAccumulator -= (timeGetTime() * 1000) - sleepStart;
    }
}

```

Here is the movement code:

```
r32 speed = 500 * deltaTime;

player->sprite->position.x += speed * input->gamepads[0].axisMap[GAMEPAD_LEFT_STICK_X]->normalized;
player->sprite->position.y -= speed * input->gamepads[0].axisMap[GAMEPAD_LEFT_STICK_Y]->normalized;

player->sprite->position.x = Clamp(0, player->sprite->position.x, screenWidth - player->sprite->width);
player->sprite->position.y = Clamp(0, player->sprite->position.y, screenHeight - player->sprite->height);

```

Here is the code for the spinlock test that will be mentioned bellow:

```
while(isRunning)
{
    loopOldTime = loopNewTime;

    if((acceptInputWithoutFocus && canRunWithoutFocus) || isFocused)
    {
        -- Input Stuff --
    }

    if(canRunWithoutFocus || isFocused)
    {
        -- Update Stuff --

        -- Render Stuff(calculating vertexes and putting those in place) --

        glClear(OPENGL_CLEAR_BITS);

        glBufferSubData(GL_ARRAY_BUFFER, 0, spriteFactory.verticesSize, spriteFactory.vertices);
        glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, spriteFactory.indicesSize, spriteFactory.indices);

        glDrawElements(GL_TRIANGLES, spriteFactory.spriteLimit * 6, GL_UNSIGNED_SHORT, (void*)0);

        SwapBuffers(deviceContext);

        framerateTimeThreshhold += loopDuration;
        ++framerateCount;

        if(framerateTimeThreshhold >= 1000000)
        {
            framerate = framerateCount;
            framerateCount = 0;
            framerateTimeThreshhold -= 1000000;
        }
    }

    sleep = true;

    while(sleep)
    {
        loopNewTime = timeGetTime();

        if(loopNewTime - loopOldTime > 15)
        {
            sleep = false;
        }
    }
}

```

Some notes:

* timeBeginPeriod(1) has been invoked beforehand to make the precision of timeGetTime and Sleep(need confirmation) 1ms.
* I'm handling timings in milliseconds.
* Variables types:
    + u \> unsigned int || s \> signed int || r \> float/doable
    + number \> size

I made the following tests:

1. Put the code that is moving the blocks on Update and scaled with deltaTime.
2. Put the code that is moving the blocks on FixedUpdate and use timeInterpolation to the vertexes.
3. Remove the game loop structure and use a simple spinlock as seen above. The fps is of course not locked at 60(63 in the example above).
4. Switched from timeGetTime to QueryPerformanceFrequency/Counter.
5. Switched between glBufferSubData and glMapBufferRange.
6. Tried explicit OpenGL synch with glFinish.
7. Tried no timing at all.
8. Tried VSync on and off along all the previous tests.

Here if what i managed to notice:

* Vsync makes the way stutter less common. But it still happens in all cases except the one that uses no timing at all.
* The stutters are more frequent when running movement code on FixedUpdate with interpolation.
* The stutters happen in periods. After some time of them happening constantly, there will be some that they will not happen at all.
* The stutters seem to coincide with peaks in timeInterpolation. Some of the time, when interpolation reaches 0.9 \>, a stutter happens. And when a period of frequent stutters happen, timeInporlation also peaks frequently.
* While using the spinlock, the stutters happens at a fixed frequency.
* While recording it i noticed that the stutters happen less in the recording(after, not during) but still do happen.

And this is what i have. At every step i find something new that bounces me between the problem being in my OpenGL code or in my loop code, but never conclusive or clear enough for me to figure out what really is the problem. Frustrating, to say the least.

Thanks in advance for any tips or ways of finally finding out the problem.

# Answer
> 1 votes
Calls to `timeBeginPeriod`/`timeEndPeriod` won’t result in a `Sleep()` of 1ms. You will get anything but 1ms and possible values as high as 10-15ms. Also, no need to adjust scheduler timeslice for `timeGetTime` either, the default will give you accurate enough timing.

Your monitor is fine, the ghosting you are seeing is known as temporal aliasing. If you clear the buffer between moves and correctly implement interpolation, this effect can be mitigated.

---
Tags: opengl, game-loop, fixed-timestep
---


# Question
Title: How to implement a pixelated screen transition shader?
I am interested in creating a screen transition seen in a lot of retro games. The transition is just a kind of pixelated distortion that increases or decreases in granularity over time.

The effect is present in Super Mario World, and can be seen recreated in this clip.

Also, here is an image depicting the transition (ignore the gradual lightening of the screen):

I want to achieve this by animating the uniforms of a GLSL shader.

Unfortunately, I don't know how to design the shader.

I know how to sample gradient textures to create various screen wipes, as well as how to sample noise textures to create simple distortion effects. But I can't figure out exactly how to create this effect.

**Any advice on how to set up a shader to achieve this effect?**

# Answer
> 4 votes
You need to make psuedo pixels. The great thing about this effect for this purpose is that it didn't do an average of the pixels, but chose the colir at the top left corner, so you won't have to do a costly averageing shader.

You'll need to pass in the screen size to the shaders (`screenSize`) and the size of the pixels you want (`pixelSize`) and you'll have to have uv/texture coordinates.

So, to make the uv coordinates "pixelated" you'll have to round to the nearest pseudo pixels corners. Basically, multiply by screen size over pixel size, floor and divide by screensize over pixelsize again:

```
vec2 newUV = floor(uv * screenSize / pixelSize) / screenSize * pixelSize;

```

Now just gradually increase pixelSize and use newUV instead of uv

---
Tags: opengl, 2d, shaders, glsl
---


# Question
Title: RawInput -- Getting the system default mouse and keyboard
I'm using RawInput for device management, in a project that I have been working on for some time. It works great, really, but...

After some hardware changes on my development system, including the addition of a second Wacom device, I'm having difficulty getting RawInput to enumerate the default mouse and keyboard input devices without going in and plugging hard values into the enumeration code.

When I call **GetRawInputDeviceList** and sort through the device instances based on their RawInput DeviceType, I have 5 keyboard devices and 6 mice, along with a slew of non-specific HID devices. Usually, the first keyboard device returned is the real default system keyboard -- but not *always*. Adding or removing USB devices between application runs almost always breaks it.

Digging deeper into the enumerated device instances, I thought that examining the RawInputDeviceInformation structure would help. For some devices, especially older input devices, there's a value that allows you to identify which device instance is a real physical device and not one of those phantom/pseudo devices. DeviceInformation structures on keyboard device instances all report a differing number of keys, with all the other significant values -- vendor, usage page, usage, etc. being identical. Unsurprisingly, the reported number of keys doesn't even reflect the actual number of physical keys on the keyboard.

DirectInput identifies the default system mouse and keyboard, and although it's based on RawInput, does it use RawInput to achieve this? Switching away from RawInput is not an option for me because of the other devices I am operating with it (Wacom, Logitech G19 etc). Any advice on how to straighten this out would be gratefully received, with thanks!

# Answer
> 0 votes
I solved this problem finally. To get the default mouse and/or keyboard on systems that have more than one such device installed requires the PageOnly member of RawInputDeviceFlags.

---
Tags: input, windows, directinput
---


# Question
Title: New Unity Post Processing - Default Project '3d With Extras' - What effect is causing this transparency in distant objects?
I've recently seen in Unity you can start a new project with Extras included. Which is basically some post processing to make it look nicer as standard, as well as some assets/materials etc to get you started.

I have started a new project like this. And you can drive a car around a fixed camera. But if the car goes a few metres (well maybe 10-30 metres or so) into the distance there is a sort of grey fog there and it makes much of the cars mesh become more and more transparent the further you go.

It doesnt look nice at all because parts of the car (like the windscreen) can still be seen, whilst the car body is not visible.

My question is, what is this effect called and where do I alter/disable it:

# Answer
Just in case anyone else finds the exact problem I described above. I got the answer from some very helpful guys at the Unity forums.

Its under Windows/Rendering/Lighting:
> 0 votes

---
Tags: unity, post-processing
---


# Question
Title: Why is my spritesheet displaying all messed up in game?
I'm having an issue I don't quite understand, where my spritesheet is looping strangely and not showing the full sprite I want, even though I feel like I'm specifying it correctly. My code is in phaser.js.

Example: https://i.stack.imgur.com/PlD0N.jpg

My code for it is as follows:

```
this.load.spritesheet('dude', 'assets/bunny.png', { frameWidth: 32 , frameHeight: 42 });

    this.anims.create({
        key: 'left',
        frames: this.anims.generateFrameNumbers('dude', {start: 56, end: 64}),
        frameRate: 5,
        repeat: -1
    });

    this.anims.create({
        key: 'turn',
        frames: [{key: 'dude', frame: 4}],
        frameRate: 20
    });

    this.anims.create({
        key: 'right',
        frames: this.anims.generateFrameNumbers('dude', {start: 40, end: 48}),
        frameRate: 5,
        repeat: -1
    });

```

Look fine on the 'turn' frame, but not so fine on movement. For reference, here's the spritesheet I'm attempting to use: https://i.stack.imgur.com/Tn45R.jpg

# Answer
You set your sprite sheet grid to 32x42 `{ frameWidth: 32 , frameHeight: 42 }`

This is how the sprites end up being sliced with the 32x42 grid you specified:

You need to properly line up your sprites within the grid cells.
> 1 votes

# Answer
May I suggest an online tool, which has helped me a lot recently? https://css.spritegen.com/ You import all your seperate sprite images, add the padding you like and it creates a spritesheet and a css file. Though the css file is not needed in phaser, it displays useful information such as sprite width, sprite height, padding.

So finding the frameWidth and frameHeight values becomes very easy!

```
{ frameWidth: sprite width + sprite padding , frameHeight: sprite height + sprite padding }

```
> 0 votes

---
Tags: javascript, sprites, phaser
---


title: Object move along path

text:
# Question
Title: Object move along path
I am making a game where the player gets chased by lava along a road.

From the road mesh i can access the points along each side. Currently i have an edge collider that moves along these points and once it reaches the player it's game over.

My problem is that i can't figure out how to make the lava follow the edge collider. Any ideas? I am using Unity.

# Answer
Depending wether your game is 2D or 3D, there are different ways to go with this problem.

Supposing it is top-down and the lava is a sprite, maybe you can get around this issue by masking your lava with a Sprite mask : \- https://docs.unity3d.com/Manual/class-SpriteMask.html

If you move your mask along with your edge collider, this should do the trick.

If your lava is a 3D object, you can add a cutout shader to it, and manipulate the "cutoff" value and settings to animate it following your edge position.
> 1 votes

# Answer
You could maybe voxelize lava part of the map and form a grid. From there just use dijkstra path finding and turn it into a grid crawler. Every node on the grid is either lava or transparent. Check every frame if nodes occupied by a player are lava. Visualization of dijkstra algorithm.
> 2 votes

---
Tags: unity
---


# Question
Title: How to log how much time a user been playing with game console?
I want to create a solution for game centers which they own different game consoles, is there any way to log each user playing time and gather all of this info into a pc? if yes how is it possible?

# Answer
> 2 votes
Unfortunately, you cannot effectively get this information from the consoles themselves in an automated fashion (with consumer console hardware).

If you require that all users sign in to accounts controlled by your business, you could monitor play time for games yourself by logging in to that account as well. But you're mostly out of luck, here.

---

Given your stated use-case in the comments (a net cafe), I'd argue that time spent *playing a game* isn't what you want anyway: you want to know how much time they're *sitting in the seat*, regardless of whether or not they ever touch the console there.

To that end, I think a lower-tech method of time tracking is probably your best bet.

---
Tags: cross-platform, pc, xbox, playstation4
---


# Question
Title: Use a different language for engine and game
Just a quick question that I haven't been able to find an answer to, I am creating an engine for a game, I have begin making the engine in C++ but I want to make the game in java. My question is, is there a way to maker my game in a different language on a separate "layer"?

# Answer
> 5 votes
Yes, this kind of inter-operation between languages is doable and in fact fairly common. For games, it's typically done as part of implementing a scripting system, which may give some hints as to where to look for further research.

The specific process depending on which languages you'd like to pair together. Almost all languages you're likely to use have some kind of inter-operability mechanism, most of them based on the standardized ABI of C.

For Java in particular, you'd want to look at the JNI (or possibly other community projects like JNA). The JNI will allow you to call functions implemented in C from your Java code, so could implement your "engine functionality" in native code but have your game logic written in Java.

One way to go about this is to declare the existence of the native methods in Java using the `native` keyword, generate a boilerplate header using the `-h` flag of the Java compiler, implement the native functions in that header in C++, compile the result into a shared library, load that library from Java and call the functions.

---
Tags: c++, java
---


title: Weird behavior using TextMeshPro

text:
# Question
Title: Weird behavior using TextMeshPro
I have a very simple scene setup. What I want to do is to create a button prefab composed of a sprite and a TextMeshPro object. When I group the sprite and the text under a GameObject, the pivot of the compound object appears very far from the center of the GameObject (please see the attachment).

I can't move the pivot of the text to the center no matter what I do.

Is this an expected behavior?

# Answer
I think you should've created a Canvas first and then create the icon and label, then make an empty object align it between the two objects(icon & label) then drag it under the empty gameobject.
> 1 votes

---
Tags: unity
---


# Question
Title: Drawing many separate lines using mouse OpenGL(GLFW/glad)
So, in order to draw a line, I track the coordinates of the mouse, then I add them to the array and capture it as GL\_LINE\_STRIP\_ADJACENCY. However, for example, I completed drawing a line1 at P1 and decided to start drawing a different line at P2 as shown in the figure, but my two points P1 and P2 joined together, how to fix it? Need to clear the array after drawing at the point P1, actually it doesn't help if I use glClearColor and glClear(GL\_COLOR\_BUFFER\_BIT).. Is there any other way?

# Answer
> 0 votes
It seems like you're drawing both lines with only one primitive by accumulating vertices frame-by-frame tracked from the mouse position. To fix it, when you're done drawing one line(you release mouse button and press again), you should create another primitive and start accumulating vertices inside it.

---
Tags: opengl, c++, mouse, glfw, lines
---


# Question
Title: Pseudo random number generation in compute shader
Using a C# script in Unity3D to control a HLSL compute shader, I'm trying to generate pseudo random numbers on the gpu. Following along with GPU Gems 3 Hybrid Tausworthe method and another thread Pseudo Random Number Generation on the GPU, I've come across an issue.

### The problem:

the resulting texture appears to be one solid color. If I run the shader multiple times, I get a different solid color texture result every time, but the entire texture is the one color.

### Compute shader code

```
#pragma kernel CSMain

RWTexture2D<float4> result; // 256 resolution texture to write to
uint4 randSeed;  //four uniform random numbers generated in C# script

struct RandomResult
{
    uint4 state;
    float value;
};

uint TausStep(uint z, int S1, int S2, int S3, uint M)
{
    uint b = (((z << S1) ^ z) >> S2);
    return ((z & M) << S3) ^ b;
}
uint LCGStep(uint z, uint A, uint C)
{
    return A * z + C;
}
RandomResult HybridTaus(uint4 state)
{
    state.x = TausStep(state.x, 13, 19, 12, 4294967294);
    state.y = TausStep(state.y, 2, 25, 4, 4294967288);
    state.z = TausStep(state.z, 3, 11, 17, 4294967280);
    state.w = LCGStep(state.w, 1664525, 1013904223);

    RandomResult rand;
    rand.state = state;
    rand.value = 2.3283064365387e-10 * (state.x ^ state.y ^ state.z ^ state.w);

    return rand;
}

[numthreads(8, 8, 1)]
void CSMain(uint3 id)
{
    result[id.xy] = HybridTaus(randSeed).value;
}

```

Do I need to save the state on the gpu? If so, how would I do that? Do I need to deallocate the memory afterwards?

I did try to assign the result of the HybridTaus() function to randSeed in hopes that it would use the new value in the following HybridTaus(randSeed) call, like this:

```
[numthreads(8, 8, 1)]
void CSMain(uint3 id)
{
    RandomResult rand = HybridTaus(randSeed);
    randSeed = rand.state;  // re-assign randSeed with the new state

    result[id.xy] = rand.value;
}

```

but to no avail.

# Answer
> 3 votes
You have to consider that one GPGPU invocation executes all `CSMain` in parallel, conceptually all at the same time.

So every pixel in your texture will come back with the same pseudo-random result as nothing changes in the values fed to the RNG.

Changing the seed value in the computer shader does not work: this is input-only and all `CSMain` **execute in parallel** so they all start with the same value. By the time the seed is changed it's too late. They are not sequentially executed.

To get "random" values in a shader you have to use some math formula and/or lookup texture both depending on the invocation coordinates (`id.xy`)

For example:

```
[numthreads(8, 8, 1)]
void CSMain(uint3 id)
{
    uint4 rs = randSeed;
    rs.x += id.x;
    rs.y += id.y;
    rs.z += (uint)(sin(id.x * 71.01) * 500461564);
    rs.w += (uint)(cos(id.y * 53.7) * 1023467329);
    result[id.xy] = HybridTaus(rs).value;
}

```

Using far fractional bits of sine/cosine can work really well as long as your factors are not a small integer ratio of PI.

# Answer
> 0 votes
First of all in `result[id.xy]` you must return a `float4` (RGBA) and the second values must be between 0 and 1

Also, you will randomly color not every pixel but every part of the pixels that belongs to a certain stream `id.xy`

---
Tags: random, gpu, compute-shader
---


# Question
Title: Unity Rigidbody sitting on top of another Rigidbody does not move with the Rigidbody its sitting on
I have a mesh with a rigid body that moves back and forth like a platform. Other rigidbodies fall onto the upper surface of this cube. The problem I have is that when the platform rigid body moves the other rigid bodies stay in the position they landed in, they do not move with the cube. Everything else physics wise works.

I have tried adding a physicsmaterial to both the platform and the rigidbodies falling onto the platform but this made no difference.

I do no want to tether them to each other because I want them to fall off when they are pushed by other objects.

The platform is moved back and forth using the RigidBody.MovePosition function.

# Answer
> 1 votes
I do not fully understand why but setting iskinematic to true on the platforms rigidbody gives me the behavior I was after.

---
Tags: unity, physics, rigidbody
---


# Question
Title: Problems when rotating object to animate in Unity
I am trying to create some animations for a car model in Unity and I have a problem with the rotation of the wheels

https://i.stack.imgur.com/HD5IB.jpg

Here I can set the rotation properly as the pivot point seems to be at the center like how I want it to be but

https://i.stack.imgur.com/0dRtC.jpg

When I play the animation it rotates on some other pivot point outside of the center of the wheel and even the car

Would you know how to fix this? Sorry if this is a dumb question

Thanks!

# Answer
In this case, the animation contains rotation in x axis. Just rotate the tire without altering the position in each keyframe.  Since object position can be changed with `Transform.Translate` function in its implementation.
> 1 votes

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


# Question
Title: How to allow to slide rectangle to not colliding with corners between two rectagles?
I am detecting each side of collision between two rectangles, and wen I collide them, lets say, with the left side, it also detects collision on the top side when I move to the top, and the downside when I move to the bottom. I think that is because it is detecting also the top/bottom corners.

How I can prevent this corner collision to allow to the player to slide?

Currently, my code is the next one (using xMove (-1 or 1) and yMove (-1 or 1) to know the player movement direction.

```
    if (collider.intersects(mapCollider)) {

            if (direction == Direction.WEST || direction == Direction.EAST) {
                // Right collision
                if (collider.x + collider.width >= mapCollider.x) {
                    isCollisionRight = true;
                }
                // Left collision
                else if (collider.x <= mapCollider.x + mapCollider.width) {
                    isCollisionLeft = true;
                }
            }

            if (direction == Direction.NORTH || direction == Direction.SOUTH) {
                // Top collision
                if (collider.y + collider.height >= mapCollider.y) {
                    isCollisionTop = true;
                }
                // Bottom collision
                else if (collider.y <= mapCollider.y + mapCollider.height) {
                    isCollisionBottom = true;
                }
            }

```

Best regards, Thank you in advance.

# Answer
Your tests for top/bottom collision are only false if `mapCollider.y == playerCollider.y`, i.e. if their tops are exactly aligned. However, this doesn't indicate whether a collision is occurring in that direction, you need to be testing for the edges of your bounding boxes, not just a single point.

For example, for left/right collision, this should be something like:

```
// Right collision
if (
    (playerCollider.x + playerCollider.width) >= mapCollider.x
    && (playerCollider.x + playerCollider.width) <= (mapCollider.x + mapCollider.width))
{
    isCollisionRight = true;
}

// Left collision
if (
    playerCollider.x <= (mapCollider.x + mapCollider.width)
    && playerCollider.x >= mapCollider.x )
{
    isCollisionLeft = true;
}

```

Note that only one of left/right collision should be true at a time, unless the player completely inside the object.

Also, some version of this is very likely what the `intersect` function you are calling is doing, is there a version that returns the intersection you can call? Or otherwise you might want to replace it with your own code.
> 0 votes

---
Tags: java, 2d, collision-detection, collision-resolution
---


# Question
Title: Camera Movement - Snap Camera back to origin in relation to the player object
I am trying to implement camera movement like it is done in Guild Wars 2. Scenario is when A and D keys are pressed, the player rotates right / left and the camera follows and stays behind the character / player like this (Starts at 23 seconds)
https://www.youtube.com/watch?v=XkHJ2uSrLjE

I can get the basic working fine, and I did it this way

```
private void KeysRotateCameraAndPlayer()
{
    float keysOrbitingSpeed = 120;
    this.player = GameObject.FindWithTag("Player").transform;

    if (Input.GetKey(KeyCode.A))
    {
        Debug.Log("Rotate Left");
        CenterPoint.eulerAngles -= new Vector3(0, 360 + Time.deltaTime * keysOrbitingSpeed, 0);
        player.eulerAngles -= new Vector3(0, 360 + Time.deltaTime * keysOrbitingSpeed, 0);

    }
    else if (Input.GetKey(KeyCode.D))
    {
        Debug.Log("Rotate Right");
        CenterPoint.eulerAngles += new Vector3(0, 360 + Time.deltaTime * keysOrbitingSpeed, 0);
        player.eulerAngles += new Vector3(0, 360 + Time.deltaTime * keysOrbitingSpeed, 0);
    }
}

```

Now the next part I am trying to achieve , when the camera is rotated / orbited around the player using the mouse and is left in a position that is not the origin i.e behind the player (in relation to player)… when A and D keys are pressed, what happens in GW2 is the camera seems to snap back to the origin and then continue to follow the player from the back ( or its relation origin with regards to the player Object if that makes sense)

This is what the game does (which I hope to achieve)
https://www.youtube.com/watch?v=qTTDaeuHl80

so at present moment with my current code
https://www.youtube.com/watch?v=a53lZ\_0BDtg
camera and player will continue to rotate (with A and D), from where the camera was last left during orbit. How can I add to this, to force the camera to snap back to origin like they have in Guild Wars 2?

# Answer
```
void Update () {
    Camera.main.transform.position = player.transform.position -  Quaternion.Euler(player.transform.rotation.eulerAngles) * transform.forward * distance;
    Camera.main.transform.rotation = Quaternion.Euler (0, player.transform.rotation.eulerAngles.y, 0);
}

```

It will change the position and rotation and camera to make it stay behind the player. If you need to move the camera smoothly you can use `Vector3.Lerp` for position and `Quaternion.Lerp` for rotation.

```
void Update () {
    desiredPos = player.transform.position - Quaternion.Euler (player.transform.rotation.eulerAngles) * transform.forward * distance;
    desiredRot = Quaternion.Euler (0, player.transform.rotation.eulerAngles.y, 0);
    Camera.main.transform.position = Vector3.Lerp (Camera.main.transform.position, desiredPos, Time.deltaTime*camPosSpeed);
    Camera.main.transform.rotation = Quaternion.Lerp (Camera.main.transform.rotation, desiredRot, Time.deltaTime*camRotSpeed);
}

```
> 1 votes

---
Tags: unity, camera
---


# Question
Title: How do I determine which voxels to test for collision against the player?
I've implemented Minkowski subtraction to test whether (and where) two AABBs collide, independent of framerate/time-step, in my Minecraft-like game.

But since there may be tens of thousands of voxels, I'm realizing I can't just test everyone of them. Is there an alternative to just scanning for nearby voxels? I worry that if I just do collision for voxels within a fixed range, then I've undone the framerate independence that I had sought.

# Answer
This post is a bit old, but it got bumped, so I'll followup with the solution I implemented.

I used the players velocity (multiplied by the framerate) to compute a simple 3D cartesian range of voxels that the player *could* collide with.

When moving diagonally, it tests more voxels than is required (as crudely sketched below):

However, at typical FPS & velocity, only about a dozen voxels are tested per frame (regardless of the size of the world). So I'm quite happy with it.

Seems so obvious now; can't believe I asked, lol.
> 1 votes

# Answer
First of all, minkowski sum is overkill for this, since the blocks are static. Go a bit simpler and use swept AABB.

Secondly if you can, break the world into chunks, then only check blocks inside chunks the player collides with. This reduces the amount of blocks you need to check from hundreds of thousands to a couple thousand (if we assume a chunk size of 10 x 100 x 10, then it' around 90000). Chunks are basically big blocks and if the player doesn't go very fast (very fast in this context means faster, than 1 chunk per frame), then you only need to check the chunk the player is standing in and the 8 neighbouring ones.
> 1 votes

---
Tags: collision-detection, voxels, aabb
---


title: Why are spherical worlds so rare?

text:
# Question
Title: Why are spherical worlds so rare?
I remember back in the 90s when *X-Com* came out, being really impressed by the way its world map was an actual world: a map of Earth drawn on a spherical surface. That was pretty cool, because I had never seen it before. And now, thinking back... I can't recall just off the top of my head ever seeing it again, with the obvious exception of *X-Com: Terror From The Deep*, which used the same engine.

Most games that have an entire-planet world map either use a rectangle that wraps around at the sides but not the top and bottom (a cylinder), or a rectangle that wraps around at all four edges (an impossible geometry that some people call a "torus", even though it can't actually represent a real torus.) And that makes me wonder why.

What difficulties does attempting to build a spherical world map for a video game raise, that it's so incredibly rare to actually see it done?

# Answer
Because spherical maps, compared to rectangular ones, create a lot of additional complexities regarding the technical implementation and the UI design while usually offering very little gameplay advantage.

First, there is the technical problem. With a rectangular map, you just use a 2-dimensional array to represent map positions. But unfortunately there is no proper way to map a 2-dimensional plane to a 3-dimensional sphere. So if you want your world to be tile-based, then that is usually incompatible with a spherical world (unless you are willing to accept some weird artifacts). And even if your game mechanics are not based on tiles: common tasks which are trivial on a plane, like measuring distances, calculating angles or detecting collisions between geometrical shapes, become a lot more complex when you are doing them in a spherical coordinate system.

The science of doing geometry on curved surfaces is called **Non-Euclidean Geometry**. If you want to dive deeper into the mathematical details, then this would be the search term to start your research with. But be warned: It drove various mathematicians crazy for over a millennium.

Then there are the UI problems. There is no good way to show the player the whole globe at once. The player can only see half of the game world at a time, and everything near the edges becomes distorted. Also, globes are difficult to navigate. If you let the player rotate the globe around the world axis', you encounter gimbal lock around the poles, which results in very awkward controls. If you let the player rotate the globe relative to their viewport, then the globe will end up in strange orientations and the player gets disoriented. A plane is usually far more intuitive for the player.

This UI problem is so prevalent that even real-world applications where it is important to remember that the Earth is round still often decide to visualize the Earth as a distorted plane instead. Like NASA mission control software, for example.

But dealing with those complications would be worth it if a spherical game world has a notable advantage over a rectangular one. But there are very few game concepts where the shape of the world would make a big difference.

If you wonder if the game you are designing right now should have a truly spherical map or if a planar map would suffice, ask yourself this: Do you have any game-mechanical reason besides "realism" why you want the map to be a sphere? If you can't think of any important game mechanic which would require a sphere and couldn't work on a plane, then do yourself a favor and don't torture yourself with trying to pull this off.
> 12 votes

---
Tags: game-design, geometry, maps, world-design
---


# Question
Title: Animate Player using Finite State Machine in Ashley ECS
Hi everyone this is my first question on this forum hope you can clarify my doubt. I'm gonna start by saying that im not very good at english so my apologies.

So I have a big school project and I'm developing a Pixel Platformer game using libGDX for it.

I'm using ECS for the most part, but I've been having trouble rendering my player's animations because I can not distinguish the state of the player or at least the attack ones.

## Player State Class

Let me jsut show you, so I have this "move" states:

```
public enum PlayerState implements State<PlayerAgent> {

Idle(){
    @Override
    public void update(PlayerAgent agent) {
        agent.moveOnGround();
        if(!agent.isTouchingGround) {
            if (agent.body.getLinearVelocity().y < -0.05)
                agent.stateMachine.changeState(Falling);
            else
                agent.stateMachine.changeState(Jumping);
        }else{
            if (agent.body.getLinearVelocity().x != 0)
                agent.stateMachine.changeState(Walking);
        }
    }
},

Walking() {
    @Override
    public void update(PlayerAgent agent) {
        agent.moveOnGround();
        if(!agent.isTouchingGround) {
            if (agent.body.getLinearVelocity().y < -0.05)
                agent.stateMachine.changeState(Falling);
            else
                agent.stateMachine.changeState(Jumping);
        }else{
            if (agent.body.getLinearVelocity().x == 0)
                agent.stateMachine.changeState(Idle);
        }
    }
},

Jumping() {
    @Override
    public void enter(PlayerAgent agent) {
    }

    @Override
    public void update(PlayerAgent agent) {
        agent.moveOnAir();
        if (agent.body.getLinearVelocity().y < 0)
            agent.stateMachine.changeState(Falling);
        /* else if (agent.jumpOnAir())
            agent.stateMachine.changeState(DoubleJumping);*/
    }
},

DoubleJumping () {
    @Override
    public void update(PlayerAgent agent) {
        agent.moveOnAir();
        if (agent.body.getLinearVelocity().y < 0)
            agent.stateMachine.changeState(Falling);
    }
},

Falling() {

    @Override
    public void update(PlayerAgent agent) {
        agent.moveOnAir();
        if (agent.isTouchingGround) {
            agent.stateMachine.changeState(Idle);
        } else {
            if (agent.stateMachine.getPreviousState() != DoubleJumping) {
                if (agent.jumpOnAir())
                    agent.stateMachine.changeState(DoubleJumping);
            }
        }
    }
};

@Override
public void enter(PlayerAgent agent) {
    // System.out.println(this.toString());
}

@Override
public void update(PlayerAgent agent) {

}

@Override
public void exit(PlayerAgent agent) {
    agent.timer = 0.0f;
}

@Override
public boolean onMessage(PlayerAgent agent, Telegram telegram) {
    return false;
}
}

```

## Player Animations Enum

But I'll need at least this states for player animation:

```
public enum PlayerAnimations {

 Idle, Walking, Jumping, DoubleJumping, Falling, Attack, JumpAttack, FallingAttack, FallAttack, Hit, Die;

}

```

And many more has u can see on this packed texture: Player Animations Atlas

## PlayerAgent Class:

```
public class PlayerAgent implements Updateable {

    private Entity player;

    protected Body body;
    private TransformComponent transform;
    SensorCollisionComponent sensors;

    protected static StateMachine<PlayerAgent, PlayerState>  stateMachine;

    public boolean isTouchingGround = true;
    public boolean isTouchingWallLeft = false;
    public boolean isTouchingWallRight = false;

    public static float timer = 0.0f;

    public PlayerAgent(Entity player) {
        this.player = player;
        body = player.getComponent(B2dBodyComponent.class).body;
        transform = player.getComponent(TransformComponent.class);
        sensors = player.getComponent(SensorCollisionComponent.class);

        stateMachine = new DefaultStateMachine<PlayerAgent, PlayerState>(this, PlayerState.Idle);
    }

    @Override
    public void update(float deltaTime) {
        isTouchingGround = (sensors.numFoot > 0);
        isTouchingWallLeft = (sensors.numLeftWall > 0);
        isTouchingWallRight = (sensors.numRightWall > 0);

        stateMachine.update();

        if (!KeyboardController.left && !KeyboardController.right)
            body.setLinearVelocity(MathUtils.lerp(body.getLinearVelocity().x, 0, 0.2f), body.getLinearVelocity().y);

    }

    public static PlayerState getCurrentState(){
        return stateMachine.getCurrentState();
    }
    public static PlayerState getLastState(){
        return stateMachine.getPreviousState();
    }
    public static boolean isInState(PlayerState state){
        return stateMachine.isInState(state);
    }

    public boolean moveOnGround() {
        if (KeyboardController.left) {
            body.setLinearVelocity(MathUtils.lerp(body.getLinearVelocity().x, -3f, 0.1f), body.getLinearVelocity().y);
            transform.flipX = true;
        }
        if (KeyboardController.right){
            body.setLinearVelocity(MathUtils.lerp(body.getLinearVelocity().x, 3f, 0.1f), body.getLinearVelocity().y);
            transform.flipX = false;
        }
        if (KeyboardController.up) {
            body.applyLinearImpulse(0, 2.7f, body.getWorldCenter().x, body.getWorldCenter().y, true);
            KeyboardController.up = false;
        }
            return (KeyboardController.left || KeyboardController.right);
    }

    public boolean moveOnAir(){
        if (KeyboardController.left){
            body.setLinearVelocity(MathUtils.lerp(body.getLinearVelocity().x, -1.5f, 0.1f), body.getLinearVelocity().y);
            transform.flipX = true;
        }if (KeyboardController.right){
            transform.flipX = false;
            body.setLinearVelocity(MathUtils.lerp(body.getLinearVelocity().x, 1.5f, 0.1f), body.getLinearVelocity().y);
        }
            return (KeyboardController.left || KeyboardController.right);
    }

    public boolean jumpOnAir(){
        if (KeyboardController.up) {
            body.applyLinearImpulse(0, 2.5f, body.getWorldCenter().x, body.getWorldCenter().y, true);
            KeyboardController.up = false;
            return true;
        }
        return false;
    }

}

```

## Animation Code

Code in the AnimationSystem that takes care of the player:

```
PlayerComponent pc = pm.get(entity);
                if (pc.attacking) {

                    switch (PlayerAgent.getCurrentState()) {
                        case Idle:
                        case Walking:
                            if(PlayerAgent.getLastState() == PlayerState.Falling) {
                                key = PlayerAnimations.FallAttack.ordinal();
                                if(ani.animations.get(key).isAnimationFinished(PlayerAgent.timer)) pc.attacking = false;
                            }else
                                key = PlayerAnimations.Attack.ordinal();
                            break;
                        case Jumping:
                        case DoubleJumping:
                            key = PlayerAnimations.JumpAttack.ordinal();
                            break;
                        case Falling:
                            key = PlayerAnimations.FallingAttack.ordinal();
                            break;
                        default:
                            key = PlayerAnimations.Idle.ordinal();
                            break;
                    }
                } else {
                    switch (PlayerAgent.getCurrentState()) {
                        case Idle:
                            key = PlayerAnimations.Idle.ordinal();
                            break;
                        case Walking:
                            key = PlayerAnimations.Walking.ordinal();
                            break;
                        case Jumping:
                            key = PlayerAnimations.Jumping.ordinal();
                            break;
                        case DoubleJumping:
                            key = PlayerAnimations.DoubleJumping.ordinal();
                            break;
                        case Falling:
                            key = PlayerAnimations.Falling.ordinal();
                            break;
                        default:
                            key = PlayerAnimations.Idle.ordinal();
                            break;
                    }

                }
                PlayerAgent.timer += deltaTime;
            }

```

I was thinking of having states inside a state like Grounded -\> Idle, Walking. But I still dont know how I can make the player AttackStates.

Thanks for replying.

# Answer
> 1 votes
I could be missing something, but it looks to me like you're setting key = the numeric value of the enumeration entry for your current state, then the only place I see it getting used is in looking for the isAnimationFinished() case for Idle/Walking when used to be falling.

I see you've got an accumulator PlayerAgent.timer, that your'e adding deltaTime to...

I don't see all of your code, so hard to say, but I would expect there to be a property on your PlayerComponent, holding the current Animation. You would call getKeyFrame(deltaTime) on that animation, to get the current frame (it keeps it's own time accumulator to select the correct frame, based on the frame delay you set on the animation object when you instantiated it).

By way of example, possibly too long-winded, here's what I have going on in the top-down 2D game I'm working on presently: I use a home-grown ECS, as I didn't know about Ashley back when I started this project. Should be a very similar solution to what you are after though.

I'm switching animations dependent on direction. In my case, I have a "Drawable" component, for any entity that has a visual presentation, and it has a collection of Animations, with standardized keys for "WALK\_NORTH", "WALK\_EAST", "WALK\_SOUTH", and "WALK\_WEST"... as well as a collection of static sprites, similarly named. Code in the moving system sets the appropriate animation or sprite as current for the Drawable component, then the Drawing system calls the currentAnimation.getKeyframe(delta) method (make sure you're not re-setting the currentAnimation if not actually switching animations, since it'll get a new accumulated time, and mess up frame selection if you create a new instance).

Not sure that's of any use to you or not. Good luck!

---
Tags: java, libgdx, animation, entity-component-system, fsm
---


# Question
Title: Why do old platformers typically scroll to the right?
Lots of old platformers are only left-to-right-ish and they don't allow you to move viewport left.

I'm interested was it just a game design choice or it's due to some limitations back then.

I have a lot of possible reasons in my head, but I'm interested in actual one, so please consider reply with citation.

*Not sure I'm in correct community with this question, sorry in advance.*

# Answer
> 3 votes
The answer to this is a synergy of a number of factors. Most people are right handed. Most languages are written from left to right. When placing objects, people typically start to the left and work to the right.

Programmatically, if a game Map was represented using a two dimensional array, logical traversion of said map would require moving to the right.

There are a number of very old (late 70s, early 80s) games that permit both left and right exploration but depending on the title and it’s complexity, memory constraints might play a role.

---
Tags: game-design, platformer, side-scroller
---


title: Unity Anti-Cheat solutions

text:
# Question
Title: Unity Anti-Cheat solutions
I'm currently working for a websites client development team and need guidance on where to go for anti-cheat with unity.

We have scripting, where a user can code in their own features via a editor we have made in lua, with a scripting api that allows them to interact with parts of the game via said scripting, others can exploit this with tools and execute scripts on games that didnt have said scripts, via "hacking". I'm trying to stop script execution exploit(eg scripts being executed that weren't put there by the author) and general hacks such as speedhacks, assembly injection, etc. We have tried the anti-cheat toolkit but it hasn't worked well for us. In terms of execution we have the lua5.2 library in a dll, of course they can hook this library and execute anything via luas execution functions built in, statistcally linking the library would help defend againist this but that is not a option that is easily done in unity, so anyone could just hook it and execute any script/lua they want. we have server-side scripts(executed on server) and client/local-side scripts(executed on client/locally), we've done our best to secure these but we're looking into more ways to help protect us, such as anti-cheat.

We have plans to possible invest into paid anti-cheats in the future such as battleeye, easyanticheat, etc.

we currently don't make a lot of capital and i have no experience making any type of anti-cheat nor anti cheat in unity, where do i start and what do i do?

# Answer
You said you are primarily targeting web browsers as your platform. That means that 3rd party anti cheat tools (ACTs) won't work for you. These tools work by hooking into the users operating system and looking for any suspicious activity. A browser-based application does not have permission to do that, so it won't work.

But even if it would work, ACTs aren't 100% effective. In they end, they too are are just software. And any software which runs on the user's hardware can be manipulated. I have played a lot of multiplayer games where rampant cheating was going on despite there being an ACT. Hackers were able to either hack the ACT itself and disable it or were able to find hacking methods the ACT was unable to detect.

Rule number one for cheat prevention in online games is **never trust the client**. The client is in the hands of the enemy. The player can do what they want with your client and there is nothing you can do about it. That means that **cheat prevention is not the responsibility of the client development team**. It is the responsibility of the team which designs the network protocol and the server backend. They write the code which is not under the control of the end-user.

* Any calculation where cheating gives the player a notable advantage must happen on the server.
* Any information the player must not know about should not be sent to them over the network.
* Any input validation ("Can the player actually attack right now?") must happen on the server. Client-sided input validation for the convenience of the non-cheating player is optional.

If you properly follow these paradigms, then allowing client-sided scripting isn't actually all that risky. The player might try to set the coordinates of their character to somewhere at the other end of the map, but the server won't accept these coordinates and act as if the character is still in its old location. That means your scripting API should not have any functions which "do" stuff. It should only have functions which "request" stuff and allow the player to implement error handling if the server denies the request.

I would argue that adding a scripting engine makes the game even less cheatable, because the one thing you can not prevent with an authoritative server - automation - becomes a legit part of your game design.
> 2 votes

---
Tags: unity, anti-cheat
---


# Question
Title: Unity camera has no preview, and is not moving
I have set up a camera in 2D mode. There is only one camera named "Main Camera", and it is set to "MainCamera" (tag). In console I can see camera's transform position updating, but it isn't moving. And if I adjust field of view for perspective mode, it doesn't take effect.

That is saying, when I hit "Play", the game view is always fixed. In inspector there is no camera preview neither (see image 2).

The only effect I can make to camera is changing the background color.

**EDIT:**

Main camera is placed right at root. And the camera is supposed to be looking at a small area:

**EDIT:**

Thanks for DMGreygory pointing out, I'm using default canvas settings and this won't move with camera in play mode. (btw, if not best under canvas, where exactly is suggested to apply those graphics?)

# Answer
As @DMGregory pointed out in comment, I shouldn't be using default canvas overlay mode. Change that to world space makes camera back to expected behaviour.
> 1 votes

---
Tags: unity, camera
---


# Question
Title: Why do most 2D platformers start off in the left and progress in the right direction?
In almost all 2D platformers I've played, your avatar always starts off on the left side of the world, and continues on to the right. Is there something designers gain by doing this?

# Answer
I'm not sure if there's any technical reason, but a large portion of the world reads from left to right (and many early games were made in the portions that do, i.e. Pitfall!). So starting left and going right may seem more natural. Once enough of the early games did this, it became standard practice.

Additionally, it could be from the roots of design. If these games were first designed with paper and pencils, it would feel more natural to go from left to right, as that's the way the designers were used to writing.

So I suppose by continuing to do this, developers do gain something. Player familiarity.

The likely history behind this would go as follows:

1. Reading/Writing develop a left to right (LR) convention, thanks to the Greeks.
2. The development of hardware is heavily influenced by #1. Display technology included.
3. Software follows hardware. The design of games, influenced by the LR read/write convention and the hardware lead to a LR convention for side scrollers.

In summation, we can give thanks to the Greeks for their contribution to modern gaming.
> 70 votes

# Answer
It might be worth looking at film theory for an explanation. Cinematographers within Europe and the US often work under the assumption that left-to-right movement suggests power, whereas right-to-left movement suggests tension, something to fear, or awkwardness.

Game designers most likely unconsciously adopted the conventions of movement suggested from other media, including print and film. The hero character generally moves left to right, facing enemies and conflict moving counter to that direction; if the hero has to retreat, moving back toward the left is awkward.

It's certainly possible that some consideration was made as to which direction was the most natural, but I know that even preceding the Super Mario era, it was pretty common to see left to right movement as the starting point (Donkey Kong, Pac Man's starting direction, Defender, Parsec, etc).

As for cultural context, one of my college professors in Japanology suggested that Japanese and Chinese film convention actually adopted the opposite convention from what I described above, though I'm not sure I see it in practice. It's possible that Hebrew, Farsi and Arabic films have the opposite convention from the US and Europe, though I'm not sure I've seen enough Arabic language films to notice.

Lazy references (not quite formal reference material, but at least corroborating):
> 38 votes

# Answer
Maybe it is just the natural way to implement it: Assume you start at position x = 0 and since x coordinates of pixels normally increase from left to right on a display the end of a platformers level is on the right side...
> 18 votes

# Answer
The hardware on computers and console machines addressed the screen pixels from left to right. Just like writing or mathematics. Simply look at a graph:

Typically the natural thing to do is to increase the position of a character from 0 to higher positive numbers.
> 10 votes

# Answer
It all derives from the western writing system most people are used to, it reads and write from the left to the right and due to the amount of text nowadays this order is linked in our mind, from sketches, to coordinate systems, to visual flow. After a time it's perceived as natural flow, even though left and right actually plays almost no difference in nature.

This of course finds itself into technology and everything else human made, such as games.
> 5 votes

# Answer
I don't really think so. It's probably just because Super Mario Bros. 1 did it, and everyone followed suit. I have heard somewhere, however, that things to the right look comfortable and thinks to the left and weirder looking. So maybe if everything scrolled to he left it would just be too weird.
> 4 votes

# Answer
I think the convention goes back a lot further than people have alluded to. On a race track where contestants (people, horses, chariots, or whatever) orbit in a counter-clockwise direction, the contestants who are the side of the track nearer to any particular spectator will be moving left to right. Many artworks depicting races thus show contestants racing from left to right. I'm not sure that chariots were raced counter-clockwise 2,000 years ago, but that certainly is the common direction today and I have no particular reason to believe that it has changed over the years.

While I don't know that right-to-left motion suggests "tension", narrative films generally use the left-to-right direction of motion to suggest the first forward progress, and use right-to-left motion to suggest movement in the other physical direction (films will generally avoid reversing the physical directions associated with screen directions unless a shot is included where the the camera crosses the "imaginary line" which establishes the directions).
> 4 votes

# Answer
The obvious answer is that Western people have a left to right and top to bottom reading system, which is learned very early on in our childhood. *Text* is the primary form of how we access stored information, and as such reading plays a paramount role in our lives.

There is also no physical reason why the Cathode Ray Tube (CRT) writes from left to right and top to bottom, other than that this came most natural to the western scientists which developed it.

The same holds true for how **initially console-graphics updated its contents**, and later on other more sophisticated computer graphics contraptions. Additionally, we also learn to read matrices from left to right and from top to bottom, so we design our loops iterating over the elements the same way. Graphics is a lot about linear algebra involving lots of matrices.

The interesting part is that, this **hypothesis** should be **testable**. People from cultures who do not read from left to right and top to bottom,, yet are just as computer savvy, should have **initially slower reaction times** in **platformers** which start off from the left. Indeed I just proposed this to an acquaintance working in neuroscience.

There was an interesting publication on how different cultures scan and recognize images and their contents, measured through iris trackers. (I am not up to date, and this is not my field of expertise, so I am sure there is much more to be discovered on this topic)
> 3 votes

# Answer
Im pretty sure this is a convention that was made implicitly by developers along the years.

Its all about how we learn to think when we are little, while people in oriental countries usually learn to read and write right to left, and are able to think that way for other things, people from the western part of the world are usually tought to think of the concepts from left to right, and only that way everything makes sense.

With games, probably it was just a matter of sticking with one of the ways, for the same reason, for example, that space is the jump key very often, its all about intuition at the end. It would be very hard to individuals to be good players in both settings, or at least as good as they would be if they learnt only one.

That said, if the platformers happened to be in the opposite direction since the beggining , im sure everyone would find it natural.
> 2 votes

# Answer
Early computers came from a number of places, all of which preferred left to right writing.

```
Apple (from the Homebrew Computer Club in California, USA).
Timex Sinclair (from Brittan)
VIC 20 / PET / Commodore 64 (from Canada)
IBM PC, 5150 (from the USA, designer from Boca Raton, Florida)
TRS 80 (from Tandy Computers, Fort Worth, Texas)

```

Other countries did have early computing efforts; however, they typically *started* their efforts by importing a computer and then using it as the basis for their understanding and improvements. For example, the Japanese NEC computer came with a QWERTY keyboard, and used English "Basic" as its primary programming language. China started by importing a computer (to keep up with their Russian counterparts). And the Chinese motto "innovation after imitation" led to mostly adopting left-to-right computing patterns.

By the time that right to left processing became a real player, the chips, graphics cards, memory ordering, disk layout, and other items were firmly entrenched in left to right ordering. It doesn't *have* to be that way, but if you produce a chip set that assumes right to left ordering (or top to bottom ordering) you now effectively design yourself out of the market, as you would need an entire marketplace of like-minded chips to build a computer.

At the software layer, bidi text processing and other technologies emulate non-left to right processing on top of systems that are oriented with left to right assumptions. If you feel very strongly about the screen position, you are free to write a software layer above the graphics positioning like so...

```
void drawPixel(int x, int y) {
  realDrawPixel(screenWidth - x - 1, screenHeight - y - 1);
  // the "extra" minus one is to ensure that pixel 0 is on the screen
}

```
> 2 votes

# Answer
Not all platformers do go left to right, but one reason most do many do may have to do with control orientation. Nearly all controllers have the joystick/d-pad on the left, and other control buttons on the right, and it feels more natural to have one's thumb nearer the middle of the controller then to have it hanging off the edge. The only real counterexample I can think of is the N64 controller, which had the joystick in the middle. But even that had its d-pad on the left, and by the time more symmetrical controllers came into use, it was already an ingrained habit.

Note that there are some games that go right-to-left, for example, Final Fantasy has had the players on the right in battles for a long time (although FF has never been a platformer).

Nearly all right-to-left platform levels have been ones based on either sneaking/infiltration or returning from wherever you went in previous left-to-right levels.
> 2 votes

# Answer
It is likely because the world zone taught to think left-to-right (the direction of writing), the Western world, has "colonized" of sorts practically everywhere in the world. Even lands of right-to-left writing systems are at least *very* aware of our left-to-right culture, if not catering to it. That said, not all games are strictly left-to-right. I don't know if I agree much with the answers above saying that it is more comfortable to press movement left-to-right the way our controllers are set up. At least to ***me*** it could work either way, right or left.

Metroid has its share of going right-to-left: Not only is the first and easiest-to-get item left of the start, but reaching the final boss is a right-to-left journey, all the way to the escape! The retold story Zero Mission "corrects" this by adding more to the story with one more final boss, the second escape being left-to-right.

Metroid II (Return of Samus) and Super Metroid both have their final bosses to the left on the map, but that means their escapes are left-to-right. That is, from the boss close to the map's far-left, to the gunship closer to the middle. In Super Metroid, the gunship is still noticeably far left of center.

The Mega Man Zero series is as much left-to-right as any other series, but it has its many exceptions. The first Zero game has its right-left-right missions in the desert (Find Shuttle) and Underground Lab (Retrieve Data). All other desert missions are purely right-to-left, starting in the desert by the Resistance Base and ending either in the desert far left or in the ocean cave with the hidden base. The mission to save the Resistance Base from being bulldozed is another right-to-left. In Zero 2's boss fight in the second-to-final stage, Zero is being chased right-to-left.
> 0 votes

# Answer
Psychologist Dr. Peter Walker of Lancaster University speculates that there is an innate bias in our preference to see moving things depicted in a way that follows the left to right convention. Here's an excerpt taken from the abstract of his paper Depicting Visual Motion in Still Images: Forward Leaning and a Left to Right Bias for Lateral Movement published in the journal Perception (bold text indicates my own emphasis):

> Inspection of the availability of italic fonts in Hebrew indicates an additional artistic convention for conveying motion, based on a fundamental bias, yet to be confirmed, for **people to expect to see**, or prefer to see, **lateral movement (real or implied) in a left to right direction, rather than a right to left direction**. Evidence for such a bias is found in photographs of a range of animate and inanimate items archived on Google Images. Whereas a rightward bias is found for photographs of animate and inanimate items in motion (the more so, the faster the motion being conveyed), either no bias or a leftward bias is found for the same items in static pose. Possible origins of a fundamental left to right bias for visual motion, and future lines of research able to evaluate them, are identified.
> 0 votes

---
Tags: game-design
---


title: HLSL float bitfield

text:
# Question
Title: HLSL float bitfield
In HLSL I want to store a bitfield for each color in a texture. Specifically spanning 3 floats (RGB, not alpha).

Since each float has to be between 0 and 1 I can only use the significand/mantissa of each float (last 23 bits) which should give me 23\*3 = 69 values for my bitfield.

How can I set and get specific bits? (without bitwise operators, obviously, since these are floats)

Remember to take floating point precision errors into consideration.

# Answer
> 1 votes
Figured it out. The trick is you can clamp an integer between 0 and 1 by dividing 1 by it, to "unpack" it you divide 1 by the result and the way that floats work I think you could technically use all 32 bits in the 0-1 range. The problem is precision. If you're using Shader Model 4.0 you can use bitwise operators for the integer bitfield, otherwise, you can do this:

Read a bit from float:

```
fmod(1.0 / num, pow(2, bit + 1)) >= pow(2, bit);

```

Set bit that is 0 to 1 (when I set a bit to 1 I know it's 0 if that's not the case you could always read the bit to check first):

```
num = 1.0 / (round(1.0 / num) + pow(2, bit))

```

You can store a bitfield of 23 bits in a float with this method, but beyond 23 bits the precision is too bad for the round function to handle.

For RGB this gives you a bit field of 23\*3 = 69 bits. You can access RGB component by integer division:

```
rgba[bit / 23]

```

Get bit in RGB component with modulus:

```
fmod(bit, 23)

```

---
Tags: shaders, hlsl, floating-point
---


title: Why won't InvokeRepeating work for me?

text:
# Question
Title: Why won't InvokeRepeating work for me?
I am designing an FPS game and scripted this shooting enemy that is supposed to shoot at the player if he is in the trigger zone once every second, but it just rapid fires and `InvokeRepeating` doesn't seem to do anything. No errors or anything. I am new to programming so it is most likely a rookie mistake. So here is the code

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

public class EnemyAI2 : MonoBehaviour
{
    public float fireRate = 10f;
    public float CanShoot;
    public float forceadded;
    public Transform BulletSpawn;
    public Transform PlayerTransform;
    GameObject player;
    NavMeshAgent enemy;
    public GameObject bulletclone;

    // Use this for initialization
    void Start()
    {
        player = GameObject.FindGameObjectWithTag("Player");
        enemy = GetComponent<NavMeshAgent>();
        {
            InvokeRepeating("OnTriggerStay", 1.0f, 1.0f);
        }
    }

    // Update is called once per frame
    void Update()
    {
        Vector3 direction = PlayerTransform.position - this.transform.position;
        enemy.destination = player.transform.position;

    }

    void OnTriggerStay(Collider other)
    {
        if(other.gameObject.tag == ("Player"))
        {
            gameObject.GetComponent<NavMeshAgent>().enabled = false;
            {
                Vector3 direction = PlayerTransform.position - this.transform.position;
                {
                    var Bullet = (GameObject)Instantiate(bulletclone, BulletSpawn.position, BulletSpawn.rotation);
                    Bullet.GetComponent<Rigidbody>().velocity = Bullet.transform.forward * forceadded;
                    Destroy(Bullet, 1.0f);

                }

            }
        }
        else
        {
            gameObject.GetComponent<NavMeshAgent>().enabled = true;
            enemy.destination = player.transform.position;
            Vector3 direction = PlayerTransform.position - this.transform.position;
        }
    }
}

```

# Answer
I think you're trying to do a lot of treatments in the OnTriggerStay function.

You should try to create a variable that checks if the player is on sight or not, something like this:

```
void Update()
{
  if (playerOnSight == true && Time.time > lastTimeFired)
  {
    gameObject.GetComponent<NavMeshAgent>().enabled = false;
    var Bullet = (GameObject)Instantiate(bulletclone, BulletSpawn.position, BulletSpawn.rotation);
    Bullet.GetComponent<Rigidbody>().velocity = Bullet.transform.forward * forceadded;
    Destroy(Bullet, 1.0f);
    lastTimeFired = Time.time + 1.0f;
  }
if(playerOnSight == false)
{
          gameObject.GetComponent<NavMeshAgent>().enabled = true;
        enemy.destination = player.transform.position;
        Vector3 direction = PlayerTransform.position - this.transform.position;
}
}
void OnTriggerStay(collider other)
{
  if (other.gameobject.tag == "Player")
    {
      playerOnSight = true;
    }
}
void OnTriggerExit(collider other)
{
  if (other.gameobject.tag == "Player")
    {
      playerOnSight = false;
    }
}

```

Note that I haven't tested this code.
> 0 votes

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


# Question
Title: Prevent rendering queue from overflowing when using Vsync
My game loop currently looks something like this:

```
while (!quit) {
    takeInput(); // Input is sampled however fast loop can run

    time_now = get_time()
    time_passed += (time_now - time_prev);
    time_prev = time_now;

    while (time_passed > SOME_TIME) {
        update(); // Update is done over fixed time-step for determinism
        time_passed -= SOME_TIME_STEP; // This time step is less than or equal to SOME_TIME
    }
    render(time_passed); // Render using interpolation from previously updated position and velocity
}

```

Basically, I take input as fast as I can, run the movement and physics only in discreet chunks of time after certain period and interpolate the difference in the renderer. The renderer is set to draw at Vsync (using `SDL_GL_SetSwapInterval(-1)`) and currently, the value of SOME\_TIME is set so that `update()` runs at half of display's refresh frequency (but with a minimum bound of SOME\_TIME\_STEP which is set to 5 millisecond).

The problem is that I am running the renderer as fast as I can which is submitting frames continuously. Because I am currently loading a test level, the game loop is basically finishing up in a few microseconds (unless there is something wrong with how I am calculating time too). As far as I understand, my program will submit frames to the driver way faster than it is going to draw (because of Vsync) and this should lead to some type of periodic locking up/lagging.

So my question is, how to I prevent this? Should I put the render call in a time bound loop too just like `update()`? Should I call `sleep()` manually instead of relying on graphics driver for Vsync?

# Answer
> 1 votes
> As far as I understand, my program will submit frames to the driver way faster than it is going to draw (because of Vsync) and this should lead to some type of periodic locking up/lagging.

Not it wont. The video driver doesn't buffer frames indefinitely.

The video driver buffers at most 1 frame (double buffering) or 2 frames (triple buffering).

If your render loop attempts to draw faster than the display the video driver can display it will sleep/hold your thread until the vblank happens and a render back buffer becomes available.

Which is at most 1 frame time (eg: 16ms at 60Hz).

You don't need to put your thread to sleep, the video driver takes care of that.

If you put your thread to sleep manually the video driver can't force the OS to wake up your thread when the vertical blank signal happens because it doesn't know that's what you're waiting for. That could cause your app to sleep for easily 10ms longer than it should.

# Answer
> 0 votes
In SDL2 is standard practice as far as I know to use an `SDL_Delay` to delay the game loop after you've completed all rendering of textures and game logic.

Here is code that will delay you to a 60 FPS game, you can adjust the number accordingly:

```
#define FRAMES_PER_SECOND 60

uint32_t timer = 0;

while(1)
{
    /* Game logic... rendering... */

    if(SDL_TICKS_PASSED(timer, SDL_GetTicks()))
    {
        SDL_Delay(timer - SDL_GetTicks());
    }

    /* Global Timer */
    timer = SDL_GetTicks() + (1000 / framesPerSecond);
}

```

Because `SDL_GetTicks()` can overflow, you must use `SDL_TICKS_PASSED` which is a builtin SDL2 macro based that allows integer overflow into the equation.

---
Tags: opengl, game-loop, c, sdl2, vsync
---


# Question
Title: How to manage collision between balls in Game Maker 2 (Drag and Drop)
Hey there I'm using Game Maker 2 Drag and Drop for a project, I made a game like Break Out and when the ball collides with the wall it doesn't bounce, in Game Maker Studio we had *Bounce Action* but in GMS2 is deleted, can anyone help me about this issue?

# Answer
I don't know if it'll work similair to Bounce, but it can be a workaround:

Make a wall object and place that on the edge, just outside the room, then, make a Collision Event when the ball collides with the wall object. Then inverse the movement of the ball.
> 1 votes

---
Tags: collision-detection, physics, game-maker
---