# Question
Title: Why does my 2D + 2.5D implementation look weird?
I am thinking about this for a very long time but I couldn't figure it out.

I have to rotate my character 360 degrees, and because of that, I have to use a top-down perspective like in Hotline Miami. Also, I want to have an environment like Undertale's top-down perspective (2.5D).

My problem is that my implementation looks weird and I'm concerned that will negatively affect its playability, mechanics and review scores.

Here are a few screenshots of how it looks:

Here's a short video clip of the game.

Note: I took the character from Hotline Miami.

What can I do to fix this? Does this seem like it will cause problems later with respect to mechanics & playability? Are there better ways to mix 2D & 2.5D?

If the media that I provided are not representative enough, please tell me how can I spot the problem & improve my question.

# Answer
> 4 votes
The problem is the perspective mismatch between the character and the environment. It is very obvious that they are seen at different angles, which confuses the spatial perception of the viewer.

What you could do is to also show the game world exactly from the top down, like in Hotline Miami:

This is IMO a really underrated perspective for action-adventures. It's easy to create art assets, gives the player a really good view because no objects are in the way and allows you to rotate things without having to re-draw the sprite for each angle.

But the main problem is that it does not show anything of vertical surfaces like walls. One solution to this problem is to display the world in the "fake-3d" perspective used in the indoor areas of NES Zelda (ignore the sprites, which also have a perspective mismatch - it would probably look better with top-down sprites):

# Answer
> 4 votes
Firstly, don't rip graphics or IP in general from other games. Even doing this as filler can be problematic as you're going to need to go back through your game later on & check your content to make sure you're not infringing. As mentioned in the other answer, the inconsistency between the art style of the character and the other art assets makes the character look out of place (yet another reason not to rip assets).

Regarding your game, one problem that I noticed immediately is that the shadows are inconsistent. I've marked up your second screenshot to draw attention to a few problem spots:

The biggest error I see is illustrated by the arrows. The shadow on the sign is cast in one direction while the shadow of the character is cast in a somewhat opposing direction. The shadow for the tree appear to be cast straight back. If the sign & character were on opposing sides of an obvious light source, it would make sense that their shadows would go in different directions. But there's nothing in the scene that accounts for this. At best it comes across as weird and at worst it comes across as looking like an obvious error &/or a lack of quality control.

This may also negatively affect gameplay & mechanics. In a 2.5D game, a player is going to be relying heavily on shadows to determine depth. Inconsistent shadows can make this unnecessarily difficult and frustrating. Unless that's an intentional design choice (i.e. a game with a Lovecraftian theme involving unnatural geometries), it's likely to be a liability in terms of how players perceive, review & rate your game.

The character's shadow 'fighting' with the scene shadows is even more noticeable in the video. It looks like the shadow for your character is generated dynamically by the game engine whereas the shadows on the sign & tree appear to be part of the sprites. Assuming that's the case, a couple of things are required to fix things:

* Make sure your sprites are consistently shaded. Usually sprites within an asset pack are consistent with themselves, but be especially attentive when mixing assets from different sources.
* Generally speaking, you should fix the lighting on your character so that its shadow doesn't change in angle or oppose other shadows. If it is going to change, make sure it makes sense with respect to obvious light sources.

A somewhat different shadow problem is in the dashed line area. There's an odd square bit of shadow cast on part of the wall that I can't visually account for. I can't tell if it's from some occluded art asset, some other error, or if it's hinting at something in the scene that is hidden from view but it looks out of place to me.

# Answer
> 3 votes
It has been done before, games like the early GTA titles used to be top-down with 360 directions in a 3D-like environment. Although the camera angle showed both environment and character in one angle.

Although for your situation, then 'The Legend of Zelda: A Link Between Worlds' also comes to mind, where the environment is 3D and the character can move around in 360 degrees. But they've created an illusion to view the character's body and the sides of the cliffs by tilting them all sideways, while the world's mechanics are actually top-down, like this:

So, it looks weird because the character and environment have different camera angles. One way to rework it is to show the character's body so it blends better with its environment, similar to 'A Link between Worlds'. (Although such change may need sprite work in each direction to keep the 360 aim.)

Another way is to actually keep the character top-down as is, I think it's a fresh take on the genre, but consider the interactable objects accordingly. (Enemies, obstacles, items etc.)

---
Tags: game-design, game-mechanics, assets, pixel
---


# Question
Title: A problem of sampling _CameraOpaqueTexture in Unity 2020.3
I'm using URP 10.6 and I found a wired problem. I use following code to sample the `_CameraDepthTexture`

```
float2 screenUV = input.positionCS.xy * rcp(_ScreenParams.xy);
half4 col = SAMPLE_TEXTURE2D(_CameraDepthTexture, sampler_ScreenTextures_linear_clamp, screenUV)

```

The `input.positionCS` is from `o.positionCS = TransformObjectToHClip(v.positionOS)` in vertex shader.

Then everything goes well. However, when I try to sample the `_CameraOpaqueTexture` with the same uv, everything goes wrong. There is nothing showing by using following code

```
float2 screenUV = input.positionCS.xy * rcp(_ScreenParams.xy);
half4 col = SAMPLE_TEXTURE2D(_CameraOpaqueTexture, sampler_CameraOpaqueTexture_linear_clamp, screenUV)

```

After long time searching, I realise that I need to use this snippet to make it work.

```
float2 screenUV = input.positionCS.xy * rcp(_ScreenParams.xy);
screenUV = screenUV * 0.5 + 0.5;
half4 col = SAMPLE_TEXTURE2D(_CameraOpaqueTexture, sampler_CameraOpaqueTexture_linear_clamp, screenUV)

```

Why must I do `screenUV = screenUV * 0.5 + 0.5` before sampling `_CameraOpaqueTexture` while sampling `_CameraDepthTexture` doesn't need it?

# Answer
The reason you need to adjust the screenUV coordinates by multiplying by 0.5 and adding 0.5 when sampling the \_CameraOpaqueTexture is related to the texture coordinate conventions used in Unity's Universal Render Pipeline (URP).

In URP, the \_CameraDepthTexture follows a normalized device coordinate (NDC) convention where the texture coordinates range from -1 to 1. Therefore, when sampling the depth texture, you can directly use the screenUV values as they are.

On the other hand, the \_CameraOpaqueTexture follows a convention where the texture coordinates range from 0 to 1. In order to map the screenUV values to this texture coordinate range, you need to apply a transformation by multiplying by 0.5 and adding 0.5. This transformation scales and shifts the coordinates from the NDC range (-1 to 1) to the texture coordinate range (0 to 1), allowing proper sampling of the opaque texture.

Therefore, the adjustment of screenUV by screenUV = screenUV * 0.5 + 0.5 before sampling the \_CameraOpaqueTexture is necessary to correctly map the NDC coordinates to the texture coordinate space used by the opaque texture in URP.

Source: Unity Doc on Cameras and depth textures
> 0 votes

---
Tags: unity, shaders, unity-urp
---


title: how to load all players once?

text:
# Question
Title: how to load all players once?
In tera online when you enter a battleground or go into a city with hub with hundreds of players all in one place, The game has to download the faces, hairstyles... armors and weapons of every single player... and the players that are not downloaded look like T posing Black untextured manequins.

so to avoid the same problem, since each of my players has like a lot of hairtyle sets, weapon and armor sets and 30 face sets + eyes...well... it gets easily in the 100'000 vertexes in total per player which can take quite a while to download.

and no, calling and deleting pieces of the players as scenes is not an option :/, all assets are into one file and are turned visible/invisible when the player wears their respective items.

# Answer
Art assets should be client-sided, not server-sided.

The 3d meshes and textures of those "hairtyle sets, weapon and armor sets and 30 face sets + eyes" should all be bundled with the client. When a new character comes onto the screen of a client, then the server only tells that client the ID number of each of those assets. So communicating the whole visual appearance of a character only takes a few bytes of network traffic.

However, some loading time on the client might not be completely avoidable. As your library of character parts grows over the course of development, you will soon run out of RAM / VRAM to keep all those textures and meshes permanently in memory. At that point it becomes necessary to load those from the file system whenever a character with a previously unloaded art asset comes onto the screen. To optimize those loading times it can be useful to have each of those assets as an own file, or if you want to use some archive format to bundle assets, choose one that can unpack individual files without having to unpack the whole archive.

But loading assets from files will still take time. So if you don't want the game to hang while loading and parsing all those files, you will have to temporarily represent characters with placeholder assets while the actual art assets load in the background.

> and no, calling and deleting pieces of the players as scenes is not an option :/, all assets are into one file and are turned visible/invisible when the player wears their respective items.

Well, then you should revise your architecture to **make** it an option. Your approach might work while you still have a low number of variations. But when you get into the thousands of character art assets (which isn't even that much for an MMORPG), you will experience a very long initial load time of the game, and a while later you will start losing players because after an update their computers no longer have enough memory to keep all the new art assets loaded.
> 2 votes

---
Tags: 3d, multiplayer, godot, opengl-es2, rpg
---


# Question
Title: Best practice for getting references to specific child objects in Unity
When structuring the script to control a game object with several generations of children underneath, I gather from one of Jason Weimann's videos that it's a bad idea to use the string based methods to get your references like `transform.Find("objectName")` because those names could change and break things.

So what's the best way to do it? I'd prefer not to have to wire everything up via the inspector. I guess you can use `GetChild()` but then you run the risk of breaking it a different way if that index ever changes.

As an example, I currently have a custom UI slider prefab that is a game object containing several child game objects, which in turn have components or subchildren with components such as text and shapes (from the Shapes plugin), which move dynamically during interaction and therefore need their own local transforms. There is also a raw image to catch interactions.

The whole thing is controlled by a script on the root game object, so it needs references to all the children to set their position / values / colors etc.

The dependencies are all in the master script, none of the sub components know about the master script, their parameters get set by it.

Currently I have it set up to reference via things like `transform.Find("child1").Find("child2").gameObject.GetComponent<>....`

Is that the best way in this case? Would it be better to refactor so each component has its own script and just referenced the master script?

One thing I don't think I made clear:

This isn't a regular slider that sets the parameters of shapes, it is its self a new stylable UI element I've created that replaces Unity's standard slider, and is built out of `Shape` and `TextMeshPro` assets.

There aren't any testable rules about which object should be referenced, the variable for the "Outline thickness" will always need to link to that parameter on a particular Shape component a few levels down the hierarchy.

Maybe in this case just using names and making sure they don't get changed is fine?

# Answer
> There aren't any testable rules about which object should be referenced

If you can't state a rule for the computer to follow, then there's no way to automate this. You will have to manually specify which child object/component to use for each reference.

That means your options are:

1. Give distinct names to each child you need to access, and look them up with `transform.Find("name here")` as you describe.

This has the problem you mentioned that changing the names or making a typo anywhere could cause the script to break. That makes this approach very brittle - especially if you ever need to spawn objects dynamically or have multiple copies of certain items. For this reason, I strongly recommend avoiding name-based lookups whenever you can.
2. Navigate to children by order in hierarchy, using `transform.GetChild(index_here)`. As you note, this has similar problems, where now just re-ordering children could cause the script to break, and it will be even less clear why because the script is full of magic number index values that don't give good clues which object they were supposed to find.
3. **Use Inspector references.** I know you've said:

> I'd prefer not to have to wire everything up via the inspector

But it really is worth doing just that. Some advantages you get:

* References are robust against name or hierarchy changes.
    * They're deserialized efficiently on the loading thread, so they don't contribute to an initial hitch when loading a scene (which you can get if lots of scripts are running search routines to find their references on the first frame).
    * They require less code, and less work overall - you would literally spend longer typing up an equivalent code snippet to assign the reference in `Start/Awake` than it would take to just drag the right reference in via the UI.

So if you want a "best practice" for assigning references that don't have a stable identifying characteristic you can just search for, wiring up those references in the inspector at edit time is far and away the best way to go.

---

There is one halfway approach you could take, if you really want to avoid the UI:

```
[SerializeField, HideInInspector] TextMeshPro _someText;

// This could go in a static utility class if you like.
bool TryGetChildComponent<T>(Transform child, out T reference) where T:Component {
    if (child != null)
        return child.TryGetComponent(out reference);

    reference = null;
    return false;
}

#if UNITY_EDITOR
// OnValidate is called in Editor only,
// after the component is added or changed, or on assembly reload.
void OnValidate() {
    if (_someText == null)
        if (!TryGetChildComponent(transform.Find("Container")?.Find("Label"), out _someText))
            Debug.LogWarning($"{name} could not find child path 'Container -> Label' - make sure you've named your child elements correctly.");

    // Repeat for each reference you need to wire up.
}

// Adds context menu option to un-wire and re-wire references.
[ContextMenu("Reset References")]
void ResetReferences() {
    // Ensure changes are tracked, saved, serialized.
    UnityEditor.Undo.RecordObject(this, "Reset References");

    _someText = null;
    // Repeat for each reference you need to clear.

    OnValidate();
}
#endif

```

This gives you a compromise between options 1 and 3:

* Yes, the references are stringly typed, but the name is used only once at edit time to assign the reference. If the child later changes its name, the reference is not broken.
* The references are assigned automatically, without cluttering the Inspector view for the component.
* If a reference is missing, you get a warning at edit time, rather than waiting until runtime to find out.
* At runtime, the reference is deserialized cheaply on the loading thread, just like in option 3.
> 1 votes

# Answer
In addition to the methods in the answer by DMGregory I would like to offer a 4th alternative: `GetComponentInChildren<SomeDistinctComponent>()`.

In most cases, the reason why you want a specific child object is because it has a specific component you want to interact with. So by using `GetComponentInChildren` you can find that component on the first child that has it. In case you actually need the game object that component is on and not just the component itself, you can obtain that through the `.gameObject` property you have on every component.

Sometimes you might have multiple child-objects with the component in question. For that case there is also `GetComponentsInChildren` (plural) which gets you an array of all the components in the children of that object. You can then examine those components and the rest of their gameObjects to find out which one you want to interact with. Or interact with all of them, if that's what you want to do:

```
foreach(var thingDoer in GetComponentsInChildren<ThingDoer>()) {
    thingDoer.DoTheThing();
}

```

Oh, and by the way, the whole `GetComponent*` family of methods also works with interfaces. When you have multiple components that implement the same interface, then you can use this method to get all of them.
> 1 votes

# Answer
There are a few ways you can do this, with different impact on performance, and different ease of use. You haven't specified ***why*** you want to avoid setting them in the inspector, so it's hard to say if the solution offered will be better for you. Still, here are a couple that may work.

Option 1: Create a component that specifies what type of child this is (ChildTagger in my example below), add it to each of the children you want to reference to, then use GetComponentsInChildren to iterate these children and assign them each according to their tag. Changing hierarchy and object names will not break this as long as you keep this component and tags.

```
public class ChildTagger : MonoBehaviour {
    public string myTag;
}

public class MyClass : MonoBehaviour {
    private Transform circle;
    private Transform triangle;

    private void Awake() {
        foreach (ChildTagger child in gameObject.GetComponentsInChildren<ChildTagger>()) {
            switch (child.myTag) {
                case "circle":
                    this.circle = child.transform;
                    break;
                case "triangle":
                    this.triangle = child.transform;
                    break;
                default:
                    Debug.LogError("Unhandled child tag: " + child.myTag);
                    break;
            }
        }
    }
}

```

Option 2: Iterate the full child hierarchy and search for object by name. This is similar to the transform.find that you used in your example above, but it will not be dependant on the child's exact position in the hierarchy, whether it is a direct child or grandchild. It will, however, take longer to run, so don't use this if you plan to run this code many times per frame.

```
public class MyClass : MonoBehaviour {
    private Transform circle;
    private Transform triangle;

    private void Awake() {
        void IterateTransform(Transform t) {
            // Check if this object is one that we need to assign
            switch (t.name) {
                case "circle":
                    this.circle = t;
                    break;
                case "triangle":
                    this.triangle = t;
                    break;
            }

            // Iterate child objects
            for (int i = 0; i < t.childCount; i++) {
                IterateTransform(t.GetChild(i));
            }
        }
    }
}

```

Last note, if you use this search methods for convenience, so you don't have to manually assign in the inspector, I would still recommend allowing for the options to assign in the inspector, and letting your component know that it should skip the search in such cases. That would allow much better performance in cases where it matters (by using the inspector), but still allow for convenience in cases where performance is not an issue.
> 0 votes

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


title: Don't know what to work on next

text:
# Question
Title: Don't know what to work on next
I'm currently working on a 2D platformer, and I have no idea what to add next. I've created the code for the player, the animations for the player(just the player for now so that I don't get burnt out), basic player functionality, and I'm just completely dumbfounded on what to do next. Of course I have big plans, including story, cutscenes, the rest of the graphics, level design, etc., but I just feel like I need to continue more of the basics and the "basics" doesn't feel like it's completed yet for me to move forward. I feel like there's a bridge between working on the big things and small things in this game, and I don't want to just jump forward and start working on story or level design when the fundamentals might not even be finished. Sorry if this is all a bit rambly by the way.

# Answer
> 5 votes
I would focus on making one example/ showcase scene that contains everything that you envision later to be in your game.

That way you can test all elements of your game, see if they are working as they should, need tweeking or if something crucial is missing. This gives you as well a small piece that you can give others for a first feedback or if you just want to show it to other people.

* A story line can be broken down in a single interaction with one npc to test if your dialog system is working.
* That npc might give a kill or fetch quest
* You already have the animations done for your player, maybe adding a simple one for one enemy to test combat.
* Placing skill checks in your game. If you have a double jump, having a pit that can only cleared by a double jump. Wall jump. Dash test. Whatever your game has to offer.

This demo scene can later be used as part of a tutorial as well. All your big plans are later build on top of it.

You know the basic is done when it is working in your example scene. You can do a double jump? Don't second guess your code. If it works, it is good enough to focus on the next thing in the list. No code is ever fully finished, perfectly written, can't be in one or three ways be refactored or otherway adjusted. Focus on bringing functionality to it and move to the next basic block once one is done.

If you are done with what makes your game your game, you build on top of these building blocks with story, levels, graphic improvement and everything else. If you have a great idea, just write it down so you don't forget it later.

# Answer
> 1 votes
My first priority in every game project I participate in is to create a minimum viable product (MVP). An MVP is the simplest, quickest and dirtiest possible implementation of your game which can be playtested and deliver you useful data.

The MVP for a platformer would be a simple test level with the player being able to jump and run. If you want to create a platformer in this day and age which actually sells, then you also need some unique gimmick. If you do have such an unique gimmick in mind as a core part of your game idea, then it should also be part of the MVP to prove that the concept works. If you don't, then don't worry. You will certainly come up with *something* over the course of the next months.

The MVP doesn't need to be pretty or interesting. It just needs to demonstrate the core mechanic of your game.

Now you can test your core mechanic. You can find out if it even works the way you pictured it and if it is fun to play. You might have to tweak it a bit to get good "game-feel". That is particularly important in a platformer, because the way the character jumps and runs will affect every single level, obstacle and mechanic you add later. That means it can get really expensive to make changes to the character's moveset at a later point in the development process. For example, when you later find out that the game would be more fun if the player's jump would be 10 pixels shorter, then you need to revise every single level you already created to make sure it's still solvable. You really don't want that, so take your time with your test level and make sure you got the basic player controls exactly the way you want them.

With that, you created a solid foundation you can build on. Now you can, for example:

* Add enemies and other hazards
* Add special abilities
* Create actual levels
* Create special objects within levels that interact in fun(?) ways with the character's abilities
* Work on your art assets so your ugly test level with those ugly placeholder characters gets closer to the final look you want the game to have
* Add juice like sound effects or particles

Which one do you start with? Well, which one do you *want* to start with? At this point of development, you still have total freedom what you want to tackle first. Try any of the above things, playtest the result, and then decide if you want to keep, revise or discard the thing you just added.

---
Tags: game-design, game-mechanics
---


# Question
Title: I want to have a light/lampshade hanging from a cable component, but when running the level the mesh and light fall to the ground
Here's a screenshot illustrating my setup:

There is a cable component with attach start, want toand the cable itself swings fine. However I want to attach the cone to the floating end of the cable. I attempted to do this by adding a socket to the mesh:

As per the first pic I completed the "Attach End To" of the cable component, setting the Referenced Actor and Attach to Socket properties to my lampshade mesh and socket.

What am I doing wrong?

# Answer
> 0 votes
I think I've fixed it.

I had the lamp shade as the parent of the group, not the cable component. I reorganised it like this:

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


# Question
Title: how to move a mesh to be the child of another node?
if i import an item directly unto a bone attachment for some reason it becomes so small it is invisible even tho the bone attachment has a scale of 1 to 1 and was never re-sized

also the rotation is wrong, even the bone attachment has a rotation of 0-0-0 always.

and the items I'm importing are always 0-0-0 and 1-1-1, they have no animation data, no animation player and were never attached to any armor ever.

but if i import the same thing as a child of any other node and then move it under the bone attachment, the size remains normal.

i tried to do that in code for a weapon system, and it always gives me an error saying that the item is already the child of a node and can't be moved.

so is there a way to do it?

# Answer
> 2 votes
> error saying that the item is already the child of a node and can't be moved

The node can have only one parent. If you added it to a parent already (with `add_child`), you would have to remove it (with `remove_child`) to be able to add it to a different one.

For example:

```
node.get_parent().remove_child(node)
new_parent.add_child(node)

```

---

However, keeping the transform is another thing, you would want to save it:

```
var saved_transform := node.global_transform
node.get_parent().remove_child(node)
new_parent.add_child(node)
node.global_transform = saved_transform

```

---

You might be able to discard the scale (and also any shear) instead:

```
var saved_basis := node.global_transform.basis
node.global_transform.basis = Basis(saved_basis.get_rotation_quat())

```

*The above code should work unless the scale is zero, at which point getting the rotation fails.*

---

> if i import an item directly unto a bone attachment for some reason it becomes so small it is invisible even tho the bone attachment has a scale of 1 to 1 and was never re-sized

You must have introduced this scaling. The most common case is that the original character was 100 bigger, so you reduce the size in Godot. If you can make the character model it the correct size before importing it (e.g. in blender) that should prevent this trouble.

---

On the other hand, if you know the scale, you can compensate for it, for example:

```
node.global_transform.basis = node.global_transform.basis.scaled(
    Vector3(100.0, 100.0, 100.0)
)

```

---

**Addendum**: If the `Basis` is all wrong, we could reset that:

```
node.global_transform.basis = Basis.IDENTITY

```

---
Tags: 3d, godot, rpg, scale, bones
---


# Question
Title: How do tween librarys in Unity update tweens?
I am trying create a small lerp helper script that basically allows me to do something like a small tween with a extension or static method (So I can call it from my other scripts easily like you can do with tween libraries). I know how to do a simple lerp for this with an corutin or in Update, but I don't understand how to make it work with extension or static methods because I can't really use corutines or update there.

EDIT:

With the help of answer bellow I ended Up solving this with async await. Which I can confirm worked in WebGl in this example (I think that is because I didn't run it on a new thread) Here is my code:

```
    public static async void LerpPositionXAsync(this Transform target, float endPosition, float duration)
    {
        float elapsedTime = 0;
        float startPossitionX = target.localPosition.x;

        while (elapsedTime < duration)
        {
            elapsedTime += Time.deltaTime;
            target.localPosition = new Vector3(Mathf.Lerp(startPossitionX, endPosition, elapsedTime / duration),
                target.localPosition.y);

            await Task.Yield();
        }

        //Makes sure possition is correct after animation
        target.localPosition = new Vector3(endPosition,
                target.localPosition.y);

        await Task.Yield();
    }

```

**Note that I am lerping a float value here and not Vector3 but it works the same.**

**UPDATE**

Since I posted this question I have learned that Task.Delay() specifically doesn't work with WebGl so you you should probably be fine if you don't use that or you don't start any tasks. However in Unity 2023 (Not sure for the older ones) they added Awaitable class for the async workflow that works similar to the coroutine and it is supported by WebGl so if you are thinking about using async with WebGl I would recommend that.

# Answer
**Two options:**

1. You can pass in a Monobehaviour to the static / extension to perform the coroutine or update. Something similar to a functionTimer that CodeMonkey makes in this video. Except his way is to instantiate a monobehavior gameObject, where as in your case, you can inject in by the caller when caller is a monobehaviour.
2. You can use async/awaits that is from c#. Or better yet use Unitask which is async/await integration for Unity.

**Addition Note**

If you are targeting WebGL build, async and Unitask is not supported. So you will be stuck with using coroutine. I later thought of the way of not having to inject monobehaviour in it since the caller is usually a MonoBehaviour, so your extension just have to be an IEnumerator. Here's an example code on how it could be done:

```
using UnityEngine;

public static class LerpHelper
{
    public static IEnumerator LerpPosition(this Transform transform, Vector3 targetPosition, float duration)
    {
        float elapsedTime = 0f;
        Vector3 startPosition = transform.position;

        while (elapsedTime < duration)
        {
            elapsedTime += Time.deltaTime;
            float t = Mathf.Clamp01(elapsedTime / duration);
            transform.position = Vector3.Lerp(startPosition, targetPosition, t);
            yield return null;
        }

        transform.position = targetPosition;
    }
}

public class ExampleCaller : MonoBehaviour
{
    [SerializeField] private Transform targetTransform;
    [SerializeField] private Vector3 targetPosition;
    [SerializeField] private float duration = 1f;

    private void Start()
    {
        // Example usage of the LerpPosition extension method
        StartCoroutine(targetTransform.LerpPosition(targetPosition, duration));
    }
}

```
> 1 votes

---
Tags: unity, lerp, tweening
---


# Question
Title: Material going to oposite side in procedural mesh creation
Tried to instantiate this gameobject procedurally, material texture went to the other side:

```
public class tileCreator: MonoBehaviour
{
    public int tileSize = 1;

    public Material tileMaterial;

        void Start(){

        GameObject tileObject = new GameObject("Tile");

        MeshFilter meshFilter = tileObject.AddComponent<MeshFilter>();

        MeshRenderer meshRenderer = tileObject.AddComponent<MeshRenderer>();

        MeshCollider meshCollider = tileObject.AddComponent<MeshCollider>();

        Mesh tileMesh = new Mesh();

        Vector3[] vertices = new Vector3[4]
        {
            new Vector3(0f, 0f, 0f),
            new Vector3(tileSize, 0f, 0f),
            new Vector3(tileSize, 0f, tileSize),
            new Vector3(0f, 0f, tileSize)
        };

        int[] triangles = new int[6] { 0, 1, 2, 0, 2, 3 };

        Vector2[] uv = new Vector2[4]
        {
            new Vector2(0f, 0f),
            new Vector2(1f, 0f),
            new Vector2(1f, 1f),
            new Vector2(0f, 1f)
        };

        tileMesh.vertices = vertices;
        tileMesh.triangles = triangles;
        tileMesh.uv = uv;

        tileMesh.RecalculateNormals();

        meshFilter.mesh = tileMesh;
        meshRenderer.material = tileMaterial;

        tileObject.transform.localScale = new Vector3(tileSize, 0.01f, tileSize);
        tileObject.transform.position = new Vector3(x * tileSize, 0f, z * tileSize);

        meshCollider.sharedMesh = tileMesh;
        meshCollider.convex = true;
       }
}

```

Without Rotation:

180 Degrees:

# Answer
> 1 votes
When creating a mesh from code, it is important to know that you need to display them in clockwise (CW) in order for the triangles to face the camera. If you put them in counter clock wise (CCW), they will face away from the camera.

So, in your line of code :

```
int[] triangles = new int[6] { 0, 1, 2, 0, 2, 3 };

```

Just change it to

```
int[] triangles = new int[6] { 0, 2, 1, 0, 3, 2 };

```

---
Tags: unity, c#, 3d-meshes, mesh
---


# Question
Title: When to use InverseTransformDirection in Unity
I want to know when to use **InverseTransformDirection**. Unity documentation says : "Transforms a direction from world space to local space". Honestly, it is not clear for me.

I came across this piece of script for multilevel turret. "Barrels" is a child of "turretBase" and Barrels must face the target. I don't really undestand this script beacuse of **InverseTransformDirection**.

```
    private void RotateBarrelsToFaceTarget(Vector3 targetPosition)
    {
        Vector3 localTargetPos = turretBase.InverseTransformDirection(targetPosition -
        barrels.position);
        Vector3 flattenedVecForBarrels = Vector3.ProjectOnPlane(localTargetPos, Vector3.up);
        ...
    }

```

# Answer
> 1 votes
The InverseTransformDirection function is used to convert the target direction from world space to the local space. Which in your code the "turretBase" transform, enabling the correct calculation of the rotation needed for the "Barrels" to face the target within its local coordinate system.

Perhaps another way to understand this by trying out this code:

```
public class TestCode : MonoBehaviour
{
    public Transform playerTransform;

    private void Update()
    {
        // Get the input direction in world space
        Vector3 inputDirection = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));

        // Convert the input direction to local space of the player
        Vector3 localDirection = playerTransform.InverseTransformDirection(inputDirection);

        // Use the local direction for player movement
        // or
        Debug.Log(localDirection);
    }
}

```

---
Tags: unity, rotation, movement, vector, transformation
---


# Question
Title: Rectangular shape NavMeshAgent for Unity?
I have an issue with the tank character. The Unity's navmesh agent only has a cylinder shape, so when the enemies are nearby, it causes unwanted results. If the navmesh is too big(to cover the entire tank body), the enemies can't approach the side of the vehicle. If the navmesh is too small(only covering the center), the enemies pass through the front of the car and back. Putting the collider doesn't make any changes, the unity's navmesh agent ignores whether it has a collider. How do I make navmeshagent shape fit the mesh?

# Answer
> 0 votes
You can try:

1. Modify the NavMeshAgent's radius: The NavMeshAgent has a "Radius" property that determines the size of the agent's navigation cylinder. You can adjust this value to better match the size of your tank mesh. Increase the radius if the enemies need to approach the tank from the sides, or decrease it if you want more precise collision detection.
2. Use multiple NavMeshAgent components: Instead of relying on a single NavMeshAgent for the entire tank, you can attach multiple smaller NavMeshAgent components to different parts of the tank, such as the front, sides, and back. This way, each agent can have a smaller radius and navigate more accurately around the tank's specific shape.
3. Employ additional colliders: While the NavMeshAgent doesn't directly interact with colliders, you can add separate colliders to the tank, such as box colliders or mesh colliders, that cover the entire tank's body. These colliders can be used to detect collisions with enemies and trigger appropriate actions or behaviors.
4. Combine navigation with custom steering behaviors: Instead of relying solely on the NavMeshAgent for enemy movement, you can combine it with custom steering behaviors, such as obstacle avoidance or path following. By implementing these behaviors, you can provide more precise control over enemy movement around the tank and ensure they navigate according to your desired rules.

---
Tags: unity, navmesh
---


# Question
Title: In Unity, switching mesh on skinnedMeshRenderer works in editor but not in build
I got this very annoying bug, since it's only related to build and I'm wondering why that bug does not appear in editor. I'm trying to switch the mesh that SkinnedMeshRenderer displays with another similar one, it works as expected in editor. Here's a short video of the working version in editor. https://www.youtube.com/watch?v=Xm1Fw9bgCRc

When trying to do the same thing on Build, I get this weird bug where the skinnedMeshRenderer seems to stop working when switching mesh.

Instead of having the mesh following properly the character, it just hang above it. See the picture below :

When building, I get a few warning and exceptions, I don't know if it's related and if it is, I don't know how to solve those. :

# Answer
I think the target device can't handle the shader that you are using. Try use a different material with the unity default shader and see if this bug still occurs
> 0 votes

---
Tags: unity, mesh, bug
---


# Question
Title: How to correctly position a set of cuboids based on a direction property in MonoGame
I am trying to create a map for my game using a list of cuboid sections that are defined like this:

```
[{
    Position: new Vector3(0, 0, 0),
    Size: new Vector3(6f, 100f, 0.1f),
    Direction = Vector3.Forward
 },
 {
    Size: new Vector3(6f, 100f, 0.1f),
    Direction = Vector3.Right
 },
 {
    Size: new Vector3(6f, 100f, 0.1f),
    Direction = Vector3.Right
 },
 {
    Size: new Vector3(6f, 100f, 0.1f),
    Direction = Vector3.Left
 }]

```

Note that only the first section has a position coordinate. After enumerating these values I am aiming to end up with a map that looks like this.

I've gotten as far as this code which solves some of the problem, but I can't wrap my head around how to get it to work taking into account the prior cubes orientation.

```
var v = new Vector3((0.5f * (x1 - x2)) + priorSection.Position.Value.X, 0, (-0.5f * (y1 + y2)) + priorSection.Position.Value.Z);

```

I am stuck. The problem that I run into is that the concept of left and right is relative to the orientation of the prior section of the map and I can't work out how to calculate the coordinates of each section based on the orientation and position of the prior section.

Can anyone please help?

# Answer
> 0 votes
1. Adding vectors geometrically 'concatenates' them, lays them end-to-end.
2. Rotating the rectangle simply swaps the x and y values, so a vertical rectangle of size {6f, 100f} becomes horizontal rectangle of size {100f, 6f}.

*Assuming down is negative values of Y (if not, simply negate the Y value)*

The top right corner of the first rectangle is the centroid plus half the size, so {0f + 3f, 0f - 50f} = {3f, -50f}. The bottom left corner of the second rectangle (the only one touching the first one) is {3f, -50f + 6f} = {3f, -44f}. This shifting factor is determined by its being aligned to the top of the last rectangle. So, the centroid (center point) of the second rectangle is simply this plus half the rotated size of the second rectangle: {3f + 50f, -44f - 3f} = **{53f, -47f}**

So, the centroid of each next rectangle is half of the rotated size of the previous rectangle plus a shifting factor and plus half of its own rotated size.

---
Tags: monogame, geometry, orientation, position
---


# Question
Title: I want add a piece of code where the game checks if the players velocity along the Y axis is under a certain number
The piece of code I want to write is where the game will check if the player is colliding with anything it will check this by looking at your y vector3 is under a certain number (its like this cause the gravity and collisions overall is a bit wonky) like if the players vector3 is under (0.0f, 1.0f, 0.0f) then the game will call that line of code again if you're above that vector3 it will not call it again. My main problem trying solve this is telling unity who to check for which I'm not to sure how to do it. Whenever I do try to implement it all I get is errors sometimes I get really close but I'm unable to implement it due to some issues within the if statements.

As stated before I never was able to get implement I'll update things if I do figure it out on my own.

# Answer
```
if (Player.velocity.y < 0.01f)
{
   // do thing
}

```
> 0 votes

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


# Question
Title: How to carry other players and NPCs and Objects?
In my game you don't have inventory slots, you can hold two things if your player has 2 arms and so on, you can hold more things if you equip a bags on your belt or backpacks... and you can carry even more things if you buy a horse or a carriage or even a ship to sail the waters while trying to avoid other players or pirates... carrying stuff is very much a great part of the game.

and you can also carry npcs or your fallen or injured teammates.

so I was thinking of methods to do this, is this as simple as taking the model of a player/npc/object and adding it as a child of the carrying player and apply to the carried thing the animation loop that constantly plays the pose ''carried" ?

I'm asking becase yesterday i wasted like 3 hours assuming something was easy and basic only to find out it is incredibly stressful.

# Answer
> 1 votes
This can be coded exactly like an inventory system, but limited to 2 items and animated to show the item being carried.

An inventory is just an array of items. Here's some C# pseudo code:

```
Class Inventory
{
    Item[] inventory {get; set;}

    Inventory() //empty inventory
    {
        inventory = new[2];
        inventory[0] = new();
        inventory[1] = new();
    }

    void AddItem(Item item)
    {
        if (inventory[0] == null)
        {
            inventory[0] = item;
        }
        else if (inventory[1] == null)
        {
            inventory[1] = item;
        }
        else
        {
            Console.log = "Maximum carrying capacity already reached."
        }
    }
}

```

---
Tags: 3d, movement, multiplayer, rpg, godot-3
---


# Question
Title: Switching states within conditional statements in C#
In the usual `Update()` of a state (let's call it `Attack` for simplicity) of an object state manager `unit` called there's a conditional statement:

```
if (Condition a)
{
//do something
SwitchState(unit.anotherState)
//then do something else
}

```

What I don't understand is why, after switching states, `then do something else` continues execution? Clearly it should terminate execution of `Attack` and switch to `anotherState`. So why doesn't it happen?

# Answer
Using your example but filling in what is happening

```
public class Class : Monobehaviour
{

    private int state = 0;

    private void Update()
    {

        if (Condition a)
        {
            //do something
            SwitchState(unit.anotherState)
            //then do something else
        }

    }

    private void SwitchState(int new_state)
    {

        state = new_state;

    }
}

```

The execution order is:

```
1. Update()
2. ->  if (Condition a)
3.     ->  //do something; state = 0;
4.         SwitchState(unit.anotherState)
5.         ->  state = new_state;
           <-
6.         //then do something else; state = unit.anotherState
       <-
   <-

```

Then on re-entering this Update() again, `Condition a` is most likely still the same but `state != 0`. This is an assumption and in coding `->` never assume anything.

---

Besides, this is a class not a state. Also this does make me think you ought to use switches rather then if-statements. No answer/comment here will change though. Reconsideration of your example will have a learning function as you call `unit` a statemachine, I tend to think `SwitchState` belongs in `unit`. As the statemachine is responsible for state-handling. Narrow all your code to the responsible class, it will help you not to repeat your code too.

---

When `SwitchState(...)` can fail to change the state, consideration of returning `true` on success of `false` on fail would create the ability to put the call into an if-statement to execute it's scope or not. Like:

```
if(!SwitchState(unit.anotherState)
{
    ...
}

```

If it will always change the state, code afterwards shouldn't be added when it doesn't suppose to be executed. In case of code after the if-statement should be executed, adding a `return` in the scope of the if-statement or an `else` will be your friends, so when the `Condition a` is not met, that scope is skipped and the code after it will be executed.

```
private void Update()
{

    if (Condition a)
    {

        //do something
        SwitchState(unit.anotherState);
        return;

    } // else

    if (Condition b)
    {
        //do something
    }

}

```
> 1 votes

# Answer
Because `SwitchState(unit.anotherState)` is a method. And when the method has finished, the program execution continues after the method-call.

If you don't want that, add a `return;` statement after the method call. This will finish the current method and return execution to the scope it was called from.
> 0 votes

# Answer
I’m going to rewrite your code using different names. And highlight why you would WANT this to work the way it does

```
if (Condition a)
{
    //do something
    SwitchState(unit.anotherState)
    //then do something else
}

if (Condition applesOnSale)
{

    OpenBasket();

    SwitchPeaches(to.Apples);

    RecaclulateTotalPrice();
}

```

If we want to recalculate our price after we’ve made a switch, we want to make sure that our code completes with all lines running. It wouldn’t make sense to skip that line, since we haven’t reached the closing } yet. Nothing from this code suggests that that line should be skipped.

I think what might be confusing you is that your switch method “shifts control” to the other class. But once that happens and completes it comes back and finishes this function.

We would never want the price recalculation to be skipped after we switch to apples. It’s just another step that occurs after the switch is complete!
> 0 votes

---
Tags: unity, c#, state, fsm
---


# Question
Title: How to calculate shadow position below arcing projectile in Isometric 2d tilebased grid?
I have an Isometric 2D grid-based tilemap, and am firing a projectile (at **Vector P1** in image below) from the player (at **Vector A**) to a location "above" a target location (at **Vector B**). This works mostly fine (see animation gif at bottom of post).

**How can I calculate the location of a shadow sprite? I've tried several usages of dot products and projections but I can't figure out what I am doing wrong. How do I project a location from the projectile arc position **P1** down onto the AB line?**

The shadow should always be located along the line **AB**:

This is the closest I've gotten in the below animation:

Here is some of the code for the above animation:

```
private void Update()
{
    // ... other code for moving the flare sprite

    var A = new Vector2(_castFromLocation.x, _castFromLocation.y);
    var B = new Vector2(_hoverOverLocation.x, _hoverOverLocation.y);
    var P1 = new Vector2(_flare.transform.position.x, _flare.transform.position.y);

    var AB_ = B - A;
    var AP1_ = P1 - A;

    var dotProduct = Vector2.Dot(AB_, AP1_);
    var distanceAlongAB = dotProduct / AP1_.magnitude;

    _shadow.transform.position = Vector3.Lerp(_castFromLocation, _hoverOverLocation, distanceAlongAB);
}

```

# Answer
Here's a simple, scalable solution. There are several prerequisites to be clarified:

1. For the oblique throwing motion, it can be decomposed into the uniform linear motion of the x-axis and the vertical upward throwing motion of the y-axis.
2. The shadow is moving in a straight line with uniform speed.
3. The object is directly above the shadow, and the height conforms to the quadratic function, and the height is 0 at the start and end.

So we can **draw the shadow first**, and then draw the object through the position of the shadow, which is simpler.

```
private const float MOVE_DURATION = 2f;
private float moveTimeLeft = 0f;
private Vector3 from;
private Vector3 to;

private void Update()
{
    ...
    if(moveTimeLeft<=0) return;
    moveTimeLeft -= Time.deltaTime;
    var moveRate = 1 - moveTimeLeft/MOVE_DURATION;
    var shadowPosition = Vector3.Lerp(from, to, moveRate);
    _shadow.transform.position = shadowPosition;
}
public void StartMove(Vector3 fromSet, Vector3 toSet)
{
    from = fromSet;
    to = toSet;
    moveTimeLeft = MOVE_DURATION;
}

```

Here we assume that the moving time is fixed, and the shadow moves to the end at a constant speed according to this time.

Then let's deal with the height of the object, here we introduce a "normalized" quadratic function: $$ y=-\left(2x-1\right)^{2}+1 $$

It looks like this:

When x represents the rate of movement, we can use it to calculate the height of the object.

```
private const float MOVE_DURATION = 2f;
private const float HIGHEST_HEIGHT= 2f;
private float moveTimeLeft = 0f;
private Vector3 from;
private Vector3 to;

private void Update()
{
    ...
    if(moveTimeLeft<=0) return;
    moveTimeLeft -= Time.deltaTime;
    var moveRate = 1 - moveTimeLeft/MOVE_DURATION;
    var shadowPosition = Vector3.Lerp(from, to, moveRate);
    _shadow.transform.position = shadowPosition;

    var height = − Mathf.Pow(2*moveRate−1,2) + 1;
    _flare.transform.position = shadowPosition + Vector3.up * height * HIGHEST_HEIGHT;
}
public void StartMove(Vector3 fromSet, Vector3 toSet)
{
    from = fromSet;
    to = toSet;
    moveTimeLeft = MOVE_DURATION;
}

```

Because the game is not the real world, you can draw the trajectory according to the effect you want. Here are some examples:

1. The shadow has a constant speed:

```
private const float shadowSpeed = 2f;
private float moveTimeMax = 0f;
private float moveTimeLeft = 0f;
public void StartMove(Vector3 fromSet, Vector3 toSet)
{
    from = fromSet;
    to = toSet;
    var distance = Vector3.Distance(from,to);
    moveTimeMax = distance / shadowSpeed;
    moveTimeLeft = moveTimeMax;
}

```
2. The maximum height of the object varies with the launch distance:

```
private float highestHeight = 0f;
private void Update()
{
    ...
    _flare.transform.position = shadowPosition + Vector3.up * height * highestHeight;
    ...
}
public void StartMove(Vector3 fromSet, Vector3 toSet)
{
    ...
    highestHeight = distance/2;
    ...
}

```
3. Objects are always launched at a 45 degree angle:

```
public void StartMove(Vector3 fromSet, Vector3 toSet)
{
    ...
    highestHeight = distance/4;
    ...
}

```

In general, if we give up the accurate calculation of physics such as gravity acceleration and velocity, things will be much simpler. We can directly give a motion curve and scale it.
> 0 votes

# Answer
Simply copy the x,y (but not height z) coords of the projectile.

Copy the terrain height z at this x,y coordinate.

In 3D space, your shadow is at x,y,z.

Project this using orthogonal projection to screen space X,Y.

In your terrain code, make sure you have a way to get the discrete grid X,Y given a 3D vector's x,y, and get the height given this X,Y coord, and translate that height into 3D amount (to scale).

Here's some pseudo code:

```
float x = _flare.transform.position.X;
float y = _flare.transform.position.Y;
float z = _terrain.GetHeight((int)x, int(y));

_shadow.transform.position = new Vector3(x, y, z);

```
> 0 votes

---
Tags: unity, tilemap, isometric, grid, linear-algebra
---


# Question
Title: How to launch a soccer ball on a parabolic path in a 2.5D game?
I am trying to make simple 2D soccer game in Unity, but I feel a top-down view in such simple games isn't as exciting as the pseudo-3D view in games like Kunio Kun Nekketsu Soccer League.

I am trying to understand how to implement a similar pseudo-3D effect:

1. The players move along the x (left and right) and y axis (the upper and lower part of the field), but they can jump in z axis.
2. The kicked ball moves in the x, y axis (because it opposes the force of gravity), but also z, when, for example, we pass from one wing to the other.

How can all this be mathematically realized in a 2D game? A ball kicked in a platform game would only move in a parabola on the x and y axes, but *here* there's a z axis and things get complicated.

Moreover, look at the second picture. The goal line is at a slight angle to the Z axis (so the Y axis is in fact at a slight angle to the Z axis). But, in the second picture you can see that in the middle part of the pitch, the Y and Z axes are parallel to each other.

# Answer
> 0 votes
If I were to do this, I would seperate the problem into 2 parts:

**Visual part** : when the ball is kicked (just a `rigidbody2D.AddForce`) to mid-air, turn on the shadow prefab of the ball (just a black version of the sprite and elongated to look like a shadow). During the trajectory movement of the ball, the shadow copy and uses the x pos value of the ball, while y pos remain unchanged.

**Physic Interaction**: In your Ball script, create a float zHeight to mimic the height movement if it were on a z axis. Like this : . Then you use the zHeight value to control and affect any physic interaction and sorting order. For example, when the zHeight is over a half the length of the character sprite height (meaning its above waist) turn off the the interaction by setting it to airborne layer (use layer cuz you can't turn off rigidbody during the trajectory unless you want to write your own projectile code), and then set it back to ground layer when zHeight falls below waist. Note that:

```
zHeight = Ball.transform.position.y - yOffset;

```

And yOffset is the y position when the ball is kicked.

---
Tags: unity, c#, graphic-effects, projectile-physics, 2.5d
---


# Question
Title: Unprojecting screen space to world space stops working when camera not at origin
I'm trying to implement screen space to world space in my engine to allow object selection in editor. I understand that the process should essentially be the reverse of projection. So to go from world space to screen space, I would do `ModelMatrix * ViewMatrix * ProjectionMatrix * Point`. So to go from screen space to world space I should be able to do `Point * (ProjectionMatrix * ViewMatrix * ModelMatrix)^-1`. I've been assuming that the `ModelMatrix` should always be the identity matrix.

The code I have works perfectly when the camera is at the origin, but when I start moving the camera around, the further away from the origin it gets, the more incorrect the results become. I should note that `m_currentCamera->GetViewMatrix()` flips the z axis so the camera is looking at +Z instead of negative Z, and also inverts the camera transform matrix as necessary to convert to camera space.

```
glm::mat4 projection_matrix = glm::perspective(glm::radians(60.), (double)g_width / (double)g_height, (double)0.1, (double)10000);
projection_matrix[1][1] *= -1;

glm::mat4 view_matrix = m_currentCamera->GetViewMatrix();

// Cast mouse position from screen space to world space
POINT mouse_position = InputState::GetMousePosition();

float mouse_x = mouse_position.x;
float mouse_y = mouse_position.y;

// Convert from screen space to Vulkan NDC space
mouse_x = (2.f * (mouse_x / (float)g_width)) - 1.f;
mouse_y = (2.f * (mouse_y / (float)g_height)) - 1.f;

glm::vec4 screen_space_mouse = glm::vec4(mouse_x, mouse_y, 0.f,  1);

glm::mat4 pv =  projection_matrix * view_matrix;
screen_space_mouse =  glm::inverse(pv) * screen_space_mouse;

screen_space_mouse /= screen_space_mouse.w;
m_world_space_mouse = screen_space_mouse;

```

What am I missing? The behavior is a little strange, when the camera is in the -Z, the ray ends up pointing behind the camera. I've done a ton of research on screen space unproject and I can't see a difference in what I'm seeing online vs what my code is doing.

# Answer
> 0 votes
Well I figured it out. The screen space mouse needed to be at z of 1 like this:

```
glm::vec4 screen_space_mouse = glm::vec4(mouse_x, mouse_y, 1.f,  1);

```

I thought I had tried at z of 1 but I must have missed that case in my testing.

---
Tags: mathematics, glm, vulkan
---


# Question
Title: Recommended approach to image rendering on quads for OpenGL-backed canvas
I am working on a vector graphics rendering library for OpenGL in Rust. Currently, the library's API is as follows:

```
let mut canvas = Canvas::new();
canvas.set_background(Color(1.0, 1.0, 1.0));
canvas.add_rect(-0.5, 0.0, 0.8, 0.5, Color(1.0, 0.0, 0.0));
canvas.add_polygon(0.0, 0.0, 0.3, 6, Color(1.0, 0.0, 1.0));
canvas.add_rect(0.1, 0.3, 0.4, 0.3, Color(0.0, 1.0, 0.0));
canvas.add_circle(0.0, -0.2, 0.2, Color(0.0, 1.0, 1.0));

```

Internally, `canvas` is represented as an array of shapes, each of which is composed of multiple vertices:

```
#[derive(Debug)]
struct Canvas {
    points: Vec<Vec<[f32; 5]>>,
    background: Color
}

```

When a drawing command is issued for the canvas, internally, the library draws the shape as a set of connected triangles. Each vertex in each triangle is composed of an `(x, y)` position and a `(r, g, b)` color. For example, for drawing rectangles:

```
fn add_rect(&mut self, x: f32, y: f32, w: f32, h: f32, fill: Color) {
    // 6 vertices to make up 2 triangles that are part of rectangle
    let p1 = [x + w, y, fill.0, fill.1, fill.2]; // top right
    let p2 = [x + w, y + h, fill.0, fill.1, fill.2]; // bottom right
    let p3 = [x, y, fill.0, fill.1, fill.2]; // top left
    let p4 = [x + w, y + h, fill.0, fill.1, fill.2]; // bottom right
    let p5 = [x, y + h, fill.0, fill.1, fill.2]; // bottom left
    let p6 = [x, y, fill.0, fill.1, fill.2]; // top left
    let rect = vec![p1, p2, p3, p4, p5, p6];
    self.add_shape(rect);
}

```

When drawing is completed, rendering is conducted by flattening the shapes array into a single 1D array of vertices, which are then sent to OpenGL to be rendered. This approach works reasonably well for just rendering 2D shapes. However, I would like to introduce rendering textured quads for eventual text rendering.

An approach I have thought of so far is to add two texture coordinate `(u, v)` values to the vertices of the quad, so each vertex would be composed of the following:

```
let vertex = [x, y, r, g, b, u, v];

```

However, requiring texture coordinates for shapes that don't even need textures seems redundant, and if texture coordinates were required for every object, textures would be incredibly badly distorted as they would be warped to fit every shape. Clearly, this approach does not work.

What would the approach to doing this form of rendering that would best interoperate with the existing system I have devised?

# Answer
> 1 votes
Most general-purpose 3D/GPU rendering systems have a concept of “material”. A material is a definition of how surfaces should appear, separate from the shape of the object that has those surfaces. Or, we can say that it is information about the object that is conveyed *separately* from the vertices. (Exactly what information makes up a material depends on what the renderer supports.)

So, in your case we could say have multiple materials:

* Vertex-colored only
* Texture #1
* Texture #2
* ...

Each material has different information which must be conveyed to the GPU (in a basic OpenGL application, using uniforms), and therefore it is generally desirable to **group vertices by the material they use**. In your application, this means you might as well separate the colored vertices from the textured vertices and give them a different layout.

```
#[derive(Debug)]
struct Canvas {
    colored_verts: Vec<Vec<ColorVertex>>,
    textured_verts: Vec<Vec<TexVertex>>,
    background: Color
}

#[repr(C)]
#[derive(Debug)]
struct ColorVertex {
    position: [f32; 2],
    color: [f32; 3],
}

#[repr(C)]
#[derive(Debug)]
struct TexVertex {
    position: [f32; 2],
    texcoord: [f32; 2],
}

```

(Rust-specific note: the `#[repr(C)]` guarantees straightforward in-order layout for the two `struct`s, so that they will each be laid out just like a `[f32; N]` would be and are suitable for use in vertex buffers.)

You'll specify different attribute layouts for your two materials, since one has 5 floats and the other has 4.

---

Another common option, instead of having multiple vertex layouts, is to have a single vertex layout with all properties, as you thought of — `[x, y, r, g, b, u, v]`. In your fragment shader, multiply the color from the vertex with the color from the texture. Then, for your colored vertices, select a texture which has just 1 white texel, and for your textured vertices, make the color white (or some other color to “tint” the texture). This means that your materials only differ by choice of texture, so your code is more straightforward, and you can tint the textures (e.g. for colored text). However, these vertices occupy more memory.

A weirder option is to select the type of information per-vertex: for example, by storing either `[r, g, b]` or `[-1, u, v]` in the same 3 floats. Since color components are never negative (unless you are doing special wide-gamut color processing), the shader can tell which is which and decide whether to use a texture or not.

---

However, even if you choose one of those two alternatives, you'll still need to break up vertices into groups if you want those groups to be rendered with *different textures* rather than just reasons of a single texture.

---
Tags: opengl, rendering, graphics-programming
---


# Question
Title: BasisParser returns undefined from loading KTX2 file with custom extension
I get 'undefined' from the BasisParser that I use from Pixi itself, when loading a KTX2 file with a custom extension (through Assets.load):

```
import { TranscoderWorker } from '@pixi/basis';
import { loadKTX2 } from '../loaders/PixiLoadKTX2'; // Custom extension
...

constructor() {
    Pixi.extensions.add(loadKTX2);
    TranscoderWorker.loadTranscoder(window.location.origin + '/basis_transcoder.js', window.location.origin + '/basis_transcoder.wasm');
}

public async create(filename: string): Promise<void> {
    const texture = (await Assets.load(filename)) as Pixi.Texture;
    const sprite = new Pixi.Sprite(texture);

    ...
}

```

My extension code is based on the loadBasis extension from Pixi itself. I also use KTX-Parse to read the ktx2 file from which (I think) I use the basis data to transcode it to an usable Pixi texture:

```
import { read } from 'ktx-parse';
...

const response = await settings.ADAPTER.fetch(url);
const arrayBuffer = await response.arrayBuffer();
const ktxBuffer = concat([arrayBuffer]);
const ktxContainer = read(ktxBuffer);  // KTX-Parse read function

let textures: Texture<Resource>[] = [];
await new Promise<void>((res) => {
    ktxContainer.levels.forEach(async (level, index) => {
        const resources = await BasisParser.transcode(level.levelData); // Pixi basis transcoding
    const type: TYPES = BASIS_FORMAT_TO_TYPE[resources.basisFormat];
    const format: FORMATS = resources.basisFormat !== BASIS_FORMATS.cTFRGBA32 ? FORMATS.RGB : FORMATS.RGBA;

    textures = textures.concat(
        resources.map((resource) => {
            const base = new BaseTexture(resource, {
                mipmap: resource instanceof CompressedTextureResource && resource.levels > 1 ? MIPMAP_MODES.ON_MANUAL : MIPMAP_MODES.OFF,
                alphaMode: ALPHA_MODES.NO_PREMULTIPLIED_ALPHA,
                type,
                format,
                ...asset.data,
            });
            return createTexture(base, loader, url);
        })
    );

...

```

But I get 'undefined' in my 'resources' object when transcoding the basis data. When I look further into the BasisParser code in my node-modules and add some logs to debug, I see that it stops at the worker trying to transcodeAsync():

```
...
await worker.initAsync();
// ---- Stops here
const response = await worker.transcodeAsync(new Uint8Array(arrayBuffer), _BasisParser.defaultRGBAFormat.basisFormat, _BasisParser.defaultRGBFormat.basisFormat);
// ----
const basisFormat = response.basisFormat;
const imageArray = response.imageArray;
const fallbackMode = basisFormat > 12;
...

```

The error:

`tslib.es6.js:74 Uncaught (in promise) undefined`

KTX2 Container is not (yet) implemented into pixi, that is why I'm searching for a way to get it loaded into a pixi sprite. To be sure you get enough information: I used KTXSoftware's toktx tool to create a KTX2 file from a png.
I tried these commands and have loaded them all in:

```
ETC1S
.\toktx.exe --t2 --encode etc1s --clevel 5 --qlevel 255 book.ktx2 book.png
ASTC
.\toktx.exe --t2 --encode uastc --uastc_quality 4 book.ktx2 book.png
UASTC
.\toktx.exe --t2 --encode astc --astc_blk_d 4x4 --astc_quality 100 book.ktx2 book.png

```

That's where I'm stuck at the moment. I don't know if I use the BasisParser or even the KTX2 data correctly? I use the latest Pixi V7.

# Answer
> 0 votes
I have implemented the KTX2 container in Pixi.js myself and I might ask for permission to contribute this to the project. But I first want to test some more and make sure the code is good enough. Proof that it worked.

---
Tags: textures, webgl, compression, pixi.js, typescript
---


# Question
Title: How to create persona pieces for Minecraft Bedrock?
I'm learning addons creation for Minecraft Bedrock. I learned about the creation of resource packs and behaviour packs, following some tutorials like the ones provided by FoxyNoTail.

Now I want to create pieces for character creator, like the ones in the screenshots below. I searched everywhere for docs/tutorials on this subject, and found nothing.

I see there are items divided in *Body* and *Style* sections, each with their own subsections. I digged through the documentations at bedrock.dev and Microsoft sites, but couldn't find anything.

I also searched the game data files, where there are some `manifest.json` files with modules of type `persona_piece`, but this type of module is not documented anywhere.

I believe it must be in a resource pack, is it right? If it is so, how should the `manifest.json` file be structured?

Any hints? Thanks in advance!

# Answer
> 3 votes
I posted an issue at Minecraft Creator repository about this question. The answer is that, to be able to create persona pieces, one must be participant of the Minecraft Partner Program. There's documentation on the subject, but its access is restricted to partners.

To apply to the program, it's needed to develop and provide a portfolio of high quality content created and shared with the community (maps, realms, addons, skins, hosted servers).

So, I don't think it's possible for beginners to create persona pieces, at least not right now.

# Answer
> 0 votes
You could just make a resource pack then activate that in the global resource but that is very complex and you would need to make models animation if you want some very complex. You can start by make a model of you want to make then you can make the texture then put the model where you want it to be on the player then last you could add some animations this could easily be done on blockbench

---
Tags: minecraft-modding, minecraft-bedrock-modding
---


# Question
Title: Getting looping music to work in Roblox Studio
I've been trying for a few days now to get my background music to work on one of my Roblox places, but every time I get the error:

*13:50:23.806 - Players.PungentZeus0.PlayerGui.bgmusic:21: attempt to index global 'Sound' (a nil value)*

Here's the code:

```
local ContentProvider = game:GetService("ContentProvider")

local pageTurnId = "rbxassetid://144585389"

local sound = Instance.new("Sound")
sound.SoundId = pageTurnId

local assets = { sound }

ContentProvider:PreloadAsync(assets)

print("All assets loaded.")

local sound = Instance.new("Sound", game.Workspace)
sound.SoundId = "rbxassetid://144585389"

if not sound.IsLoaded then
    sound.Loaded:wait()
end

Sound:Play()

```

# Answer
> 1 votes
It turns out that I simply forgot to put the whole command:

```
Workspace.Sound:Play()

```

It now works as expected.

# Answer
> 0 votes
You Didn't need to make an entire script, you could've just went to properties and click the looping button.

---
Tags: music, roblox
---


# Question
Title: How do you clone a part to the Player in Roblox?
I have been making a game in Roblox, But I had one problem.

I wanted to make a debug GUI that one can use to spawn items at the Player Location, but I do not really know how to copy it to the player location.

If anyone is willing to help me fix this problem, I would appreciate that - a ton.

# Answer
You could use the Archivable property of the player's character (which's false by default) and set it to true, then call Character:Clone() to clone the character, set the property back to false, do what you need to do with the clone and done, you have a clone.
> 0 votes

---
Tags: lua, roblox
---


# Question
Title: Iterating through every pixel in a shader - skipping pixels
I made the below shader to draw a mesh for every pixel on a texture, and color it with that pixel.

It iterates through the pixels, correctly drawing and coloring the mesh instances. However it skips about 10% of them. Can anyone see something wrong with the shader?

The missing ones mean some pixels on the texture are being skipped, so my `xTexLoc` and `yTexLoc` values are probably doing the math wrong.

```
   //The texture size is externally supplied in the properties because WebGL 2.0 (OpenGL ES 3.0 / #pragma target 3.0`) doesn't have `Texture2d.GetDimensions()`.
   _texSize("TextureSize", Int) = 256
        ...
        CGPROGRAM
        #pragma target 3.0
        #pragma vertex vert
        #pragma fragment frag
        #pragma multi_compile_instancing

        float _drawScale;

        int _texSize;
        sampler2D _PosColorTex;

        // vertex shader inputs
        struct appdata
        {
            float4 vertex : POSITION; // vertex position
            float4 color : COLOR;
        };

        struct v2f
        {
            float4 vertex : SV_POSITION; // clip space position
            float4 color : TEXCOORD3;
        };

        v2f vert (appdata v, const uint instance_id : SV_InstanceID)
        {
            v2f o;

            //Getting each pixel loc. Cast as int to round decimals downward
            float xTexLoc = (int)((float)instance_id % (float)_texSize);
            float yTexLoc = (int)((float)instance_id / (float)_texSize);
            //Divide into normalized float 0...1
            xTexLoc = xTexLoc / (float)_texSize;
            yTexLoc = yTexLoc / (float)_texSize;
            // Offset Loc so it samples from the middle of the pixel to avoid edge behavior
            xTexLoc = xTexLoc + (1 / (2 * _texSize));
            yTexLoc = yTexLoc + (1 / (2 * _texSize));
            o.vertex = UnityObjectToClipPos(v.vertex + (pos_color * _drawScale);
            o.color = pos_color;
            return o;
        }

        fixed4 frag (v2f i) : SV_Target
        {
            fixed4 col = i.color;
            return col;
        }
        ENDCG

```

# Answer
Solved. The above shader works fine. However, outside the shader I was dynamically sizing the texture based on the size of a data set, using the square root rounded up. When I switched to powers of to, the issue went away- perhaps it was rounding errors, or lack of support for textures in sizes other than powers of 2.

There are many methods for calculating a power of 2, but I chose to use 2048 textures, since it can contain any data set I expect to encounter, and should be easily supported on any (WebGL) platform.
> 1 votes

---
Tags: unity, shaders, hlsl, instancing
---


# Question
Title: How do I place objects so they snap to my TileMap in Godot?
When I'm placing objects on tiles in my TileMap, they snap to positions that aren't on my tile's grid. I drag my object to the middle of the grid square, but it keeps snapping to the corners.

I'm talking about placing in the editor, not at runtime.

# Answer
> 3 votes
Godot snaps to the grid **guidelines** and not the cells between them. So you won't snap to the middle of the square that you're dragging to. That's because you're snapping the position of the object (that little symbol in the centre) to a grid, which is a specific position (the line).

For reference, these are the snap settings:

There are two aspects to solving this: your object's root and your grid/world settings.

# Scene root position

When viewing a scene (like your player), if you click on the root node (at the top of Scene) you'll see a red cross indicating the root position. For side-view games, we want this on the bottom/feet of the object.

1. Set the root position of your objects to their feet/bottom to make it easy to snap to floors. With top-level object selected, you should see the root (red cross) on the red line (x-axis). See short video here.
2. Or if they're just a sprite, use the Offset setting.

# World position on grid

We need to align our grid with our world so it positions objects correctly.

1. From the snap settings, Configure Snap and adjust the offset to put the grid line in the middle of your tiles.
2. Or you could also adjust the position of your TileMap to be on the grid instead.

---
Tags: tilemap, grid, godot-4
---


# Question
Title: How can I fix this NullReferenceException error while all the references are set to specific objects?
I'm currently working on a boss fight for my game. My problem is that I keep getting a `NullReferenceException` error that prevents the boss (named The Smallest Stain) from moving in the Shoot State. I understand the different meanings of this error, but I don't understand its meaning when all references are set to specific game objects.

Let's start from the beginning to make the problem clearer.

This is the battle area. The player character is on the left and the boss is on the right. When in the Shoot State, I want the boss to change their position depending on where the player is right now.

To do this, I placed triggers on all the platforms and created empty children for them that act as the boss' new positions (They're visible as blue-green circles in the image).

This image shows the objects' organization in the hierarchy:

And this is how the Animator states look like for the boss (For the purposes of this question, I don't write about the Laugh state here):

I wrote the following code and added it to each Trigger gameobject:

```
using UnityEngine;

public class TheSmallestStain_ShootingTriggers : MonoBehaviour
{
    // These are the positions for the boss.
    public Transform bossPosition1;
    public Transform bossPosition2;
    public Transform bossPosition3;
    public Transform bossPosition4;
    public Transform bossPosition5;
    public Transform bossPosition6;
    public Transform bossPosition7;
    public Transform bossPosition8;
    public Transform bossPosition9;
    public Transform bossPosition10;

    public static bool enteredTrigger1;
    public static bool enteredTrigger2;
    public static bool enteredTrigger3;
    public static bool enteredTrigger4;
    public static bool enteredTrigger5;
    public static bool enteredTrigger6;
    public static bool enteredTrigger7;
    public static bool enteredTrigger8;
    public static bool enteredTrigger9;
    public static bool enteredTrigger10;

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject == Player.Instance.gameObject)
        {
            if (gameObject.name == "Trigger 1")
            {
                enteredTrigger1 = true;
                Debug.Log("Yes! It works!");  // This Debug.Log works and I see the message every time I play the game.
            }

            else if (gameObject.name == "Trigger 2")
            {
                enteredTrigger2 = true;
            }

            else if (gameObject.name == "Trigger 3")
            {
                enteredTrigger3 = true;
            }

            else if (gameObject.name == "Trigger 4")
            {
                enteredTrigger4 = true;
            }

            else if (gameObject.name == "Trigger 5")
            {
                enteredTrigger5 = true;
            }

            else if (gameObject.name == "Trigger 6")
            {
                enteredTrigger6 = true;
            }

            else if (gameObject.name == "Trigger 7")
            {
                enteredTrigger7 = true;
            }

            else if (gameObject.name == "Trigger 8")
            {
                enteredTrigger8 = true;
            }

            else if (gameObject.name == "Trigger 9")
            {
                enteredTrigger9 = true;
            }

            else if (gameObject.name == "Trigger 10")
            {
                enteredTrigger10 = true;
            }
        }
    }
}

```

Then, I used those references in this script, which is attached to "The Smallest Stain Shoot" State:

```
using UnityEngine;

public class TheSmallestStain_Shoot : StateMachineBehaviour
{
    public float timer;
    public float speed;

    private Transform playerPos;

    TheSmallestStain theSmallestStain;
    TheSmallestStain_ShootingTriggers shootingTriggers;

    GameObject theBoss;

// OnStateEnter is called when a transition starts and the state machine starts to evaluate this state
override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
    playerPos = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();

    theSmallestStain = animator.GetComponent<TheSmallestStain>();
    shootingTriggers = animator.GetComponent<TheSmallestStain_ShootingTriggers>();

    theBoss = GameObject.Find("The Smallest Stain");

    timer = 5;
}

// OnStateUpdate is called on each Update frame between OnStateEnter and OnStateExit callbacks
override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
    theSmallestStain.LookAtPlayer();

    if (TheSmallestStain_ShootingTriggers.enteredTrigger1 == true)
    {
        theBoss.transform.position = shootingTriggers.bossPosition1.position; // The error points out to this line.
    }

    if (TheSmallestStain_ShootingTriggers.enteredTrigger2 == true)
    {
        theBoss.transform.position = shootingTriggers.bossPosition2.position;
    }

    if (TheSmallestStain_ShootingTriggers.enteredTrigger3 == true)
    {
        theBoss.transform.position = shootingTriggers.bossPosition3.position;
    }

    if (TheSmallestStain_ShootingTriggers.enteredTrigger4 == true)
    {
        theBoss.transform.position = shootingTriggers.bossPosition4.position;
    }

    if (TheSmallestStain_ShootingTriggers.enteredTrigger5 == true)
    {
        theBoss.transform.position = shootingTriggers.bossPosition5.position;
    }

    if (TheSmallestStain_ShootingTriggers.enteredTrigger6 == true)
    {
        theBoss.transform.position = shootingTriggers.bossPosition6.position;
    }

    if (TheSmallestStain_ShootingTriggers.enteredTrigger7 == true)
    {
        theBoss.transform.position = shootingTriggers.bossPosition7.position;
    }

    if (TheSmallestStain_ShootingTriggers.enteredTrigger8 == true)
    {
        theBoss.transform.position = shootingTriggers.bossPosition8.position;
    }

    if (TheSmallestStain_ShootingTriggers.enteredTrigger9 == true)
    {
        theBoss.transform.position = shootingTriggers.bossPosition9.position;
    }

    if (TheSmallestStain_ShootingTriggers.enteredTrigger10 == true)
    {
        theBoss.transform.position = shootingTriggers.bossPosition10.position;
    }
}

// OnStateExit is called when a transition ends and the state machine finishes evaluating this state
override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {

    }
}

```

Now, we get to the error. I get it whenever the player enters the first Trigger and the boss enters the Shoot state. As you can see in the image, it points out to line 35, which is `theBoss.transform.position = shootingTriggers.bossPosition1.position;`. Essentially, the line that should change the position of the boss to their new position. But the strange thing is that all those references are set to their objects (both in the script and Inspector). So, I don't know why it's not working.

I would appreciate it if you let me know in case I'm doing something wrong here. Thanks!

# Answer
First let's simplify your shooting triggers script. We'll use arrays to make the code shorter and faster. Instead of looking for ten different hard-coded names (and paying string comparison costs for each attempt), we'll just add an integer field you can set in the inspector to let each instance know which index it should use (starting at zero).

This script doesn't use `bossPositions` anywhere, so that data probably does not belong in this script and should be hosted somewhere else.

```
using UnityEngine;

public class TheSmallestStain_ShootingTriggers : MonoBehaviour
{
    // These are the positions for the boss.
    public Transform[] bossPositions;

    // Set in inspector (way faster and more reliable
    // than tem if statements doing string
    // comparisons on the game object's name)
    public int triggerId;

    public static bool[] enteredTriggers = new bool[10];

    private void OnTriggerEnter2D(Collider2D collision)
    {
        // Consider using physics layers so that
        // the player is the ONLY thing that collides
        // with the trigger's layer, then you don't
        // need this if check at all.
        if (collision.gameObject == Player.Instance.gameObject)
        {
            enteredTriggers[triggerId] = true;
        }
    }
}

```

Next, we'll apply similar simplifications to your shooting script, and add error logging so you get better feedback about where your mistake is.

```
using UnityEngine;

public class TheSmallestStain_Shoot : StateMachineBehaviour
{
    public float timer;
    public float speed;

    private Transform playerPos;

    TheSmallestStain theSmallestStain;
    TheSmallestStain_ShootingTriggers shootingTriggers;

    GameObject theBoss;

    override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        // Never search by name if you have another way.
        playerPos = Player.instance.transform;

        if (!animator.TryGetComponent(out theSmallestStain)) {
            Debug.LogError("No smallest stain component found");
        }

        if (!animator.TryGetComponent(out shootingTriggers)) {
            Debug.LogError("No shooting triggers component found");
        };

        // Would this not be the same object that has
        // the SmallestStain component?
        theBoss = GameObject.Find("The Smallest Stain");

        if (theBoss == null) {
            Debug.LogError("No boss found");
        }

        timer = 5;
    }

    override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        theSmallestStain.LookAtPlayer();

        int maxTriggerEntered = -1;
        for (int i = 0; i < TheSmallestStain_ShootingTriggers.enteredTriggers.Length; i++) {
            if (TheSmallestStain_ShootingTriggers.enteredTriggers[i]) maxTriggerEntered = i;
        }

        if (maxTriggerEntered > -1 && maxTriggerEntered < shootingTriggers.bossPositions.Length) {
            if (shootingTriggers.bossPositions[maxTriggerEntered] == null) {
                Debug.LogError($"Boss position {maxTriggerEntered} is null");
            } else if (theBoss == null) {
                Debug.LogError("Something destroyed the boss");
            } else {
                theBoss.transform.position = shootingTriggers.bossPosition[maxTriggerEntered].position;
            }
        }
    }
}

```

There we go. Shorter, faster code, which will tell you exactly which reference is null when you've set it up incorrectly.

"There are no contradictions: when you perceive one, check your assumptions."
> 3 votes

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


# Question
Title: Maintain constant Y position value for a dynamic body
Something obvious is skipping my mind with Bullet Physics library, so apology in advance:

I have a dynamic rigidbody, which I'd like to have its Y (up/down) coordinate to be at constantly at a certain value, let's say 50 units in world space, and move freely along the X Z axis.

With the following code, I set the get the body current origin, and just correct the Y coordinate to 50, like this:

```
    m_bt_rigid_body->setDamping(0.5f, 0.5f);
    btTransform trans = m_bt_rigid_body->getCenterOfMassTransform();
    btVector3 bodyPos = trans.getOrigin();
    btScalar desiredHeight = 50.0f;
    bodyPos.setY(desiredHeight);
    trans.setOrigin(bodyPos);
    m_bt_rigid_body->setCenterOfMassTransform(trans);

```

this works but the body is wildly shaking, up and down, see videos:

https://youtu.be/SdhgbopYliM

https://youtu.be/Bo4IQvwZ6ms

which is surprising considering the value's constant nature (50.0f). As you can see on the videos, the X Z values are smooth, as they left intact.

The code above is executed in a bullet's pre-tick callback function. I tried the on-tick callback function, but it shakes even more. I also tried to grab the motionstate (default) transformation and set it in rendering frame, but no joy.

I have no other place i manipulate this body. Its mass is 1.0, and the gravity is -9.8, and the body does not collide with anything in the videos.

How could this jittering be eliminated?

(I see in other posts that kinematic objects have no such issues, but my use case is with plain dynamic bodies).

Thanks!

# Answer
The solution was easy. Just call `clearForces()` after `setCenterOfMassTransform()`, so the remainder forces don't mess with the body transformation.
> 1 votes

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


# Question
Title: How to draw selected instances with gl_InstanceID and glDrawElements...?
I want to draw a selected number of instances using `glDrawElements...` but I don't know which function to use and how to set the parameters.

I set the `gl_InstanceID` in shader and set the shader data through SSBO:

```
glGenBuffers(1, &SSBO);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, SSBO);
glBufferData(GL_SHADER_STORAGE_BUFFER, data_vector.size() * sizeof(data_type), data_vector.data(), GL_DYNAMIC_DRAW);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, binding_index, SSBO);

```

I have an array `drawable_vector` contains `bool` to check if the vertex is drawn or not.

```
for(auto index = 0; index  < drawable_vector.size(); index ++){
    glDrawElements...(???)
}

```

I want to draw instance with ID `gl_instanceID` only when the `drawable_vector[index]` is `true`. The size of drawable\_vector, data\_vector and number of instances are the same.

Edit: Setup & render code

Setup:

```
//VAO
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);

//VBO1 - Position
glGenBuffers(1, &VBO1);
glBindBuffer(GL_ARRAY_BUFFER, VBO1);
glBufferData(GL_ARRAY_BUFFER, 3*sizeof(glm::vec4), vertices.data(), GL_DYNAMIC_DRAW);

//VBO2 - color
glGenBuffers(1, &VBO2);
glBindBuffer(GL_ARRAY_BUFFER, VBO2);
glBufferData(GL_ARRAY_BUFFER, 3*sizeof(glm::vec4), colors.data(), GL_DYNAMIC_DRAW);

//EBO
glGenBuffers(1, &EBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_DYNAMIC_DRAW);

//SSBO - models in shader
glGenBuffers(1, &SSBO);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, SSBO);
glBufferData(GL_SHADER_STORAGE_BUFFER, models.size() * sizeof(glm::vec4), models.data(), GL_DYNAMIC_DRAW);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, SSBO);

//Set data of shader
//in_pos
glBindBuffer(GL_ARRAY_BUFFER, VBO1);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, (void *) 0);
glEnableVertexAttribArray(0);
//in_color
glBindBuffer(GL_ARRAY_BUFFER, VBO2);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, (void *) 0);
glEnableVertexAttribArray(1);

glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, 0);
glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);
glBindVertexArray(0);

```

Shader:

```
#version 450 core
out vec4 frag_color;

in vec4 out_color;

void main()
{
    frag_color = out_color;
}

```

```
#version 430 core
layout (location = 0) in vec4 in_pos;
layout (location = 1) in vec4 in_color;
layout(std430, binding = 2) buffer DataBuffer
{
    mat4 in_models[];
} buffer_data;

uniform mat4 view;
uniform mat4 projection;

out vec4 out_color;

void main()
{
    out_color = in_color;
    gl_Position = projection * view * buffer_data.in_models[gl_InstanceID] * in_pos;

}

```

Render:

```
use_shader();
shader_set_view("view", view);
shader_set_projection("projection", projection);
update_models();
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO1);
glBindBuffer(GL_ARRAY_BUFFER, VBO2);
glBindBuffer(GL_ARRAY_BUFFER, EBO);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, SSBO);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, SSBO[0]);
glDrawArraysInstanced(GL_TRIANGLES, 0, 3, n_instances);

glfwSwapBuffers(window);
glBindVertexArray(0);

```

# Answer
> 0 votes
I figured it out.

Hav to use the command `glDrawElementsInstancedBaseInstance` and added gl\_BaseInstance to the shader

```
void main()
{
    out_color = in_color;
    gl_Position = projection * view * buffer_data.in_models[gl_BaseInstance+gl_InstanceID] * in_pos;

}

```

and set `baseinstance` in `glDrawElementsInstancedBaseInstance` to instance numbers to draw.

```
for(int r_index = 0; r_index < instance_id_list; r_index++) {
    glDrawElementsInstancedBaseInstance(
            GL_TRIANGLES,      // type of primitive to render
            3,                 // vertex count
            GL_UNSIGNED_INT,   // type of each index in the GL_ELEMENT_ARRAY_BUFFER
            (void*)0,          // element array buffer offset
            1,                 // Number of copies to render
            instance_id_list[r_index]  // Number to start from for InstanceId
    );
}

```

---
Tags: opengl, instancing
---


# Question
Title: In Unity, how can I make sprites be affected by lights in the scene? The Sprite-Lit-Default Material doesn't seem to be working
I am trying to make it so the sprites in my scene are affected by lighting, but I cannot figure out how. I looked it up, and everywhere I looked, I was told to switch the sprite's material from "Sprite-Unlit-Default" to "Sprite-Lit-Default." According to what I had heard, assuming my scene had no lights, all of the sprites should have turned completely black, but instead, all of the sprites remained completely unchanged. I then tried creating my own lit material, by creating a material and setting the shader to Universal Render Pipeline \> 2D \> Sprite Lit Default, but again, nothing happened once I applied it to the sprites. Here is a screenshot of the situation, the Sprite-Lit-Default material is attached to all three sprites:

Does anyone know why this is happening, or what is even happening in the first place, and how I can fix it? Any help you can give is much appreciated. Thanks! (I'm still relatively new to Unity and URP, so the solution may very well be extremely simple.)

# Answer
> 2 votes
Possibly, your sprites won't turn black because of ambient light. If it's at `1.0` then sprites won't look any different than when rendered with the base shader.

Just in case, make sure you configured the URP 2DRenderer for use with the 2D lighting package, and upgraded prefabs and scenes if needed.

You can also use masks and normal maps for sprites to achieve a nice look for lights affecting your game objects. Many parameters are exposed for 2D lights to customise their behaviour.

---
Tags: unity, 2d, sprites, lighting
---


# Question
Title: teleportation...how to not teleport inside walls
when the player uses the teleportation skill, he is instantly teleported X distance in the direction of movement so front, back, left and right depending in which direction the player wants to go.

the first problem with this system was falling through the terrain, to stop it I added a ray below the feet of the player that points downward, if it checks that there is terrain, the player will teleport on that terrain.

also added another ray on the player's head, this one points towards the sky... if it checks that there is land above the player's head, it will be teleported with his feet landed on the above terrain.

so no more falling endlesly through the emptiness by teleporting inside the terrain...

but one problem I have never manage to fix.... teleporting inside walls or teleporting inside enemies or inside other players.

# Answer
> 0 votes
Fixed it deleted all the rays, I hate rays anyways, for anyone wanting to use it, all you have to do is decide the teleport\_distance by asigning it a number and then add a keybind for "blink", then you can just copy and paste this in your func \_physics\_process(delta):

```
    if Input.is_action_just_pressed("blink"):
    var forward_direction = -global_transform.basis.z
    var teleport_vector = forward_direction.normalized() * -teleport_distance
    var teleport_position = translation + teleport_vector
    var collision = move_and_collide(teleport_vector)
    if collision:
        teleport_position = collision.position
    translation = teleport_position

```

keep in mind that this version is adjusted to teleport your player where the camera is pointing not where the player is facing, if you use a different directional system just use your direction variable instead of "forward\_direction" also change -teleport\_distance by deleting the minus like this

```
    if Input.is_action_just_pressed("blink"):
    var teleport_vector = direction.normalized() * teleport_distance
    var teleport_position = translation + teleport_vector
    var collision = move_and_collide(teleport_vector)
    if collision:
        teleport_position = collision.position
    translation = teleport_position

```

The first method is perfect for games with strafing or first person games, the second method is perfect for games like Zelda, Tera, Monster hunter... where movement is complely free and more natural.

ps: if you copy and paste this, adjust the indents/spaces/tabs.

---
Tags: collision-detection, 3d, rpg, collision-prediction, godot-3
---


# Question
Title: How to generate .sln files manually in Unity
I'm using git with a Unity project of mine. I'm working on my home machine and also on one at school.
I started it at home and it works perfectly on my machine.
Once I cloned it at school it opened fine and everything still worked. Only problem was VS did not generate a project. At home I have 2019 and school has 2017.

If I generate a new Unity Project at school it has the .sln and I can open it using `Assets -> Open C# Project`. There is no such project generated when opening the cloned project.
I need get around this as it's near impossible for me to code efficiently at school.
Because it is an EDU machine I have very limited access to certain things. Can I create a project by hand or run a command to generate one?

# Answer
I was able to get around this.
First I looked up VS in the start menu and clicked "Open File Location" which lead me to a shortcut to the school server. Then I made a link to that link on my desktop.
In Unity went to preferences and set the default editor to that like. Then I opened a .cs file and it generated the solution.

On my machine it opened ALL of Unity's code as seperate projects in one big solution which doesn't bug me.
On another computer it only opened the scripts written by us.
Unsure which it will normally do but it solved the situation.
> 2 votes

# Answer
To regenerate your .sln and related files:

1. `Edit` -\> `Preferences`
2. `External Tools`
3. Under `External Script Editor` select `Microsoft Visual Studio 20xx` (pick your version)
4. Press `Regenerate project files`
> 1 votes

# Answer
Well you can create a solution from a console with the dotnet SDK:

`dotnet new sln`

And add Projects with:
`dotnet sln <SLN_FILE> add <PROJECT_PATH>`

I don't know if Unity works with a default C#-Solution, or if it needs a.

(Of course you need to replace the `<SLN_FILE>` and `<PROJECT_PATH>`).
> 0 votes

---
Tags: unity, visual-studio
---