title: Initializing Monobehaviour in Unity

text:
# Question
Title: Initializing Monobehaviour in Unity
I have three scritps and one plain C# class.
EnemyMonobehaviour, EnemyAttackMonobehaviour and UnitState plain class.

In enemyMono I have Initialize function that initializes unitState.

```
public void Initialize(float moveSpeed, Transform[] waypoints,
    Damage damage, Armor armor, Health health, float magicalResistance, int bounty) {

    this.unitState = new UnitState(damage, armor, health, magicalResistance);

    this.bounty = bounty;

    GetComponent<EnemyFollowPath>().Initialize(moveSpeed, waypoints);
}

```

I have a WaveManager class that spawns different enemies and than later it initializes them.

```
GameObject enemyUnit = container.InstantiatePrefab(enemy.prefab, spawningPoint, Quaternion.identity, null);
enemyUnit.GetComponent<Enemy>().Initialize(2f, EnemyPath.Instance.getWaypoints(),
            new Damage(enemy.damageType, enemy.attackType, enemy.minDamage, enemy.maxDamage),
            new Armor(enemy.armorType, enemy.armor),
            new Health(enemy.maxHealth), 10, enemy.bounty);

```

And now here is where the problem appears. EnemyAttack is initialized like this

```
private void Awake() {
    this.enemy = GetComponent<Enemy>();

    IUnitState unitState = enemy.GetState();

    minDamage = unitState.GetDamage().minDamage;
    maxDamage = unitState.GetDamage().maxDamage;
    damageType = unitState.GetDamage().damageType;
    attackType = unitState.GetDamage().attackType;
}

```

EnemyAttack.Awake() is being called before the `Initialize` function from the Enemy script while unit state is still `null`. So the question is how to correctly initialize monobehaviour component field values if there are some fields that cannot be passed as SerializeFields or Prefabs in Editor and need to be passed down during Instantiation?

Also I don't want to initialize EnemyAttack From Enemy.Initialize function. My initial approach was to have EnemyMono that contains various properties that other scripts can use like EnemyAttack, EnemyFollowPath and so on. They just need to acquire Enemy reference with GetComponent();

# Answer
you could try using https://docs.unity3d.com/ScriptReference/MonoBehaviour.Start.html instead Awake, should do the trick. Or handle actual initialization and "begin" execution manually.
> 0 votes

# Answer
You can have the factory method where you instantiate the prefab in `WaveManager` also call `Initialize` on the `EnemyAttack` after you initialize `Enemy`. There you would execute the code currently in `Awake`. This allows you to control how you initialize these components that depend on each other and orchestrate the order in which that happens.
> 0 votes

---
Tags: unity, architecture, monobehaviour
---


# Question
Title: How can the player jump on top of the enemy, damage the enemy and the player does not get damaged?
Currently, when the player jumps on top of an enemy, the player and the enemy take damage.

I'm trying to figure out a way that only the enemy gets damaged when the player jumps on top of the enemy and so the player does not get damaged. I have two colliders on the enemy (image below). One collider under the Enemy gameObject (wider, bottom collider) and then there's a child gameObject under Enemy called Receive Damage Check that has a collider (top, smaller collider player jumps on). There is a hazard Layer that the enemy gameObject is on. The child gameObject, Receive Damage Check, underneath the enemy is not on the hazard Layer.

The goal is to have the Receive Damage Check collider register the player collided with it and only damage the Enemy.

Base class:

```
public class Character : MonoBehaviour {

    public int maxHealth;
    public int currentHealth;
    public HealthBar healthBar;

    [SerializeField] protected float damageInterval = 2f; //in seconds
    protected float currentDamageInterval;

    protected SpriteRenderer sr;
    private Rigidbody2D rb;

    protected virtual void Start() {
        sr = GetComponent<SpriteRenderer>();
        rb = GetComponent<Rigidbody2D>();
        currentHealth = maxHealth;
        healthBar.SetMaxHealth(maxHealth);
    }

    protected virtual void Update() {
        //subtract 1 real life second
        if (currentDamageInterval >= 0)
            currentDamageInterval -= Time.deltaTime;
    }

    public bool CanTakeDamage() {
        return (currentDamageInterval < 0);
    }

    public virtual void TakeDamage(int damage) {
        currentHealth -= damage;
        healthBar.SetHealth(currentHealth);

        int yDamageVelocity = 15;
        rb.velocity = new Vector2(rb.velocity.x, yDamageVelocity);

        //set currentDamageInterval to start a new cooldown/delay period (2 seconds)
        currentDamageInterval = damageInterval;
    }
}

```

Children classes:

```
public class Player : Character {

    [SerializeField] private Transform groundCheck;
    [SerializeField] private LayerMask hazardLayer;

    private Color[] colors = { Color.red, Color.white };
    private Coroutine damageFlash;

    protected override void Start() {
        base.Start();
        maxHealth = 10;
    }

    protected override void Update() {
        base.Update();
        //if the current number in the currentDamageInterval is <= 0 or in other words if
        //2 seconds of delay has passed, take damage
        if (CanTakeDamage())
            if (Physics2D.OverlapCircle(groundCheck.position, 0.5f, hazardLayer)) {
                TakeDamage(1);
            }

        //for testing purposes
        if (Input.GetKeyDown(KeyCode.H))
            TakeDamage(1);
    }

    public override void TakeDamage(int damage) {
        base.TakeDamage(damage);
        //guarantee at most, one coroutine runs at a time
        if (damageFlash != null)
            StopCoroutine(damageFlash);
        damageFlash = StartCoroutine(DamageFlashing(1f, .1f));
    }

    IEnumerator DamageFlashing(float duration, float interval) {
        int index = 0;
        //var is a replacement for WaitForSeconds bc it would be redundant
        var wait = new WaitForSeconds(interval);

        for (float elapsedTime = 0; elapsedTime < duration; elapsedTime += interval) {
            //divides the index by 2 and returns the remainder
            sr.color = colors[index % 2];
            index++;
            //waits the interval time and then continues the next color in the flashing duration
            yield return wait;
        }
        damageFlash = null;
    }
}

```

```
public class Enemy : Character {

    protected override void Start() {
        maxHealth = 3;
        base.Start();
    }

    private void OnCollisionEnter2D(Collision2D collision) {
        if (collision.gameObject == GameObject.FindWithTag("Player"))
            if (CanTakeDamage())
                TakeDamage(1);
    }
}

```

# Answer
> 1 votes
When you detect the top collider colliding with the player you can try disabling the enemy bottom collider or flag it as unable to inflict damage for a short while using a coroutine. If both colliders are triggered at the same time you are still in trouble. In which case you might do as Egor suggests and test if the player is on above the enemy and block it from inflicting damage on the player.

# Answer
> 1 votes
I would do this with only one collider and then analyze the contact points to decide who gets hurt.

```
private void OnCollisionEnter2D(Collision2D collision) {
    if (collision.gameObject == GameObject.FindWithTag("Player"))
       var contact = collision.GetContact(0);
       Vector2 collisonPoint = contact.point;

```

Now you have one of the points in world space where the colliders of player and enemy touched. When its y-component is on the upper edge of the enemy collider, that means the player hit form above. When it's further down, the player hit from the side or from below.

```
      if(collisionPoint.y >= GetComponent<Collider2D>().bounds.max.y) {
         // Player hits from above
      } else {
        // Player hits from side or below
      }

```

Note that this particular code sample uses the axis-aligned bounding box of the collider. This box should be equal to the collider if it is a non-rotated box collider. When you use more complex colliders, then the bonds might be larger than you would expect, so you might have subtract a bit from it or access the type-specific properties of the particular type of collider you are using.

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


# Question
Title: How to rotate 2D image in 3D space using a quaternion
I am trying to rotate a flat 2D image around a 2D origin in 3D space. The problem I am having is that the image becomes stretched after the rotation. I am using the WGSL from this tutorial, but with the camera logic removed. The clip-coordinates have to be a 3d vector + `w`.

Here is what the sprite is meant to look like:

Here is what the sprite looks like when rotated 45 degrees:

I am using the cgmath crate for the quaternions. I have tried creating a quarternion from the Z angle:

```
let rotation = Quaternion::from_angle_z(cgmath::Deg(rotation));

```

And also tried manually:

```
let rotation = Quaternion::from_axis_angle(
    Vector3 {
            x: 0.0,
            y: 0.0,
            z: 1.0,
    },
    cgmath::Deg(rotation).normalize(),
);

```

I tried making a matrix that looks like this:

$$\begin{bmatrix} \cos \theta & -\sin \theta & 0 & 0\\ \sin \theta & \cos \theta & 0 & 0\\ 0 & 0 & 1 & 0\\ 0 & 0 & 0 & 1 \end{bmatrix}$$

and I have also tried calling `from_axis_angle` using the normalised position as the axis argument.

All of these solutions have resulted in the same effect.

I also tried manually rotating the vertices, however, this just caused the position of the 2D image to rotate further.

Vertex shader to manually rotate each vertex:

```
struct EntityInput {
    @location(5) position: vec2<f32>,
    @location(6) origin: vec2<f32>,
    @location(7) rotation: f32,
    @location(8) scale: f32,
}

@vertex
fn vs_main(
    model: VertexInput,
    entity: EntityInput,
) -> VertexOutput {
    var out: VertexOutput;
    var orig_x: f32 = model.position.x - entity.origin.x;
    var orig_y: f32 = model.position.y - entity.origin.y;
    var new_x = (orig_x * cos(entity.rotation)) - (orig_y * sin(entity.rotation));
    var new_y = (orig_y * cos(entity.rotation)) + (orig_x * sin(entity.rotation));
    var final_x = new_x + entity.origin.x;
    var final_y = new_y + entity.origin.y;
    var final_vec = (vec4<f32>(final_x, final_y, 1.0, 1.0) + vec4<f32>(entity.position, 0.0, 0.0));
    final_vec.x = final_vec.x * entity.scale;
    final_vec.y = final_vec.y * entity.scale;
    out.tex_coords = model.tex_coords;
    out.clip_position = final_vec;
    return out;
}

```

# Answer
I managed to solve the problem, I was normalising the initial coordinates of where the vertexes should be for the sprite. For some reason, this cause the sprite to warp as it rotated, almost as if the vertexes were being normalised repeatedly against wrong values due to rotation.

The solution was to using pixel values only within the main Rust code, then normalise the very final clip coordinate at the end of the vertex shader:

@vertex
fn vs_main(
    model: VertexInput,
    entity: EntityInput,
) -> VertexOutput {
    var screen_width = 562.0;
    var screen_height = 1021.0;
    var out: VertexOutput;
    var orig_x: f32 = model.position.x - entity.origin.x;
    var orig_y: f32 = model.position.y - entity.origin.y;
    var new_x = (orig_x * cos(entity.rotation)) - (orig_y * sin(entity.rotation));
    var new_y = (orig_y * cos(entity.rotation)) + (orig_x * sin(entity.rotation));
    var final_x = new_x + entity.origin.x;
    var final_y = new_y + entity.origin.y;
    var final_vec = (vec4<f32>(final_x, final_y, 0.0, 0.0) + vec4<f32>(entity.position, 0.0, 0.0));
    final_vec = vec4<f32>(normalise(vec2<f32>(final_vec.x, final_vec.y), screen_width, screen_height), 1.0, 1.0);
    out.tex_coords = model.tex_coords;
    out.clip_position = final_vec;
    return out;
}

fn normalise(given: vec2<f32>, width: f32, height: f32) -> vec2<f32> {
    var new_vec: vec2<f32>;
    new_vec.x = ((2.0 * (given.x)) / width) - 1.0;
    new_vec.y = ((2.0 * (given.y)) / height) - 1.0;
    return new_vec;
}
```

> 0 votes

---
Tags: 3d, rotation, rust
---


# Question
Title: D3D11 Indices are Messed Up and Doesn't Follow my Primitive Topology
I am attempting to create a cube but I have been stuck on this for a very long time to no avail.

My results look like this:

All of my indices are messed up! Some are connected to the wrong vertices and most weirdly the light blue vertex is alone; it isn't a complete triangle.

Here is my initialization function:

```
swap_chain_description.BufferDesc.Width = 0; // Figure it out yourself
swap_chain_description.BufferDesc.Height = 0;
swap_chain_description.BufferDesc.Format = DXGI_FORMAT::DXGI_FORMAT_B8G8R8A8_UNORM; // Layout of pixels
swap_chain_description.BufferDesc.RefreshRate.Numerator = 0; // Pick whatever is already there
swap_chain_description.BufferDesc.RefreshRate.Denominator = 0; // Pick whatever is already there
swap_chain_description.BufferDesc.Scaling = DXGI_MODE_SCALING::DXGI_MODE_SCALING_UNSPECIFIED; // Don't need scaling
swap_chain_description.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER::DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; // Scanline order (Interlaced, etc)
swap_chain_description.SampleDesc.Count = 1; // No anti-aliasing
swap_chain_description.SampleDesc.Quality = 0; // No anti-aliasing
swap_chain_description.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // Use buffer as render target
swap_chain_description.BufferCount = 1; // One back buffer
swap_chain_description.OutputWindow = window; // Use this window
swap_chain_description.Windowed = true; // We want it windowed
swap_chain_description.SwapEffect = DXGI_SWAP_EFFECT::DXGI_SWAP_EFFECT_DISCARD; // Swap effect that usually has the best performance
swap_chain_description.Flags = 0u; // No flags

D3D11CreateDeviceAndSwapChain(
    nullptr, // Choose default adapter
    D3D_DRIVER_TYPE::D3D_DRIVER_TYPE_HARDWARE, // Use hardware device
    nullptr, // Handle to driver
    0, // No flags
    nullptr, // Give us any feature level
    0,
    D3D11_SDK_VERSION, // Default SDK Version
    &swap_chain_description, // Swap chain description
    &swap_chain, // Swap Chain
    &device, // Device
    nullptr, // Output pointer - Sets to feature level
    &context // Context
);

Microsoft::WRL::ComPtr<ID3D11Resource> back_buffer = nullptr;
swap_chain->GetBuffer(0, __uuidof(ID3D11Resource), &back_buffer);
device->CreateRenderTargetView(
    back_buffer.Get(),
    nullptr,
    &target
);

// Create depth stencil state
D3D11_DEPTH_STENCIL_DESC depth_stencil_description = {};
depth_stencil_description.DepthEnable = true;
depth_stencil_description.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depth_stencil_description.DepthFunc = D3D11_COMPARISON_LESS;
Microsoft::WRL::ComPtr<ID3D11DepthStencilState> depth_stencil_state;
device->CreateDepthStencilState(&depth_stencil_description, &depth_stencil_state);

// Bind depth state
context->OMSetDepthStencilState(depth_stencil_state.Get(), 1u);

//Create depth stencil texture
Microsoft::WRL::ComPtr<ID3D11Texture2D> depth_stencil;
D3D11_TEXTURE2D_DESC desc_depth = { };
desc_depth.Width = 800u;
desc_depth.Height = 600u;
desc_depth.MipLevels = 1u;
desc_depth.ArraySize = 1u;
desc_depth.Format = DXGI_FORMAT::DXGI_FORMAT_D32_FLOAT;
desc_depth.SampleDesc.Count = 1u;
desc_depth.SampleDesc.Quality = 0u;
desc_depth.Usage = D3D11_USAGE::D3D11_USAGE_DEFAULT;
desc_depth.BindFlags = D3D11_BIND_FLAG::D3D11_BIND_DEPTH_STENCIL;
device->CreateTexture2D(&desc_depth, nullptr, &depth_stencil);

// Create depth stensil state
D3D11_DEPTH_STENCIL_VIEW_DESC descDSV = { };
descDSV.Format = DXGI_FORMAT::DXGI_FORMAT_D32_FLOAT;
descDSV.ViewDimension = D3D11_DSV_DIMENSION::D3D11_DSV_DIMENSION_TEXTURE2D;
descDSV.Texture2D.MipSlice = 0u;
device->CreateDepthStencilView(depth_stencil.Get(), &descDSV, &depth_stencil_view);

Microsoft::WRL::ComPtr<ID3D11RasterizerState> rasterizer_state = nullptr;
D3D11_RASTERIZER_DESC rasterizer_state_description = { };
rasterizer_state_description.FillMode = fill_mode;
rasterizer_state_description.CullMode = cull_mode;
rasterizer_state_description.FrontCounterClockwise = true;
rasterizer_state_description.DepthBias = false;
rasterizer_state_description.DepthBiasClamp = 0;
rasterizer_state_description.SlopeScaledDepthBias = 0;
rasterizer_state_description.DepthClipEnable = true;
rasterizer_state_description.ScissorEnable = false;
rasterizer_state_description.MultisampleEnable = false;
rasterizer_state_description.AntialiasedLineEnable = false;
HANDLE_POSSIBLE_EXCEPTION(device->CreateRasterizerState(&rasterizer_state_description, rasterizer_state.GetAddressOf()));

context->RSSetState(rasterizer_state.Get());

// Configure Viewport
viewport.Width = 800u;
viewport.Height = 600u;
viewport.MinDepth = 0;
viewport.MaxDepth = 1;
viewport.TopLeftX = 0;
viewport.TopLeftY = 0;
context->RSSetViewports(1u, &viewport);

Microsoft::WRL::ComPtr<ID3D11BlendState> blend_state = nullptr;
D3D11_BLEND_DESC blend_description = {};
ZeroMemory(&blend_description, sizeof(D3D11_BLEND_DESC));
blend_description.RenderTarget[0].BlendEnable = true;
blend_description.RenderTarget[0].SrcBlend = D3D11_BLEND::D3D11_BLEND_SRC_ALPHA;
blend_description.RenderTarget[0].DestBlend = D3D11_BLEND::D3D11_BLEND_INV_SRC_ALPHA;
blend_description.RenderTarget[0].BlendOp = D3D11_BLEND_OP::D3D11_BLEND_OP_ADD;
blend_description.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND::D3D11_BLEND_ONE;
blend_description.RenderTarget[0].DestBlendAlpha = D3D11_BLEND::D3D11_BLEND_ZERO;
blend_description.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP::D3D11_BLEND_OP_ADD;
blend_description.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE::D3D11_COLOR_WRITE_ENABLE_ALL;
device->CreateBlendState(&blend_description, &blend_state);

context->OMSetBlendState(blend_state.Get(), 0, 0xffffffff);

// Set Primitive Topology to triangle list
set_primitive_topology(primitive_topology);

context->OMSetRenderTargets(1u, target.GetAddressOf(), depth_stencil_view.Get());

```

My primitive topology is set to `D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST`, which is why I'm confused about why there is that uncompleted triangle in the result.

This is my draw function:

```
set_vertex_buffer(object);
set_index_buffer(object);

/* I don't think the shader and constant buffer business matters so I didn't include it here, it's here though */

// Draw it
context->DrawIndexed((UINT)object.appearance.mesh.indices.size(), 0u, 0u);

```

Setting my index and vertex buffers is straight-forward:

```
Microsoft::WRL::ComPtr<ID3D11Buffer> vertex_buffer = nullptr;

// Buffer Description (Vertex)
D3D11_BUFFER_DESC buffer_description = {  };
buffer_description.BindFlags = D3D11_BIND_VERTEX_BUFFER;
buffer_description.Usage = D3D11_USAGE_DEFAULT;
buffer_description.CPUAccessFlags = 0u;
buffer_description.MiscFlags = 0u;
buffer_description.ByteWidth = sizeof(Vertex) * object.appearance.mesh.vertices.size();
buffer_description.StructureByteStride = sizeof(Vertex);
D3D11_SUBRESOURCE_DATA data = {  };
data.pSysMem = &object.appearance.mesh.vertices[0];

// Creating the Buffer
device->CreateBuffer(&buffer_description, &data, &vertex_buffer);

// Bind Vertex Buffer to Pipeline
UINT stride = sizeof(Vertex);
UINT offset = 0u;
context->IASetVertexBuffers(0u, 1u, vertex_buffer.GetAddressOf(), &stride, &offset);

```

and

```
Microsoft::WRL::ComPtr<ID3D11Buffer> index_buffer;
D3D11_BUFFER_DESC index_buffer_description = { };
index_buffer_description.BindFlags = D3D11_BIND_INDEX_BUFFER;
index_buffer_description.Usage = D3D11_USAGE_DEFAULT;
index_buffer_description.CPUAccessFlags = 0u;
index_buffer_description.MiscFlags = 0u;
index_buffer_description.ByteWidth = sizeof(USHORT) * object.appearance.mesh.indices.size();
index_buffer_description.StructureByteStride = sizeof(USHORT);
D3D11_SUBRESOURCE_DATA subresource_data = { };
subresource_data.pSysMem = &object.appearance.mesh.indices[0];
device->CreateBuffer(&index_buffer_description, &subresource_data, &index_buffer);
// Bind index buffer
context->IASetIndexBuffer(index_buffer.Get(), DXGI_FORMAT_R16_UINT, 0u);

```

Here is where I'm initializing my vertices and indices, I also drew them out:

```
Mesh mesh = {
     {
        {-1.0f, -1.0f, -1.0f, 255, 0, 0, 255},
        { 1.0f, -1.0f, -1.0f, 0, 255, 0, 255 },
        { -1.0f, 1.0f, -1.0f, 0, 0, 255, 255 },
        { 1.0f, 1.0f, -1.0f, 255, 0, 255, 255 },
        { -1.0f, -1.0f, 1.0f, 255, 255, 0, 255 },
        { 1.0f, -1.0f, 1.0f, 0, 255, 255, 255 },
        { -1.0f, 1.0f, 1.0f, 255, 0, 0, 255 },
        { 1.0f, 1.0f, 1.0f, 0, 255, 0, 255 }
    },
    {
        0u, 2u, 1u, 2u, 3u, 1u,
        1u, 3u, 5u, 3u, 7u, 5u,
        2u, 6u, 3u, 3u, 6u, 7u,
        4u, 5u, 7u, 4u, 7u, 6u,
        0u, 4u, 2u, 2u, 4u, 6u,
        0u, 1u, 4u, 1u, 5u, 4u,
    }
};

```

I do not change my primitive topology anywhere else than the places I showed.

Please ask me anything about my code if you need to, I am very confused about why my code is doing this.

Thank you.

# Answer
> 2 votes
Note that you are using 16-bit indices in your call:

```
context->IASetIndexBuffer(index_buffer.Get(), DXGI_FORMAT_R16_UINT, 0u);

```

Thus, all your index data on CPU must be 16-bit also (unsigned **short** instead of unsigned *int*).

If you'd rather want to keep the indices on CPU 32 bit, just change it to DXGI\_FORMAT\_R32\_UINT.

# Answer
> 1 votes
I fixed it by changing my indices from UINTs to USHORTs.

I'm not sure why this fixes it but it does.

Such pretty cubes :)

---
Tags: directx11, vertex
---


# Question
Title: Determine when object moving along Bezier Curve and an object along a line collide
I have been using the method here to find the intersection between a line and a curve but, I am not too sure how I would go about solving the time for when two objects moving along their respective tracks would collide. Both objects have a constant speed and radius.

# Answer
Three useful facts we can use here:

* We can use De Casteljau's algorithm to split a Bézier curve into two smaller Bézier curves of the same degree. This tends to gradually straighten the child curves, as they cover less and less of the bends in the original curve.
* A Bézier is that the path is always fully contained in the convex hull of its control points. For the cubic case, that's a quadrilateral, or just two triangles.
* A disc somewhere inside that quadrilateral can only collide with the disc moving on a straight line *only* if the quadrilateral itself overlaps a capsule shape.

The capsule's radius is equal to the sum of the two discs' radii, and its start/end points are the disc's position on the straight line path at the start and end of the time interval it takes to traverse the curve segment that quad contains.

(You could check this by doing two point-in-quad checks and a circle cast if both come up negative - two circle casts if you want both entry and exit times to narrow your search window)

We can use this to quickly narrow down the range of possible collisions.

First, we check this capsule against the quad containing the entire curve. If there's no overlap, we know for sure that we miss.

Then we sub-divide the curve. There are probably principled ways to do this, but they run into edge cases, so for a simple first pass I'd suggest dividing into 3-10 even time segments between the earliest and latest overlap times.

Repeat the overlap test with each segment, using a smaller capsule - accounting for the fact that the disc on the straight line trajectory crosses only a part of its path during each of these time segments.

You can eliminate any segment that does not overlap, then further subdivide those that do. You can binary search for the intersection, pruning any quads that have no overlap, and recursively subdividing those that do. Your recursion bottoms-out when the time interval is small enough or the quad is flat enough to approximate as a straight line segment: then you can switch to a conventional swept disc collision test to get a closed-form solution for the time and location of the collision.
> 2 votes

---
Tags: collision-detection, physics, beziers
---


title: How to set a header on a WebSocketPeer?

text:
# Question
Title: How to set a header on a WebSocketPeer?
How to pass custom header information on a Godot4 WebSocketPeer connection?

# Answer
> 1 votes
Okay, I have found how to do this:

1. Create an instance of `PackedStringArray`
2. Add it to the WS Client using `_set_handshake_headers`

Example:

```
var _connHeader = PackedStringArray(["header-key: header-value"])
_mySocket.set_handshake_headers(_connHeader)

```

---
Tags: websocket, gdscript, godot-4
---


# Question
Title: Utilize type hints over duck-typing for "@export var" for custom resource
I'm going through the "Creating your own resources" steps. Here's an abbreviated version of the demo resource `bot_stats.tres` and the associated `bot_stats.gd` script:

```
extends Resource

@export var health: int

func _init(p_health = 0):
    health = p_health

```

And they suggest using it like this in another Node:

```
extends CharacterBody3D

@export var stats: Resource

func _ready():
    # Uses an implicit, duck-typed interface for any 'health'-compatible resources.
    if stats:
        stats.health = 10
        print(stats.health) # Prints "10"

```

Is it possibly to use a stronger type-hint? I'd love to have (and tried) something like:

```
@export var stats: BotStats

```

or

```
@export var stats: bot_stats

```

To get some intellisense rolling in the editor. But they give things like:

> Error at (3,18): Could not find type "BotStats" in the current scope.

Is this possible?

# Answer
You need to give a class name to your custom `Resource` first. For example:

```
class_name BotStats
extends Resource

@export var health: int

func _init(p_health = 0):
    health = p_health

```

Then you should will be able to use that on the export variable:

```
@export var stats: BotStats

```

See Static typing in GDScript, Registering named classes and the Resources section of GDScript exports.

By the way, even though the term "type hint" stuck, these are actual type definitions, not just hints.

I also want to mention that this is not implemented properly in Godot 3.x at the time of writing (see pull request 44879), there are workaround, but since you are for Godot 4, I'll not get into that. We can consider this a Godot 4 feature.
> 3 votes

---
Tags: gdscript, godot-4
---


# Question
Title: How to get equivalent of "padding" on a button?
I'm using Godot 4. I want to increase the distance between the Button's Text (and possibly icon, later on), and it's outer edges, while keeping the "Colors" options such as "Font Hover Color". The equivalent effect of `padding` on a CSS styled `button`.

**What I've tried:**

I've searched online to find my answer, but that led mostly to different threads about *containers*, not buttons. Only this rejected GitHub issue to add "Padding" for controls seemed relevant; I *think* it was rejected mostly because there are already other ways to achieve the effect of paddings? But I can't seem to distill from that thread how to set this up for buttons.

I've gone through all the "Theme Overrides" options in the Godot editor, but only `H Separation` seemed relevant but that's for space between the icon and text.

I've tried leaving the Button's text empty and creating a child `MarginContainer` with a child `Label` but then (a) the button size is nearly zero, plus I worry the "Colors" from the button's theme options won't work.

**Bottom line:**

How do you set a "padding" (a fixed number of pixels between the edge and contents) of a button in Godot 4?

# Answer
What you use are the define style overrides, which means you have to do it separately for Normal, Hover, Pressed, Disabled, and Focus states.

All the kinds of `StyleBox*` have content margin properties that can do what you want.

The `StyleBoxFlat` also have border width properties. This border comes outside of the contents, but it is part of the sizing of the `Control`. *`StyleBoxFlat` also allows you to specify rounded corners.*

Similarly, `StyleBoxTexture` has texture margin properties, which lets you specify how much of the texture will be treated as border. *There are no properties for rounded corners, but you can do them with transparency in the texture.*

Both `StyleBoxTexture` and `StyleBoxFlat` also have expand margin properties that would make the `Control` larger, but they are not part of its sizing. *`StyleBoxFlat` also allows you to specify shadows which aren't part of the sizing of the `Control` either.*

*By the way, I know it can be somewhat frustrating that there is disparity on the features provided by the different kinds of `StyleBox*`. However, know that a `Button` can have children `Control`s, so you can use a `ColorRect` or `TextureRect` for the background and a `Label` for the text.*
> 3 votes

---
Tags: gui, ui-design, godot-4
---


# Question
Title: Why might performance of a Rust-sdl2 project be better while profiling?
I'm making a simple SDL2-based Rust game, on an OSX laptop. Graphics mostly involves drawing lots of colored squares to the screen. Performance is really slow for what I'm doing, so I decided to profile with Flamegraph. The weird thing is, when I run with flamegraph, performance improves dramatically, going from ~20-50ms/frame to more like 5-10ms/frame. What could possibly be causing this (and how can I take advantage of it)?

Here's the command I use to run the program normally: `sudo CARGO_PROFILE_RELEASE_DEBUG=true cargo run`

Here's the command I use to run the program with flamegraph: `sudo CARGO_PROFILE_RELEASE_DEBUG=true cargo flamegraph`

(Flamegraph requires some permissions to run, so I run them both with sudo for maximum comparability.)

# Answer
> 1 votes
Per the Flamegraph README, it runs using the release profile by default:

```
# defaults to profiling cargo run --release
cargo flamegraph

```

So you must also run using the release profile, by running `cargo run --release`, to see the same performance.

---
Tags: performance, sdl2, profiling, rust, metal
---


# Question
Title: Implementing a Maya-like orbit camera in Vulkan/OpenGL
I want to create an orbit camera with zooming, panning, and rotation. I used the following examples to create cameras:

I've faced problems with the pivot position when I tried to create rotation around the center of a screen.

My implementation:

```
void Camera::lookAt(const glm::vec3 &eye, const glm::vec3 &center, const glm::vec3 &up)
{
    mTranslation = glm::translate(glm::mat4(1.0f), eye) * mTranslation;
    transform.position = eye;
    mViewInverse =  mRotation * mPivot * mTranslation;
    mView = glm::inverse(mViewInverse); // More academic than actually necessary.
}
void Camera::updateViewMatrix()
{
    mPivot = glm::translate(glm::mat4(1.0f), mCenter);
    mViewInverse = glm::inverse(mPivot) * mRotation * mPivot *  mTranslation;
    mView = glm::inverse(mViewInverse); // More academic than actually necessary.
}
glm::vec3 Camera::right() const { return glm::normalize(glm::vec3{mViewInverse * glm::vec4{1, 0, 0, 0}}); }
glm::vec3 Camera::up() const { return glm::normalize(glm::vec3{mViewInverse * glm::vec4{0, 1, 0, 0}}); }
void Camera::rotate(float angleX, float angleY)
{
    transform.rotation -= glm::vec3{up().y > 0.0f ? angleX : -angleX, angleY, 0.0f};
    mRotation = glm::mat4{1.0f};
    mRotation = glm::rotate(mRotation, transform.rotation.x, glm::vec3{0.0f, 1.0f, 0.0f});
    mRotation = glm::rotate(mRotation, transform.rotation.y, glm::vec3{1.0f, 0.0f, 0.0f});
    updateViewMatrix();
}
void Camera::pan(float x, float y)
{
    const float zoomAmount = -std::abs(mTranslation[3][2]);
    glm::vec3 panX = right() * (x * zoomAmount);
    glm::vec3 panY = up() * (y * zoomAmount);
    glm::vec3 motion = panX + panY;
    transform.position += motion;
    mCenter -= motion;
    mTranslation = glm::translate(glm::mat4(1.0f), transform.position);
    updateViewMatrix();
}
void Camera::zoom(const float zoomAmount)
{
    transform.position.z -= zoomAmount;
    mTranslation = glm::translate(glm::mat4(1.0f), transform.position);
    updateViewMatrix();
}

```

I now understand why I get the wrong results. The camera is initially pointed along the Z axis. Then I rotate the camera to the X axis and pan the camera (on the X axis, the Z value translates). And the pivot point also translates. Then I rotate the camera to the Z axis again, and I get incorrect rotations because the pivot center has been changed.

If I use vec3 in the pivot point `[mCenter.x, mCenter.y, 0.0f]` I get correct rotations, but then when I try to pan, the translation is done in local orientation instead of world space (for example, if the camera is in front of the X axis, panning to X means panning to Z in world space). In this case, however, panning is also on the X axis.

Video: https://www.youtube.com/watch?v=WBvLKR64VqM

If I use vec3 in the pivot point `[mCenter.x, mCenter.y, mCenter.z]` I get correct panning on any axis, but rotations are bad because the pivot point was changed. I think for better results I have to use different pivot points (for translation and rotation). But I don't understand how to separate the pivot point for panning and for rotation.

Video: https://www.youtube.com/watch?v=Tky8c-HGl7Y Or are there other options for completing this task?

By the way, I have searched for other questions. I discovered another implementation on the GitHub. But, unfortunately, this project also has the same issue. I also tested the behavior in the Maya alternative (just Maya is more well-known). The pivot center also displaces in these apps, but it also translates when the user zooms. But I get the wrong behavior. I don't seem to understand the pivot-center logic using zooming.

# Answer
Today, I found the solution. The answer was straightforward: just multiply X and Z by the camera vectors. Hence, the right vector at the starting location is 1, 0, 0, as well as 0, 0, -1 for the dir vector. The values are then reversed while turning (when the camera is focused on the X axis). But there was a question about the appropriateness of this function. In almost all existing editors, this point is not worked out. It's just that when we rotate the camera and reset the center of rotation to the center of the screen, the rotation will already occur around the new center of rotation. and it may be inconvenient for the user. Well, for example, the user turned a cube by 5 degrees. Then by 10, and each time, the cube will "run away" because the center of rotation has changed. The only program where this is handled is Maxon Cinema 4D. So in this app, it's done kind of conveniently. There is a center of rotation (we will call it the permanent center). It can be changed. And there is also a cursor binding. I.e., if the object hits the object or point with the cursor, a temporary center of rotation is formed. All turns are made around it. The Z data is recorded at a permanent center. Now, if the user clicks the cursor on a non-object (just a viewport), the X and Y data in the permanent center of the screen are overwritten with data relative to the center of the screen, and the Z coordinate is already there. As a result, it turns out that while the user is working with the cube object, the cube will not run away. And it looks correct. I think I should consider this option.
> 1 votes

---
Tags: opengl, camera, matrix, glm, vulkan
---


# Question
Title: Assigning references to Prefabs placed in each Scene
I am currently working on a small 2D game which has a few different scenes, which are each a different level. I want to use my object prefabs from one scene in the others, but these do not include references to objects when I add the prefabs to my new scene.

Is it best to just manually add the references in the new scene to each object for every level, which is quite a long process, or is it better to change my script to use `Find()`?

What's a good practice when creating lots of levels with slight changes each time?

# Answer
> 0 votes
Similar to an answer here, an intermediate option you can use is to put the "Find" logic in `OnValidate`, so it runs once at edit time to save you the manual step of populating the references, without any runtime overhead in-build.

Something like this:

```
public class GameManager : MonoBehaviour {

    // Save these references at edit time and allow editing in the inspector.
    [SerializeField] PlayerController _player;
    [SerializeField] Spawner _allySpawner;
    [SerializeField] Spawner _enemySpawner;

    // Run in-Editor only: when the prefab is placed in the scene,
    // on scene load, on enter/exit play mode, when any changes
    // are made to this component instance in the Inspector,
    // or when reloading the script assembly after a code change.
    void OnValidate() {
        this.TryGetSceneReference(ref _player);
        this.TryGetSceneReference("Ally Spawner", ref _allySpawner);
        this.TryGetSceneReference("Enemy Spawner", ref _enemySpawner);
    }
}

```

Here I assume you probably want to wire up several of these dependencies, so I packaged the boilerplate into an extension method you can put in a separate file - so each call is just a one-liner:

```
public static class SceneDependencyHelper
{
    public static bool TryGetSceneReference<T>(this MonoBehaviour script, ref T reference) where T:Component {
        if (reference != null) return true;

        reference = Object.FindObjectOfType<T>();

        if (reference != null) return true;

        Debug.LogWarning($"{script.name} ({script.GetType().Name}) needs a reference to a {typeof(T).Name}, but none was found in the scene.");
        return false;
    }

    public static bool TryGetSceneReference<T>(this MonoBehaviour script, string name, ref T reference) where T : Component
    {
        if (reference != null) return true;

        var namedObject = GameObject.Find(name);
        if (namedObject != null) {
            if (namedObject.TryGetComponent(out reference)) return true;
        }

        Debug.LogWarning($"{script.name} ({script.GetType().Name}) needs a reference to a {typeof(T).Name} named {name}, but none was found in the scene.");
        return false;
    }
}

```

This handles doing no work if the reference has already been found, and logging useful warnings if the reference was not found.

---
Tags: unity, scene, prefabs
---


title: ObjFile not properly loading

text:
# Question
Title: ObjFile not properly loading
i am losing my mind. I am trying to create an obj parser has a way to learn opengl but i have ran into a brick wall. with DMGregory help i got the textures to work i think but know the mesh just looks like a blob

--Result--

--Obj parser code--

```
using OpenTK.Mathematics;
using System.Runtime.InteropServices;

using Core.Common.Objects;

namespace Core.Common
{
    public class LoadModel
    {
        public (vertex[] vertices, int[] indices) LoadObj(string path)
        {
            List<Vector3> Positions = new List<Vector3>();
            List<Vector2> texCoords = new List<Vector2>();

            List<int> position_Indices = new List<int>();
            List<int> texture_Indices = new List<int>();

            int[] indicesArray = null;
            vertex[] vertices = null;

            Console.ForegroundColor = ConsoleColor.DarkBlue;
            Console.WriteLine("loading " + path + " ... ");
            Console.ResetColor();

            string[] lines = File.ReadAllLines(path);

            foreach (string line in lines)
            {
                string[] parts = line.Split(' ');

                switch (parts[0])
                {
                    case "v":
                        Vector3 pos = new Vector3(Convert.ToSingle(parts[1]), Convert.ToSingle(parts[2]), Convert.ToSingle(parts[3]));
                        Positions.Add(pos);
                        break;

                    case "vt":
                        Vector2 texture = new Vector2(float.Parse(parts[1]), float.Parse(parts[2]));
                        texCoords.Add(texture);
                        break;

                    case "f":
                        string[] vertex1 = parts[1].Split('/');
                        string[] vertex2 = parts[2].Split('/');
                        string[] vertex3 = parts[3].Split('/');

                        int index1 = int.Parse(vertex1[0]) - 1;
                        int index2 = int.Parse(vertex2[0]) - 1;
                        int index3 = int.Parse(vertex3[0]) - 1;

                        int texIndex1 = Int32.Parse(vertex1[1]) - 1;
                        int texIndex2 = Int32.Parse(vertex2[1]) - 1;
                        int texIndex3 = Int32.Parse(vertex3[1]) - 1;

                        position_Indices.Add(index1);
                        position_Indices.Add(index2);
                        position_Indices.Add(index3);

                        texture_Indices.Add(texIndex1);
                        texture_Indices.Add(texIndex2);
                        texture_Indices.Add(texIndex3);

                        break;
                }
            }

            // bellow is modified\\

            indicesArray = new int[position_Indices.Count];
            vertices = new vertex[position_Indices.Count];

            for (int i = 0; i < vertices.Length; i++)
            {
                vertices[i].pos = Positions[position_Indices[i]];
                vertices[i].tex = texCoords[texture_Indices[i]];
            }

            for (int i = 0; i < position_Indices.Count; i++)
            {
                indicesArray[i] = i;
            }

            foreach (var item in vertices)
            {
                Console.WriteLine(item.pos);
            }

            return (vertices, indicesArray); //return modeldata and faces
        }

    }
}

```

--Rendering code--

```
using OpenTK.Graphics.OpenGL4;
using OpenTK.Mathematics;
using System.Runtime.InteropServices;

using Core.Common.Objects;
using Core.Render;

namespace Core.Common
{
    public class Loader
    {
        private List<int> vbos = new List<int>();
        private List<int> vaos = new List<int>();

        public RawModel loadModel(vertex[] verts, int[] indices, string texPath)
        {
            int vao = createVAO();
            vbos.Add(vao);
            bindIndicesBuffer(indices);
            storeDataInPosAttribList(0, 3, verts, vertex.Stride);
            storeDataInTexAttribList(1, 2, verts, vertex.Stride);
            loadTexture(texPath);
            unbindVAO();
            return new RawModel(vao, indices.Length);
        }

        private int createVAO()
        {
            int vao = GL.GenVertexArray();
            GL.BindVertexArray(vao);
            return vao;
        }

        private void loadTexture(string path)
        {
            Texture texture;
            texture = Texture.LoadFromFile(path);
            texture.Use(TextureUnit.Texture0);
        }

        private void storeDataInPosAttribList(int attribNum, int size, vertex[]  verts, int stride)
        {
            int vbo = GL.GenBuffer();
            vbos.Add(vbo);
            GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
            // bellow is modified\\
            GL.BufferData(BufferTarget.ArrayBuffer, stride * Vector3.SizeInBytes, ref verts[0].pos, BufferUsageHint.StaticDraw);
            GL.VertexAttribPointer(attribNum, size, VertexAttribPointerType.Float, false, 0, 0);
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
        }

        private void storeDataInTexAttribList(int attribNum, int size, vertex[] tex, int stride)
        {
            int vbo = GL.GenBuffer();
            vbos.Add(vbo);
            GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
            // bellow is modified\\
            GL.BufferData(BufferTarget.ArrayBuffer, stride * Vector2.SizeInBytes, ref tex[0].tex, BufferUsageHint.StaticDraw);
            GL.VertexAttribPointer(attribNum, size, VertexAttribPointerType.Float, false, 0, 0);
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
        }

        private void unbindVAO()
        {
            GL.BindVertexArray(0);
        }

        private void bindIndicesBuffer(int[] indices)
        {
            int vbo = GL.GenBuffer();
            vbos.Add(vbo);
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, vbo);
            GL.BufferData(BufferTarget.ElementArrayBuffer, indices.Length * sizeof(int), indices, BufferUsageHint.StaticDraw);
        }

        public void cleanUP()
        {
            foreach (var item in vaos)
            {
                GL.DeleteVertexArray(item);
            }

            foreach (var item in vbos)
            {
                GL.DeleteBuffer(item);
            }

        }

    }
}

```

# Answer
> 0 votes
Special thanks to DMGregory for dealing with my doubts.

I solved my problem by creating a new list of `Vector`s:

```
List<Vector3> out_verts = new List<Vector3>();
List<Vector2> out_uv = new List<Vector2>();

```

Then, I iterate through a list of indices:

```
for (int i = 0; i < position_Indices.Count; i++)
{
    out_verts.Add(Positions[position_Indices[i]]);
    out_uv.Add(texCoords[texture_Indices[i]]);
}

```

I create the indices array with the whole number of the index list:

```
indicesArray = new int[position_Indices.Count];

for (int i = 0; i < position_Indices.Count; i++)
{
    indicesArray[i] = i;
}

```

Finally, the renderer multiplies the lists by the size of the specified vector:

```
GL.BufferData(BufferTarget.ArrayBuffer, Vector3.SizeInBytes * verts.Count, verts.ToArray(), BufferUsageHint.StaticDraw);
GL.BufferData(BufferTarget.ArrayBuffer, Vector2.SizeInBytes * tex.Count, tex.ToArray(), BufferUsageHint.StaticDraw);

```

Final result:

(I'm not very good at explaining things, so I hope all this makes sense.)

---
Tags: opengl, textures, obj
---


# Question
Title: How to make raycast go through platform effector?
I'm making a 2D game and I'm using a raycast.

I want the raycast to ignore the platform when hitting it from beneath, but not when hitting it from above.

Right now the raycast always hits no matter what side of the platform it touches.

Is there any way to configure the raycast or the platform effector so that they work as I explained?

# Answer
This example assumes you are using Unity, other game engines might work differently although the concept still applies.

You could to use RaycastAll and check the position of the platform.

> This function is similar to the Raycast function but instead of detecting just the first Collider that is hit, an array of all Colliders along the path of the ray is returned.

Create a Tag named something like "Platform" and add it to the platform game object.

Then in code use the above mentioned raycast to check all game objects in the desired direction and check if any are tagged as *Platform*.

If it's tagged *Platform* then check its position relative to the origin of the raycast.

Now that you know if its below or above you can act accordingly.

```
//script on a "player" game object
var hits = Physics2D.RaycastAll(transform.position, Vector2.up, 10);
foreach (var hit in hits)
{
    if (hit.transform.CompareTag("Platform"))
    {
        if (transform.position.y > hit.transform.position.y)
        {
            Debug.Log(hit.transform.gameObject);
        }
    }
    else
    {
        //if its not a platform do something else
        Debug.Log(hit.transform.gameObject);
    }
}

```

The player is represented by the triangle and the raycast is pointing up.

Now the player is above the platform and the raycast is pointing down.
> 2 votes

---
Tags: 2d, raycasting, platformer
---


title: Computations in GPU Unity

text:
# Question
Title: Computations in GPU Unity
I've made a fluid simulation using particles in Unity, but now it is painfully slow because all computations are done using the CPU. In order to make it faster, I need to do computations on the GPU, and I learned that I would have to use compute shaders for that.

The problem is, to make a fluid simulation, I need to make and track each particle and perform collisions on each of them on a certain time interval, and I don't understand how this could be achieved using shaders when the concept of shaders (from what I currently understand) is performing calculations on one already made mesh. Also, I'm using prebuilt physics calculations (rigidbody) in Unity, and would using shaders mean that I would not be able to use these?

How can I make this effect more efficient?

# Answer
> 1 votes
Create a compute shader in Unity and write your particle update logic (e.g., position, velocity, collision detection, and response) in the shader code.

Store your particle data in StructuredBuffers or other appropriate buffer types. You will need to create a buffer for the particle positions, velocities, and any other properties you need to track in the simulation.

In your C# script, create and configure the necessary buffers to hold particle data and pass them to the compute shader using the SetBuffer method.

Dispatch the compute shader by invoking the Dispatch method in your C# script. You'll need to specify the number of threads to run in parallel, which should be configured to best match your GPU's capabilities.

After the compute shader finishes executing, retrieve the updated particle data from the buffers in your C# script.

Use the updated particle data to update the positions of your particles in the scene. You can either use the Graphics.DrawMeshInstanced method to render the particles as meshes or update the positions of ParticleSystem particles.

---
Tags: unity, shaders, gpu
---


# Question
Title: Vertical components not working with NavMeshAgent .move or .velocity?
This is a weird one. I'm using a 2d adaptation of the NavMesh (found here: https://github.com/h8man/NavMeshPlus) to get obstacle avoidance for my AI in my 2d game.

I also want to use it for my player controller, so that I can get collisions with walls for 'free' without having to use a box or circle collider and deal with any clipping issues. So currently my player component has a Rigidbody2d set to Kinematic, a circle collider (to register collisions with bullets etc.), and a Nav Mesh Agent component. In the Start method of my script, I was told to add these lines:

```
agent.updateRotation = false;
agent.updateUpAxis = false;

```

I used to use this method of moving the player in the `FixedUpdate` loop (which also has vertical-movement jittery issues when paired with the Nav Mesh Agent):

`transform.Translate(new Vector3(moveVal.x, moveVal.y, 0) * moveSpeed * Time.fixedDeltaTime, Space.World);`

However I read that I'd want to set the agent's velocity to make it better suited to being avoided by enemy AI, if required. So I tried...

`agent.velocity = new Vector3(moveVal.x, moveVal.y, 0) * moveSpeed;`

Ok, this works... but it only works in the x direction. If I hit W or S on keyboard to move vertically, it does nothing. *However*, if I hold both vertical AND horizontal move keys down, it works! ...bizarre.

I did try this with joystick movement and it also worked fine, which is also bizarre. I logged out `moveVal.x` and `moveVal.y` for both control methods; the keyboard values were always either 1, 0, or -1, whereas the gamepad/joystick values were floats anywhere between -1 and 1. (I'm using new input system with an action type of Value and control type Vector2)

And yes, I did try commenting out the `agent.updateUpAxis = false` line since it did look suspicious to me too, but that didn't change anything unfortunately.

# Answer
The issue you're experiencing might be related to the way you're updating the agent's velocity. When using keyboard input, the agent's velocity might not be updated correctly due to the combined input values being too large or too small. Here's a suggestion to improve the player movement:

Normalize your input vector to ensure the player's speed is consistent in all directions:

```
Vector2 moveValNormalized = moveVal.normalized;

```

Update the agent's velocity using the normalized input values:

```
agent.velocity = new Vector3(moveValNormalized.x, moveValNormalized.y, 0) * moveSpeed;

```

In your FixedUpdate loop, make sure you're calling agent.nextPosition to update the agent's position:

```
private void FixedUpdate()
{
    agent.nextPosition = transform.position;
}

```

With these changes, your player should move smoothly in all directions using both keyboard and joystick inputs. If you still experience issues with the vertical movement, you may want to debug the input values to ensure they're being read correctly. Additionally, make sure there are no other scripts or components interfering with the player's movement.
> 0 votes

---
Tags: unity, navmesh
---


# Question
Title: Are there feature/performance/platform limitations when using the Mono/C# version of Godot?
I've read through the Godot page about differences between the C#/mono version and the standard version (gdscript), and it primarily seems to be focused on the fact that C# is a different language with different conventions, and that support is a new feature that may have issues. It doesn't really seem to discuss any different capabilities or features gained or lost by using one version vs. the other.

The drawbacks of using the Mono/C# version seem to be:

* There are likely some bugs because it is a new feature
* If you don't already know C#, you need to learn (as with any language)

Are there different features, performance implications, or platform support limitations when using C#?

# Answer
> 1 votes
> There are likely some bugs because it is a new feature

C# - the language - is well supported. Also, a lot of effort have gone into supporting ahead of time compiling, which allows greater platform support than it would have otherwise. However:

* Some .NET libraries may cause trouble (mainly related to threading and reflection).
* It is not well integrated into the editor. At least not at the time of writing. So I'd advice to use an external editor such as Visual Studio Code with C# Tools for Godot.

---

> If you don't already know C#, you need to learn

The same can be said of GDScript. In fact, given that other engines also use C# - but not GDScript - you probably have an easier time transfering knowledge using C# (and even entire classes, if they don't have engine specific code). But don't let that discorage you form learning GDScript.

---

> For someone who is comfortable working with both gdscript and c#, what are the reasons for choosing one version of godot over the other?

Some C# cons:

* Using C# your build will be somewhat heavier.
* We can be sure that everybody using Godot can use GDScript. Thus GDScript is the language of choice for addons. *Going to C++ if we want to squish more performance, or if we need to talk to native code.*
* Metaprogramming is easier with GDScript: you crate a GDScript object with some code, then load it, instance it and run it. With C# you would need reflection for something like that, but it may not work, in particular with platforms that need ahead of time compiling.

Some C# pros:

* You will have access to a larger set of libraries (with some caveats, as I said earlier, some cause trouble).
* GDScript - prior to Godot 4 - is an interpreted language. And also C# is fully typed. As a result, C# often performs better than GDScript.
* C# has some language features that make it easier to use compared to GDScript (e.g. iterators, lambda functions).

---

For everyday use, either is OK - so you can go with personal preference. However, when you get into very specific uses (e.g. metaprogramming, addons) or when you need some extra performance, that may tip the balance one way or the other. You may - of coruse - not know if you will run into those situations ahead of time.

On that note, I want to mention that you can combine both in the same game. *So **don't decide between them too early**.* In fact, using GDScript to deal with signals and have it call into C# code for game logic, might be a good idea. Since GDScript is a great glue language, and C# can archive better performance.

However, sometimes the interaction between these languages is not that smooth. For instance, `async` methods in C# - often - returns a `Task` and GDScript can't handle that with `yield`. For those situation, you want to refactor the code to use signals instead of `async` methods.

*And - by the way - you can combine any other language you have in Godot, including visual scripting, and third party languages that you can install into Godot such as Lua and Python and so on. And yes, C++.*

# Answer
> 0 votes
There is like a Godot world and .NET/Mono world (.NET for Godot 4 and Mono for Godot 3). Godot world runs your scenes and nodes, .NET/Mono runs your scripts when using C#. GDScript scripts are apparently better at communicating with this Godot world, than C# scripts (C# carries additional cost or so I heard). On the other hand the scripts themselves in C# might be faster (especially if you want to run some complex simulation/computation). C# also gives access to many convenient libraries.

However C# can introduce some confusion and not so obvious bugs. When you write your scripts in GDScript, you are limited to doing things the Godot way. When you write in C# you can still do things the Godot way, but .NET/Mono way of doing things become available (which you might want to do if you are familiar with the language/framework). Not everything translates 1:1 between those 2 worlds (though a lot of effort went into Godot 4.0 to make the experience more seamless). In C# you might face 2 different ways to declare and emit signals, run async code, read files etc. Sometimes both are fine, sometimes one is wrong and it's not obvious when. In many cases, sticking to the Godot way of doing things might be a better option in the long run, as there is some serious optimization related to managing nodes and scenes on the Godot end and using the .NET/Mono way may cause bugs with the engine. On the other hand if you want to tap some of extra power that comes with .NET/Mono you would have to abandon Godot way of doing something. When coding in C#, you might think "how do I solve this in .NET" and miss that Godot has a built-in function for that already. Some built-in parts of .NET ecosystem refuse to work in a Godot project (I was unable to use ASP for networking, but thankfully Godot has it's own functions for that).

Adding to the mix of pros and cons, in C# it's easier to extend Godot's built-in functions using Extensions and the the like (for when GDScript is missing something). Although some of the things I miss in GDScript work in C# out of the box for Godot (like you can do much more with collections and easier at that). GDScript in Godot 4.0 went a long way from the previous versions, so I expect less things to complain about in future versions of Godot.

With Godot 4.0, Visual Studio integration works really well and preparing the environment for debugging is much easier. C# project structure and solution were also greatly improved (Framework styled project were replaced with the modern SDK style projects and Godot no longer appears to overwrite them which would lead to losing changes made in an external IDE).

Last, but not least, I think it's possible to do a bit of both (C# and GDScript) in your project.

---
Tags: c#, godot
---


# Question
Title: Define 2D polygon area and check if point is inside at runtime
I'm trying to write a GDScript (using Godot *4*) function that creates a new component at a specific `Vector2` position. This works quite well with the following code:

```
func _create_thing(at_position):
    var component = load("res://thing.tscn").instantiate() as Node2D
    component.position = at_position
    %PlayfieldNode2D.add_child(component)

```

Now I'm trying to restrict where players can create something. I want to define a polygon shape in the editor to determine the area where this is allowed. My thought was to create an `Area2D` node with a `CollisionPolygon2D` shape and then do something like this:

```
    if %AllowedArea2D.contains_point(at_position):
         # creation logic here

```

This is pseudo-code, because I found no `contains_point(...)` or similar method in the Area2D docs. I looked through the docs of other related Node types such as the `CollisionPolygon2D`, `Polygon2D` and several others, but found no solution yet.

Bottom line: how can I define a polygon shape in Godot 4 and later check if a specific `Vector2` is inside that polygon?

# Answer
> 3 votes
Minutes after posting I find the answer myself, was tempted to delete my question because it was so simple, but it might help someone else too...

Although I found no method on one of the object's classes themselves, it *is* on a `Geometry2D` helper class, specifically the `is_point_in_polygon(point, polygon)` method does what you need here. For example:

```
    if Geometry2D.is_point_in_polygon(at_position, %CollisionPolygon2D.polygon):
         # creation logic here

```

# Answer
> 2 votes
I know you found an alternative approach. However, originally you wanted something that worked with `Area2D`. Well, here is that:

```
var query := PhysicsPointQueryParameters2D.new()
query.collide_with_areas = true
query.collide_with_bodies = false
query.position = at_position
var result := get_world_2d().direct_space_state.intersect_point(query)
var in_the_area := false
for entry in result:
    if entry.collider == area_2d:
        in_the_area = true
        break

prints(in_the_area)

```

---
Tags: gdscript, godot-4
---


# Question
Title: Vertex sorting to match triangle list definition of an hexagon
I’m working on a project to display molecules with DirectX that I’m updating regularly to add visual effects. The one I’m working on is simple: display a flat transparent hexagon that match a substructure made of 6 atoms positions, as shown here:

In most cases the connectivity of atom leading to this hexagonal structure is well known (like the one named Tyr56 in the picture) e.g.

```
  C2-C4
 /     \
C1     C6
 \     /
  C3-C5

```

So I have built my triangle list according to this e.g. C1-C2-C3; C3-C2-C4; C3-C4-C5; C5-C4-C6. Note that culling is off to see the hex in transparent mode from either side.

Now my problem is that often there is an unconventional structure (the one in the center of the picture) inserted in conventional ones whose connectivity is defined but that not always comply with the standard one.

I have a protocol to display the hexagon based on the standard triangle list and I want to sort the vertex list of the non-standard structure to match my triangle list sequence.

This is where I need help to find a sorting method for the 6 vertices to match my triangle list, regardless of the order of the atom connectivity description. Currently I'm doing several tries to find the correct atom order, which works but is annoying.

# Answer
I have adapted the solution from the link provided in the comment. Finally I have changed my mind. Instead of using a trilist matching the standard structure and trying to adapt my vertex order to this trilist, I use this method sorting vertex clockwise and then I generated a trilist in a more general way based on this clockwise ordering.

Below a result that works for me although I did not check with culling as I don't want to cull.

Using DX11 and XMVECTOR type with no SSE intrinsic.

```
PDPATOM is a struct describing an atom with position XYZ Pos and a FLOAT Angle
LPPDBATOM is a pointer to a PDPATOM struct
LPPDBATOM* is a list of LPPDBATOM
ACount is a DWORD for the number of LPPDBATOM in the pointer list

//sorting function based on Angle value
int __cdecl SortAtomDistance(const VOID* arg1, const VOID* arg2)
{
   LPPDBATOM a1 = *(LPPDBATOM*)arg1;
   LPPDBATOM a2 = *(LPPDBATOM*)arg2;

   if (a1-> Angle > a2-> Angle) return +1;
   if (a1-> Angle < a2-> Angle) return -1;
   return 0;
}

//function that create a temporary copy of the original list to work with
//use qsort to order the atom based on the Angle value
//at the end copy the temporary list to the original one
void SortAtomPoly(LPPDBATOM* ppAList, DWORD ACount)
{
   LPPDBATOM* ppAListTmp = new LPPDBATOM[ACount];
   memcpy(ppAListTmp, ppAList, sizeof(LPPDBATOM)*ACount);
   qsort(ppAListTmp, ACount, sizeof(LPPDBATOM), SortAtomDistance);
   memcpy(ppAList, ppAListTmp, sizeof(LPPDBATOM)*ACount);
   delete[] ppAListTmp;
}

//main function that generate a planar geometry for my needs.
//note that the geometry is expected to be flat convex and to be a tri,
//quad, pent or hex or more but here limited to a hex.
//parameters function are ppAList : the original list of atom, ACount
//the number, Faces the number of poly to be generated (e.g. Face = 1
//means tri, 2=quad, etc…

 void CGeometryDX::SetPolygon(LPPDBATOM* ppAList, DWORD ACount, DWORD Faces)
 {
    //calculate the center from the positions
    XMVECTOR Centroid = XMVectorSet(0, 0, 0, 0);
    for (DWORD a = 0; a < ACount; a++)
    {
       LPPDBATOM pA = ppAList[a];
       Centroid += pA->Pos;
    }
    Centroid /= ACount;
    //Get a plane equation from the three first positions. We expect a planar geometry
    XMVECTOR Plane = XMPlaneFromPoints(ppAList[0]->Pos, ppAList[1]->Pos, ppAList[2]->Pos);
    // Inverse the Plane,
    XMVECTOR QuadXY = XMQuaternionInverse(Plane);
    //for each position calculate the delta to centroid and multiply by
    //inverse plane. Use the result XY to get the Angle representing the
    //orientation (clockwise) of the position from the centroid (radian)
    for (DWORD a = 0; a < ACount; a++)
    {
       LPPDBATOM pA = ppAList[a];
       XMVECTOR XY = QuadXY*(pA->Pos-Centroid);
       pA->Angle = atan2f(XY.y, XY.x);
    }
    //then sort
    SortAtomPoly(ppAList, ACount);
    Vertex V[6];//we want vertex list for hexagon shape : max 6 vertices
    for (DWORD a = 0; a < ACount; a++)
    {
       LPPDBATOM pA = ppAList[a];
       XMStoreFloat3(&V[a].Pos, pA->Pos);
       V[a].Color = XMVectorSet(1.0, 1.0, 1.0, 0.5);//transparent white
       V[a].Tex = XMFLOAT2(0, 0);//no texture applied
       V[a].Normal = XMFLOAT3(0, 1, 0);//default normal
    }
    //for this application we will have only convex geometry so
    //generate a list of tris in a trianglefan mode
    //(old DX7/8 trilist type)
    //with point zero as starting vertex for all tris.
    //alternative generation of indices is possible
    WORD IBs[12];//we want tri list for hexagon shape : max 4*3 indices
    //loop based on Faces param, 1 = tri, 2 = quad, etc...
    //should work for more than hexagon
    DWORD i = 0;//incremented each loop step to turn around point zero
                //with increasing vertex index. E.g. 0,1,2 -> 0,2,3…etc
    for (DWORD f = 0; f < Faces; f++)
    {
       IBs[f * 3 + 0] = 0;
       IBs[f * 3 + 1] = i + 1;
       IBs[f * 3 + 2] = i + 2;
       i ++;
    }
    CreatMesh(V, Faces+2, IBs, Faces*3, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  }

```
> 0 votes

---
Tags: directx11, vertex, sorting
---


title: Enemy is losing 2 health instead of 1

text:
# Question
Title: Enemy is losing 2 health instead of 1
I am trying to componentize all of my scripts and I would like the enemy to lose 1 health (enemy max health is 3) every time the player collides with the enemy. Right now the enemy is losing 2 health instead of 1. This is my hierarchy for the enemy:

There is Health and Take Damage On Collision scripts under the Enemy gameObject and a Health Bar script under the Health Bar gameObject.

Enemy gameObject:

Health Bar gameObject:

Perhaps there's code running one in two separate places? I know OnCollisionEnter2D runs every frame but that's why I created a damageInterval. Here are my scripts:

```
public class Health : MonoBehaviour {

    public int maxHealth;
    public int currentHealth;

    void Start() {
        currentHealth = maxHealth;
    }
}

```

```
public class HealthBar : MonoBehaviour {

    [SerializeField] private GameObject character;
    public Slider slider;
    public Gradient gradient;
    public Image fill;

    private void Start() {
        Health health = character.GetComponent<Health>();
        HealthBar healthBar = gameObject.GetComponent<HealthBar>();
        healthBar.SetMaxHealth(health.maxHealth);
    }

    public void SetMaxHealth(int health) {
        slider.maxValue = health;
        slider.value = health;

        /*on the gradient that has (left to right) red, yellow and green fixed portions,
        all the way to the left 0f (red), and all the way to the right 1f (green)
        we assign the entire fill of the HealthBar to this color
        */
        fill.color = gradient.Evaluate(1f);
    }

    public void SetHealth(int health) {
        slider.value = health;

        /*we assign the entire fill of the HealthBar to the normalized value (0 to 1) so
        //the 0 to 10 points of health syncs with 0 to 1 on the gradient. this determines
        what color the fill will be depending on how much health is left
        */
        fill.color = gradient.Evaluate(slider.normalizedValue);
    }
}

```

```
public class TakeDamage : MonoBehaviour {

    private float damageInterval = 2f;
    private float currentDamageInterval;

    private void Update() {
        if(currentDamageInterval >= 0)
            currentDamageInterval -= Time.deltaTime;
    }

    public bool CanTakeDamage() {
        return (currentDamageInterval < 0);
    }

    public void EnemyTakeDamage(int damageAmount) {
        Health health = gameObject.GetComponent<Health>();

        if(gameObject.CompareTag("Hazard") && CanTakeDamage()) {
            health.currentHealth -= damageAmount;
            currentDamageInterval = damageInterval;
            if (health.currentHealth <= 0)
                Destroy(gameObject);
        }
    }
}

```

```
public class TakeDamageOnCollision : MonoBehaviour {

    [SerializeField] private int damageAmount;
    [SerializeField] private GameObject healthBarGO;
    HealthBar healthBar;
    TakeDamage takeDamage;

    private void Start() {
        takeDamage = gameObject.AddComponent<TakeDamage>();
        healthBar = healthBarGO.GetComponent<HealthBar>();
    }
    //if the player collides with enemy weak spot and can damage enemy
    private void OnCollisionEnter2D(Collision2D collision) {
        if (gameObject.CompareTag("Hazard") && collision.gameObject.CompareTag("Player")) {
            takeDamage.EnemyTakeDamage(damageAmount);
            healthBar.SetHealth(damageAmount);
        }
    }
}

```

If you have any tips on componentizing my scripts, I'm all ears.

# Answer
> 29 votes
I think you have twice as many components as you need here. While I'm generally in favour of small single-purpose classes, "have a health value" is so tightly linked to "modify health value" that they're really together a single purpose.

By splitting the jobs of having, displaying, and modifying health between separate files, you make the reader do a lot more jumping around in their editor, and juggle more moving parts in mind. That added complexity makes it easy to miss obvious mistakes like this:

```
healthBar.SetHealth(damageAmount)

```

You're setting the displayed health value to the amount of damage you took, not the amount of health remaining after subtracting that damage.

I'd split out the classes like this:

* `ResourceBar`: responsible for displaying a bar measuring some quantity. Could be health, but you can also re-use the same component to handle stamina/mana/time/food/etc.
* `Health`: responsible for having and modifying a health number, handling taking damage, immunity interval, issuing `OnDie` events when health reaches zero, etc. Has a reference to a `ResourceBar` that can be updated when the health changes.
* `CollisionDamage`: handles responding to collision event by issuing damage to `Health.TakeDamage()`. Doesn't need to know anything about `ResourceBar` since updating the display is not its responsibility.

Also, does not need to check its own tag in the collision handler (`gameObject.CompareTag("Hazard")`). If you didn't want this object to run this collision handler, you would simply not attach this component to it.

---

Here's an example:

```
public class Health : MonoBehaviour {
    [field:SerializeField]
    public int MaxHealth {get; private set;}

    [field:SerializeField]
    public int CurrentHealth {get; private set;}

    [SerializeField]
    float _invulnerabilityDuration;
    float _invulnerabilityRemaining;

    [SerializeField]
    ResourceBar _bar;

    public UnityEvent OnDie;

    public bool IsAlive => CurrentHealth > 0;
    public bool CanTakeDamage => IsAlive && (_invulnerabilityRemaining <= 0f);

    public void TakeDamage(int damage, bool bypassInvulnerability = false) {
        Assert.IsTrue(damage >=0,
            "Cannot apply negative damage - call Heal instead");

        if (!(bypassInvunerability || CanTakeDamage)) return;

        CurrentHealth -= damage;

        if (CurrentHealth <= 0) {
            CurrentHealth = 0;
            OnDie?.Invoke();
        }

        if (!bypassInvulnerability) {
            _invulnerabilityRemaining = invulnerabilityDuration;
        }

        if (_bar != null) {
            _bar.SetValue(CurrentHealth, MaxHealth);
        }
    }

    public void Heal(float gain) {
        Assert.IsTrue(gain >=0,
             "Cannot apply negative healing - call TakeDamage instead");

        CurrentHealth = Mathf.Min(CurrentHealth + gain, MaxHealth);

        if (_bar != null) {
            _bar.SetValue(CurrentHealth, MaxHealth);
        }
    }

    void Start() {
        if (_bar != null) {
            _bar.SetValue(CurrentHealth, MaxHealth);
        }
    }

    void FixedUpdate() {
        _invulnerabilityRemaining -= Time.deltaTime;
    }
}

```

Since the `Health` component's `TakeDamage()`/`Heal()` functions are the only ones that can modify the internal health value, and calling them always updates the health bar if one is provided, you know that anything that affects health will correctly update both the internal health value and the bar in sync, as well as handle doing things like invoking death. All that complexity is encapsulated, so outside code doesn't need to know the details of everything that might need to respond to changes in health state - it just needs to know the `TakeDamage()`/`Heal()` interface. And this restricts the possible search area for bugs in health changes to just a few lines in one file.

---
Tags: unity, c#, 2d
---


# Question
Title: See connected signals for instantiated Node while in Debug mode
I'm trying to debug an issue with my game, where the function that should be connected to a signal is not being called. I have a created minimal repro of the situation by:

1. Create a fresh Godot 4 project
2. Create a `Thing` scene with `StaticBody2D` node (with sprite and square collision shape) and a `Thing.gd` script:

```
extends StaticBody2D

func _on_input_event(viewport, event, shape_idx):
    if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT:
      modulate = Color(1,1,0,1) if event.is_pressed() else Color(1,1,1,1)

```

The `_on_input_event` function is connected to the `input_event` signal of the `StaticBody2D`.
3. Creating a `Root` `Node2D` node with a `Root.gd` script:

```
extends Node2D

var thing_scene = preload("res://Thing.tscn")

func _ready():
    var other_thing = thing_scene.instantiate()
    other_thing.position = Vector2(200, 200)
    add_child(other_thing)

```
4. Set a break point at that last line of code
5. Run the `Root` node in debug mode
6. When the breakpoint hits, click "Locals" =\> "other\_thing"'s Object ID to open the Inspector

At this point I *can* see the *properties* of the Node, like so:

My problem is that I see *nothing* if I then click on the "Node" tab next to "Inspector", it will just say:

> Select a single node to edit its signals and groups

Here's a screenshot of that:

What I was *hoping* to see is the same thing I see when *not* running in Debug mode and selecting the to-be-instantiated scene's `StaticBody2D` node:

In my sample / repro above the signal *is* working because I can observe the function's effects. In my actual game the signal is *not* working, which is why I'm looking for a way to debug that situation. I want to know if the signal is connected at all, or if something else is causing my issues.

Bottom line: How can I check connected signals for a component created with `instantiate()` while debugging?

# Answer
I'm unaware of a way to see the connected signals of a `Object` in runtime in the debugger.

You could select the `Node` in the "Scene" in the "Local" tab while the game is running, but that will only show you the signals connected in design. I mean, it is not looking at the `Node`s in runtime. You can see at the `Node`s in runtime using the "Remote" tab, but then it won't show the signals.

---

Instead, we could check the connections form code. To see what is connected to an `Object` do this:

```
for signal_description in signal_source.get_signal_list():
    var signal_name := str(signal_description["name"])
    var connections := signal_source.get_signal_connection_list(signal_name)
    for connection in connections:
        prints(connection)

```

Or to see what is connected to an `Object` do this:

```
for connections in signal_target.get_incoming_connections():
    for connection in connections:
        prints(connection)

```

---

Regardless, about the issue you are trying to debug… You don't need to connect the `"input_event"` signal from the `StaticBody2D` to itself, instead you can override the virtual method `_input_event`.

---

Finally, about the source of your issue… Following your instructions you didn't set `input_pickable` to `true`. It defaults to `false` in Godot 4.

You need to set `input_pickable` to `true` for either the `"input_event"` signal or the virtual method `_input_event` to work. **Addendum**: Inside of a `Viewport` (either `SubViewport` or `Window`) you also need to set `physics_object_picking` to `true`.

This is likely the source of the issue.

*Note: `"input_event"` and `_input_event` also don't work if the `collision_layer` property is empty (i.e. `0` \- it defaults to `1`).*

---

By the way, be aware that, based on your first picture, you have added an instance of `Thing` in `Root` in the editor. And you are also adding another instance of `Thing` from the code in `_ready`. So there will be two instances in runtime.

You also want to make sure the positions and dimensions of the collision shape are what you expect. You can enable "Visible Collision Shapes" in the "Debug" menu so Godot renders the collision shapes in the running game.
> 1 votes

---
Tags: debugging, gdscript, godot-4
---


title: How to enable V-Sync in Java?

text:
# Question
Title: How to enable V-Sync in Java?
I have used the BufferStrategy, but my code runs still way too fast. `xrandr` reports that `TearFree` is "on" and the video mode has 60 Hz. But when I measure the time between two frames, I get one millisecond or less instead of about 16ms.

I am using OpenJDK 17.0.4 on Debian 11 using Linux 5.10.0-20-amd64. The hardware is an AMD Ryzen 7 5700G. I have visually tested TearFree with `glxgears` which reports about 60 frames.

Output of `xrandr`:

```
HDMI-A-0 connected 3840x2160+0+0 (normal left inverted right x axis y axis) 698mm x 393mm
        EDID:
                00ffffffffffff0009d1507945540000
                1e1f0103804627782e5995af4f42af26
                0f5054a56b80d1c0b300a9c081808100
                81c0010101014dd000a0f0703e803020
                3500ba892100001a000000ff0058374d
                30313638353031390a20000000fd0018
                4c1e873c000a202020202020000000fc
                0042656e5120455733323730550a0165
                02034df1515d5e5f6061101f22212005
                14041312030123090707830100006d03
                0c002000387820006001020367d85dc4
                01788003681a00000101283cfde305e0
                01e40f180000e6060501544c2c565e00
                a0a0a029502f203500ba892100001abf
                650050a0402e6008200808ba89210000
                1c0000000000000000000000000000ad
        GAMMA_LUT_SIZE: 4096
                range: (0, -1)
        DEGAMMA_LUT_SIZE: 4096
                range: (0, -1)
        GAMMA_LUT: 0
                range: (0, 65535)
        CTM: 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0
                0 1
        DEGAMMA_LUT: 0
                range: (0, 65535)
        TearFree: on
                supported: off, on, auto
        HDCP Content Type: HDCP Type0
                supported: HDCP Type0, HDCP Type1
        Content Protection: Undesired
                supported: Undesired, Desired, Enabled
        vrr_capable: 0
                range: (0, 1)
        max bpc: 8
                range: (8, 16)
        underscan vborder: 0
                range: (0, 128)
        underscan hborder: 0
                range: (0, 128)
        underscan: off
                supported: off, on, auto
        scaling mode: None
                supported: None, Full, Center, Full aspect
        link-status: Good
                supported: Good, Bad
        CONNECTOR_ID: 80
                supported: 80
        non-desktop: 0
                range: (0, 1)
   3840x2160     60.00*+  60.00    50.00    59.94    30.00    25.00    24.00    29.97    23.98
   2560x1600     59.94
   2560x1440     59.95
   1920x1200     60.00
   1920x1080     60.00    60.00    50.00    59.94    30.00    25.00    24.00    29.97    23.98
   1600x1200     60.00
   1680x1050     59.88
   1600x900      60.00
   1280x1024     75.02    60.02
   1440x900      60.00
   1280x800      59.91
   1152x864      75.00
   1280x720      60.00    50.00    59.94
   1024x768      75.03    60.00
   832x624       74.55
   800x600       75.00    60.32
   720x576       50.00
   720x480       60.00    59.94
   640x480       75.00    60.00    59.94
   720x400       70.08

```

Complete Java example code just drawing a single blue dot:

```
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Label;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Map;

public class Gfx
{
  static void draw ()
  {
    pixel (width/2, height/2, blue);
  }

  static boolean done = false;

  static final int black = Color.BLACK.getRGB ();
  static final int white = Color.WHITE.getRGB ();
  static final int red   = Color.RED.getRGB ();
  static final int green = Color.GREEN.getRGB ();
  static final int blue  = Color.BLUE.getRGB ();

  static final int width   = 100;
  static final int height  = 100;
  static final int canvas_width  = 1000;
  static final int canvas_height = 1000;

  static Frame frame = null;
  static void frame (String title)
  {
    frame = new Frame (title);
    frame.addWindowListener (new WindowAdapter ()
      {
        @Override
        public void windowClosing (WindowEvent ev) { done = true; }
      });
    frame.setResizable (false);
    frame.setLayout (new BorderLayout ());
    frame.setFont (new Font(Font.MONOSPACED, Font.PLAIN, 18));
  }

  static FileDialog loadfile = null;
  static void loadfile ()
  {
    loadfile = new FileDialog (frame);
  }

  static BufferedImage image = null;
  static void image ()
  {
    image = new BufferedImage (width, height, BufferedImage.TYPE_INT_ARGB);
    draw();
  }

  static void pixel (int x, int y, int c) { image.setRGB (x, y, c); }
  static void pixel (int x, int y) { pixel (x, y, black); }

  static Canvas canvas = null;
  static void canvas ()
  {
    canvas = new Canvas ()
      {
        @Override
        public Dimension getPreferredSize () {
          return new Dimension (canvas_width, canvas_height); }
        @Override
        public void paint (Graphics graphics)
        {
          super.paint (graphics);
          graphics.drawImage (image, 0, 0, canvas_width, canvas_height, this);
        }
      };
    frame.add (canvas, BorderLayout.CENTER);
  }

  static MenuBar menubar = null;
  static void menubar ()
  {
    menubar = new MenuBar();
    Menu menu_app = new Menu("App");
    menubar.add(menu_app);
    MenuItem app_loadfile = new MenuItem("Load File");
    app_loadfile.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ev)
        {
          loadfile.setVisible (true);
          System.out.println (loadfile.getDirectory() + loadfile.getFile());
        }});
    menu_app.add(app_loadfile);
    frame.setMenuBar (menubar);
  }

  static Label statusbar = null;
  static void statusbar ()
  {
    statusbar = new Label("Hallo");
    frame.add (statusbar, BorderLayout.SOUTH);
  }

  static void start ()
  {
    frame.pack ();
    frame.setVisible (true);
    canvas.createBufferStrategy(2);
    BufferStrategy strategy = canvas.getBufferStrategy();
    long t0 = -1;
    long t1 = -1;
    DecimalFormat df = new DecimalFormat("###");
    // Main loop
    while (!done) {
      // Prepare for rendering the next frame
      if (t1 > 0) t0 = t1;
      t1 = System.currentTimeMillis();
      if (t0 > 0)
        System.out.print("     \r" + df.format(t1 - t0));

      // Render single frame
      do {
        // The following loop ensures that the contents of the drawing buffer
        // are consistent in case the underlying surface was recreated
        do {
          // Get a new graphics context every time through the loop
          // to make sure the strategy is validated
          Graphics graphics = strategy.getDrawGraphics();

          // Render to graphics
          // ...
          image();
          graphics.drawImage (image, 0, 0, canvas_width, canvas_height, canvas);

          // Dispose the graphics
          graphics.dispose();

          // Repeat the rendering if the drawing buffer contents
          // were restored
        } while (strategy.contentsRestored());

        // Display the buffer
        strategy.show();

        // Repeat the rendering if the drawing buffer was lost
      } while (strategy.contentsLost());
    }

    // Dispose the window
    frame.setVisible(false);
    frame.dispose();
  }

  public static void main (String[] args)
  {
    frame ("Gfx");
    loadfile ();
    menubar ();
    image ();
    canvas ();
    statusbar ();
    start ();
  }
}

```

I tried also this example, but it does not compile anymore:

```
VSyncTest.java:7: error: package sun.java2d.pipe.hw is not visible
import sun.java2d.pipe.hw.ExtendedBufferCapabilities;
                      ^
  (package sun.java2d.pipe.hw is declared in module java.desktop, which does not export it)
1 error

```

# Answer
`drawImage()` returns immediately - it doesn't wait until the content is drawn.

Similarly, I don't see anything in the docs that says any of the other graphics code is blocks until drawn to screen. As such, you aren't measuring the refresh rate of the monitor, you are measuring frame rate of your simulation. specifically, you are measuring how quickly your code is looping & *attempting* to push stuff out.

The buffering prevents the screen from tearing - it promises that the hardware will update the entire screen at once using a buffer that can't be changed while the hardware is reading from it. But it doesn't do anything to throttle the rate at which you can change the other buffer(s).

If you want to get info about how fast the hardware is doing stuff, you might want to look into OpenGL Timer queries.

If you want to pursue synching up your code with the GL activities, (as discussed on this SO post), then you should look into using sync objects.

If the real goal is to throttle your framerate, we have a number of posts about dealing with timesteps in Java. If none of them address your issue, you should ask a new question about that specifically.
> 2 votes

---
Tags: java, vsync
---


# Question
Title: Most efficient way to get the world position of the 8 vertices of a Box Collider
What I am looking for is the most efficient way to get the world position of the 8 vertices of the Box Collider of a freely rotated Game Object. I cannot use collider.bounds since object is rotated, not axis-aligned.

I'm using Unity 5 with C#.

# Answer
Try this:

```
    BoxCollider b = obj.GetComponent<BoxCollider>(); //retrieves the Box Collider of the GameObject called obj

    Vector3 vertice1 = myobject.transform.TransformPoint(b.center + new Vector3(-b.size.x, -b.size.y, -b.size.z)*0.5f);
    Vector3 vertice2 = myobject.transform.TransformPoint(b.center + new Vector3(b.size.x, -b.size.y, -b.size.z)*0.5f);
    Vector3 vertice3 = myobject.transform.TransformPoint(b.center + new Vector3(b.size.x, -b.size.y, b.size.z)*0.5f);
    Vector3 vertice4 = myobject.transform.TransformPoint(b.center + new Vector3(-b.size.x, -b.size.y, b.size.z)*0.5f);
    Vector3 vertice5 = myobject.transform.TransformPoint(b.center + new Vector3(-b.size.x, b.size.y, -b.size.z)*0.5f);
    Vector3 vertice6 = myobject.transform.TransformPoint(b.center + new Vector3(b.size.x, b.size.y, -b.size.z)*0.5f);
    Vector3 vertice7 = myobject.transform.TransformPoint(b.center + new Vector3(b.size.x, b.size.y, b.size.z)*0.5f);
    Vector3 vertice8 = myobject.transform.TransformPoint(b.center + new Vector3(-b.size.x, b.size.y, b.size.z)*0.5f);

```
> 7 votes

# Answer
If you can access a Mesh of the same size and shape, you can use Mesh.bounds, which returns positions in local space.
> 2 votes

# Answer
```
public static List<Vector3> GetBoxColliderCornersWorld(BoxCollider boxCollider)
{
    Vector3 size = boxCollider.size;
    List<Vector3> list = new();
    var signs = new List<int> { -1, 1 };
    signs.ForEach(signX =>
        signs.ForEach(signY =>
            signs.ForEach(signZ => {
                var vector = new Vector3(size.x * signX, size.y * signY, size.z * signZ);
                list.Add(boxCollider.transform.TransformPoint(boxCollider.center + vector * 0.5f));
            })));

    return list;
}

```
> 0 votes

---
Tags: unity, c#, transformation, linear-algebra, collider
---


title: Score count-up speed based on music

text:
# Question
Title: Score count-up speed based on music
I'm trying to implement a score count-up that is synced with the tempo of some short music jingle, but I'm failing on calculating the math for it.

Let's say I have a total score of 2000 that I want to count-up on the screen to the player, starting from 0 up to 2000. There's a catch though - I want to have the count-up synced to a short music jingle that's played during the count-up.

Let's say the music jingle is 15 seconds long, in a specific BPM (beats per minute). As soon as the music jingle starts playing, the score starts counting up from 0, in a certain speed. What I would like to have is the score count-up reach 2000 just when the music jingle is ending (so in this case when 15 seconds has passed), so the count-up speed needs to be based on that music jingle's total time, which is 15 seconds. The same mechanic needs to work if I later on decide to change the music jingle to a 8 seconds jingle instead.

I can't really wrap my head around it and needs some assistance.

# Answer
You can do something as simple as converting the time spent counting so far to a fraction out of the total counting duration (capped at 1 so you don't overshoot if the time keeps accumulating), then multiply your target value by that fraction.

```
progress = secondsSinceCountingStarted/durationSeconds;
progress = Min(progress, 1.0);
// Optional: you can apply an easing function if you
// want progress to be faster at the start, end, or middle.
// progress = Ease(progress);
currentCount = Round(progress * targetCount);

```

If you want to use an easing function as mentioned in the comment, it can be anything that maps `f(0) = 0` and `f(1) = 1`, like the square function (eases in) or smoothstep (eases in & out).
> 1 votes

---
Tags: c++, mathematics, audio, music
---