title: Using fixed time for Lerp

text:
# Question
Title: Using fixed time for Lerp
I would like to change a camera's rotation and position from its current position and rotation to a destination position and rotation.

This should happen within a specific time (seconds).

I call this void "pRotateAndPosition" in each Public void Update().

However, I'm having trouble getting the 3rd argument for Lerp (time) correct.

Could anybody tell me where my mistake(s) are?

Thank you.

```
private void pRotateAndPosition()
{
    _TimeElapsed += (Time.deltaTime / TimeInSecondsInWhichWeWantToGetToFinalRotationAndPosition);

    if (_TimeElapsed >= TimeInSecondsInWhichWeWantToGetToFinalRotationAndPosition)
    {
        _StopCallingThisVoid = true;//don't call this anymore

        //set the final position and rotation in case we're not completely there yet
        _camera.transform.localRotation = Quaternion.Euler(goalRotation);
        _camera.transform.localPosition = goalPosition;
        return;
    }

    float fTime = _TimeElapsed;//absolutely not sure about this one

    _camera.transform.localRotation = Quaternion.Lerp(_camera.transform.localRotation, Quaternion.Euler(goalRotation), fTime);
    _camera.transform.localPosition = Vector3.Lerp(_camera.transform.localPosition, goalPosition, fTime);
}

```

# Answer
> 1 votes
In addition to 'Alex F's answer:

You were handling the elapsed time badly. The stop condition was wrong in combination with how you were counting time.

**Edit: You also need to save the position/rotation your camera has at the beginning of the Lerp action, otherwise you will not interpolate correctly! You can't just plug in the current position into the Lerp function again.**

```
private void pRotateAndPosition()
{
    // Count the real elapsed time, not some scaled pseudo-time
    _TimeElapsed += Time.deltaTime;

    if (_TimeElapsed >= TimeInSecondsInWhichWeWantToGetToFinalRotationAndPosition)
    {
        _StopCallingThisVoid = true;//don't call this anymore

        //set the final position and rotation in case we're not completely there yet
        _camera.transform.localRotation = Quaternion.Euler(goalRotation);
        _camera.transform.localPosition = goalPosition;

        return;
    }

    // This will be (almost) zero at the beginning and ~1 when finished
    float fTime = _TimeElapsed / TimeInSecondsInWhichWeWantToGetToFinalRotationAndPosition;

    // The Lerp time should always be between 0 and 1. Time 0 gives you the start value, 1 the goal value, 0.5 is half-way between them.
    // Maybe the Slerp function looks smoother: https://en.wikipedia.org/wiki/Slerp Unity has this too
    _camera.transform.localRotation = Quaternion.Slerp(initialCameraRotation, Quaternion.Euler(goalRotation), fTime);
    _camera.transform.localPosition = Vector3.Lerp(initialCameraPosition, goalPosition, fTime);
}

```

You might want to try S(pherical)lerp with quaternions, just try out which one looks better to you.

For positions Lerp is the right choice, you want to move in a linear fashion most of the time.

# Answer
> 2 votes
I think you are slightly confused about what `Lerp` does (although it's very possible that I just don't understand your code and what's calling it). It takes a starting configuration, an ending configuration, and another value. The other value simply tells you how far to go between the two configurations. Since that explanation is kind of confusing, here's an example. Let's say you're `Lerp`ing between `1` and `5` (using `Mathf.Lerp`). If the third argument is `0`, you'll get `1`, and if it's `1`, you'll get `5`. If it's `0.5`, you'll get `3`.

With that out of the way, here are some possible solutions to your problem.

1. Coroutines: coroutines let you run a function alongside your main function. See the link for more information; looking at the first example, using `f` as the third argument to `Lerp` should achieve the effect you want (I'm assuming that you can modify the for loop).
2. The other option that springs to mind is to emulate a coroutine inside your `Update` function, by using a private variable to store how far along you are in the `Lerp`.

---
Tags: unity, lerp
---


# Question
Title: How to make walls opaque in PuzzleScript
On the PuzzleScript home page, there is an example of an enemy (`Eyeball`) which, when you (`Player`) are directly in its line of sight, will move one square closer to you, using the rule

```
[ Eyeball | ... | Player ] -> [ > Eyeball | ... | Player ]

```

However, the `Eyeball` will walk towards `Player` even if it shouldn't be able to see you, for instance if there is a wall in the way. This is apparent in a level like

```
#########
#....O..#
#.......#
#########
#.......#
#..P....#
#########

```

where, if `Player` passes below `Eyeball`, `Eyeball` will move one square down.

How do I make it so that the enemy can't see me through walls?

Inserting `no Wall` into the rule above doesn't work, as that doesn't tell `...` to only match wall-free tiles, but rather checks whether there is at least one non-wall tile between `Eyeball` and `Player`. And adding the rule

```
[ > Eyeball | ... | Wall | ... | Player ] -> [ Eyeball | ... | Wall | ... | Player ]

```

in an attempt to correct the movement doesn't work as two ellipses in a single match pattern isn't allowed.

# Answer
> 0 votes
I've come across a solution which works. It basically uses a phantom block to raycast from `Player` to any `Eyeball` in line with the `Player`, and if that block hits an `Eyeball` before it hits a `Wall`, it will make the `Eyeball` move toward the `Player`:

```
[Player | Eyeball] -> [Player | < Eyeball]
[Player | no Wall |... | EyeBall] -> [ Player | > Gaze | ... | Eyeball]
[> Gaze | no Wall | ... | Eyeball ] -> [ | > Gaze | ... | Eyeball ]
+ [> Gaze | Eyeball ] -> [ | < Eyeball > Gaze]
[ Gaze ] -> []

```

This works fine even for multiple `Eyeball`s, apart form some slight hiccups when Eyeballs compete for a square. That is to say, if you have two `Eyeball`s both touching the `Player`, and the `Player` moves out of the way, only one `Eyeball` will move to fill in the spot left by the `Player`, and which one that turns out to be is decided by the engine when the movement occurs.

(This competition would probably be tricky to solve using rules because doing so would require to match patterns that are not along a single line.)

If there is only one `Eyeball`, then the first two rules may be put together and simplified to

```
[Player | ... | EyeBall] -> [ Player > Gaze | ... | Eyeball]

```

This runs into issues with more than one `Eyeball` because several `Gaze` blocks cannot coexist in the same cell, meaning only one `Gaze` block ever gets made. One could also mend this by putting `again` after each rule, but that would make moves not happen instantaneously so it's not optimal.

---
Tags: puzzle
---


title: MMO - Server monster handling

text:
# Question
Title: MMO - Server monster handling
Dabbling with basic MMO code because it intrigues me.

How does the server handle monsters / mobs?

I understand that generally on each game tick, the server loops through each player to send them updated positions of each other nearby player or mob.

So every player loop you're also looping through every other player but is it just standard to loop through the entire mob list too? I mean there could be 1000+ mobs idling around the game world/zone. Would this just slow the loops down?

I thought maybe they keep a seperate list of ACTIVE mobs, ones that are either near a player or are chasing a player, but that would still require looping the idle ones to check if a moving player comes near one. Unless the aggro loop is less frequent (thinking out loud here)..

Is there some tricks or common workarounds involved? Or is that just how they work?

# Answer
If a monster is in the forest, but there's nobody there to see it, does it really exist?

* If a monster is in an area with no players, just ignore it. Nobody will attack it, and it won't attack anyone. So just pretend its not there. In fact, don't even bother initialising it. Its data probably exist in a file, hidden away from the CPU and memory.
* Whenever the player moves to an area, if that area is meant to have monsters, initialise them. Now you'd need to send their data to that player.
* If a player moves to a location but another player is already there, don't initialise the monsters, but make sure the new player is now getting their location and stats.

Don't forget that all games are full of illusions to make you believe things are less complicated than they actually are.
> 4 votes

---
Tags: mmo, server
---


# Question
Title: Calculate a random position inside a 2D area excluding a subset
Given this area

```
- - - -
- X X -
- X X -
- - - -

```

I have a **GameObject** size 4x4 and **inside another GameObject** size 2x2.

I know how to calculate a random position inside the 4x4 zone (using GameObject position and collider size), but I do not know **calculate a random position evading the 2x2 zone**.

What I am using right now is:

1. Calculate position inside 4x4.
2. If that position is inside 2x2 go back to step 1.

But it is not a good way to do this. Do you know can I calculate a random position inside 4x4 area evading a 2x2 area?

I though generating small GameObjects, 1x1 instead if 4x4. So first select a random of the 4x4 tagged, for examble, as "IsWalkable", and then calculate a random position insided the selected small square.

# Answer
If your objects are always rectangular, a very simple way is the following:

* split the container object into *N* sub-rectangles that are fully accessible and *M* that are fully inaccessible. In your example *N=8*, *M=1* except if the contained object is on a border (then *N=5*, *M=1*) or in a corner (*N=3*, *M=1*)
* compute the areas of each sub-rectangle: $$ A\_i ~~ \forall i \in \\{1, ..., N\\}$$
* draw the random index *r* in *{1, 2, ..., N}* with probability $$p(r = i) = \frac{A\_i}{\sum\_{i=1}^N A\_i} ~~ \forall i \in \\{1, ..., N\\}$$

note that the sum in the denominator is just the area of the container minus the area of the contained rectangle.

* draw a random point inside the sub-rectangle *r*.

The approach works even if the container contains other rectangles. You can also adapt it for other shapes easily.

Here is a picture to get you started: if you can figure out the area of each of the labelled rectangle and if you can write a function that draws a point at random in a rectangle, you are done. :)
> 2 votes

---
Tags: unity, 2d, random
---


title: Load character instead of load level

text:
# Question
Title: Load character instead of load level
I have some trouble finding out how I can load my character at the start of the level, instead of resetting the whole thing. The game mechanics are quite straight forward; don't touch the walls. If the player touches the walls, he "pops" (seeing as it is a balloon.)

This is my current script:

```
public class playerSpawner : MonoBehaviour {

public Sprite charAlive, charDead;
public AudioClip popAudio;

void  OnCollisionEnter2D (Collision2D col ){

    if (col.gameObject.name == "dirtWalls") {
        AudioSource.PlayClipAtPoint(popAudio, transform.position);
        gameObject.GetComponent<SpriteRenderer>().sprite = charDead;
        StartCoroutine (Dead ());
    }
    if (col.gameObject.name == "gooWalls") {
        gameObject.GetComponent<SpriteRenderer>().sprite = charDead;
        StartCoroutine (Dead ());
    }
    if (col.gameObject.name == "grassWalls") {
        gameObject.GetComponent<SpriteRenderer>().sprite = charDead;
        StartCoroutine (Dead ());
    }
}

IEnumerator Dead() {

    AudioSource.PlayClipAtPoint(popAudio, transform.position); // PLAYS SEVERAL TIMES
    yield return new WaitForSeconds(3/2);
    Application.LoadLevel ("untitled");
    // LOAD LEVEL RESETS EVERYTHING, MAKE LOAD CHAR INSTEAD?
}

```

}

How can I just respawn the player object instead of resetting the whole scene?

# Answer
> 1 votes
You could turn your player into a prefab. When your player "pops" destroy that gameobject and create a new one at the start of the level.

# Answer
> 0 votes
As ThePumkinMelon suggested, create a prefab for your player game object.

Then remove the player object from your scene, have your player spawner reference the player prefab and also reference the current player game object in the scene:

```
public class PlayerSpawner : MonoBehaviour {

    public GameObject playerPrefab;
    private GameObject currentPlayer;

```

Then in the Update-method of the PlayerSpawner, do this:

```
    if (currentPlayer == null) {
         currentPlayer = Instantiate(playerPrefab, transform.position, transform.rotation);
    }

```

This will check if its player is in the scene, and when it is not it will spawn a new player at the position and with the rotation of the spawner (that means you need to place the PlayerSpawner game object at the location where you want the player to spawn).

There are two cases where `currentPlayer == null` will be true.

Now your `Dead` coroutine just needs to `Destroy` the player game object and the PlayerSpawner will promptly instantiate a new one.

---

However, keep in mind that if you excessively destroy and instantiate a lot of game objects, you might start to notice notable performance degregation due to memory fragmentation and garbage collection. In this case this shouldn't matter, because the player will die every few seconds at most, even if you create a hellishly difficult game. But if you have some kinds of objects in your game which get destroyed and respawned serveral times per second, then you might want to look into a pattern called "object pools". But that's a topic for a different question.

I am looking forward to playing your game.

---
Tags: c#, unity, collision-detection
---


title: Why can't I read this JSON file?

text:
# Question
Title: Why can't I read this JSON file?
I get an error every time I try to parse this .json file.

Here is the error:

```
Exception in thread "LWJGL Application" com.badlogic.gdx.utils.SerializationException: Error reading file: skin/glassy-ui.json
  at com.badlogic.gdx.scenes.scene2d.ui.Skin.load(Skin.java:104)
  at com.badlogic.gdx.scenes.scene2d.ui.Skin.<init>(Skin.java:81)
  at com.mygdx.game.MyGdxGame.create(MyGdxGame.java:45)
  at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:149)
  at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:126)
Caused by: com.badlogic.gdx.utils.SerializationException: Error reading file: skin/glassy-ui.json
  at com.badlogic.gdx.utils.Json.fromJson(Json.java:715)
  at com.badlogic.gdx.scenes.scene2d.ui.Skin.load(Skin.java:102)
  ... 4 more
Caused by: com.badlogic.gdx.utils.SerializationException: Error parsing file: skin/glassy-ui.json
  at com.badlogic.gdx.utils.JsonReader.parse(JsonReader.java:78)
  at com.badlogic.gdx.utils.Json.fromJson(Json.java:713)
  ... 5 more
Caused by: com.badlogic.gdx.utils.GdxRuntimeException: File not found: skin\glassy-ui.json (Classpath)
  at com.badlogic.gdx.files.FileHandle.read(FileHandle.java:142)
  at com.badlogic.gdx.files.FileHandle.reader(FileHandle.java:169)
  at com.badlogic.gdx.utils.JsonReader.parse(JsonReader.java:76)
  ... 6 more

```

Here is the code:

```
mySkin = new Skin(Gdx.files.classpath(constants.skin));

```

I have my references correct and the assets are properly placed in the folder. I'm not sure why it is saying file not found: skin/glassy-ui.json

json code:

```
{
com.badlogic.gdx.graphics.g2d.BitmapFont: {
  font: {
    file: font-export.fnt
  }
  font-big: {
    file: font-big-export.fnt
  }
}
com.badlogic.gdx.graphics.Color: {
  black: {
    r: 0
    g: 0
    b: 0
    a: 1
  }
  cyan: {
    r: 0
    g: 1
    b: 0.99166656
    a: 1
  }
  dark-cyan: {
    r: 0
    g: 0.39373153
    b: 0.4333333
    a: 1
  }
  white: {
    r: 1
    g: 1
    b: 1
    a: 1
  }
}
com.badlogic.gdx.scenes.scene2d.ui.Skin$TintedDrawable: {
  pale-blue: {
    name: white
    color: {
      r: 0.48342222
      g: 0.76367503
      b: 0.99333334
      a: 1
    }
  }
  black: {
    name: white
    color: {
      r: 0
      g: 0
      b: 0
      a: 1
    }
  }
}
com.badlogic.gdx.scenes.scene2d.ui.Button$ButtonStyle: {
  default: {
    up: button
    down: button-down
  }
  small: {
    up: button-small
    down: button-small-down
  }
}
com.badlogic.gdx.scenes.scene2d.ui.CheckBox$CheckBoxStyle: {
  default: {
    checkboxOn: checkbox
    checkboxOff: checkbox-off
    font: font
    fontColor: white
  }
  radio: {
    checkboxOn: radio-button
    checkboxOff: radio-button-off
    font: font
    fontColor: white
  }
}
com.badlogic.gdx.scenes.scene2d.ui.ImageButton$ImageButtonStyle: {
  default: {
    up: button
    down: button-down
  }
}
com.badlogic.gdx.scenes.scene2d.ui.ImageTextButton$ImageTextButtonStyle: {
  default: {
    font: font-big
    up: button
    down: button-down
  }
}
com.badlogic.gdx.scenes.scene2d.ui.Label$LabelStyle: {
  default: {
    font: font
  }
  big: {
    font: font-big
  }
  black: {
    font: font
    fontColor: black
  }
}
com.badlogic.gdx.scenes.scene2d.ui.List$ListStyle: {
  default: {
    font: font
    fontColorSelected: white
    fontColorUnselected: dark-cyan
    selection: pale-blue
    background: list
  }
  plain: {
    font: font
    fontColorSelected: white
    fontColorUnselected: dark-cyan
    selection: pale-blue
  }
}
com.badlogic.gdx.scenes.scene2d.ui.ProgressBar$ProgressBarStyle: {
  default-horizontal: {
    background: progress-bar
    knobBefore: progress-bar-knob
  }
  default-vertical: {
    background: progress-bar-vertical
    knobBefore: progress-bar-knob-vertical
  }
}
com.badlogic.gdx.scenes.scene2d.ui.ScrollPane$ScrollPaneStyle: {
  default: {
    hScroll: horizontal-scroll-bar
    hScrollKnob: horizontal-scroll-knob
    vScroll: vertical-scroll-bar
    vScrollKnob: vertical-scroll-knob
  }
  scroll: {
    background: list
    hScroll: horizontal-scroll-bar
    hScrollKnob: horizontal-scroll-knob
    vScroll: vertical-scroll-bar
    vScrollKnob: vertical-scroll-knob
  }
}
com.badlogic.gdx.scenes.scene2d.ui.SelectBox$SelectBoxStyle: {
  default: {
    font: font
    fontColor: dark-cyan
    background: select-box
    scrollStyle: scroll
    listStyle: plain
  }
}
com.badlogic.gdx.scenes.scene2d.ui.Slider$SliderStyle: {
  default-horizontal: {
    background: slider
    knob: slider-knob
  }
  default-vertical: {
    background: slider-vertical
    knob: slider-knob
  }
}
com.badlogic.gdx.scenes.scene2d.ui.SplitPane$SplitPaneStyle: {
  default-horizontal: {
    handle: horizontal-split-pane
  }
  default-vertical: {
    handle: vertical-split-pane
  }
}
com.badlogic.gdx.scenes.scene2d.ui.TextButton$TextButtonStyle: {
  default: {
    font: font-big
    up: button
    down: button-down
  }
  small: {
    font: font
    up: button-small
    down: button-small-down
  }
}
com.badlogic.gdx.scenes.scene2d.ui.TextField$TextFieldStyle: {
  default: {
    font: font
    fontColor: black
    background: textfield
    cursor: black
    selection: pale-blue
  }
}
com.badlogic.gdx.scenes.scene2d.ui.Tree$TreeStyle: {
  default: {
    plus: plus
    minus: minus
    selection: pale-blue
  }
}
com.badlogic.gdx.scenes.scene2d.ui.Window$WindowStyle: {
  default: {
    background: window
    titleFont: font
    titleFontColor: black
  }
}
}

```

# Answer
> com.badlogic.gdx.utils.GdxRuntimeException: File not found: skin\glassy-ui.json (Classpath)

The json reader can't find your file, you can't fix that by changing the files content.

The first problem is that you're using the classpath file locator, it's described as "should be avoided" in the wiki:

> They have their purpose, but should be avoided if possible.

Try

```
Gdx.files.internal("skin/glassy-ui.json")

```

Where the file is placed in the "YourProjectName/android/assets/skin" folder (the standard assets-folder).

This is the preferred method to refer to assets in LibGDX:

> Internal files are relative to the application’s root or working directory on desktops, relative to the assets directory on Android, and relative to the core/assets/ directory of your GWT project. These files are read-only. If a file can't be found on the internal storage, the file module falls back to searching the file on the classpath. This is necessary if one uses the asset folder linking mechanism of Eclipse, see Project Setup

This only works if you have set up the project correctly (with the setup GUI / gradle) though.

Check the LibGDX Wiki on file handling: LibGDX Wiki - File (Storage) Types

And on Project setup: LibGDX Wiki - Project Setup
> 3 votes

# Answer
It is not correct JSON, strings in JSON must be surrounded with quotes, and values in object must be comma-separated

For example

```
{
    "key": "value",
    "number": 1,
    "nested-object": {
        "name": null,
        "array": [{
            "id": 1234
        },{
            "id": 5678
        }]
    }
}

```

You always can validate your JSON online
> 1 votes

---
Tags: java, libgdx, json
---


# Question
Title: Is GL_DEPTH_COMPONENT32 deprecated in OpenGL 4.5?
I'm in the process of migrating our object oriented OpenGL wrapper from 3.3 core to 4.5 core.

Some OpenGL implementations are notoriously permissive on what inputs they'll accept which can make tracking down bugs difficult. Wherever possible the inputs to our wrapper are validated with asserts to keep them in line with the spec.

While setting up the asserts for `glTextureStorage3D` I've noticed that according to this page on the Khronos website it only accepts the following sized depth types: `GL_DEPTH_COMPONENT32F`, `GL_DEPTH_COMPONENT24`, `GL_DEPTH_COMPONENT16`, `GL_DEPTH32F_STENCIL8` or `GL_DEPTH24_STENCIL8`.

Non-floating point 32bit depth types seem to be missing from that list which leads me to believe they're no longer supported (or at least actively discouraged). There's also this answer to another question which states that:

> GL\_DEPTH\_COMPONENT32 is probably overkill, and as of 4.5, isn't a required format for OpenGL implementations to support (though 16 and 24 bit ones are).

I have tried to find some reference to this in the 4.5 core spec but turned up nothing.

Is `GL_DEPTH_COMPONENT32` a deprecated size type? If so, why?

# Answer
Typically, I've managed to find the answer almost immediately after asking the question.

> **§8.5.1 TEXTURE IMAGE SPECIFICATION, p201**
>
> ...
>
> Implementations are required to support at least one allocation of internal component resolution for each type (unsigned int, float, etc.) for each base internal format.

~~This seems to say that yes the format is deprecated.~~ It appears the format is not deprecated but is now optional and may not be available on all OpenGL 4.5 implementations. The reason is that only one type (int, float, etc) needs to be supported for each resolution (8, 16, 24, 32, etc).
> 1 votes

---
Tags: opengl
---


# Question
Title: FormatMessage not working for HRESULTs returned by Direct3D 11
*I am using Windows 7 x64 and Visual Studio 17 (v15.9.7).*

Say I try to create a swap chain using `IDXGIFactory2::CreateSwapChainForHwnd` and pass in `DXGI_SCALING_NONE`. I will get the following message in debug output (if I have enabled Direct3D debugging):

```
DXGI ERROR: IDXGIFactory::CreateSwapChain: DXGI_SCALING_NONE is only supported on Win8 and beyond. DXGI_SWAP_CHAIN_DESC{ SwapChainType = ..._HWND, BufferDesc = DXGI_MODE_DESC1{Width = 816, Height = 488, RefreshRate = DXGI_RATIONAL{ Numerator = 0, Denominator = 1 }, Format = B8G8R8A8_UNORM, ScanlineOrdering = ..._UNSPECIFIED, Scaling = ..._UNSPECIFIED, Stereo = FALSE }, SampleDesc = DXGI_SAMPLE_DESC{ Count = 1, Quality = 0 }, BufferUsage = 0x20, BufferCount = 2, OutputWindow = 0x0000000000290738, Scaling = ..._NONE, Windowed = TRUE, SwapEffect = ..._FLIP_SEQUENTIAL, AlphaMode = ..._UNSPECIFIED, Flags = 0x0 } [ MISCELLANEOUS ERROR #175: ]

```

The function returns `0x887a0001` in form of a `HRESULT`. If I put `@err,hr` in the watch window, I get a nice error message there:

```
ERROR_MOD_NOT_FOUND : The specified module could not be found.

```

However, if I pass this `HRESULT` to `FormatMessage`, it just puts `NULL` in the output and returns 0. `@err,hr` helpfully informs me that the new error is `ERROR_MR_MID_NOT_FOUND : The system cannot find message text for message number 0x%1 in the message file for %2.`

My questions are:

1. Why is `FormatMessage` not giving me right error string (the one starting with `ERROR_MOD_NOT_FOUND...`)?
2. Where is Visual Studio getting these pretty error strings from?
3. Can I get them too? Who do I pay?

---

PS. I am using the Windows 10 SDK version of DX11, not the older DirectX SDK version. Thus, I can't really link to `dxerr.lib` either.

This is the code that is used to print the error message:

```
LPTSTR error_text = NULL;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
              FORMAT_MESSAGE_ALLOCATE_BUFFER |
              FORMAT_MESSAGE_IGNORE_INSERTS,
              NULL,
              hr,
              MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
              (LPTSTR)&error_text, 0,
              NULL);

```

# Answer
> 2 votes
**TL;DR:** The short answer is that you should be using `FormatMessage`, but you should also be using Windows 8 or later. With Windows 7, the OS was never updated to include the DirectX error messages in `FormatMessage`.

In my blog post on replacing the legacy DXERR library, I try using `FormatMessage` and if that fails fallback to the local list for cases like Windows 7.

You are using the DirectX 11.1 Runtime which is partially supported for Windows 7 Service Pack 1 per Microsoft Docs. That page explicitly states:

> IDXGIFactory2::CreateSwapChainForHwnd takes a DXGI\_SWAP\_CHAIN\_DESC1 structure, which has a field for Scaling. DXGI\_SCALING\_NONE is not supported on Windows 7 with the platform update and causes CreateSwapChainForHwnd to return DXGI\_ERROR\_INVALID\_CALL when called.

---
Tags: directx11, windows, visual-studio, win32
---


# Question
Title: What makes a shader function with a LineRenderer?
A LineRenderer has both Material and Color properties.
But many shaders do not work, ie the line will not respect the Color property, or the line will show black (regardless of the materials having its own color).

For example the Standard, Diffuse, Mobile/Diffuse shaders all show black. Unlit/Color ignores the LineRenderer color and uses only the Material Color property. Particles\>Additive works great, but Particles\>Standard Surface does not.

What part of the shader code is important to make a LineRenderer display using its own Color property? When it does work, how should shader code decide how to merge between the two colors?

# Answer
> 4 votes
Color on a LineRenderer is represented as a color property on the vertices themselves. It behaves just like other vertex properties such as position and UV coordinates. However, vertex colors are uncommon in most models, so you won’t see most shaders support them. To get this data to be transferred to the shader, you need to declare a custom vertex struct and function. Here is an example of a custom standard surface shader which includes vertex colors, taken from the Unity forums:

```
Shader "Custom/StandardVertex" {
    Properties {
         _Color ("Color", Color) = (1,1,1,1)
         _MainTex ("Albedo (RGB)", 2D) = "white" {}
         _Glossiness ("Smoothness", Range(0,1)) = 0.5
         _Metallic ("Metallic", Range(0,1)) = 0.0
     }
     SubShader {
         Tags { "RenderType"="Opaque" }
         LOD 200

         CGPROGRAM
         #pragma surface surf Standard vertex:vert fullforwardshadows
         #pragma target 3.0
         struct Input {
             float2 uv_MainTex;
             float3 vertexColor; // Vertex color stored here by vert() method
         };

         struct v2f {
           float4 pos : SV_POSITION;
           fixed4 color : COLOR;
         };

         void vert (inout appdata_full v, out Input o)
         {
             UNITY_INITIALIZE_OUTPUT(Input,o);
             o.vertexColor = v.color; // Save the Vertex Color in the Input for the surf() method
         }

         sampler2D _MainTex;

         half _Glossiness;
         half _Metallic;
         fixed4 _Color;

         void surf (Input IN, inout SurfaceOutputStandard o)
         {
             // Albedo comes from a texture tinted by color
             fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
             o.Albedo = c.rgb * IN.vertexColor; // Combine normal color with the vertex color
             // Metallic and smoothness come from slider variables
             o.Metallic = _Metallic;
             o.Smoothness = _Glossiness;
             o.Alpha = c.a;
         }
         ENDCG
     }
     FallBack "Diffuse"
}

```

Notice that it combines texture color with material color (`fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;`) and then later combines it with the vertex color (`o.Albedo = c.rgb * IN.vertexColor`) to get a final value which takes all three into account.

---
Tags: unity, shaders, color
---


# Question
Title: Controlling a thrustered 2D space ship with angular rotation and max speed
In my game I have a computer controlled **ship** that is accelerated by a **thruster**: with a constant force and in the direction of the ship's current orientation/rotation angle.

**Thrusting** My ship has a maximum speed limit (velocity) and a maximum thrust power that can be applied each time to the velocity until maximum speed has been reached.

**Rotating** Given a "desired target" (click the screen on my demo), it determines the required angle and rotates by a constant angular force until it reaches the desired value.

Finding the angle and rotating is done. The problem is that the only way I know how to keep a speed limit is by limiting the ship's velocity vector before it is summed to the ship's location, but this way the ship is always thrusting (like in the video) only the effect is caped:

Check: Thruster space ship in action (youtube)

**Thrusting only when required** In a better approach, I only thrust if the ship orientation angle is aligned with the target angle.

Check: A better approach (youtube)

While this is visually more effective, thrusting is still done at max power and still relies in limiting the velocity when the ship is thrusting.

**What I need (and I can't do)** I need to calculate the force that the thruster should apply to the ship's velocity to change the direction while keeping the overall speed not beyond the limit so I can get rid of limiting the ship's velocity.

Reading this thread I understand (I think) that I need to apply to the velocity **only** the component of the force that will affect the ship velocity angle and not its length. And I can determine this checking if the direction of the impulse (thrusting force) is orthogonal to the current direction of the ship's velocity and applying the relevant component of that force (x or y).

I did many attemps and all failed. So I came here with hope to find someone who is more familiarized with this or at least that can explain how to apply @dannuic reply to my code.

This is my code on github, just clone and if in Linux run ./simpleServer (may require chmod u+x).

Thank you very much!

# Answer
> 0 votes
The applied force should be proportional to the desired velocity, relative to the current velocity.

In that case, if the current velocity is zero, the force will be proportional to the desired velocity.

If the current velocity is the desired velocity, the force will be zero.

```
Vec3 force = factor * (desired_velocity - current_velocity)

```

The proportionality factor is something that will depend on the scale of your game.

---
Tags: 2d, javascript, vector, steering-behaviors
---


# Question
Title: Calculating vertex normals in OpenGL C++
Does anyone knows a simple solution for calculating vertex normals? I've been looking for this on the internet but i cant find a simple solution, for example, if I have some vertices like this:

```
GLfloat vertices[] =
{
 0.5f,  0.5f, 0.0f,  // Top Right
 0.5f, -0.5f, 0.0f,  // Bottom Right
-0.5f, -0.5f, 0.0f,  // Bottom Left
-0.5f,  0.5f, 0.0f   // Top Left
};

```

# Answer
> 5 votes
Finding the vertex normal is actual really easy. Lets say that you want to find to normal for the vertex i (i is a 2D/3D vector), where i1 is the vertex after i and i2 is the vertex before i, this is what you do:

1. Create two vectors, v1 and v2. Set v1 it to i1 - i, and set v2 it to i2 - i
2. Create another vector called v3 and set it to the cross product between v1 and v2
3. Finally, your normal will be the v3 normalized.

Note: If your model is not appearing then try inverting the normals or disabling cull face mode(if enabled). Also, by 'the vertex before' and 'the vertex after' I simply mean two different vertices adjacent to i.

# Answer
> 2 votes
I disagree with JasonPh's answer. The result from his approach is face normal---the normal perpendicular to the face of i-i1-i2.

To calculate vertex normal, you need to calculate face normal first. The vertex normal is usually the average of the normals of faces adjacent to this vertex. Alternatively, a weighted average of these face normals can be used.

In order to traverse the faces adjacent to this vertex, half-edge data structure (http://www.sccg.sk/~samuelcik/dgs/half\_edge.pdf) are usually adopted. It not only helps find the faces adjacent to a vertex, but also helps answer other questions more easily

* Which faces use this vertex?
* Which edges use this vertex?
* Which faces border this edge?
* Which edges border this face?
* Which faces are adjacent to this face?
* ...

The structure is like

```
struct HE_edge {
    HE_vert* vert; // vertex at the end of the half-edge
    HE_edge* pair; // oppositely oriented half-edge
    HE_face* face; // the incident face
    HE_edge* prev; // previous half-edge around the face
    HE_edge* next; // next half-edge around the face
};

struct HE_vert {
    float x, y, z; // the vertex coordinates
    HE_edge* edge; // one of the half-edges emanating from the vertex
};

struct HE_face {
    HE_edge* edge; // one of the half-edges bordering the face
};

```

With this structure, the procedure is basically (just a code to help understand, not the most effective one):

```
for each vertex v:
    // initialize
    v->normal = vec3(0,0,0);
    //iterate through all v's neighbouring face
    neighbouring_edge = v->edge;
    v->normal += calcFaceNormal(neighbouring_edge->face);
    //find the next edge emanating from vertex v
    neighbouring_edge = neighbouring_edge->pair->next
    while neighbouring_edge!= v->edge:
        v->normal += calcFaceNormal(neighbouring_edge->face);
        neighbouring_edge = neighbouring_edge->pair->next;
    v->normal = normalize(v->normal);

```

where the calcFaceNormal function can be (assuming triangle mesh):

```
calcFaceNormal(myface):
    v1 = face->edge->vert;
    v2 = face->edge->next->vert;
    v3 = face->edge->prev->vert;
    e1 = v2-v1;
    e2 = v3-v1;

    return corss_product(e1,e2);

```

---
Tags: opengl, c++, graphics, glsl
---


# Question
Title: How can I avoid writing a class for each of my 800 different items?
I have a webgame written in PHP and using MariaDB for the database. I'm currently looking into ways of improving core systems.

One example would be items. Currently, there is a table `data_items` that lists all of the items, what category they fall into, their sale value, description, icon and so on. There is then an `inventory` table with foreign keys referencing `users` and `data_items`, and a `quantity` column. Simple, and it works.

However, some items have effects. Actually most of them do.

Currently effects are implemented in one of two ways.

1. The item is requested specifically by the code. For example, a particular feature requires a particular item, so that item is loaded up, its quantity is checked in the player's inventory, and the code proceeds if the user has the item. This is fine.
2. The item's properties are checked. For items in the "Consumables" category, there's currently a `switch` statement that provides different effects based on the item in question. This is horrible.

I'm considering the idea of having a `class` for each item. The class can then have methods such as `isConsumable()`, `consume()`, and whatever else may be needed as applicable to each item.

Should I still have the database? I assume so. There are cases when items need to be searched, eg. by category, for showing the player's inventory. In a case like this, where there are upwards of 800 items at this point, I wouldn't want to have to load 800 classes.

What kind of combination of things should I be aiming for here? Maybe have an item "prototype" that just holds data, which can be used when enumerating the items for the inventory? Then, when the item is actually used for something, check for its specific class and only load it at that point? I think that makes sense, but any advice on this matter would be very helpful indeed.

I'm facing a similar problem for the creatures within the game. Most of them have nothing special to them, so the database works fine. But some have different images based on certain factors. One in particular can be customised to have whichever pair of colours the user chooses. These are currently all handled by `switch` statements in the `getImage()` method of the generic creature object. Should this be split into classes for each (of the 1200+) creatures?

# Answer
Having a class *for* items is a good idea, but it is rarely useful to have a class *for each* item. When entities in a game differ by their values and not their behavior, then it is usually better to implement them as instances of the same class which differ by their data. The only case where you need to create new classes inheriting from `Item` is when you have items which have unique game mechanics. And even then it might be advisable to implement that mechanic somewhere else and just add some kind of tag to the item data which tells the game to use that special mechanic.

Regarding the question if you should keep item types in the database or not: I haven't worked with PHP in a very long time, and back then it was difficult to share data between requests without taking a detour through a database. But if it is possible now then I would avoid reading the data about the item types from the database and keep them in memory instead. The reason is that you are dealing with data which changes very rarely (whenever you release an update) but which is required very frequently. That means it is data which should be read at server startup and then stay in memory for fast access.
> 2 votes

---
Tags: data-structure, databases, php
---


# Question
Title: Why doesn't my android application rotate when I rotate my screen
I am building a game in LibGDX and the game screen orientation is in landscape. I want it to stay in landscape but I still want the user to be able to flip the device onto the other side and the screen will rotate with it. My application refuses to do that and I don't know what to do to fix that. I tried turning on my accelerometer and compass (wasn't expecting anything from compass) but nothing changed. Any ideas?

# Answer
> 19 votes
It defaults to locked on "landscape" mode in a libGDX project. You need to go into your "**AndroidManifest.xml**" and change **android:screenOrientation="landscape"** too **android:screenOrientation="sensorLandscape"**

There are more options - http://developer.android.com/guide/topics/manifest/activity-element.html#screen Just replace "sensorLandScape" with the one you want.

# Answer
> 0 votes
I know this old, but for the users who come here for an answer, all you need to do is in the "AndroidManifest.xml" file. Where it has a tag you will need to place a android:screenOrientation="sensor" to track its orientation from landscape to portrait and vice versa

---
Tags: android, libgdx
---


# Question
Title: How do you animate/collide against a tessellated mesh?
Now that I have a implemented tessellation for my mesh, I am trying to understand how I can leverage the generated primitives.

**Example:**

I have the following track mesh generated procedurally, it consists of quads, in the first picture you can see one of them I am highlighting using the mouse.

In the following picture, the shader applies some tessellation, you can see that now a quad has generated 16 quads.

**Question (two-folded):**

Now that I have more control points for each of my quad, suppose I want to deform one of them, for instance, to look like the following:

1. How is one supposed to apply such transformation ?

* basically, what in terms of code-behind / shader code infrastructure is required to achieve such thing.
2. How can collisions be checked for against that deformed mesh ?

* from what I've understood, a mesh collider would be unpractical since it's a heavy operation that just forbids real-time updates

# Answer
> 2 votes
In general, you should avoid asking two separate questions in one post on StackExchange. I'll focus on your second question as it's the meatier of the two, and give a quick overview of the first:

> How is one supposed to apply such transformation?

There are a few places you can do this:

* Domain Shader

+ interpolate vertex from tesselator using hull information
    + modify vertex position \<--- here
    + return tesselated vertex
* Vertex Shader

+ process input vertex
    + modify position \<--- or here
    + transform position to clip space
    + return transformed vertex
* Geometry Shader

+ process input primitive...
    + write vertex position \<--- or even here
    + emit vertex
    + next vertex...
    + output primitive

In any of these marked places, you can replace the position read from the input vertex/buffer or computed from your interpolation function with a new position of your choosing. Typically you'd calculate the new position as a function of the original vertex parameters (eg. looking up a value from a displacement map texture and offsetting the vertex along its normal by the computed distance) along with any other variables you like (eg. time, intensity parameters...)

Check out tutorials on vertex displacement for code examples in your shader dialect of choice.

> How can collisions be checked for against that deformed mesh?

Generally speaking, you don't.

Mesh collisions are already expensive, to the extent that games will often use one mesh for visual display, and a separate, lower-detail mesh (or collection of primitives) for collision - even when we're not applying dynamic tesselation to increase the visual detail further.

Wherever you can, I'd recommend making your collision geometry just detailed enough for "plausible" physics behaviour, and keeping it constant.

There are some cases where that's not practical however. Depending on what you need, we'll come up with different solutions. Here are a few examples of the kinds of things we might do:

* We need objects to follow a dynamically moving surface, like the roiling waves of a dynamically tesselated ocean.

Here, we'll often attach invisible "floater" objects to the bodies that need buoyancy. These will typically have a simple shape we can work with analytically, like a sphere, and we'll place multiple floaters with different positions/sizes/density to approximate the shape of a ship's hull.

Each physics step, we can query the depth of each floater below the water's surface by evaluating the same wave height function used in our dynamic tesselation / vertex displacement shader. (So we're not reading back the triangles from the GPU, just performing the same math with the same inputs to get the same result, but for a few point samples instead of the entire water surface mesh) Based on this depth, and possibly a surface normal, we can compute the buoyancy forces to apply to our parent body.

This method isn't rigidly accurate, but for a fluid surface with some "slosh" it's plausible enough, and very flexible for a variety of collider shapes / configurations and surface behaviours.
* We need visually-correct collisions specifically for content we're looking at (eg. correct snap-to-surface for content under the cursor, or on-screen character feet, or visible particles bouncing off a surface instead of passing through it)

Here, we can render the tesselated mesh to a depth texture, and query it to find the exact collision point along a ray from the camera. For content like particles, we can simulate their physics and collisions wholly on the GPU this way to save expensive synchronization & readback to the CPU for collision-handling there.

The downside is that it works only for stuff the camera sees, and it does not correctly handle physics behind occluder objects. For off-screen objects we can fall back on a simpler collision model that might not capture all the detail, but this is usually forgivable since the errors happen out of sight.
* We need precise matching between the rendered polygons and logical collisions everywhere (DANGER)!!

In this case, there's not a lot we can do but duplicate the tesselation & displacement logic CPU-side, and use it to re-generate the collision mesh when it changes. As you say, this is expensive, so we should avoid this wherever possible, and minimize how frequently / how many polygons worth of collision data we update this way. Dividing the mesh into chunks may be one way to do that - localizing updates to just one chunk at a time.

---
Tags: unity, animation, tessellation
---


# Question
Title: How to move points of a multi-segmented bezier curve to one side
I am trying to move points from a multi-segmented bezier curve to one end of the curve using the following code which modified for my use from here. Only the last segment seems to give the desired behaviour. All other segments, basically just disappear or skip through briskly.

```
public Vector2[] MultiSegmentCubicCurveReduction(Path curve, float start, float end)
{
    List<Vector2> pointsForSubpath = new List<Vector2>();

    float oneMinusStart = 1f - start;
    float oneMinusEnd = 1f - end;

    float scale = (end - start) / (curve.NumPoints - 1);

    for (int i = 0; i < curve.NumSegments; i++)
    {

        var a =
            oneMinusStart * oneMinusStart * oneMinusStart * curve[3*i] +
           3f * oneMinusStart * oneMinusStart * start * curve[3 * i + 1] +
           3f * oneMinusStart * start * start * curve[3 * i + 2] +
                                     start * start * start * curve[3 * i + 3];

        var b = a + (3f * oneMinusStart * oneMinusStart * (curve[3 * i + 1] - curve[3 * i]) +
                     6 * start * oneMinusStart * (curve[3 * i + 2] - curve[3 * i + 1]) +
          3 * start * start * (curve[3 * i + 3] - curve[3 * i + 2])) * scale;

        ;

        var d = oneMinusEnd * oneMinusEnd * oneMinusEnd * curve[3 * i] +
            3f * oneMinusEnd * oneMinusEnd * end * curve[3 * i + 1] +
            3f * oneMinusEnd * end * end * curve[3 * i + 2] +
                                            end * end * end * curve[3 * i + 3];

        var c = d - (3f * oneMinusEnd * oneMinusEnd * (curve[3 * i + 1] - curve[3 * i]) +
                     6 * end * oneMinusEnd * (curve[3 * i + 2] - curve[3 * i + 1]) +
                                                        3 * end * end * (curve[3 * i + 3] - curve[3 * i + 2])) * scale;

        pointsForSubpath.AddRange(new List<Vector2>() { a, b, c, d });
    }

    return pointsForSubpath.Distinct().ToArray();

}

```

**UPDATE**

The brisk movement I was having earlier was actually a reduction of control points to four regardless of the number of segments. Now I am getting the following behaviour. All the points for the first segment converge to one end point whiles all the points of the remaining segments converge to the other end point, resulting in a straight line.

# Answer
> 1 votes
The code in the linked answer moves the endpoints of a single segment of a Bézier curve.

Using it on all segments simultaneously as you do here doesn't make sense. At most you want to be changing one segment at a time - the flaming tip of the wick as it burns down. Segments in the middle of the chain shouldn't change at all until their neighbouring segment on one side or the other is completely consumed.

So, let's sketch out how we'd solve this problem.

First, let's assume we have a `BezierSpline` type that provides an ordered, resize-able sequence of `BezierSegment` entries. Let's also associate with each segment an (approximate) arc length. We can use this to get a more uniform rate of motion as we contract the curve. (You can always translate this into a raw position array later, but talking about it in an object oriented fashion makes the description a bit clearer for this answer)

With this in hand, we can make a version of the `IntevalFromTo` method from the earlier answer that operates on a spline, rather than on a segment, producing a new spline. The version I show here is O(n) in the number of segments in the spline - you could make one that's O(log(n)) with binary search if you have exceptionally long splines, but I'm keeping it simple for now.

```
BezierSpline IntervalFromTo(BezierSpline sourceSpline, float start, float end) {
    // Ensure our start & end parameters are in a sensible range.
    Assert(start >= 0 && start <= end && end <= 1);

    // Convert our relative start & end values to absolute arc length measures.
    float lengthStart = start * sourceSpline.totalLength;
    float lengthEnd = end * sourceSpline.totalLength;

    // Scan for the first segment in our new, contracted spline,
    // skipping over segments that have been completely consumed.
    int firstSegment = 0;
    float accumulatedLength = 0f;
    while(lengthStart >= accumulatedLength + sourceSpline.GetSegment(firstSegment).length) {
        // This is simple, but not strictly numerically stable,
        // so you may need to exercise more care if you need high precision.
        accumulatedLength += sourceSpline.GetSegment(firstSegment).length;
        firstSegment++;
    }

    // Translate our start point into the local parameter space of the first segment.
    // (For better uniformity here, you can instead search for the point at which
    // the arc length along this curve exactly matches the residual)
    float localStart = Clamp01((lengthStart - accumulatedLength)
                     / sourceSpline.GetSegment(firstSegment).length);

    int lastSegment = firstSegment;
    while(lengthEnd < sourceSpline.segmentCount - 1
       && lengthEnd > accumulatedLength + sourceSpline.GetSegment(lastSegment).length) {
        accumulatedLength += sourceSpline.GetSegment(lastSegment).length;
        lastSegment++;
    }

    // Translate our end point into the local parameter space of the last segment.
    // (For better uniformity here, you can instead search for the point at which
    // the arc length along this curve exactly matches the residual)
    float localEnd = Clamp01((lengthEnd - accumulatedLength)
                     / sourceSpline.GetSegment(lastSegment).length);

    int segmentCount = lastSegment - firstSegment + 1;
    var modifiedSpline = new BezierSpline(segmentCount);

    if (segmentCount == 1) {
        // We've reduced the spline to one segment!
        // Use the single-segment version of IntervalFromTo in my earlier answer.
        var segment = IntervalFromTo(
                          sourceSpline.GetSegment(firstSegment),
                          localStart,
                          localEnd
                      );
        modifiedSpline.SetSegment(0, segment);
    } else {
        // Form a shortened start segment,
        // using our IntervalFromTo method for individual segments.
        var segment = IntervalFromTo(
                          sourceSpline.GetSegment(firstSegment),
                          localStart,
                          1f
                      );
        modifiedSpline.SetSegment(0, segment);

        // Copy all intact segments between the start and end, unchanged.
        for(int i = 1; i < segmentCount - 1; i++) {
            modifiedSpline.SetSegment(i, sourceSpline.GetSegment(firstSegment + i));
        }

        // And finally, cap it off with a shortened end segment.
        segment = IntervalFromTo(
                          sourceSpline.GetSegment(lastSegment),
                          0f,
                          localEnd
                      );
        modifiedSpline.SetSegment(segmentCount - 1, segment);
    }

    return modifiedSpline;
}

```

---
Tags: unity, mathematics, curves
---


# Question
Title: How can one replicate the 'Quake Disruptor' of Wipeout XL/2097?
Following my previous question, I am wondering how one can achieve the same effect under Unity?

# The effect in action

https://youtu.be/kzmmLeCwL0g?t=790

# Description of the effect

When you fire the Quake Disruptor weapon, it creates a sine wave that mimics an earth quake, it happens over the next track sections forward to the player ship as you can see on the small video. This results in instant-damage and slowdown to the ships that are caught in the quake.

# Technical challenges

### Deforming the mesh

The function for generating a quake-like wave to apply to each section of the track mesh is easy, e.g. a Gaussian filter will probably be good enough:

https://www.desmos.com/calculator/goasdepcmv

### Applying the deformation to mesh

This is where it starts to get trickier, a track is made out of sections that have few faces, each face being nothing more than a quad.

Here you can see three sections and their faces (wall, track, track, wall):

The challenge in here is how to apply the deformation and yet being able to check collisions against the track (remember that we can't use a mesh collider since it'll be updated in real-time).

I first thought that subdividing the mesh using tessellation would be needed to apply smooth deformations, hence my previous question. However, if you look closely at the video they simply move either edge of faces according to where they're against the 'quake' function being applied to the track mesh.

Here's a link to a video with the best quality, around 13 mins 10 secs:

https://archive.org/details/PSX\_Longplay\_243\_Wipeout\_2097

We're getting closer but we still need to be able to check for collisions.

### Being able to still collide against the track

This is the big question mark, since we cannot update a mesh collider in real-time as it's a CPU hog, I really have no idea on how to address this part of the problem.

This also leads to another problem, since we cannot use a mesh collider, how are physics are going to be handled, by writing a physics system from scratch ?

# Question

How can such effect be achieved under Unity, if possible at all?

PS You will want to remember that the PS1 had a 33Mhz CPU and certainly no mesh collider like the one we can find in Unity, yet they achieved to do it. For sure there is a trick involved but I couldn't figure it out.

# Answer
This effect is almost certainly not achieved by reshaping a mesh collider.

In fact, it's very unlikely Wipeout even used what we'd recognize as a mesh collider for its track. If you have such a constrained problem case, you can use much simpler approaches.

I don't have any information about the game's internals, but I'd suspect they store their track as something a bit more like a spline. If you know a given car's progress "forward" around the racetrack, and a lateral position between the track's left and right edge, you can efficiently evaluate the (collection of) spline(s) at that parameter index to compute the height, bank angle, etc. of the terrain under that point sample.

The fact that the vehicles hover means a point sample is enough - you don't need to simulate a wheeled vehicle rolling until all its wheels are in contact - the banking of the ship can be a purely visual effect as a function of the track's banking and the player's steering.

Now, if we want to add a sine wave, we can literally do exactly that: calculate a sinusoidal function of that same "around the track progress" parameter, and add it to the height we got from the spline. You can do the same with its derivative to bias the calculated slope of the track accordingly.

Now, in Unity, you probably don't want to create your own whole new track physics model just to imitate an older game, so building on a mesh collider is not a bad start.

We can still draw inspiration from the method outlined above, and think of it as an additive force:

Create a kinematic trigger volume to represent the area of effect of your wave, and push it along your track at the desired speed to match the visual progression of the wave (that you're applying in the vertex shader, likely - you could even use this trigger object's transformation matrix as an input to the shader to keep the two exactly in sync). For all bodies touching this trigger, calculate their proximity to the wave shape, and apply a force that pushes them outward, away from the wave surface, proportionate to their proximity.

Or, if your vehicle hover behaviour is based on a raycast at a distance, you could have them detect a raycast intersection with a collider representing a "distortion decal" - if they hit such an object, then instead of using the raycast hit position/distance/normal to determine your hovering force, they instead ask the distortion decal component, "where should I pretend the ground is?" and it can reply using any custom shape function it likes. Then the rest of the hover forces are computed just as though that was the real ground position returned by the raycast - as far as the code downstream is concerned, you really did distort the collider in realtime. It doesn't need to know you just computed an offset with some sinusoidal math. ;)

(The upshot: in games, beware the temptation to believe that what's driving the logical simulation is the same thing you see on the screen as a player - these two things very rarely have much to do with each other in the underlying code/data, and it's an act of delicate choreography that makes them look consistent with one another)
> 1 votes

---
Tags: unity, collision-detection, physics, animation, mesh
---


title: RTS Attack Formation

text:
# Question
Title: RTS Attack Formation
If i select a group of units and send them somewhere i form them like the following;

If i select them and order an attack, i want three things to happen:

1. High range units should keep the distance while attacking.
2. Each unit should attack if possible.
3. Attack formation should not look too unnatural.

Now i can handle the first two by forming the units as a circle by considering the range and unit count etc. But it looks very unnatural.

It's acceptable if some of the units are being idle for some reason, but i want most of the units join attack and they don't look so artificial.

Any ideas on that? Thanks.

# Answer
> 2 votes
A possible approach could be to consider a discrete number of positions on the map.

Then rate each spot on desirability to be at that spot for a certain unit type.

* Crowded spots get rated down.
* Sparse spots get rated up.
* Spots at a good attack distance get rated up.
* Spots too far from, or for archers, too near to, enemies get rated down.

Then let good spots attract units, and bad spots repel units.

With a little luck, they'll spread out appropriately without looking unnatural.

You would have to account for the problem of getting stuck in 'local optima' though.

# Answer
> 1 votes
Some kind of rudimentary rules based swarming system might work. Basically, give each individual in a unit a set of rules, and treat them as individuals, not as a group. The rules though create group/formation behaviors.

For example imagine you wanted a formation of archers to stick together as best as possible, while maintaining range. And an archer can shoot a distance of 20 (of whatever unit you have).

Start with some basic rules like this...

1. Archers should try to maximize their range from target (as close to 20 away, but not beyond)
2. Archers should stay at least 10 units away from the target
3. Archers should not have more than 2 archers between themselves and the target (to avoid overly deep formations).
4. Archers should have at least 3 archers with a distance of \<= 1 (to encourage grouping)
5. If given an order to set up a formation at a given location, archers should set up within 5 units of the destination.

Given an order to set up formation at a certain location, the group of archers will all begin to move to the new location, evaluating their movement (or decision to not move) each time step.

1. Initially, each archer will choose the target deployment spot as their destination.
2. The first archer who reaches this spot will stop, and "deploy".
3. Any time an archers movement destination becomes taken, the archer tries to find a suitable destination that meets rules criteria, and sets that new location as their movement destination.
4. Once set up, all archers continue to check that basic setup rules are in place. If for example the enemy moves too close, archers closest to the enemy will reposition to be farther away.

It would take some tweaking, but if done right you could get some interesting behaviors as a result. Specifically, adding the "no more than 3 archers deep" rule and the "at least 3 archers next to each other" rule will drive some interesting behaviors. I honestly don't know what the result would be of those rules, but it's conceptually a way to start.

You might also have to refine this by having one archer be the leader. Let the leader make initial moves and decisions, and have the others set up based on the leader's decision. The leader might have their own rules for example to pick a new formation location when the formation gets too close to the enemy.

If you search for "rules based flocking model" you'll find a number of references to the concept that go into greater detail.

# Answer
> 1 votes
Right now they're moving until they're at exactly their attack range, and they stand there and shoot. Since they're all the same unity type and all have an equal attack range, they all stand the same distance away.

The simplest way to make them seem more natural is to add something called irregularity. This can be done many ways, but the two that come to mind are: 1) adding irregularity to their attack range or 2) adding irregularity to the distance they travel after coming in range of a target.

1. Adding irregularity to the attack range is the simplest option. Basically, you can set a variable that will act as a small, random increase or decrease to each unit's attack range. This could be done when you create the unit, or could be done each time an attack order is issued. This way when they move to get in range, they'll all have slightly different ranges and thus won't form a perfect circle. The downside to this technique is that if this is a competitive RTS for example, randomly having more or less attack range could be criticized as unfair if its noticeable.
2. The second way you could add irregularity is to add momentum to their movement, so instead of stopping on a dime at the exact attack range, they will come to a stop a small, random amount of time after entering attack range. To implement this, you don't necessarily need to add momentum, just add an extra distance for them to move once entering attack range, but if you already have physics then momentum could look and work well.

With either approach, the attackers will not form perfect circles. The idea is to add a small, adjustable irregularity to their actions that you can tweak until it feels right.

---
Tags: game-mechanics, rts
---


# Question
Title: Operating Expenses of Mathmetic Operations
I understand that math operations require more resources/take longer than others when being computed. *(e.g. square roots take longer than divisions which takes longer than multiplications which takes longer than additions)*

Are there known times for how long specific operations take or methods with which to measure said times? *(I'm guessing no for the former based on the wide variety of hardware that exists. I'm technically looking for measurements related to **Game Maker: Studio 2** if it matters)*

*(P.S. Sorry if the tags for this question are wrong.)*

# Answer
> 1 votes
There aren't known times for mathematics operations that are consistent across all devices, since speeds on each machine will vary, but it is known that certain mathematical operations will always take longer than others. Here is a list of mathematical operations in order from Fastest to Slowest:

* Add / Subtract / Multiply by power of 2
* Divide by power of 2
* Modulo by power of 2
* Multiply
* Divide
* Modulo
* Square root
* System Functions (sin, cos, tan & other library functions like floor & ceil)
* User Functions

This list is derived from how computers perform mathematical operations on a bit by bit level.

Furthermore, certain types of loops are more efficient than others. Here they are listed Fastest to Slowest:

* While
* If
* Fixed / Static function calls
* Switch
* Indirect function calls (virtual or dynamic binding)

If you'd like to test the speed of a particular section of code, put the code in a loop and implement a timer to start before the loop, stop after the loop, and display the total elapsed time. Since computers can do most math so quickly a timer has trouble measuring it, we increase the loop to run many times; hundreds or even thousands of times. This way we can measure the elapsed time in seconds and milliseconds rather than nanoseconds. An operation that is only nanoseconds more efficient by comparison if ran once will be milliseconds or full seconds faster by comparison when ran thousands of times.

For extra info, check out "Big O Notation" and here's a cool sorting visualization.

I am compelled to add two things: 1) get everything working before you try to optimize and 2) use the timer and loop technique (aka build a profiler) or use the game engine profiling tools to identify which areas are slow, rather than guessing. Changing how you're doing mathematical operations will save you very little when it comes to performance. Much larger gains can be achieved by fixing logic, adding LODs to models, less raycasting etc.

# Answer
> 2 votes
You don't measure operations in time, because it only takes a couple of nanoseconds and it changes based on the CPUs clock speed. You should use cycles instead, these generally tell you how many steps it takes for a CPU to do an operation (this is a simplified explanation, but it should get the point across).

Addition and subtraction only generally take 1 or 2 cycles, multiplication takes 2-3, division is 10-20, square root is a ~100, trig functions are a couple hundred (if you want more detail, look into the intel optimization manual). Although these might seem like a lot, given how CPUs run at 4GHz (4 million cycles per second) these days, it's really not a lot.

However, in the case of game maker it's much more difficult to guess. It's not clear whether Game Maker uses an interpreter or compiler nowadays (it has used interpreter in older versions and we don't know whether they changed it since), so let's go with the worst case scenario and say it's an interpreter.

Interpreters (instead of taking your code and converting it to machine code) take your code, divide it into tokens and go through them one by one, executing the necessary operations. These require a large amount of branching and equality checking, so they can't match the speed of compiled programs. It's next to impossible to know how much time they need per operation.

However, since we're still working with modern, fast CPUs, stronger than the combined computing power of the Apollo program and using GPUs to make graphics even faster, if a 2d game maker game starts lagging, you most likely did something wrong. Make sure to not have 2 million particles in each scene.

# Answer
> 1 votes
Generally speaking (i.e. not just GameMaker), there are few ops / scenarios you need to watch out for, in rough order of precedence:

* Cache misses (hard for you tell when this is happening in GM, so don't worry much about this)
* Conditionals, especially deeply nested `if` / `for` / `while` / ternary operator
* Trig functions `sin`, `cos` etc.
* `sqrt`
* Division / Modulus

Multiplication is really not a concern, same for addition and subtraction. Bitwise / logical operators are even cheaper to process, generally.

# Answer
> 0 votes
It boils down to if the algorithm to compute the operator is parallelizable or not, as multiplication is "glorified" addition there is no problem in computing it on different instructions, if you are doing division you need the last operation to go on to the next one so instruction-level parallelism is not so straight forward. Search on SO why is division slower than multiplication.

---
Tags: mathematics, architecture, game-maker
---


title: Get a point inside an ellipse

text:
# Question
Title: Get a point inside an ellipse
So I have a sprite of an ellipse ( it is a 2D game). I would like to get a point inside this ellipse so I can instantiate something. How would I do that? Sprite won’t be changing the scale, so uniform scale.

The point shouldn’t be on the edge and a bit further away from the edge

# Answer
If you know the width and height, then a random, non-uniform value could be obtained, by getting a random angle and a random value between 0 and 1. 1 means the point is at the edge, 0 is at the center. These can be converted into an XY coordinate system using

$$angle = rand() * 2 * \pi$$ $$\lambda = rand()$$ $$x=\frac{cos(angle)\cdot width}{2}\cdot \lambda$$ $$y=\frac{sin(angle)\cdot height}{2}\cdot \lambda$$

Where \\$rand()\\$ returns a random value between 0 and 1.

The problem with this is that i tends to generate more points in the center, since there's less space there.

To solve this, you could instead try to generate a random point in the rectangle that contains the ellipse, check if it's inside the ellipse, if it isn't, try again. It's easy to check if a point lies inside an ellipse. If the point is \\$(x,y)\\$, then

$$d = \sqrt{(2x/width)^2+(2y/height)^2}$$

If \\$d\\$ is less than or equal to 1, it's inside
> 1 votes

---
Tags: unity
---


title: Mathf.Hermite not available in Mathf

text:
# Question
Title: Mathf.Hermite not available in Mathf
I see here that Hermite should be function in the class Mathf.

However, when I try to use it, the compiler tells me that Mathf doesn't contain a definition for Hermite.

This is an example:

```
    float fNewDistance = Mathf.Hermite(_initialDistance, _GoalDistance, fTime);

```

What am I doing wrong here?

Thank you!

# Answer
> 2 votes
It's not available. What you're looking at is `Mathfx`, an extension you can manually add. Create a new script called Mathfx.cs and paste the code in there.

Then call using Mathfx.Hermite

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


# Question
Title: Handling bad network clients using socket.io
Currently I'm working on a MMO game which players can join and exit game whenever they want. I have a connection manager server (CMS) written in golang using socket io library. World connects to CMS and clients connect to CMS and talk to world and world update clients with snapshots of game state. For testing I wrote a client that connects to CMS and act as a player for testing how many clients can my CMS handle. I reach around 80 clients per one core vcpu and 1 gig ram and that's acceptable for my game and resources. I released the game but in real life when there is around 5 or 6 real players and one player with bad network connection joins game it massively take effect the another players game experience. Packets don't receive to another clients or delayed heavily! I believe it's because socket io uses tcp and when a bad network client joins it should send messages many times for client received it completely. How should I overcome this? I know I should used udp for my game but it's too late and I released my game in play store and it got around 700 installs. Is there anyway I can put a time to live like attribute to messages that if client don't received them at a certain time dropped them? Any idea whould be helpful.

# Answer
> 1 votes
> Packets don't receive to another clients or delayed heavily!

Since you didn't provide any definitive information (like your servers update loop or some pseudo-code) i have guess: **Are you (or Socket.io) doing blocking writes to the TCP stream somewhere? Are you sending world updates regardless of whether the client can process them fast enough or not? Are you even checking if your client has received/processed your updates?** Sounds like your server isn't serving the clients asynchronously, either per design or accident, which would explain why a bad client can pull down the whole server.

If you are really running on a half decent VPS (which usually have 100 to 1000 Mbit/s uplink) the network speed would be more than sufficient to handle hundreds to thousands of clients. The network speed surely isn't your root problem, you're probably not even coming close to saturating your VPSes connection.

**It's how your server handles the data distribution that's causing trouble.**

> Any idea whould be helpful.

Stop serving clients when their connection speed drops, I'm not talking about kicking them off, just stop sending them world updates when they are not able to process them. Continue sending them updates once the situation improves!

**If you just keep pushing updates to a client that has connection problems you will pile up heaps of data in the send-buffer of your server.** This will completely saturate the clients connection once it's speed improves. It might even block your server once you pile up enough data, that depends on how socket.io handles this internally.

Remember that when using TCP or other reliable stream-like protocols nothing will be lost, which in turn can lead to data accumulating. This can cause additional latency and bandwidth spikes if not handled well. It will lead to unrecoverable situations if your server does not react to this.

---
Tags: libgdx, networking, socket
---


title: LibGDX input y-axis flipped

text:
# Question
Title: LibGDX input y-axis flipped
I'm writing a game in Java for Android using LibGDX, and I connected my phone so I can test it on it.

I know that LibGDX's render system works different than regular Java systems since the 0,0 coordinate is in the lower-left corner, while in java it usually is in the upper-left corner.

But now I use the touchDown method out of the GestureListener class, it's like the regular Java rendering system: when I obviously tap in the left down corner of my screen, I debug-messaged the coordinates and it says it's Y-coordinate is 475, while I render the object at 0,0.

Is there a way to fix this easily?

# Answer
The problem you are facing is **conversion between two different coordinates systems**: the graphical one and the input one.

## Graphics coordinates

Like you said, libGDX uses a 1 to 1 ratio between space coordinates and pixels, and starts in the bottom left corner. **But it can be anything, really**. That is just the default behavior of libGDX. **You could change the origin of the coordinates system, flip the axis and even scale them**.

Under the hood there is a graphics library called OpenGL. This graphics library will use a transformation matrix in order to draw shapes on the screen. Its default matrix will create the following coordinates system:

So as you can see, we are far away from a pixel-perfect camera.

## Input coordinates

Each hardware can have a different implementation of this, but **the most popular by far is to use the top left corner for the origin and use a 1 unit to 1 pixel ratio**. So when you poll a mouse (or touch) position, *(0,0)* will be top-left, and the position will match screen size in pixels.

## Conversion

What you need to do now is **convert the input coordinate to fit in the graphics space**. In your example, it is quite simple: you only need to take the height of the screen and subtract the Y position of the touch. This will "flip" the Y position, thus giving you the value you wanted:

```
// This will flip the Y value of the touch
graphicsY = screenHeight - touchY;

```

Please note that this will only work if both the graphical and input spaces are the same height. If not, you will need to multiply this value with the ratio of the two spaces:

```
// Here we add the ratio
graphicsY = (screenHeight - touchY) * (graphicsHeight / screenHeight);

```
> 5 votes

# Answer
had a similar problem... figured out that when u draw, pixels start from bottom left, but when u need to obtain position of something, coordinates that you obtain start from top left(in my case). This means that whats for you is the lowest Y, for libgdx its the highest. u need to do something like Gdx.graphics.getHeight()-screenY. Anaways you just need to understand how coordinates work
> 2 votes

---
Tags: java, libgdx
---


# Question
Title: How to make fighting roster actually fair and FEEL fair?
I plan on creating a fighting game in the future, and I'm wondering how to make a roster functionally fair, and feel fair. You see, Super Smash Brothers Ultimate is functionally fair (I think), but at certain times, it doesn't *feel* fair (partially because I suck at the game).

Mario's up smash is one of the few that can't hit people on the lower platforms of battlefield, however, it still feels fair game somehow (up tilt is my guess). However, when playing against Ness, it can *feel* unfair to play because the other player can just spam PK Fire (side special) and then smash attack them at high enough HP. In other words, it is fair, but not fun.

How can I avoid something being spammed feeling unfair when creating a fighting game, and all the other moves of characters feel (and actually be) fair?

# Answer
# Playtesting

A large, commercial game like SSB will go through hundreds if not thousands of hours of playtesting prior to release to tweak the strength, size, duration, etc. of individual attacks to find an approximation of what is 'fair'.

# Balance Passes

A balance pass is a post-release patch which adjusts the relative strengths of characters / attacks / items / etc.; it functions similarly to the tweaks made during playtesting but is usually more drastic and based on observing actual player statistics.

---

# How can you achieve these with your game?

It's unlikely you'll have the time and/or money to do large scale playtesting, but there are a few ways you can make the task easier on yourself:

1. Start small - it will be much easier to balance characters if you add them one-by-one, because you've already got a metric for what 'fair' is with the existing characters.
2. Get friends / family / pets / *anyone else* to test the game from the moment it's playable - the more feedback you have, the more likely you'll get a balanced viewpoint.
3. Collect statistics - when developing your game, make sure you include some functionality to record key stats. The stats that matter to your game may vary, but things like which character wins, average fight duration, most popular / most effective attacks, etc.
> 1 votes

# Answer
An important part to a mechanic feeling fair is the feeling that you (the target) can do something about what's happening. I.e. any mechanic (Ness side special) must have some sort of *counterplay*.

It's a design decision on whether that counterplay is specific or more general - Super Smash Brothers prefers more general counterplay mechanics in dodging and shield to avoid attacks, and falloff to make spamming a single mechanic less effective (as you use an ability more, it does less damage; as you dodge more, dodges provide less invincibility, lock you out for longer, etc). To continue the original example, there are a variety of general counterplay maneuvers to a player using Ness to spam side special and followup with a smash later (in order from general to specific):

* As Ness uses side special, it does less and less damage, so the use is less punishing (every ability has this same mechanic)
* The ability has an animation (as all abilities), which puts a window of vulnerability on Ness (every ability has this same mechanic)
* Side special is dodge-able, though its persistence makes it less good to block. (Mostly generic counterplay)
* Side special is a projectile, so any projectile reflect or absorb abilities will stop it (generic to any projectiles)

So, more generally - to make a fighting roster actually fair, you must include counterplay to any given mechanic. Not necessarily perfect counterplay (all of the above still rely on the receiver being "good enough" to execute on the counterplay strategies), but some counterplay.

To make a roster *feel* fair, you must make counterplay strategies *accessible*. It's one thing to have dodging/blocking/projectile reflection in the game, it's another thing for those mechanics to be available. If you can dodge an ability but the game never tells you that "dodge" is an action (or how to do it), then it's not an accessible counterplay mechanic. There are a variety of ways to make mechanics accessible, for example:

* A tutorial can go a long way in showing players mechanics and how to use them
* Help pages to refresh memory on what mechanics exist without having to replay the tutorial and learning how to walk again. A tutorial that's setup in steps that are each individually replayable can assist this as well.
    + i.e. a help page detailing "this is a dodge, this is what it does and how to use it \[with a short video to help players recognize times they've dodged or enemies have dodged\]", and then a playable exercise to show off dodging and give specific practice
* Periodic random tips noting counterplay mechanics, or the ins-and-outs of them can be really helpful
    + A tip saying "dodges exist" isn't great (though depending on genre and target audience, a tip saying "If you're being hit too much, try dodging!" could go over well)
    + A tip mentioning that "Y character's X ability can't be dodged, but blocks are effective!" reminds the player to dodge, reminds the player to block, and gives the player insight into how they should be countering another specific instance.
* Even using the "show don't tell" method can work well with this - if you have AI's make full use of the counterplay mechanics you expose, that can help players realize what those are and how to use them (you start realizing how good dodging can be if you're doing something and the enemy AI is dodging it constantly).
> 1 votes

---
Tags: game-design, balance, combat, psychology, fighting-game
---


# Question
Title: Vertical camera rotation has reduced speed & range when looking at the character from the left or right
I completed a camera tutorial for Unity. I can rotate a camera around my figure around the Y axis (Vector3.up) and I wanted to extend that for a Fixed-Free 3rd Person camera (What are the types of 3rd-person camera called?) where I can tilt aswell but I am stuck with the wrong rotation.

I expect the camera to go up/down whenever I use the joystick up/down and always go left/right when I use the joystick left/right.

But instead of that I get always left/right movement as I wish but up/down is only working at the center. The further I go left or right (see images) the less I go up/down. This sounds super complicated, please see the images. I want the same behaviour as shown when the camera is behind the object and I want to avoid the behaviour at the right side like in the first image.

Bonus would be if I can limit the up and down movement to say 160° so the player can't look top down.

The Code looks like this (only RotateCamera() and UpdateCameraPosition() are relevant):

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

public class PlayerCamera : MonoBehaviour
{
    [System.Serializable]
    public class InputSettings : System.Object
    {
        public float inputThreshold = 0.1f;
        public string VERTICAL_AXIS = "CameraVertical";
        public string HORIZONTAL_AXIS = "CameraHorizontal";
        public string LOCK_TARGET_PYRAMID = "LockToPyramid";
        public string LOCK_TARGET_AREA = "LockToArea";
    }

    [SerializeField] private Transform target;
    [SerializeField] private float cameraSpeed = 2;
    [SerializeField] private Vector3 lookAtPlayerOffset = new Vector3(0f, 0.6f);

    private PlayerController playerController;
    private float cameraHorizontal, cameraVertical;
    private float lockPyramid, lockArea;
    private InputSettings inputSettings;
    private Vector3 cameraPlayerOffset;

    void Start()
    {
        SetCameraTarget(target);

        inputSettings = new InputSettings();
        cameraPlayerOffset = transform.position - playerController.transform.position;
    }

    private void Update()
    {
        GetInput();
    }

    private void LateUpdate()
    {
        RotateCamera();
        UpdateCameraPosition();
    }

    private void RotateCamera()
    {
        Quaternion cameraRotationXDelta = Quaternion.AngleAxis(cameraHorizontal * cameraSpeed, Vector3.up);
        Quaternion cameraRotationYDelta = Quaternion.AngleAxis(cameraVertical * cameraSpeed, Vector3.right);

        // this does not work how I wish it would after rotating around a bit
        cameraPlayerOffset = cameraRotationYDelta * cameraRotationXDelta * cameraPlayerOffset;

    }

    private void UpdateCameraPosition()
    {
        // prevent camera from clipping through floor
        Vector3 newPos = playerController.transform.position + cameraPlayerOffset;
        newPos.y = newPos.y < 0.2f ? newPos.y = 0.2f : newPos.y;
        transform.position = newPos;
        transform.LookAt(target.transform.position + lookAtPlayerOffset);
    }

    private void GetInput()
    {
        cameraHorizontal = Input.GetAxis(inputSettings.HORIZONTAL_AXIS); // interpolated
        cameraVertical = Input.GetAxis(inputSettings.VERTICAL_AXIS); // interpolated

        lockPyramid = Input.GetAxis(inputSettings.LOCK_TARGET_PYRAMID); // interpolated
        lockArea = Input.GetAxis(inputSettings.LOCK_TARGET_AREA); // interpolated
    }

    private void SetCameraTarget(Transform targetTransform)
    {
        target = targetTransform;

        if (target != null)
        {
            if (target.GetComponent<PlayerController>())
            {
                playerController = target.GetComponent<PlayerController>();
            }
            else
            {
                Debug.LogError("The camera's target needs a player character controller.");
            }
        }
        else
        {
            Debug.LogError("Your camera needs a target");
        }
    }
}

```

# Answer
This line rotates the camera around the **world** X axis (`Vector3.right`):

```
Quaternion cameraRotationYDelta = Quaternion.AngleAxis(cameraVertical * cameraSpeed, Vector3.right);

```

So when your camera's offset from the character is close to perpendicular to the world X axis, you rotate in a wide circle around that axis when rotated by the line above.

As your camera offset direction swings toward the world X axis, it starts tracing out a narrower and narrower cone around that axis.

At the limit, when your camera is directly to the left or right of your character, this rotation produces no change in position at all: points on the rotation axis remain fixed no matter how great the angle of rotation.

Instead, you probably want to rotate about the camera's X axis (`transform.right`). This ensures the rotation axis runs left-right relative to what the player sees on screen in the current camera orientation, rather than with regard to the fixed world coordinate system.
> 0 votes

---
Tags: camera, quaternion
---


# Question
Title: Can we flip znear and zfar so that positive z values increase away from the viewer?
I am confused about the projection matrix in OpenGL.

i have a habit of writing the code as follows.

```
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if(w<=h)
   glOrtho(0.0f,250.0f,0.0f,250.0f*h/w,1.0,-1.0);
else
   glOrtho(0.0f,250.0f*w/h,0.0f,250.0f,1.0,-1.0);
 glMatrixMode(GL_MODELVIEW);
 glLoadIdentity();

```

Simple, This code sets the viewing clipping region that maintains the equal width and height. negative z value points away from the viewer. as z value extends from 1 to -1. anything that lies outside this value wont be visible to the user. But i have seen the code like this.

```
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(left,right,bottom,top,1.0, 500.0);  //how????
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0f, 0.0f, -250.0f);       ///?????
glutSolidSphere(15.0f,15,15);           /// how is this visible on the screen
}

```

Please help me understand this code. As from my point of view the z value is totally flipped near is 1.0 its okay but zfar is 500 and following that code there is a translation of z value to -250. and drawing that sphere will be visible on the screen how? My question is can we flip znear and zfar so that positive z value will go away from the viewer.

# Answer
In the second piece of code, I can't tell what you're unsure of, so I'll go through all the lines you have commented.

* The `glOrtho` call appears to be made with predefined variables to avoid using magic numbers.
* The `glTranslatef` call will move the origin 250 units into the scene, since by default, the coordinate system points outward. However, from the rest of your post it appears you already knew this, so I'm unsure of what to make of this comment.
* The `glutSolidSphere` call just puts a sphere at the origin of the scene. Since the origin was just moved 250 units into the scene, the sphere appears at \[0, 0, -250\] relative to the camera.

(I'd like to emphasize that I have very little experience with OpenGL, so if someone sees something wrong with the above explanation, please comment or edit!)

As for the rest of your question, I suspect you want to use `glScalef(1.0, 1.0, -1.0);` to reflect your coordinate system across the XY plane.
> 1 votes

---
Tags: opengl, projection, glut
---


title: Memory dataflow for uniform variables?

text:
# Question
Title: Memory dataflow for uniform variables?
When a texture (2D) is supplied to a shader as a 'uniform' input, it is first uploaded to OpenGL using glTexImage2D() and then using glUniform1i() it is associated to shader uniform.

eg code :

**Texture data**

`glTexImage2D()`: is used to transfer texture data to the server side

`glGetUniformLocation()`: is used to access shader uniform handle

`glUniform1i()`: associates the data pointed by texture unit to the shader 'uniform'

but when we pass matrix (eg matrix4x4) to a shader as a 'uniform' input, when don't use any specific function to upload it to OpenGL.

(we just used to glUniform..() to associate the data with the shader input which we also used in the case of texture data)

**Matrix data**

`glGetUniformLocation()`: to access shader uniform handle

`glUniformMatrix4fv()`: to associate matrix data to the shader uniform input.

**Where does the matrix data live in each step in the process of passing it to a shader as a uniform input?**

* Does matrix data always live on client side/ CPU accessible memory and fetched every frame by server side?
* If it is uploaded to OpenGL:

+ which step/function call uploads the data?
    + where does the data live in OpenGL memory?
    + how its memory location is pointed?

# Answer
> 1 votes
The matrix data is "uploaded" using `glUniformMatrix4fv`.

The data lives wherever the OpenGL driver wants it to be. The data is written to the shader's uniform data storage. That can be in GPU memory only, held in CPU memory until a draw call is issued at which point the GPU fetches the data from CPU memory, the data could be put in the command queue for the GPU to store before running the shader, or any other method.

Shaders most likely have a block of memory for its uniforms that the GPU loads into it's shader cores local memory/registers when the shader is ran, or the GPU driver could inline the values right into the shader code, or a mix. It's really up to the driver and GPU architecture.

Conceptually, the glUniformMatrix4fv() data (and the other uniforms) are written to the shader. That data/settings stays with the shader.

Texture samplers are different. You don't write a pointer to the texture in the shader. What you set in the shader is the index of which hardware sampler is being used for the shader's named/abstracted samplers.

And configure the hardware sampler(s) to use a specific texture as a separate operation, not associated with the shader object: You change the shader and the textures stay configured in the sampler units as it was, but that shader can be set to use sampler unit 3 instead of unit 0.

The client/server language in OpenGL is a bit confusing and in practice isn't really how it is implemented anymore (and drivers themselves sometimes get it wrong) but you can change "client" for "application" and "server" for "OS+GPU+driver" side and it's a bit closer to current implementations.

In practice, often, both the application (client) and the driver (server) keeps copies of data to speed things up (eg: for table look ups and merging data updates to send in bulks).

---
Tags: opengl
---


# Question
Title: Procedurally create a polygonal shape filled with texture in unity 2d
I want to **procedurally** create a polygonal shape filled with texture in unity 2d (no 3d meshes). Something that looks like this: https://www.conceptdraw.com/How-To-Guide/picture/landscape-plan/Building-Plans-Landscape-Garden-Design-Elements-Roofs.png

As you can see roofs can be rectangles, but also any polygonal shapes.

Can it be done in vanilla unity 2d? Or should I rely on 3rd party libraries and if so which one would fit best?

p.s. I will most likely overlay that object with PolygonCollider2d for physics

# Answer
Sprite shapes

They allow you to create adbitary polygons filled in with sprites. You can also make the edges different based on the angle.

They've been built into Unity for a a year or so.
> 2 votes

---
Tags: unity, 2d
---


title: Orbital rotation equation

text:
# Question
Title: Orbital rotation equation
I am developing a space sandbox (3D). Now I am working on an asteroid belt around a planet. I have an `Asteroid` class and an `AsteroidBelt` class that has a collection of the `Asteroid` instances. Each `Asteroid` object is placed randomly during initialization.

Asteroid class:

```
Matrix4 transform;
double angle;
float x, y, z;
Vector3 initPosition;

public Asteroid(ModelObject object, Texture diffuseTex){

    initPosition = new Vector3(
            MathUtils.random(-Settings.RingsDepth, Settings.RingsDepth), //x
            MathUtils.random(-.5f, .5f), //y
            MathUtils.random(-Settings.RingsDepth, Settings.RingsDepth)); //z
}

public void update(Camera camera){

    angle += Settings.RingsRotationalSpeed;
    if(angle>360) angle=0;
    if(angle<0) angle = 360;

    double angleRad = angle * MathUtils.degreesToRadians;

    x = (float) (Math.sin(angleRad) * Settings.RingsRadius  + initPosition.x);
    y = initPosition.y;
    z = (float) (Math.cos(angleRad) * Settings.RingsRadius + initPosition.z);

    transform.idt();
    transform.translate(x, y, z);
}

```

The code above works correctly, but it doesn't allow to rotate the asteroid belt around a planet. How to modify x, y, and z to rotate the asteroid belt around a planet freely? I hope the illustration below will clarify my problem:

Now the asteroid belt looks like below:  But I need to rotate it from -90 to 90 degrees by X and Y axis:    Any help will be appreciated!

# Answer
LibGDX allows us to get rid of complex mathematics. I've solved my issue by using `Matrix4` class:

Asteroid class:

```
Vector3 position;
Matrix4 rotationMatrtix;

public void update(Camera camera){

    angle += Settings.RingsRotationalSpeed;
    if(angle>360) angle=0;
    if(angle<0) angle = 360;

    double angleRad = angle * MathUtils.degreesToRadians;

    x = (float) (Math.sin(angleRad) * Settings.RingsRadius  + initPosition.x);
    y = initPosition.y;
    z = (float) (Math.cos(angleRad) * Settings.RingsRadius + initPosition.z);

    position.set(x, y, z);

    //rotate asteroid around X-axis
    rotationMatrtix.setToRotation(Vector3.X, Settings.RingsXRotation);
    position.mul(rotationMatrtix);

    //rotate asteroid around Z-axis
    rotationMatrtix.setToRotation(Vector3.Z, Settings.RingsZRotation);
    position.mul(rotationMatrtix);

    transform.idt();
    transform.translate(position);
}

```

Don't forget to create instances of the `position` and `rotationMatrtix`
> 0 votes

---
Tags: opengl, java, libgdx, 3d, mathematics
---


title: Overlapping Ovals

text:
# Question
Title: Overlapping Ovals
So I am instantiating 2 ovals/ellipses at runtime with random rotations. The first oval will always be spawned at the center. However, the second oval must be placed in a way that should always intersect/overlap the first oval, something like a Venn Diagram. How would I do so? We are talking 2D and the ovals are sprites

# Answer
> 1 votes
If you know the length of the distance from the middle of the sprite to the closest point on the outside of the oval (which can either be guessed and then adjusted or produced mathematically), then a reasonable approximation for the second ovals location would be `new Vector2(oval1minDist + oval2minDist - offset, 0)`, where offset is a small but not negligible value. This ensures your ovals will always overlap by at least `offset` pixels. However, this solution doesn't account for the case where the ovals are long and skinny, in which case the ovals may form a cross.

---
Tags: unity
---