title: Twin-stick backwards tank movement

text:
# Question
Title: Twin-stick backwards tank movement
I'm creating a 3D twin-stick tank game in Godot with C#. I have created the tank movement and rotation, separate of its turret, and it seems to be working properly.

The issue: I want the body of the tank to rotate in the direction which is closest to the tank's current rotation, and more specifically, even when that is backwards relative to the body of the tank itself. Currently, the "animation" is flipping around a full 180 degrees (or Pi radians), when suddenly moving the tank from left to right, or from up to down.

The following snippet is from my `Rotator` `Node3D` class:

```
public override void _PhysicsProcess(double delta)
{
    // TODO: Implement driving backwards, because tanks shouldn't suddenly rotate all the way around.

    var angle = _input.AngleTo(Vector2.Up);
    Rotation = Rotation with { Y = Mathf.LerpAngle(Rotation.Y, angle, _rotationSpeed * (float)delta) };
}

```

The input vector is a Vector2D that is based on the left-stick, or WASD movement.

For completeness, but not very relevant, here's the movement (from my `Mover` `Node3D` class) logic itself:

```
public override void _PhysicsProcess(double delta)
{
    Position += new Vector3(_input.X, 0, _input.Y) * _movementSpeed * (float)delta;
}

```

This GIF showcases the issue, I don't want the tank to suddenly turn around, but simply drive backwards. Do you have any pointers (or even an implementation) to help me figure this out?

# Answer
Someone on the Godot Discord helped me out, and told me to store the previous input vector and compare it to the current one. Then, if they are pointing in opposite directions (`dot product < 0`), invert the resulting vector.

Here is the resulting implementation:

```
private Vector2 _input;
private Vector2 _previousInput;
private bool _driveBackwards;

public override void _PhysicsProcess(double delta)
{
    if (_input.Dot(_previousInput) < 0)
    {
        _driveBackwards = !_driveBackwards;
    }

    var angle = _input.AngleTo(_driveBackwards ? Vector2.Down : Vector2.Up);
    Rotation = Rotation with { Y = Mathf.LerpAngle(Rotation.Y, angle, _rotationSpeed * (float)delta) };

    _previousInput = _input;
}

```

As a bonus, I made the rotation linear. Also, I limited the final rotation to tau (the full unit circle), because it kept increasing when rotating in one direction:

```
private static double LerpLimitedLinearAngle(double from, double to, double weight)
{
    const double destinationWeight = 1d;
    var destinationAngle = Mathf.LerpAngle(from, to, destinationWeight);
    var linearAngle = Mathf.Clamp(destinationAngle, from - weight, from + weight);
    var limitedAngle = linearAngle % Mathf.Tau;
    return limitedAngle;
}

```

Which is called with:

```
var newRotation = LerpLimitedLinearAngle(Rotation.Y, angle, _rotationSpeed * delta);

Rotation = Rotation with { Y = (float)newRotation };

```

Now it looks like this:
> 2 votes

---
Tags: mathematics, vector, godot
---


# Question
Title: Static Niagara System for fire on a torch
I'm building a Niagara System for fire and smoke that would be placed on a torch when it's lit. While smoke works just fine when it's static, when I move the camera (and so the torch itself moves too) the smoke is always far behind the torch. I understand it makes sense from physics perspective, but for the purpose of my game I need the smoke to be static on top of the torch, so I want all particles to always be vertically above the torch.

Is there a way to turn off inertia (for lack of a better term) on particles? Or probably I should use another approach for my problem?

# Answer
> 1 votes
With a suggestion from @dmgregory I found a solution: Local Space makes particles relative to the emitter origin. It is located under Niagara Overview Node's properties -\> Emitter \> Local Space.

---
Tags: unreal, particles, unreal-5
---


# Question
Title: Changing the scale of a character and speed to match the perspective of a 2D background while traveling along the Y axis
I am making a 2D point and click game, just for fun.

I want to create some sense of perspective, so I am trying to change the scale of the player as he travels along the Y axis. Obviously, the speed has to change as well (far: moves slow - near: moves faster) to help creating the feeling of perspective.

Here is a GIF of the player moving and changing the scale/speed with my current set-up:  Is there a math formula to calculate the scale of the character as it travels along the Y axis? And for the speed?

At the moment I am doing:

For scale (**ScaleOffset** is a value set by every scene, trying to match the perspective manually) :

```
while (path.Count() > 0)
{
    var distanceBetweenPoints = lastPosition.DistanceTo(path[0]);
    if (distance <= distanceBetweenPoints)
    {
        Position = lastPosition.Lerp(path[0], (float)distance / distanceBetweenPoints);
        Scale = new Vector2( Scale.Y - ((lastPosition.Y - Position.Y) / ScaleOffset), Scale.Y - ((lastPosition.Y - Position.Y) / ScaleOffset) );
        return;
    }
    distance -= distanceBetweenPoints;
    lastPosition = path[0]; path.RemoveAt(0);
}
Position = lastPosition;

```

For speed:

```
if (speed > max_speed * Scale.X)
{
    speed = max_speed * Scale.X;
}

```

I know it's not the right thing, but it looks better than without it. However, I want to understand and find the right way to do this.

Am I being crazy? Should I just make the background 3D in order to avoid doing all this jazz? I believe many point and click games do this. An example can be Broken Sword 5 (here you can see the characters moving along the Y axis on a 2D background, changing size and speed https://youtu.be/St\_i74zG\_ac?si=JcWNkNykjYaaCRae&t=13675)

# Answer
You have the correct idea.

It might be easier to manage if you define the scale at two different points and interpolate/extrapolate it.

For example, if you know that \\$Y\_1\\$ the scale should be \\$S\_1\\$, and at \\$Y\_2\\$ the scale should be \\$S\_2\\$, then you can figure out where your \\$Y\\$ is relative to those:

$$P(Y) = \frac{Y - Y\_1}{Y\_2 - Y\_1}$$

Here \\$P(Y)\\$ should be \\$0\\$ when \\$Y = Y\_1\\$, and \\$1\\$ when \\$Y = Y\_2\\$, it will be a value in between \\$0\\$ and \\$1\\$ if \\$Y\\$ is between \\$Y\_1\\$ and \\$Y\_2\\$ and it might extend beyond those bounds with either negative numbers (less than \\$0\\$) or numbers greater than \\$1\\$.

And now we use that as weight to lerp the scale:

$$S(Y) = S\_1 + (S\_2 - S\_1)P(Y)$$

Then you need to figure out the correct scale for two different points on the plane, and with that you can have the scale anywhere on the plane.

---

And yes, you could do the same thing for speeds. In fact, since speed is distance over time, and time is not affected by this transformation, the relative change is size on one axis (i.e. the scale factor on one axis) should match the relative change in speed. Thus multiplying the original speed by one axis of the current scale to get the current speed is correct.

---

Should you do this in 3D? I do not know. Certainly 3D would solve some other issues, but might make some things harder to work with (e.g. rotations). Aesthetically it can look the same (e.g. you can make a 3D scene, with 3D physics, but use billboards/3D sprites to have look exactly the same as you have, and using the same textures), but the workflow will be different, and not knowing the scope of your game and your experience with 3D, it is hard for me to judge if using 3D is better for you.
> 1 votes

---
Tags: 2d, godot, perspective
---


# Question
Title: Please explain this matrices interpolation code
```
int rate,frac;
sint16 *frmptr[2];

frac = GetFrames(item, frmptr, &rate);

```

```
int GetFrames( ITEM_INFO *item, sint16 *frmptr[], int *rate )
{
    int first;
    int interp;

    // frm - current frame (for example 30 fps, its means one frame from 30)
    // rat - ratio for current animation for example 4

    //get pointer to current frame (start of position and rotation data)
    frmptr[0] = frmptr[1] = anim->frame_ptr;

    first =  frm/rat;
    interp = frm%rat;

    //take this frame
    frmptr[0] += first * frame_size;
    //take next frame
    frmptr[1] = frmptr[0] + frame_size;

    *rate = rat;

    //increase frame counter
    frm++;

    return interp;

}

```

Get position x1, y1, z1 and rotation xr1, yr1, zr1 from frmptr\[0\];

Get position x2, y2, z2 and rotation xr2, yr2, zr2 from frmptr\[1\];

Compose two matrices m1 and m2 correspond to position 1,2 and rotation 1,2.

Then interpolate two matrices. Matrices are colmajor.

```
sint32  *phd_mxptr; /* matrix pointer....*/
sint32  *IMptr;

enum msoff { M00,M01,M02,M03,
     M10,M11,M12,M13,
     M20,M21,M22,M23 };

void    InterpolateMatrix( void )
{
    sint32  *mptr,*iptr;
    sint32  frac,rate;

    //first matrix for interpolation m1
    mptr = phd_mxptr;

    //second matrix for interpolation m2
    iptr = IMptr;

    if ( rate==2 || (frac == 2 && rate == 4))                       // If interpolating Odd Frames
    {                                           // then do simple case
        *(mptr+M00) = (*(iptr+M00) + *(mptr+M00)) >> 1;
        *(mptr+M01) = (*(iptr+M01) + *(mptr+M01)) >> 1;
        *(mptr+M02) = (*(iptr+M02) + *(mptr+M02)) >> 1;
        *(mptr+M03) = (*(iptr+M03) + *(mptr+M03)) >> 1;

        *(mptr+M10) = (*(iptr+M10) + *(mptr+M10)) >> 1;
        *(mptr+M11) = (*(iptr+M11) + *(mptr+M11)) >> 1;
        *(mptr+M12) = (*(iptr+M12) + *(mptr+M12)) >> 1;
        *(mptr+M13) = (*(iptr+M13) + *(mptr+M13)) >> 1;

        *(mptr+M20) = (*(iptr+M20) + *(mptr+M20)) >> 1;
        *(mptr+M21) = (*(iptr+M21) + *(mptr+M21)) >> 1;
        *(mptr+M22) = (*(iptr+M22) + *(mptr+M22)) >> 1;
        *(mptr+M23) = (*(iptr+M23) + *(mptr+M23)) >> 1;
    }
    else if (frac == 1)
    {
        *(mptr+M00) += (*(iptr+M00) - *(mptr+M00)) >> 2;
        *(mptr+M01) += (*(iptr+M01) - *(mptr+M01)) >> 2;
        *(mptr+M02) += (*(iptr+M02) - *(mptr+M02)) >> 2;
        *(mptr+M03) += (*(iptr+M03) - *(mptr+M03)) >> 2;

        *(mptr+M10) += (*(iptr+M10) - *(mptr+M10)) >> 2;
        *(mptr+M11) += (*(iptr+M11) - *(mptr+M11)) >> 2;
        *(mptr+M12) += (*(iptr+M12) - *(mptr+M12)) >> 2;
        *(mptr+M13) += (*(iptr+M13) - *(mptr+M13)) >> 2;

        *(mptr+M20) += (*(iptr+M20) - *(mptr+M20)) >> 2;
        *(mptr+M21) += (*(iptr+M21) - *(mptr+M21)) >> 2;
        *(mptr+M22) += (*(iptr+M22) - *(mptr+M22)) >> 2;
        *(mptr+M23) += (*(iptr+M23) - *(mptr+M23)) >> 2;
    }
    else
    {
        *(mptr+M00) = *(iptr+M00) - ((*(iptr+M00) - *(mptr+M00)) >> 2);
        *(mptr+M01) = *(iptr+M01) - ((*(iptr+M01) - *(mptr+M01)) >> 2);
        *(mptr+M02) = *(iptr+M02) - ((*(iptr+M02) - *(mptr+M02)) >> 2);
        *(mptr+M03) = *(iptr+M03) - ((*(iptr+M03) - *(mptr+M03)) >> 2);

        *(mptr+M10) = *(iptr+M10) - ((*(iptr+M10) - *(mptr+M10)) >> 2);
        *(mptr+M11) = *(iptr+M11) - ((*(iptr+M11) - *(mptr+M11)) >> 2);
        *(mptr+M12) = *(iptr+M12) - ((*(iptr+M12) - *(mptr+M12)) >> 2);
        *(mptr+M13) = *(iptr+M13) - ((*(iptr+M13) - *(mptr+M13)) >> 2);

        *(mptr+M20) = *(iptr+M20) - ((*(iptr+M20) - *(mptr+M20)) >> 2);
        *(mptr+M21) = *(iptr+M21) - ((*(iptr+M21) - *(mptr+M21)) >> 2);
        *(mptr+M22) = *(iptr+M22) - ((*(iptr+M22) - *(mptr+M22)) >> 2);
        *(mptr+M23) = *(iptr+M23) - ((*(iptr+M23) - *(mptr+M23)) >> 2);
    }
}

```

In this example used fixed point math.

I dont understand process interpolation of matrices - 3 cases from InterpolateMatrix() function. Please explain.

# Answer
This is more a less a component-wise interpolation of 2 matrices of integers using some binary hacks to optimize divide by 2 and divide by 4. You can rewrite the 3 cases like this:

1. `(A + B) >> 1` =\> `(1/2 * A) + (1/2 * B)`
2. `B + (A - B) >> 2` =\> `(1/4 * A) + (3/4 * B)`
3. `A - (A - B) >> 2` =\> `(3/4 * A) + (1/4 * B)`

So it's splitting the interpolation in 3 cases each 25% along the linear interp of the 2 matrices.

From the looks of it this an attempt to inerpolate position/rotation matrices, and while the positional component will work relatively fine this is not a correct way to interpolate rotation matrices. It might be good enough for an extremely performance-critical application though.

To do it correctly the easiest way is to convert the rotation to a quaternion and then using a slerp operation.
> 2 votes

# Answer
Shift on 1 = division on 2 (i.e. 0.5). Shift on 2 is division on 4 (i.e. 0.25)

Key is this part of code:

```
    first =  frm/rat;
    interp = frm%rat;

```

For example we do count the frame each time. And now number frame is 8 (totaly could be 30 fps - frame per second). And Frame Rate = 4.

For example currect frame is 8. i.e. frm = 8. Then:

```
int first = 8/4 = 2;
int interp = 8%4 = 0;

```

For example the current frame frm= 9:

```
int first = 9/4 = 2;
int interp = 9%4 = 1;

```

And next frame is 10:

```
int first = 10/4 = 2;
int interp = 10%4 = 2;

```

And next frame is 11:

```
int first = 10/4 = 2;
int interp = 10%4 = 3;

```

And for example next frame is 12:

```
int first = 12/4 = 3;
int interp = 12%4 = 0;

```

Four frames first variable stays 2 and four frames interp variable is 0,1,3.

The first case:

```
if ( rate==2 || (frac == 2 && rate == 4))

       // If interpolating Odd Frames
    {

```

If frac == 2 i.e. first 8 + interp 2 = 10 - it's half of frame (Frame Rate = 4 i.e. half of frame = 2) then we do interpolation:

m1 = (m2 + m1) * 0.5;

Second case:

```
else if (frac == 1)
{
m1 = m1 + (m2 - m1) * 0.25;

```

if frac == 1 i.e. 1 of 4 = 0.25, i.e. 1/4 = 0.25:

And third case obviously frac == 3 i.e. 3 (third) part of 4 (four) = 3/4 = 0.75, i.e. from m2 - 0.25 of(m2- m1):

```
else // if (t == 0.75)
  {
    m1 = m2 - (m2 - m1) * 0.25; // = lerp(m1, m2, 0.75)
  }

```

As result we can do so:

```
if(frac == 2) //i.e. 0.5 (2 of 4)
{
    //matrix interpolation
}
else if(frac == 1) //i.e. 0.25 (1 of 4)
{
    //matrix interpolation
}
else // if(frac == 3) i.e. 0.75 (3 of 4)
{
    //matrix interpolation
}

```

I.e. it is my answer:

```
if (t == 0.5)
  {
    m1 = (m2 + m1) * 0.5; // = lerp(m1, m2, 0.5)
  }
  else if (t == 0.25)
  {
    m1 = m1 + (m2 - m1) * 0.25; // = lerp(m1, m2, 0.25)
  }
  else // if (t == 0.75)
  {
    m1 = m2 - (m2 - m1) * 0.25; // = lerp(m1, m2, 0.75)
  }

```

Shorterner case of code above in my question is:

```
matrix4x4 m1, m2;

    if ( rate==2 || (frac == 2 && rate == 4))
    {
        m1 = (m2 + m1) >> 1;
    }
    else if (frac == 1)
    {
        m1 = m1 + (m2 - m1) >> 2;
    }
    else
    {
        m1 = m2 - (m2 - m1) >> 2;
    }

```
> 0 votes

---
Tags: c++
---


# Question
Title: Accessing an Animation Blueprint C++ class from a Character C++ class
This is my first leap out of tutorials and building my own game so bear with me. I've been struggling with getting C++ classes to work with one another and accessing Unreal blueprints from my code.

I currently have the Action Bound and logic required for an "attack action" in my Character C++ class. I want to access the C++ UAnimInstance class that I created and is currently parenting my Animation Blueprint for my character so that I can change a bool variable within it - this bool is a requirement in my state machine to begin the attack animation.

How do I access one class from another?

***What I Have Tried:***

MainCharacter.h:

```
UCLASS()
class SQUEEGLESADVENTURE_API AMainCharacter : public ACharacter

private:
    class UABP_MainGoblin* GoblinClass;

```

MainCharacter.cpp

```
void AMainCharacter::IceAttack()

{

  GoblinClass->bIceAttack = true;

}

```

I'm getting error "Pointer to incomplete class type "UABP\_MainGoblin" is not allowed.

# Answer
For anyone who comes across this, I did not find an answer per say.

But, I did find a work around.

I put the logic in my C++ class for the MainCharacter, then exposed a bool variable to blueprints in that class, and then changed that bool based on my C++ logic.

Then, in the event graph of the Animation Blueprint for that character in the engine, I got hold of the MainCharacter class and called that bool variable I had set in the code. Then I used that bool reference to set a new bool I created in the animation blueprint - which I can now use in my ABP\_MainCharacter.

So in a round about way, the code is in my Character.cpp and it is setting the bool value that is being used in my character's animation. Likely not the most optimal way to do it (or explain it) but hey, sometimes it's just about what works.

Hope this helps someone!
> 0 votes

---
Tags: c++, unreal
---


# Question
Title: "Button is not an attribute class" error when integrating Steam achievements
I am writing the code for my button, but it's giving me errors like this:

> Assets\Scripts\SteamIntegration.cs (60, 6): 'Button' is not an attribute class

Where did I make a mistake in this code?

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

public class SteamIntegration : MonoBehaviour
{
    public Button button;

    void Start()
    {
        button.onClick.AddListener(() => {
        });

        try
        {
            Steamworks.SteamClient.Init(/*AppID here*/);
        }
        catch (System.Exeption e)
        {
            Debug.Log(e);
        }
    }

    // ...
    [Button]
    public void IsThisAchievementUnlocked(string id)
    {
        var ach = new Steamworks.Data.Achievement(id);
        Debug.Log($"Achievement {id} status: " + ach.State);
    }

    [Button]
    public void UnlockAchievement(string id)
    {
        var ach = new Steamworks.Data.Achievement(id);
        ach.Trigger();

        Debug.Log($"Achievement {id} unlocked");
    }
}

    [Button]
    public void ClearAchievementStatus(string id)
    {
        var ach = new Steamworks.Data.Achievement(id);
        ach.Clear();

        Debug.Log($"Achievement {id} cleared");
    }

```

# Answer
When you put a word in square brackets before a type, variable, or method declaration, that's called an Attribute.

Attributes are special classes that annotate the declaration with metadata and can be used via reflection as hints for code generation, serialization, or drawing appropriate controls in Inspector UI. For example, when you write `[Range(0, 1)]` over a public or serialized float variable, that signals to the Unity inspector to draw that field as a slider instead of just a numeric input box. The `RangeAttribute` class is the one that stores this metadata about the field.

When you write `[Button]` above a method, the compiler is going to look for a class named `Button` or `ButtonAttribute` that can be used as an attribute to annotate that method. It searches the namespaces you've imported with your `using` statements at the top of the file.

In this case, the only `Button` it can find is `UnityEngine.UI.Button`, and that's descended from `UnityEngine.Component`, not `System.Attribute`. So the compiler is telling you that you cannot use this class as though it were an attribute, when it isn't one.

Maybe you meant to refer to a different thing *also* named `Button`? If so, it's likely that it's in a different namespace, and you need to import that namespace with `using Somenamespace;` or specify the exact path to it, like `[SomeNamespace.Button]` instead of the unqualified `[Button]` each time you use it.

If you go the `using` route, you may need to disambiguate, something like...

```
using UIButton = UnityEngine.UI.Button;
using InspectorButton = Somenamespace.ButtonAttribute;

```

...ensuring you can unambiguously refer to the two similarly-named types with distinct names of your choosing.

Or these attributes might have been added in error. Maybe you copied them from an example where someone was using a library similar to this one to add clickable buttons in the Inspector for the component, but that library is not a part of your project at the moment. If you want this functionality, you'll need to include the library and update your references to its namespace/attributes as above.

Or, if you don't want this functionality, you can simply delete the `[Button]` lines to clear this error.
> 2 votes

---
Tags: unity, c#, unity-ui, steam, achievements
---


# Question
Title: How to save and instantiate game data containing lists of polymorphic types
Let's say I have a class named `Entity` such as:

```
class Entity
{
  public string name;
  public List<Behavior> behaviors;
  // other stuff...
}

```

I want to create an editor window that allow game designers to create "*instances*" of that class by giving the name and a set of `Behavior`, which are premade classes by devs.

What I need is a file format to save what the game designers have input in the editor window when they click on "save", like json, to use that data later in the runtime of the game. But, of course, you can't save a list of polymorphic classes instances with json, so I'm looking for alternatives.

How can I save what designers create and load/instantiate/use it during runtime?

At first, I was thinking of creating prefabs, but:

* `prefabutility.createprefab` is tagged as Obsolete in the docs
* I don't know if it's a good solution in term of memory, maintainability, scalability, ...

# Answer
## Option 1: ScriptableObject

The simplest way to do this is if `Behaviour` and `Entity` inherit from `ScriptableObject`; then you can do something like this:

```
public abstract class Behaviour : ScriptableObject {
    // Stuff common to all behaviours goes here.
}

[CreateAssetMenu(fileName = "someBehaviour.Asset", menuName = "Behaviours/Some Behaviour")]
public class SomeBehaviour : Behaviour {
   // Customized behaviour stuff goes here.
}

[CreateAssetMenu(fileName = "newEntity.Asset", menuName = "Entity")]
public class Entity : ScriptableObject {
    // No need for a "name" - it inherits that already from ScriptableObject.

    public List<Behaviour> behaviours;
}

```

This adds options to create entities and behaviours into the Asset \> Create menu in the Unity editor, and the Create menu you get when right-clicking in the Project tab.

Your designers can then create a `.asset` file for each version of a behaviour, and each entity, using the existing Inspector, before you write any custom editor code. Because this is using native Unity serialization, references between the assets are visible to Unity, so it can keep them updated, cull unused assets from builds, and pack the data efficiently using binary serialization. You get handy features like multi-object editing basically "for free", and when writing your own editor code you can use the infrastructure provided by Unity's `SerializedObject` / `SerializedProperty` to process changes field-by-field, support undo, etc.

ScriptableObjects are also eligible to receive certain message calls automatically, like `Awake`, `OnEnable`, `OnValidate`, `OnDisable`, `OnDestroy`, which can help when you need to do some dynamic initialization or cleanup before/after using them.

To instantiate a copy of one of these entities at runtime, without altering the source asset file, you can just say `Instantiate(myEntity)` like you would with a prefab. I haven't tested whether this performs a deep copy (instantiating copies of each behaviour in the list) or a shallow copy (instantiating a copy of the list whose entries all still point to the original behaviours), so you might have to implement your own deep copy method if the behaviours contain mutable data.

By default, you'd have to create each customized behaviour instance as its own asset file, then link references to those assets in the entity's list. So if I have variants on a "flee" behaviour that each use a different speed, I'd need to create `FleeSlow.asset`, `FleeMedium.asset`, `FleeFast.asset`, even if they're all just instances of the same `FleeBehaviour` script with different parameter values.

That's useful if you have shared behaviours that should use the same values for every entity that uses them - saving file size and memory by de-duplicating the data, and avoiding the need to manually keep many separate instances in sync - but cumbersome if every entity is using bespoke behaviour instances. The Entity inspector will also just show a list of references to Behaviours, not nested inspectors so you can tune their parameters all in one place.

Both these frustrations can be improved by writing a custom inspector or custom editor window that acts on this data. The big win is that you don't have to finish that editor window before you begin working with this solution, since the default inspector handles a basic workflow out of the box.

The downside of course is that this is no longer a plain old C# class, but carries some overhead due to inheriting `ScriptableObject`. If getting this type as lean as possible is important to you, you can instead handle your own polymorphic serialization via XML.

## Option 2: XML Serialization

The built-in .Net XML Serialization library lets you use attributes to customize how a class should be represented in XML form, including options to serialize lists of polymorphic types.

```
using System.Collections.Generic;
using System.Xml.Serialization;

public class Entity {
    // This makes the "name field show up as an attribute inside the <Entity> tag
    [XmlAttribute]
    public string name;

    // This parses tags for any of the specified class names as items in this list.
    [XmlElement(typeof(SomeBehaviour)), XmlElement(typeof(SomeOtherBehaviour)) /*...*/]
    public List<Behaviour> behaviours;
}

```

This will allow you to read/write entities from XML that looks like this:

```
<?xml version="1.0"?>
<Entity xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="My Awesome Entity">
    <SomeBehaviour someAttribute="5">
        <direction>
            <x>1</x>
            <y>0</y>
        </direction>
    </SomeBehaviour>
</Entity>

```

You can store this text in a `.xml` file, and read/write it with the XmlSerializer class.

The downside here is that you're responsible for doing *all* the heavy lifting yourself. Any deserialize-edit-serialize-save operations need to be handled in your custom editor window code. The assets on disc will tend to be larger since XML is such a verbose text format, and reading/writing them is likely to be slower. As far as Unity is concerned, this is just a text file, so if any references in your project that this entity depends on change, it won't know how to update the text to match unless you expressly handle that change yourself.

On the plus side though, you're now completely independent of Unity serialization, so you could stream new entity definitions from a server at runtime, or allow modders to create and distribute their own entities, without needing the Unity editor installed. I've used this in the past to support games with user generated content.
> 0 votes

---
Tags: unity, c#, serialization, asset-workflow
---


# Question
Title: Emulating 3d trajectory in top-down 2d game?
As the title suggests, I am wondering if it's possible to emulate a 3d arrow trajectory to a top-down 2d game? If you would look at this clip of Age of Empires 2 game, especially when archers are firing from bottom to top. Can the parabola/arc of the trajectory (in that certain view angle) be emulated in a 2d orthographic, top-down game? So that the arrows would look like they're in 3d space. I know it's tricky but I wonder if there's some computation available for this.

If you could point me in the right direction or some sample code I would be very grateful. I've only implemented this projectile motion in a side-scroll view.

Thank you in advance.

# Answer
> 2 votes
I created this version which uses a target position and t (time 0-1).

I would loop this function in an update function `if (t < 1) t` would increase by `projectileSpeed * deltaTime` in the update after the function was called:

**AS THE PROJECTILE**

```
const float projectileHeight = 10f;
const float projectileSpeed = 5f;

Vector3 startPos;
Vector3 endPos;
float fireLerp = 1;

void FireProjectile(Vector3 firePoint, Vector3 targetPos)
{
    startPos = firePoint;
    endPos = targetPos;

    // Setting the fire lerp to 0 will begin the fire animation
    fireLerp = 0;
}

void Update()
{
    if (fireLerp < 1)
    {
        Vector3 newProjectilePos = CalculateTrajectory(startPos, endPos, fireLerp);
        transform.position = newProjectilePos;

        fireLerp += projectileSpeed * Time.deltaTime;
    }
}

Vector3 CalculateTrajectory(Vector3 firePos, Vector3 targetPos, float t)
{
    Vector3 linearProgress = Vector3.Lerp(firePos, targetPos, t);
    float perspectiveOffset = Mathf.Sin(t * Mathf.PI) * projectileHeight;

    Vector3 trajectoryPos = linearProgress + (Vector3.up * perspectiveOffset);
    return trajectoryPos;
}

```

# Answer
> 1 votes
Store the Z coordinate and move object as if it was in 3D space. When drawing on screen, add object's Z to Y (you can multiply Z by some constant to make world look 'flatter').

---
Tags: unity, c#, 2d, projectile-physics, trajectory
---


# Question
Title: Unity New Input System - What Is The Correct Way To Check If Any Button From An Action Map Was Pressed?
Good Morning All,

I am using Unity's New Input System. I have an Action Map created called 'Menu'.

Currently, this is how I check for ***specific*** button presses.

```
If( xxx.Menu.Select.WasPressedThisFrame() )
{
  // Do Stuff
}

```

The above works fine. However, now I need to check if ***any*** button was pressed from the Action Map.

For example, my game could show an image of a PS4's X Button. I need to detect if the player presses the right ***or wrong*** button. If the right button is pressed they win and if the wrong button is pressed they lose.

Hopefully this makes it even more clear:

```
If( METHOD THAT CHECKS IF ANY INPUT FROM THE MENU ACTION MAP WAS PRESSED ) // <- This is what I need
{
      If( xxx.Menu.Select.WasPressedThisFrame() )
      {
        // You win!
      }

      Else
      {
        // You Lose!
      }
}

```

To summarize, I'm looking for a method from Unity's New Input System that checks if any button was pressed. Thank you so much for taking the time!

# Answer
You could use a setup like this :

And then check with:

```
if (inputActions.actionMap.TestAction.WasPressedThisFrame())
{
    if (inputActions.actionMap.Good.WasPressedThisFrame())
    {
        Debug.Log("You win!");
    }
    else if (inputActions.actionMap.Bad.WasPressedThisFrame())
    {
        Debug.Log("You lose!");
    }
}

```

But, in general, with the new Input System it might make more sense to organize the input logic by using callbacks, rather than polling. Like this:

```
inputActions.actionMap.Good.performed += () =>
{
    Debug.Log("You win!");
}
inputActions.actionMap.Bad.performed += () =>
{
    Debug.Log("You lose!");
}

```
> 1 votes

# Answer
Here is an example how you can check for any `InputAction` being triggered in any or specific `InputActionMap`:

```
using System.Linq;
using UnityEngine;
using UnityEngine.InputSystem;

public class TestAnyButton : MonoBehaviour
{
    [SerializeField] private InputActionAsset iaa;

    void Start()
    {
        iaa.Enable();
    }

    void Update()
    {
        if (iaa.Any((ia) => ia.WasPressedThisFrame()))
        {
            Debug.Log("Any action", this);
        }

        if (iaa.FindActionMap("AcitonMapName").Any((ia) => ia.WasPressedThisFrame()))
        {
            Debug.Log("Any action in an action map", this);
        }
    }
}

```

An alternative way is to subscribe to all the `InputAction`s in a map:

```
public class TestAnyButton : MonoBehaviour
{
    [SerializeField] private InputActionAsset iaa;

    private InputActionMap observedMap;

    void OnEnable()
    {
        iaa.Enable();

        observedMap = iaa.FindActionMap("ActionMapName");
        foreach (var inputAction in observedMap)
        {
            inputAction.started += OnStarted;
        }
    }

    void OnDisable()
    {
        foreach (var inputAction in observedMap)
        {
            inputAction.started -= OnStarted;
        }
    }

    void OnStarted(CallbackContext context)
    {
        if (context.started)
        {
            Debug.Log($"{context.action.name} started.", this);
        }
    }
}

```
> 3 votes

---
Tags: unity, input
---


# Question
Title: How would I mask the player node out of a canvas shader?
I'm making a 3D game, and I want to create a post processing effect using a canvasitem and a colorrect, that effects everything on screen apart from the player. I already have the shader itself made, but my first attempt at masking the player out didn't work. I used 2 cameras, one for the world and one for the player, but that meant the player was in front of everything in the world.

Ideally, I need to be able to make a texture like the one below (forgive the MS Paint mockup) to use for transparency in the canvas shader. How would I do this?

# Answer
I have found an answer to how to do this. Other methods I have found, would single the player out of the environment, and make it show in front of everything.

For my method, I make a subViewport, with a second camera, and make it copy the transform of the main camera. I put the player on a second cull layer, and have the second camera not see the player. I then make a shader which compares the view of the main camera, and the camera without the player, and do a difference operation (abs(a-b)) to find what is different between the 2 camera views, which would be everywhere the player is in the image. This also takes obstacles into account, as the obstacles would be the same in the 2 views.

The only times this method wouldn't work is if the player happens to be standing in front of an object with the exact same RGB value as it, which for my game, would never happen.
> 0 votes

# Answer
You will setup a `SubViewport` (you would not need a container for it, since - I presume - it would not be shown), make sure its render mode and its clear mode are set to always. And the `SubViewport` can have its own world (I'll get back to this).

Inside the `SubViewport` you want to have a different `Camera3D`, and (maybe) a copy of the character model with a material override (I'll get back to this). The material override must be an all white material, unshaded (and you can also have depth test disabled).

You need the clear color to be black. If the clear color in project settings is black, you are done. Otherwise, you can also set a `WorldEnviroment` inside the `SubViewport` and set its background to custom color and pick black (this only works if the `SubViewport` has its own world). *I suppose that as last resort you could have black quad match the view (which you can do by giving it a material that moves the vertex), and either have it match the far plane, or have the material override for the character has depth test disable.*

You would - by script - keep the `Camera3D` and character inside the `SubViewport` synchronized. *Copy their `global_transform` in `_process`, and any other relevant property (e.g. field of view of the camera). I suppose animations might be a challenge, depending how you are handling them for your character.*

Could you use the same character instead of a copy? Sure, if you do not set the `SubViewport` to have its own world, it will default to the same as the parent. However, since you need different materials, you will have to duplicate the meshes. To make one copy of the mesh show in the `SubViewport` and another outside, give them different layers (it is under `VisualInstance3D`), and then give matching cull masks to the `Camera3D`s.

Then you can get the texture from the `SubViewport`.If you need to set it in the Inspector (for example as a parameter of your canvas shader), pick `ViewportTexture` and point it to the `SubViewport`. Note: The `SubViewport` needs to be first in the scene tree (before where you use the `ViewportTexture`) so that during initialization the `SubViewport` is created before the `ViewportTexture` that references it. *Alternatively, could also take a texture from the `SubViewport` from a script.*
> 3 votes

---
Tags: godot, fragment-shader, screen, godot-4, masking
---


# Question
Title: How To Implement Button-Matching Minigame In New Input System
Good Afternoon,

I'd like to incorporate a button-matching minigame into my game. I have an `InputActionMap` made specifically for this minigame. One of the buttons from the 'Any' `InputAction` will be chosen randomly as the 'correct' button. An image of the chosen button will display on the screen and the player will need to press the matching button on their gamepad.

I need to be able to tell when the player presses one of the 'Any' buttons, and if it was the correct button or not. If the player presses the correct button, they win. If they press a button and its ***not*** the correct button, they lose.

# Answer
> 1 votes
I would implement this like so:

Create a MinigameActions input map with 4 distinct buttons - not all lumped into one "Any" button. Something like:

* MinigameActionA
* MinigameActionB
* MinigameActionC
* MinigameActionD

You can default these to north/east/south/west face buttons, and in your options menu, you can let players remap them to other controls if they like (e.g. for accessibility controllers).

We'll make each one correspond to an enum value, and also make an enum for the results from pressing them:

```
public enum MinigameAction {
    A, B, C, D
}

public enum MinigameActionResult {
    Correct,
    Incorrect,
    Neutral // Use for buttons you want to ignore / not mark "wrong".
}

```

Then we can define a parent type for your minigame-specific gameplay scripts:

```
public abstract class Minigame : MonoBehaviour {
    MinigameActionResult PerformAction(MinigameAction action);
}

```

A button combo matching minigame script could then look like this:

```
public ButtonComboMatch : Minigame {

    public List<List<MinigameAction> comboSequence;

    int _currentCombo;
    int _placeInCombo;

    public MinigamActionResult PerformAction(MinigamAction action) {
        if (comboSequence[_currentCombo][_placeInCombo] != action) {
            // Trigger combo broken feedback, then rewind to the start of the combo.
            _placeInCombo = 0;
            return MinigameActionResult.Incorrect;
        }

        // Otherwise, correct! Advance to the next button to press.
        if(++_placeInCombo == comboSequence[_currentCombo].Count) {
            // Finished the current combo - trigger success fanfare and advance.
            if (++_currentCombo == comboSequence.Count) {
                // Finished final combo - you win!
                // TODO: trigger victory.
            }

            _placeInCombo = 0;
        }

        return MinigameActionResult.Correct;
    }
}

```

Your input script can then take a reference to the current `Minigame` gameplay script, and relay button presses to it:

```
Minigame _currentMinigame;

void RelayAction(MinigameAction action) {
    var result = _currentMinigame.PerformAction(action)
    switch (result) {
       case MinigameActionResult.Correct:
           // Do any common "on correct action" feedback here.
           break;
       case MinigameActionResult.Incorrect:
           // Do any common "on action incorrect" feedback here.
           break;
    }
}

void SetupActions(ActionMap actionMap) {
    actionMap.MinigameActionA.performed += () => RelayAction(MinigameAction.A);
    actionMap.MinigameActionB.performed += () => RelayAction(MinigameAction.B);
    actionMap.MinigameActionC.performed += () => RelayAction(MinigameAction.C);
    actionMap.MinigameActionD.performed += () => RelayAction(MinigameAction.D);
}

```

In this way, the script that talks directly to the input system has only one job: report which button was pressed.

Categorizing that press as either correct or incorrect is the job of the minigame script, and you can swap those out without touching anything in the input system.

---
Tags: unity, input
---


# Question
Title: What if I use delta time to just regulate framerate but not individual entities?
What if, instead of multiplying all my values that change each frame by delta time, I just increased one number in increments multiplied by delta time, and used that number to advance to the next frame? What's really the drawback here?
As far as I can tell, the famous "**Fix Your Timestep!**" article doesn't mention this.
Basically, I had implemented everything using integer positions with the intent of making games that had a similar game feel to NES and GameBoy Color games. This worked perfectly when using frame delay, but when it came time to implement delta time, it wasn't as simple as just multiplying my velocities by delta time. It was so much more of a headache than it was worth.
So I was inspired by **this** video (specifically the part on random numbers) to come up with a dumb solution like so:

```
float dirty_delta = 0;

while (!done)
{
    float dt = get_delta_time();

    dirty_delta += dt * 60;

    begin_frame();

    if (dirty_delta >= 1)
    {
        update();
        dirty_delta = 0;
    }

    draw();

    end_frame();
}

```

After implementing dirty delta, the program appears to work just fine. So if all I care about is keeping the game loop from moving too fast or slow based on the user's machine, is this good enough for government work?

# Answer
*I do not know about government work, of which government, and which laws...*

We can be sure there won't be an issue with not passing `delta` if:

* You know the hardware you are targeting, it has predictible performance, and a standard refresh rate.
* You can identify when a frame is taking too long and have a commitment to fix it before release.

Or from the opposite point of view, not passing `delta` has these possible drawbacks:

* If you decide to change the frame rate (e.g. porting to a different hardware, or if you want to make it match the refresh rate of the display) your code won't be able to adapt to that.
* When a frame is taking too long (either because the update code is a bottleneck, or because the OS/CPU/Other apps degrading performance), your code could not adapt to that. *Arguably you might want this.*

We can also argue that not using `delta` has a benefit: update code is simpler (e.g. we assume a constant `delta`, or hardcode values as if already multiplied by `delta`), and since it would be doing less (less multiplying by `delta`) it would perform better (if this improvement in performance is significant is a different matter).

Thus, not passing `delta` is a good option on limited hardware with fixed specifications, in particular when the game is the only thing running on the system (which is the case of old consoles).

---

I see that in the code you post you call `draw` every loop, thus the concerns about refresh rate might be mitigated already (I'm assuming `draw` hides logic for swapping buffers, checking for VSync, or similar). *Consider if you can save time in redundant draws by using a similar structure to the one you use for updates.*

And about the updates, as I mentioned above, perhaps what you want is that updates to not adapt to the timing between updates. For example, if a particular frame takes longer, you won't see entities doing a big step afterwards to compensate.

---

You could pick some minimum hardware specifications below which your game is not expected to perform well anyway, so you can take that as your target hardware, and if you can assure that your updates stay within their allocated time on that target hardware (barring OS/CPU/Other apps)… Then if there are performance degradations, at least your game is not to blame.

Doing that might require (depending on your game and the target hardware) techniques such as:

* Limit the number of entities in the game at any given time.
* If you allow more entities that can be updated then each frame a different subset gets updated.
* Or you might have some have a simple update (e.g. keep going the direction they were) and some have a complex update (e.g. do path finding).
* Speaking of complex updates, you might want to write it a way that can be halted and resumed on the next update.

Notice that these and similar techniques depends on the game, and as such a general purpose game engine cannot make promises about them, so it makes sense that game engines give you `delta` (another reason for engines giving you `delta` is that they might allow to export your game to different hardware and operating systems).

---

I cannot tell you if that is OK for your game. *And your government*.

And I remind you to test.
> 0 votes

---
Tags: frame-rate, deltatime
---


# Question
Title: How do I make a 3D cursor that follows the mouse in Godot?
I want to position a 3D object at my mouse cursor. How can I do that in Godot? In Unity, I'd use `Camera.ScreenToWorldPoint`.

# Answer
> 3 votes
`Camera3D.project_position` is the Godot equivalent function.

Here's an implementation that can either move the position with fixed orientation or can also point the cursor object. I'm using `_g` to indicate which values are in worldspace (global) to avoid confusion with localspace.

```
extends Node3D

@onready var camera := get_parent() as Camera3D
@export_range(1, 1000) var depth := 10.0
@export var should_only_set_position := false

func _process(_dt):
    var mouse_pos = get_viewport().get_mouse_position()
    var cursor_pos_g = camera.project_position(mouse_pos, depth)

    if should_only_set_position:
        # To just position it, set global_position and set the desired
        # orientation in your scene.
        global_position = cursor_pos_g

    else:
        # To make the cursor point at the centre of the screen, ensure it faces
        # -z direction.
        var cam_forward_g = -camera.get_global_transform().basis.z
        var look_pos_g = camera.global_position + cam_forward_g * depth * 1.5
        look_at_from_position(cursor_pos_g, look_pos_g)

```

Since Godot's forward direction is -z (?!), you need to point your cursor along the -z axis for it to be oriented correctly. (Notice `cam_forward_g` is also -z.) If you have trouble, add some extra arms to make the orientation changes very obvious.

Cursor has the above script and it has some shapes underneath it to make it visible:

I put it under the camera, but you could also a export to let it live anywhere: `@export var camera : Camera3D` instead.

You could also change this code to make `look_pos_g` the global position of an object you're going to interact with or your player character.

---
Tags: godot, mouse, godot-4
---


# Question
Title: What's a convenient way to setup two objects that physically "plug" into each other?
I'm making a puzzle game and I need two pieces that look like they fit together (like a DVI port and DVI plug). I want them to be two separate scenes because I want to place and animate them separately.

What's a good way to set this up to make it easy to edit them and keep their shapes in sync?

# Answer
> 4 votes
1. Put each half in its own scene (A and B).
2. Place both in a scene that's just for editing them (E). This is a normal scene that you don't spawn in gameplay.
3. Edit them in scene E.
4. On the instances of A and B:
    1. "Make Local".
        * This severs the relationship to the saved scene.
    2. "Save Branch as Scene" and overwrite original.
        * This recreates the relationship to the saved scene and updates the scene file.

---
Tags: godot
---


# Question
Title: How can I make a reliable time-based object updating system?
So an object has a position, velocity, and is affected by gravity.

```
#include <simd/simd.h> // MacOS
struct Object {
    vector_float3 Translation; // Units
    vector_float3 Velocity; // Units per second
};

```

The game loop typically runs 60 times per second.

```
void ObjectUpdate(struct Object *obj) {
    obj->Velocity.y -= 9.80655/60;
    obj->Translation += obj->Velocity/60;
}

```

There are a couple problems with this approach:

* Lag exists, so the assumption of 60 updates per second being embedded in the code is not great.
* Floating point types are susceptible to precision errors at far distances from the origin, and are also more difficult to handle in some ways than integers.

I attempted to solve these with a fixed-point approach, and the use of `clock()` as well as keeping track of the time of the last update.

```
struct Object {
    vector_long3 Translation; // 65536ths of a unit
    vector_long3 Velocity; // 65536ths of a unit per second
    clock_t LastUpdate;
};
void UpdateObject(struct Object *obj) {
    const clock_t current = clock();
    const unsigned long delta = (unsigned long)((current-obj->LastUpdate)*(clock_t)65536/CLOCKS_PER_SEC); // Try to find the number of 65536ths of a second since the last update, in a way that it does not matter whether clock_t is integral or real
    obj->LastUpdate = current;
    obj->Velocity.y -= delta*642682>>16; // 642682 = 9.80655*65536
    obj->Translation -= delta*obj->Velocity>>16;
}

```

However, this suffers from other problems, most notably, being extremely chunky and unreliable. If I simply add `delta` to an accumulator and then print the accumulator, the value rises at an inconsistent rate, typically much slower than by 65536 per second.

How should I handle objects that need *'constant'* updating and their updates are contingent on time?

# Answer
The problem was that `clock()` measures CPU time and not absolute time. Using `clock_gettime()` with `CLOCK_MONOTONIC` instead of `clock()` should solve the problem. The code will have to be updated to use `struct timespec` instead of `clock_t` like so:

```
struct Object {
    vector_long3 location; // 65536ths of a unit
    vector_long3 velocity; // 65536ths of a unit per second
    long last_update;
};
void Object_update(struct Object *obj) {
    struct timespec t;
    if (clock_gettime(CLOCK_MONOTONIC, &t))
        abort();
    const long current = t.tv_sec<<16|t.tv_nsec>>16, delta = current-obj->last_update;
    obj->last_update = current;
    obj->velocity.y -= delta*642682>>16; // 642682 = 9.80655*65536
    obj->location -= delta*obj->velocity>>16;
}

```
> 0 votes

---
Tags: game-loop, c, timestep, floating-point, fixed-point
---


# Question
Title: How can I handle voxels that require extra data in my octree?
I am using octrees as an efficient way to store voxel data in a voxel game. The details of my octree implementation can be found here, but in a nutshell, each node is 16 bits, and the most significant bit determines whether the other 15 bits refers to a voxel type or an index to another set of 8 nodes. The index is relative to the set the node is in. There are 5 maximum levels, including a root node stored separately, making each octree 32x32x32 voxels. This means that for nodes in the bottom layer, the MSB is irrelevant to the structure of the tree and can be used for another purpose.

This system works and is efficient. Any one of 32768 voxel types (air, stone, dirt, etc.) can be stored, and any power-of-2 aligned cube inside the octree that is all the same type, is only stored as one entry, resulting in memory savings and iteration performance savings for octree regions that are mostly the same type.

The issue I have is when I need to introduce more complicated voxel types to the game, that need more data than just 15 bits to represent. I decided to split voxel types into 3 complexity categories:

* Simple (up to 15 bits). They can be stored in any level of the octree.
* Complex (up to 63? bits). They can only be stored at the bottom level of the octree, and cannot be merged if they are the same, because their MSB has to be used. The MSB would determine whether the remaining 15 bits is Simple voxel or an somehow a reference to a 64-bit object. If the LSB of the 64-bit object is not set, the remaining 63 bits are the data of a Complex entry.
* Arbitrarily complex (up to an arbitrary number of bytes in size). If the LSB of a Complex voxel entry is set, the remaining 63 bits (with the LSB cleared) becomes a pointer to some dynamically allocated entity of an arbitrary size.

I use this to describe a Complex entry:

```
typedef union Ptr {
    union Ptr *p;
    uint64_t u;
} Ptr;

static_assert(sizeof(Ptr)==sizeof(uint64_t), "sizeof(Ptr)!=sizeof(uint64_t)");

```

## This brings us to my question:

How can I efficiently *'embed'* these extra data entries in the octree? I have some ideas in mind but are not currently feasible in their current state:

* 16-bit entries at the bottom level of the octree with their MSB set refer to an absolute index in a separate array of Complex entries via their remaining 15 bits. The problem is insertion and deletion. As I found out with designing the octree structure as altogether, before I considered the Complex entries, absolute indices are trouble. If I have to insert/delete something in the middle of the tree and I want to keep the data ordered and contiguous, I will have to shift all the entries after the modification point, thus track down and update all the indices referring to them.

What if I do not keep them contiguous? Then writing them to files will be trouble. I will still have to iterate all the entries to defragment and also iterate the entire tree to correct the indices to refer to the right places after defragmentation. (I refuse to save any *gaps* to the file).
* I could embed them inside the tree after the sets that reference them. But this means changing a simple node (even at the bottom level) to a complex node would require a potential mid-tree insertion. And the indexing can get complicated since the 8-byte Complex node entries are not the same size as the 16-byte sets of 8 nodes, meaning an odd number of Complex entries embedded in a tree could result in all sets after them becoming no longer 16-byte aligned. Implementing this could potentially cause unforeseen consequences and require a major rewrite of the `octree_set()` function I already have and worked so hard on.

Are there any other options that I have for embedding 64-bit entries in an octree designed for 16-bit entries? Are there any variations of my existing ideas that would make implementing them less troublesome?

Note: I also refuse to simply quadruple the size of the entire tree to make every entry 64 bits. This would quadruple memory usage.

# Answer
> 2 votes
I would suggest going with a variant an absolute index in a separate array.

Rather than insert/delete with shifting (which would be painful to implement and slow), or leaving gaps, there is a third option: every time an entry is deleted, retarget whatever is in the last entry in the array to fill that gap created by the deletion. Adding an entry just goes on the end of the array.

So for instance, if the array is originally:

A,B,C,D,E,F

and entry C (index 2) is deleted, move F (originally index 5) to fill in the gap to get:

A,B,F,D,E

Then adding an entry G would give:

A,B,F,D,E,G

Finding the entry in the voxel structure to change does involve a reverse lookup (what points to index 5 that we now want to point to index 2?). Two options here, depending on whether space or speed is more important:

* If space is more important, just scan the tree replacing the index wherever it occurs (can stop after the first one is found if there is only one pointer to each element of this array)
* If speed is more important, have some information about where the pointer is either stored elsewhere (parallel array?) or embedded into the complex data structure, although that does mean that you lose the plain 64 bit option.

This is outside the scope of your question, but if you are prepared to limit yourself to 16384 simple voxel types (14 bits), using the two most significant bits rather than one means that you can have the complex structure at levels other than the bottom of the tree:

There are many possible encoding options for this, but one example:

0xxxxxxxxxxxxxxx - index to another set of 8 nodes

10xxxxxxxxxxxxxx - simple voxel type

11xxxxxxxxxxxxxx - pointer to a complex or arbitrarily complex entry.

---
Tags: voxels, data-structure, c, octree
---


title: How to draw table border in libgdx?

text:
# Question
Title: How to draw table border in libgdx?
I'm new to libgdx and I'm currently working on TableLayout and wondering how could I draw borders for each cells.

I've done some research on this but it seems that I could come up with this solution only: https://stackoverflow.com/questions/13828423/drawing-table-borders-in-libgdx-0-9-7

However, turning on the debug option would be a bit dumb and it's not what I want. I'd like to control the color, thickness of the cell border. Is there anyway to achieve this?

Thanks!

# Answer
I don't believe there is a built-in function for this.

You have a few options though:

1. Use a 9-patch for table background with a border (thats what I do)
2. Place another table underneath the main table, and make the size a bit bigger so you can see the edges, giving the impression of a border. This is probably your best choice since you want to control color/thickness etc.
> 6 votes

# Answer
Another option besides the ones mentioned is to use Pixmap to draw the rectangle border and then use it as the background. It will give the idea of a border. The code below uses KTX so LibGDX with Kotlin.

```
    val pixmap = Pixmap(64, 64, Pixmap.Format.RGBA8888)
    pixmap.setColor(Color.BLACK)
    pixmap.drawRectangle(0,0,64,64)
    val borderTexture = TextureRegionDrawable(Texture(pixmap))
    pixmap.dispose()

// initialize table etc...
table.background = borderTexture

```
> 0 votes

---
Tags: libgdx
---


# Question
Title: Is instanced rendering any different from indexing seperate buffers using div and mod in the shader?
As far as I can tell instanced rendering is simply a way to separate a single vertex buffer into a buffer for vertex-specific data and instance-specific data. This could be useful for rendering multiple otherwise identical models, but each one is at a different offset in the world. You only have to store the model once, and you have a per instance translation that you add to each vertex in the shader. Metal and OpenGL both have special mechanisms (functions) for instanced rendering.

However, how is instanced rendering any different from just using normal, non-instanced rendering where I index the vertex buffer with `vertex_id%VERTICES_PER_INSTANCE` and index a pseudo-instance buffer with `vertex_id/VERTICES_PER_INSTANCE` within the shader? For example, are there performance gains from using official instanced rendering instead of just using `/` and `%` in the shader? Are there other more subtle differences that I am not aware of? What capabilities do the existing official instanced-rendering facilities provide that emulating instanced rendering using `/` and `%` in the shader does not?

# Answer
One significant disadvantage of doing manual vertex fetching is that it will generally not be able to take advantage of the post transform cache. That alone could easily reduce vertex processing performance by a factor of two or more if you're not using it.

If you want to take full manual control of mesh processing, you might want to look into mesh shaders (GL\_MESH\_SHADER\_NV/GL\_TASK\_SHADER\_NV in OpenGL).

That brings me to another reason that you might want to use the standard hardware instancing support - it's more portable. For example, you might not be able to do manual vertex fetching on every mobile phone GPU that supports hardware instancing. Mesh shaders require even more modern GPUs, and APIs.
> 1 votes

---
Tags: opengl, rendering, instancing, metal
---


title: Unity keyframe animations not smooth?

text:
# Question
Title: Unity keyframe animations not smooth?
I'm new to Unity in general, and particularly to animations, but what I'm trying to do should be fairly basic so I'm probably doing something simple wrong.

I've broken this down into a very simple demo case: I need to spin a cube *smoothly*.

Here's what I've done:

* Created a `TestCube`.
* Using the `Timeline` window, created a `Director` component with a `Playable`.
* Added an `Animation Track` to the timeline linked to `TestCube` (which automatically added the `Animator` component to the cube).

I then recorded a very simple animation with two keyframes, where I rotate `TestCube` 180 degrees.

The result *looks* okay at first glance, but in reality it is actually quite jittery and uneven. I created a simple script to log how much the cube rotates each frame. In my real application, I'm mainly working in `FixedUpdate`, but I'm interested in both, so I logged both.

```
using UnityEngine;

public class Test : MonoBehaviour
{
    private Quaternion previousUpdateRotation;
    private Quaternion previousFixedUpdateRotation;

    private void Awake()
    {
        previousUpdateRotation = transform.rotation;
        previousFixedUpdateRotation = transform.rotation;
    }

    private void Update()
    {
        Debug.Log($"Update|{Quaternion.Angle(previousUpdateRotation, transform.rotation)}");
        previousUpdateRotation = transform.rotation;
    }

    private void FixedUpdate()
    {
        Debug.Log($"FixedUpdate|{Quaternion.Angle(previousFixedUpdateRotation, transform.rotation)}");
        previousFixedUpdateRotation = transform.rotation;
    }
}

```

I then graphed the output:

As you can see, the rotation of the cube is very much *not* smooth. My first thought way maybe the `Animator.UpdateMode` parameter could help me. I set it to `Animate Physics` and ran the test again, hoping to get a better result on FixedUpdate. But I got similar results.

Can anyone tell me what I'm doing wrong? How can I get a smooth response to match the smoothness of the animation curve?

# Answer
I tried this on my end and found that I got jitter that looked similar when graphed, *when playing the animation on a Timeline through a Playable Director*. The delta graph looks much smoother when played directly from the Animator component without a Playable Director (i.e. using an Animator Controller).

Note that the Playable Director has its own Update Mode settings and these do not include any option to update the timeline from the fixed time step. You could set the mode to "manual" and update it from `FixedUpdate()` with your own code; otherwise, there's no point to measuring deltas in `FixedUpdate()` because they are out of sync with `Update()`.

What's more important than the `Update()` deltas is how smooth the animation is over time. The interval between frames won't be entirely consistent, even if you have specified a target framerate (via `Application.targetFramerate`), so some jitter in the deltas is expected. If you graph the actual euler angle over *time* (**not** over frames), that graph should look pretty smooth, even when played from a Playable Director.

Here's a way to graph it in the Editor:

```
public class Test : MonoBehaviour {

    public AnimationCurve animationCurve;
    public AnimationCurve deltaCurve;
    private Quaternion previousUpdateRotation;

    private void Awake() {
        previousUpdateRotation = transform.rotation;
    }

    private void Update() {
        animationCurve.AddKey(Time.time, transform.eulerAngles.y);
        deltaCurve.AddKey(Time.time, Quaternion.Angle(previousUpdateRotation, transform.rotation));
        previousUpdateRotation = transform.rotation;
    }

}

```

The above code records the values each frame into `AnimationCurve`s, which can then be viewed from the inspector. Note that since I'm not bothering to smooth the bezier handles, the curve from point to point in the graph won't look exactly right. Just focus on the actual points, not the interpolated curve between them.

**Deltas over time**

**Euler angle over time**

Notice that despite some nasty-looking jitter in our deltas, the actual curve of the euler angle over time is very smooth. This suggests that the delta time between frames is relatively inconsistent but the engine is correctly accounting for this when performing the animation.

If you want to remove inconsistent frame intervals from the equation, use `Time.captureFramerate = 60` (or whatever framerate you want to use). This will force the engine to use a consistent delta time for each frame. This setting is intended for use when recording gameplay videos, hence the name, and normally shouldn't be used for actual gameplay (unless you want the game to go into apparent slow motion if the player's hardware can't keep up with the desired framerate).

**TLDR**

* Don't use delta between frames to try to measure how smooth an animation is
* If you want a graph to show you how smooth an animation is, graph the value that you're animating over time (**not** over frames)
* You may see more inconsistent frame timing when playing an animation through a Timeline rather than through an Animator Controller. This doesn't necessarily mean the animation will look any less smooth to the player.
> 4 votes

---
Tags: unity, animation
---


title: Why is the grid's Z coords = -10

text:
# Question
Title: Why is the grid's Z coords = -10
I'm using mouse input to move the player from where they are to where the mouse position is relative to the cell on a tilemap. However I found when I click on a point of the tilemap, the z coordinate for it is -10. This has led to me to dealing with a work around of just resetting the player's z coordinate every time they are moved. I was wondering why this is the case and if there is a way to fix this so I don't have to reset the z coordinate every time.  Player starts at (0,0,0) in world position.

Moving the player 2 hexs to the right should result in (2,0,0) but instead returns (2,0,-10)

Here is the code for player movement:

```
var screenPos = Input.mousePosition;
var worldPos = Camera.main.ScreenToWorldPoint(screenPos);
var coordinate = grid.WorldToCell(worldPos);
Debug.Log(coordinate);
//resetting the z coord
transform.position = grid.CellToWorld(coordinate);
Vector3 position = transform.position;
position.z = 0;
transform.position = position;

```

# Answer
> 0 votes
The docs for `ScrenToWorldPoint` say:

> Screenspace is defined in pixels. The bottom-left of the screen is (0,0); the right-top is (pixelWidth,pixelHeight). **The z position is in world units from the camera.**

When you don't provide a z component, it defaults to 0 — zero units in front of the camera.

The camera in Unity is, by default, placed at -10 on the z axis. So that's likely where your -10 is coming from.

If you say `coordinate.z = grid.transform.position.z` before converting to cell coordinates, that should eliminate the unwanted offset by clamping your input to the plane of the grid.

---

The above works for an orthographic camera looking straight at the tilemap, which seems to be what you're using. To make this answer useful for other folks who may find it, here's how you'd handle other camera arrangements:

If you're using a perspective camera, you'll want to instead set the proper depth before unprojecting, like so:

```
Camera cam = Camera.main;
Vector3 screenPos = Input.mousePosition;
screenPos.z = Vector3.Dot(grid.transform.position - cam.transform.position, cam.transform.forward);
var worldPos = cam.ScreenToWorldPoint(screenPos);

```

If the camera is looking at the tilemap diagonally/obliquely rather than straight-on, then you'd instead use `ScreenPointToRay` then intersect the ray with the tilemap plane to find the world space position, since the correct unprojection depth varies across the screen.

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


# Question
Title: What's the correct way to use NavigationAgent3D in Godot?
I've just started using Godot and obviously fail to use `NavigationAgent3D` correctly. I've added a `NavigationRegion` and baked a navigation mesh successfully (not too hard, though). The navigation mesh hovers the actual geometry by one cell unit, which is correct according to the Godot documentation.

In my player node I've added a NavigationAgent3D and implemented movement in the `_PhysicsProcess` method (using C#, because I'm comfortable with it)

```
public override void _PhysicsProcess(double delta)
{
    if (NavigationAgent.IsNavigationFinished())
    {
        AnimationPlayer.Play("Idle");
        return;
    }

    AnimationPlayer.Play("Walk");

    var currentPosition = Position;
    var nextPosition = NavigationAgent.GetNextPathPosition();
    LookAt(new Vector3(nextPosition.X, currentPosition.Y, nextPosition.Z));
    Velocity = (nextPosition - currentPosition).Normalized() * Speed;

    MoveAndSlide();
}

```

When implementing movement this way, the player would move to the desired position on the navigation mesh, i.e. hovers the actual ground, which might work in some cases, but not for mine.

Moving the `NavigationRegion3D` downwards somehow works, but looks weird when the character moves on stairs, plus the docs say

> Do not expect the NavigationMesh to perfectly follow the original surfaces. Especially navigation polygons placed over ramps will not keep an equal distance to the ground surface. To align an actor perfectly with the ground use other means like physics.

So I tried to correct the players position, but when I'm doing so, the player won't move at all. It looks as if `NavigationAgent.GetNextPathPosition()` won't give the next path position, I assume because the last one is still too far away.

All of the tutorials I've watched did not really address the issues I'm facing and neither does the official documentation as far as I can tell. Having the `NavigationAgent3D` within the player node seems to be the way to go according to Docs: Setup for 3D scene.

What is the correct way to have a `NavigationAgent3D` with a non-floating 3D character?

# Answer
Usually, a good place to start is the godot demos. There's a 3D Navigation demo with a character moving along ramps and multiple levels. However, only the Godot 3.x version of that demo uses NavAgents. But I think you can translate that solution to what you're doing. Here's their code:

```
func _physics_process(delta):
    if _nav_agent.is_navigation_finished():
        return
    var next_position = _nav_agent.get_next_location()
    var offset = next_position - global_position
    global_position = global_position.move_toward(next_position, delta * character_speed)

    # Make the robot look at the direction we're traveling.
    # Clamp y to 0 so the robot only looks left and right, not up/down.
    offset.y = 0
    look_at(global_position + offset, Vector3.UP)

```

If I C#-ifiy that code, it should look roughly like this:

```
NavigationAgent _nav_agent;
public override void _PhysicsProcess(double delta)
{
    if (_nav_agent.IsNavigationFinished())
    {
        AnimationPlayer.Play("Idle");
        return;
    }
    AnimationPlayer.Play("Walk");

    var next_position = _nav_agent.GetNextLocation();
    var offset = next_position - GlobalPosition;
    GlobalPosition = GlobalPosition.MoveToward(next_position, delta * character_speed);

    // Make the robot look at the direction we're traveling.
    // Clamp y to 0 so the robot only looks left and right, not up/down.
    offset.y = 0;
    look_at(GlobalPosition + offset, Vector3.UP);
}

```

Comparing that to your code there are three core differences:

* Movement is done by modifying the transform
* Local vs global positions
* Look is done after movement

## Movement

I'd suggest getting it to work without `MoveAndSlide` first to reduce the scope of your problem. Get NavAgents working first, then start figuring out physics.

## Local vs Global

The code in your question uses `Position` and compares it to the value returned by `GetNextPathPosition`, but the docs say:

> Vector3 get\_next\_path\_position()
>
> Returns the next position in **global coordinates** that can be moved to...

So that's working with positions with two (potentially) different frames of reference so the results are meaningless. (If the player is under the level and the level is at `(100, 0, 0)`, then the values will all have x values off by 100. Use `GlobalPosition` instead.

## LookAt

`LookAt` is calculated based on your current position (imagine looking at a sign and then walking past it without changing your head's direction), so you want to do it after you apply the move.

# Going Further

If that's not sufficient to get your character feeling grounded, then you should look into raycasts to snap them to the ground or IK (Inverse Kinematics) to position their feet on the ground.
> 1 votes

---
Tags: godot, navmesh, godot-4
---


title: Bullet physics linker error

text:
# Question
Title: Bullet physics linker error
I am trying to build my project in VS, which is a copy of HelloWorld.cpp provided by Bullet. I am getting a list of errors of sort "unresolved external symbol" when I build my project, however everything is alright with HelloWorld.cpp.

What I did prior to the event: I have downloaded Bullet from repository, started build\_visual\_studio\_vr\_pybullet\_double.bat as suggested in the guide, which produced .sln file. I opened the file and built BulletDynamics, BulletCollision and LinearMath. Then I added Bullet source folder into my project include directories, as well as generated .lib files for all 3 project to my project additional dependencies (via Project-\>Properties).

What I did to solve the problem:

1. Set Runtime Library = /MT in properties both for my project and bullet (tried various values, but similar on both sides)
2. Built Bullet projects following specific order: Duynamics-\>Collision-\>LinearMath Notjing worked out. Please help!

Source.cpp code for my project applied:

```
#include "btBulletDynamicsCommon.h"
#include <stdio.h>

/// This is a Hello World program for running a basic Bullet physics simulation

int main()
{
///-----includes_end-----

int i;
///-----initialization_start-----

///collision configuration contains default setup for memory, collision setup. Advanced users can create their own configuration.
btDefaultCollisionConfiguration* collisionConfiguration = new btDefaultCollisionConfiguration();

///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded)
btCollisionDispatcher* dispatcher = new btCollisionDispatcher(collisionConfiguration);

///btDbvtBroadphase is a good general purpose broadphase. You can also try out btAxis3Sweep.
btBroadphaseInterface* overlappingPairCache = new btDbvtBroadphase();

///the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded)
btSequentialImpulseConstraintSolver* solver = new btSequentialImpulseConstraintSolver;

btDiscreteDynamicsWorld* dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, overlappingPairCache, solver, collisionConfiguration);

dynamicsWorld->setGravity(btVector3(0, -10, 0));

///-----initialization_end-----

//keep track of the shapes, we release memory at exit.
//make sure to re-use collision shapes among rigid bodies whenever possible!
btAlignedObjectArray<btCollisionShape*> collisionShapes;

///create a few basic rigid bodies

//the ground is a cube of side 100 at position y = -56.
//the sphere will hit it at y = -6, with center at -5
{
    btCollisionShape* groundShape = new btBoxShape(btVector3(btScalar(50.), btScalar(50.), btScalar(50.)));

    collisionShapes.push_back(groundShape);

    btTransform groundTransform;
    groundTransform.setIdentity();
    groundTransform.setOrigin(btVector3(0, -56, 0));

    btScalar mass(0.);

    //rigidbody is dynamic if and only if mass is non zero, otherwise static
    bool isDynamic = (mass != 0.f);

    btVector3 localInertia(0, 0, 0);
    if (isDynamic)
        groundShape->calculateLocalInertia(mass, localInertia);

    //using motionstate is optional, it provides interpolation capabilities, and only synchronizes 'active' objects
    btDefaultMotionState* myMotionState = new btDefaultMotionState(groundTransform);
    btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, groundShape, localInertia);
    btRigidBody* body = new btRigidBody(rbInfo);

    //add the body to the dynamics world
    dynamicsWorld->addRigidBody(body);
}

{
    //create a dynamic rigidbody

    //btCollisionShape* colShape = new btBoxShape(btVector3(1,1,1));
    btCollisionShape* colShape = new btSphereShape(btScalar(1.));
    collisionShapes.push_back(colShape);

    /// Create Dynamic Objects
    btTransform startTransform;
    startTransform.setIdentity();

    btScalar mass(1.f);

    //rigidbody is dynamic if and only if mass is non zero, otherwise static
    bool isDynamic = (mass != 0.f);

    btVector3 localInertia(0, 0, 0);
    if (isDynamic)
        colShape->calculateLocalInertia(mass, localInertia);

    startTransform.setOrigin(btVector3(2, 10, 0));

    //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
    btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
    btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, colShape, localInertia);
    btRigidBody* body = new btRigidBody(rbInfo);

    dynamicsWorld->addRigidBody(body);
}

/// Do some simulation

///-----stepsimulation_start-----
for (i = 0; i < 150; i++)
{
    dynamicsWorld->stepSimulation(1.f / 60.f, 10);

    //print positions of all objects
    for (int j = dynamicsWorld->getNumCollisionObjects() - 1; j >= 0; j--)
    {
        btCollisionObject* obj = dynamicsWorld->getCollisionObjectArray()[j];
        btRigidBody* body = btRigidBody::upcast(obj);
        btTransform trans;
        if (body && body->getMotionState())
        {
            body->getMotionState()->getWorldTransform(trans);
        }
        else
        {
            trans = obj->getWorldTransform();
        }
        printf("world pos object %d = %f,%f,%f\n", j, float(trans.getOrigin().getX()), float(trans.getOrigin().getY()), float(trans.getOrigin().getZ()));
    }
}
system("pause");
///-----stepsimulation_end-----

//cleanup in the reverse order of creation/initialization

///-----cleanup_start-----

//remove the rigidbodies from the dynamics world and delete them
for (i = dynamicsWorld->getNumCollisionObjects() - 1; i >= 0; i--)
{
    btCollisionObject* obj = dynamicsWorld->getCollisionObjectArray()[i];
    btRigidBody* body = btRigidBody::upcast(obj);
    if (body && body->getMotionState())
    {
        delete body->getMotionState();
    }
    dynamicsWorld->removeCollisionObject(obj);
    delete obj;
}

//delete collision shapes
for (int j = 0; j < collisionShapes.size(); j++)
{
    btCollisionShape* shape = collisionShapes[j];
    collisionShapes[j] = 0;
    delete shape;
}

//delete dynamics world
delete dynamicsWorld;

//delete solver
delete solver;

//delete broadphase
delete overlappingPairCache;

//delete dispatcher
delete dispatcher;

delete collisionConfiguration;

//next line is optional: it will be cleared by the destructor when the array goes out of scope
collisionShapes.clear();
}

```

# Answer
> 0 votes
Your question doesn't provide enough information. In most cases you should check where each error comes from (which function), and resolve the linking errors, as they appear.

---
Tags: c++, visual-studio, bullet-physics
---


# Question
Title: Adaptation of values from previous constant frame rate to new constant frame rate
I'm trying to learn how to adapt my old values to new values. First of all, I don't use delta time at all. My game has lock with 30 FPS and I want to lock it with 60 FPS, I wrote all my values in pixels per frame. I can't just multiply by 0.5 ratio when it's not a linear equation. For example:

```
// INIT

speed = 10;
gravity = 1;
position = 0;

// UPDATE

speed += gravity;
position += speed;

```

When I reach frame 30 with 30 FPS lock, **speed** is equal to 40 and **position** is equal to 765. If I lock to 60 FPS, I want to get half of **speed** and **position** on frame 30 and same values on frame 60.

I have seen many topics about this problem, but still can't figure out how to just adapt these values a single time for new FPS lock to have the same behavior as before.

Generally, I want to learn how to read these equations to come up with formulas inside them to build graphs or something (I mean, when people show formulas from Wolfram, they somehow break down equations and read them as formulas).

# Answer
> 1 votes
First, we know that if we halve the timestep, we have to halve the gravity, so that we still add the same total amount to the speed when we run twice as many iterations.

Adjusting the initial speed or velocity is a little more nuanced. The equation for continuous motion under constant acceleration is:

$$\vec p (t) = \vec p\_0 + t \vec v\_0 + t^2 \frac {\vec a} 2$$

But using an Euler integrator like in your code is a discrete approximation of this that adds some integration error — so your object won't trace exactly the same parabola as the continuous physics would suggest.

It turns out that this integration error is exactly equivalent to shifting the initial velocity by one half a timestep. It's like, anytime you read/write the velocity in the Euler simulation, you're actually looking at the object slightly in the past, compared to its position.

So, we can convert between these modes just by adding/subtracting one half a time step's worth of acceleration. If we have two objects following exactly the same parabola of positions over time, one moving continuously with initial velocity \\$\vec v\_\infty\\$ and one moving discretely at some fixed fps with initial velocity \\$\vec v\_{fps}\\$, that looks like this:

$$\vec v\_\infty = v\_{fps} + \vec a \frac 1 {fps \cdot 2}\\ \vec v\_{fps} = v\_\infty - \vec a \frac 1 {fps \cdot 2}$$

So to get from your 30 fps initial velocity to 60, we first add half a 30 fps step of gravity to get to the velocity for the continuous sim, then subtract half a 60 fps step of gravity to get the initial velocity for the 60 fps sim:

$$\begin{align} v\_{60} &= v\_\inf - \frac {g\_{60}} 2\\ &= v\_{30} + \frac {g\_{30}} 2 - \frac {g\_{30}} 4\\ &= v\_{30} + \frac {g\_{30}} 4\\ &= 1 + \frac {10} 4\\ &= 1 + 2.5\\ &= 3.5 \end{align}$$

So your new initial velocity for this object is 3.5 instead of 1. Adding half this velocity to your position each frame will exactly reproduce the positions seen in your 30 fps sim, just two ticks apart. (We add half because we haven't changed the units — we're still measuring speed in "pixels per thirtieth of a second" to keep it directly comparable for any calculations you have that are checking it against threshold speeds)

Here's a spreadsheet proving these match as desired \- you can click in the cells to see the exact calculations I'm doing at each step:

There is a wrinkle though: the speed you get after some even number of ticks won't exactly match the speed you had at half that many ticks in the 30 fps case. That's again due to this time-shifting. Where the 30 fps sim was giving us speeds measured at \\$t - \frac 1 {60}\\$ in the continuous world, our 60 fps sim is telling us what the speed was at \\$t - \frac 1 {120}\\$. So you need to subtract half a (60 fps) timestep's acceleration from the speed to see the same value you got from the 30 fps sim at the corresponding tick.

---
Tags: physics, mathematics, frame-rate
---


# Question
Title: Vertex Shader Sphere Projection and CPU Distance Calculation
I have multiple planes whose vertices are transformed to a position on a sphere in the vertex shader. The GLSL function called `pointToSphere` transforms a point `p` to a position on a sphere with a radius of 100 units centered around `localcenter`.

I need to find a way to calculate the distance between the newly transformed planes and some position `C` on the CPU side. My algorithm has `N` number of planes for each side, and I need to find the distance between each plane and point `C`, not the entire sphere.

This doesn’t work `plane.distanceTo(C)`

CODE EXAMPLE:

```
let camera, scene,rtCamera,renderTarget,rtScene, renderer;
let uniforms, mesh, w;
let bbox  = new THREE.Box3();

renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setClearColor('white');
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
document.body.appendChild(renderer.domElement);

function vertexShader() {
  return `
    uniform vec3 wTl;
    uniform vec3 ps;
 vec3 pointToSphere(vec3 p, vec3 localCenter){
    return 100.0*normalize(p-localCenter) + localCenter;
  }

varying vec3 v3n;
    void main() {
      vec3 newPosition   =  pointToSphere(position,wTl) ;
      gl_Position = projectionMatrix  * modelViewMatrix * vec4( newPosition, 1.0 ) ;
    }
  `
}

function fragmentShader(){
  return `
    uniform vec3 ucolor;
    void main() {
      gl_FragColor  = vec4(ucolor,1.0);
    }
`
}

init();

function init() {
    w = 100
    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 0.001, 100000);
    camera.position.z = 250;
    scene.add(camera);

    let controls = new THREE.OrbitControls(camera, renderer.domElement);

    var front = buildMesh();
    var fg = new THREE.Group(front)
    fg.add(front)

    var back = buildMesh();
    var bg = new THREE.Group(back)
    bg.add(back)
    bg.position.z = -w;
    bg.rotation.y=(Math.PI)

    var right = buildMesh();
    var rg = new THREE.Group(right)
    rg.add(right)
    rg.position.z = -((w)/2);
    rg.position.x =  ((w)/2);
    rg.rotation.y = (Math.PI/2)

    var left = buildMesh();
    var lg = new THREE.Group(left)
    lg.add(left)
    lg.position.z = -((w)/2);
    lg.position.x = -((w)/2);
    lg.rotation.y=(-Math.PI/2)

    var top = buildMesh();
    var tg = new THREE.Group(top)
    tg.add(top)
    tg.position.z = -((w)/2);
    tg.position.y = ((w)/2);
    tg.rotation.x=(-Math.PI/2)

    var bot = buildMesh();
    var bog = new THREE.Group(bot)
    bog.add(bot)
    bog.position.z = -((w)/2);
    bog.position.y = -((w)/2);
    bog.rotation.x=(Math.PI/2)

    var g = new THREE.Group()
    g.add(fg)
    g.add(bg)
    g.add(lg)
    g.add(rg)
    g.add(tg)
    g.add(bog)

  scene.add(g)
    var sides = [
      ...fg.children,
      ...bg.children,
      ...rg.children,
      ...lg.children,
      ...tg.children,
      ...bog.children,
    ]

    var cnt = centerPosition(g)
    var localCenter = new THREE.Vector3();
    for (let index = 0; index < sides.length; index++) {
      const element = sides[index];
      let color = new THREE.Color( 0xffffff );
      color.setHex( Math.random() * 0xffffff );
      element.worldToLocal(localCenter.copy(cnt))
      element.material.uniforms['wTl'].value = localCenter
      element.material.uniforms['ps'].value = element.position
      element.material.uniforms['ucolor'].value = color

    }

  }

  function buildMesh(t){
    let geometry = new THREE.PlaneGeometry(w, w,50,50);
    uniforms = {
      ucolor:{value:new THREE.Vector3()},
      wTl:   {value:new THREE.Vector3()},
      ps:    {value:new THREE.Vector3()}
               };
    let material = new THREE.ShaderMaterial({
      uniforms: uniforms,
      fragmentShader: fragmentShader(),
      vertexShader: vertexShader(),
      wireframe:false
    });

    var mesh = new THREE.Mesh(geometry, material);
    return mesh
  }

  function centerPosition(g) {
    bbox.expandByObject(g);
    var center = new THREE.Vector3();
    bbox.getCenter(center);
    return center
  }

update()

function update(t) {
  renderer.render(scene, camera);
  requestAnimationFrame (update);
}
```

```
 <script src="https://cdn.jsdelivr.net/npm/three@0.132.2/build/three.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/three@0.132.2/examples/js/controls/OrbitControls.js"></script>
```

# Answer
> 3 votes
I ended up finding an answer. To obtain the center of a projected plane that is projected on the GPU, you need to take the position of the unprojected plane and project it.

```
function project( v, r, center ){
    v.sub( center ).setLength( r ).add( center );
}

let positionCenter = new THREE.Vector3()
project(positionCenter,radiusOfSphere,centerOfSphere)

```

This will give you the center of the mesh then use `plane.localToWorld(positionCenter) positionCenter.distanceTo(C)` to get the correct distance.

The solution can be seen here: https://github.com/miguelmyers8/PlanetTechJS/blob/main/src/lib/PlanetTech/sphere/sphere.js

---
Tags: mathematics, shaders, glsl, geometry
---


# Question
Title: Difference in glDrawArrays and glDrawElements
While refreshing my mind on OpenGL ES, I came across `glDrawArrays` and `glDrawElements`.

I understand how they are used and sort of understand why they are different.

What I do not seem to understand is that, I fail to see how `glDrawElements` can save draw calls (***saving draw calls*** is a description that is mentioned by most of the books I have read, hence my mentioning of it here).

Imagine a simple scenario in which I tried to draw a square using 2 triangles.

I would need to have a set of 6 vertices using `glDrawArrays` while using `glDrawElements`, I would need only 4 in addition to an index array that has 6 elements.

Given the above, here is what I do not understand:

1. how could `glDrawElements` save draw calls, if it still needs to use the index array (6 indices, in case of a square) to index into my vertex array that had 4 elements (6 times)? Other words, does it mean `glDrawElements` would still need to have a total of 6 draw calls just like `glDrawArrays`?
2. how would using `glDrawElements` save space, if one would still need to have 2 arrays, namely, one for the vertices and one for the indices?
3. In the case of drawing a square from 2 triangles, for simplicity, how many draw calls does `glDrawElements` (4 items in vertex array and 6 items in index array) and `glDrawArrays` (6 items only in vertex array) need, individually?

Thanks.

# Answer
Each glDraw\* is a draw call.

1 glDrawArrays is 1 draw call.
1 glDrawElements is 1 draw call.

It doesn't matter (so far as draw call count is concerned) how many vertices or indices you use, 1 glDraw\* is 1 draw call.

The simple cases of drawing quads (assuming the GL version you use hasn't removed quads) or triangles are not a good example for comparing these, because a list of quads or a list of triangles can be drawn with a single call to either, and glDrawArrays will appear more efficient because it doesn't have the additional overhead of indexing.

Let's take a slightly more complex case, but one which is representative of a more real-world scenario. Imagine that you have a model composed of multiple triangle strips and fans:

```
glDrawArrays (GL_TRIANGLE_FAN, .....);
glDrawArrays (GL_TRIANGLE_STRIP, .....);
glDrawArrays (GL_TRIANGLE_STRIP, .....);
glDrawArrays (GL_TRIANGLE_FAN, .....);
glDrawArrays (GL_TRIANGLE_STRIP, .....);
glDrawArrays (GL_TRIANGLE_FAN, .....);

```

In this example, using glDrawArrays gives you a total of 6 draw calls for the model. However, both strips and fans can easily be converted to indexed triangles, so add indices and it becomes:

```
glDrawElements (GL_TRIANGLES, .....);

```

That's one draw call, for the entire model.

---

The advantages of glDrawElements over glDrawArrays are more than just memory saving, which is the naive way of measuring it. There is *potential* for memory saving where vertices can be reused, because an index is typically smaller than a vertex (so even if you have lots of indices on balance they'll be smaller), but other advantages include:

* Reduced draw call count. Each draw call incurs some overhead from validating state, setting things up, etc, and much of this overhead happens on the CPU side. By reducing the number of draw calls we avoid much of this overhead.
* Vertex reuse. This is much more than just memory-saving. Your GPU likely has a hardware vertex cache, where recently transformed vertices can be stored; if the same vertex comes in again, and if it's in the cache, it can be reused from the cache rather than having to transform again. Your hardware will check the cache by comparing indices, so in OpenGL terms the only way you get to use the cache is to use glDrawElements.

---

So to answer your specific questions:

1. **how could glDrawElements save draw calls...?** In the example you use, it doesn't. Each has one draw call. As I discuss above, this example is a very bad one for comparing the two.
2. **how would using glDrawElements save space...?** Because indices are smaller than vertices. A 16-bit index is two bytes, a position/color/texcoord vertex is 24 bytes. 6 vertices is 144 bytes, 4 vertices plus 6 indices is 108 bytes.
3. **In the case of drawing a square from 2 triangles...?** One and one. A glDraw\* call is one draw call, the number of vertices or indices used is irrelevant for this measurement. But I must re-emphasise, this is a very bad example for comparing the two.

---

Finally, and just to complicate matters a little, while glDrawElements with triangles is the optimal path on desktop GPUs, on mobile it might be very different. Some mobile GPUs might prefer glDrawArrays with GL\_TRIANGLE\_STRIP (you would add degenerate triangles to concatenate primitives in this case), and I haven't even touched on more advanced topics such as primitive restart or multi-draw.
> 26 votes

# Answer
When you use `glDrawArrays` you have to choose an indexing pattern, one of `GL_TRIANGLES`, `GL_TRIANGLE_STRIP` or `GL_TRIANGLE_FAN`. This determines the indexing pattern into your buffers for the whole draw call (single call to `glDrawArrays`). If you choose `GL_TRIANGLES` the indexing pattern means you must provide data independently for each vertex, even if that vertex is "shared" with another triangle. More importantly, for the same point location shared by two different triangles, you can have an different normal vector. So it would be possible to shade that triangle visibly as an independent triangle, if you were going for a low-poly look for example.

With `GL_TRIANGLE_STRIP` or `GL_TRIANGLE_FAN` you are sharing vertex and normal data between triangles, and for normals this means you get smooth shading - you could not create that hard edge between the triangles if you wanted that.

See the indexing patterns for those 3 constants described here.

These indexing patterns used for `glDrawArrays` are fixed. This means you need to order your vertexes so that these indexes refer to your vertexes in counter-clockwise order (by default, but configurable in OpenGL to clockwise order using `glFrontFace`). Even if your normals are facing the right way, OpenGL may not draw your triangles if they are not wound the right way. This is called "face culling" and is also configurable. It's disabled by default, and can be set to front or back, but it's encouraged to enable it because it can save useless calls into your shaders. It's complicated because what gets culled is a combination of the order of your vertexes in your vertex buffer, the winding order you set with `glFrontFace` and the value you set for `glCullFace`.

With `glDrawElements` you provide a buffer of indexes to use. This gives you full control of the order that your vertexes are referenced in order to construct a triangle. So your vertexes could be ordered clockwise in your vertex buffer, but you could use an index pattern that constructs your triangle in counter-clockwise order. More importantly, it allows you to be more flexible:

For example, imagine you want a flat shading effect but you want this to be quad-based - each quad should be shaded visibly with hard edges around the quad, but you don't need a visible edge in the diagonal across the quad. You ideally want to only specify 4 vertexes and 4 (identical) normals for each quad. If you choose `glDrawArrays` with `GL_TRIANGLES` you would be forced to store 6 vertexes and 6 normals per quad. If you choose `GL_TRIANGLE_STRIP` you would only need to store 2 vertexes and 2 normals per quad (plus two extra at the start of the strip), but the normals would be shared between quads so you would get smooth shading on the edges between the quads. But if you use `glDrawElements` you can use an index pattern where the vertexes and normals on each end of the diagonal are shared with the triangles on either side of the diagonal, but vertexes and normals are not shared between each quad.

With `glDrawArrays` you are choosing an indexing pattern that applies for the whole draw call. However, with `glDrawElements` you can specify a mixed indexing pattern within the single draw call. So you could have the first X triangles with flat shading, some more triangles with smooth shading, some quads with flat shading, etc - all with a single call to `glDrawElements`. However, you have to generate, store and load that index buffer onto the GPU, which adds extra time and takes extra space.
> 1 votes

---
Tags: opengl, opengl-es, memory-efficiency, vertex-arrays, index-buffer
---