# Question
Title: Unity: running GPU intensive operations in editor mode
I have written an erosion simulator that I want to execute from the editor (for generating terrain and such outside of play mode). Unfortunately, when I crank the parameters on my simulation, unity hangs. The UI becomes unresponsive, none of the menus work anymore. However, the process is still running - windows doesn't claim that the program is no longer responding.

The weird thing is that task manager claims that the GPU is sitting at zero utilization while Unity hangs. My (CPU side) erosion code looks something like this (executed via editor script):

```
    HydraulicCompute.SetFloat("_ErosionRadius", ErosionRadius);
    HydraulicCompute.SetBuffer(_erosionId, "HeightMap", heightMap);
    HydraulicCompute.SetBuffer(_erosionId, "Droplets", _dropletBuffer);

    int threadGroupsX = Mathf.CeilToInt(mapSize / 8.0f);
    int threadGroupsY = Mathf.CeilToInt(mapSize / 8.0f);
    for (int i = 0; i < 100; i++) {
        HydraulicCompute.Dispatch(_dropletId, Mathf.CeilToInt(_dropletBuffer.count / 1024.0f), 1, 1);
        HydraulicCompute.Dispatch(_erosionId, threadGroupsX, threadGroupsY, 1);
    }

```

When the size of the `_dropletBuffer` is bigger than 12,000 (32 bytes per droplet), and the `heightMap` buffer larger than `1024x1024` (4 bytes per pixel), then I run into the aforementioned problem.

I would guess that the issue occurs either because there is a problem with the buffer sizes, or that the frame takes too long and Unity times out.

When I comment out the `Dispatch` calls Unity is able to allocate and populate the buffers instantaneously (at least it looks really quick). While that doesn't rule out the potential buffer problem, it certainly makes it seem less likely.

So what exactly is the problem here? Is it a memory problem? Or is the frame timing out? Or something else entirely?

Is there a prescribed way to doing this kind of intensive GPU work in the background in editor mode? I've looked at the Job system, but that seems to be CPU side only...

\[EDIT\]

I have managed to put together the following snippet which *always* crashes on my GPU (NVIDIA 980ti):

```
[numthreads(1,1,1)]
void CSMain(uint3 id : SV_DispatchThreadID)
{
    for (int i = 0; i < _NumIterations; i++) {
        HeightMap[1024*512 + 512] = 0;
    }
}

```

When executed as 1 thread group for 1 iteration (`_NumIterations = 1`), this crashes my GPU driver. I am running on the latest version. I have no idea as to what might be causing the problem, windows event viewer just lists a `nvlddmkm` error, which apparently means it could be just about anything. It's frustrating to say the least.

# Answer
> 1 votes
I found a possible reason and it works in my case.

There's a feature names "Timeout Detection and Recovery(TDR)" on Windows since Vista. And what TDR do is assume a crash and reset the graphics card's driver if the graphics card does not respond within a certain time frame. The default TDR time is about 2 seconds, it's easy to exceed that limit when using GPGPUS like CUDA and compute shader.

There are 2 solutions according to the cause of the problem:

1. **Divide the task into several subtasks**. Means if there's a ComputeShader.Dispatch() performs 100 cycles, you can do ComputeShader.Dispatch() 10 times and 10 cycles each time. This is the way I finally used.
2. **Increase the TDR delay time by modifying the corresponding registry entry**. Run the command "regedit", navigate to "HKEY\_LOCAL\_MACHINE -\> SYSTEM -\> CurrentControlSet -\> Control -\> GraphicsDrivers" where you can create a key of type "DWORD" and name it "TdrDelay" taking the delay time as an argument. Restart your computer.

There is a link to the introduction of TDR. Hope it helps.

---
Tags: unity, compute-shader
---


# Question
Title: How do I make my camera avoid being blocked by or intersecting obstacles?
I have a regular Camera and this script is attached to the camera. When I rotate the camera around and the camera hits an object sometimes the camera gets pushed and if the camera distance from the target is 5 then when pushed the distance is almost 0.

The variable distanceFromTarget is set to 5 by default for example the distance from the player is 5. The problem is when the camera should or hit an object the camera in most of the cases move through the objects even if the objects have a collider and in some cases sometimes the camera distance from the player is change from 5 to almost 0.

Not sure if I need to add a collider and how to the camera or to do something else in the script ?

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

public class CameraController : MonoBehaviour
{
    public Transform targetToRotateAround;

    public float distanceFromTarget = 5.0f;

    public float xSpeed = 120.0f;
    public float ySpeed = 120.0f;

    public float yMinLimit = -20f;
    public float yMaxLimit = 80f;

    public float distanceMin = .5f;
    public float distanceMax = 15f;

    public float cameraHeight;

    public bool makeTransition = false;

    private Rigidbody rigidbody;
    private float x = 0.0f;
    private float y = 0.0f;

    // Use this for initialization
    void Start()
    {
        Vector3 angles = transform.eulerAngles;
        x = angles.y;
        y = angles.x;

        rigidbody = GetComponent<Rigidbody>();

        // Make the rigid body not change rotation
        if (rigidbody != null)
        {
            rigidbody.freezeRotation = true;
        }
    }

    private void Update()
    {

    }

    void LateUpdate()
    {
        if (targetToRotateAround)
        {
            x += Input.GetAxis("Mouse X") * xSpeed * distanceFromTarget * 0.02f;
            y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;

            y = ClampAngle(y, yMinLimit, yMaxLimit);

            Quaternion rotation = Quaternion.Euler(y, x, 0);

            distanceFromTarget = Mathf.Clamp(distanceFromTarget - Input.GetAxis("Mouse ScrollWheel") * 5, distanceMin, distanceMax);

            RaycastHit hit;
            if (Physics.Linecast(targetToRotateAround.position, transform.position, out hit))
            {
                distanceFromTarget -= hit.distance;
            }
            Vector3 negDistance = new Vector3(0.0f, cameraHeight, -distanceFromTarget);
            Vector3 position = rotation * negDistance + targetToRotateAround.position;

            transform.rotation = rotation;
            transform.position = position;
        }
    }

    public static float ClampAngle(float angle, float min, float max)
    {
        if (angle < -360F)
            angle += 360F;
        if (angle > 360F)
            angle -= 360F;
        return Mathf.Clamp(angle, min, max);
    }
}

```

# Answer
Why dont you use unity cinemachine it is much easeyer to create 3rd person camera and it has a component that handles passing trough objects. Here are the docs: https://docs.unity.cn/Packages/com.unity.cinemachine@2.2/manual/index.html
> 0 votes

# Answer
If you want to use the camera as a physics object that treats other rigidbodies as obstacles. You have to first make sure a rigidbody and collider is attatched to the camera's GameObject. You then have to make sure to use `rigidbody.MovePosition(pos);` and `rigidbody.MoveRotation(rot);` instead of `transform.position = pos;` and `transform.rotation = rot`.

For your problem with the camera teleporting almost instantly to the player when it's trying to avoid an obstacle... For third person camera's the name of the game is to be *predictive* so you can smoothly interpolate camera movements. Instead of linecasting to see if the camera **is** be obsccured, you could try line casting to predict if the camera **will** be obscured and pre-emptively start zooming the camera towards or away from the player accordingly. Third person camera's are hard though --\> they're not solved mathematical problems.

Here's a GDC talk by the person who worked on Journey's third person camera which might help. Good luck!
> 1 votes

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


# Question
Title: Can I use unique names from other media within my game?
For example, Starcraft 1 has a unit called "Hydralisk" and from what I can tell, its unique to that game. Does this mean that I can't have a unit called 'Hydralisk' in my game? I'm not going to name my game Blizzard's Hydralisk: The RTS, only having a unit bearing the same name and looks.

I guess I'm asking whether I could have a red plumber named Mario in my game too. Not whether I can name my game Super Mario: The RTS. Additionally, Lord of the Rings 'invented' the modern Orc, and it's safe to use your own Orcs in your game, I'm not clear on what the line is.

Assume that the look of the unit I want to make may be inspired by the art in that game, in that it's a slithering, mantis-bladed thing that shoots poison spikes.

This Law question suggests that names can't be copyrighted (but can be trademarked), but I'm not sure how that applies here.

US Copyright on games says:

> Copyright does not protect the idea for a game, its name or title, or the method or methods for playing it. Nor does copyright protect any idea, system, method, device, or trademark material involved in developing, merchandising, or playing a game.

An example of an original creature The Beholder from DnD is featured in some games but with permission of its creators, "Beholders are one of the few classic Dungeons & Dragons monsters that Wizards of the Coast claims as Product Identity and as such was not released under its Open Game License."

# Answer
First off, disclaimer: I am not a lawyer, nor am I a very knowledgeable person on this matter, but here's what I *believe* is correct.

Alright, with that out of the way. As Vaillancourt said, this would probably fall under trademark, not copyright. For trademark to hold up in court it generally requires 2 things:

A. The person who claims trademark must have proof that he is the first to use it.

B. The person who claims trademark must prove that your use of his word could possibly confuse buyers between your and his products.

Does Starcraft own Hydralisk? I have no idea.

However, as to the confusing of buyers, I don't think they could complain about using the *name*, or using a similar type of *alien*. However if you used both the name and the alien character, they *might* have a chance of winning a court case.

Why would they care? If you have a trademark on something, you have to defend it, or it will be hard to defend in court when you really need to.

However, whether you break trademark or not, they can still sue you and it's really not worth the money. Why don't you just use a similar alien character and change the name somewhat. They don't own Hydra, so just use a slightly different ending.

As I said, I'm not a lawyer and Copyright/Trademark are very blurry things, so if I said anything incorrect feel free to correct me in the comments.
> 1 votes

---
Tags: copyright, trademark
---


# Question
Title: Godot label Attached to 3D object gets larger when moving away from the object
I have a scene that consists of a `CSGBox` and a `Label` as a child of it.

In the script for the `CSGBox`, I get the label and center it on the box so that whenever the player is looking at it, they can see the label above the box.

```
extends CSGBox

# The box's label.
onready var label: Label = get_node("Label")
# The player's camera.
onready var camera: Camera = get_viewport().get_camera()

# Aligns the position of the label to always face the camera.
#
# `point` - The position to align the label to.
func position_label(point: Vector3):
    var offset = Vector2(label.get_size().x / 2, 0)
    label.rect_position = camera.unproject_position(point) - offset

# Every frame we check to see if the label is behind the camera or the label is
# out of the render distance and if so we return early. Otherwise, we position
# the label on the cube so that it's always facing the camera.
#
# `_delta` - The difference in time between the last frame and the current frame.
func _process(_delta):
    var pos: Vector3 = global_transform.origin

    # If the point is behind the camera we hide the label and return early.
    if camera.is_position_behind(pos): return

    position_label(pos)

```

This works pretty well, however it seems that the label gets smaller when moving closer to the box and larger when moving away from it. I know that it's not actually increasing in size because I can log the size of the text in the label and it's always the same but I'm not sure what could be causing this effect or how it can be "countered" to make the text seem the same no matter the distance.

# Answer
> 3 votes
The text on the label is the same size always, period.

The label does not exist in 3D space, it has no concept of depth.

You already know how to convert a point from 3D space to 2D.

I present a few ways to go about this.

*By the way, I remind you that the current camera can change.*

---

## Scale by the camera projection

Here is an idea: convert another point slightly offset vertically.

Let us start with your code:

```
    var offset = Vector2(label.get_size().x / 2, 0)
    label.rect_position = camera.unproject_position(point) - offset

```

We need another point just offset on y axis:

```
    var offset = Vector2(label.get_size().x / 2, 0)
    label.rect_position = camera.unproject_position(point) - offset

    var another_point = Vector3(point.x, point.y + v_size, point.z)

```

Where `v_size` is, I don't know, `1`? You can make it the vertical size of the label in 3D.

And we "unproject" that too:

```
    var offset = Vector2(label.get_size().x / 2, 0)
    label.rect_position = camera.unproject_position(point) - offset

    var another_point = Vector3(point.x, point.y + v_size, point.z)
    var another_point_2d = camera.unproject_position(another_point_2d) - offset

```

Then we take the distance, and use that as scale factor:

```
    var offset = Vector2(label.get_size().x / 2, 0)
    label.rect_position = camera.unproject_position(point) - offset

    var another_point = Vector3(point.x, point.y + v_size, point.z)
    var another_point_2d = camera.unproject_position(another_point_2d) - offset
    label.rect_scale = base_scale * label.rect_position.distance_to(another_point_2d)

```

Where `base_scale` is some `Vector2` that has the size normal scale of the label. If `v_size` is the height you want the label to have in 3D space, then `base_scale` is simply `Vector2(1, 1)`. However, if you let `v_size` be `1`, you would want to tweak `base_scale` to something you like. You can either tweak `base_scale` or `v_size` or both.

---

## Scale by field of view

To be fair, that is not the only way to go about it. Since you know both the position of the camera and the position of the object the label is supposed to be attached to…

You can easily compute the distance:

```
var distance = camera.global_transform.origin.distance_to(global_transform.origin)

```

By the way, if you want to use the distance along the direction the camera is looking, you can project over the the z basis from its transform:

```
var difference = global_transform.origin - camera.global_transform.origin
var distance = difference.project(camera.global_transform.basis.z).length()

```

Either way, you just use some scale factor divided by the distance:

```
var scale = factor * get_viewport().size.y / distance
label.rect_scale = Vector2(scale, scale)

```

And you tweak the `factor` to your liking.

---

What about the field of view? Right.

Computing the screen size of 3D object given its real size, the field of view and distance took me some figuring out. This is how I made sense of it:

First we will find the size the screen would take on the 3D world at the given distance from the camera. Let us consider half the size. So we have a right triangle with the camera one the corner, one side is in the direction the camera is looking and its size is the distance, the angle there is half the field of view:

```
         3d_screen_size/2
         ┌────────────
         │          ⟋
         │        ⟋
distance │      ⟋
         │    ⟋
         │  ⟋
         │⟋ <- FOV/2
       camera

```

So that `3d_screen_size` is `distance * 2 * tan(FOV * 0.5)`.

We can then compute what proportion of that our object occupies:

```
proportion = object_size / 3d_screen_size

```

And scale that with the view port size:

```
size.y = viewport.size.y * proportion

```

That is:

```
size.y = viewport.size.y * object_size / (distance * 2 * tan(FOV * 0.5))

```

Actually, let us get a scale:

```
scale = viewport.size.y / (distance * 2 * tan(FOV * 0.5))

```

So we can do this:

```
var scale = factor * get_viewport().size.y / (distance * 2 * tan(camera.fov * 0.5))
label.rect_scale = Vector2(scale, scale)

```

Again I have added a factor for you to tweak, because honestly, it is going to look huge on normal settings (considering that the size of the label in pixels is being taken as a size in 3D).

By the way, since you have some `factor` and - assuming no changes in the camera field of view - `2 * tan(camera.fov * 0.5)` is just some constant. Then you probably can simply have some constant. And trigonometry stuff is not needed. *Yeah, all that figuring out is just throw a constant factor at it.*

---

**Errata**: The above method works until the field of view reaches 90º (a quarter turn). Then the `tan` formula will give you negatives.

**Addendum**: So here is yet another way to figure out the scale that does not have the problem I mentioned above:

```
var difference = global_transform.origin - camera.global_transform.origin
var depth = difference.project(camera.global_transform.basis.z).length()

var ref = camera.project_position(Vector2.ZERO, 1)
var scaled_ref = camera.project_position(Vector2.ZERO, depth)
var regular_size = ref - ref.project(camera_transform.basis.z)
var scaled_size = scaled_ref - scaled_ref.project(camera_transform.basis.z)
var scale = regular_size.length() / scaled_size.length()
rect_scale = scale_factor * Vector2(scale, scale)

```

The code projects the top left corner of the viewport to 3D space using the camera projection at two different depths: 1, and the distance to the object along the view line of the camera (depth).

That should give you points in the top left line of the viewing frustum (within rounding error), at depth 1, and at the depth of the object.

Then the code projects them into the view line of the camera, and take the difference. This gives you two vectors normal to the view line of the camera, so we an use their relative size for scaling.

---

## Render to a texture

And those aren't the only ways to go about this.

You can render the `Label` to a texture by placing it inside a `Viewport` node with its own `Camera2D`. And then make a `ViewportTexture` from it and set it to a 3D object.

See the official 2D in 3D demo project

---
Tags: 3d, camera, godot
---


# Question
Title: How can I set up enemies spawning in set locations in every level in my Unity game?
I'm new to Unity and I've made a game in which I can make the levels using prefabs quickly, but I found that making Enemies in prefabs isn't a good idea because they can't follow or interact with the player. What is the best way to make Enemies spawn as soon as the level generates without having to individually create every single one?

Player Code (or at least the instance variables without the methods):

```
public class PlayerPhys : MonoBehaviour
{
[SerializeField] private float m_JumpForce = 400f;
[Range(0, 1)] [SerializeField] private float m_CrouchSpeed = .36f;
[Range(0, .3f)] [SerializeField] private float m_MovementSmoothing = .05f;
[SerializeField] private bool m_AirControl = true;
[SerializeField] private LayerMask m_WhatIsGround;
[SerializeField] private Transform m_GroundCheck;
[SerializeField] private Transform m_CeilingCheck;
[SerializeField] private Collider2D m_CrouchDisableCollider;

const float k_GroundedRadius = .2f;
private bool m_Grounded;
const float k_CeilingRadius = .2f;
private Rigidbody2D m_Rigidbody2D;
private bool m_FacingRight = true;
private Vector3 m_Velocity = Vector3.zero;

[Header("Events")]
[Space]

public UnityEvent OnLandEvent;

[System.Serializable]
public class BoolEvent : UnityEvent<bool> { }

public BoolEvent OnCrouchEvent;
private bool m_wasCrouching = false;

private Animator m_Anim;

Transform playerGraphics;

```

Enemy prefab code I have so far:

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

public class EnemyAttack : MonoBehaviour
{
    public int health = 1;

    // Update is called once per frame
    void Update()
    {
        // Destroy this if killed
        if (health <= 0)
        {
            Destroy(gameObject);
        }
    }

    // Take damage
    public void TakeDamage(int damage)
    {
        health -= damage;
    }
}

```

I used this Brackeys tutorial to create levels, and all I'm confused about is how I can make it so that the level creator can create enemies which can interact with the player. I wish he went over how he made prefabricated coins able to be picked up by the player

# Answer
> 1 votes
To get a reference to the player. I normally add to my scene an empty game-object called 'GAME\_MANAGER' or similar. Attach to this a script with similar name GameManager.cs for example.

Inside GameManager.cs there are several ways we can get a reference to the player in the scene. Personally I like to spawn (ie. gameObject.Instantiate(playerPrefab)) the player in the GameManager. But I'll assume you have your player dragged into the scene so you don't have any reference. Well one way to make a reference to the existing player in the scene is to use Find (https://docs.unity3d.com/ScriptReference/GameObject.Find.html)

Here is a little example code:

GameManager.cs

```
public class GameManager : MonoBehaviour
{
     PlayerPhys Player;

     void Start()
     {
         Player = GameObject.Find("EXACT PLAYER NAME").GetComponent<PlayerPhys>();

         // A different way is to FindObjectByType, it will return the first object it finds with a PlayerPhys component attached
         Player = FindObjectOfType<PlayerPhys>();
     }

}

```

I also make my GameManager class a singleton. https://refactoring.guru/design-patterns/singleton/csharp/example

This way you can easily use this player reference from other scripts for example your enemies.

A very quick intro of how to make GameManager.cs into a singleton is as follows:

```
public class GameManager : MonoBehaviour
{
     public static GameManager singleton_instance;
     public PlayerPhys Player;

     void Start()
     {
         if (singleton_instance == null)
             singleton_instance =  this;
         else
             Destroy(this);
         Player = GameObject.Find("EXACT PLAYER NAME").GetComponent<PlayerPhys>();
     }

}

```

Disclaimer: I am not an expert. Just a indie game dev wannabe you has picked up tricks as I go. Others here can give much more technical and precise help/advice. That said if you have questions about what I wrote here, I will do my best to answer for you.

EDIT: An example of finding the player from within another script such as Enemy.cs:

```
public class Enemy : MonoBehaviour
{
     void Update()
     {
          // ensure 'Player' in GameManager.cs is declared as public
          Vector3 player_position = GameManager.singleton_instance.Player.tranform.position;
     }
}

```

---
Tags: unity, c#, game-mechanics
---


title: One side of every object is black

text:
# Question
Title: One side of every object is black
I'm trying to make a driving game in Unity, but recently have been having lighting issues.

When I was first building it, the lighting worked fine. However, recently, one side of everything (the indirect lighting side) has turned black.

Here's an image of the issue.

I've tried changing my lighting settings, but can't seem to fix it. Here are my lighting settings.

What can I do to fix this? (I am using Unity 2017.2.0f3)

# Answer
> 0 votes
The problem turned out to be my environment lighting.

When the Environmental Lighting was set to Skybox, the indirect lighting was set to black - causing the problem with the scene.

Setting it to Gradient, and then setting the colors to a (slightly tan) white, grey, and a darker shade of grey has solved the issue.

# Answer
> 0 votes
After some troubleshooting, I found that I could fix it with a shader called `DoubleSided`.

Here's what my scene looked like after applying the shader.

(The `DoubleSided` shader is available in the free asset NYC Block #6.)

Here's what my skybox looked like as well.

# Answer
> 0 votes
This issue was you had Skybox on as your Environment lighting method but you needed to generate that ProbeLight. In Unity 2020 that's in `Light Settings`. Switching to color or gradient just changed the lighting method but didn't "fix" the issue. Cubemaps for Reflections and Environment lighting generally looks better that color or Gradient as your scene lighting will have more range in the ambient values; simulating bounce lighting. Unfortunately Unity current has a confusing system where "real-time" light baking is under: `Window->Rendering->Lighting->Baked Lightmaps->Generate Lighting`.

Even if you're only using real-time lighting and not using "Backed Lightmaps" you need to generate the convolved cubemaps for environment lighting for real-time reflections and lighting.

Documentation for precomputed lighting data.

---
Tags: unity, lighting
---


title: Shaders overriding other shaders

text:
# Question
Title: Shaders overriding other shaders
Recently, I've been making a 3D game and I have been having trouble with making multiple shaders. I've researched this for a bit, and told that I had to use `gluseshader` or `shader.bind()` in my code, but the post processing shader overrides the cube shader.

Here is my code

```
package me.pale.main;

import java.io.FileNotFoundException;
import java.io.IOException;

import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL20;
import org.lwjgl.util.glu.GLU;
import org.newdawn.slick.opengl.Texture;

import me.pale.model.Voxel;
import me.pale.postprocess.FBO;
import me.pale.postprocess.PostProcessQuad;
import me.pale.shader.PostProcessShader;
import me.pale.shader.Shader;
import me.pale.texture.Tex;

public class BlockGame {

    float fac = 640;

    float t = 640;

    float u_Time = 0;

    Texture testtex;

    PostProcessShader postprocess;

    FBO fbo;

    float rot;

    PostProcessQuad ppq = new PostProcessQuad();

    Voxel test = new Voxel();

    // FBO fbo;

    public void window(String name, int width, int height) throws LWJGLException, FileNotFoundException, IOException {

        Display.setDisplayMode(new DisplayMode(width, height));
        Display.create();

        fbo = new FBO(FBO.DEPTH_RENDER_BUFFER);
        postprocess = new PostProcessShader();
        Shader shader = new Shader();
        Tex testtex = new Tex();

        GL11.glMatrixMode(GL11.GL_PROJECTION);
        GL11.glEnable(GL11.GL_TEXTURE_2D);
        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
        GL11.glClearColor(0, 0, 0, 0);
        GLU.gluPerspective(90.0f, 1.333f, 0.1f, 650.0f);
        GL11.glMatrixMode(GL11.GL_MODELVIEW);
        GL11.glEnable(GL11.GL_DEPTH_TEST);
        GL11.glDepthMask(true);

        // GL20.glUniform1f(GL20.glGetUniformLocation(shader.getProgID(), "fac"), fac);

        GL11.glTranslated(0.0f, 0.0f, -5.0f);

        // fbo.printAllThings();
        testtex.loadTexture("res/test.png");
        System.out.println(testtex.getTextureID());
        System.out.println(fbo.getColorTexture());

        System.out.println("PROGRAM ID FOR POST PROCESSING: " + postprocess.getProgID());
        System.out.println("PROGRAM ID FOR DEFAULT SHADER: " + shader.getProgID());

        float x = 0;

        while (!Display.isCloseRequested()) {

            rot += 0.05f;
            // shader.start();
            shader.start(shader.getProgID());
            fbo.bindFBO();
            GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
            GL11.glClearColor(1.0f, 1.0f, 0.2f, 1.0f);
            GL11.glPushMatrix();
                // shader.start(shader.getProgID());
                GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
                // GL13.glActiveTexture(GL13.GL_TEXTURE0 + 1);
                GL13.glActiveTexture(GL13.GL_TEXTURE0);
                GL11.glBindTexture(GL11.GL_TEXTURE_2D, testtex.getTextureID());
                // GL20.glUniform1i(GL20.glGetUniformLocation(shader.getProgID(), "tex"), 1);
                GL11.glRotatef(rot += 0.01f, 1.0f, 1.0f, 1.0f);
                test.draw();
                // GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
                // shader.halt();
            GL11.glPopMatrix();
            fbo.unbindFBO();

            // renderPP();
            // RENDER FBO QUAD
            GL11.glDisable(GL11.GL_DEPTH_TEST);
            /* postprocess.start(postprocess.getProgID());

            GL20.glUniform1f(GL20.glGetUniformLocation(postprocess.getProgID(), "u_Time"), u_Time += 0.005f);

            if (fac < 0) {

                fac = 0;
                t = 0;

            }

            if (Keyboard.isKeyDown(Keyboard.KEY_DOWN)) {

                // GL20.glUniform1f(GL20.glGetUniformLocation(shader.getProgID(), "fac"), fac -= 0.25f);
                GL20.glUniform1f(GL20.glGetUniformLocation(postprocess.getProgID(), "t"), fac -= 0.8f);

            }

            if (Keyboard.isKeyDown(Keyboard.KEY_UP)) {

                // GL20.glUniform1f(GL20.glGetUniformLocation(shader.getProgID(), "fac"), fac += 0.25f);
                GL20.glUniform1f(GL20.glGetUniformLocation(postprocess.getProgID(), "t"), fac += 0.8f);

            }

            if (Keyboard.isKeyDown(Keyboard.KEY_R)) {

                fac = 1024;
                // GL20.glUniform1f(GL20.glGetUniformLocation(shader.getProgID(), "fac"), 1024);
                GL20.glUniform1f(GL20.glGetUniformLocation(postprocess.getProgID(), "t"), 640);

            }

            // GL20.glUniform1i(GL20.glGetUniformLocation(postprocess.getProgID(), "renderTex"), fbo.getColorTexture());
            // GL13.glActiveTexture(GL13.GL_TEXTURE0);
            GL11.glBindTexture(GL11.GL_TEXTURE_2D, fbo.getColorTexture());
            renderQuad();
            GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
            postprocess.halt(); */

            postProcess();
            GL11.glEnable(GL11.GL_DEPTH_TEST);

            // UPDATE DISPLAY
            Display.update();

        }

        fbo.wash();
        postprocess.wash();
        shader.wash();
        testtex.wash();
        Display.destroy();
        System.exit(0);

    }

    public static void main(String[] args) throws LWJGLException, FileNotFoundException, IOException {

        BlockGame bg = new BlockGame();
        bg.window("Game", 640, 480);

    }

    public void postProcess() {

        postprocess.start(postprocess.getProgID());

        GL20.glUniform1f(GL20.glGetUniformLocation(postprocess.getProgID(), "u_Time"), u_Time += 0.005f);

        if (fac < 0) {

            fac = 0;
            t = 0;

        }

        if (Keyboard.isKeyDown(Keyboard.KEY_DOWN)) {

            // GL20.glUniform1f(GL20.glGetUniformLocation(shader.getProgID(), "fac"), fac -= 0.25f);
            GL20.glUniform1f(GL20.glGetUniformLocation(postprocess.getProgID(), "t"), fac -= 0.8f);

        }

        if (Keyboard.isKeyDown(Keyboard.KEY_UP)) {

            // GL20.glUniform1f(GL20.glGetUniformLocation(shader.getProgID(), "fac"), fac += 0.25f);
            GL20.glUniform1f(GL20.glGetUniformLocation(postprocess.getProgID(), "t"), fac += 0.8f);

        }

        if (Keyboard.isKeyDown(Keyboard.KEY_R)) {

            fac = 1024;
            // GL20.glUniform1f(GL20.glGetUniformLocation(shader.getProgID(), "fac"), 1024);
            GL20.glUniform1f(GL20.glGetUniformLocation(postprocess.getProgID(), "t"), 640);

        }

        // GL20.glUniform1i(GL20.glGetUniformLocation(postprocess.getProgID(), "renderTex"), fbo.getColorTexture());
        GL13.glActiveTexture(GL13.GL_TEXTURE0);
        GL11.glBindTexture(GL11.GL_TEXTURE_2D, fbo.getColorTexture());
        renderQuad();
        GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
        postprocess.halt();

    }

    /* public void renderPP() {

        // postprocess.start();
        // GL11.glBindTexture(GL11.GL_TEXTURE_2D, fbo.getColorTexture());

        GL11.glDisable(GL11.GL_DEPTH_TEST);

        postprocess.start();

        GL20.glUniform1i(GL20.glGetUniformLocation(postprocess.getProgID(), "renderTex"), fbo.getColorTexture());
        // GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
        GL11.glEnable(GL11.GL_TEXTURE_2D);
        GL13.glActiveTexture(GL13.GL_TEXTURE0);
        GL11.glBindTexture(GL11.GL_TEXTURE_2D, fbo.getColorTexture());

        renderQuad();
        postprocess.halt();

        GL11.glEnable(GL11.GL_DEPTH_TEST);

    } */

    public void renderQuad() {

        // fbo.bindFBO();
        GL11.glBegin(GL11.GL_TRIANGLES);
        GL11.glTexCoord2f(0, 0);
        GL11.glVertex3f(-1, 1, 0);
        GL11.glTexCoord2f(1, 0);
        GL11.glVertex3f(1, 1, 0);
        GL11.glTexCoord2f(0, 1);
        GL11.glVertex3f(-1, -1, 0);

        GL11.glTexCoord2f(0, 1);
        GL11.glVertex3f(-1, -1, 0);
        GL11.glTexCoord2f(1, 0);
        GL11.glVertex3f(1, 1, 0);
        GL11.glTexCoord2f(1, 1);
        GL11.glVertex3f(1, -1, 0);

        GL11.glEnd();
        // fbo.unbindFBO();

    }

}

```

> The main problem I am having is using multiple shaders. I use one shader for the post processing (render FBO texture to quad), and a cube shader (the shader that textures the cube), but after I got FBOs working, shaders have been a hassle. Like the cube shader isn't working and the post-process shader is overriding it or overpowering it. It is also using a pixelized texcoord, one that I am not using at all in either shader files

This is currently what it is doing:

But its supposed to render a texture on it like this:

This is a workable solution, but the solution to this problem to make the texture render was to not start the cube shader `shader.start(shader.getProgID());`. I need shaders if I want to do some special effects per voxel group, and multiple shaders for other things in the future.

the cube shader, `shader.start(shader.getProgID());` is supposed to render a texture on the cube that is rendered on the fbo on the screen. The post processing shader, `postprocess.start(postprocess.getProgID());` is supposed to render the fbo to a texture, and put it on the quad, then renders the quad wrapped onto the screen. When I add `shader.start(shader.getProgID());`, it does not render the texture, but renders a pixelized texcoord, one that I am only using in the postprocess shader that is able to pixelize the fbo. When I specify no gl\_FragColor in the cube shader (`shader.start(shader.getProgID());`), it still renders the pixelized texcoords. When I specify a `gl_FragColor`, it renders the pixelized texcoords, even if the `gl_FragColor` has a vec4 assigned to it, like `vec4(1.0, 0.0, 0.0, 1.0);`

It turns out that during debugging, it turns out that both the cube texture and the fbo texture have the same ID... How do I fix this?

Thanks for your help!

# Answer
After having an enlightenment, there was an error in the shader code that the shader program wasn't catching because it was a vec2 method, but weird. Anyways, I got it working there was an error in shader code.
> 0 votes

---
Tags: opengl, java, lwjgl, fragment-shader, vertex-shader
---


# Question
Title: Can I change an Android IAP's type from Consumable to Non-Consumable?
I was inspecting a bug with one of our old Android games, where a "level pack" in-app purchase was being lost after the player re-installed the game etc.

The issue became obvious when I realized that it was being declared as Consumable.

```
configurationBuilder.AddProduct(ID_LEVEL_PACK,  ProductType.Consumable);

```

Now, I am contemplating what the correct fix is.

1. Will it suffice to simply change the ProductType? I am skeptical, because it feels odd to me that Google would let a developer to simply change the type of an in-app product from one version to another.
2. Create a new product with a new ID and correct ProductType, then replace the old product. This doesn't sound bad, but is there any way we can properly deal with the people who unfortunately purchased the Consumable version? From my understanding using Unity's Purchasing package doesn't expose any API to query purchased products.

The first option would be ideal if it were possible and also if Unity could retroactively "restore" purchases made when the IAP was still Consumable. From my understanding, Unity performs said restoration upon re-installation (on Android) but only for Non-Consumables or Subscriptions.

While I am in the process of testing that, this seems like a fairly delicate issue so I'd like to see if anyone has insight on this matter: can I change a product's type from Consumable to Non-Consumable, and will Unity retroactively restore the old purchases?

# Answer
I have done minimal testing, and here are the results:

* Store: Google Play
* Unity Purchasing Package version: 3.2.1
* Unity Version: 2020.3.7f1

---

1. There doesn't seem to be any errors if you upload a build that changes a product's definition from Consumable to Non-Consumable.
2. If you purchased the Consumable version before the conversion, Unity will not be able to retrieve its receipt and therefore the product won't be restored. This is what will happen to the players who already purchased it before the update.
3. If you purchase the Non-Consumable version (after the conversion, of course), and then re-declare the product back to a Consumable type, it seems like the product will still be treated as a Non-Consumable because the receipt is still available (even after re-installation), and if you try to purchase it, you will get an error saying that you already own it.
4. If you purchased the Consumable version before the conversion, then update to the build that has the Non-Consumable declaration, you'll have to purchase it again. If you do so, it will work as expected and it will treat the product as a Non-Consumable from now on.

So it seems like you could just change the product type, and then provide customer support to the people that bought it before the change. However, since it's not clear whether this behaviour will be the same in all stores, I think it is safer to replace the product ID with a new one, and then check for receipts in either of the two IDs when attempting to restore the product.
> 1 votes

---
Tags: unity, android, in-app-purchase
---


# Question
Title: How to stop player from slingshotting across my game window
In my pygame dungeon rpg when my player collides with a wall at the top or the bottom of its rect and I move the player in either x-direction, the player gets slingshotted off the screen. Using print debugging I've realized that when the player is colliding with the top it hits the individual hitboxes of the tiles and slingshots it to the outside of my game map because of how my collisions work.

```
    def colliders(self):
        hit_list = self.collision_test(tile_rects)
        for tile in hit_list:
            if self.speed[0] > 0:
                self.rect.right = tile.left
                print('right')
            elif self.speed[0] < 0:
                self.rect.left = tile.right
                print('left')
        hit_list = self.collision_test(tile_rects)
        for tile in hit_list:
            if self.speed[1] > 0:
                self.rect.bottom = tile.top
                print('bot')
            elif self.speed[1] < 0:
                self.rect.top = tile.bottom
                print('top')

```

The tile is derived from the hitboxes of each individual tile in the above function. Speed and rect are derived from my player init function above.

Video of error: https://www.youtube.com/watch?v=FbJAC3LulHM&feature=youtu.be&ab\_channel=spretzelz

Code: https://pastebin.com/jXav1PdU

# Answer
When a character collides with a tile while moving up, the collision must push back on the Y axis first, but your code unconditionally checks X axis first.

Choose an axis based on the penetration direction, like this:

```
    if abs(self.rect.centerx - tile.rect.centerx) > abs(self.rect.centery - tile.rect.centery):
        # resolve X axis
    else:
        # resolve Y axis

```
> 0 votes

---
Tags: collision-detection, python, pygame, collision-resolution
---


# Question
Title: How can I rotate the player only to -40 or -45 degrees?
```
float c = 0.0f;
private void FixedUpdate()
{
    if (startRotatingBack)
    {
        var p = transform.eulerAngles;

        if (p.y != -40)
        {
            p.y -= 1;
            transform.eulerAngles = p;
        }

        c = c + 0.1f;
        playerAnimator.SetFloat("Forward", c);
    }
}

```

The problem is that the transform keeps rotating nonstop.

Maybe the problem is with this chick?

```
if (p.y != -40)

```

I want to make that the player will rotate backward. -40 or -45 is good enough but the player the transform is keep rotating nonstop so it's making circles instead of rotating once to -40 or to -45.

I tried also this way but it's not working either :

```
if (!Mathf.Approximately(p.y, -40))

```

# Answer
Problem is your if condition.When `startRotatingBack` value is true, your rotating code continue rotating. If you set `startRotatingBack=false`, it won't run again.

```
   if (startRotatingBack)
    {
        var p = transform.eulerAngles;

        if (p.y != -40)//I think -40 your target angle
        {
           p.y -= 1;
           transform.eulerAngles = p;
        }else{
           //if p.y=-40, you reached your target angle
           startRotatingBakc=false;//assign false and it won't rotate again.
        }

        c = c + 0.1f;
        playerAnimator.SetFloat("Forward", c);
    }

```
> 0 votes

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


# Question
Title: Why does only the sound for turning off the flashlight play?
This script is supposed to play a sound when I turn on the flashlight sprite and a different sound when I turn it off, but for some reason it's only playing the second sound.

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

public class flashlightonoffsound : MonoBehaviour
{
    public static bool flashlightisoff = false;

    public AudioSource flashlightsound1;

    public AudioSource flashlightsound2;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.E))
        {
            if (flashlightisoff)
            {
                flashlightsound1.Play();
            }
            else
            {
                flashlightsound2.Play();
            }
        }

    }
}

```

# Answer
First I would suggest not to use 2 AudioSources. That causes a lot of confusion. Instead use only one audiosource for one game object, and switch between audioClips:

```
public AudioClip clip1;
public AudioClip clip2;

```

and then somewhere in your logic you play the clip:

```
myAudioSource.PlayOneShot(clip1); // or clip2 ....

```

Second make sure you are changing value of *flashlightisoff* correctly. For example you maybe changing it ok, but next frame it reverts back (which often is mistake when people are using *Input.GetKeyDown*). You can track value of your variable like that:

```
void Update()
{
    Debug.Log("value:" + flashlightisoff );
}

```

then watch console for what happens with your variable every frame, and you will know where fault is.
> 2 votes

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


title: ArgumentException for unused axis

text:
# Question
Title: ArgumentException for unused axis
I'm creating a simple Pachinko-style game and using a single button to drop balls in. Everything is working great, but the Unity Editor is throwing an ArgumentException for the **Submit** axis "not set up", so I added it to the InputManager only for it to then throw the same error for the **Cancel** axis.

When I first started the project I deleted the default axes from the InputManager and replaced them with a single one I've called "Fire". I don't use any other axes in any of my two script.

If I select the error in the console it jumps me to BaseInput.cs

I researched this for a while, but the only solution I saw was regarding a misspelling of the axis name, but I'd like to be clear that in this case the axes involved are totally unused in my code.

# Answer
> 0 votes
Thanks to DMGregory for answering this! The problem was indeed caused by a Standalone Input Module on my EventSystem which was created when I added the UI Canvas. Thanks so much!

---
Tags: unity
---


# Question
Title: How "smart objects" are implemented and actually work?
I'm drafting my game and implementing small stuff in it, but hit a roadblock. You see, for my game I would like for different items to behave the same or to share behavior, for instance, some items can be picked up and dropped to the floor, some items can get damaged and be repair while some only can get damage (the player cannot repair the item), some items can be use for a variety of different purposes (fire arms as weapons, frying pan as cooking tool and as a weapon), some items can get wet while others can get wet, catch fire and spread it further (or not; this is a reference to systemic games) and so on.

In my mind, the behavior must exist in the object and be abstracted from the player/AI/Other items nevertheless I'm lacking experience on how to go about this and I think that beside implementing a behavior there must exist also code that knows how to interact with such behavior, but this approach feels odd IMHO. In any case, I was asking around and The Sims was thrown in a reply, searching on the web found Living with The Sims’ AI: 21 Tricks to Adopt for Your Game, the trick 5 reads:

> Each object has a public interface that broadcasts its functionality to actors in the game. This is called advertising data in The Sims, and contains a list of possible actions and what motives they satisfy.

If reading this correctly, it means that "smart objects" have a standard interface that actors can access to, right? My guess is that this interface covers everything behavior/systemic-wise that could happen in the game and the "actors" have code implemented that allow them to make use of this advertised interface, right?

# Answer
> 4 votes
Well, concerning "The Sims" article you are reffering to that actually could mean a lot of different things. But the core idea as I get it is that each object can expose a list of "functions" that can be applied to it. For example

```
item : ["destroy", "pick up", "eat", "cook"]

```

and then the actor decides it can be processed with:

```
item.pickUp(actor)

```

or

```
actor.pickUp(item)

```

or something else, depending on details of implementation.

So imaging the actor clicks on the `item` and basically sees this list of possible interactions. Each action is binded to specific code for processing and accepts the actor as argument.

The "broadcast" mentioned in the article means, as far I understand, that item are proactively inform actors about their features so they can move to them and interact if necessary.

# Answer
> 2 votes
With strong typed languages, you can create this functionality broadcast in public interfaces by the way of interfaces. Say:

```
interface IDamageSource
{
    DamagePoints Damage { get; }
    void Consume( DamagePoints points );
}

interface IDamageTarget
{
   void TakeDamage( DamageSource source );
}

interface IFixTarget
{
    FixMaterial[] FixCost();
    void FixApply( FixMaterial[] materials );
}

class Tool implements IDamageSource, IDamageTarget, IFixTarget {}
class Rock implements IDamageSource, IDamageTarget {}

class DamageEffect
{
    public InterfaceUpdates DoDamage( IDamageSource source , IDamageTarget target )
    {
        // Common logic, return any visual effects to later GUI render
    }
}

```

So in this example, a `Rock` can cause damage and can be damaged but not restored, and a `Tool` can cause damage, be damaged and be fixed with some cost. Any specifics is handled in each object implementation of interface, and the common logic is handled in `DamageEffect`.

When the user points to a object in screen, then you can "ask" to object:

```
// Can damage?

user.AttackAction.Enabled = user.SelectedObject is IDamageTarget;

// Can fix?

var fixable = user.SelectedObject as IFixTarget;
if ( fixable == null )
    user.FixAction.Status = UserFixActionEnum.NotFixable;
else
    if ( this.HasEnoughMaterials( fixable.FixCost() ) )
        user.FixAction.Status = UserFixActionEnum.Fixable;
    else
        user.FixAction.Status = UserFixActionEnum.MissingMaterials;

```

This could be realized by all "in game" objects having a common standard interface, but this is the way of one big class with tons of unrelated functionality, and that is a bad design that leads to very bad code later on.

---
Tags: entity-system, godot, gameobject
---


title: Why the Lerp never ending at 0?

text:
# Question
Title: Why the Lerp never ending at 0?
0.001266956

```
private void Slow()
    {
        if (timeElapsed < lerpDuration)
        {
            valueToLerp = Mathf.Lerp(startValue, endValue, timeElapsed / lerpDuration);
            playerAnimator.SetFloat("Forward", valueToLerp);
            timeElapsed += Time.deltaTime;
        }
    }

```

startValue value is 1 and endValue value is 0 lerpDuration value is 3 timeElapsed value is 0 and valueToLerp value is also 0

In the end, the value of valueToLerp is 0.0002498031

I could add a reset line in the end of the Slow method :

```
private void Slow()
        {
            if (timeElapsed < lerpDuration)
            {
                valueToLerp = Mathf.Lerp(startValue, endValue, timeElapsed / lerpDuration);
                playerAnimator.SetFloat("Forward", valueToLerp);
                timeElapsed += Time.deltaTime;
            }

            playerAnimator.SetFloat("Forward", valueToLerp);
            valueToLerp = 0;
        }

```

This will work but only when I call the method Slow once if I tried to call the method again it will not work it will never get to 0 again.

and if I'm not using these two lines in the end then it will not get to 0 even the first time.

I want that I will be able to call Slow many time and it will slowly get to 0 each time I'm calling the method.

# Answer
> 0 votes
Alexei Levenkov accurately summarizes your problem:

> if I ensure a \< b...

We only enter the `if` block if `timeElapsed` is less than `lerpDuration`:

```
if (timeElapsed < lerpDuration)

```

That means that `timeElapsed / lerpDuration` is less than 1.

And so,

```
valueToLerp = Mathf.Lerp(startValue, endValue, someValueLessThanOne);

```

...will set `valueToLerp` to something that is not quite `endValue`.

You can avoid this problem by moving your time increment to before the `Lerp`, not after. That way, if `timeElapsed` is initially just a frame or less away from `lerpDuration`, `timeElapsed += Time.deltaTime;` will put it over the top just before the `Lerp` acts (and it automatically clamps the value for you, so that it will not exceed 1).

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


# Question
Title: "contains support" for Dreamcast/Atari/etc, but "not officially supported"?
I found this on the About page on the official Pygame website:

> Truly portable. Supports Linux (pygame comes with most main stream linux distributions), Windows (95, 98, ME, 2000, XP, Vista, 64-bit Windows, etc), Windows CE, BeOS, MacOS, Mac OS X, FreeBSD, NetBSD, OpenBSD, BSD/OS, Solaris, IRIX, and QNX. The code contains support for **AmigaOS, Dreamcast, Atari,** AIX, OSF/Tru64, RISC OS, SymbianOS and OS/2, but these are not officially supported. You can use it on hand held devices, game consoles and the One Laptop Per Child (OLPC) computer.

I suspect this page is severely outdated as it doesn't even mention Windows versions beyond Vista, but it's quite intriguing to me that Pygame could potentially run on such old platforms.

What exactly does "contains support, but not officially supported" mean? Does it mean they could they technically run Pygame, but aren't thoroughly tested for bugs? Or are they just listing systems they *think* could run it, if they were willing to code it in?

# Answer
I'm not familiar with Pygame in particular, but as a general rule the word "support" can be used in at least *three* different but related ways:

1. "X supports Y" / "X has support for Y": the software X has at some point been edited to work with platform/configuration Y, or tested on Y. If they write "has support for", this suggests it has specific code needed to run on Y, without which it would *definitely not* run on Y. (For example, graphics/UI libraries often need code to create windows on different window systems — Windows, X11, macOS, and Android, to name a few, have completely different APIs for that.)
2. "Y is \[officially\] supported": the maintainers will consider it a bug if X doesn't run or misbehaves on Y, and work to fix it if informed. New versions of X are routinely tested on Y, if the project does any such systematic testing.
3. "Y is \[officially\] supported": You can *obtain technical support for* your attempts to use X on Y, whereas if you ask for help with an unsupported configuration it may not be provided.

In your case, I expect the quoted text means that (1) is true and (2) is not. So, for example, the support (sense 1) might have been broken by recent changes that nobody tested on those platforms; there's no guarantee.
> 0 votes

---
Tags: python, pygame, cross-platform
---


# Question
Title: How to hide player when in Shadow using Unity 2D Light System?
I have been looking for this for a couple of days now and cant find an answer; how can I **hide a player** when they are in the **shadow** when am using Unity **2D Light** System? I know I can choose not to cast light on objects, but when I do it still shows the object in the shadow. What am looking for is **hiding the player** completely when they are in **shadow**, and when the **light hits** them it would **reveal** the player. This effect is in the **game Among Us**, I know that they are using some sort of **shaders** and they didn't have 2D light when they were developing it.

So am assuming this would be a **shader** as well where it would reveal the player when they are in the light and hide them when they are in the shadow. Below are pictures of what I have and what I want it to look like.

**This is what I have in Unity**

So you can see that the player is **not hidden** in the **shadows**, but rather its **blacked out**.

**But this is what am looking to recreate:**

You see how the **top half** of the body which is in the **shadow** is hidden while the **bottom half** is **revealed** because its in the **ligh**t? This is the effect that I want to recreate.

Is there some sort of **Shader** or code that can do this? I really been looking for something like this for so long and couldn't find it. Any help will be really appreciated.

# Answer
It took me a while to figure it out, and tbh I wasn't the one who figured it out, I got help from someone on the Unity Discord server. He went into the `Sprite-Lit-Default` and changed some code that accounts for the `luminance`, now I don't know anything about shader programming so I won't be able to explain it much. But he created a `.hlsl` file with the same functionality as the `Sprite-lit-Default` file but added some argument that accounts for `luminance`. Now here are the file content of both the `.shader` file and the `.hlsl` file.

But **YOU NEED TO KEEP BOTH FILES IN THE SAME FOLDER, OTHERWISE IT WONT WORK. ALSO KEEP THE FILE NAMES THE SAME, UNLESS YOU KNOW WHAT YOU ARE DOING**

File name `HideInShadow.shader`

```
Shader "Universal Render Pipeline/2D/HideInShadow"
{
    Properties
    {
        _MainTex("Diffuse", 2D) = "white" {}
        _MaskTex("Mask", 2D) = "white" {}
        _NormalMap("Normal Map", 2D) = "bump" {}

        // Legacy properties. They're here so that materials using this shader can gracefully fallback to the legacy sprite shader.
        [HideInInspector] _Color("Tint", Color) = (1,1,1,1)
        [HideInInspector] _RendererColor("RendererColor", Color) = (1,1,1,1)
        [HideInInspector] _Flip("Flip", Vector) = (1,1,1,1)
        [HideInInspector] _AlphaTex("External Alpha", 2D) = "white" {}
        [HideInInspector] _EnableExternalAlpha("Enable External Alpha", Float) = 0
    }

    HLSLINCLUDE
    #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
    ENDHLSL

    SubShader
    {
        Tags {"Queue" = "Transparent" "RenderType" = "Transparent" "RenderPipeline" = "UniversalPipeline" }

        Blend SrcAlpha OneMinusSrcAlpha
        Cull Off
        ZWrite Off

        Pass
        {
            Tags { "LightMode" = "Universal2D" }
            HLSLPROGRAM
            #pragma vertex CombinedShapeLightVertex
            #pragma fragment CombinedShapeLightFragment
            #pragma multi_compile USE_SHAPE_LIGHT_TYPE_0 __
            #pragma multi_compile USE_SHAPE_LIGHT_TYPE_1 __
            #pragma multi_compile USE_SHAPE_LIGHT_TYPE_2 __
            #pragma multi_compile USE_SHAPE_LIGHT_TYPE_3 __

            struct Attributes
            {
                float3 positionOS   : POSITION;
                float4 color        : COLOR;
                float2  uv           : TEXCOORD0;
                UNITY_VERTEX_INPUT_INSTANCE_ID
            };

            struct Varyings
            {
                float4  positionCS  : SV_POSITION;
                half4   color       : COLOR;
                float2  uv          : TEXCOORD0;
                half2   lightingUV  : TEXCOORD1;
                UNITY_VERTEX_OUTPUT_STEREO
            };

            #include "Packages/com.unity.render-pipelines.universal/Shaders/2D/Include/LightingUtility.hlsl"

            TEXTURE2D(_MainTex);
            SAMPLER(sampler_MainTex);
            TEXTURE2D(_MaskTex);
            SAMPLER(sampler_MaskTex);
            half4 _MainTex_ST;

            #if USE_SHAPE_LIGHT_TYPE_0
            SHAPE_LIGHT(0)
            #endif

            #if USE_SHAPE_LIGHT_TYPE_1
            SHAPE_LIGHT(1)
            #endif

            #if USE_SHAPE_LIGHT_TYPE_2
            SHAPE_LIGHT(2)
            #endif

            #if USE_SHAPE_LIGHT_TYPE_3
            SHAPE_LIGHT(3)
            #endif

            Varyings CombinedShapeLightVertex(Attributes v)
            {
                Varyings o = (Varyings)0;
                UNITY_SETUP_INSTANCE_ID(v);
                UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);

                o.positionCS = TransformObjectToHClip(v.positionOS);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                o.lightingUV = ComputeNormalizedDeviceCoordinates(o.positionCS);
                o.color = v.color;
                return o;
            }

            #include "CombinedShapeLightSharedHidden.hlsl"

            half4 CombinedShapeLightFragment(Varyings i) : SV_Target
            {
                half4 main = i.color * SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, i.uv);
                half4 mask = SAMPLE_TEXTURE2D(_MaskTex, sampler_MaskTex, i.uv);

                return CombinedShapeLightShared(main, mask, i.lightingUV);
            }
            ENDHLSL
        }

        Pass
        {
            Tags { "LightMode" = "NormalsRendering"}
            HLSLPROGRAM
            #pragma vertex NormalsRenderingVertex
            #pragma fragment NormalsRenderingFragment

            struct Attributes
            {
                float3 positionOS   : POSITION;
                float4 color        : COLOR;
                float2 uv           : TEXCOORD0;
                float4 tangent      : TANGENT;
                UNITY_VERTEX_INPUT_INSTANCE_ID
            };

            struct Varyings
            {
                float4  positionCS      : SV_POSITION;
                half4   color           : COLOR;
                float2  uv              : TEXCOORD0;
                half3   normalWS        : TEXCOORD1;
                half3   tangentWS       : TEXCOORD2;
                half3   bitangentWS     : TEXCOORD3;
                UNITY_VERTEX_OUTPUT_STEREO
            };

            TEXTURE2D(_MainTex);
            SAMPLER(sampler_MainTex);
            TEXTURE2D(_NormalMap);
            SAMPLER(sampler_NormalMap);
            half4 _NormalMap_ST;  // Is this the right way to do this?

            Varyings NormalsRenderingVertex(Attributes attributes)
            {
                Varyings o = (Varyings)0;
                UNITY_SETUP_INSTANCE_ID(attributes);
                UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);

                o.positionCS = TransformObjectToHClip(attributes.positionOS);
                o.uv = TRANSFORM_TEX(attributes.uv, _NormalMap);
                o.color = attributes.color;
                o.normalWS = TransformObjectToWorldDir(float3(0, 0, -1));
                o.tangentWS = TransformObjectToWorldDir(attributes.tangent.xyz);
                o.bitangentWS = cross(o.normalWS, o.tangentWS) * attributes.tangent.w;
                return o;
            }

            #include "Packages/com.unity.render-pipelines.universal/Shaders/2D/Include/NormalsRenderingShared.hlsl"

            half4 NormalsRenderingFragment(Varyings i) : SV_Target
            {
                half4 mainTex = i.color * SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, i.uv);
                half3 normalTS = UnpackNormal(SAMPLE_TEXTURE2D(_NormalMap, sampler_NormalMap, i.uv));
                return NormalsRenderingShared(mainTex, normalTS, i.tangentWS.xyz, i.bitangentWS.xyz, i.normalWS.xyz);
            }
            ENDHLSL
        }
        Pass
        {
            Tags { "LightMode" = "UniversalForward" "Queue"="Transparent" "RenderType"="Transparent"}

            HLSLPROGRAM
            #pragma vertex UnlitVertex
            #pragma fragment UnlitFragment

            struct Attributes
            {
                float3 positionOS   : POSITION;
                float4 color        : COLOR;
                float2 uv           : TEXCOORD0;
                UNITY_VERTEX_INPUT_INSTANCE_ID
            };

            struct Varyings
            {
                float4  positionCS      : SV_POSITION;
                float4  color           : COLOR;
                float2  uv              : TEXCOORD0;
                UNITY_VERTEX_OUTPUT_STEREO
            };

            TEXTURE2D(_MainTex);
            SAMPLER(sampler_MainTex);
            float4 _MainTex_ST;

            Varyings UnlitVertex(Attributes attributes)
            {
                Varyings o = (Varyings)0;
                UNITY_SETUP_INSTANCE_ID(attributes);
                UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);

                o.positionCS = TransformObjectToHClip(attributes.positionOS);
                o.uv = TRANSFORM_TEX(attributes.uv, _MainTex);
                o.color = attributes.color;
                return o;
            }

            float4 UnlitFragment(Varyings i) : SV_Target
            {
                float4 mainTex = i.color * SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, i.uv);
                return mainTex;
            }
            ENDHLSL
        }
    }

    Fallback "Sprites/Default"
}

```

File name `CombinedShapeLightSharedHidden.hlsl`

```
#if !defined(COMBINED_SHAPE_LIGHT_PASS)
#define COMBINED_SHAPE_LIGHT_PASS

half _HDREmulationScale;
half _UseSceneLighting;
half4 _RendererColor;

half4 CombinedShapeLightShared(half4 color, half4 mask, half2 lightingUV)
{
    if (color.a == 0.0)
        discard;

    color = color * _RendererColor; // This is needed for sprite shape

#if USE_SHAPE_LIGHT_TYPE_0
    half4 shapeLight0 = SAMPLE_TEXTURE2D(_ShapeLightTexture0, sampler_ShapeLightTexture0, lightingUV);

    if (any(_ShapeLightMaskFilter0))
    {
        half4 processedMask = (1 - _ShapeLightInvertedFilter0) * mask + _ShapeLightInvertedFilter0 * (1 - mask);
        shapeLight0 *= dot(processedMask, _ShapeLightMaskFilter0);
    }

    half4 shapeLight0Modulate = shapeLight0 * _ShapeLightBlendFactors0.x;
    half4 shapeLight0Additive = shapeLight0 * _ShapeLightBlendFactors0.y;
#else
    half4 shapeLight0Modulate = 0;
    half4 shapeLight0Additive = 0;
#endif

#if USE_SHAPE_LIGHT_TYPE_1
    half4 shapeLight1 = SAMPLE_TEXTURE2D(_ShapeLightTexture1, sampler_ShapeLightTexture1, lightingUV);

    if (any(_ShapeLightMaskFilter1))
    {
        half4 processedMask = (1 - _ShapeLightInvertedFilter1) * mask + _ShapeLightInvertedFilter1 * (1 - mask);
        shapeLight1 *= dot(processedMask, _ShapeLightMaskFilter1);
    }

    half4 shapeLight1Modulate = shapeLight1 * _ShapeLightBlendFactors1.x;
    half4 shapeLight1Additive = shapeLight1 * _ShapeLightBlendFactors1.y;
#else
    half4 shapeLight1Modulate = 0;
    half4 shapeLight1Additive = 0;
#endif

#if USE_SHAPE_LIGHT_TYPE_2
    half4 shapeLight2 = SAMPLE_TEXTURE2D(_ShapeLightTexture2, sampler_ShapeLightTexture2, lightingUV);

    if (any(_ShapeLightMaskFilter2))
    {
        half4 processedMask = (1 - _ShapeLightInvertedFilter2) * mask + _ShapeLightInvertedFilter2 * (1 - mask);
        shapeLight2 *= dot(processedMask, _ShapeLightMaskFilter2);
    }

    half4 shapeLight2Modulate = shapeLight2 * _ShapeLightBlendFactors2.x;
    half4 shapeLight2Additive = shapeLight2 * _ShapeLightBlendFactors2.y;
#else
    half4 shapeLight2Modulate = 0;
    half4 shapeLight2Additive = 0;
#endif

#if USE_SHAPE_LIGHT_TYPE_3
    half4 shapeLight3 = SAMPLE_TEXTURE2D(_ShapeLightTexture3, sampler_ShapeLightTexture3, lightingUV);

    if (any(_ShapeLightMaskFilter3))
    {
        half4 processedMask = (1 - _ShapeLightInvertedFilter3) * mask + _ShapeLightInvertedFilter3 * (1 - mask);
        shapeLight3 *= dot(processedMask, _ShapeLightMaskFilter3);
    }

    half4 shapeLight3Modulate = shapeLight3 * _ShapeLightBlendFactors3.x;
    half4 shapeLight3Additive = shapeLight3 * _ShapeLightBlendFactors3.y;
#else
    half4 shapeLight3Modulate = 0;
    half4 shapeLight3Additive = 0;
#endif

    half4 finalOutput;
#if !USE_SHAPE_LIGHT_TYPE_0 && !USE_SHAPE_LIGHT_TYPE_1 && !USE_SHAPE_LIGHT_TYPE_2 && ! USE_SHAPE_LIGHT_TYPE_3
    finalOutput = color;
#else
    half4 finalModulate = shapeLight0Modulate + shapeLight1Modulate + shapeLight2Modulate + shapeLight3Modulate;
    half4 finalAdditve = shapeLight0Additive + shapeLight1Additive + shapeLight2Additive + shapeLight3Additive;
    finalOutput = _HDREmulationScale * (color * finalModulate + finalAdditve);

    half luminance = max(finalModulate.r, max(finalModulate.g, finalModulate.b));
    finalOutput.a = min(luminance * 2, color.a);
#endif

    finalOutput = finalOutput *_UseSceneLighting + (1 - _UseSceneLighting)*color;
    return max(0, finalOutput);
}
#endif

```

The part that he added is that last part where it starts at `half luminance....`

After copying them into your own files, you can then use the `.shader` file to add it to a material and then apply it to the objects you want to disappear in shadows. So if the light hits the object it will appear, but it will appear gradually as the light source gets closer to that object, the only downside to this is there must be a light source in the game so that it can use to calculate the luminance, otherwise the object will just default back to a luminance of 1, meaning completely visible. But, I think if you want to make an object disappear in the shadows then you're most likely using a light source. This is how it looks like:

Of course, you play with the light source and the intensity to get the result you want.

If you have any questions I guess you can comment or something and I will help once I see the comment.
> 0 votes

# Answer
This effect is most commonly created by overlaying two cameras, one that renders the players and the other which does not (and has the darkness filter applied). Both are written to textures, after which a full-screen shader determines for which areas to draw in the 'lit' and 'unlit' camera views.
> 0 votes

---
Tags: unity, shaders, textures, unity-shader-graph
---


# Question
Title: Invert the colour of pixels where 1 bit sprites are overlapping
I have a simple scene in Unity that makes use of some simple art that uses either white or transparent colours to create a 1-bit art design. The image below shows this.

I want to have a that if two sprites overlap then the colour changes to transparent which makes the sprite appear to have its colours inverted. For example, a white cone from a lamppost could look like a beam of light. When the character walks into the beam its colour should change black so it is still visible under the light. As well as this, if the sprite is only partially in the light then only that portion of the sprite should be revealed.

I used a sprite mask and a second sprite hidden behind the first with different sprite mask interaction options to achieve the effect but I also have a variety of particle systems, such as the rain visible above, and would like this to also be affected. I've included a rather crude image of what I am aiming for.

I believe that I need some sort of shader but am struggling to even know where to start looking so any help at all would be appreciated.

# Answer
> 17 votes
We can do this by making a custom version of the standard sprite shader (so it still does everything the one you're used to can do), and modifying its blending operation.

Start by going to the Unity Download Archive, and grab the built-in shaders for the version of Unity you're using. I'm currently on 2020.3.7f1 (LTS)

Inside that zip, you'll want to copy `DefaultResourcesExtra/Sprites-default.shader` \- place the copy in your project's `Assets` folder with a new name, like "Sprites-invert.shader"

Now open up the text file and make two modifications:

First, at the very top of the file, change the shader's name to match the name you picked for the file, so it doesn't collide with the built-in shader.

```
Shader "Sprites/Invert"
{

```

Then scroll down to this line:

```
Blend One OneMinusSrcAlpha

```

This says "When blending this sprite with the background, the output colour should be the colour of this sprite times 'one', plus the colour already in the frame times 'one minus the alpha value of this sprite'". That gives us what's called premultiplied alpha blending.

We'll change it to this:

```
Blend OneMinusDstColor OneMinusSrcColor

```

Now we're multiplying the foreground colour by the inverse of the background, and the background by the inverse of the foreground. That gives us...

| Foreground | Background | First Term | + | Second Term | = | Output |
| --- | --- | --- | --- | --- | --- | --- |
| 1 (White) | 0 (Black) | (1) * (1-0) = 1 | + | (0) * (1-1) = 0 | = | 1 (White) |
| 1 (White) | 1 (White) | (1) * (1-1) = 0 | + | (1) * (1-1) = 0 | = | 0 (Black) |
| 0 (Black) | 0 (Black) | (0) * (1-0) = 0 | + | (0) * (1-0) = 0 | = | 0 (Black) |
| 0 (Black) | 1 (White) | (0) * (1-1) = 0 | + | (1) * (1-0) = 1 | = | 1 (White) |

...And for values in between we get greys, so you don't lose your antialiased adges like on that triangular sprite in your mask example.

Make a material that uses your new shader, and assign it to the SpriteRenderer components for your foreground sprites. You'll get a result something like this:

(Using this "Sauropod skeleton" icon by Caro Asercion as an example)

You can apply a post effect at the end to remap your colours if you want the white and black to look like something else. This keeps the shader simpler than trying to use those special colour values throughout the pipeline.

What's nice about this is that it has exactly the same cost as the original sprite shader - we didn't add even a single new instruction, just changed the parameters of the blending operation we were already doing anyway That's much cheaper than mask-based solutions that require extra rendering/sampling from the mask texture.

If you have both sprites using the default material and sprites using this new material in your scene, you'll pay a little cost due to splitting them into separate draw calls for each shader. But if you're using this new sprite shader exclusively then it's effectively free.

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


# Question
Title: How can I install Unreal engine on a PC with metered connection or completelly offline?
I need to get Unreal Engine 4 as soon as possible on my desktop PC, in order to complete a task. However, the computer is on a metered connection and downloading it there would cost me about 3 pizzas worth of money.

I have a laptop which I can bring somewhere where there is WiFi. But I see that Unreal Engine only provides an online installer, judging from the fact that the installer has 40MB.

So how could I install Unreal on my laptop, then move it to this desktop PC? I don't mind using some data if it needs to connect to the internet to verify my account, but I don't want to download over 10GB over mobile data unless it's absolutely necessary.

It must be Unreal Engine 4 specifically, I cannot use something else, nor I wish to.

# Answer
It is possible to install the Unreal Engine to an external hard drive and run it on any PC you like through a USB connection. A number of people do this so their engine and all their projects can be worked on in a number of locations.

You need to make sure that the PC you're trying to run it on has the require prerequisites (VS C++ 2015 I think) but these are downloaded as well into the Unreal Engine folder and can be installed later if needed.
> 1 votes

---
Tags: unreal-4, windows, installer
---


# Question
Title: How to port/convert a Java program to mobile?
I have coded a simple video game in Java. It works fine on all computers that have Java installed. However, I would really like to play it on my smartphone and it would also be nice to be able to play it on pretty much any smartphone no matter what model/company/OpSys etc. Here is my question:

**How can I convert my Java video game into something that runs on mobile devices (a smartphone), ideally without completely rewriting the whole source code?**

After all, the idea of Java is that you write the code once and then it runs on pretty much all devices. I would not mind copy-pasting my own source code and maybe add/change a few lines of code. But I would really like to avoid having to rewrite it in some completely different language.

Details about my game: It is a simple one-player vs CPU 2D card game, where you click on a few buttons and pictures. Every now and then there is a dialog window. That's pretty much all. But there are many pages of AI / game logic source code.

On the computers the input for this game is just left-clicking on the buttons. Ideally, on a device with a touch screen, one would just touch the buttons depicted on the screen. I have not really looked into porting myself that much. My hope was that in this modern day and age, where smartphones are pretty much computers, there would be something as close to a one-click-converter as possible. Again, the original idea was that with Java you are supposed to write one source code for all devices.

# Answer
What you want to do is most likely not as easy as you think. Yes, Java is one of the main programming languages for Android, but that's where all the similarities end with desktop and browser-based Java.

It really depends on the environment you're using. Unless you're using something game-oriented, such as libGDX, or a natively multiplatform framework, like Codename One, the entire programming paradigm from desktop and browser simply doesn't apply to Android. Even the concept of a program that starts with `public static void main(String[] args)` doesn't really apply to Android -- Android Java programming works in terms of activities and intents, not processes and command line parameters.

Certainly the purely algorithmic parts of your game, which don't depend on any external library, could in principle be used as-is, or almost-as-is, but all the platform interaction, from graphics, to sound, to input, is dramatically different.

Cross platformness is a state of mind, not a programming language. In fact, it is probably easier to port a C/C++ game that uses OpenGL from desktop to Android, than porting a native Java app/applet to Android.
> 2 votes

# Answer
It seems possible, albeit not being trivial:

https://gluonhq.com/products/mobile/javafxports/

“\[...\] brings Java and JavaFX to mobile \[…\] including iPhone, iPad, Android devices, and the Raspberry Pi.“

“Write once, run anywhere.“ I love that slogan!

It seems one 'just' has to install some development environments (and maybe some plug-ins), add a few lines of code, test and compile and most of the porting is done automatically.

I will try it. But I will need quite a while to get through this all. Good thing the website has a documentation that guides one through the whole process. Also there seems to be a community/forum about it right here: http://stackoverflow.com/questions/tagged/javafxports

In hindsight, I should have posted the question on Stack Overflow right from the beginning. But I guess, it cannot hurt being here.
> 0 votes

---
Tags: java, mobile, porting
---


# Question
Title: Material overridden when importing package between 2 pc
So I work with my colleague A and he has (for example) a basic scene

A exports the scene as package to give me.

and on my pc with new project I imported the package

everything is fine

and I make adjustment on material, and rename the scene and material

then I export the scene as package as well

now back to A's computer, he imports my package into his project with that basic scene

Wow ! In my scene, the new material is not assigned rather is the old red one.

How is this happening ? Please save me thank you

# Answer
> 1 votes
My best guess is that Unity changes the GUID of the imported item when it detects a collision with an existing asset. You might want to try duplicating the material and renaming the duplicate, instead of renaming the original. That way it should get a new, non-colliding GUID. (from DMGregory

---
Tags: unity, materials, import, export
---


title: Phaser 3 animation API

text:
# Question
Title: Phaser 3 animation API
I am following the tutorial for Phaser 3 game development and came across the following line of code.

```
player.anims.play('Left', true);

```

I am curious about the Boolean parameter here. What is the purpose of "true"? I searched through the API documents but was unable to find it. Thanks!

# Answer
> 0 votes
The documentation for the play method reads:

> **play(key \[, ignoreIfPlaying\] \[, startFrame\])**
> Plays an Animation on a Game Object that has the Animation component, such as a Sprite.
>
> Animations are stored in the global Animation Manager and are referenced by a unique string-based key.
>
> **Parameters:**
>
> | Name | Type | Argument | Default | Description |
> | --- | --- | --- | --- | --- |
> | key | string | Phaser.Animations.Animation |  |  | The string-based key of the animation to play, as defined previously in the Animation Manager. Or an Animation instance. |
> | **ignoreIfPlaying** | boolean |  | false | **If this animation is already playing then ignore this call.** |
> | startFrame | integer |  | 0 | Optionally start the animation playing from this frame index. |

So, `true` in the second argument says that if this same animation specified in `key` is already playing, don't interrupt it to execute the animation described in this call. If you pass `false` instead, then this animation call will stop the current animation - even if it's the one specified in `key` \- and take over with the animation you've specified, starting at `startFrame`.

# Answer
> 0 votes
I found the answer in this link as quoted below.

"Just wanted to expound upon this answer, for anyone who stumbles across this in the future. That second parameter on `anims.play` is named "ignoreIfPlaying." If false, whichever animation is currently playing will stop, even if it's the animation you intend to play. If true, then if you're already playing that animation it will continue.It's false by default, so you can omit the second argument entirely."

---
Tags: animation, phaser
---


# Question
Title: Is it possible to detect two different mice at the same time, and have their movements recorded separately?
I'm thinking of making a game that requires two mice to play. It needs to register the movements separately from one another. Is this possible? Or does the Windows architecture not allow for such things?

# Answer
> 5 votes
Because mice are just another kind of HID (human interface device) you can plug in as many as you want, but custom software is required to actually do anything with them, as Windows API will typically offer functions to get "the" mouse pointer.

There are some links over SuperUser, but be advised the answers there mainly contain links (sometimes dead) to vaporware, phantomware, and an academic article on ergonomics from 2004. There may be no real solutions there.

# Answer
> 2 votes
Looks like it can be done using calls to `user32.dll` to the GetRawInput\* methods.

There is an example of how to do this in rawinput-sharp.

I apologize for the link-only answer but the solution would make for quite a long post. The first link is the official documentation and the second is a C# wrapper you can use.

---
Tags: input, windows, mouse
---


# Question
Title: Simulating Road Traffic/Overtaking - Overtake works mostly, but starts clipping other vehicle
I am trying to improve on my Car class, which is used to make a small road scene with 3 lanes each direction with the ability to overtake by changing lanes.

I had a very basic version working with all box colliders and a predictive movement script in my code (so basically I performed the movement of the object, then immediately check a collision and move it to previous\_position in same frame). It worked OK but i found i was a bit clunky and I had to have oversized collision boxes on the car which caused me other problems elsewhere in the game.

Now I am using Raycast. At first I used just one Raycast from the centre of the car. But of course once the centre of the car had past the vehicle in front it would think road was clear. I tried to fix this by having 3 rays (centre, left, right in local space). This improved it a lot but the wingmirrors of the car (and often times a slice of the body) would clip into each-other.

I've ended up adding around 10 Raycasts trying to make sure it always sees the car in front. I even tried making the edge-most ones slightly past the width of the car.

The only thing I can think to mention is that the cars are rotated 90 degree. So transform.forward is actually facing either +/- X-Axis in world space depending on if isTopLane is true/false.

Here is the Car class in full. For the life of me I cannot figure out why the cars overtake but stop overtaking too early (ie. they continue straight through the edge of the car in front):

```
public class Car : MonoBehaviour
{
    bool isTopLane;
    float speed;

    float vehicle_width;
    float vehicle_length;
    Material material;

    AudioSource audioSource;
    float start_pitch;
    float max_pitch;

    float ray_length_forwards;
    float ray_length_sideways;

    public void InitCar(int spawn_z)
    {
        Color color = new Color(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f), 1);
        speed = Random.Range(Level_Road.car_speed_min, Level_Road.car_speed_max);

        if (spawn_z <= 0)
            isTopLane = false;
        else
            isTopLane = true;

        float x = -Level_Road.SPAWN_POSITION_X;
        Vector3 rot = Vector3.zero;
        rot.y = 90;
        if (isTopLane)
        {
            x *= -1;
            rot.y *= -1;
        }

        transform.position = new Vector3(x, 0, spawn_z);
        transform.eulerAngles = rot;

        material = GetComponentInChildren<MeshRenderer>().material;
        material.color = color;

        audioSource = GetComponent<AudioSource>();
        start_pitch = audioSource.pitch + (speed * 0.01f);
        max_pitch = start_pitch * 2.6f;

        vehicle_width = GetComponent<Collider>().bounds.size.x;
        vehicle_length = GetComponent<Collider>().bounds.size.z;
        ray_length_forwards = GetComponent<Collider>().bounds.size.z * 1.4f;
        ray_length_sideways = GetComponent<Collider>().bounds.size.x * 1.4f;

        if ((isTopLane && transform.position.z < 1.1f) || (!isTopLane && transform.position.z > -1.1f))
            speed = Level_Road.car_speed_max;

    }

    private void FixedUpdate()
    {
        if (GameManager.instance.Game_Paused)
            return;

        audioSource.enabled = GameManager.instance.Options_SoundOn;

        audioSource.pitch += (speed * 0.04f) * Time.fixedDeltaTime;
        if (audioSource.pitch > max_pitch)
            audioSource.pitch = start_pitch;

        Drive();
    }

    void Drive()
    {
        Vector3 centre = transform.position;
        Vector3 right1 = centre + Vector3.up * (vehicle_width * 0.1f);
        Vector3 right2 = centre + Vector3.up * (vehicle_width * 0.2f);
        Vector3 right3 = centre + Vector3.up * (vehicle_width * 0.3f);
        Vector3 right4 = centre + Vector3.up * (vehicle_width * 0.4f);
        Vector3 right5 = centre + Vector3.up * (vehicle_width * 0.5f);
        Vector3 right6 = centre + Vector3.up * (vehicle_width * 0.65f);
        Vector3 left1 = centre + Vector3.down * (vehicle_width * 0.1f);
        Vector3 left2 = centre + Vector3.down * (vehicle_width * 0.2f);
        Vector3 left3 = centre + Vector3.down * (vehicle_width * 0.3f);
        Vector3 left4 = centre + Vector3.down * (vehicle_width * 0.4f);
        Vector3 left5 = centre + Vector3.down * (vehicle_width * 0.5f);
        Vector3 left6 = centre + Vector3.down * (vehicle_width * 0.65f);
        Vector3[] ray_origins = { centre, right1, right2, right3, right4, right5, right6, left1, left2, left3, left4, left5, left6 };
        for (int i = 0; i < ray_origins.Length; i++)
        {
            if (Physics.Raycast(new Ray(ray_origins[i], transform.forward), out RaycastHit hit, ray_length_forwards))
            {
                if (hit.transform.gameObject.GetComponent<Car>())
                {
                    Overtake();
                    return;
                }

            }
        }

        DriveForwards();

    }

    void DriveForwards()
    {
        Vector3 motion = transform.forward * speed * Time.fixedDeltaTime;
        transform.position += motion;
    }

    void Overtake()
    {
        if (isTopLane && transform.position.z <= 1)
            return;

        if (!isTopLane && transform.position.z >= -1)
            return;

        if (Physics.Raycast(new Ray(transform.position, -transform.right), out RaycastHit hit, ray_length_sideways))
        {
            if (hit.transform.gameObject.GetComponent<Car>())
                return;
        }

        Vector3 motion = -transform.right * speed * Time.fixedDeltaTime;
        transform.position += motion;
    }

}

```

The behaviour I see in game is acting as if the `vehicle_width` is too thin. I have checked as best I can and my code to get the width seems correct `vehicle_width = GetComponent<Collider>().bounds.size.x;` I am quite sure the problem must lie in my Drive() function. Somehow the Ray Origins are positioned wrong. This is my guess, but I have tried many different ways. For me this seems impossible that the car can drive forwards if another car is in-front.

**Drastically widening the box trigger has actually given me some help. But it needs to be a lot wider than the car why is this?**

Thank you for your time and help.

# Answer
> 0 votes
Well thanks to the advice in the comments. I have sort of fixed it (although I am still baffled why the original code in the question doesn't work).

I fixed it by adding child object called `OvertakeZone` with a script component attached with the same name. In the picture you can see it is another collider much larger than the car.

Now my code looks like this. The cars give eachother enough space now but I must say its still not as big a space as the large collider suggests.

```
    void Drive()
    {
        if ((isTopLane && transform.position.z < 1.1f) || (!isTopLane && transform.position.z > -1.1f))
            speed = Level_Road.car_speed_max;

        Vector3 centre = transform.position;
        Vector3 right = centre + Vector3.up * (vehicle_width * 0.6f);
        Vector3 left = centre + Vector3.down * (vehicle_width * 0.6f);
        Vector3[] ray_origins = { centre, right, left};
        for (int i = 0; i < ray_origins.Length; i++)
        {
            if (Physics.Raycast(new Ray(ray_origins[i], transform.forward), out RaycastHit hit, ray_length_forwards))
            {
                if (hit.transform.gameObject.GetComponent<OvertakeZone>())
                {
                    Overtake();
                    return;
                }

            }
        }

        DriveForwards();

    }

    void DriveForwards()
    {
        Vector3 motion = transform.forward * speed * Time.fixedDeltaTime;
        transform.position += motion;
    }

    void Overtake()
    {
        if (isTopLane && transform.position.z <= 1)
            return;

        if (!isTopLane && transform.position.z >= -1)
            return;

        Vector3 centre = transform.position;
        Vector3 left = centre + Vector3.left * (vehicle_length * 0.6f);
        Vector3 right = centre + Vector3.right * (vehicle_length * 0.6f);
        Vector3[] ray_origins = { centre, right, left };
        for (int i = 0; i < ray_origins.Length; i++)
        {
            if (Physics.Raycast(new Ray(ray_origins[i], -transform.right), out RaycastHit hit, ray_length_forwards))
            {
                if (hit.transform.gameObject.GetComponent<OvertakeZone>())
                {
                    return;
                }

            }
        }

        Vector3 motion = -transform.right * speed * Time.fixedDeltaTime;
        transform.position += motion;
    }

```

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


# Question
Title: How to convert large grid data to easily saveable format?
I'm trying to recreate the grid system from RimWorld, and I'm facing an issue when having to save the map, which can be up to 500x500 tiles in size.

My map has multiple layers, the base layer is procedurally generated from a seed, so I can just save that seed and regenerate that terrain without having to save all of the tile data.

However, on that base layer, you can place floors and other things which by themselves don't hold any extra information.

The way Rimworld does this (according to their save file and based on my understanding), is that it somehow converts all of that grid data to one giant string, which at runtime is then "de-obfuscated" and loaded back as actual floor tiles.

Here's an example:

However, every other object which needs to hold any significant data is saved like this:

What would be a good way to save such simple data, similar to how Rimworld did it? 500x500 maps are huge on their own since every single grass already has to keep data about itself, and doing the same way of saving for things which only need e.g. location saved would create insanely large save files.

# Answer
This looks like they've...

* taken their array of tile information...
* converted it to an array of bytes...
* run the Deflate compression algorithm on those bytes to compress the byte stream...

(You can do this with the DeflateStream class )
* and converted that byte stream to a Bas64-encoded string.

(You can do this with Convert.ToBase64String() )

Then to load the map, you can run this process in reverse, to convert the Base64 string to an array or stream of bytes, decompress the byte array with the Deflate algorithm, and use those uncompressed bytes to deserialize into your map array.
> 1 votes

---
Tags: unity, c#, data-structure, savegame
---


# Question
Title: For some reason the player rotation is not that smooth as I thought it was. What could be the reason?
It seems that when the player starts rotating it looks like a small "jump" of the rotation and then the rotation gets smooth.

At the top of the script : because I want to rotate on the Y only :

```
Quaternion startRotation;
Quaternion endRotation;
float rotationProgress = -1;

```

In Start()

```
void Start()
{

    StartRotating(-40f);
}

void StartRotating(float yPosition)
{

    // Here we cache the starting and target rotations
    startRotation = transform.rotation;
    endRotation = Quaternion.Euler(transform.rotation.eulerAngles.x, yPosition, transform.rotation.eulerAngles.z);

    // This starts the rotation, but you can use a boolean flag if it's clearer for you
    rotationProgress = 0;
}

```

Then in FixedUpdate()

```

private void FixedUpdate()
{
    if (startRotatingBack)
    {
        if (rotationProgress < 1 && rotationProgress >= 0)
        {
            rotationProgress += Time.deltaTime * rotationSpeed;

            // Here we assign the interpolated rotation to transform.rotation
            // It will range from startRotation (rotationProgress == 0) to endRotation (rotationProgress >= 1)
            transform.rotation = Quaternion.Lerp(startRotation, endRotation, rotationProgress);
            //transform.GetComponent<Rigidbody>().MoveRotation(Quaternion.Lerp(startRotation, endRotation, rotationProgress));
        }

        if (exitSpaceShipSurroundingArea)
        {

            playerAnimator.SetFloat("Forward", Mathf.Lerp(min, max, t));
            t += 1f * Time.deltaTime;
        }
        else
        {
           var distance = Vector3.Distance(transform.position,spaceShip.position);

           distanceText.text = distance.ToString();

           if (distance < 90f)
           {
               if (slowDownBack == false)
               {
                   playerAnimator.SetFloat("Forward", Mathf.Lerp(min, max, t));
                   t -= 1f * Time.deltaTime;
               }

               if (playerAnimator.GetFloat("Forward") == 0)
               {
                  ThirdPersonUserControl.stop = false;
                  slowDownBack = true;
                  startRotatingBack = false;
               }
           }
        }
    }
}

```

I tried also using Rigidbody MoveRotation but with the same result the first frame or some frames the rotation is like "jumping" then getting smooth. not sure why it's not smooth slowly rotating from the beginning.

Tried also this but still, the beginning is not smooth.

```
if (rotationProgress < 1 && rotationProgress >= 0)
{
    transform.rotation = Quaternion.Lerp(startRotation, Quaternion.Euler(new Vector3(transform.rotation.eulerAngles.x, -40f, transform.rotation.eulerAngles.z)), rotationProgress);
    rotationProgress += Time.fixedDeltaTime * rotationSpeed;
}

```

In this case, it should rotate smoothly towards degrees -40 the main goal is to rotate the transform towards a target but it's not rotating smoothly at the beginning yet.

I solved it :

The problem was that I referenced for the transform rotation at the Start() but the transform rotation was not the same when start rotating.

The solution is to start rotating from the current rotation :

```
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(new Vector3(transform.rotation.eulerAngles.x, -40f, transform.rotation.eulerAngles.z)), rotationProgress);

```

This part :

```
Quaternion.Lerp(transform.rotation

```

And NOT :

```
Quaternion.Lerp(startRotation

```

# Answer
The problem was that I referenced the transform rotation at the Start() but the transform rotation was not the same when start rotating.

The solution is to start rotating from the current rotation :

```
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(new Vector3(transform.rotation.eulerAngles.x, -40f, transform.rotation.eulerAngles.z)), rotationProgress);

```

This part :

```
Quaternion.Lerp(transform.rotation

```

And NOT :

```
Quaternion.Lerp(startRotation

```
> 1 votes

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