# Question
Title: How to detect when a keyboard arrow key is held down?
I am very new to Python I started to make a pong game, but can't get it to let me hold down the buttons for the paddle to move. I'm using the turtle, not Pygame

```
 def paddle_a_up():
   y = paddle_a.ycor()
   y += 15
   paddle_a.sety(y)

def paddle_a_down():
    y = paddle_a.ycor()
    y -= 15
    paddle_a.sety(y)

def paddle_b_up():
    y = paddle_b.ycor()
    y += 15
    paddle_b.sety(y)

def paddle_b_down():
    y = paddle_b.ycor()
    y -= 15
    paddle_b.sety(y)

# binds
wn.listen()
wn.onkey(paddle_a_up, "w")
wn.onkey(paddle_a_down, "s")
wn.onkey(paddle_b_up, "o")
wn.onkey(paddle_b_down, "i")

```

I can't seem to get my arrow up and down to work with the binds so that's why I'm using "o" and "i". If you have a solution for that too, I'd be very grateful.

# Answer
> 1 votes
System sends to programs information about pressed key (`"events"`) only when key changes state from `not-pressed` to `pressed` or from `pressed` to `not-pressed` (`released`). It doesn't send events when you hold down key.

You have to use `onkeypressed()` to set `arrow_up_pressed = True` and `onkeyreleased()` to reset `arrow_up_pressed = False` and `ontimer()` to run repeatedly code which checks if `arrow_up_pressed` is `True` and move object up. The same you should do with `arrow_down_pressed`, etc.

Or you can use variable `speed` instead of `arrow_up_pressed` and `arrow_down_pressed` so you can assing `+15` or `-15` to the same variable (or `0` when keys are released). And again you need `ontimer` to run repeatedly code which add speed to position.

In example I use second method.

---

Minimal working code

```
import turtle

def paddle_a_up():
    global a_speed_y

    a_speed_y = +15

def paddle_a_down():
    global a_speed_y

    a_speed_y = -15

def paddle_a_left():
    global a_speed_x

    a_speed_x = -15

def paddle_a_right():
    global a_speed_x

    a_speed_x = +15

def paddle_a_stop_y():
    global a_speed_y

    a_speed_y = 0

def paddle_a_stop_x():
    global a_speed_x

    a_speed_x = 0

def update_frame():
    x, y = paddle_a.position()

    y += a_speed_y
    x += a_speed_x

    paddle_a.goto(x, y)

    # here update position for other objects - ie. move ball

    # run again after 50ms
    wn.ontimer(update_frame, 50)  # 50ms means ~20 FPS (Frames Per Second) (1000/50 = 20)

# --- main ---

# default values at start
a_speed_x = 0
a_speed_y = 0

wn = turtle.Screen()
paddle_a = turtle.Turtle()

# run first time after 50ms
wn.ontimer(update_frame, 50)  # 50ms means ~20 FPS (Frames Per Second) (1000ms / 50ms = 20)

# binds
wn.onkeypress(paddle_a_up, "Up")
wn.onkeypress(paddle_a_down, "Down")
wn.onkeypress(paddle_a_left, "Left")
wn.onkeypress(paddle_a_right, "Right")

wn.onkeyrelease(paddle_a_stop_y, "Up")
wn.onkeyrelease(paddle_a_stop_y, "Down")
wn.onkeyrelease(paddle_a_stop_x, "Left")
wn.onkeyrelease(paddle_a_stop_x, "Right")

wn.listen()
wn.mainloop()

```

---

**BTW:** The same way you would have to do this in `PyGame` or `Pyglet`.

---

**EDIT:**

You get better result if you add/substract value to `speed` instead of assigning - because when you press `left` and `right` at the same time then it will stop move (because speed +15 and -15 will gives 0), and when you release only one - ie. `left` \- then it will again move `right`. In previous version when you release one but you still keep pressed other then it doesn't move again.

```
import turtle

def paddle_a_up_pressed():
    global a_speed_y

    a_speed_y += 15

def paddle_a_down_pressed():
    global a_speed_y

    a_speed_y -= 15

def paddle_a_left_pressed():
    global a_speed_x

    a_speed_x -= 15

def paddle_a_right_pressed():
    global a_speed_x

    a_speed_x += 15

def paddle_a_up_released():
    global a_speed_y

    a_speed_y -= 15

def paddle_a_down_released():
    global a_speed_y

    a_speed_y += 15

def paddle_a_left_released():
    global a_speed_x

    a_speed_x += 15

def paddle_a_right_released():
    global a_speed_x

    a_speed_x -= 15

def update_frame():
    x, y = paddle_a.position()

    x += a_speed_x
    y += a_speed_y

    paddle_a.goto(x, y)

    # run again after 50ms
    wn.ontimer(update_frame, 50)  # 50ms means ~20 FPS (Frames Per Second) (1000/50 = 20)

# --- main ---

# default values at start
a_speed_x = 0
a_speed_y = 0

wn = turtle.Screen()
paddle_a = turtle.Turtle()

# run first time after 50ms
wn.ontimer(update_frame, 50)  # 50ms means ~20 FPS (Frames Per Second) (1000/50 = 20)

# binds
wn.onkeypress(paddle_a_up_pressed, "Up")
wn.onkeypress(paddle_a_down_pressed, "Down")
wn.onkeypress(paddle_a_left_pressed, "Left")
wn.onkeypress(paddle_a_right_pressed, "Right")

wn.onkeyrelease(paddle_a_up_released, "Up")
wn.onkeyrelease(paddle_a_down_released, "Down")
wn.onkeyrelease(paddle_a_left_released, "Left")
wn.onkeyrelease(paddle_a_right_released, "Right")

wn.listen()
wn.mainloop()

```

---
Tags: input, python, keyboard
---


# Question
Title: Multiple small UDP packets vs One big constant UPD packet
I'm making a MMO Bullet Hell game on Game Maker Studio 2 with a node.js server and I'm already able to receive and send information through UDP connections. I NEED to keep the server as fast as possible on the response to avoid lag to players since on this genre lag means death in most of the cases.

My main problem is: I need to get the ping/ms of the clients on the server and other informations (such as player data) from the client to the server. I'm currently dividing the two, so i send a "ping/pong" packet from the server to the client to get the ping/ms and every time something inside the player data is modified on the client it sends the information to the server on a JSON.

Now to the question: Should I put all the data on a big JSON and send to the server constantly or should i keep my current model and send a packet to get the ms and other packets to send and receive data? Keep in mind that when my player is moving it'll send a bunch of data packets to the server whilst the ping function is running.

# Answer
What you really need to do here is bit packing and unpacking. Here is a decent tutorial so you can get the most out of each packet, as each bit you send should convey as much information as possible. JSON might be easy to read, but we are programmers and do not need to actually read the data in our packets (unless debugging!). We simply need to interpret the bits into a usable struct in whichever language we choose.

JSON might be the simplest solution, but it is quite far from the best. The best MMOS spend years optimizing this process. In fact, for MMOs, it may be preferable to use TCP! Here is an excerpt from the link mentioned,

> UDP is another widely used transport protocol, but it cannot be applied to MMORPGs directly due to the lack of reliable and in-order transmission. To deal with packet loss and the reordering of game messages that need strict reliability and in-order processing, an excessive amount of effort is required if UDP is adopted.

Another thing you need to think about is encryption. Sending plaintext packets in JSON is a quick way to introduce vulnerabilities to your game. Packet editors are one of the oldest tools hackers have in their toolbox, and plaintext packets are just asking to be exploited.

Here are a few more resources to explore

http://ithare.com/udp-for-games-security-encryption-and-ddos-protection/

https://pvigier.github.io/2019/09/08/beginner-guide-game-networking.html

https://gamedevcoder.wordpress.com/2011/08/28/packet-encryption-in-multiplayer-games-part-1/
> 1 votes

# Answer
While everybody is super experienced with telling that JSON is literally not the option along with the UDP, in your case it is better to send chunks of data, because even though it theoretically will use more traffic, it will result in more fail-safe environment as if you lose one packet with some data, it will be some what all right because you will get it anyway later, while getting other packets successfully, but if you will lose big data, it will hurt more, as you've lost a lot, creating nearly an artificial disconnection, so it will be much of a severe problem.
> 0 votes

---
Tags: networking, game-maker, mmo, node.js, udp
---


# Question
Title: Why Unity Corrupts textures when used on a Sample Texture node shader
I am trying create a glow effect on a background, to do this I am using shaders, when I use the main texture everything is okay, but when I put the emission map the texture corrupts

Here's the original image for those trying to replicate the problem:

I am beginner about shaders and Unity

# Answer
> 2 votes
It looks like you've imported this texture with the flag "Alpha is Transparency" ticked.

This tells Unity that the colour values of texels in zero-alpha areas will never be seen (because they're transparent), so it's free to modify them to help avoid ugly fringes at the edges of sprites, or to make the texture compress better.

So here it's bled the white of your windows out into the zero-alpha regions of the texture, on the assumption that you will keep the promise you made and only ever treat those texels as transparent.

You can see the correct shapes of the windows are still preserved in the alpha channel. And if we multiply the RGB channels by the alpha (like we would if rendering the image with transparency), we get the same result as your original image:

So there's no "corruption" here at all. Unity is applying a safe, information-preserving transformation to help your image render correctly in the way you promised you were going to render it.

The problem here is you broke your promise. You're not using it like a transparent sprite. You're discarding the alpha channel and using the RGB channels alone for emission.

Because you're using the texture in a way that's different from what you promised by ticking "Alpha is Transparency", the transformation Unity applied is no longer safe for that use case.

So, three solutions:

1. Uncheck "Alpha is Transparency" so you're not making promises that you don't plan to keep.
2. Pre-multiply the RGB channels by the Alpha channel as shown above, and pass the multiplied result to the emission pin. That way you emulate the transparent blending that's assumed by the "Alpha is Transparency" checkbox. This will also work for colour images.
3. If you only want white emission, wire just the texture's Alpha pin to the material emission pin. That way you can discard the unused RGB information entirely, and store your texture in an Alpha-only format.

---
Tags: unity, shaders, textures
---


# Question
Title: How to use X,Y, and Z instead of Pitch, Roll and Yaw
I'm learning Unreal engine, and I'm rather disappointed because it uses pitch roll and yaw instead of the standard x, y, and z that I'm used to. Is there any way to convert this easily, or is there a preference, or do I have to get used to using y,z,x, instead of x,y,z.

# Answer
> 1 votes
Depending on what you're trying to do, both rotational and vector coordinates are normally available. The following C++/Blueprint methods are available to move between the two different types of coordinate systems. Hope it helps!

# FRotator

Represents rotational coordinates (yaw, pitch, roll).

**C++:** FRotator::Vector()

**Blueprints:** Break Rot Into Axes

# FVector

Represents vector coordinates (x, y, z).

**C++:** FVector::Rotation()

**Blueprints:** Rotator from Axis and Angle

# Other Conversions

Here's a list of other conversions. This may not be an exhaustive list as their code changes from version to version often. So, navigating the engine's source code on your computer will be the the final source of truth.

---
Tags: unreal-4, coordinates
---


# Question
Title: Correcting imported animation to avoid hand going through the face of character
I've imported an animation from Mixamo called standing draw bow. When I use it with my character in Unity the hand goes through the face of my character.

Is there a way to move hand a little outside the face of the character using Blender or Unity? Or am I required to make up the animation myself?

I tried modifying parameters Mixamo offers but doesn't resolve the problem.

I actually tryed to solve the problem with IK by adding a Multi-Parent constraint ( cause i didn't manage to have multi-postion constraint to work ) and tried to move lowerarm\_r Bone a little bit off the face of the character but it only did force the bow to stay in the position and rotation of the "Target" while being buggy in certain keyframes. my aim is to force that bone to not rotate more than certain degree to not go through the face while executing the animation. I believe the problem is coming from the fact that animation is made for normal head character not big head ones.

# Answer
> 1 votes
It turns out that putting that animation (since other animations works well) in another animation layer and lowering the weight of the animation layer force the hand to not rotating too much and go through the character face.

edit: i actually found out that you can also lower the weight of only the bones that rotates too much by reassigning the mesh's bonesWeight using a C# script if you want it to be made for a short time or if you have problem with your animations you can configure bones rotation limits by configuring the avatar of your character.

---
Tags: unity, animation, blender
---


# Question
Title: Can I use a creative common licensed CC BY 4.0 model in a commercial indie game?
I want to use this keyboard model in my commercial indie game.

The site says the asset is available with a "CC Attribution" licence, linking to the information page for the CC BY 4.0 licence.

From what I understood, you are able to use the creative common asset if you modify it. As the site says:

> **Share** — copy and redistribute the material in any medium or format
>
> **Adapt** — remix, transform, and build upon the material for any purpose, even commercially.

As you can see it doesn't say anything about using the Creative Commons asset, which made me wonder if I can actually use it (with credit).

# Answer
> 1 votes
I am not a lawyer and this is not legal advice. What we can help you with here are the *game* parts of making a game. For aspects relating to *law*, you should always consult a lawyer.

What I'll do here is simply read to you the text of the page you've already linked, which contains every piece of information you need.

> # You are free to:
>
> **Share** — copy and redistribute the material in any medium or format

"Indie game" is included in "*any* medium or format"

> **Adapt** — remix, transform, and build upon the material for any purpose, even commercially.

Building a game that includes this asset is "building upon the material," and "any purpose, even commercially" means you have permission to sell the result.

> # Under the following terms:
>
> **Attribution** \- You must *give appropriate credit*, provide a link to the license, and *indicate if changes were made*. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use.
>
> **No additional restrictions** — You may not apply legal terms or technological measures that legally restrict others from doing anything the license permits.

So you can't put a licence on your game that forbids players from using the keyboard model in their own projects. (You probably weren't going to anyway)

There are tooltips on the page that clarify how to **give appropriate credit**:

> If supplied, you must provide the name of the creator and attribution parties, a copyright notice, a disclaimer notice, and a link to the material.

Here, you have the name of the creator, Oscar Herry, and a link to the material, so you would be expected to make those available alongside your work that builds on this asset - like in the credits screen of your game. This would also be the place to mention whether you modified the asset, like changing the material or textures to work with your game's style.

# Answer
> 0 votes
As it stands on CC website you are allowed to redistribute it almost however you want including for commercial use. But you have give credit to the person who made it.

---
Tags: licensing
---


# Question
Title: Buttons only trigger right/left movement once, not continually
I have a Unity mobile project where I am trying to use right/left movement using two UI buttons situated accordingly. The issue is that it only moves the player to the right/to the left one time, not continually when the player is holding the button down.

I'd like the player to be able to hold down a certain button and have the character move constantly in that direction until the button is released. I've tried making the void into a Coroutine, but nothing working works.

Here is my code. (`rightCallable` and `leftCallable` are attached to the buttons).

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

public class playerController : MonoBehaviour
{
    public GameObject player;
    public float speed = 1000f;
    public GameObject left;

    //this is so the player may also use the A and D keys if they want, and it works fine.
    public void Update()
    {
        var movement = Input.GetAxis("Horizontal");
        transform.position += new Vector3(movement, 0, 0) * Time.deltaTime * speed;
    }

    //Below is what isn't working
    public void rightCallable ()
    {
        StartCoroutine("moveRight");
    }

    public void leftCallable ()
    {
        StartCoroutine("moveLeft");
    }

    IEnumerator moveRight()
    {
        var movement = 1f;
        transform.position += new Vector3(movement, 0, 0) * Time.deltaTime * speed;
        yield return null;
    }
    IEnumerator moveLeft ()
    {
        var movement = -1f;
        transform.position += new Vector3(movement, 0, 0) * Time.deltaTime * speed;
        yield return null;
     }
 }

```

# Answer
Replace your code with something like this:

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

public class PlayerController : MonoBehaviour
{
    public GameObject player;
    public float speed = 1000f;
    public GameObject left;

    bool _isLeftHeld;
    bool _isRightHeld;

    public void Update()
    {
        var movement = Input.GetAxis("Horizontal");

        // Ignore cases where neither/both left and right are held at once.
        if (_isRightHeld ^ _isLeftHeld) {
            // Override the movement input from the keyboard/joypad.
            if (_isRightHeld) movement = 1f;
            else movement = -1f;
        }

        // Act on the movement input in just one place, following the DRY principle.
        transform.position += new Vector3(movement, 0, 0) * Time.deltaTime * speed;
    }

    public void HoldRight(bool held)
    {
        _isRightHeld = held;
    }

    public void HoldLeft(bool held)
    {
        _isLeftHeld = held;
    }
}

```

Then add an `EventTrigger` component to each on-screen button.

Add two event types to this component: Pointer Down (to detect a press), and Pointer Up (to detect a release). Optionally, you can also detect Pointer Exit and treat that like a release.

When pressed, call your `HoldRight` or `HoldLeft` function respectively, and tick the checkbox to send the argument `true` ("The button is held").

When released, call your `HoldRight` or `HoldLeft` function respectively, and leave the checkbox unticked to send the argument `false` ("The button is *not* held").

It'll look something a bit like this:
> 0 votes

---
Tags: unity, c#, movement, character-controller
---


# Question
Title: How to correctly instantiate prefab in Unity
I made a prefab and drag drop it to the Tile Prefab slot as shown in the picture

In my code

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

public class GameGrid :MonoBehaviour
{
    private int width;
    private int height;
    private int[,] gridArray;
    private float cellSize;

    [SerializeField]
    GameObject tilePrefab;// = default;

    public GameGrid(int width, int height, float cellSize)
    {
        this.width = width;
        this.height = height;
        this.cellSize = cellSize;

        gridArray = new int[width, height];

        Debug.Log(width + " " + height);

        for(int x = 0; x < gridArray.GetLength(0); x++)
        {
            for(int z = 0; z < gridArray.GetLength(1); z++)
            {

                GameObject tile =Instantiate(tilePrefab);
                tile.transform.SetParent(transform, false);
                tile.transform.localPosition = GetWorldPosition(x,z);
            }
        }
    }

    private Vector3 GetWorldPosition(int x, int z, int y = 0)
    {
        return new Vector3(x, 0, z) * cellSize;
    }

}

```

1.It throw out error, ArgumentException: The Object you want to instantiate is null, it is very strange because I have the Prefab assigned in the inspector, what could ran wrong, and it is strange that the console did not tell me which line is wrong.

2.Another error is "You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed", it confused me because I did not new anything.

3.This line of code "tile.transform.SetParent(transform, false);" I copied from other resource which I do not fully understand, I looked to the Unity menu still did not get any idea of what it does, it setParent but what parent property this function tries to setup, is it trying to set its parent's transform or what?

Thanks very much I'm still new to Unity.

EDIT: Here is my testing.cs

```
public class Testing : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        GameGrid grid = new GameGrid(20, 10, 1);
    }
}

```

1.Remove the default assignment is not working either. 2.Regarding to the setParent, I do not have a parent, then what parent this child is attached to, if this function will instantiate a parent, then no information is provided to the creation of the parent, still confused.

# Answer
> Another error is "You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed", it confused me because I did not new anything.

You are doing this here: `GameGrid grid = new GameGrid(20, 10, 1);` Creating a MonoBehaviour through a constructor does not work, because they can only be created within the context of a GameObject. So they should not have constructors. MonoBehaviours should be created through the editor as part of the scene, or if you really want to add them via code (which you shouldn't do if it can be avoided), you have to do it using the method `GameObject.AddComponent`.

If you try to create a MonoBehavior through a constructor anyway, then Unity will be unable to populate any of the public variables, which is why you get a NullReferenceException later. What you set in the inspector doesn't matter, because you are not using that GameGrid from your inspector. You are creating a new separate GameGrid here which has no connection to the one from the inspector.

When your MonoBehaviour requires some initialization code, then that code should be in the `void Start()` method. You might notice that this method accepts no parameters. When your MonoBehaviour requires some information for its initialization, you need to set that information beforehand. When you have the MonoBehaviour attached to a GameObject (which is the recommended way of doing things), make those variables `public` and set them in the inspector.

When you want to create an object with a MonoBehaviour at runtime, then:

1. Create a new GameObject with `GameObject newGo = new GameObject()`. Or alternatively, get a reference to an existing GameObject to add the MonoBehaviour to.
2. Create a new MonoBehaviour and attach it to that new gameObject with `GameGrid grid = newGo.AddComponent<GameGrid>() as GameGrid`. This creates a new component with all public variables set to the default values, but does not yet run the Start method.
3. Set each of those public variables like this: `grid.width = 20;`. Or alternatively create your own public initialization method and call it.

The Start method of that new object will get executed before the next frame.

But I am a bit puzzled why you have that Testing.cs script in the first place, because your first image shows that you already created a GameObject called "Grid" with a GameGrid component attached in the editor. So there is no reason to create another one via code. While I am not sure what exactly you are trying to do, you likely don't need that script.

---

Regarding the line: `tile.transform.SetParent(transform, false);`: This attaches the newly instantiated tile to the gameObject which instantiated it. `transform` here refers to the Transform component of the object this script is attached to. The Transform component is also the component which manages parent/child relationships. Which is why `SetParent` expects the transform of the new parent.
> 1 votes

---
Tags: unity, prefabs
---


title: Directional light shadow on terrain

text:
# Question
Title: Directional light shadow on terrain
When player is walking on terrrain, around him Unity is rendering shadow coming from directional light.

But after some radius in the distance, shadows are not rendered.

Only when player walks close to some prefab, shadow is being drawn.

This is not very realistic. I would like that shadows are visible in the distance as in real terrain.

How to fix that ?

# Answer
You probably need to increase the radius of the light source.

Unity models light using the Inverse Square Law, so the farther from the source, the less light hits the target, and thus the less distinct the shadow.

Also, ensure that the mesh is set to Receive Shadows, and the player is set to Cast Shadows.
> 1 votes

# Answer
You can have a look at the **shadow distance** settings in your project : if it is low, the shadows for real time lights will not be rendered in the distance, which allows for better performance but causes the effect you are describing.

https://docs.unity3d.com/Manual/shadow-distance.html
> 1 votes

---
Tags: unity, lighting, terrain
---


title: GtkRadiant to unity?

text:
# Question
Title: GtkRadiant to unity?
i just chose unity as my game engine an i don't like the level editor, and i really enjoy gtkradiant, its really easy and fun to use. I was wondering if someone knows a way i can use my gtkradiant levels in unity, since i know gtkradiant is meant for id tech 3, but i heard there is some way you can import your radiant levels to unity, does anyone know how? also, if you guys dont know how, can you please tell me how to get id tech 3? i would enjoy using that engine knowing how great the graphics can be if you mod it the right way.

# Answer
> 2 votes
We have been using our own "hacked up" fork of GtkRadiant for a long time and we use it with a number of game engines. You might be interested in it: http://thamessoftware.co.uk/openradiant/

It is still free and open-source but it treats art assets like a standard modeller (i.e not from Quake III specific pk3 files). It also exports directly to .obj (for intergration with the rest of your art pipeline) and exports / exposes all the entities in a simple parseable file.

Finally it also provides some basic lightmap baking and optionally extends the .obj format to include lightmap coordinates. However you could also just export without lightmaps and use Maya, Blender, UE4, Unity etc to do its own.

Hope this helps.

# Answer
> 1 votes
The Id tech engine uses a fundamentally different data structure to store scene data than Unity does which means you can't just move scene files between engines. Based on the little bit of digging I did you would have to export to something like Maya and then into Unity. You may also want to check out Pro Builder. It works right in the Unity editor but works a lot like the Radiant/Hammer editor.

---
Tags: unity
---


# Question
Title: For dynamically batched objects the `unity_ObjectToWorld` shader variable is always set to default?
I'm using the standard render pipeline and the `unity_ObjectToWorld` variable for some calculations in my shader. After I enabled dynamic batching these calculations got broken. It seems that `unity_ObjectToWorld` is set to default when the objects are being batched. Is it by design? I didn't find anything in the documentation.

# Answer
> 1 votes
This is documented in the manual where it describes dynamic and static batching:

> Dynamic batching works by **transforming all GameObject vertices into world space** on the CPU

> Internally, static batching works by **transforming the static GameObjects into world space** and building one shared vertex and index buffer for them

And here:

> Some shaders (mostly ones that do object-space vertex deformations) do not work when Draw Call Batching is used – that’s because **batching transforms all geometry into world space**, so “object space” is lost.

Naturally, since all the vertices in the batch have been pre-transformed into world space on the CPU side prior to rendering, `unity_ObjectToWorld` is simply the identity matrix. There's no other work for it to do in the GPU shader, and because the objects in the batch could have come from multiple different object spaces, there's no way this one variable can preserve the information about all of them.

We have some prior Q&A on this topic here, with some hints about how we can work around this for some shaders that need object space data, without giving up batching completely.

---
Tags: unity, shaders, batching
---


# Question
Title: How do i put random velocity in a Vector2?
I'm very new to C# scripting.

I want to use a random velocity for my Enemies using Vector2. Here's the code that I have done at the moment:

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

public class Enemy1 : MonoBehaviour
{
    [SerializeField]
    Rigidbody2D rb2d;

    [SerializeField]
    Vector2 vectorEnemysVelocity;

    [SerializeField]
    gameManager gameManager;

    [SerializeField]
    AudioSource source;

    [SerializeField]
    AudioClip deathSound;

    private void Awake()
    {
        gameManager = FindObjectOfType<gameManager>();
    }

    void Start()
    {
        MoveEnemy();
    }

    void MoveEnemy()
    {
        rb2d.velocity = vectorEnemysVelocity;
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if(collision.gameObject.layer == 8)
        {
            gameManager.GenerateGameOver();
            source.PlayOneShot(deathSound, 1f);
        }

        if (collision.gameObject.layer == 9)
        {
            Destroy(gameObject);
        }
    }
}

```

With this I can choose the velocity but as I said earlier I want it to be random. How can I do this?

# Answer
There is always more than one way on how to do it.

https://docs.unity3d.com/ScriptReference/Random.Range.html

This gives you a random value between your given min and max value. Gives you a lot of control and is easy to understand.

```
float minValue = 0f;
float maxValue = 10f;
Vector2 randomVector = new Vector2(Random.Range(minValue, maxValue), Random.Range(minValue, maxValue));

```

Another method (credit to DMGregory) is https://docs.unity3d.com/ScriptReference/Random-insideUnitCircle.html which gives you directly a Vector2.

```
float maxValue = 10f;
Vector2 randomVector = Random.insideUnitCircle * maxValue;
Debug.Log(randomVector);

```
> 2 votes

# Answer
Another approach is generate a random vector in polar coordinates, and convert it to cartesian coordinates:

```
public Vector2 InCircle(float radius)
{
    // Generate random vector in polar coordinates
    var radius = Random.Range(0f, radius);
    var angle = Random.Range(0f, 2f * Mathf.PI);

    // Convert to cartesian coordinates
    var x = radius * Mathf.Cos(angle);
    var y = radius * Mathf.Sin(angle);

    return new Vector2(x, y);
}

```

---

I have a Unity library with UPM support called `Eflatun.RandomUtils` that has a bunch of useful RNG utility methods, and one of them covers your case, called `InCircle`:

```
// using Eflatun.RandomUtils;

var rng = new BetterRandom();
var result = rng.Vector2.InCircle(radius);

```
> 0 votes

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


# Question
Title: How can I call Schedule() on interface that inherits from IJob
So I have a voxel terrain engine, and I have an interface that all meshing jobs should inherit from. That looks like this (simplified from the actual):

```
public interface IMesherJob : IJob
{
    VoxelDataVolume<byte> VoxelData { get; set; }

    NativeArray<MeshingVertexData> OutputVertices { get; set; }
    NativeArray<ushort> OutputTriangles { get; set; }
}

```

One example of a meshing job is marching cubes, which looks like this: `public struct MarchingCubesJob : IMesherJob`

So here's my question: If I have a reference to an `IMesherJob`, can I somehow call `Schedule` on it? If I have a reference to `MarchingCubesJob`, I can call `Schedule` on it:

This works:

```
MarchingCubesJob myMeshingJob = GetMeshingJob();
JobHandle handle = myMeshingJob.Schedule(voxelCount, 64)

```

But this does not work:

```
IMesherJob myMeshingJob = GetMeshingJob();
JobHandle handle = myMeshingJob.Schedule(voxelCount, 64);

```

I noticed that `Schedule()` is an extension method for `T where T : struct, IJob` so that might be interfering with it, but it should still work because `IMesherJob` inherits from `IJob`

# Answer
As a work-around, I created a struct `JobHandleWithData<T>`, which has a `JobHandle` field and a `T` field for the data that should be associated with that particular job handle. I schedule the job inside of `GetMeshingJob`, and changed it to return a `JobHandleWithData<IMesherJob>`.
> 1 votes

---
Tags: unity, c#, unity-job-system
---


# Question
Title: How to get object or its index from mouse coordinates?
Basically, I have a NumPy array of rectangles that store their colour and position.

I want to be able to compare my mouse position and clicked on the rectangle's position and get the index or the object itself from the array.

Do I have to iterate through every square in the array and compare item's coordinates?

The structure looks like:

`Cube[Face][Horizontal-Line][Square] = np.array([colour, coordinates])`

What's the most efficient way to do it? I'm thinking of using `colliderect()` method, but I don't know how to implement it.

# Answer
> 0 votes
The solution was just to use grid system and floor division operator `//`.

---
Tags: 2d, python, pygame
---


# Question
Title: Opengl in 500 lines point in triangle question
https://github.com/ssloy/tinyrenderer/wiki/Lesson-2-Triangle-rasterization-and-back-face-culling

I am on lesson 2 of the `"Opengl in 500 lines"` tutorial. I follow the part of the lesson in `"The method I adopt for my code"`, but I don't understand this leap from

```
P = A + uAB-vector + vAC-vector

```

to

```
0-vector = uAB-vector + vAC-vector + PA-vector.

```

# Answer
If I understand if you have

```
 P = A + uAB + vAC

```

and you substract `P` on both sides then you get

```
 0 = A + uAB + vAC - P

```

and you change order

```
 0 = A - P + uAB + vAC

```

but `A - P` can mean vector `PA`

```
 0 = PA + uAB + vAC

```
> 2 votes

---
Tags: graphics, graphics-programming, rasterization, triangulation, barycentric-coordinates
---


# Question
Title: Why do console games not allow completely custom key bindings?
So I plugged in my PlayStation 2 for the first time in ten years and realized that I could not customize my key bindings, only pick from select pre-sets that the developers put in, which I thought was strange. So I checked through a few of my games on Xbox 360, PlayStation 2, and Nintendo 64 and realized that none of them had customizable controls, only control schemes (if even that)!

**Why is this?** Is it a limitation of the consoles or is it policy from Sony's and Microsoft's part that games should only offer select pre-sets, not completely customizable key bindings? The same games have customizable key bindings on PC and have no issues with binding to my Xbox 360 PC controllers.

I don't own any more modern consoles, so maybe it's different nowadays. If so, why did the old consoles have these limitations that the new ones do not have?

# Answer
Found some interesting discussions of this question, one that pointed to the following podcast at 43:35. The most salient point, in my opinion: "\[remapping controls\] is a bug factory".

My suspicion would be that in reality it's not that the limitation of consoles prevent these sorts of custom settings but rather that the variability of PC environments require them. I'm not a professional game developer, so take this with a grain of salt, but I think it's probably a lot of work for a feature that only a relatively small proportion of users would find useful. If this is something that's been changing nowadays, I would imagine it has more to do with more attention being paid towards accessibility these days than any differences in hardware.
> 2 votes

---
Tags: input, user-experience
---


# Question
Title: Humanoid Rig Animations Not Playing Properly
Although I have seen a few questions that are similar to my own, none had specific or clear answers that actually solved the problem, so here I am.

Just recently, I have imported a rig from Blender into Unity, along with a few embedded animations. As you can see here: https://gyazo.com/54f5717fa71170b198a77d5458aad919 the animations imported fine and function normally with the generic rig. The moment I switch the avatar to a humanoid-type rig, however, the only part that moves is the heart, as it is not mapped in the rig: https://gyazo.com/0f9a0b9a1c2580b848733e980fb9fcef.

As Unity has told me many times now, this is due to the humanoid rig's muscle system thing which doesn't make any sense.

So my question here is, how does one make an animation that works on humanoid rigs? Did I somehow import the Blender animation wrong or am I supposed to use Unity's animator to do it (even though *it* doesn't work either)?

# Answer
> 1 votes
Nevermind, I have figured it out on my own. Since I was importing the animations via separate fbx files with embedded animations, not all of the animations came from humanoid rigs, so the animations wouldn't play properly.

---
Tags: unity, animation, blender, rigging
---


# Question
Title: Building meshes conforming to terrain deformation
I have an uneven terrain on which the player is supposed to build buildings. For most structures I can just fudge the foundations, have them extend through the terrain. For roads, pipes, tracks and such I do have however the problem how to make them line up. What techniques can I best use to make the meshes of adjacent pieces line up, making it conform to the terrain?

# Answer
As with many other obstacles of procedural geometry, this problem can be solved with splines! It’s only one of many ways to address this engineering challenge.

Here is an excellent tutorial on how to play with splines for this exact purpose. Here’s another one demonstrating road placement.

Unity doesn’t have a purely mathematical code-based spline implementation, so i made one a while back for my own ease of use. I suggest an implementation like mine if you prefer to implement this with more code than editor, as it makes more sense to me for real-time applications.
> 1 votes

---
Tags: unity, terrain, mesh
---


# Question
Title: How do I stop a moving object when colliding with a static wall or falling to a static ground
I'm writing my very first 2D game engine in C++ and SDL2. I wrote a very simplistic `RigidBody` class that computes the resultant force, applies forces and simulates gravity. I also wrote a `BoxCollider` class and a `QuadTree` class which as any game dev would know manages collisions. Every thing seems to be working fine, however I'm facing a pit stop I can't wrap my head around. How do I stop a `GameObject` when it collides with a static wall or ground. I tried setting the `velocity` to zero but that literally freezes the object and I can't move it using my controls. Also setting the `gravity` to zero doesn't stop the object since it still has a non zero `velocity` and it sort of digs it's way through the ground. How can I implement this and if there are any decent tutorials regarding my question please do share them. Thanks!

# Answer
Check out Erin Catto’s (one of the creators of Box2D) GDC slides, he has by far one of the most succinct explanations of collision resolutions i’ve ever read. He also provides an accompanying demo of code which actually implements incredibly straight forward collision resolution in just a few hundred lines of code. He uses what is known as a sequential impulse solver, which is mathematically very similar to gauss-siedel solvers (a very common MLCP solver used in game physics).
> 1 votes

---
Tags: c++, collision-detection, physics, sdl2
---


# Question
Title: How to align prefab to a accurate position with the best practice?
I'm making a plumber game, I have a pump prefab, and pipe section prefab, which allows the user to connect the pipe during game, the pipe needs to be connected seamlessly during game, which means pipe prefab needs to be aligned in pixel level, please check below

User needs to add more and more pipe to connect the with each other, pipe is fixed length prefab.I've got choices,

1.Is the pipe prefab instantiated during game play a good practice? Because it might have many pipe prefabs, if the pipe goes a long way to another position, than there will needs to be so many pipe prefabs, compared to have procedrually generated pipe mesh during runtime, then a long pipe will not have to be cut off to the same small pieces?Which is good way to adpot?

2.If I use the same pipe prefabs to fabricate the piping system, how to accurately connect each other in pixel level, I can make the whole piping system in blender, then cut the system into pieces as my prefabs, then import to Unity as my first choice, this can do pixel level connection, but it seems to have better choice solely solved pixel level connection in Unity?

3.If I do it by generating the mesh during game play, then it could be complex especially it is hard to make elbow pipe mesh during runtime, or could you please advise me of some known library or package can do the work?

# Answer
> 1 votes
I think you are overthinking it. Usually this type of games have pipes that are taking 1x1 space, even if your visual representation looks like a 0.1x1 pipe, the player can normally rotate them, right? But never place them too close to each other, there is always a good space between them. So all you have to do now is snap your pipes to a grid since each piece has the same length and width.

I would not generate them on the fly but model a few pieces that you then use a prefabs. You need a corner, a straight, a t-crossing and a 4-way crossing. Maybe a deadend. Since you created them before, you can be sure that they are pixel perfect matching.

On your gameplay when the player drops a pipe, you check the x/y of the element and snap it to the next grid space, you overlap normally more than one place, you can pick the closer space by the difference in length between the center of your piece and the grid location center. It is always nice to give the player already the visual adjusted feedback where their tile is going to drop - like a shadow tile that gets displayed and the player knows immidiatly: if it stop dragging, my tile would be placed there.

Don't worry about the amount of prefabs, we are talking about how many? 100-200? That is nothing for a scene, even on mobile.

---
Tags: unity
---


# Question
Title: How to change player objects when switching scenes?
I have a scene for lobby. When player connects to server he gets a lobbyCharacter, which is an empty gameobject with a script on it that create UI element with the players name. In lobby players can select character they want to use.

Now when starting game, i would like to switch scene to the game scene when all players are ready. I have been reading the API, documentation, and different stack questions, but i cant seem to find any info on how this should work. On NetworkManager i can do scene schange which will be changed on all clients. But how do i persist data over multiple scenes? And if the lobby characters are destroyied how are the game characters instansiated according to the choises made in lobby? How does the client connection persist between multiple scenes?

Do i just manage the character locally and use syncHooks to synchronize over the server? Do i need to create somesort of container gameobject that holds the player connection information and some extra stuff?

EDIT

Reading the soruce code of mirror i fouind that NetworkManager holds the connection of the client, sort of. So now the issue has come down to replacing the prefab for the connection.

I have the following code:

```
 public void switchScene()
    {
        GameObject obj = NetworkClient.connection.identity.gameObject;

        NetworkServer.ReplacePlayerForConnection(NetworkClient.connection, Instantiate(shipPrefab));

        NetworkServer.Destroy(obj);
        ServerChangeScene(gameScene);
    }

```

This should switch the prefab for connection and then switch scene, but i keep getting error

```
InvalidCastException: Specified cast is not valid.
Mirror.NetworkIdentity.SetClientOwner (Mirror.NetworkConnection conn) (at Assets/Mirror/Runtime/NetworkIdentity.cs:362)
Mirror.NetworkServer.InternalReplacePlayerForConnection (Mirror.NetworkConnection conn, UnityEngine.GameObject player, System.Boolean keepAuthority) (at Assets/Mirror/Runtime/NetworkServer.cs:837)
Mirror.NetworkServer.ReplacePlayerForConnection (Mirror.NetworkConnection conn, UnityEngine.GameObject player, System.Boolean keepAuthority) (at Assets/Mirror/Runtime/NetworkServer.cs:697)
LobbyManager.switchScene () (at Assets/LobbyManager.cs:51)

```

And i dont understand why this is happening. New prefab has networkIdentity and networkTransform. Old prefab only has network transform. Up until this point everything wors, but once i want to switch scenes, it breaks.

# Answer
Had the same issue. You will have to get a `networkbehaviour` on your player with `GetComponent` and take the `connectionToClient`. Only works when your `switchScene()` is running on the server, obviously.
> 1 votes

---
Tags: unity, mirror-networking
---


# Question
Title: How to create a 2D tile-map in python ASCII style
Still learning about python programming and I wanted to create a little map like below but the thing is I know a for loop will draw down not draw across. However, I want to change the size of the area and add new tiles later on. I understand that this might be a really bad question but I cannot wrap my head around this.

```
posX = 0
posY = 0

tile1 = 'X'
tile2 = 'O'

width = int(12)
height = int(9)

'''

<--- 12 --->
XXXXXXXXXXXX ^
XOOOOOOOOOOX |
XOOOOOOOOOOX |
XOOOOOOOOOOX
XOOOOOOOOOOX 9
XOOOOOOOOOOX
XOOOOOOOOOOX |
XOOOOOOOOOOX |
XXXXXXXXXXXX v

'''

#Draws down and across
for i in range(width):
    print(tile1 * width)

```

# Answer
> 1 votes
You can split it on three elements and only one need `for`-loop

1. Top line `XXXXXXXXXXXX`

```
print(tile1 * width)

```
2. Middle lines `XOOOOOOOOOOX`

There will be `height-2` lines and they will have `"X"`, next `"O" * (width-2)`, next `"X"`

```
for i in range(height-2):
    print(tile1 + (tile2 * (width-2)) + tile1)

```
3. Bottom line `XXXXXXXXXXXX`

```
print(tile1 * width)

```

Code:

```
posX = 0
posY = 0

tile1 = 'X'
tile2 = 'O'

width = 12   # no need `int()`
height = 9   # no need `int()`

# top line

print(tile1 * width)

# middle lines

for i in range(height-2):
    print(tile1 + (tile2 * (width-2)) + tile1)

# bottom line

print(tile1 * width)

```

---

**EDIT:**

To make it useful put all lines on list - i.e `all_lines` \- using `append()` instead of `print()`. But keep every line as list of chars instead of string with all chars (I will use `[ ]` in code to do it).

It means

```
['X', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'X']

```

instead of

```
XOOOOOOOOOOX

```

And then you can easily replace elements

```
all_lines[1][1] = '@'

```

where you have positions `[Y][X]` not `[X][Y]` \- `all_lines[Y][X]` or in other words `all_lines[row][col]`

```
posX = 0
posY = 0

tile1 = 'X'
tile2 = 'O'

width = 12   # no need `int()`
height = 9   # no need `int()`

all_lines = []

# top line

all_lines.append([tile1] * width)

# middle lines
for i in range(height-2):
    all_lines.append([tile1] + ([tile2] * (width-2)) + [tile1])

# bottom line

all_lines.append([tile1] * width)

print(all_lines)

```

and this gives 2D list

```
[
  ['X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'],
  ['X', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'X'],
  ['X', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'X'],
  ['X', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'X'],
  ['X', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'X'],
  ['X', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'X'],
  ['X', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'X'],
  ['X', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'X'],
  ['X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X']
]

```

and you can display it using `for`-loop and `"".join()`

```
for line in all_lines:
    print("".join(line))  # <-- join list of chars to one string and display it

```

Result with `@`

```
XXXXXXXXXXXX
X@OOOOOOOOOX
XOOOOOOOOOOX
XOOOOOOOOOOX
XOOOOOOOOOOX
XOOOOOOOOOOX
XOOOOOOOOOOX
XOOOOOOOOOOX
XXXXXXXXXXXX

```

---

**EDIT:**

To work with map you can also use other `for`-loop

```
for y in range(height):
    for x in range(width):
        print(all_lines[y][x], end='')  # draw without going to new line
    print()  # go to new line

```

and then you can use it with extra `if/else` to test or change elements

```
for y in range(height):
    for x in range(width):
        if all_lines[y][x] == '@':
           all_lines[y][x] = '%'
        #print(all_lines[y][x], end='')
    #print()

```

You can also use more Pythonic method with enumerate

```
for y, line in enumerate(all_lines):
    for x, item in enumerate(line):
        if item == '@':
           all_lines[y][x] = '%'  # it has to replace in original `all_lines`
        #print(item, end='')
    #print()

```

---
Tags: tilemap, python, rpg
---


# Question
Title: How can I programmatically add a Controller to an Animator during runtime?
I am trying to set the Controller of an Animator during runtime using a script.

When I click on the dot in the inspector manually, I can choose one called "Standard Walk", but have not found a way to automate it.

# Answer
> 1 votes
You should be able to swap out controllers at runtime by changing the animator's `runtimeAnimatorController` property.

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


# Question
Title: Prevent weapon from clipping during animations
I am trying my ways with Unity 3d animations, and so far so good.

The only problem is, when I equip an weapon in the player model's hand, the weapon clip through player's head during some frames of some animations. Please refer to the gif and the screenshot below for an example.

Here you can see that the top of the bow is clipping through the player head during the arrow fire animation.

Here you can see a demonstration gif of the problem.

I've been thinking and I will probably need to adjust the weapon rotation/position so it fits the animations, right?

# Answer
> 3 votes
Your characters have very deformed proportions. It seems like you took an animation designed for a character with more realistic proportions and retargeted it. Animation retargeting generally only gives you good results for characters with very similar proportions. When the characters are too different, then you usually get better results if you redo their animations from scratch.

When you have characters with deformed proportions, you need to design your animations in a way which accounts for those proportions. The physique of a character affects the way it moves. Your characters look super cute, even without textures. But they are simply physically unable to perform the same motions a character with realistic proportions could perform, at least not in the same way.

And even if some animations sort of work without clipping, they might not necessarily be appropriate for the general look and feel of the character. Animating chibi-characters can be a lot of fun, because you can really exaggerate their motions and body language. And it would be a shame to not make any use of this creative potential.

I am looking forward to playing with those characters in their finished form.

# Answer
> 0 votes
This works in some cases:

* You can modify the weight of bones that rotate too much by changing the animation layer Weight at the time where your problematic animations start and reset it back to 1 when you go back to animations that works with no problem
* You can also configure your avatar to set limits to rotations of bones that cause the clipping

---
Tags: unity, animation
---


# Question
Title: Can I legally modify the Unity splash to fit the game's theme?
I've been working on a retro game, and I was wondering whether I could change the Unity logo to make it fit the game's style (eg. pixelating the logo).

I know how to do this, but my question is whether it is illegal, assuming I have a Plus, Pro, or Enterprise licence for Unity that allows me to edit this splash screen at all.

# Answer
As covered in the existing questions here and here, you may only customize or remove the Unity splash screen if you have a Unity Plus, Pro, or Enterprise licence. If you're using the free version of Unity, then legally you must leave the splash screen as-is. (Even if you have a clever workaround that lets you change the data without the Unity editor offering you that option, it's still a violation of the EULA)

Assuming you have a licence from Unity allowing you to modify this splash screen, your treatment of Unity's trademarks is still governed by the published Guidelines for Using Unity Trademarks and Style Guide for Permitted Uses.

Since Unity may choose to update these documents at any time, I won't try to reproduce the full rules here in this answer. Just be aware that this type of brand guideline tends to include...

* Minimum spacing between the mark and other content.
* Not presenting the mark in a way that implies authorship, ownership, endorsement, or sponsorship of your product by Unity.
* Not filling the mark with gradients, images or textures, or changing it from filled to stroked.
* Not putting the mark over a noisy background image.
* Not distorting the mark.
* Not re-arranging the mark and logotype outside the provided options.

Currently the published guidelines state:

> **Use official, unmodified Unity Logos.** Each Unity Logo is an artistic asset. As such, you may only use those Unity Logos from the download source indicated to you by Unity or reproductions of master artwork provided by Unity, and you must follow any Unity Logo style guide made available by Unity. The Unity Logos may not be altered or modified in any way, including by changing the colors, changing the font, applying strokes, rearranging elements of the design, or stretching/distorting. Nor may Unity Logos be animated. Clear and consistent use is required.

I'd argue that pixelating the mark constitutes "modifying it in any way" and so would be forbidden. Unity would be within their rights to ask you not to use their mark in a way that breaks the above rules (though you could choose to simply omit the logo / splash screen entirely).

You can try negotiating alternative terms with Unity if you want to do something outside the ground rules they have set. It's always possible for them to issue you a customized licence if they're happy with the presentation you propose.
> 1 votes

---
Tags: unity, licensing
---


# Question
Title: Unreal Engine 4 - Error in Macro Syntax Causes Build to Hang
# Problem

Errors in macro syntax causes the module's build to hang for 2+ hours (possibly, indefinitely) with no indication of a build error.

## Steps to Reproduce

1. Create a template game project in the editor.
2. Introduce the following macro into some C++ code:

```
UE_LOG(LogTemp, WrongVerbosityTypeHere, TEXT("Some Text Here"));

```
3. Trigger a module-only build e.g. right-click project \> Build.
4. Look for the following in the build output:

```
1>Using Visual Studio 2019 14.28.29335 toolchain (C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.28.29333) and Windows 10.0.18362.0 SDK (C:\Program Files (x86)\Windows Kits\10).
1>Building 4 actions with 32 processes...

```
5. The message should stay the same for 2+ hours. So wait for that long or until you feel something is wrong...
6. Remove or correct the macro usage with something like the following:

```
UE_LOG(LogTemp, Log, TEXT("Some Text Here"));

```
7. Trigger module-only build.
8. Build completes in seconds.

# Development Environment

* Windows 10 (Version 10.0.19042 Build 19042)
* Visual Studio Community 2019 (Version 16.8.3)
* Unread Editor 4.26 (Version 4.26.0-0+++UE4+Release-4.26)

# Questions

1. Is this a known bug?
2. If not, is there a configuration in UBT via Visual Studio or in the terminal to report errors quickly?

# Cross Postings

Unreal Engine Forums

# Answer
> -1 votes
A C macro is literally just text substitution, about half a step up from basic search-and-replace. The UE\_LOG macro is defined somewhere, providing a bit of code that the values you provide are substituted into, which then gets inserted into your code in the place of the UE\_LOG invocation you wrote out.

If putting an invalid value into the macro causes the build to hang, it's probably not an error with the macro, but with the compilation. The best course of action would be to file a bug report.

---
Tags: unreal-4, unreal, visual-studio
---


# Question
Title: How to prevent automation-type cheating?
Lets say I'm making an incremental game, (e.g. cookie-clicker-like). The premise of the game is simple: players send inputs that advance their game state. Players convert their own real-life time into progress in the game.

Obviously, players can cheat on the client-side, so to prevent this - the entire game logic happens on the server, and the client's only role is to render an interface that lets the players send their inputs to the server over the network. Thus, players can't take any actions that aren't allowed by the game's rules, because each action is validated on the server.

However, this still brings up a problem: what about this type of cheating:

Instead of playing the game manually, a player just writes a script that plays the game for them. They leave their PC running 24/7, and make progress in the game, all within the game's rules, but without using their own real-life time to play.

Obviously, this gives an edge over "legit" players that only play using the game's intended interface for committing actions.

Is there anything I can do to prevent this type of cheating, or is this a lost cause with no solution?

For the sake of this discussion, assume that the player that wants to cheat is able to easily reverse engineer the clientside code. For example lets say it's an HTML5 game with JS code, and that the cheater is smart enough to read minified code (which is not a far stretch at all). This means they can basically copy the code to their own machine, set up a server (with the JS example, setting up a Node.js server takes about 2 minutes), add a bit of their own code for the automation, and make their server send requests to my server with spoofed headers in a way that it pretends to be a regular user agent.

\[Edit\] in response to questions in the answers: The game has no player interaction, but there's an online scoreboard, and higher-ranking players get rewards; in other words, cheating is not isolated to the cheater's local machine, and cheating can ruin the experience for other players.

# Answer
The good news is that it's very difficult to design a bot/script that can fool *all* attempts to distinguish it from a real player.

The bad news is that it's very difficult to design a detection process that will catch *all* bots/scripts. And harder still to avoid catching legit but oddly-robot-like real players in the net.

So these systems end up being arms races between the cheaters and the developers, with the battle ebbing and flowing with the stakes at play. If cheaters can make real money by farming with bots, then expect to face a dedicated adversary. There are some strategies that can help though:

1. **Don't punish cheaters right away.**

This might sound counter-intuitive, but the closer your punishment comes after the offense, the more information you give to the bot-builder about what actions gave them away.

If they have a bunch of bots get blocked after their 10th time clicking on a particular in-game button, then they have a strong clue that there's a rate limit or position-of-click check (like Tom Tsagk suggests) in place there. So they build a bot with a slight randomization in how it clicks that button, and lo and behold it's not banned after the 10th click, so they know they've successfully defeated your detector, for now.

Instead, flag cheaters and let them go about their business for a few days, then ban bunches of them in big batches, so the ban isn't directly attributable to any one action. That keeps them guessing about how your detector really works, and means they have to run every experiment for days before they find out if their guess was right, slowing down their adaptation.

This also gives you more time to gather data on the suspected bot accounts. You can analyze this to find other tell-tale behaviours of the bots beyond what originally flagged them, so you can diversify your detection methods - letting you still catch the bot even if the original giveaway gets patched.
2. **Look for patterns**

Once you take this long-term view of cheaters, many more potential signals become available to you, like play schedules & frequencies of particular actions. Human players will occasionally sleep or put the game down for a minute - do your suspected bots? Human players will usually buy an upgrade pretty close to the time when they can afford it - do you have some accounts that build up large stockpiles overnight then go on a spending spree when their human wakes up?

Machine learning algorithms can be useful for identifying these types of patterns. Especially if a particular cheater uses the same script for a whole botnet for farming, or distributes their script, you'll have a group of accounts all playing exactly the same way (to within whatever randomization parameters the script uses), a cluster that stands out like a sore thumb to ML approaches.

You'll still want to keep the decision of which accounts to punish manual - use algorithms to highlight suspected cheaters, or assign them scores based on how many humanity tests they fail, but always keep a human in the pipeline who can inspect the data, spot new patterns, and override the algorithm when it's flagged an account believed/known to be a real (if curiously consistent) human.
3. **Use game design**

As ddyer points out, one of the most robust ways to protect your game against farming is to put limits on how much a player can do in a day. That way even someone with a perfectly undetectable bot can't do better than a human using their full action count / energy bar for the day.

(This also gives you an opportunity to monetize players to whom longer play sessions/faster progress is worth a microtransaction or two. Just ensure you're doing this honestly - being up-front about what value they get for their investment, and not abusing players' cognitive biases or gambling addictions)

The trick with this though is if your action caps are generous enough to not impinge on your most dedicated players, then there's still headroom for a more casual/occasional player to use a bot to fill-in the extra time & max-out their progress dishonestly. But we can find game design approaches to this too.

Consider including elements in your game that humans can perform easily, but scripts would have a harder time keeping up with - like an optional, time-limited bonus round every so often that involves clicking on a particular object in an image. You generate the image and check the click zone on your server, so a client-side script can't just peek under the hood to see where it's supposed to click, or memorize every image possibility. While still possible for a bot to solve, we've upped the programming challenge from emulating human clicks & timings to neural network computer vision, putting the bar for cheaters that much higher.

If you make the bonus round very profitable but optional, you help narrow the progression rate gap between humans who can do these bonus rounds easily, and bots that can't. You also get another useful signal to use in highlighting potential bots: are some accounts ignoring these super-profitable bonus opportunities? Or getting the very easy-for-a-human challenge wrong routinely? Maybe flag those accounts for additional inspection...
> 4 votes

# Answer
If players are not interacting with each other, I wouldn't suggest worrying about it too much, whatever a player does on their local copy, is their business. If they have this much knowledge to reverse-engineer and spend so much time to do it, let them.

If players are interacting with each other, the only solution is to detect "bot-like" behaviour and punish it. When a human plays the game, the input is "clumsy". Humans can't move a mouse on a perfect straight line, and when clicking the same button, it's very difficult to click the same pixel twice (assuming they moved their mouse in-between). You can take advantage of that, and if you detect "too many" very precise movements, then you know something is up.

There's a lot you can do code-wise, but be careful. Do not punish a player that is legit even if their actions look robotic. You can counter that by influencing the gameplay to be more active (at least the non-idle part).
> 2 votes

# Answer
Put an activity limit on your game. Think of it as enforcing bathroom/nutrition/sleep breaks. If you do this gently, real players won't even be aware that limits exist. If you want to be nasty about it, when limits are exceeded restart the next session where *this* session started.
> 1 votes

# Answer
Turn it around and make a game out of automating the game. Provide a scripting language players can use to write bots to play for them, and then rate the bots on things like CPU usage and code-length.

Why, yes, I have played a few Zachtronics games.
> 1 votes

# Answer
Modifying your reward design seems the best approach. If being at the top of the leaderboard is giving a player extra advantages that may just perpetuate the problem of power gap seen in most pay to win games out there. If the only way to stay on top is to be on top I'd consider that a design flaw.

Perhaps participation, mission, or milestone rewards would be better?
> 0 votes

---
Tags: anti-cheat
---


# Question
Title: Unity raycasting not always detecting component
I am trying to determine what object I am clicking with the help of a raycast, however it doesn't always work

In update I call:

```
if (Input.GetMouseButtonDown(0))
{
    selectedObject = null;
    selectedUnits = new List<Unit>();
    Select(Input.mousePosition);
    startPos = Input.mousePosition;
}

```

which calls:

```
void Select(Vector2 screenPos)
{
    Ray ray = cam.ScreenPointToRay(screenPos);
    RaycastHit hit;
    //Debug.Log("1");
    if (Physics.Raycast(ray, out hit, 100))
    {
        OnClicked(hit.transform.tag);
        //Debug.Log("2");
        if (hit.transform.GetComponent<Unit>())
        {
            //Debug.Log("3");
            if (!selectedUnits.Contains(hit.transform.GetComponent<Unit>()))
            {
                //Debug.Log("4");
                selectedUnits.Add(hit.transform.GetComponent<Unit>());
            }
        }

        if (hit.transform.GetComponent<Building>())
        {
            if (hit.transform.GetComponent<Building>() != selectedObject)
            {
                selectedObject = hit.transform.gameObject;
            }
        }
    }
}

```

Detecting a "building" always works and is fine, but clicking on a "unit" works anywhere between 0 and 5 times per play session before it returns nothing anymore like the object doesn't exist. I have tried to find where it gets stuck and it gets stuck after the 2nd debug (debug 1 and 2 print but 3 and 4 do not).

This is the Unit in the inspector

and this is it in the hierarchy

When drawing the ray here you can see it hits the cube 3 times before it just passes right through the 4th time.

it seems like after each hit the ray penetrates the collider more and more

But how and why can it only hit it a couple of times before it passes through. After a certain amount of clicks with or without moving my mouse it just doesn't hit it anymore even though in the inspector nothing changes and there are no scripts that alter the box collider.

I hope someone knows what's going wrong, thanks!

# Answer
> 1 votes
The most likely problem is that you're hitting something else for whatever reason. You say that your debug log "2" is always going off. Instead of logging "2", try logging `hit.transform.name` instead. This would tell you what it is you're hitting. Then you'd have a much easier job of figuring out what's going wrong.

You can also use `Debug.DrawRay` to make sure the ray is being cast as you expect it to. (This is best used in a "split screen" mode with both the Game view and the Scene view open side by side.)

# Answer
> 0 votes
I have found the issue, apparently this issue is caused by having a rigidbody and a navmeshagent component simultaneously. Just remove the rigidbody and it works fine.

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


# Question
Title: Unexpected result when generating world with 2 perlin noises
I try to generate a world with a temperature and an humidity noise to generate biome based on the y values of the two. I take the y values and round them on a 33 base for the humidity and 25 for the temperature then add the two to get 12 possibilities of biome. to test it I first tried generating a chunk by assining the sum of humidity and temperature to their y location. I was expecting to get multiple platform at different height (12 possibilities of height) but I instead got this

even if it doesn't look like it, there are random patterns within the bigger layers. i don't understand why I got that result (which looks pretty sick not gonna lie). here is my script

```
const int seed = 50;
const int FREQUENCE = 100;
const int AMPLITUDE = 100;
const int size = 100;

int[] BIOME_DATA = { 0, 33, 66, 25, 58, 91, 50, 83, 116, 75, 108, 141 };

int[] temp_VERT = new int[100 * 100];
int[] hum_VERT = new int[100 * 100];
public int[] biome_VALUE = new int[100 * 100];

void Start()
{
    //generate the y values for the humidity vertices
    for (int x = (int)transform.position.x, i = 0 ; x < size+ (int)transform.position.x; x++)
    {
        for (int z = (int)transform.position.z; z < size+(int)transform.position.z; z++)
        {
            float y = Mathf.PerlinNoise((float)x+seed / FREQUENCE, (float)z / FREQUENCE) * AMPLITUDE;
            y = Mathf.Floor(y / 33) * 33;
            hum_VERT[i] = (int)y;
            i++;
        }
    }

    //generate the y values for the temperature vertices
    for (int x = (int)transform.position.x, i = 0; x < size+ (int)transform.position.x; x++)
    {
        for (int z = (int)transform.position.z; z < size+ (int)transform.position.z; z++)
        {
            float y = Mathf.PerlinNoise((float)x-seed / FREQUENCE, (float)z / FREQUENCE) * AMPLITUDE;
            y = Mathf.Floor(y / 25) * 25;
            temp_VERT[i] = (int)y;
            i++;
        }
    }

    //assigne une valeur représentant un biome pour chaque vertex
    for(int i = 0; i < biome_VALUE.Length; i++)
    {
        biome_VALUE[i] = System.Array.IndexOf(BIOME_DATA, (hum_VERT[i] + temp_VERT[i]));
        //biome_VALUE[i] = new Vector2(temp_VERT[i],hum_VERT[i]);
    }

    GenerateChunk(biome_VALUE);
}

void GenerateChunk(int[] Y_VERTICES)
{
    Mesh meshy;
    MeshRenderer meshRenderer = GetComponent<MeshRenderer>();
    meshRenderer.sharedMaterial = new Material(Shader.Find("Standard"));
    MeshFilter meshFilter = gameObject.GetComponent<MeshFilter>();

    Vector3[] VERTICES = new Vector3[Y_VERTICES.Length];
    List<Vector2> UV = new List<Vector2>();
    List<int> TRIANGLES = new List<int>();
    List<Vector3> NORMALS = new List<Vector3>();

    meshy = new Mesh();

    //création des Vecteur
    for (int i = 0, x = 0; x < size; x++)
    {
        for (int z = 0; z < size; z++)
        {
            VERTICES[i] = new Vector3(x+transform.position.x, BIOME_DATA[Y_VERTICES[i]], z+transform.position.z);
            i++;

        }
    }

    //création des normales
    for (int i = 0; i < VERTICES.Length; i++)
    {
        NORMALS.Add(-Vector3.forward);
    }

    //création des triangles
    for (int x = 0; x < size - 1; x++)
    {
        for (int z = 0; z < size - 1; z++)
        {
            int i = size * x + z;
            TRIANGLES.Add(i);
            TRIANGLES.Add(i + 1);
            TRIANGLES.Add(i + size);
            TRIANGLES.Add(i + size + 1);
            TRIANGLES.Add(i + size);
            TRIANGLES.Add(i + 1);
        }
    }

    //création des uv
    for (int i = 0; i < VERTICES.Length; i++)
    {
        UV.Add(new Vector2(VERTICES[i].x, VERTICES[i].z));
    }

    //assignation des valeurs
    meshy.vertices = VERTICES;
    meshy.triangles = TRIANGLES.ToArray();
    meshy.uv = UV.ToArray();
    meshy.normals = NORMALS.ToArray();
    meshFilter.mesh = meshy;
}

```

}

# Answer
> 0 votes
According to the doc Mathf.PerlinNoise returns a value between 0.0 and 1.0. You multiply it by AMPLITUDE which is 100. So if you divide it by 33, you get values between 0 and 3. This is what we see in the picture.

Instead, do not multiply by AMPLITUDE and calculate

```
float y = Mathf.PerlinNoise(...);
hum_VERT[i] = (int)(33f * y);

```

Note that casting a `float` to `int` truncates the value. Therefore a call to `Mathf.Floor` is not required.

Be careful with the perlin noise values. The doc also says *"Return value might be slightly below 0.0 or beyond 1.0"*. This might lead to an index out of bounds exception somewhere else. If this happens, I suggest writing

```
hum_VERT[i] = Math.Min(32, Math.Max(0, (int)(33f * y)));

```

Assuming that the valid index range is 0 to 32 (inclusive).

---

Here is a good tutorial for Noise, being a pseudorandom artist

---
Tags: unity, c#, 3d, mesh, world-design
---


title: How to get last 20 banned Steam IDs

text:
# Question
Title: How to get last 20 banned Steam IDs
I am working on a cheat analysis system using data from Steam. From this page, we can get the last 20 checked Steam IDs. Is there a way to get the last 20 **banned** Steam IDs?

VacList has a section with the last banned accounts, but I don't know how to extract the data. A solution like that provided by `vacbanned.com` would be much better.

# Answer
According to the information posted on the Steam Web API, Steam doesn't provide a way to get the last 20 banned Steam IDs.

`GetPlayerBans` takes a comma-delimited list of SteamIDs as input & returns the Community, VAC, and Economy ban statuses for given players of the SteamIDs.

Based on that, I suspect the listings you mentioned are aggregates of data they've pulled from Steam. For example, they might be listing the last 20 banned accounts out of all the accounts they've checked. Or the 20 bans they've found that where most recently enacted.

You might be able to get the data from one of the other sites you've mentioned, but I didn't see any APIs provided by either VacList or Vacbanned. You could contact them to see if they would be willing to share that information.

Automating the extraction of their content (scraping) and the legality thereof, isn't something I feel qualified to speak about beyond noting that it isn't on topic for game dev.
> 0 votes

---
Tags: steam, anti-cheat, valve
---


# Question
Title: How to make the character move along the axis using touch?
I have the following code it works, but I don't know how it works.

This is the code I found:

```
void Update()
{
#if UNITY_ANDROID

    if(Input.touchCount>0 && Input.GetTouch(0).phase == TouchPhase.Moved )
    {
        Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;
        float offset = touchDeltaPosition.x * 40f / 18 * Mathf.Deg2Rad;
        transform.position += new Vector3(0f, 0f, offset);
        transform.position = new Vector3(0f, 0f, Mathf.Clamp(transform.position.z, -7.1f, 7.1f));
    }
#endif
}

```

I need to move the player along the axis by touch, for example, like in the game Cube Surfer!

What I want to get (I used android emulator):

The code I wrote works well at 720x1280, but if you set the resolution to 1440x2960, the controls become too sharp. I know why this is happening because touch.delta is getting too big.

My code:

```
if (Input.touchCount > 0)
{
    var t = Input.GetTouch(0);

    var delta = t.deltaPosition;

    if (delta != Vector2.zero)
    {
        var offset = transform.position;

        offset.x += delta.x * Sensitivity * Time.deltaTime;

        offset.x = Mathf.Clamp(offset.x, -4f, 4f);

        transform.position = offset;
    }
}

```

How to fix it?

ScreenToWorldPoint this does not fit because the player moves along a spline.

Thank for help

# Answer
Try multiplying your offset by your aspect ratio: `Screen.width / Screen.height`.

```
if (Input.touchCount > 0)
{
    var t = Input.GetTouch(0);

    var delta = t.deltaPosition;

    if (delta != Vector2.zero)
    {
        var offset = transform.position;

        offset.x += delta.x * Sensitivity * ((float) Screen.width / Screen.height) * Time.deltaTime;

        offset.x = Mathf.Clamp(offset.x, -4f, 4f);

        transform.position = offset;
    }
}

```

Note: you may need to adjust your sensitivity.
> 1 votes

# Answer
You are using `Mathf.Clamp` to prevent it from going out of bounds. You can use it as well to restrict the speed

```
offset.x += Mathf.Clamp(delta.x * Sensitivity, -_MaxSpeed, _MaxSpeed) * Time.deltaTime;

```

\_MaxSpeed is something you would need to figure out until it matches your gameplay.
> 0 votes

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


# Question
Title: Why isn't my tilemap collider appearing?
I am trying to make a 2d game but my player falls through the tilemap every time.

My tilemap collider doesn't seem to show up.

What is going on and how do I fix this?

The first image is rigidbody currently falling through the tilemap and the tilemap. The second image is rigidbody currently falling through the tilemap and the rigidbody.

# Answer
The issue is with the sprite itself

to fix I clicked the sprite copy that unity creates whenever you first import a sprite went to collider type and selected grid. this allowed the tilemap collider to work on the white block and any new tiles painted
> 1 votes

---
Tags: unity, tilemap, collider
---


title: pick up material from another object

text:
# Question
Title: pick up material from another object
is it possible to obtain a material from another object? I'm trying everything and nothing, the only thing I could get was just the color of another object

```
public MeshRenderer takematerial;
public GameObject[] Objects;
for (int i = 0; i < Objects.Length; i++) {
    Objects [i].GetComponent<Renderer> ().material = takematerial.material;
}

```

# Answer
You need to reach or interact with the target object, by raycast, tag, collision, etc, it doesn't matter:

```
GameObject targetObj=GameObject.FindWithTag("Player");

Material targetMat = targetObj.GetComponent<Renderer>().material;
//Creates  a copy of the first material of the object,unique to this renderer, if it had been a shared asset previously.

targetMat.color=Color.red;
//Now targetMat referencing targetObjects renderer first material.

```
> 0 votes

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


title: How to render metaballs?

text:
# Question
Title: How to render metaballs?
How to render metaballs?
I am a Python programmer familiar with the Panda3d and Blender3d APIs. My math kinda sucks, but I know enough to write game logic code and procedural model generation code, as well as importers/exporters for the 3d modeller Blender. So you kind of get my level of experience. So can anyone explain or link to a tutorial which explains what needs to be done, without advanced math or with mentioning what math concepts are needed?

This is what I want to achieve:

http://www.youtube.com/watch?v=dEipENLes10
http://www.dailymotion.com/video/xn3xfn\_mercury-meltdown-psp-un-trailer-pour-mercury-meltdown\_videogames?search\_algo=2

Though with probably more metaballs on screen at the same time.

# Answer
One option is to use Marching Cubes. There are plenty of tutorials and example code in the Internet such as this. Implementing this is not very easy, but doable.

Thanks to the increased power of computers and especially GPUs, raycasting has also become a fast enough solution for rendering metaballs and other surfaces. Check for example this tutorial. This should be easier to implement. The downside is that it might not fit to the rest of the 3D engine as well as polygonizing the metaballs.
> 7 votes

# Answer
Unfortunately, 'without advanced math' is a fairly high bar to set for this particular tutorial, because the topic is inherently fairly advanced; metaballs are just a more colloquial way of talking about a particular type of *isosurface visualization*. The simplest way to conceptualize it may be to imagine taking everything down a dimension; imagine that you're working on a plane (or technically the surface of a sphere) rather than in space, and consider a classic heightmap; then the coastline of the terrain represents one isosurface: it's the set of all the points on the map where the height (the elevation above sea level) is zero. Now, suppose that you had a bunch of elevation data and you were asked to draw coastlines. One approach would be to (somehow) find *one* spot along a coast and then 'follow that coastline' until you get back to your original point — but that requires you to find that first point, and when you complete your loop you can't be sure whether you've missed anything (imagine tracing the coast of England and entirely missing Ireland in the process).

Instead, you might try an approach where you scan over your map pixel by pixel, looking for spots where you have two adjacent points, one above water and one below, and then carefully drawing a line that cuts between the two, somehow making it match up from pixel to pixel. The generalization of this idea from two to three dimensions is commonly known as the *marching cubes* method, and it's the most common algorithm for rendering isosurfaces; things are somewhat more complicated in the 3d case than in 2d (since you effectively have 256 cases, one for each of the 28 possible assignments of 'above surface' and 'below surface' to the vertices of a voxel), but the core ideas are the same. Note that even pretty low resolutions on your grid can give good results for this; the demo you linked to is probably running the Marching Cubes algorithm on a 32x32x32 (or likely even 16x16x16) grid and it looks perfectly reasonable doing so.

This leaves open the question of just what your heightfield is, of course — I don't have time to go into that side of things right now (although some searching should find you a handful of different potential functions), but I'll try and flesh this answer out a bit later to give some of the details on that front too.

Of course, because you're essentially dealing with n3 pieces of data (the values on an n x n x n grid) then even fairly low grid resolutions can get expensive pretty fast. With the right potential function, though, you can use *interval arithmetic* to bound the values of your potential function on larger chunks of space and cut down on the number of actual calculations you have to do; essentially, this is applying octree-style spatial partitioning to the metaball problem.
> 1 votes

# Answer
There is another quite impressive solution for this problem using GPU based raycasting approach together with Depth Peeling and Bezier Clipping algorithms.

Implementation is not straightforward but performance is worth it. Please check the white-paper.

Not sure if Python is good idea for such problem since is more related to shader programming.

If you still interesting we can collaborate together to solve this problem. I suggest to use tooling like Godot, Unity or Unreal
> 0 votes

---
Tags: 3d, mathematics, procedural-generation, python, panda3d
---


# Question
Title: Attempt to fix sprite sheet pixel bleeding in OpenGL 2D causing sprite distortion
While working on a project, I encountered the common problem of pixel bleeding when trying to draw subregions of my sprite sheet. This caused sort of "seams" to appear at the edges of my sprites. You can see the issue here, on the right and top of the sprite .

Doing some searching, I found others with a similar problem, and a suggested solution (here, and here for example) was to offset my texture coordinates by a bit, such as 0.5. I tried this, and it seemed to work. But I have noticed that sometimes, depending on where the sprite or camera is, I get a bit of distortion on the sprites. Here, the left side appears to be cut off, and here, the bottom seems to have expanded. (I should note, the distortion happens on all sides, I just happened to take screenshots of it happening on the bottom and left.) It may be a little difficult to see in screenshots, but it is definitely noticeable in motion. For reference, here is the part of the sprite sheet that is being displayed here

Does anybody have any idea what is going on here? I didn't actually notice this issue until recently. I originally set out to resolve the pixel bleeding when I saw it occurring between my tile sprites. This new issue does not occur with them using my current half-pixel offset solution (or if it does, it's not noticeable).

Code:

Texture parameters

```
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

```

Texture coordinate calculation

```
std::vector<glm::vec4> Texture2D::GetUVs(int w, int h)
{
std::vector<glm::vec4> uvs;
int rows = Width/ w;
int columns = Height / h;

for(int c = 0; c < columns; c ++)
{
    for(int i = 0; i < rows; i ++)
    {
        float offset = 0.5;
        uvs.emplace_back(glm::vec4(float(((i) * w + offset))/Width,
                              float(((1 + i) * w - offset))/Width,
                              float(((c) * h + offset))/Height,
                              float(((1 + c) * h - offset))/Height));
    }
}
return uvs;

```

Where Width and Height are the dimensions of the sprite sheet, and w and h are the dimensions of the subregion, in this case 32 and 32.

How I pass the uvs to the shader

```
GLfloat verticies[] =
{
    uv.x, uv.w,
    uv.y, uv.z,
    uv.x, uv.z,

    uv.x, uv.w,
    uv.y, uv.w,
    uv.y, uv.z
};

this->shader.Use().SetVector2fv("uvs", 12, verticies);

```

Where uv is the uv at an index in the uvs vector that was returned above in the GetUVs function.

Vertex shader

```
#version 330 core
layout (location = 0) in vec2 vertex;

out vec2 TextureCoordinates;

uniform vec2 uvs[6];
uniform mat4 model;
uniform mat4 projection;

void main()
{
    const vec2 position [6] = vec2[]
    (
        vec2(0.0f, 1.0f),
        vec2(1.0f, 0.0f),
        vec2(0.0f, 0.0f),

        vec2(0.0f, 1.0f),
        vec2(1.0f, 1.0f),
        vec2(1.0f, 0.0f)
    );

   TextureCoordinates = uvs[gl_VertexID];
   gl_Position = projection * model * vec4(position[gl_VertexID], 0.0, 1.0);
}

```

Fragment shader

```
#version 330 core
in vec2 TextureCoordinates;
out vec4 color;

uniform sampler2D image;
uniform vec4 spriteColor;

void main()
{
    color = vec4(spriteColor) * texture(image, TextureCoordinates);
}

```

Thanks for reading. I have asked this question a few places and not gotten any response, so any help is greatly appreciated.

# Answer
In case anyone ever has a similar problem and finds this, I was able to find a very simple solution. The issue occurs when attempting to render at non-whole numbers, so the solution is to simply insure that that never happens. Right before I render, I round the position of the sprites and my camera to whole numbers. An example of my render function:

```
void DrawSprite(Texture2D &texture, glm::vec2 position, float rotate, glm::vec2 size)
{
    glm::mat4 model;
    position.x = round(position.x);
    position.y = round(position.y);
    model = glm::translate(model, glm::vec3(position, 0.0f));

    //the rest of the model transforms
    //pass the model transform to the shader
}

```

There is still potentially an issue of either bleed or deforming when rotating sprites, but that is a separate problem.
> 1 votes

---
Tags: opengl, c++
---


title: Determining first voxel ray intersects

text:
# Question
Title: Determining first voxel ray intersects
I'm trying to implement the Fast Voxel Traversal Algorithm on a uniform grid of axis-aligned rectangles. Having read the paper, I understand how the traversing works, but not the initialization. I've looked around and I did find a readme that overviews the algorithm, but I fail to see how the derive how to determine the index in a data structure (such as an array) that corresponds to the first voxel the ray intersects.

Using the construct presented in the readme, assuming the grid is 2x2 and stored in (going to use Python) an list like so:

```
+--------+--------+
|        |        |
|        |        |
|  0, 1  |  1, 1  |
|        |        |
|        |        |
+--------+--------+
|        |        |
|        |        |
|  0, 0  |  1, 0  |
|        |        |
|        |        |
+--------+--------+

grid = [[(0, 0), (1, 0)],
        [(0, 1), (1, 1)]]

```

In the overview, the compute `r2 = r` and resolve `t = 27/32`, but I fail to see how they translate that to the index `grid[0]`.

Some other resources I've used to try and understand:

# Answer
Short answer: rounding down.

Long answer:

> The ray in the image above might be represented as `r = u + tv` where `u = <0,-3/4>` and `v = <1, 8/9>`, i.e. r follows the line `y = (3/4)+ (9/8)x`.

Note: that is a typo, it should read `y = (3/4)+ (8/9)x`.

> Thus, `ray.origin.x = 0` and `ray.origin.y = -3/4`.

We can start from these terms: `y = y₀ + mx`. The ray crosses the vertical axis at `y₀`, and has a slope of `m`. Now, the vector `u` would be `(0, y₀)` which is the point where the ray crosses the vertical axis. And the vector `v` would be `(1, m)`.

Constructing the ray in this fashion we would always have `1` on the horizontal axis of `v`. Which would prevent us from representing a vertical ray. Also, `v` is not normalized. However, this poses no problem for our purposes.

---

> Based on grid (given at initialization) we know that
>
> ```
> grid.corners =   [(0,0),(0,2),
>                   (2,2),(2,0)];
>
> ```

Here we are defining a rectangle that contains the whole grid. We want to know where the ray enters the rectangle.

> Thus, we can determine the boundary at which `r` intersects the grid. In particular, we see the `y = 0` boundary of the grid is represented by the vector `r2 = <0,0> + <1,0>t`;

At `y = 0`, there is a boundary of the rectangle that contains the grid. That boundary starts at `(0, 0)` and ends at `(2, 0)`. We can create a second ray line that corresponds to the boundary. That second ray line `r2`. The second ray starts at `u2 = (0, 0)`, and `v2` would be `(1, 0)`.

> solving for `r2 = r` yields `t = 27/32`.

That is, we find the point where the two rays intersect. We can easily check the particular solution:

```
r2 = r
<0,0> + <1,0>t = <0, -3/4> + <1, 8/9>t
<0,0> - <0, -3/4> = <1, 8/9>t - <1,0>t

=>

0 = 0t
3/4 = (8/9)t

=>

3*9 = (4*8)t
27 = 32t
27/32 = t

```

Note: We discarded the not useful `0 = 0t`.

This is not a general approach. It works thanks to both rays using the horizontal axis as parameter. And we were able to discard `0 = 0t`, which is not always the case.

---

I'll go ahead and find a general solution:

```
r(t) = r2(t2)
u + tv = u2 + t2v2

u.x + tv.x = u2.x + t2v2.x
u.y + tv.y = u2.y + t2v2.y

u.x + tv.x = u2.x + t2v2.x
u.x - u2.x + tv.x = t2v2.x
(u.x - u2.x + tv.x)/v2.x = t2
(u.x/v2.x) - (u2.x/v2.x) + t(v.x/v2.x) = t2

u.y + tv.y = u2.y + t2v2.y
u.y + tv.y = u2.y + ((u.x/v2.x) - (u2.x/v2.x) + t(v.x/v2.x))v2.y
u.y + tv.y = u2.y + (u.x*v2.y/v2.x) - (u2.x*v2.y/v2.x) + t(v.x*v2.y/v2.x)
u.y + tv.y - t(v.x*v2.y/v2.x) = u2.y + (u.x*v2.y/v2.x) - (u2.x*v2.y/v2.x)
tv.y - t(v.x*v2.y/v2.x) = u2.y + (u.x*v2.y/v2.x) - (u2.x*v2.y/v2.x) - u.y
t(v.y - (v.x*v2.y/v2.x)) = u2.y + (u.x*v2.y/v2.x) - (u2.x*v2.y/v2.x) - u.y

t = (u2.y + (u.x*v2.y/v2.x) - (u2.x*v2.y/v2.x) - u.y)/(v.y - (v.x*v2.y/v2.x))
t = (u.x*v2.y - u.y*v2.x - u2.x*v2.y + u2.y*v2.x)/(v.y*v2.x - v.x*v2.y)

```

---

Thus:

```
t = (u.x*v2.y - u.y*v2.x - u2.x*v2.y + u2.y*v2.x)/(v.y*v2.x - v.x*v2.y)
t = (0*0 - (-3/4)*1 - 0*0 + 0*1)/((8/9)*1 - 1*0)
t = (3/4)/(8/9)
t = (3/4)*(9/8)
t = (3*9/4*8)
t = 27/32

```

let us figure out the coordinates:

```
p = r(t)
p = <0,-3/4> + <1, 8/9>t
p = <0,-3/4> + <1, 8/9>(27/32)
p = <0,-3/4> + <27/32, (8/9)*(27/32)>
p = <0,-3/4> + <27/32, 3/4>
p = <27/32,0>

```

Since we had constructed the ray with `v = (1, m)` the solution point is simply `(t, 0)`. The approach above is not limited to such cases.

On the other hand, if we construct vertical rays with `v = (0, 1)` we will find other optimizations for such case.

---

> Thus, at the annoying value of `t = 27/32`, the ray `r` will intersect the boundary of the grid. Note that this value of `t` is the least such value of t for all boundary crossings.

Note: `27/32 = 0.84375`. Thus, the entry point on the grid is `<0.84375, 0>`which is on the cell (0, 0), as depicted on the image. We find that simply by rounding down (assuming the cell size is 1).

Now that you have a general formula, you can apply it for all the boundaries and find the one that yields the lowest `t` (`tMin`). The corresponding point is the point where the ray enters the grid.

You can define the four boundaries of the rectangle as follows:

```
r2(t) = <0, 0> + <1, 0>t
r3(t) = <0, h> + <1, 0>t
r4(t) = <0, 0> + <0, 1>t
r5(t) = <w, 0> + <0, 1>t

```

Assuming the grid has a corner at the origin, and `w, h` define the size of the grid (not the number of cells, but the length of the sides of the rectangle that contains the gird).

As you can see we have a lot of 0s, which will result in a lot of cancellations, which is room for optimization.
> 1 votes

---
Tags: collision-detection, algorithm, voxels, aabb, raytracing
---


# Question
Title: How to Make Organic Fade to Black in Unity
I'm working a retro/old-style video game, and I was wondering whether or not there is a way to create an organic fade-to-black, similar to what is found in the original NES console. I am aware of how to create a traditional fade-to-black screen, but it doesn't really fit the theme of my game. I'm using Unity 2019.4 LTS.

Here’s a example of a character about to exit the area and cause a fade to black:

Here’s what the organic fade looks like at 75% completion:

And here’s what a traditional fade looks like at 75% completion:

# Answer
> 1 votes
I'd start with changing brightness/contrast in post effect, there are many implementations for Unity available on the internet. As an example I just opened and modified image in paint.net:

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