# Question
Title: Moving Multiple Objects With Vector2.MoveTowards Not Consistent
Good Afternoon,

I'm trying to move three objects from their current position to a shared target position based on speed. Once they reach the target position, they move to a shared respawn location and then start their journey over again.

The objects move to the target position and restart their journey successfully. However, the problem is that the distance between each object starts to gradually change. Eventually, the spacing/gap between objects becomes bigger or smaller. I'm honestly not certain if this an issue caused by framerate changing, or if my logic is simply off.

---

Here is an example of how the three objects look at the start. They're evenly spaced out by an x value of 340:

* buttons0 (Left Square) Pos X 340
* buttons1 (Middle Triangle) Pos X 680
* buttons2 (Right Triangle) Pos X 1020
* targetPos (The position they're traveling to) Pos X -340
* RespawnPos (Where they restart) Pos X 680

---

And here is one example of what eventually happened to the spacing after a short period of time:

---

Here is the code I am currently using:

```
public IEnumerator MoveTheButtons()
    {
        var i = 0;

        while(needsToMove)
        {

            while (i < 3)
            {
                buttons[i].MyRectTransform.position = Vector2.MoveTowards(buttons[i].MyRectTransform.position, targetPos.position, buttonTravelSpeed * Time.deltaTime);

                if (buttons[i].MyRectTransform.position.x <= targetPos.position.x)
                {
                    buttons[i].MyRectTransform.position = RespawnPos.position;

                }

                i++;

            }

            if (i == buttons.Count)
            {
                i = 0;
            }

            yield return null;

        }

    }

```

---

Additionally, here is the code calling the MoveTheButtons() Coroutine. I made sure that it's only being called once:

```
private IEnumerator BeginActionCommand()
{
    xxxtestSkill.needsToMove = true;

    // Start moving the buttons
    StartCoroutine(xxxtestSkill.MoveTheButtons());

    var isComplete = false;

    while (!isComplete)
    {
        if (xxx.myInputActions.Minigame.Any.WasPressedThisFrame())
        {
            if(correctButtonPressed && currentButton.canBePressed)
            {
                Debug.Log("Correct Button Pressed!");
                Debug.Log("Timed Correctly!");
            }
            else
            {
                Debug.Log("WRONG Button Pressed!");
            }
        }

        if (xxx.myInputActions.Minigame.EndButton.WasPressedThisFrame())
        {
            isComplete = true;
            yield break;
        }

        yield return null;

    }

}

```

I'd like to keep this as a Coroutine and have one method move all three buttons, rather than have each object move on their own in their individual Update() methods.

I hope this is clear enough. Thanks so much for taking the time!

# Answer
Your framerate will very rarely work out such that your code executes at the exact moment the button hits the target. Usually you'll run a little early, and the button hasn't hit the target yet, or a little late, and the button should have hit the target a little in the past.

`Mathf.MoveTowards` removes any overshoot, so you don't see it go past the target. Then the respawn code puts them back *exactly* at the respawn point. That means if the button should have arrived at the target, say, 0.001 seconds ago, you've discarded 0.001 seconds' worth of its motion. It should have had time to move from the respawn point, but you discarded any "loose change" from overshooting the target instead of applying it to the next pass. This slightly shifts the position of the teleported button relative to its peers.

If you throw out enough of this loose change across several cycles, you begin to significantly distort the spacing between buttons.

We can fix that in a couple of ways. The most direct is this:

```
public IEnumerator MoveTheButtons() {
    while(needsToMove) {

        // No need for separate declaration/test/increment lines when 'for' does all that.
        for (int i = 0; i < 3; i++) {
            // We'll work on a temporary - cheaper than poking Transform every time.
            Vector3 pos = buttons[i].MyRectTransform.position;

            // Slide left and allow overshoot.
            pos.x -= buttonTravelSpeed * Time.deltaTime;

            // If we hit OR PASSED the target, warp back to respawn,
            // preserving any overshoot as movement post-respawn.
            if (pos.x <= targetPos.position.x)  {
                pos.x += RespawnPos.position.x - targetPos.position.x;
            }

            // Assign just once.
            buttons[i].MyRectTransform.position = pos;
        }

        // No need to compare i to count; for loop starts over next frame.
        yield return null;
    }
}

```

This preserves the loose change we have from overshooting the target... at least to within float rounding precision. You can still get accumulating error from this, but if you're only ever going through dozens of cycles, not hundreds or thousands, it probably won't be noticeable.

If you need something like this that's bulletproof, even if we leave the game cycling continuously for a week, we can go with a more over-engineered solution:

```
public IEnumerator MoveTheButtons() {
    // We're going to model our cycle as a "phase" number that just
    // continuously counts down from 1 to 0 and repeats forever.
    float phase = 1f;

    // Distance covered in one cycle (scale factor between phase and position)
    float span = RespawnPos.position.x - targetPos.position.x;

    // Time scale factor converting from seconds to cycles.
    float phaseSpeed = buttonTravelSpeed / span;

    // Initialize a phase offset for each button - how early/late should
    // it cross the 0/target point, relative to the ruling phase metronome?
    foreach (var button in buttons) {
        // Note that this value can be arbitrarily large to start,
        // if we have buttons that start way off and don't join the cycle
        // until a few repetitions in.
        buttons[i].phaseShift = (buttons[i].MyRectTransform.position.x - RespawnPos.position.x)/span;
    }

    while (needsToMove) {
        // Advance the governing metronome.
        phase -= Time.deltaTime * phaseSpeed;

        // Wrap around at zero.
        if (phase < 0f) {
            phase += 1f;

            // Any buttons that have not yet hit the target need
            // their phase shift updated so they don't teleport back.
            foreach (var button in buttons) {
                if (button.phaseShift >= 0f) button.phaseShift -= 1f;
            }
        }

        foreach (var button in buttons) {
            // Compute button's position in cycle according to metronome.
            float buttonPhase = phase + button.phaseShift;
            // Wrap around at zero (teleport from target back to respawn point).
            if (buttonPhase < 0f) buttonPhase += 1.0f;

            // Turn button phase into corresponding position.
            var pos = targetPos.transform.position;
            pos.x += buttonPhase * span;
            button.MyRectTransform.position = pos;
        }

        yield return null;
    }
}

```
> 2 votes

---
Tags: unity, frame-rate, logic, coroutines
---


# Question
Title: JIttery rendering and ghost trail behind platformer character in Godot
I have no gamedev experience and I just started learning. I wanted to develop a basic platformer to learn.

I got stuck pretty soon with rendering in Godot. When I run the game, it just feels... Jittery... There is sort of a "ghost trail" behind my player, most noticeable when jumping. The run animation also does not seem very clear to me.

I am running it on: `Vulkan API 1.2.231 - Forward+ - Using Vulkan Device #0: Apple - Apple M1` using `Godot Engine v4.1.1.stable.official.bd6af8e0e`. According to the documentation, I should be able to run this without seeing any stutter, and I did not expect jitter since my MacBook Pro 13 should run at 60Hz.

I have read several articles and forum posts online on this issue, and I think I am using `delta` in my processing correctly and that my `AnimationPlayer` is configured fine. I made sure that VSync is enabled, my stretch mode is set to `canvas_items`, my `Default texture filter` is set to `Nearest` and I have enabled both `Snap 2D transforms to pixel` and `Snap 2D vertices to pixel`.

My player movement logic is written in `_physics_process` method. I have also tried doing it in `_process`, but I don't notice any difference.

Can someone tell me what I am doing wrong?

-- EDIT --

I mispoke originally and wrote that I am experiencing stutter instead of jitter.

# Answer
> 2 votes
After testing (both on my end and OP end) with different rendering backends (including Godot support for ANGLE, on prerelease at the time of writing), and the common advice regarding jittering and stutter, we have found out that:

* The movement in Godot seems to be performant and smooth, yet the visuals are not desirable (what OP describes as a "ghost trail").
* It is possible to export the game, and other can play it without the issue.
* The issue is rooted in hardware, and it seems that it cannot be fixed via Godot configuration. It is unclear to me if this is purely a GPU issue, or if there are other issues elsewhere on the video stack (e.g. OS, driver, display).
* Thus, changing the hardware is only solution found at the time of writing.

---
Tags: godot, platformer, godot-4
---


title: Center image in Steam page

text:
# Question
Title: Center image in Steam page
I am struggling to Center my image in my game's Steam page.

`[img][center]` --\> Error

`[center][img]` --\> Just prints a text "center" before and after the image :(.

How would a mere mortal center the image on Steam?

# Answer
I don't think this is possible to do with Steam's markdown. I just opted to make my image exactly 618px wide (unsure if this has some special relevance, I would suggest experimenting with larger images too and see if those are automatically fit \[most likely they will\]). So center your wanted content on a larger transparent image.
> 2 votes

# Answer
This is an old question but for future reference this is doable by inserting ` ` characters in the description text. If you do it immediately before the `[img]` tag it will push the image slightly to the right. My images are 400px wide and I needed 26 of those non-breaking spaces to get the image to center.

Note that if you open the description editor again, the non-breaking spaces will be replaced by normal spaces, and if you save that, the centering will not work! So make sure you edit your description in a separate file that you copy-paste into the description box.

Hope it helps someone.
> 2 votes

---
Tags: steam
---


title: unity onTriggerEnter does not work

text:
# Question
Title: unity onTriggerEnter does not work
so in here there is a box to which i have attaches this script and ATTACH1 is a socket interactor here i want is when the box which i have attaches attaches to that socket interactor the text which is on canvas destroy!! But infortunately this is not working! do you see any issues here or something that u thing is wrong or I missed?

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

public class Box1 : MonoBehaviour
{

    private GameObject box2;
    private Text noBox;
    // Start is called before the first frame update
    void Start()
    {
        box2 = GameObject.Find("ATTACH1");
        noBox = GameObject.Find("text").GetComponent<Text>();

    }

    void Update()
    {

    }
    void onTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag("Player"))
        {
            Destroy(noBox);
        }
    }
}

```

# Answer
You have to name the method `void OnTriggerEnter` with a capital `O`. Not `void onTriggerEnter`. Capitalization matters. If you don't name message handler methods **exactly** as written in the documentation, then the engine won't call them.

There are also a couple other problems in your code:

1. Using `GameObject.Find` to create object relations is bad. It is slow. It doesn't work when you type the name of the object wrong. It breaks when you change the name of the object. It breaks when you make another object with the same name. It is better to make it a `public Text noBox;` variable and then assign the correct object in the inspector.
2. The code will throw an error when the player enters the trigger a second time, because `noBox` will already be destroyed. I recommend to check beforehand if the box still exists:

```
    void OnTriggerEnter(Collider other)
    {
        if (noBox != null && other.gameObject.CompareTag("Player"))
        {
            Destroy(noBox);
        }
    }

```
> 2 votes

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


title: Rotate Object Smoothly When Dragging

text:
# Question
Title: Rotate Object Smoothly When Dragging
I want to make a 3d object rotate smoothly when being dragged in a ui in Unity. My stuff currently works but I just can’t get it to rotate smoothly, I can only make it rotate instantly which looks bad. So my question: How do I make the Object rotate smoothly if this code here makes it rotate instantly?

```
void IDragHandler.OnDrag(PointerEventData eventData)
    {
        mousePositionDelta = Mouse.current.delta.ReadValue();

        float dotProduct = -Vector2.Dot(mousePositionDelta, uiCamera.transform.right);
        characterModelTransform.Rotate(transform.up, dotProduct * characterRotationModifier);

        prevMousePosition = eventData.position;
    }

```

Thank you for any answers in advance ^^

# Answer
It seems strange you are updating prev mouse position if you use some other function to get mouse deltas.

I also strongly suspect you are tripping over different spaces, as the mouse deltas are most likely aligned with the screen and doing a dot product with a 3D vector in Unity space makes no sense.

If you want to smooth out the rotation being applied you can keep a parameter, say float targetRotation which you will modify in the function you show. Then in Update you can use Mathf.SmoothDampAngle to change the transform smoothly.
> 0 votes

# Answer
I think I understand what you want to do. This is not pretty, but it works to smoothly start and end rotation from the mouse drag.

```
public GameObject Target;  //GameObject to rotate

[Range(0.1f,1f)]
public float smoothTime = 0.3f;

float CurrentSpeed = 0f;
float WantedSpeed  = 0f;
float SpeedInc     = 0f;
float Velocity = 0.0f;

public void OnDrag(PointerEventData eventData)
{
    SpeedInc += eventData.delta.x;  // Find the mouse delta x.
}

void Update()
{
    WantedSpeed -= SpeedInc * Time.deltaTime;
    WantedSpeed = Mathf.SmoothDamp(WantedSpeed, 0, ref Velocity, smoothTime);
    SpeedInc = 0;
    Target.transform.Rotate(Target.transform.up,WantedSpeed,Space.Self);
}

```
> 0 votes

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


# Question
Title: How to design an EventBus(guided by the pub/sub pattern)
I'm working on my game engine, and was faced with the fact, that i don't know how properly design an event system. As a pattern i choose Pub/Sub with an event bus, but i don't know where i should 'place' bus. I have the main engine class, called `RubyApp`, which connect all engine systems. I was thinking of placing an event bus inside a `Window` class, which is responsible(unexpectedly!:)) for the main game window, and in `Window` constructor pass pointer to bus to `glfwSetWindowUserPointer()`. But I have doubts about this idea, as well as about making `EventBus` fields and methods static

# Answer
> i don't know where i should 'place' bus

Being fully internal, it should be part of the core of the engine, and no particular place beyond that.

You could have one single event bus with multiple events, in which case it can be static/singleton/global. It is also possible to have multiple buses, for different purposes, which does not preclude an static/singleton/global façade from where you can get the different instances.

It is more interesting to consider who is responsible for connecting it.

We have three options:

* Subsystems do not know about the event bus: For receive messages, the code that construct the subsystems, can also make the connections so the subsystems do not even need to be aware of them. To send messages, they are going to need some handle to the event bus that you pass on construction, so the subsystems can use it to send messages.
* Subsystems do about the event bus: so they can connect themselves, and the code that constructs them is simpler. Plus they can directly call into the event bus to send messages.
* A mix of both.

I'm aware that the common advice against static/singletons/global is that changes to them propagate to everything (they are a hidden dependency). So, if we are worried about changes in the event bus, the former approach makes some sense.

However, being internal, the event bus would only be changing because a change to its interface is necessary. Plus I do not expect that update the code that uses it to be too complicated.

Furthermore, the purpose of the event bus is to allow subsystems to communicate using it, so that they not need to worry if there is code handling the messages on the other side. Which means that as long as the subsystems use the event bus, they can change independently of each other. That it, they would be fully decoupled.

Thus, my suggestion is to let subsystems access the event bus directly.

Yet please notice that by using the event bus for communication between subsystems, they lose the ability to give a result right away. Thus, I do not believe all your subsystems need to be fully decoupled. If it make sense to couple subsystems, couple them.

---

> I was thinking of placing an event bus inside a `Window` class

I would make the event bus separate from the `Window`, avoiding to make the `Window` code more complex than necessary.

The fact that you want it in the `Window` class makes me think that you are thinking of the message loop. You, of course, want a layer of abstraction on top of it... Which, GLFW already gives you, and it allows you to connect callbacks for multiple events. The callbacks might send messages over the event bus if that is necessary.

You might also wonder if you need to protect your code from changes in GLFW. However, GLFW will not change beneath you. If it changes, it is because you have decided to update it. However, it makes sense to limit the propagation of those changes by keeping all the GLFW specific code in a single place, so if you need to update GLFW, you know you only need to change code there.

---

> how properly design an event system

An event bus should allow to:

* Add and remove listeners for a particular "event". Which means there will be a list of connections (which you might pool).
* Send messages for a particular "event" which all listeners of that "event" would receive.

For your consideration: A feature that you might find useful is the ability to schedule a message for an specific frame. Which also requires a method to tell the event bus which is the current frame (which you would call from the game loop), so it dispatched scheduled messages.

Even if you do not schedule messages, it might still be a good idea to not dispatch them right away, but dispatch them at a dedicated time using a call from the game loop.

I'm confident you can find plenty of examples.

However, given that this is for internal use, I suspect the primary usage would be commands. Thus, so I submit to your consideration: channels. A subsystem would create a channel, and only the subsystem that created will be listening on it. Other subsystems can then get the channel (so they must be accesible from anywhere), and use it to send messages to that particular subsystem. Thus you would not have API to add and removing listeners. It also means that the subsystem might poll messages, instead of being called.
> 0 votes

---
Tags: c++, architecture, gui, events, glfw
---


# Question
Title: Collision in space between two characterbody3d
I have a characterbody3d that acts as a spaceship that I have temporarily given movement using the keyboard and then I have a characterbody3d that acts as a player that I have placed inside the ship, but outside the ship node. When the ship moves, the player should stay still because it is floating inside it, but when it collides with a wall of the ship (I have colliders3d for that), it should collide and follow the movement of the ship. What is happening to me now is that the ship stops completely and the player stays completely still. I'm not very good at this, I'm about 5 hours into godot and maybe I'm using a characterbody3d for the ship when it should be something else or maybe there's no way to do what I say automatically and I need to program something to do it. such an effect, I don't know. I use godot 4 and my question is more to see how I approach this to obtain the desired result. If you need it, I can pass the project on to you since it is just a test, nothing more.

I have tried several things both in code and touching the properties of the objects and the colliders, but I can't get anything

This is my node structure:

* Node3D
    + Ship (Characterbody3D)
        - Mesh
        - Collider1 (represents one of the walls of the ship)
        - Collider2 (represents one of the walls of the ship)
        - Collider3 (represents one of the walls of the ship)
        - Collider4 (represents one of the walls of the ship)
    + Player (Characterbody3D)
        - Camera3D
        - Collider1 (Capsule3D)

This is the code associated with the characterbody3d that acts as a ship:

```
extends CharacterBody3D

@export var max_speed = 50.0 # FIXME velocidad de la luz 99%
@export var acceleration = 0.6
@export var pitch_speed = 1.5
@export var roll_speed = 1.9
@export var yaw_speed = 1.25  # Set lower for linked roll/yaw
@export var input_response = 8.0

var horizontal_speed = 0.0
var vertical_speed = 0.0
var forward_speed = 0.0
var pitch_input = 0.0
var roll_input = 0.0
var yaw_input = 0.0

func get_input(delta):
    # STRAFE LEFT AND RIGHT
    if Input.is_action_pressed("STRAFE_RIGHT"):
        horizontal_speed = lerp(horizontal_speed, max_speed, acceleration * delta)
    if Input.is_action_pressed("STRAFE_LEFT"):
        horizontal_speed = lerp(horizontal_speed, -max_speed, acceleration * delta)

    # STRAFE FRONT AND BACK
    if Input.is_action_pressed("STRAFE_FRONT"):
        forward_speed = lerp(forward_speed, max_speed, acceleration * delta)
    if Input.is_action_pressed("STRAFE_BACK"):
        forward_speed = lerp(forward_speed, -max_speed, acceleration * delta)

    # STRAFE UP AND DOWN
    if Input.is_action_pressed("STRAFE_UP"):
        vertical_speed = lerp(vertical_speed, max_speed, acceleration * delta)
    if Input.is_action_pressed("STRAFE_DOWN"):
        vertical_speed = lerp(vertical_speed, -max_speed, acceleration * delta)

    # ROTATE LEFT AND RIGHT
    if Input.is_action_pressed("ROTATE_LEFT"):
        yaw_input = lerp(yaw_input, yaw_speed, acceleration * delta)
    if Input.is_action_pressed("ROTATE_RIGHT"):
        yaw_input = lerp(yaw_input, -yaw_speed, acceleration * delta)

    # ROTATE UP AND DOWN
    if Input.is_action_pressed("ROTATE_UP"):
        roll_input = lerp(roll_input, roll_speed, acceleration * delta)
    if Input.is_action_pressed("ROTATE_DOWN"):
        roll_input = lerp(roll_input, -roll_speed, acceleration * delta)

    # ROTATE UP AND DOWN
    if Input.is_action_pressed("TURN_LEFT"):
        pitch_input = lerp(pitch_input, pitch_speed, acceleration * delta)
    if Input.is_action_pressed("TURN_RIGHT"):
        pitch_input = lerp(pitch_input, -pitch_speed, acceleration * delta)

    #pitch_input = lerp(pitch_input, Input.get_axis("pitch_down", "pitch_up"), input_response * delta)
    #roll_input = lerp(roll_input, Input.get_axis("roll_right", "roll_left"), input_response * delta)
    # yaw_input = lerp(yaw_input, Input.get_axis("yaw_right", "yaw_left"), input_response * delta)
    #yaw_input = roll_input

    # TODO recoger también las pulsaciones directas con el ratón en los botones

func _physics_process(delta):
    get_input(delta)
    transform.basis = transform.basis.rotated(transform.basis.z, roll_input * roll_speed * delta)
    transform.basis = transform.basis.rotated(transform.basis.x, pitch_input * pitch_speed * delta)
    transform.basis = transform.basis.rotated(transform.basis.y, yaw_input * yaw_speed * delta)
    transform.basis = transform.basis.orthonormalized()

    velocity = (-transform.basis.z * horizontal_speed) + (-transform.basis.x * forward_speed) + (transform.basis.y * vertical_speed)
    #move_and_collide(velocity * delta)
    move_and_slide()
    #if move_and_collide(velocity * delta):
    #   for i in get_slide_collision_count():
    #       var col = get_slide_collision(i)
    #       if col.get_collider() is CharacterBody3D:
    #           col.get_collider().apply_force(col.get_normal() * 1000)

```

And this is the one with the player who has a camera with the script:

```
extends Camera3D

const ray_length = 1000

#@export var pushForce = 500
#@export var bodyPath: NodePath = ".."
#@onready var body: CharacterBody3D = get_node(bodyPath)

var SENSITIVITY = 0.3
var v = Vector3()

func _ready():
    Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)

func _process(delta):
    pass

func _input(event):
    if event is InputEventMouseMotion:
        v.y -= (event.relative.x * SENSITIVITY)
        v.x -= (event.relative.y * SENSITIVITY)
        v.x = clamp(v.x, -80, 90)
    #if event is InputEventMouseButton:
    #   if event.button_index == MOUSE_BUTTON_LEFT:
    #       if event.pressed:
    #           var camera = $Camera3D
    #           var from = camera.project_ray_origin(event.position)
    #           var to = from + camera.project_ray_normal(event.position) * ray_length
    #           print("Hit at point: ", to.position)

func _physics_process(delta):
    rotation_degrees.x = v.x
    rotation_degrees.y = v.y

    #if body.move_and_slide(): # true if collided
    #   for i in body.get_slide_collision_count():
    #       var col = body.get_slide_collision(i)
    #       if col.get_collider() is CharacterBody3D:
                #col.get_collider().apply_force(col.get_normal() * -pushForce)
                #body.velocity(col.get_normal() * -pushForce)

```

# Answer
> 4 votes
The main issue is this: You are responsible for moving the `Characterbody3D`.

This means that - barring an `AnimatableBody3D` serving as a moving platform※ - no interaction with another body will move the `CharacterBody3D`. In fact, nothing will push the `CharacterBody3D`, unless you write code for that.

※: In Godot 3 `KinematicBody` was the recommended way to make a moving platform, so yes a `KinematicBody` could ride on another. In Godot 4 `AnimatableBody3D` is the recommended way to make a moving platform. This means that **Making the ship a `AnimatableBody3D` might be a solution**.

This is good, in particular for beginners, because it means that at no point you will be fighting the physics engines. That is, at no point you will be trying to move the `CharacterBody3D` one way, when the physics engine wants to move it another way.

The basic physic bodies work like this:

* `StaticBody3D`: It does not move.
* `CharacterBody3D`: You move it.
* `RigidBody3D`: The physics engine moves it.

*Of course this is a simplification.*

Thus, picking between a `Characterbody3D` and `RigidBody3D` for a player character ultimately boils down to this question: can other things push it?

And in this case, it seems the ship should push the player character, thus **implementing the player character as a `RigidBody3D` is a solution**.

With that said, it does not mean we cannot script the ship pushing the player character. And looking at your commented code it seems you were on the right track...

Thus **scripting the movement of the `CharacterBody3D` is a solution**.

*No, a `CharacterBody3D` does not have `apply_force`, those are `RigidBody3D`. And no, `velocity` is not a method.*

You want something like this:

```
move_and_slide()
for i in get_slide_collision_count():
    var collision := get_slide_collision(i)
    var character := collision.get_collider() as CharacterBody3D
    if is_instance_valid(character):
        character.velocity = velocity.project(collision.get_normal())
        character.move_and_slide()

```

I'm not sure this is the desired behavior, but I expect that adding this code to the ship results in it "pushing" the player character, and hopefully you can tweak it from there.

---
Tags: 3d, godot-4
---


# Question
Title: How can I dynamically change the skin and blush colours of an animated sprite's face in Unity?
I want to achieve this effect in unity when processing my sprites before

After

I was thinking that I could use two color pickers to tell a shader only to create a gradient if two colors share a border. That way the gradient will not bleed into the other areas of the texture.

Most of the tutorials I've seen show how to do it with 2 colour textures, but I don't know how to isolate the specific colors and borders to make a gradient when there are more than 2 colors involved. I'm still a beginner to shaders, so I don't know if there's a better way to approach this.

# Answer
It's hard to answer this question without seeing any of your actual artwork, but I'll try anyway (if you don't have any actual artwork yet, you are trying to solve this problem way too early).

It sounds like you're trying to make this way more complicated than it should be.

If your character's face is a sprite...

...just make another transparent sprite for the blush...

... and place it over the face.

For more control over the color, you would normally make the blush sprite pure white and set the color in Unity.

In this simple example, my gradient blush is covering up the 5 lines on the cheek. This can be solved by adding the lines to the gradient blush, or making them a separate sprite and placing that above the gradient blush.

On the right side of the image, the girl's hair is partially obscuring the blush on her left cheek. This would require the hair to be on a separate layer on top of the blush.

**What if the character is 3D?** If the character is 3D, you might be able to get away with placing a blush sprite in front of the character's cheek as long as the player can't get close enough to tell that the blush is a sprite. Otherwise, you'll need a shader with an extra texture layer to blend over the main texture.
> 1 votes

---
Tags: unity, shaders, textures, fragment-shader, graphic-effects
---


# Question
Title: Where to put data/values of Status Effects... in Status effect object or just reference from Ability source?
for turn based game, units can get buffed/debuffed with status effects, like poison, etc. I would like to ask the advisable place where to put amount of poison in the data structure. I can think of two approaches, one is, on the Status Effect object itself, or the Status Effect will just reference it from base ability used. I would like to ask for best practice, and if there are better approaches aside from 2 below. And if possible, I'd like to ask the pros and cons. Thank you very much.

I. On the Status Effect object itself

```
// Unit model
{
  "unit_identifier": "some_unit_identifier1",
  "status_effects": [
    {
      "status_identifier": "some_identifier1",
        "status_type": "poison",
        "custom_value": 50,
        //... other properties
    }
  ]
}

```

II. Status Effect will just reference it from base ability used. "some\_status\_effect\_identifier2" will be used to get what ability was used. And get the value of poison from there.

```
// Unit model
{
  "unit_identifier": "some_unit_identifier1",
  "status_effects": [
    {
       "status_identifier": "some_status_effect_identifier2",
       "status_type": "poison",
        //... other properties
    }
  ]
}

```

# Answer
The main difference will be in cases you have buff/ debuffs. A self buff that increases your damage by 50% for 10sec would with the first model not care when you hit the enemy with the poison - as long as you manage to apply it with even one second left on the buff, the whole poison duration is profitting from it. With the second approach on each poison tick you need to check if there are buffs/ debuffs currently active, the poison only deals extra dmg during the duration of the buff and will be weaker once it runs out. There is as well more lookups needed to do (one check on skill start for the first method vs one check for each skill tick)

For me the second interaction in games always felt wrong. How does a debuff/ status effect on the enemy knows that I got stronger/ weaker? But there might be as well play styles that try to add as many debuffs on the enemy before using a self buff and increasing the damage for all of them.

Both the first or second method are giving the same result on self buffs for the enemy. If the enemy has 25% poison resist, the initial value of 50 would be still 50. The resist should be factored in at the time when the actual damage is dealt (in addition to any other buffs that are currently running at that time on the enemy)
> 2 votes

---
Tags: data-structure, turn-based
---


title: Sphere to plane collision

text:
# Question
Title: Sphere to plane collision
I could check for the distance of a vector from the sphere's center to the plane's center, but that would be inefficient, since there are multiple positions where they may not be intersecting but still are an "accepted" distance to flag a collision. I thought of two other methods (1) To get the distance between the center and all the vertices and (2) To have a normal on the plane get added to a vector between the plane's and sphere's centers, then check if the final point is in the sphere's radius and a certain distance from the plane, are these methods practical?

# Answer
> 2 votes
You're overcomplicating this.

```
public static float DistanceFromPlane(Vector3 testPoint, Vector3 pointOnPlane, Vector3 planeUnitNormal) {
    return Vector3.Dot(planeNormal, testPoint - pointOnPlane);
}

```

This works with any point on the plane, using the unit (length = 1) normal of the plane to extract only the perpendicular component of the distance.

This will return a signed distance value, with positive values on one side of the plane, negative on the other, and zero for points on the plane.

If the absolute value of this signed distance is equal to the sphere radius, the sphere is kissing the plane at one point. If it's less than the radius, the sphere intersects the plane. If it's greater than the radius, the sphere is wholly separated from the plane, and the sign tells you which side it's on.

You can do this a bit more efficiently if you express the plane as a 4-vector — then you only need one subtraction instead of three.

---
Tags: physics, computational-geometry
---


# Question
Title: Why check the ball and brick collision twice?
I watched https://www.youtube.com/watch?v=F86edI\_EF3s.

I believe the following code is the complete code

https://github.com/games50/breakout/tree/master/breakout13

And

https://github.com/games50/breakout/blob/master/breakout13/src/states/PlayState.lua is the code in play.

**relevant code:**

```
-- detect collision across all bricks with the ball
for k, brick in pairs(self.bricks) do

    -- only check collision if we're in play
    if brick.inPlay and self.ball:collides(brick) then

        -- add to score
        self.score = self.score + (brick.tier * 200 + brick.color * 25)

        -- trigger the brick's hit function, which removes it from play
        brick:hit()

        -- if we have enough points, recover a point of health
        if self.score > self.recoverPoints then
            -- can't go above 3 health
            self.health = math.min(3, self.health + 1)

            -- multiply recover points by 2
            self.recoverPoints = math.min(100000, self.recoverPoints * 2)

            -- play recover sound effect
            gSounds['recover']:play()
        end

        -- go to our victory screen if there are no more bricks left
        if self:checkVictory() then
            gSounds['victory']:play()

            gStateMachine:change('victory', {
                level = self.level,
                paddle = self.paddle,
                health = self.health,
                score = self.score,
                highScores = self.highScores,
                ball = self.ball,
                recoverPoints = self.recoverPoints
            })
        end

        --
        -- collision code for bricks
        --
        -- we check to see if the opposite side of our velocity is outside of the brick;
        -- if it is, we trigger a collision on that side. else we're within the X + width of
        -- the brick and should check to see if the top or bottom edge is outside of the brick,
        -- colliding on the top or bottom accordingly
        --

        -- left edge; only check if we're moving right, and offset the check by a couple of pixels
        -- so that flush corner hits register as Y flips, not X flips
        if self.ball.x + 2 < brick.x and self.ball.dx > 0 then

            -- flip x velocity and reset position outside of brick
            self.ball.dx = -self.ball.dx
            self.ball.x = brick.x - 8

        -- right edge; only check if we're moving left, , and offset the check by a couple of pixels
        -- so that flush corner hits register as Y flips, not X flips
        elseif self.ball.x + 6 > brick.x + brick.width and self.ball.dx < 0 then

            -- flip x velocity and reset position outside of brick
            self.ball.dx = -self.ball.dx
            self.ball.x = brick.x + 32

        -- top edge if no X collisions, always check
        elseif self.ball.y < brick.y then

            -- flip y velocity and reset position outside of brick
            self.ball.dy = -self.ball.dy
            self.ball.y = brick.y - 8

        -- bottom edge if no X collisions or top collision, last possibility
        else

            -- flip y velocity and reset position outside of brick
            self.ball.dy = -self.ball.dy
            self.ball.y = brick.y + 16
        end

        -- slightly scale the y velocity to speed up the game, capping at +- 150
        if math.abs(self.ball.dy) < 150 then
            self.ball.dy = self.ball.dy * 1.02
        end

        -- only allow colliding with one brick, for corners
        break
    end
end

```

## Question

Why does the above code check `if self.ball.x + 2 < brick.x and self.ball.dx > 0 then`?

I am especially confused because the code already did the collision check with `if brick.inPlay and self.ball:collides(brick) then`, but now the code adds a +2.

The same goes for the other similar sections `self.ball.x + 6 > brick.x + brick.width and self.ball.dx < 0` I don't know why +6 is also checked.

I also do not understand why ball velocity (`dx`) is also used for checking.

According to the comments in the source code, it seems to be a process at the edge, but I don't really understand it. Is this a common process (or patterns) in game programs (especially in 2D collision)?

---

I thought it was to solve the following problem(tunneling), but I felt it was something different and could not understand the code myself.

In games physics engines, what is "tunneling", also known as the "bullet through paper problem"?

---

In writing this question, I think I am getting a little more organized.

the ball needs to bounce at a leftward velocity if it is on the left edge, and the ball needs to bounce at a rightward velocity if it is on the right edge, so I think (not sure exactly) this is what is being handled here.

I assume the +2 and +6 are arbitrary by the author. I just don't know why those values should be added instead of the current position.

By using the algorithm above code, is it possible to determine which side (top, bottom, left, or right) the collision occurred with?

I am having a hard time imagining it clearly.

# Answer
The double check aspect of the code is discussed at this point in the video. The first check lets you know that *some sort* of collision occurred. However, in order to bounce the ball correctly, you need to know more about the collision. Hence the additional checks.

The `dx` test is for checking whether the collision occurred on the left or the right side of the brick and discussed here in the video:

> "...if the dx is negative, there's no way our ball is colliding with the left side of our brick..."

You are correct that the offset added to the checks isn't related to tunneling. As discussed here, it's a fix for dealing with corner hits:

> "it plays a little bit rough with corners because you could theoretically get into a position where you come in at an angle and it's intersecting with the paddle in two positions, both on top and on the left or on the bottom and on the left, so in that case adding two sort of prioritizes the Y being hit"

Note: I believe the presenter says "paddle" by mistake - a few seconds later they refer to it as a brick collision & the code being referenced at that point in time is the brick collision code you are asking about.

The offset is is also mentioned in the code comments here:

> -- left edge; only check if we're moving right, and **offset the check by a couple of pixels
-- so that flush corner hits register as Y flips, not X flips**

and also here:

> -- right edge; only check if we're moving left, , and **offset the check by a couple of pixels
-- so that flush corner hits register as Y flips, not X flips**

The correction for the other direction needs to account for the size of the ball. A mirrored correction would be -2, but the ball is 8 pixels, so the result is +6. This is an excellent example of how magic numbers (see also this SO post), while sometimes convenient in the moment, can make code harder to understand. It's a bit out of order, but a clearer, more descriptive way to write the code is mentioned at this point & then the +6 ball offset is discussed.

Using `ball.width - 2` would have made the mirrored logic a bit more obvious. For that matter, I would argue that using self documenting code, something like `ball.width - CORNER_CASE_OFFSET` would have been better yet.

In summary, it's a small offset meant to deal with a simultaneous collision edge case and it appears to have been chosen either experimentally or arbitrarily.
> 2 votes

---
Tags: collision-detection, collision-resolution, lua, love2d
---


# Question
Title: In C++, should POD-types be used for performance-critical parts, where many instances of the type will be handled?
(In C++) For a type whose instances will be handled in great numbers in performance-critical areas, such as a `Vector2` class representing 2D-positions, should such types preferably be made POD? So something like:

```
struct Vector2f
{
    float x;
    float y;
};

```

rather than:

```
struct Vector2f
{
    float x;
    float y;
    float crossProduct();
    float magnitude();
    ... // Etc, functions that could be handy
};

```

I've read that making types whom you will handle many instances of POD can improve performance, because it is easier for the program to deal with them since it doesn't have to deal with vtables and other things.

When should POD-types be used? Is there a good rule of thumb?

# Answer
There is no difference in your 2 code examples, both would run at the same speed.

> Is there a good rule of thumb?

Yes:

**Do not attempt to over-optimize your code**.

---

I follow these basic rules:

1. Avoid square root operations, and when required, store the result if needed multiple times.
2. Avoid `*`, `/` or `%` by powers of 2. Use `<<`, `>>` and `&` instead.
3. Use bit fields as much as possible. Parallel condition checks become "all for the cost of one".
4. Try to avoid nested loops, sometimes unavoidable, but if you hit a 3rd or *ouch* 4th nesting level, consider other ways to accomplish the task, try a tree, grid or other data structure.
5. Always `break;` or `return` out of loops early if possible.
6. Avoid recursion, unless the bounds are known and/or maxdepth is provided.
7. If you find yourself reusing the same heap reference a bunch of times: "object.something" or "object-\>something" store it in a local variable to help with cache locality.

Like every rule, these were made to be broken with discretion.

Beyond these rules, I ask myself: "Is it worth the hassle?" The profiler times will usually answer this question and identify the *critical* sections for me.

I only **then** do I optimize the problem areas.

---

To address your "vtable" concern, use `virtual` sparingly, or simply avoid inheritance in your classes and use static "POD" calls with reference parameters to implement common methods.

This is similar to what the compiler does in the background, only avoiding the run-time lookup table since the classes and calls are concrete(fixed addresses are provided) at compile time.

That is overkill, but to eek out every ounce of performance, this answers your question as asked.
> 3 votes

---
Tags: c++, performance
---


# Question
Title: Focus scene2d UI actors programmatically in libGDX
I am trying to implement keyboard movement in game main menu which is libGDX `Stage` with UI-Actors. I'm also trying to code this feature myself since I can't neither find anything relevant to it in the docs nor find libraries for the feature.

I have a bunch of `Button`s in the `VerticalGroup`. Using keyboard *UP* and *DOWN* keys, I want to somehow focus, highlight or hover buttons like the way that mouse hovering do. Hovewer, firing `FocusEvent` on children of the `VerticalGroup` do not change `Button` appearance.

So how do I focus these buttons or any other UI element (because there are other menus with more complex UI architecture) ?

Here is the code for the menu (Kotlin, using *ktx-scene2d* builders and *ktx-actors* event methods):

```
class MainMenuUi: Stage() {
    val root = verticalGroup {
        center()
        setFillParent(true)
        expand(true)
        space(spacing)
        fill(0.5f)
        wrap(false)

        textButton("Start")
        textButton("Settings")
        textButton("Exit")

        onKeyUp { key ->
            when(key) {
                Input.Keys.UP -> { /* ??? */ }
                Input.Keys.DOWN -> { /* ??? */ }
            }
        }
    }.also {
        addActor(it)
        keyboardFocus = it
    }
}

```

# Answer
I wanted to build something very similar but I didn't love the idea of manipulating the cursor like the other answer as it feels really hacky, though it might work.

In my case, I was also looking to be able to control everything with a controller as well. So I started with creating this concept of a `SelectableButtonGroup` which can take a Table of Buttons.

```
import com.badlogic.gdx.scenes.scene2d.Group

class SelectableButtonGroup(private val buttonGroup: Group) : SimulatesTouchOverButtons() {
    private var currentButtonIndex = 0

    fun changeSelectedButton(isUpPressed: Boolean): Boolean {
        unselectButton(buttonGroup.children[currentButtonIndex])
        val change = if (isUpPressed) {
            -1
        } else {
            1
        }
        // make sure the index wraps around
        currentButtonIndex =
            (currentButtonIndex + buttonGroup.children.size + change) % buttonGroup.children.size
        return selectButton(buttonGroup.children[currentButtonIndex])
    }

    fun clickSelected(): Boolean {
        val currentButton = buttonGroup.children[currentButtonIndex]
        return clickButton(currentButton)
    }

    fun releaseSelected(): Boolean {
        val currentButton = buttonGroup.children[currentButtonIndex]
        return releaseButton(currentButton)
    }

    fun isEmpty(): Boolean {
        return buttonGroup.children.size == 0
    }
}

```

Above uses this somewhat generic class for mimicking the mouse/touch events:

```
import com.badlogic.gdx.Input
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.utils.Pools

open class SimulatesTouchOverButtons {

    /**
     * Simulate button click down.
     *
     * @param button
     * @return
     */
    protected fun clickButton(button: Actor): Boolean {
        val event = Pools.obtain(
            InputEvent::class.java
        )
        event.type = InputEvent.Type.touchDown
        event.pointer = -1
        event.button = Input.Buttons.LEFT
        button.fire(event)
        val handled = event.isHandled
        Pools.free(event)
        return handled
    }

    /**
     * Simulate button click release.
     *
     * @param button
     * @return
     */
    protected fun releaseButton(button: Actor): Boolean {
        val event = Pools.obtain(
            InputEvent::class.java
        )
        event.type = InputEvent.Type.touchUp
        event.pointer = -1
        event.button = Input.Buttons.LEFT
        button.fire(event)
        val handled = event.isHandled
        Pools.free(event)
        return handled
    }

    /**
     * Simulate mousing over a button.
     *
     * @param button
     * @return
     */
    protected fun selectButton(button: Actor): Boolean {
        val event = Pools.obtain(
            InputEvent::class.java
        )
        event.type = InputEvent.Type.enter
        event.pointer = -1
        button.fire(event)
        val handled = event.isHandled
        Pools.free(event)
        return handled
    }

    /**
     * Simulate mousing off of a button.
     *
     * @param button
     * @return
     */
    protected fun unselectButton(button: Actor): Boolean {
        val event = Pools.obtain(
            InputEvent::class.java
        )
        event.type = InputEvent.Type.exit
        event.pointer = -1
        button.fire(event)
        val handled = event.isHandled
        Pools.free(event)
        return handled
    }
}

```

With `SelectableButtonGroup` we can implement a `com.badlogic.gdx.InputProcessor` or `com.badlogic.gdx.controllers.ControllerListener` and by sharing the same one the switching between keyboard and controller works pretty well with the shared state.

Here's the `InputProcessor`:

```
import com.badlogic.gdx.Input
import com.badlogic.gdx.InputAdapter
import com.badlogic.gdx.InputProcessor

// ButtonGroupInputProcessor wraps an input processor by intercepting up and down and modifying
// a SelectableButtonGroup.
class ButtonGroupInputProcessor(
    private val inputProcessor: InputProcessor,
    private val selectableButtonGroup: SelectableButtonGroup,
) :
    InputAdapter() {

    override fun touchDragged(screenX: Int, screenY: Int, pointer: Int): Boolean {
        return inputProcessor.touchDragged(screenX, screenY, pointer)
    }

    override fun mouseMoved(screenX: Int, screenY: Int): Boolean {
        return inputProcessor.mouseMoved(screenX, screenY)
    }

    override fun keyDown(keycode: Int): Boolean {
        when (keycode) {
            Input.Keys.UP -> selectableButtonGroup.changeSelectedButton(isUpPressed = true)
            Input.Keys.DOWN -> selectableButtonGroup.changeSelectedButton(isUpPressed = false)
            Input.Keys.ENTER -> selectableButtonGroup.clickSelected()
        }

        return inputProcessor.keyDown(keycode)
    }

    override fun keyUp(keycode: Int): Boolean {
        when (keycode) {
            Input.Keys.ENTER -> selectableButtonGroup.releaseSelected()
        }

        return inputProcessor.keyUp(keycode)
    }

    override fun keyTyped(character: Char): Boolean {
        return inputProcessor.keyTyped(character)
    }

    override fun touchDown(screenX: Int, screenY: Int, pointer: Int, button: Int): Boolean {
        return inputProcessor.touchDown(screenX, screenY, pointer, button)
    }

    override fun touchUp(screenX: Int, screenY: Int, pointer: Int, button: Int): Boolean {
        return inputProcessor.touchUp(screenX, screenY, pointer, button)
    }

    override fun touchCancelled(screenX: Int, screenY: Int, pointer: Int, button: Int): Boolean {
        return inputProcessor.touchCancelled(screenX, screenY, pointer, button)
    }

    override fun scrolled(amountX: Float, amountY: Float): Boolean {
        return inputProcessor.scrolled(amountX, amountY)
    }
}

```

Then back to your Stage code it could look something like this:

<pre><code>...

val buttonGroup = Table()
buttonGroup.add(startButton).row()
buttonGroup.add(optionsButton).row()
buttonGroup.add(exitButton)

// Add the table to the stage
stage.addActor(buttonGroup)

// Add the listeners for the buttons
val selectableButtonGroup = SelectableButtonGroup(buttonGroup)
Controllers.addListener(ButtonGroupControllerListener(selectableButtonGroup))
// add a keyboard listener
Gdx.input.inputProcessor = ButtonGroupInputProcessor(stage, selectableButtonGroup)
```
</code></pre>
> 1 votes

# Answer
I looked up in the library source code how do Scene2d Actors understand that they are hovered, and it seems to work this way:

* `Button`: calling internal `ClickListener.isOver()`, which, in fact, checking *over* or *pressed* private members. Member *over* is setted when there is an *InputEvent* with **enter type** (*over* is true) or **exit type** (*over* is false) and **pointer == -1**;
* `SelectBox`: exact same way that `Button` does. Except `SelectBox` itself doesn't have `isOver` method.
* `Slider`: implementing hovering itself, using private *mouseOver* member; It is adding to itself *InputListener* that's observe *InputEvent* hovering the same way that `ClickListener` does, but change the *mouseOver* member instead of *over*.

Other UI elements either inherit from the `Button` (e.g. `CheckBox`), or don't have any hovering detection ability (and so they can't change the appearance when they are hovered).

Knowing that, I can implement `HoverEvent` that can trigger hovering in that limited list of UI elements:

```
class HoverEvent: InputEvent() {
    init {
        type = Type.enter
        pointer = -1
    }
}

```

It is change the appearance of the elements, however to un-hover such element I must manually move mouse to it and then outside of it. Or write some `UnhoverEvent`. This approach, though it seems to me the most correct one, in the end turns out to be inconvenient and in some way impractical.

---

So, as a workaround, I wrote extension function to the `Actor` that move cursor position to `Actor`'s center:

```
fun Actor.moveCursorToIt() {
    val stageCoords = localToStageCoordinates(Vector2())
    val screenCoords = stage.stageToScreenCoordinates(stageCoords)
    Gdx.input.setCursorPosition(
            (screenCoords.x + width / 2).toInt(),
            (screenCoords.y - height / 2).toInt()
    )
}

```
> 0 votes

---
Tags: libgdx, scene2d, kotlin
---


# Question
Title: Do "procedurally generated" skyboxes on the Unity Asset Store use machine learning trained on existing images?
I noticed that some skyboxes on the Unity Asset Store specifically say they use AI image models like Stable Diffusion, for instance "Stylized Space Skybox pack":

The description of this asset says:

> # Created with AI
>
> **AI (Stable Diffusion)** was used to generate elements for the skybox images. The images were then upscaled with AI and edited to fix seams, artifacts, stretch, and vortex elements. Only generic words were used, no media or artist names.

Meanwhile, other skybox assets don't explicitly say AI, but they do say "procedurally generated", for instance "Space & Nebula Skyboxes"

This asset says:

> The Space & Nebula Skyboxes is a collection of 30 **procedurally generated**, high quality skyboxes. The detail of the skyboxes is amazing considering that each cubemap side has 4k resolution.

I know that AI generated images created by models like Stable Diffusion use training from a set of existing images created by real artists in order to create new images. This might potentially lead to some copyright issue if some real artists are not happy that their original images are used in the training set without their permission.

So I want to know whether I can safely use "procedurally generated" skyboxes that don't specify they were made by AI, or if they are produced the same way.

# Answer
> 5 votes
"Procedural generation" is a broad umbrella that can include any technique that produces content through an algorithmic procedure. There's no hard rule that says that *cannot* include machine learning algorithms like AI image models, though most uses of "procedural generation" in game development are not talking about that technique.

For example, Unity has a built-in feature called "procedural skyboxes". This is a shader material that runs the math to simulate Rayleigh scattering of light through particles in the atmosphere for each pixel to calculate what colour should be visible in that direction. That's the "procedure" in "procedural" in this case.

Other conventional ways to procedurally generate skybox images would be to use a 3D rendering package to pseudo-randomly scatter bright points for stars, use noise functions to sculpt fake nebulas or clouds, etc. None of these techniques rely on machine learning training from artist-created images.

However, the terminology around procedural generation and machine learning models is not regulated. It would be possible for an asset creator to use an AI image model to produce assets and then not disclose that in the asset description (even if this would go against any relevant terms of service the shop ostensibly enforces - violations happen).

The only way to know for certain would be to ask the creator of a given asset directly. If they reply back in the negative, you could use record of that communication in defense against liability should anyone later claim that your game used AI in a way it should not have: you show you did your due diligence to establish whether the assets were of AI provenance, and even if the creator/distributor lied to you, that's their fault, not yours.

(I am not a lawyer, and this post is not legal advice. To get proper legal advice, consult an accredited expert in your jurisdiction)

---
Tags: unity, ai, procedural-generation, assets
---


# Question
Title: How to remove loading delay when loading from Appdata? Or to load everything at start?
Currently, when loading from Appdata, there is a noticeable delay. See a sample video here, when it changes from the sprite set in UI to the sprite loaded from Appdata through C# script.

I want to make it so that there is no delay that is visible to the end user. ***If this delay in loading from Appdata is not avoidable***, I'd be fine with loading everything at Start in the background, be it from Appdata or from UnityWebRequest **before it is visible to the end user**. *I would like to know how to do that.*

Currently I am loading the texture from UnityWebRequest and converting it to sprite, if Texture does not already exist in Appdata. Here is the code of the ImageLoader class:

```
public void GenImage(string baseUrl, string imageLin, RawImage rawImag = null, Image imag = null) {
    if(isCoroutineRunning) {
        StopAllCoroutines();
    } else {
        if(rawImag != null) StartCoroutine(LoadImage(rawImag, baseUrl+imageLin));
        if(imag != null) StartCoroutine(LoadImageSprite(imag, baseUrl, imageLin));
    }
}

// **Coroutine class to Load Sprite**
public IEnumerator LoadImageSprite(Image image, string baseUrl, string fileName) {
    isCoroutineRunning = true;
    UnityWebRequest request = UnityWebRequestTexture.GetTexture(baseUrl+fileName);
    yield return request.SendWebRequest();

    if(request.result == UnityWebRequest.Result.ConnectionError ||
        request.result == UnityWebRequest.Result.ProtocolError) {
        Debug.Log(request.error);
    } else {

        Texture2D nTexture = LoadCachedImage(fileName);
        if(nTexture != null) {
            Sprite nSprite = Sprite.Create(nTexture, new Rect(0, 0, nTexture.width, nTexture.height), new Vector2(0.5f, 0.5f));
            image.sprite = nSprite;
        }
        else {
            nTexture = ((DownloadHandlerTexture)request.downloadHandler).texture;
            Debug.Log("else block "+nTexture);
            Sprite nSprite = Sprite.Create(nTexture, new Rect(0, 0, nTexture.width, nTexture.height), new Vector2(0.5f, 0.5f));
            image.sprite = nSprite;
            SaveImage(nTexture, fileName);
        }
    }
    isCoroutineRunning = false;
}

// Save and Load Image
public void SaveImage(Texture2D texture, string fileName) {
    string savePath = Application.persistentDataPath +"/";
    Debug.Log(savePath + " " + fileName);

    try {
        if(!Directory.Exists(savePath)) {
            Directory.CreateDirectory(savePath);
        }
        byte[] textureBytes = texture.EncodeToJPG();
        File.WriteAllBytes(savePath + fileName, textureBytes);
    }
    catch(Exception e) {
        Debug.Log(e.Message);
    }
}

public Texture2D LoadCachedImage(string fileName) {
    string savePath = Application.persistentDataPath + "/";
    try {
        if(File.Exists(savePath + fileName)) {
            Debug.Log("Exists"+savePath+fileName);
            byte[] bytes = File.ReadAllBytes(savePath + fileName);
            Texture2D texture = new Texture2D(0,0);
            texture.LoadImage(bytes);
            return texture;
        }
        return null;
    } catch {
        return null;
    }
}

```

and loading image from a different script:

```
imageLoader.GenImage(baseUrl: ImageLoader.SPRITE_URL, imageLin: "urashiki.jpg", imag:characterIcon);

```

imageLoader has already been called as necessary. There is no error in Console, everything works as expected except the delay.

I understand loading from UnityWebRequest may have a noticeable delay, but I don't understand why loading from Appdata also has a noticeable delay. I would like to know how to avoid that delay, and if not possible, how to hide that delay.

# Answer
> 1 votes
**Edit:**

Your `LoadImageSprite()` function does not make sense to me. It looks like you download the image from the internet, and *then* check if it's cached on the device. You're doing that out of order - **if the image is cached, you don't need to download it**.

So right now, the noticeable delay is probably because you download the image every time.

---

> I don't understand why loading from Appdata also has a noticeable delay

The delay is not caused just by loading the image file from the user's storage drive; Unity also has to decode the JPG, convert the decoded image into a texture format that can be used by the GPU and then upload that texture into the GPU's memory. The amount of time this takes will depend on the player's hardware and the file size and resolution of the image.

> I'd be fine with loading everything at Start in the background, be it from Appdata or from UnityWebRequest before it is visible to the end user. I would like to know how to do that.

We can't give you a precise answer for this if we don't know *when* the image should be visible to the end user.

If the image(s) should be visible to the user as soon as the scene loads, you might consider loading the image(s) synchronously rather than in the background. To do this, simply call the code that loads the image from a `Start()` function in any MonoBehaviour. You might wish to display a loading screen to the user while the image(s) load.

If the image isn't shown to the player immediately, there are various methods you can use to load an image in the background:

1. You could use `File.ReadAllBytesAsync()` instead of `File.ReadAllBytes()`, although you'd then need to make sure you synchronized the loaded bytes into Unity's main thread before you called `texture.LoadImage()`. However, using this approach, there would still be a delay when you called `texture.LoadImage()` as Unity converts the image into a GPU texture format.
2. On some platforms, you can also use `UnityWebRequestTexture.GetTexture()` with the path to the file on the hard drive, using the "file://" protocol (just add "file://" before the image path - for example, "file://c:/folder/image.jpg"). This lets you load the image in the background and monitor its progress with a coroutine. For example:

```
[SerializeField] private Image image;
[SerializeField] private Transform loadingScreen;

void Start() {
    StartCoroutine(LoadImage());
}

IEnumerator LoadImage() {
    using (UnityWebRequest uwr = UnityWebRequestTexture.GetTexture("file://c:/folder/image.jpg"))
    {
        yield return uwr.SendWebRequest();

        if (uwr.result != UnityWebRequest.Result.Success) {
            Debug.Log(uwr.error);
        } else {
            var texture = DownloadHandlerTexture.GetContent(uwr);
            if (texture != null) {
                Sprite nSprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
                image.sprite = nSprite;
                loadingScreen.gameObject.SetActive(false);
            }
        }
    }
}

```

# Answer
> 0 votes
Kicking off the load to run in the background from the moment the scene starts-up is a good idea - that way, often the image will already be available by the time the user wants to see it, and they perceive no loading hitch at all.

But this does present a new problem: what if the player tries to display the image while the load is still in progress, then the load finishes while the empty placeholder for it is still displayed? How do we go find the UI element that *tried* to display the image and provide it the texture after the fact?

I had to solve something similar a while back, so here's the code I wrote for that case. I have not tailored this for your use case, so take this as an example only:

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

// This was set up as an asset file so I could provide some
// "built in" assets through the same interface as downloaded ones.
[CreateAssetMenu(fileName ="ImageCache.Asset", menuName = "Cards/Image Cache")]
public class ImageCache : ScriptableObject
{
    // Using a singleton pattern since I only ever used one cache.
    public static ImageCache Instance { get; private set; }

    // Associating a lookup key with built-in assets.
    [System.Serializable]
    public struct BuiltIn<T> {
        public string name;
        public T asset;
    }

    // Holds a weak reference to an image component that wants to
    // display a sprite that might not yet be loaded.
    struct Request {
        // The weak reference allows the image to be garbage collected
        // if it gets deleted while the load is still pending.
        System.WeakReference<Image> _destination;

        public Request(Image destination) {
            _destination = new System.WeakReference<Image>(destination);
        }

        public static bool IsInvalid(Request request) {
            return !request._destination.TryGetTarget(out Image target);
        }

        public static bool IsNull(Request request) {
            return request._destination == null;
        }

        // Called when the sprite has loaded, to update any requestors.
        public bool TryApply(Sprite sprite) {
            if (_destination.TryGetTarget(out Image target)) {
                target.sprite = sprite;
                return true;
            }
            _destination = null;
            return false;
        }
    }

    // Represents one sprite to be loaded, and cached once loaded.
    class CacheEntry {
        public Sprite sprite;

        // One sprite could be requested by many different display instances.
        public List<Request> uses = new List<Request>();
        int pendingCount;

        // Used to "pre warm" the cache for built-in assets.
        public CacheEntry(Sprite sprite) {
            this.sprite = sprite;
        }

        // Used when an image tries to display an already-cached image.
        // (In case we want to swap all uses of sprite A for sprite B)
        public void RecordUse(Image destination) {
            uses.RemoveAll(Request.IsInvalid);
            uses.Add(new Request(destination));
        }

        // Used when making a new request for a not-yet-loaded image.
        // Returns true if this is the first request.
        public bool EnqueueRequest(Image destination) {
            RecordUse(destination);
            return ++pendingCount == 1;
        }

        // Callback invoked once the asynchronous load finishes.
        public void HandleResult(SanitizedString name, Texture2D texture) {
            Sprite tempSprite;
            if (texture == null) {
                tempSprite = Instance.errorPlaceholder;
            } else {
                // In this case, we needed mipmaps because images were seen in 3D.
                var mipped = new Texture2D(texture.width, texture.height, texture.format, true, false);
                mipped.SetPixels32(texture.GetPixels32());
                mipped.Apply();

                tempSprite = Sprite.Create(mipped, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
                sprite = tempSprite;

                Destroy(texture);
            }

            // Apply the newly-loaded sprite to any outstanding requestors.
            for (int i = 0; i < uses.Count; i++)
                uses[i].TryApply(tempSprite);

            uses.RemoveAll(Request.IsNull);

            pendingCount = 0;
        }
    }

    [SerializeField]
    BuiltIn<Sprite>[] _builtInSprites;

    [SerializeField]
    BuiltIn<TMP_FontAsset>[] _builtInFonts;

    public Sprite downloadPlaceholder;
    public Sprite errorPlaceholder;

    static Dictionary<string, CacheEntry> _cache;

    private void OnEnable() {
        //Debug.Log("Enabling Image Cache.");
        Instance = this;
        if (_cache != null)
            return;

        _cache = new Dictionary<string, CacheEntry>();
        foreach (var builtIn in _builtInSprites) _cache.Add((new SanitizedString(builtIn.name)).value, new CacheEntry(builtIn.asset));

        for (int i = 0; i < _builtInFonts.Length; i++) {
            var font = _builtInFonts[i];
            font.name = font.name.ToLowerInvariant();
            _builtInFonts[i] = font;
        }
    }

    public void Insert(SanitizedString name, Texture2D image) {
        if (!_cache.TryGetValue(name.value, out CacheEntry entry)) {
            //Debug.Log("...creating blank cache entry.");
            entry = new CacheEntry(null);
            _cache.Add(name.value, entry);
        }

        entry.HandleResult(name, image);
    }

    public void RequestImage(Image destination, string name) {

        var sanitized = new SanitizedString(name);

        //Debug.Log("Requesting image " + name);

        if(string.IsNullOrWhiteSpace(sanitized.value)) {
            //Debug.Log("...substituting default sprite.");
            destination.sprite = null;
            return;
        }

        if (!_cache.TryGetValue(sanitized.value, out CacheEntry entry)) {
            //Debug.Log("...creating blank cache entry.");
            entry = new CacheEntry(null);
            _cache.Add(sanitized.value, entry);
        }

        if (!ReferenceEquals(entry.sprite, null)) {
            //Debug.Log("...serving cached image.");
            destination.sprite = entry.sprite;
            entry.RecordUse(destination);
            return;
        }

        destination.sprite = downloadPlaceholder;

        if (entry.EnqueueRequest(destination)) {
            //Debug.Log("...downloading.");
            // Load happens asynchronously in the background, then entry is
            // updated once it's ready.
            NetworkManager.Instance.DownloadTexture(sanitized, entry.HandleResult);
        } else {
            //Debug.Log("...piggybacking on existing download.");
        }
    }

    public bool HasAvailable(SanitizedString file) {
        if (!_cache.TryGetValue(file.value, out CacheEntry entry))
            return false;

        return entry.sprite != null;
    }

    public TMP_FontAsset RequestFont(string name) {
        name = name.Trim().ToLowerInvariant();
        int index = System.Array.FindIndex(_builtInFonts, (e => e.name == name));
        return _builtInFonts[Mathf.Max(0, index)].asset;
    }

    public Sprite FetchSprite(SanitizedString key) {
        return _cache[key.value].sprite;
    }
}

```

---
Tags: unity, c#, unity-ui, loading
---


# Question
Title: How to process tiles of different sizes?
I have next problem. Sprite sheet that I have has sprites of different sizes. I use 16 pixels per unit.
On the screen you can see a choosen tile and that it's height is 14 pixels. I can't resize it manually to 16 pixels as it would overlap a \`car\` sprite.
On the tile palette it results in next problem.

This gap is also in the game. Is it possible to fix it?

# Answer
> 1 votes
It appears like the tiles you have here are partially transparent tiles that are supposed to be placed on a separate layer with full tiles on the layer below them. That way they can be used to create transitions to all kinds of different floor types.

When you have tiles that are smaller or larger than the grid size, then their positioning within the grid is controlled by the **Pivot** setting of the sprite (visible in the lower right of your first screenshot). So you have to change the pivot pivot from "Center" to a custom value so that the position of the pivot point of the tile *would* be the center *if* the tile were actually 16x16. The pivot y-coordinate is measured from the bottom. But your tiles start at the top. So you need to:

1. Change the "Pivot" from "Center" to "Custom"
2. Set "Pivot Unit Mode" to "Pixels"
3. Set "Custom Pivot X" to `grid_width / 2`
4. Set "Custom Pivot Y" to `grid_height / 2 - (grid_height - tile_height)`. In your case, the grid\_height is 16 and the tile\_height is 14. So your pivot would be `16 / 2 - (16 - 14)` = **6**.

With the cars, you might also want to use a "Custom" pivot so you get full control over where exactly the sprites are placed in relation to the tile grid. In that case you can probably eyeball it and drag&drop the blue circle that marks the pivot to where you want the center of the tile to be.

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


title: Camera movement with player

text:
# Question
Title: Camera movement with player
I'm developing a game using the html5 canvas, but I've never used it before and I'm having difficulty creating a camera. The intention is that it is the same as agar.io, where the player is centered in the middle of screen and only the surrounding field is moved, a 3000x3000 field and the player screen that is rendered is only 25x25. I saw several methods of doing this but I ended up getting very confused with so much information. I prefer the method using Canva's translate, but I'm still having trouble being able to make the render. I'll show you how the code is. It's going to be a multiplayer game.

The logic of the game:

```
"use strict"

function createGame() {
  const state = {
    players: {},
    fruits: {},
    screen: {
      width: 25,
      height: 25
    }
  }

  function addPlayer({ playerId, playerX, playerY }) {
    state.players[playerId] = {
      x: playerX,
      y: playerY
    };
  }

  function removePlayer({ playerId }) {
    delete state.players[playerId];
  }

  function addFruit({ fruitId, fruitX, fruitY }) {
    state.fruits[fruitId] = {
      x: fruitX,
      y: fruitY
    };
  }

  function removeFruit({ fruitId }) {
    delete state.fruits[fruitId];
  }

  function checkFruitCollision(playerId) {
    const player = state.players[playerId];
    for (const fruitId in state.fruits) {
      const fruit = state.fruits[fruitId];
      if (player.x === fruit.x && player.y === fruit.y) {
        removeFruit({ fruitId });
      }
    }
  }

  function movePlayer(command) {
    const commandsAccepted = {
      ArrowUp: function(player) {
        if (player.y - 1 >= 0) {
          player.y -= 1;
        }
      },
      ArrowDown: function(player) {
        if (player.y + 1 < state.screen.height) {
          player.y += 1;
        }
      },
      ArrowLeft: function(player) {
        if (player.x - 1 >= 0) {
          player.x -= 1;
        }
      },
      ArrowRight: function(player) {
        if (player.x + 1 < state.screen.width) {
          player.x += 1
        }
      }
    }

    const keyPressed = command.key;
    const playerId = command.playerId;
    const player = state.players[playerId];
    const movingPlayer = commandsAccepted[keyPressed]

    if (player && movingPlayer) {
      movingPlayer(player);
      checkFruitCollision(playerId);
    }
  }

  return {
    state,
    movePlayer,
    addPlayer,
    removePlayer,
    addFruit,
    removeFruit
  }
}

export default createGame;

```

Render logic:

"use strict"

function renderScreen(screen, game, requestAnimationFrame) {
  const ctx = screen.getContext("2d");

  ctx.clearRect(0, 0, screen.width, screen.height);

  for (const playerId in game.state.players) {
    const player = game.state.players[playerId];
    ctx.fillStyle = "#4c7370";
    ctx.fillRect(player.x, player.y, 1, 1);
  }

  for (const fruitId in game.state.fruits) {
    const fruit = game.state.fruits[fruitId];
    ctx.fillStyle = "#90a32a";
    ctx.fillRect(fruit.x, fruit.y, 1, 1);
  }

  requestAnimationFrame(() => renderScreen(screen, game, requestAnimationFrame));
}

export default renderScreen;

```

# Answer
screen can be a reference to a canvas of 3000x3000, and a camera a canvas of 25x25.

Player would move around, and be drawn in screen, and camera would copy from screen and be displayed on the page, camera copies the 25x25 region that is around the player. And screen is an offscreencanvas or otherwise not displayed.
> 0 votes

---
Tags: javascript, html5, html-canvas
---


# Question
Title: How to deal with different version of Direct3D12 interfaces?
Let's say I want to enable debug layers for a Direct3D 12 renderer, for which I need to create a `ID3D12Debug` object. Problem is, there are 6 different version of this: from `ID3D12Debug` and `ID3D12Debug2` all the way to `ID3D12Debug6`. Ideally, I want to enable as many debug facilities as I can.

So, what is the proper way to deal with this? Should I first create `ID3D12Debug`, enable its facilities, and then go down the line (calling each interface's newly added functions), or should I first try to create a `ID3D12Debug6` and call all possible functions on it, unless the creation fails in which case I try to do the same with `ID3D12Debug5`, and so on.

In other words, should I go bottom-up or top-down?

PS. Additionally, is there some resource which lists the minimum supported interface versions for each Windows version? Or should we always start from the very first interface ad climb up from there?

# Answer
> 0 votes
The best option for broad support is to use the DirectX Agility SDK and just make your assumptions on the interfaces supported by the version you used since they ship with your application/game. You still need to handle cases where the functionality doesn't exist due to a lack of support in the current driver, but you can at least count on what interface versions are available.

That said, the specific reason for the interface versions is to support runtime flexibility. You should make your assumptions based on your minimum supported version of Windows 10 which at this point should be build 18362 or later. That's `ID3D12Device6` and later, `ID3D12Debug3` or later, etc. This is why all the DirectX 12 APIs take a IIID in their creation methods to make this easier to do.

Basically it comes down to which functionality you *require* and which functionality you want to *opt-in* if available but run without it otherwise. In particular, you can't count on *any* of the `ID3D12Debug*` interfaces working on a customer system as they only work when the *Graphics Tools* Windows optional feature is installed which is only a thing for developers.

So let's say you want to enable the `ID3D12Debug6` debug feature if it's supported, then you would write:

```
#include <d3d12.h>
#include <client/wrl.h>

using Microsoft::WRL::ComPtr;

...

#if defined(_DEBUG)
    ComPtr<ID3D12Debug> debugController;
    if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(debugController.GetAddressOf()))))
    {
        debugController->EnableDebugLayer();
    }
#endif

ComPtr<ID3D12Device6> device;
HRESULT hr = D3D12CreateDevice(nullptr, D3D_FEATURE_LEVEL_11_0,
        IID_PPV_ARGS(device.ReleaseAndGetAddressOf())
        );
ThrowIfFailed(hr);

#ifndef NDEBUG
    // Configure debug device (if active).
    ComPtr<ID3D12InfoQueue> d3dInfoQueue;
    if (SUCCEEDED(device.As(&d3dInfoQueue)))
    {
    #ifdef _DEBUG
        d3dInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_CORRUPTION, true);
        d3dInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, true);
    #endif
        D3D12_MESSAGE_ID hide[] =
        {
            D3D12_MESSAGE_ID_MAP_INVALID_NULLRANGE,
            D3D12_MESSAGE_ID_UNMAP_INVALID_NULLRANGE,
            // Workarounds for debug layer issues on hybrid-graphics systems
            D3D12_MESSAGE_ID_EXECUTECOMMANDLISTS_WRONGSWAPCHAINBUFFERREFERENCE,
            D3D12_MESSAGE_ID_RESOURCE_BARRIER_MISMATCHING_COMMAND_LIST_TYPE,
        };
        D3D12_INFO_QUEUE_FILTER filter = {};
        filter.DenyList.NumIDs = static_cast<UINT>(std::size(hide));
        filter.DenyList.pIDList = hide;
        d3dInfoQueue->AddStorageFilterEntries(&filter);
    }

    ComPtr<ID3D12Debug6> debug6;
    if (SUCCEEDED(device.As(&debug6)))
    {
        debug6->SetForceLegacyBarrierValidation(TRUE);
    }
#endif

```

See Anatomy of Direct3D 12 Create Device

---
Tags: directx, windows, directx12, win32
---


# Question
Title: How to code glider movement in 2D? (Godot 4)
So in Minecraft, you have the elytra. When you look up, the character moves up. When you look down, the character moves down. The speed you move forward depends on the angle you are moving. I want to do this in 2D.

Let's say that the controls are the following: it's like Learn to Fly where you press left to rotate counter-clockwise and right to rotate clockwise.

I am using a CharacterBody2D in Godot 4. What do I set the velocity to to make this work? I can't just rotate the velocity because the magnitude velocity depends on the angle the player is pointing.

# Answer
> 0 votes
I ended up just rotating the velocity only when the player is pressing a button. If someone else has a better way to do this please let me know

---
Tags: physics, movement, godot, godot-4
---


# Question
Title: BlueprintCallable functions not appearing in Blueprint - UE5
Only just started working with Unreal Engine 5 and I have an issue were my BlueprintCallable functions are not appearing/callable in the blueprint. I dont have the same issue with Unreal Engine 4.

Unchecking/Checking "Context Sensitive" does nothing. I have build the visual studio code in development/deployment/editor, compiled UE and restarted editor, restarted visual studio without any luck. What am I missing for these functions to be available in my blueprint?

# Answer
> 1 votes
Uncheck Live coding if It is checked.

# Answer
> 1 votes
You have to Recompile and reload C++ code by hitting the Recompile button at the bottom of the editor:

# Answer
> 0 votes
Are you making a Blueprint Function Library? If so make sure you declare your functions as static members.

```
UFUNCTION(BlueprintCallable)
static void OpenLobby();

```

---
Tags: blueprints, unreal-5
---


# Question
Title: Random display of a character in Godot 4
I made a character in Godot 4 that enters from one side of the image and exits from the other side, which shows its different modes randomly each time. I have written these codes for it:

```
extends RigidBody2D

@export var min_speed = 150.0
@export var max_speed = 250.0

func _ready():
    $AnimatedSprite2D.playing = true
    var mob_types = $AnimatedSprite2D.frames.get_animation_names()
    $AnimatedSprite2D.animation = mob_types[randi() % mob_types.size()]

func _on_visible_on_screen_notifier_2d_screen_exited():
    queue_free()

```

but when I press the F5 key, it displays this error:

> Invalid set index 'playing'(on base: 'AnimatedSprite2D')with value of type 'bool'.

What is the problem? How should I write the codes?

# Answer
The error is telling you that `AnimatedSprite2D` does not have a `playing` property (to which you are trying assign a `bool`).

The `AnimatedSprite2D` can hold multiple animations, and you are supposed to tell it which one you want to play by calling the `play` method:

```
$AnimatedSprite2D.play(&"NameOfMyAnimation")

```

Or by setting the `animation` property (which are already doing).

Thus, I believe that removing the offending line is sufficient to make your code work.
> 3 votes

---
Tags: godot, random, godot-4
---


# Question
Title: How to get rid of shading seams inside a cylinder?
Is there any other way to remove these shading "seams" other than to increase the vertex count of the cylinder?

# Answer
> 1 votes
There are two ways to fix this:

1. Select *only the faces that you want to smooth*, then select **Face \> Shade Smooth**

2. Enable **Shade Smooth** for *all* faces, then enable **Auto-smooth** to only smooth rounded faces (you may need to adjust the Smooth Angle if the default of 30 degrees does not look right for your model)

---
Tags: unity, graphics, blender
---


# Question
Title: Correct overloads for SpriteBatch.Draw to flip sprite horizontally
I want to flip my sprite horizontally while drawing and I can't figure out how to use the correct parameters without either an error or a warning about the method being obsolete.

This is what I assume it would be:

```
sb.Draw(NumbersGame.Arrow, resolutionRightArrow, Color.White,
SpriteEffects.FlipHorizontally);

```

Except it comes up for errors for the color (cannot convert from color to rectangle) and the `SpriteEffects` bit (cannot convert from sprite effects to rectangle).

What is the correct way to lay out these arguments?

P.S: When I provide all the default values (says it's obsolete):

```
sb.Draw(NumbersGame.Arrow, resolutionRightArrow, null, null, null, 0f, null,
Color.White, SpriteEffects.FlipHorizontally);

```

# Answer
The obsolete function signatures have been removed.

There are only two complete `Draw` functions in monogame(all of the others fill in the missing parameters and call one of these two), one uses a destination `Rectangle` the other a `Vector2` position.

The only difference between the two is in the way the scaling techniques are applied:

The `destinationRectangle` size is calculated against the source rectangle size. Resulting in two division operations per call.

The `position` variant takes a `Vector2` position and a `Vector2` scale parameter.

Either way don't forget to subtract the `origin` from the position to get the top-left point.

## The Destination Rectangle Overload

```
public void Draw(Texture2D texture,
    Rectangle destinationRectangle,
    Rectangle? sourceRectangle,
    Color color,
    float rotation,
    Vector2 origin,
    SpriteEffects effects,
    float layerDepth)

```

**texture** \- The Texture2D object to be drawn.

**destinationRectangle** \- The drawing bounds on screen. Scales to the width and height of the given rectangle.The position of the rectangle is the top left - the origin parameter.

**sourceRectangle** \- An optional region on the texture which will be rendered. If null - draws full texture.

**color** \- A value multiplied to each of the final pixels; RGBA clamped to 0-1. This can only darken colors, or increase transparency.

**rotation** \- A rotation of this sprite in radians.

**origin** \- Center of the rotation. 0,0 by default. A

**effects** \- FlipHorizontal or FlipVertical. Can be combined with `|`.

**layerDepth** \- A depth of the layer of this sprite. Order that the sprite is drawn. Can be any value. This value is used as the Z coordinate for the drawn quad.

## The Vector2 Position Overload

```
public void Draw (Texture2D texture,
                Vector2 position,
                Rectangle? sourceRectangle,
                Color color,
                float rotation,
                Vector2 origin,
                Vector2 scale,
                SpriteEffects effects,
                float layerDepth)

```

**texture** \- The Texture2D object to be drawn.

**position** \- The Top Left corner - the origin parameter.

**sourceRectangle** \- An optional region on the texture which will be rendered. If null - draws full texture.

**color** \- A value multiplied to each of the final pixels; RGBA clamped to 0-1. This can only darken colors, or increase transparency.

**rotation** \- A rotation of this sprite in radians.

**origin** \- Center of the rotation. 0,0 by default.

**scale** \- The size scaling of the `sourceRectangle` size values.

**effects** \- FlipHorizontal or FlipVertical. Can be combined with `|`.

**layerDepth** \- A depth of the layer of this sprite. Order that the sprite is drawn. Can be any value. This value is used as the Z coordinate for the drawn quad.
> 1 votes

# Answer
Have you tried this overload?

```
public void Draw(Texture2D texture, Rectangle destinationRectangle, Rectangle? sourceRectangle, Color color, float rotation, Vector2 origin, SpriteEffects effects, float layerDepth);

```
> 0 votes

---
Tags: c#, 2d, sprites, monogame, scale
---


title: Character overlaps with static objects

text:
# Question
Title: Character overlaps with static objects
I am creating a simple OpenGL C++ game. I have a main character (green box) and some static objects (red boxes) positioned as stairs.

The problem is as green box is descending down the stairs, it overlaps with the edges of red boxes. You can see in the gif that bottom right of green box intersects with top left of red boxes.

It's not the same with Unity. If the character collides, it rotates giving a much more natural feel.

`Character.cpp` (Dynamic Object)

```
m_Position = glm::vec2(800.0f, 800.0f);
m_Rotation = 45.0f;
m_Scale = 50.0f;

b2BodyDef def;
def.type = b2_dynamicBody;
def.position.Set(Util::PixelToMeter(m_Position.x), Util::PixelToMeter(m_Position.y));

m_Body = m_PhysicsWorld.CreateBody(&def);

b2PolygonShape shape;
shape.SetAsBox(Util::PixelToMeter(m_Scale / 2.0f), Util::PixelToMeter(m_Scale / 2.0f));

b2Fixture* fixture = m_Body->CreateFixture(&shape, 1.0f);
fixture->SetFriction(0.3f);

```

And then on `onRender`:

```
const auto& newPosition = m_Body->GetPosition();
m_Position.x = Util::MeterToPixel(newPosition.x);
m_Position.y = Util::MeterToPixel(newPosition.y);
m_Rotation = m_Body->GetAngle();

```

`Wall.cpp` (Static Object)

```
m_Position = glm::vec2(position.x, position.y);
m_Rotation = 0.0f;
m_Scale = 50.0f;

b2BodyDef def;
def.type = b2_staticBody;
def.position.Set(Util::PixelToMeter(m_Position.x), Util::PixelToMeter(m_Position.y));

m_Body = m_PhysicsWorld.CreateBody(&def);

b2PolygonShape shape;
shape.SetAsBox(Util::PixelToMeter(m_Scale / 2.0f), Util::PixelToMeter(m_Scale / 2.0f));

m_Body->CreateFixture(&shape, 0.0f);

```

This is my repository: https://github.com/axelthat/OpenGLBox2D

Physics world is created here: https://github.com/axelthat/OpenGLBox2D/blob/main/SuperMarioBrosClone/src/Game.cpp

Red box: https://github.com/axelthat/OpenGLBox2D/blob/main/SuperMarioBrosClone/src/Wall.cpp

Green box: https://github.com/axelthat/OpenGLBox2D/blob/main/SuperMarioBrosClone/src/Character.cpp

What am I doing wrong?

# Answer
The main problem is the drawn rotation in degrees does not match the simulated body's rotation in radians.

Your initial rotation of 45 is never applied to the body, so it is falling flat.

> Box2D uses radians for angles. Ref 1

Your renderer draw code expects degrees:

```
glm::radians(rotation)

```

You are sending it an angle in radians in `OnRender`:

```
m_Rotation = m_Body->GetAngle();

```

I understand that degrees are easier to work with, but radians have a lot of beneficial properties in Trigonometry, and are the only angular "unit" used by computer operations and matrices.

In Unity3D and Unreal Engine, any angles entered into the widgets are converted then stored and used in radians.

If I may suggest your code do the same(it will save a lot of multiplications in the long run):

```
m_RenderData.shader->SetMatrix4(
        "u_Model",
        glm::translate(glm::mat4(1.0f), { position.x, position.y, 0.0f }) *
        glm::rotate(glm::mat4(1.0f), rotation, { 0.0f, 0.0f, 1.0f }) *
        glm::scale(glm::mat4(1.0f), { scale, scale, 0.0f })
    );

```

---

The collision between the Character and Wall have zero friction since the wall fixture has no friction. This is evidenced by the slow horizontal movement that should not exist at all(see below for the explanation of the leftward movement.)

> So if one fixture has zero friction then the contact will have zero friction. Ref 2

The change the last line of `Wall.cpp` given as above to:

```
b2Fixture* fixture = m_Body->CreateFixture(&shape, 1.0f); // density is irrelevant on static bodies
fixture->SetFriction(0.3f);

```

Once you fix the friction, you will notice your box no longer slides and falls off of the ledge.

The leftward movement was a result of the iterative and precision limits of the torque calculations combined with a zero friction calculation.(a very small amount(near zero) of the torque moment was applied to the overhang in your code causing the linear sliding effect)

Near Zero and +/- Infinity inside of physics simulations tends to blow up the internal calculations(hence the unneeded 1 in the density field). Luckily Box2D does provide limits.

---

You must move the center of mass to the left so it is over the edge of the step. Your animation shows it landing flat.

There are three other considerations:

1. Gravity - Unit dependent(lower on your image than the Unity version)
2. Angular dampening - needs to be small but above 0 to stabilize the calculations
3. Restitution - a tiny, think 3-30 * double.epsilon, value will allow the simulation space to rotate in the next frame more smoothly without secondary collisions during the iterative process.
> 3 votes

---
Tags: opengl, c++, physics, box2d
---