# Question
Title: How can I spawn and unspawn chunks of tiles while the player moves through an infinite game world?
I have a procedural generated 100x100 land. I want to spawn it infinitely as the player moves on the horizontal axis, and also disappear if the player is too far. The way I generated the land is a bit weird. First I generated the plain 100x100 with sprites. Each sprite has a chance of spawning a sprites (like rock or cactus).

How can I spawn those chucks if the player moves closer to the chuck and disappear if the player moves farther away?

# Answer
> 1 votes
This is a very common design for large worlds.

You can test the distance between the player and the positions of your different chunks frequently. You also have to set a maximum distance when a chunk is loaded.

Then, it's a very simple condition:

* When the distance is less than maximum distance, you load the chunk.
* If a chunk is loaded and the distance is greater than maximum distance, you unload the chunk.

You can calculate the distance with a simple Pythagorean theorem or just use Unity's Vector3.Distance.

You first need some struct or class to represent your chunks:

```
public struct Chunk {
    public string name;
    public bool loaded = false;
}

```

Then, you can create an empty GameObject that will handle the chunk management. Here is a very rough outline to give you a direction, but you will have to fine tune it to fit the specific needs of your project.

```
using UnityEngine;
using System.Collections;

public class ChunksLoader : MonoBehaviour
{
    public Dictionary <Vector3, Chunk> chunks;
    public GameObject player;
    public float maximumDistance = 50f;

    void Awake()
    {
        chunks = new Dictionary<Vector3, Chunk>();
    }

    public void PopulateChunks() {
        /* You populate your dictionary here, as a custom editor is not needed since you generate your world.
        You can call this function when your procedural generation is finished, for example. */
    }

    void Update()
    {
        Vector3 playerPosition = player.transform.position;
        foreach (KeyValuePair<Vector3, Chunk> chunk in chunks) {
            if (chunk.Value.loaded == false && Vector3.Distance(chunk.Key, playerPosition) < 50f) {
                StartCoroutine(LoadChunk(chunk.Value));
            } else if (chunk.Value.loaded) {
                StartCoroutine(UnloadChunk(chunk.Value));
            }
        }
    }

    IEnumerator LoadChunk(Chunk chunk) {
        AsyncOperation async = SceneManager.LoadSceneAsync(chunk.name, LoadSceneMode.Additive);
        while (!async.isDone)
        {
            yield return null;
        }
        chunk.loaded = true;
    }

    IEnumerator UnloadChunk(Chunk chunk) {
        AsyncOperation async = SceneManager.UnloadSceneAsync(chunk.name);
        while (!async.isDone)
        {
            yield return null;
        }
        chunk.loaded = false;
    }
}

```

I didn't make many optimizations and this will need adjustments to work in your project. However, one of the most important optimizations (and a very simple one) is to test the bool `loaded` *before* checking the distance, since you can avoid this way some unneeded computations.

The two IEnumerator will also need adjustments to fit your needs. You can find a few examples in the official documentation.

For the infinite "loop" of your world's chunks you can just use a modulo operator on your player coordinates but it depends on how you want it to be infinite.

---
Tags: unity, procedural
---


# Question
Title: Is ray tracing performance dependent on polygon count
I want to know if mesh polygon count affects raytracing performance, by Raytracing I mean Nvidia's RTX or similar hardware accelerated raytracing.

So If I have a scene with high poly objects and total poly count of 20 million triangles and another scene but with 1 million triangles, will it work faster with 1 million.

If yes, then does the performance decrease in linear ?

# Answer
Raytracing solutions tend to use a bounding volume hierarchy to accelerate searches for the closest hit along a ray. That means your scene geometry is organized into something like a tree. If a ray misses the bounding volume of one branch of that tree, then the entire branch and all its twigs and leaves can be skipped over.

So, given no other information about the scene contents or the details of the raycasting queries being performed, we'd expect this to scale similarly to other tree search algorithms: ie. logarithmically.

That means raycasting a scene with 1 million triangles will usually be faster than doing the same in a scene with 20 million triangles, but not 20 times faster.

The particular scaling factors will depend on details of your scene geometry (do you have a lot of clusters of geometry well separated from each other, so the BVH can prune lots of it out of the path of your search? Or is all your geometry densely packed in the path of the rays you tend do shoot, so we have to visit most of it during a particular search?), the kinds of raycasting queries you use, and the particular graphics card and driver you're running on.

So as always with performance questions, the best way to get accurate answers for your use case is to build a test and profile the results.
> 3 votes

---
Tags: raytracing
---


# Question
Title: How can I resize a game object using single drag handle?
Really need your help. I'm trying to create a custom controller for my app to allow users to resize and rotate game objects using a single drag object.

I was able to create the code to create the visuals and to rotate it but I'm stuck on how to resize the game object. To position the drag handle at the start, I'm getting the bounds of the target object and taking the `bounds.extents.magnitude` to determine the y position.

So I was hoping the behavior would be such that when you drag the handle closer to the center of the target object it shrinks the `bounds.extents.magnitude` based on the new handle position and then becomes bigger if you go further away from the center of the target object.

Here is where I am now:

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

public class CircleMaker : MonoBehaviour
{
    public float lineWidth = .1f;
    private int segments=360;
    private LineRenderer line;
    private float radius;
    private Renderer boundsSource;
    private Bounds bounds;
    public GameObject dragHandle;
    public GameObject target;
    private int pointCount;
    private Vector3[] points;
    public int angle = 0;
    public float zPosition = -8.0f;
    public bool isDraggingHandle = false;

    void Start()
    {
        line = GetComponent<LineRenderer>();
        boundsSource = target.GetComponent<Renderer>();
        bounds = boundsSource.bounds;
        line.useWorldSpace = true;
        line.startWidth = lineWidth;
        line.endWidth = lineWidth;
        line.positionCount = segments + 1;
        line.receiveShadows = false;
        line.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;

        pointCount = segments + 1;
        points = new Vector3[pointCount];

        float r = bounds.extents.magnitude;
        float d2r = Mathf.Deg2Rad * (target.transform.localEulerAngles.x * 360f / segments);
        dragHandle.transform.position = new Vector3(Mathf.Sin(d2r) * r, Mathf.Cos(d2r) * r, zPosition) + target.transform.position;

        DrawCircle();

    }

    void Update()
    {
        if (isDraggingHandle)
        {
            //rotate object based on drag handle location
            Vector3 direction = target.transform.position - dragHandle.transform.position;
            int sign = (direction.x >= 0) ? 1 : -1;
            float offset = (sign >= 0) ? 0 : 360;
            float angle = Vector2.Angle(Vector2.down, direction)*sign+offset;
            target.transform.rotation = Quaternion.Euler(0, 0, angle);

        }

        if (target.GetComponent<DragAndDrop>().isDragging == true)
        {
            dragHandle.transform.parent = target.transform;
        }
        else
        {
            dragHandle.transform.parent = null;
        }

        DrawCircle();
    }

    //draw circle around target gameobject based on bounds.extents
    void DrawCircle()
    {
        radius = bounds.extents.magnitude*target.transform.localScale.x;
        for (int i = 0; i < pointCount; i++)
        {
            float rad = Mathf.Deg2Rad * (i * 360f / segments);
            points[i] = new Vector3(Mathf.Sin(rad) * radius, Mathf.Cos(rad) * radius, zPosition) + target.transform.position;
        }

        line.SetPositions(points);
    }
}

```

# Answer
fjmacs!

I created a solution for your answer; hope that's not too late.

Here you can see the whole project, with screenshots: https://github.com/burkard/ResizeHandler

If you prefer, simply use the two following scripts:

**ObjectResizer.cs**

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

public class ObjectResizer : MonoBehaviour
{
    public bool isBeingResized;
    private Bounds bounds;
    public float lineWidth = .1f;
    public float handlerSize = 0.2f;

    private int segments = 360;
    private int pointCount;
    private Vector3[] points;
    private float zPosition = 0.0f;
    private float radius;
    private LineRenderer line;

    private GameObject handler, raycastPlane;
    private float initialScale;
    private Quaternion initialRotation;

    void Start()
    {
        bounds = this.gameObject.GetComponent<Renderer>().bounds;
        isBeingResized = false;
        pointCount = segments + 1;
        initialScale = transform.localScale.x;
        initialRotation = transform.rotation;
    }

    void Update()
    {
        if (isBeingResized)
        {
            DrawCircle();
            ResizeObject();
            RotateObject();
        }
    }

    private void ResizeObject()
    {
        if (handler.GetComponent<ResizeHandler>().Scale() > 0)
            transform.localScale = Vector3.one * initialScale * handler.GetComponent<ResizeHandler>().Scale();
    }

    private void RotateObject()
    {
        transform.rotation = initialRotation;
        float rotAngle = handler.GetComponent<ResizeHandler>().Angle();
        transform.Rotate(Camera.main.transform.forward, rotAngle, Space.World);
    }

    private void OnMouseUp()
    {
        isBeingResized = !isBeingResized;
        if (isBeingResized) AddLineRenderer();
        else RemoveLineRenderer();
    }

    private void AddLineRenderer()
    {
        if (line == null)
        {
            points = new Vector3[pointCount];
            this.gameObject.AddComponent<LineRenderer>();
            line = this.gameObject.GetComponent<LineRenderer>();
            line.startWidth = lineWidth; line.endWidth = lineWidth;
            line.positionCount = pointCount;
            line.material = new Material(Shader.Find("Sprites/Default"));
            line.startColor = Color.blue; line.endColor = Color.blue;

            handler = GameObject.CreatePrimitive(PrimitiveType.Sphere);
            handler.transform.localScale = new Vector3(handlerSize, handlerSize, handlerSize);
            handler.gameObject.AddComponent<ResizeHandler>();
            handler.GetComponent<ResizeHandler>().parentCenter = transform.position;

            Vector3 cameraDirection = transform.position - Camera.main.transform.position;
            radius = bounds.extents.magnitude * this.transform.localScale.x * 1.2f;
            float rad = Mathf.Deg2Rad * (360f / segments);
            Vector3 handlerPos = new Vector3(Mathf.Sin(rad) * radius, Mathf.Cos(rad) * radius, zPosition) + this.transform.position;
            handlerPos = RotatePointAroundPivot(handlerPos, transform.position, cameraDirection);
            handler.transform.position = handlerPos;

            raycastPlane = GameObject.CreatePrimitive(PrimitiveType.Plane);
            Destroy(raycastPlane.GetComponent<MeshRenderer>());
            raycastPlane.transform.LookAt(Camera.main.transform);
            raycastPlane.transform.Rotate(new Vector3(90, 0, 0));
            raycastPlane.transform.localScale = new Vector3(1000f, 1000f, 1000f);
            raycastPlane.layer = 5;
        }
    }

    private void RemoveLineRenderer()
    {
        if (this.gameObject.GetComponent<LineRenderer>() != null)
        {
            Destroy(this.gameObject.GetComponent<LineRenderer>());
            points = null;
            Destroy(handler.gameObject);
            Destroy(raycastPlane.gameObject);
            initialScale = transform.localScale.x;
            initialRotation = transform.rotation;
        }
    }

    void DrawCircle()
    {
        Vector3 cameraDirection = transform.position - Camera.main.transform.position;

        radius = bounds.extents.magnitude * this.transform.localScale.x * 1.2f;
        for (int i = 0; i < pointCount; i++)
        {
            float rad = Mathf.Deg2Rad * (i * 360f / segments);
            points[i] = new Vector3(Mathf.Sin(rad) * radius, Mathf.Cos(rad) * radius, zPosition) + this.transform.position;
            points[i] = RotatePointAroundPivot(points[i], transform.position, cameraDirection);
        }

        line.SetPositions(points);
        line.alignment = LineAlignment.View;
    }

    Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Vector3 angles){
        Vector3 dir = point - pivot; // get point direction relative to pivot
        dir = Quaternion.LookRotation(angles, Vector3.up) * dir; // rotate it
        point = dir + pivot; // calculate rotated point
        return point; // return it
    }

    public void StopResizing()
    {
        isBeingResized = false;
        RemoveLineRenderer();
    }
}

```

**ResizeHandler.cs**

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

public class ResizeHandler : MonoBehaviour
{
    public Vector3 parentCenter = Vector3.zero;
    private Camera mainCam;
    private float startDistance, currentScale, currentAngle;
    private Vector3 startPosition;

    private void Start()
    {
        mainCam = Camera.main;
        startDistance = (transform.position - parentCenter).magnitude;
        currentScale = (transform.position - parentCenter).magnitude / startDistance;
        startPosition = transform.position;

        startPosition = transform.position;
    }

    private void OnMouseDrag()
    {
        Ray castPoint = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        LayerMask mask = LayerMask.GetMask("UI");
        if (Physics.Raycast(castPoint, out hit, Mathf.Infinity, mask))
        {
            transform.position = hit.point;
        }
        currentScale = (transform.position - parentCenter).magnitude / startDistance;
        currentAngle = CalculateAngle();
    }

    public float Scale()
    {
        return currentScale;
    }
    public float Angle()
    {
        return currentAngle;
    }

    private float CalculateAngle()
    {
        Vector3 startVector = startPosition - parentCenter;
        Vector3 endVector = transform.position - parentCenter;
        float angle = Vector3.Angle(startVector, endVector);

        float sign = Mathf.Sign(Vector3.Dot(mainCam.transform.forward, Vector3.Cross(startVector, endVector)));
        return angle * sign;
    }

}

```

Good work!
> 1 votes

# Answer
I'll give a brief answer to complement Fabio's great but in-depth answer: you need to set `target.transform.localScale` of the object to change its size.

To determine the scale, you need some kind of frame to work within: locations for the start and end of the handle track so you can determine what handle position means tiny and where is full size. (Looks like you're changing the size of the circle to match the scale.)

Then you can use the ratio between where you are within the track and the limits of the track to determine the scale:

```
var centre = target.transform.position;
var handle = dragHandle.transform.position;
var max_radius = 2f;
var distance = Vector3.Distance(centre, handle);
target.transform.localScale = Mathf.InverseLerp(0.001f, max_radius, distance);

```
> 0 votes

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


# Question
Title: Debugging shader script in GLSL ES - Game Maker 2 (CompileError)
I am trying to use this shader in the game I am making with Game Maker Studio 2.

I tried to convert it for GM2 and here is my result:

Shader type I used on GM2 is `GLSL ES`

**myshader.vsh**

```
attribute vec3 in_Position;                  // (x,y,z)
//attribute vec3 in_Normal;                  // (x,y,z)     unused in this shader.
attribute vec4 in_Colour;                    // (r,g,b,a)
attribute vec2 in_TextureCoord;              // (u,v)

varying vec2 v_vTexcoord;
varying vec4 v_vColour;

void main()
{
    vec4 object_space_pos = vec4( in_Position.x, in_Position.y, in_Position.z, 1.0);
    gl_Position = gm_Matrices[MATRIX_WORLD_VIEW_PROJECTION] * object_space_pos;

    v_vColour = in_Colour;
    v_vTexcoord = in_TextureCoord;
}

```

**myshader.fsh**

```
varying vec2 v_vTexcoord;
varying vec4 v_vColour;

uniform vec2 resolution;
uniform float pixelSize;
uniform float gamma;

void main(){
    vec2 uv = gl_FragCoord.xy / resolution.xy;
    float alpha = 1.0;
    vec4 color = v_vColour * texture2D( gm_BaseTexture, v_vTexcoord );
    gl_FragColor = color;

    float pixelSize = 3.0;
    float gamma = 3.0;

    vec2 pseudoResolution = floor(resolution.xy / pixelSize);
    vec2 pseudoPixel = floor(gl_FragCoord.xy / float(pixelSize));
    vec2 pseudoUv = pseudoPixel / pseudoResolution;

    vec3 tex = texture2D(gm_BaseTexture, pseudoUv).rgb;
    float bw = (tex.r + tex.g + tex.b) / gamma;
    float col = 0.0;

    if(bw > 0.8) {
        col = 1.0;}
    else if (bw > 0.6) {
        col = float(!(int(pseudoPixel.x) % 2 == 0 && int(pseudoPixel.y) % 2 != 0));}
        else if (bw > 0.4) {
        col = float((int(pseudoPixel.x) % 2 + int(pseudoPixel.y) % 2) % 2 == 0);}
        else if(bw > 0.2) {
        col = float(int(pseudoPixel.x) % 2 == 0 && int(pseudoPixel.y) % 2 == 0);}
    gl_FragColor = color * vec4(col, col, col, alpha);}

```

But this is just throwing this compile error:

`Fragment Shader: shd_1BitDithering at line 30 : ''`

Line 30 is:

```
25    if(bw > 0.8) {
26      col = 1.0;}
27  else if (bw > 0.6) {
28      col = float(!(int(pseudoPixel.x) % 2 == 0 && int(pseudoPixel.y) % 2 != 0));}
29      else if (bw > 0.4) {
-> 30   col = float((int(pseudoPixel.x) % 2 + int(pseudoPixel.y) % 2) % 2 == 0);}
31      else if(bw > 0.2) {
32      col = float(int(pseudoPixel.x) % 2 == 0 && int(pseudoPixel.y) % 2 == 0);}
33  gl_FragColor = color * vec4(col, col, col, alpha);}

```

Coming from a Python background, I really have no idea how to debug that message.

Any clue on how could I make this shader work, or how could I understand what the problem is?

# Answer
> 1 votes
Ok, so I managed to get it working.

My code had many problems, first of all the modulus operand `%` which is not supported by GLSL ES.

I had to use the `mod` function and, as I found on the official docs, the function needs to be called with the two operands as parameters. As I can understand from the docs, I also had to give the value to divide for as a float.

Applied this, the code gets more and more confusing because of the many parentheses: on line 30 the original script is making a modulus of a modulus, which has been a bit confusing to convert with the mod function syntax.

Fixed this, it was giving out an error on the "==" operand, so I made any number involved in a comparison a float, this fixed it.

The updated code (only the if cycle) is here:

```
if (bw > 0.8)
{
    col = 1.0;
}
else if (bw > 0.6)
{
    col = float(!(mod(pseudoPixel.x, 2.0) == 0.0) && (mod(pseudoPixel.y, 2.0) != 0.0));
}
else if (bw > 0.4)
{
    col = float(mod((mod(pseudoPixel.x, 2.0) + mod(pseudoPixel.y, 2.0)), 2.0) == 0.0);
}
else if (bw > 0.2)
{
    col = float((mod(pseudoPixel.x, 2.0) == 0.0) && (mod(pseudoPixel.y, 2.0) == 0.0));
}

```

---
Tags: shaders, glsl, game-maker, fragment-shader, game-maker-studio-2
---


title: Creating a custom camera in Godot

text:
# Question
Title: Creating a custom camera in Godot
Allow me to start with what I'm trying to achieve - there might be an easier way to do this and I'm just overcomplicating things.

I'm trying to implement a camera, that will be able to rotate around a single pivot point. The point doesn't have to move (although accounting for it might be useful for the future). I found this answer on Godot's Q&A that suggest a simple solution - nest the camera under a single `Spatial` node. Just by doing that and toying around with node properties in editor, I'm able to move the camera just in the way I wanted by applying simple transformations (on my end, the engine certainly has to calculate everything).

This would have been it, except for this simple issue. Let's say I want this camera to be reusable - I pack it into a `PivotedCamera` scene and instantiate it in my main game scene. Now whenever I want to access the camera's methods (`project_ray_origin()`, etc.), I have to go one layer deeper into the scene tree. Swapping a `Camera` for `PivotedCamera` now requires a change to the code. What is the most sensible way to solve that?

My current idea is to simply implement `Camera`'s methods in the parent `Spatial` node which merely call the child's methods and return the values, but that feels clunky and prone to breaking changes when new methods are added to the `Camera` class. A scenario that I'd prefer would be somehow returning a reference to the `Camera` child in the `get_node("CameraPivot")` call, instead of a reference to the `Spatial` node. I do not (should not) need to access the `Spatial` node as all transforms are done in an attached script and react to input.

**P.S.:** This answer here on Gamedev.SE goes deeper into solving the same issue, except in plain OpenGL, however, it feels a bit too "spartan" to be a good solution in Godot. Please do correct me if it is the best way to go!

# Answer
First of all, I want to say, I sympathize. I have gone down the path of making a custom variation of a Node by composition and turning it into a scene and then having to rely on reaching deep into the structure to use it. And I have also implemented property delegates for ease of use.

The current Godot response is Editable Children. You can instance a scene with editable children, and this will allow you to overwrite the properties of the children on the editor.

*There have also been some proposals. For example: Automate delegation of exported properties to internal nodes to improve GDScript abstractions.*

---

> but that feels clunky and prone to breaking changes when new methods are added to the Camera class.

I submit to you that the engine will not change behind your back.

If you are making a game, you decide if and when you upgrade to a new version of the engine, at which point you can update your class.

If you are making an addon or library, it is expected that you would release a new version if there are significant changes to the engine.

*And you might even have a tool generate the code for your custom class.*

*However, I understand this is not ideal.*

---

On the issue with what you want…

You could talk directly to `VisualServer` to create a low level camera (which is what the `Camera` node does behind the scenes). Or you could simply create the `Camera` node from code. But the node that does it would not be a `Camera`. So when you get it with `get_node`, what you get is not a `Camera`.

That leads you to either delegate the properties of a `Camera`… Or extend `Camera` except its `Transform` will not longer be the position of the camera, instead the position would be based on that `Transform` plus some other `Transform` that describe its motion around a point. That is, you want to break Liskov substitution principle.

The correct approach, is not to make a `Camera`, but a thing that has a `Camera`, and there is a perfectly reasonable to do that in engine: A `Spatial` with a `Camera`. And there is a perfectly reasonable way to reuse it: a scene. We are not going to change that.

So, we need a workaround `get_node` to get a `Camera`, and we need a solution to delegate the properties.

---

Before we go into that, I want to suggest an alternative approach. Consider that sometimes you might want to orbit something around something else… And have that first something not be a `Camera`. It is possible to create a custom `Node` that extends `Spatial`, that has the logic to orbit around something else (perhaps taking advantage of a `NodePath`). You can conceptualize it as a `Joint`, or you can conceptualize it a `RemoteTransform`.

In fact, it might be useful to have different controls for the `Camera` (e.g. first person, third person orbiting around the player, looking from a fixed position in a room, etc) and interpolate between them with an `InterpolatedCamera`. In fact, you don't necessarily need custom `Camera`s for those cases, you just need `Spatial`s to serve as targets for the `InterpolatedCamera`.

---

Not convinced? Ok...

> All problems in computer science can be solved by another level of indirection.

-- Attributed to Butler Lampson

So, we have `Camera`s, and we have `Camera`-like things. Let us call them `CameraHolder`. We are going to make a helper that gives you a `Camera` regardless if you give it a `Camera` or a `CameraHolder`. Easy:

```
class_name CameraGetter extends Object

static func from(node:Node) -> Camera:
    var camera_holder:CameraHolder = node as CameraHolder
    var camera:Camera

    if is_instance_valid(camera_holder)
        camera = camera_holder.get_camera()
    else:
        camera = node as Camera

    if is_instance_valid(camera)
        return camera

    return null

```

And now you can say `CameraGetter.from(get_node("CameraPivot"))` and it will give you a `Camera`.

We of course need to write the class `CameraHolder`. It must have a `get_camera` method. And we want to be able to use as if it were a `Camera`, in particular we want to appear to have all the properties of a `Camera`.

And that last part is tricky. This is the outline of what we will use:

```
tool class_name CameraHolder extends Spatial

func get_camera() -> Camera:
    return null

func _get_property_list() -> Array:
    return []

func _get(property: String):
    return null

func _set(property: String, value) -> bool:
    return false

```

First thing to notice is that there is a method `get_camera`, which in this case returns null. We will make everything else will refer to that `get_camera` method, so that a class that extends this one can simply override it.

Second, we are using `_get_property_list`. Godot will call `get_property_list` (which will call `_get_property_list` behind the scenes) to figure out what properties the `Node` exposes. In particular `_get_property_list` must return what *additional* properties the `Node` exposes. *With `_get_property_list` you can do what you would do with `export` and much more.*

The idea is to report all the properties of a `Camera`, and we can get one of those from `get_camera`, so we will use that to get its properties. We don't want to tell the editor to persist these properties, because we will delegate them to a `Camera` node that can be persisted instead. I will come back to that.

Then we have `_get` and `_set`, which will handle the case when we set properties that the `Node` does not have. However, you need to know that Godot will call them first, and only when they report that the property does not exist, then it will go to an actual property.

This is a problem, because we cannot rely on whether or not the `Camera` has a property, because our `Node` is also a `Spatial` and we don't want to delegate the its properties.

*In fact, one of the properties is the `script`, and I spent a lot of time figuring out why the script was disappearing. It was because I was delegating the `script` property to a `Camera` that didn't have a script.*

This problem is further complicated by the fact that calling `get` from `_get` will result in a stack overflow. *Similarly calling `get_property_list` from `_get_property_list` is a stack overflow.* And Godot will crash.

Thus, first we need to somehow sort out what properties do an `Spatial` have.

**Addendum**: Using `ClassDB.class_get_property_list` is a better way to do this (so we don't have to create a node to ask it about its properties and we don't need to memoize the results). However, I'm keeping my old solution for reference.

This is the solution I came up with:

```
var _spatial_property_names:Array = []

func _get_spatial_property_names() -> Array:
    if _spatial_property_names.size() == 0:
        var spatial = Spatial.new()
        var spatial_properties = spatial.get_property_list()
        for property in spatial_properties:
            if property.type == TYPE_NIL:
                continue

            _spatial_property_names.append(property.name)

        spatial.free()

    return _spatial_property_names

```

That is, we are going to create a new `Spatial`, and ask it what properties does it have. We also skip `TYPE_NIL`, because these are used to communicate property categories to the editor. They are not real properties. And, of course, also memoize the result in an array for future reference. *We don't want to make a node every time we need this.*

---

Now, we can build our property list like this:

```
var _camera_properties:Array = []

func _get_property_list() -> Array:
    var spatial_property_names = _get_spatial_property_names()
    if _camera_properties.size() == 0:
        var camera:Camera = get_camera()
        if is_instance_valid(camera):
            var properties = camera.get_property_list()
            for property in properties:
                if !spatial_property_names.has(property.name):
                    property.usage = property.usage & ~PROPERTY_USAGE_STORAGE
                    _camera_properties.append(property)

    return _camera_properties

```

As you can see, if a property is in the list of properties that `Spatial` has, it is not an additional property. It would be a duplicate. And we don't report it.

For those that we report, we make sure they don't have the flag `PROPERTY_USAGE_STORAGE` set, so the editor will not persist them. *We, of course, want to let the editor persist the `Spatial` properties, which we skipped.*

And we are also memoizing this result.

---

Finally, these are `_get` and `_set`:

```
func _get(property: String):
    var spatial_property_names = _get_spatial_property_names()
    if spatial_property_names.has(property):
        return null

    var camera:Camera = get_camera()
    if is_instance_valid(camera):
        return camera.get(property)

    return null

func _set(property: String, value) -> bool:
    var spatial_property_names = _get_spatial_property_names()
    if spatial_property_names.has(property):
        return false

    var camera:Camera = get_camera()
    if is_instance_valid(camera) and property in camera:
        get_camera().set(property, value)
        return true

    return false

```

As you would expect, we rely on `_get_spatial_property_names` to know what property to avoid delegating to the `Camera`.

*Ah, and `get_camera` can keep returning null. It is ok. We are checking with `is_instance_valid` everywhere we use it.*

Now, we can extend that class to implement `CameraPivot`:

```
tool class_name CameraPivot extends CameraHolder

func get_camera() -> Camera:
    if is_inside_tree():
        return get_node_or_null("Camera") as Camera

    return null

```

Here I'm being extra careful because I know Godot will call this in `_get_property_list`. So I do not to call `get_node` which can result in an error, I call `get_node_or_null`. And I do not call `get_node_or_null` if the `Node` is not in the scene tree.

And this is my implementation for the orbit logic:

```
export(float) var orbit_distance:float setget set_orbit_distance
export(float, -180, 180) var orbit_yaw:float setget set_orbit_yaw
export(float, -180, 180) var orbit_pitch:float setget set_orbit_pitch
export(float, -180, 180) var orbit_roll:float setget set_orbit_roll

func set_orbit_distance(new_value:float) -> void:
    orbit_distance = new_value
    update_transform()

func set_orbit_yaw(new_value:float) -> void:
    orbit_yaw = new_value
    update_transform()

func set_orbit_pitch(new_value:float) -> void:
    orbit_pitch = new_value
    update_transform()

func set_orbit_roll(new_value:float) -> void:
    orbit_roll = new_value
    update_transform()

func update_transform() -> void:
    var camera:Camera = get_camera()
    if !is_instance_valid(camera):
        return

    camera.transform = \
          Transform.IDENTITY.rotated(Vector3.UP, deg2rad(orbit_yaw)) \
        * Transform.IDENTITY.rotated(Vector3.RIGHT, deg2rad(orbit_pitch)) \
        * Transform.IDENTITY.rotated(Vector3.FORWARD, deg2rad(orbit_roll)) \
        * Transform.IDENTITY.translated(Vector3.BACK * orbit_distance)

```

You don't have to do it this way, of course. You can extend `CameraHolder` and implement `get_camera` to get you the `Camera` from wherever you have it, and add whatever properties and methods make sense to you.

*The only thing missing is that the "Preview" toggle will not appear for out `CameraHolder` or our `CameraPivot`. I suppose this can addressed with a custom gizmo (which is a type of plugin). However, I haven't delved into that.*

---

## Addendum on subclassing `Camera`.

One of the problem I ran on while testing the above solution was that I was delegating some properties that I shouldn't. Which have led to the question: Can we intercept a property? And I don't mean to override it, much less remove it. The property must remain there, and still work, so it does not break any functionality.

As you know, if we do this:

```
extends Camera

var transform:Transform

```

We get an error. That does not work.

But… We can use `_get` and `_set`!

The first part to figure out was what to intercept. So I set a `_get` and `_set` that would print whatever property is being access. And I found a couple things:

* Moving the node from the spatial gizmo avoid `_get` and `_set` entirely. Will deal with that later.
* Moving the node from the inspector panel will interact with "scale", "translation" and "rotation\_degrees"

So we will intercept those, and of course "transform" too. That is something like this:

```
tool extends Camera

var _base_transform:Transform

func _get(property: String):
    match property:
        "transform":
            return self._base_transform
        "scale":
            return self._base_transform.basis.get_scale()
        "translation":
            return self._base_transform.origin
        "rotation_degrees":
            return self._base_transform.basis.get_euler() * 180/PI
        _:
            return null

func _set(property: String, value) -> bool:
    match property:
        "transform":
            self._base_transform = value
            return true
        "scale":
            var quat = self._base_transform.basis.get_rotation_quat()
            self._base_transform.basis = Basis(quat).scaled(value)
            return true
        "translation":
            self._base_transform.origin = value
            return true
        "rotation_degrees":
            var scale = self._base_transform.basis.get_scale()
            self._base_transform.basis = Basis(Quat(value * PI/180)).scaled(scale)
            return true
        _:
            return false

```

*Those `self` will become relevant soon.*

With this code, when you modify the transform from the inspector panel, you are actually editing this new `_base_transform` variable.

Now, we want to reintroduce our orbit properties. These look the same:

```
export(float) var orbit_distance:float setget set_orbit_distance
export(float, -180, 180) var orbit_yaw:float setget set_orbit_yaw
export(float, -180, 180) var orbit_pitch:float setget set_orbit_pitch
export(float, -180, 180) var orbit_roll:float setget set_orbit_roll

func set_orbit_distance(new_value:float) -> void:
    orbit_distance = new_value
    update_transform()

func set_orbit_yaw(new_value:float) -> void:
    orbit_yaw = new_value
    update_transform()

func set_orbit_pitch(new_value:float) -> void:
    orbit_pitch = new_value
    update_transform()

func set_orbit_roll(new_value:float) -> void:
    orbit_roll = new_value
    update_transform()

```

But we will change `update_transform` to this:

```
func get_relative_transform() -> Transform:
    return Transform.IDENTITY.rotated(Vector3.UP, deg2rad(orbit_yaw)) \
    * Transform.IDENTITY.rotated(Vector3.RIGHT, deg2rad(orbit_pitch)) \
    * Transform.IDENTITY.rotated(Vector3.FORWARD, deg2rad(orbit_roll)) \
    * Transform.IDENTITY.translated(Vector3.BACK * orbit_distance)

func update_transform() -> void:
    transform = _base_transform * get_relative_transform()

```

That is, I extracted `get_relative_transform` from `update_transform`. *And also, I'm not dealing with a child `Camera`, since the `Camera` is the `Node` we are working on.*

Why?

Well, as I said, when we move the `Node` using the spatial gizmo, that avoids `_get` and `_set`. We need changes to `_base_transform` to become changes to `transform` and changes to `transform` to become changes to `_base_transform`. We accomplish this by giving a getter and a setter to `_base_transform`:

```
var _base_transform:Transform setget set_base_transform, get_base_transform

func set_base_transform(new_value:Transform) -> void:
    _base_transform = new_value
    update_transform()

func get_base_transform() -> Transform:
    _base_transform = transform * get_relative_transform().affine_inverse()
    return _base_transform

```

And there we are using `get_relative_transform()` which is why we extracted it from `update_transform`.

Also, the reason why I wrote access to `_base_transform` with `self` is to make sure it called the getter and setter.

There is just one more thing to do: make sure `_base_transform` gets persisted. We could do it by using `export`. However, to not have it appear in the inspector panel, we use `_get_property_list`, like this:

```
func _get_property_list() -> Array:
    var properties = []
    properties.append({
        name = "_base_transform",
        type = TYPE_TRANSFORM,
        usage = PROPERTY_USAGE_STORAGE
    })
    return properties

```

*I believe this approach would benefit from yet another spatial gizmo, one that eases setting the point around the camera orbits. And again, I don't know enough about gizmos to about implementing that. The approach I would follow to use this node without such gizmo is to set the orbit properties at zero, position the camera at the point it will orbit around, and then edit the orbit properties to what you want.*
> 4 votes

---
Tags: camera, rotation, godot
---


# Question
Title: Change color of point lights automatically over time
I'm using a gradient script to change the color of a sphere over time, but I want a point light associated to it to change too.

The script I'm using is this:

```
public class gradient : MonoBehaviour
{
    public Gradient myGradient;
    public float strobeDuration = 2f;

    public void Update()
    {
        float t = Mathf.PingPong(Time.time / strobeDuration, 1f);
        GetComponent<Renderer>().material.color= myGradient.Evaluate(t);
    }
}

```

The light object accepts the script but it doesn't affect the color.

I assume it's because this script is associated to materials and light has no material...

# Answer
Your light's color isn't changing because it uses the `Light` component, not `Renderer`. Simply add support for the `Light` component:

```
if (TryGetComponent(out Light light))
    light.color = myGradient.Evaluate(t);

```

With that said, I'd recommend that you use `TryGetComponent` for working with the `Renderer` component too:

```
if (TryGetComponent(out Renderer renderer))
    renderer.material.color = myGradient.Evaluate(t);

```

The use of `TryGetComponent` will help prevent potential `NullReferenceException`s from occurring.
> 3 votes

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


# Question
Title: How do I update this code to hit a moving target from a moving shooter?
I am working on a game where one spaceship("Origin") can shoot a dumb projectile("Projectile") at another spaceship("Target").

Since the target is moving we will have to lead the target. The projectile will move at a given speed (to be clear I differentiate between "velocity" which i use when talking about a vector and "speed" when i am talking about the length of said vector).

I am trying to calculate the point where I will have to aim in order to hit the target (assuming it does not change its velocity).

I tried this example.

UPDATED THE CODE

This is part of the "projectile" class that a wrote. self.targetVessel is the target self.originVessel is the shooter this function is called one in the constructor so that self.originVessel.velocity is the starting velocity self.totalSpeed is the "kick" that the projectile gets from the shooter

```
    def takeAim (self):
    t = 0

    #self.totalSpeed += math.sqrt(np.dot(self.originVessel.velocity, self.originVessel.velocity))

    posRel = self.pos - self.targetVessel.pos
    velRel = self.originVessel.velocity - self.targetVessel.velocity
    #velRel =  - self.targetVessel.velocity #this hits the target but the speeds don't add up

    a = (np.dot(velRel, velRel))-(self.totalSpeed**2)
    b = 2.0 * (np.dot(velRel,posRel))
    c = np.dot(posRel, posRel)

    disc = (b*b) - (4.0*a*c)

    print("Disc: ", disc)

    if disc < 0:
        print("Target is too fast - no point shooting!")
    else:
        t0 = (-b - math.sqrt(disc)) / (2.0*a)
        t1 = (-b + math.sqrt(disc)) / (2.0*a)

        print("t0: ", t0)
        print("t1: ", t1)

        if t0 < 0:
            t = t1
            print ("Choosing t1")
        elif t1 < 0:
            t = t0
            print ("Choosing t0")
        else:
            if t0 < t1:
                t = t0
                print("Choosing t0")
            else:
                t = t1
                print("Choosing t1")

    shoot = velRel + (posRel / t)
    self.velocity =  shoot + self.targetVessel.velocity
    self.aimPoint = self.targetVessel.pos + self.targetVessel.velocity*t
    targetDirection = self.aimPoint-self.pos
    targetDirection = targetDirection / math.sqrt(np.dot(targetDirection,targetDirection))
    self.velocity = (targetDirection * self.totalSpeed)

```

# Answer
> 0 votes
I toyed with that problem. My program had photon torpedoes that went a certain distance (game loops) and then exploded. And if the target (or any target) was within the blast radius, it took damage. I did this:

First, I calculated the distance (hypotenuse) from the shooter to the target.

Then I divided that by the velocity of the projectile. That gives an estimate of the games loops the target will travel while the projectile is in flight.

Then I multiplied the `deltax` and `deltay` of the target by this 'game loops' variable and added that to the location of the target to get an estimated location of where it might be when the projectile gets there.

Then I recalculate the range (hypotenuse) to the new location to get the actual number of game loops it will take for the projectile to travel from the shooter to the target and then use arctangent to get the angle and then sine and cosine to calculate the `deltax` and `deltay` for the projectile.

With that I have the info for the projectile to travel to where the target is likely to be (if it hasn't changed direction).

This is kind of what my code looks like to calculate angle and then `photonXch` and `photonYch` and loops to target once you have the predicted new location of the target. Opposite and adjacent are the two sides of a right triangle...you know...a^2+b^2=c^2

```
hyp=math.sqrt(opposite^2+adjacent^2)

ratio=abs(opposite/adjacent)

#comment...if either the opposite or the adjacent are 0, I make them equal to 1 to avoid dividing by zero or dividing into zero

angle=math.atan(ratio)

loops_to_target=int((hyp/photon_velocity))

photonYch=(abs(math.sin(angle)*photon_velocity))*ysign

photonXch=(abs(math.cos(angle)*photon_velocity))*xsign

```

`xsign` and `ysign` are based on whether the target location is left/right up/down from the shooter and my simple way of determining if the resulting `Xch` and `Yc` are negative or positive. In other words, if the `targetx>shooterx`, then the `Xch` will be positive, else negative and if the `targety>shootery`, then the `Ych` is positive else negative.

---
Tags: python, pygame
---


# Question
Title: Trying to update an item on the Steam Workshop, getting error: k_EResultInvalidParam (no workshop depot found)
I'm working on **Steam Workshop** integration for my Unity game's user created levels and I use **Steamworks.NET**.

**Uploading a level for the first time works just fine**, I use this snippet to upload my "XYZ.lvl" file:

```
SteamAPICall_t handle = SteamRemoteStorage.PublishWorkshopFile(filePath, null, SteamUtils.GetAppID(), workshopTitle, workshopDescription, ERemoteStoragePublishedFileVisibility.k_ERemoteStoragePublishedFileVisibilityPublic, tags, EWorkshopFileType.k_EWorkshopFileTypeCommunity);
RemoteStoragePublishFileResult.Set(handle);

```

But when I try to **update my own, just uploaded level**, I get an error: `k_EResultInvalidParam`

I use this to update it:

```
var m_UGCUpdateHandle = SteamUGC.StartItemUpdate(SteamUtils.GetAppID(), publishedFileID);
bool ret = SteamUGC.SetItemContent(m_UGCUpdateHandle, dirPath);
if (ret)
{
    SteamAPICall_t handle = SteamUGC.SubmitItemUpdate(m_UGCUpdateHandle, "Update Level");
    ItemUpdateResult.Set(handle);
}

```

If instead of `SetItemContent`, I want to just update the thumbnail with `SetItemPreview`, **everything works fine**.

So I guess **the problem is with my `SetItemContent` call.**

I tried passing these paths to it, but the same error still happens:

* A path to **just created directory** which contains the new "XYZ.lvl" file.
* A path to the **new "XYZ.lvl" file.**
* A path to an **empty directory**, hoping for a different error.

The Steamworks documentation says this about the error:

`k_EResultInvalidParam`

* Either the provided app ID is invalid or doesn't match the consumer app ID of the item or, you have not enabled `ISteamUGC` for the provided app ID on the Steam Workshop Configuration App Admin page.
* The preview file is smaller than 16 bytes.

Which is strange because as I said, if instead of `SetItemContent` I call `SetItemPreview`, the thumbnail is correctly uploaded, the API call ends successfully. **So the first case doesn't stand**: the app ID is good.

But if I add also a `SetItemContent` call to the process, the API call fails with `InvalidParam`. **So the second case doesn't stand as well**, because the thumbnail is correct due to the previous testing: it would be uploaded if I wouldn't call `SetItemContent`.

I think that's all I know. Feel free to ask for more info and thanks in advance for the help! :)

**UPDATE:**

The workshop log says that it fails because:

`Upload workshop item 2539371896 failed (no workshop depot found)`

# Answer
> 2 votes
The problem was due to not having the ISteamUGC enabled for file transfer.

Enable it at Steamworks \> Workshop \> General.

---
Tags: unity, steam, steamworks
---


# Question
Title: Unity baked light messes up a set of objects
On a few objects I use a technique where instead of using geometry, I place planes with a Cutout Material on top of each other, creating a 3D illusion with minimal cost. The thing is, it looks great with Unity's Realtime Lighting, but Baked Lighting darkens some of them.

The floor, walls and ceiling look close perfect, while the door's details are completely ruined. This was the reason I stopped baking light, but that is not a viable option as I am aiming to make it a Quest 2 Standalone project. Without baking, it just can't run it, with baking it is 100+ FPS on average.

I even turned off AO, just in case, but that didn't work either.

So my question is, that how can I fix this? Is there a stupidly simple solution, or is there a way to bake the "primitive" Realtime Lighting instead of the accurate Baked Lighting?

After countless hours of baking I'm out of ideas and started to lean towards making the problematic parts with actual geometry. That could be a bit heavy on the polygon side, but I could then include that too in the main 4K Texture Atlas. I'm quite unsure if that would be such a huge performance hit if any at all (since I could get rid of 3-4 Cutout Materials, making the SetPass calls even lower), but I'd like to keep the current approach if possible.

Realtime Lighting: Note how well the color of the door detail and the door itself match.

Baked Lighting: Now the door details are way too dark. Funnity enough the floor, walls and ceiling do actually look better baked.

PS: I know the baked image is a lot darker anyway, which is not intended and will be fixed if I find a solution to this issue first. I know how to add more strength to lights. :P

# Answer
I didn't generate Lightmap UVs. After I generated them and tweaked the settings, the overall lighting quality got a lot better.
> 0 votes

---
Tags: unity, lighting, materials, shadow-mapping, lightmap
---


title: Authoritative vs REST (server)

text:
# Question
Title: Authoritative vs REST (server)
I am filling out a Godot user survey, and I'm not sure how to answer this question:

> Do you use (or plan to use) networking in your games? *
>
> * Yes, for real-time peer-to-peer multiplayer
> * Yes, for authoritative server (cloud hosted) multiplayer.
> * Yes, for connecting with a server (REST-style)
> * No

I don't understand the difference between the middle two options, authoritative server (cloud hosted) multiplayer and connecting with a server (REST-style).

What are these options describing?

# Answer
Authorative and REST seem like orthogonal concepts from my understanding.

**Authoritative Server**

Clients become glorified controllers and rendering engines. They send inputs to the server, and ultimately the server sends back information which is correct (or authorative). Basically the server is always right, and is the baseline of truth. Unlike in P2P, where the peers themselves decide truth. You can imagine how this would be useful in multiplayer games to prevent hackers.

**REST**

REST refers to the API paradigm that is used to interface with the server. REST servers usually communicate via HTTP requests, unlike servers with realtime constraints which create socket connections or send packets directly via UDP. RESTful protocols are stateless, and therefore RESTful messages are often huge as they must include all their state every time they communicate.

**Edit**

Philipp added that:

> Another difference worth mentioning is that in the REST paradigm, all communication is initiated by the clients. The server cannot notify clients that something changed in the game states. The client must actively request that resource and see for itself if it changed. \[...\] An authoritative server, on the other hand, can message the clients immediately whenever there is a change in the game state they need to know about.

This means that REST could be employed in a turn-based dungeon crawler, as a player *initiates* the turn, and the server could send a *response*. While most real-time games could not adapt to the RESTful paradigm, because they rely on the server having being able to tick at set rates and message clients independently of their inputs.
> 1 votes

# Answer
I'd say this is a very poorly phrased survey question, so it's natural to find it confusing.

It looks like it means to ask:

* Do you have multiplayer features where a server (possibly but not necessarily cloud hosted) maintains the shared game state and sends updates to all players in that session?

or
* Do you communicate with a server for other features, like login authentication, downloading news/updates/special event content, logging to leaderboards, maintaining an online inventory / saved progress, etc?

But I'd argue it's using the wrong wording if that's what it wants to know.

**Authoritative** is a description of the server's responsibilities. An authoritative server does not just relay client actions to their peers. It takes a role in vetting the client's report and applying only valid changes to the game state/simulation, and communicating that authoritative account to the other clients.

**Cloud** is a description of where the server is hosted. In contrast to a dedicated server running on a specific machine, a cloud-hosted server is a program uploaded to a service that maintains a fleet of machines, and can spin up one or many instances of your server program across that network on demand.

**REST** is a description of how communication with the server is structured. I won't repeat the whole definition here since it's covered comprehensively elsewhere.

All 8 possible combinations of these keywords can exist. I've built a cloud-hosted authoritative server that communicates via a REST API, for example. (For an asynchronous game, so peers could pull down the latest authoritative state with a GET request) So I'd say they're not the right terms to use for this question about users' server needs.
> 2 votes

# Answer
I believe that what they mean with an "authoritative server (cloud hosted) multiplayer" is a server holding TCP connections or UDP pseudo-connections with the clients. All the game mechanics run on the server. The clients send messages to tell the server what they want to do. The gameserver calculates the results. Then it sends those results to any clients who need to know about them. Some examples of use-cases for such servers are:

* Position synchronization in fast-paced multiplayer games
* Informing the players about events ("push-messages" if you want to call them that)
* Relaying chat messages

REST stands for Representational State Transfer. It's a paradigm where clients make requests for specific resources to a server (usually via http/https) and the server responds. Clients are both able to transfer new data to the server (POST) or retrieve existing data from the server (GET).

But one central part of the REST paradigm is that all communication is initiated by the clients. Every client request gives the server exactly one opportunity to send them a response. That means the server can not actively inform the clients about something they didn't specifically ask for. This makes the REST paradigm infeasible for real-time games. But there are still a couple use-cases in game development where REST-style protocols can be useful. For example:

* Metrics
* Scoreboards
* Server-sided savegames (aka "cloud saves")
* Handling in-app purchases (both making them and allowing the client to check which IAPs were already made)
> 1 votes

---
Tags: networking, multiplayer, client-server
---


# Question
Title: How to determine if a 2D image represents what player sees in 3D game world?
I'm working on a game idea where the player is shown a 2D image (say, a "photo") and the player must find a spot in a 3D world where the view is about equivalent to that photo - not necessarily the exact same spot, but something that at least somewhat represents what is seen in the photo. How could that be approached?

To elaborate a bit, the player's objective is not to find the specific position and viewing direction in the game world. Rather, it is to find any spot in the world that matches the photo. For instance, if the photo is of a blue cube, then any view that represents a blue cube would be acceptable. Similarly, if the photo was of a triangle, any view that ends up representing a triangle (say, a pyramid viewed from a distance) would be OK.

As already discussed in the answers so far, a single correct point would be rather easy to do, or even if there were multiple possible solutions. However, if anything goes as long as it represents the photo, things seem to get a lot more difficult. I'd guess it boils down to processing the 3D view and the photo somehow and do a percentage matching between these two images to determine if they are alike..?

# Answer
To handle a symmetrical object like a cube that could be photographed from many different directions, you could try comparing silhouettes: Render the quest object's silhouette and match that against the current camera view.

## Create the quest

Use a render texture, set your camera to clear with transparent and to only renders that one object, render. Convert the render texture data to the quest silhouette by storing all transparent pixels as 0 and nontransparent as 1. (To ignore lighting and shading on the quest object.) Now set your camera to normal and render. Now you have the quest texture.

## Check if quest is satisfied

Query for the quest object in the camera frustum. If so, repeat the above steps to get the silhouette. Compare the resulting silhouette against the quest silhouette with some amount of tolerance (are 90% of pixels the same). You might need to tune a different tolerance per quest object.

If you're picking a random object in the scene, you could do both the create and check steps with rendering all quest objects. That would allow background duplicates of the quest object to be in the photo and you wouldn't have to query for the quest object. However, it might make the gameplay feel uneven -- background objects might make the positioning more finicky.
> 10 votes

# Answer
I would say it depends a lot if you have one spot for every "photo" or if there are several possible place where the photo could be used.

If you got one spot for every photo, you can simply check for the coordinates and the players viewing direction. Than you can add some tolerance to both and that should be enough.

But if you got several places where this photo could fit or the player has to place objects first (lamp on the table in the photo, but on the floor right now), so the photo does fit, then i would go another way. Similar to what TomTsagk said, create a scene from that with a camera perspectiv. You could render it now and use that as the photo or you could implement it like a frame to this scene. Basically you hold the window to the scene in your hand. As long as you keep the scene, its all good.

Now you can check, if the scene of the picture and the scene infront of the player match. Are the objects at the same position, are the angles the same?.

Another way would be to implement some sort of raytracing. Do the objects in the photo match the objects infront of the player.
> 5 votes

# Answer
This might look different depending on the tools you are using, but here is how I would approach this.

**Getting the Texture**

In the scene where the place of the photo exists, create a camera object, that is only available to you (and other developers), but not the end user. When needed, take a screenshot of what that camera sees, and use that as a 2D texture. Optionally you can edit this texture with an image manipulation tool, depending on the needs of your project.

During development, if the scene changes (things move around, lighting, etc), you can easily re-take a screenshot using the same camera, and simply replace the previous texture with the new one, without extra work. You can even re-position the camera if needed.

This can work with multiple such places that need to exist in photos. Its only drawback being that it doesn't really scale, unless you can develop a way to take screenshots of hundreds of such cameras with the press of a button, but that might be out of scope of this question.

**Finding out if the player is in the correct position**

Having the texture ready, you would then need to find out if a user is looking at the spot in the photo. The implementation will depend on the tools you are using (Game engine / Libraries).

The general idea is you would need to compare the player's camera transformation, to that of the set camera's transformation for each place that needs to be looked at.

The easiest way would be to compare the distance between the two cameras, and the difference in their rotation, and if they are small enough that means the player is (roughly) looking at the same spot as the photo.
> 3 votes

# Answer
## It depends on how much you want framing the shot to count

Basically, there are two ways you can look at this problem. You can either treat the player as someone trying to exactly recreate the scene from the photo, or you can treat it more like a scavenger hunt where the photo is just a "thing" you need to find. If you want the player to have to recreate the exact scene, then you want to use an Image Recognition API or SDK. However, if you just want to reward them based on how similar of a "thing" they can find, then you want to use meta-tag comparisons.

### Option A: Image recognition API or SDK

Other programmers have already done the hard part for you. Depending on what API/SDK you go with, it could be as simple as taking a screenshot of your viewport to create a 2-image of what you are looking at, and comparing it to the photo the player is supposed to be looking for, and the function/API call should either return a true/false based on what certainty threshold you defined, or it will return the certainty threshold (usually a percentage).

If you go with one that returns the actual certainty threshold, then you could actually use that as a basis for scoring; so, if you get a really close matchup, you might get a 95% certainty, but if you just find something that is roughly the same shape and color, you still get credit, but less points if it is only a 60% certainty.

*Personally I would recommend using some manner of exponential scoring if you do this to give more accurate shots significantly better scores... so a 60% certainty might yield 3600 points(60\*60) whereas a 95% certainty would yield 9025 points (95\*95)... just a suggestion*

### Option B: Meta-tag comparisons

If you don't care so much about matching the scenes as you do the properties of the object, a better approach would be to do meta-tag comparisons. Meta-tagging is any method of assigning hidden properties to an object that helps to define or label what it is. So if you have a photo of a teapot you could give it an associative array of properties that describe it, and a point value for each property that you match:

```
$metaTags = {'teapot' => '50', 'cookware' => '15', 'black' => '15', 'spherical' => '10',  'metal' => '10'};

```

Then when you point your camera at an object you wish to match, you just do a simple hit-test to see what object is in your crosshairs and you then compare its tags to those on the photo. So, if you find a black sports car, you might get 25 points for matching 'metal' and 'black' or if you find a red teapot, you might get 85 points for matching everything but the color.

The reason this works better for scavenger hunts is because you just need to find the object. If you have a photo of a brown teddy bear facing the camera for example, using Image Recognition will give a very low score if you take a photo from its backside, but using tag comparison, the teddy bear could be upside-down and backwards and still give full points as long as all of its tags match the photo's tags.

Meta-tag comparisons can also be cheaper since they don't require paying for any third-party licenses.
> 3 votes

---
Tags: 2d, 3d, game-mechanics, projection
---


# Question
Title: Why doesn't Unity use properties from C# scripts instead of fields?
There is plenty of popular opinion in the world surrounding the language and when developers should use a field or a property. The general consensus is that fields should remain private to a class, and, it's what I've been doing for more than a decade now.

With that, a lot of younger developers, with much less experience in the language, may not even know that fields and properties are related since modern really has no need for backing fields in 60% or more of use cases. Instead we have the auto-properties that juniors are used to seeing:

```
public int MyInteger { get; set; }

```

Most of them do not yet have the knowledge that this is actually syntactical sugar, and that the backing fields are automatically created at compile time, effectively reducing the amount of code you have to write (*cough cough, copy and paste*):

```
private int _myInteger;
public int MyInteger {
    get { return _myInteger; }
    set { _myInteger = value; }
}

```

Even seeing expression bodied methods in the getter and setter is an infrequent occurrence in modern code. With that, after the many, many years that Unity has been on the market, we still don't have natural support for using properties in the inspector for our scripts. Excluding the following work arounds, which both use field serialization:

```
// Pre C# 7.3 support:
[SerializeField] private int _myInteger;
public int MyInteger { get => _myInteger; set => _myInteger = value; }

// Post C# 7.3 support:
[field: SerializeField] public int MyInteger { get; set; }

```

Both work arounds utilize field serialization to get the exposure in the inspector for our scripts.

---

After all these years, what is the reason that Unity does not support using properties in the inspector instead of fields? I suspect it has something to do with one, if not more of the following:

* Existing asset support.
* Language support barriers (perhaps fields are easier to support?).
* Effort/Payoff (perhaps too much effort, for too little payoff?).

# Answer
> 7 votes
1. As LifGwaethrakindo noted, properties can have side effects. Imagine we had this property on a character:

```
[SerializeProperty]
public int HP {
    get => hp;
    set {
        hp = value;
        if (value == 0) GameObject.Destroy(this);
    }
}

```

The setter logic makes sense during gameplay, but not in the Editor. The default value for HP would be 0. If we forget to assign a new value in the inspector, the HP will stay at 0. The next time the scene/prefab is deserialized in the Editor, the character will be destroyed immediately (and we'll get a warning about how we should use `DestroyImmediate()` when destroying objects in the Editor from code while the game isn't running).

Such a problem could be avoided like this:

```
[SerializeProperty]
public int HP {
    get => hp;
    set {
        hp = value;
        if (Application.isPlaying && value == 0) GameObject.Destroy(this);
    }
}

```

but it would be very easy to forget the `Application.isPlaying` condition and encounter totally bizarre behavior. Such issues would look like Editor bugs and would cause the Unity QA team to be inundated with bug reports.

The engine could theoretically bypass the setter logic and only set the value of the underlying variable, but then what would happen in a case like this?

```
private int hp;
private int maxHP;

[SerializeProperty]
public int MaxHP {
    get => maxHP;
    set {
        maxHP = value;
        hp = value;
    }
}

```

When we deserialized, `hp` would not get set and would remain at 0.

2. If we could serialize both fields and properties, there would be the potential for situations like this:

```
[SerializeField] private int someValue = 50;

[SerializeProperty]
public int SomeValue {
    get => someValue;
    set => someValue = value * 2;
}

```

What happens when we deserialize this? If the property is deserialized first, the value won't change, but if the field is deserialized first, the value will double each time.

This can be resolved by *only* allowing serialization of properties, and *not* of fields, but that would be ***a massive breaking change that would destroy compatibility with every game made with any prior version of Unity.*** Imagine upgrading a large game to the newest version of Unity and then having to go through every single serialized field in every component script and replace them with serialized properties that don't have unexpected side effects.

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


# Question
Title: How to create closed source Unity bundle
I want to create an asset/bundle that I can drop into projects to get up and running easily. Ideally this bundle would be closed-source so that the code is not accessible, but yet still usable. Is there a way to do this with Unity, or does the way packages work simply mean bundles will always be accessible/browsable for the source code?

I am planning on doing this for a simple 1st person controller, so that I can easily drop it into demo scenes of assets I purchase, to get a quick feel for using them. If possible, I would also distribute this as an asset (likely free, maybe minimal cost). Is there anyway to keep it closed-source, or is this simply not possible?

# Answer
> 1 votes
You can compile your code into a managed plugin (DLL). However, be aware that DLLs can be decompiled by third-party tools back into source code. It's not something I've tried myself, but IIRC I've heard that the decompiled code is very similar to the original source and thus very easy to read, unless you obfuscate it.

---
Tags: unity, assetbundle
---


# Question
Title: check if joystick magnitude is increasing
I use joystick mechanic. What I want to do is:

* Translating my object forward when my `joystickInput.magnitude` is increasing.
* Translating backward when my `joystickInput.magnitude` is decreasing.

I need to know if my `joystickInput.magnitude` is increasing or decreasing, but I couldn't find any idea for how to do it.

I tried to keep previous magnitude for comparing them, but since there is an equality condition in the *2nd if statement*, after `magnitude = joystickInput.magnitude` it goes into this *if statement* again and again, so in every frame it just goes into *else statement* for **once** and almost never goes to the **(-)direction**.

If I don't add the equality sign, then it goes into else statement again and again as the same as previous above version.

So, what I have is this (not working as expected) ;

```
private void Update()
{
    joystickInput = new Vector2(joystick.Horizontal, joystick.Vertical);

    if(joystickInput.magnitude > 0.1f && joystickInput.magnitude < 0.9f)
    {
        Debug.Log("joystickInput.magnitude " + joystickInput.magnitude);
        Debug.Log("magnitude " + magnitude);
        if (joystickInput.magnitude >= magnitude)
        {
            Debug.Log("increasing");
            magnitude = joystickInput.magnitude;
            foreach (GameObject obj in spheres)
            {
                Vector3 direction = (obj.transform.position - centerPoint.position);
                obj.transform.position += direction * (joystickInput.magnitude + 2) * Time.deltaTime;
            }
        }

        else
        {
            Debug.Log("decreasing");
            magnitude = joystickInput.magnitude;
            foreach (GameObject obj in spheres)
            {
                Vector3 direction = (obj.transform.position - centerPoint.position);
                obj.transform.position += -direction * (joystickInput.magnitude + 2) * Time.deltaTime;
            }
        }
    }
}

```

# Answer
> 0 votes
I don't have unity on my current machine, so I can't test this, but I would try this.

```
float previousMagnitude = 0.0f;
private void Update()
{
    var joystickInput = new Vector2(joystick.Horizontal, joystick.Vertical);
    float currentMagnitude = joystickInput.magnitude;
    if(0.1f < currentMagnitude && currentMagnitude < 0.9f)
    {
        if(currentMagnitude > previousMagnitude)
        {
            Debug.Log("increasing");

        }
        else if(currentMagnitude < previousMagnitude)
        {
            Debug.Log("decreasing");

        }
        previousMagnitude = currentMagnitude;
    }
}

```

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


# Question
Title: _input not called for a node inside a Viewport
I have a scene with two viewports, the "root" viewport and another inside it, like this:

```
Root
- SomeNode1
- SomeNode2
- RootCamera
- Viewport
  - SomeDeeperNode1
  - ViewportCamera

```

Now, I have a script attached to a node that belongs to the `Viewport` node, and it works otherwise, but its `_input()` method is not called. The script itself works because if I move it out of `Viewport` (so that it's under `Root` node) it works fine. Is there something that should be taken into consideration for the `_input()` method to be invoked when it's located inside another viewport?

# Answer
> 2 votes
For your `Viewport` to get input, it must be inside a `ViewportContainer`. Thus, if you want the inner `Viewport` to receive input, you must put it inside a new `ViewportContainer` (it can have no size, or be invisible, input should still work).

The alternative is, of course, to manipulate the `Viewport` from an script located elsewhere where it can get input.

By the way, if you enable `gui_disable_input` your `Viewport` will not get input, nor anything inside of it.

---
Tags: godot, gdscript
---


# Question
Title: Fill Animation component during OnValidate()
I'm trying to fill my animation component automatically with clips which are dropped into a sister component. For nice UX I want the animation component just to sit there - artists shouldn't mess with it (`HideFlags.NotEditable`).

But I also don't want to fill the animation component during runtime if I can avoid it.

But there I run into a problem. Here's a little test code. Checking the toggle will add a test clip to the animation component's clip list, unchecking the toggle will remove it again:

```
[RequireComponent(typeof(Animation))]
public class OnValidateTest : MonoBehaviour
{
    public AnimationClip TestClip;

    public bool Toggle;

    private void OnValidate()
    {
        Debug.Log("OnValidate");

        Animation animationComponent = GetComponent<Animation>();
        // Reset clip list in Animation component, also eliminating empty clips (only clean way I found)
        UnityEditor.AnimationUtility.SetAnimationClips(animationComponent, new AnimationClip[0]);

        if (Toggle)
        {
            animationComponent.AddClip(TestClip, "test");
        }
    }
}

```

The problem now:

* It works in the scene view
* It works in prefab mode
* But when trying to edit the asset by clicking on the prefab asset in the project tab I'll run into trouble

Problem 1: `OnValidate` will be called infinitely. (constant asset updating)
Problem 2: Clip assignment will fail and the inspector will display "type mismatch" in the array - (like I tried to assign an instance instead of an asset??)

Here's also a video showing the behavior.

Is what I want achievable ?

# Answer
I wouldn't recommend OnValidate for adding editor controls. Instead, you can use a CustomEditor to add a button to your component's Inspector display (I think you could even make one for the Animation component!) or make an EditorWindow with buttons for manipulating objects.

Or, even simpler, use Button from NaughtyAttributes:

```
using NaughtyAttributes;
using UnityEngine;

public class AnimTest : MonoBehaviour
{
#if UNITY_EDITOR
    public AnimationClip TestClip;

    [Button]
    void ClearClips()
    {
        Animation animationComponent = GetComponent<Animation>();
        // We need to call Undo to ensure our changes are saved.
        UnityEditor.Undo.RecordObject(animationComponent, "ClearClips");
        // Reset clip list in Animation component, also eliminating empty clips (only clean way I found)
        UnityEditor.AnimationUtility.SetAnimationClips(animationComponent, new AnimationClip[0]);
    }
    [Button]
    void AddClip()
    {
        ClearClips();
        Animation animationComponent = GetComponent<Animation>();
        // Since we're using Animation to play instead of Animator, we must
        // mark as legacy. Otherwise we get a warning like: "The AnimationClip
        // 'animation' used by the Animation component 'GameObject' must be
        // marked as Legacy."
        UnityEditor.Undo.RecordObject(TestClip, "mark as legacy");
        TestClip.legacy = true;
        UnityEditor.EditorUtility.SetDirty(TestClip); // for some reason RecordObject isn't always enough.
        animationComponent.AddClip(TestClip, "test");
    }

#endif // UNITY_EDITOR
}

```

> Problem 2: Clip assignment will fail and the inspector will display "type mismatch" in the array - (like I tried to assign an instance instead of an asset??)

You're probably getting a warning like: "The AnimationClip 'animation' used by the Animation component 'GameObject' must be marked as Legacy."

You need to set the legacy flag to use AnimClips with Animation. (But maybe you should look into using Animator.)
> 1 votes

# Answer
Alright. This works.

```
[RequireComponent(typeof(Animation))]
public class OnValidateTest : MonoBehaviour
{
    public AnimationClip TestClip;

    public bool Toggle;

    private void OnValidate()
    {
        Debug.Log("OnValidate");

        Animation animationComponent = GetComponent<Animation>();

        if (Toggle)
        {
            //animationComponent.AddClip(TestClip, "test");
            if (!animationComponent[TestClip.name])
            {
                UnityEditor.AnimationUtility.SetAnimationClips(animationComponent, new AnimationClip[1]{TestClip});
            }
        }
        else
        {
            if (animationComponent.GetClipCount() != 0)
            {
                // Reset clip list in Animation component, also eliminating empty clips (only clean way I found)
                UnityEditor.AnimationUtility.SetAnimationClips(animationComponent, new AnimationClip[0]);
            }
        }
    }
}

```
1. Checks if a change is actually required will avoid the infinite asset update loop.
2. Using UnityEditor.AnimationUtility.SetAnimationClips() instead of animation.AddClip() will make the "type mismatch" problem go away, when trying to directly edit the asset from the project view.
> 1 votes

---
Tags: unity
---


# Question
Title: Rendering to BufferStrategy gives absolutely no output despite following instructions
I am following this YouTube tutorial by TheCherno to make 3D graphics using Java Standard Library.

Display.java

```
package aritro;

import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;

import javax.swing.JFrame;

public class Display extends Canvas implements Runnable {

    private static final long serialVersionUID = -1545751462933395031L;
    static int HEIGHT = 500, WIDTH = 800;
    static String title = "Minefront Pre-Alpha 0.0.1";
    private Thread thread;
    private boolean running = false;
    //private Render render;
    private Screen screen;
    private BufferedImage img;
    private int pixels[];

    public Display() {
        screen = new Screen(WIDTH, HEIGHT);
        img = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        pixels = ((DataBufferInt) img.getRaster().getDataBuffer()).getData();
    }

    private void start() {
        if (running)
            return;
        running = true;
        this.thread = new Thread(this);
        System.out.println("Working...");
    }

    @Override
    public void run() {
        while (running) {
            tick();
            render();
        }
    }

    private void render() {
        BufferStrategy bs = getBufferStrategy();
        if (bs == null) {
            createBufferStrategy(3);
            return;
        }

        screen.render();

        for (int i = 0; i < WIDTH * HEIGHT; i++) {
            pixels[i] = screen.pixels[i];
        }
        Graphics g = bs.getDrawGraphics();
        g.drawImage(img, 0, 0, WIDTH, HEIGHT, null);
        g.dispose();
        bs.show();
    }

    private void tick() {

    }

    public void stop() {
        if (!running)
            return;
        running = false;
        try {
            thread.join();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(0);
        }
    }

    public static void main(String[] args) {
        Display game = new Display();
        JFrame frame = new JFrame(title);
        frame.add(game);
        frame.setResizable(false);
        frame.pack();
        frame.setSize(WIDTH, HEIGHT);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        game.start();
    }

}

```

This class is the main class which renders to the JFrame. The two helper classes `Render.java` and `Screen.java`.

Render.java

```
package aritro.graphics;

public class Render {
    public int height, width;
    public int pixels[];

    public Render(int _width, int _height) {
        width = _width;
        height = _height;
        pixels = new int[width * height];
    }

    public void draw(Render render, int xOffset, int yOffset) {
        for (int y = 0; y < render.height; y++) {
            int yPix = y + yOffset;
            for (int x = 0; x < render.width; x++) {
                int xPix = x + xOffset;
                pixels[xPix + yPix * width] = render.pixels[x + y * width];
            }
        }
    }
}

```

Screen.java

```
package aritro.graphics;

import java.util.Random;

public class Screen extends Render {
    private Render test;

    public Screen(int _width, int _height) {
        super(_width, _height);
        Random random = new Random();
        test = new Render(256, 256);
        for (int i = 0; i < 256 * 256; i++) {
            test.pixels[i] = random.nextInt();
        }
    }

    public void render() {
        draw(test, 0, 0);
    }
}

```

But unlike the the end of the video, I just get the blank grey screen instead of a black one with a pitch of randomly colored pixels.

Can someone point the mistake in the code which is causing the problems?

EDIT : Someone pointed out that I had initialized running to false in void start which did not initiate the game loop. but even after setting it to true, it doesn't work.

this is the blank screen. Java version used - Java14.0.0.1

# Answer
Add the line thread.start() to void start() else the thread doesn't start
> 0 votes

# Answer
In `start` you do `running = false;` which means that when `run` gets called, the gameloop will never activate and hence your actual rendering code will never run. In the linked video the code in `start` sets `running` to `true`.
> 2 votes

---
Tags: java, 3d, software-rendering
---


title: Implementing wet and dirty materials

text:
# Question
Title: Implementing wet and dirty materials
How you would implement wet and dirty materials or material overlays that you can clean like in PowerWash Simulator.

# Answer
I've never implemented any of this stuff before. But from my understanding there's two basic ways you could solve this problem.

## Decals

The simplest solution would be to just to just put simple billboards with "wet" or "clean" materials on top of the surfaces. This has the real world equivalent of placing an animatable sticker on top of surfaces. This works great for when the effects your placing are small, and self contained (they don't need to interact with other entities of the same type to achieve their desired effect). Bullet holes, in FPSs, are ideal candidates for decals. As soon the effect needs to know where it is on a surface, or know about other nearby decals, or must curve around complicated meshes, you're out of luck unless you make your decal system much more complicated and likely much less performant.

## Textures and an alpha mask

What's probably happening in *PowerWash*, is that there are two sets of textures for every cleanable object, and then a texture mask which determines which set are visible and where. When you power wash something, you're simply coloring the alpha mask from white to black (or vice versa) which changes which set of textures (dirty or clean) are visible. From a technical POV, the hardest part of this technique would be the projection from 3D world space to 2D texture space when you have to find out where on the object's *texture* you're spraying.

**extras**

There seems to be more complicated effects happening in *PowerWash* which adds to the main effect. When you spray objects, they seem to briefly become wet, drip, and then dry. There's probably another texture which represents the wetness of every object, which gets set by the powerwash but then fades back to its original dry state (texture value) overtime.

**pros/cons**

This method is much more powerful because you have access to all the mesh and textures of whatever object you're on (unlike with decals). But it means you have to have duplicate sets of textures for *every* object which could get very expensive.

**edit**

DMGregory mentions that there's ways to reduce the memory cost of this approach by tiling and re-using materials
> 0 votes

---
Tags: 3d, textures, materials
---


# Question
Title: How do I adjust speed of an object in gamemaker studio 2
Currently, I have this in my step event.

y += sign(mouse\_y - y);

I am trying to adjust how fast it goes towards the mouse so I can have it scrolling up and down the screen. sorry if this has been asked before I need an updated answer.

# Answer
> 1 votes
If your goal is to change the movement rate by a fixed amount you could use something like:

```
y += sign(mouse_y - y)*scale;

```

Setting the variable `scale` to 3 would triple the movement rate whereas setting it to 0.5 would halve it.

For more sophisticated changes you could modify the `scale` in your game loop or update function to gradually speed up or slow down over time.

---
Tags: game-maker, game-maker-studio-2
---


# Question
Title: How to calculate the force for the fragments correctly?
I have a wall on which you can shoot cannonballs from a cannon, after hitting, I replace the wall with fragments of it.

How to correctly apply force to the fragments of the wall after being hit?

```
private void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.CompareTag("CannonBall")) {
        var fragments = Instantiate(_fragmentsPrefab);
        fragments.transform.position = transform.position;
        gameObject.setActive(false);
        Physics.SyncTransforms();
        var rigidbodies = fragments.GetComponentsInChildren<Rigidbody>();
        foreach (var rigidbody in rigidbodies) {
            rigidbody.AddForce(collision.relativeForce, ForceMode.Impulse);
        }
    }
}

```

I wrote this code but it doesn't work as realistically as I wanted.

# Answer
> 0 votes
Based on Charly's solution

```
private void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.CompareTag("CannonBall")) {
        var fragments = Instantiate(_fragmentsPrefab);
        fragments.transform.position = transform.position;
        gameObject.setActive(false);
        Physics.SyncTransforms();
        var rigidbodies = fragments.GetComponentsInChildren<Rigidbody>();
        foreach (var rigidbody in rigidbodies) {
            var distance = Vector3.Distance(rigidbody, collision.rigidbody);
            var t = Mathf.InverseLerp(_radius, 0f);
            var force = Vector3.Lerp(Vector3.zero, collision.relativeForce, t);
            rigidbody.AddForce(force, ForceMode.Impulse);
        }
    }
}

```

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


# Question
Title: How do I create a powerup that affects speed for a limited amount of time?
I am looking to create a powerup such that when the "playership" object collides with it will affect the playership's speed for a few seconds, let's say 30-60 seconds. I cannot seem to figure this out on my own nor do I know what to look up, so I am asking on here for some help.

I have this for my playership:

```
y += sign(mouse_y - y) * global.Speedy;

```

# Answer
> 2 votes
A simple implementation can be done on the `playership` object. You need to track the power-up additional speed (let's call it `powerup_speed`) and the overall bonus duration time (`powerup_countdown`). On `playership`:

*Create Event:*

```
powerup_speed = 0;
powerup_countdown = 0;

```

The power-up effects occur only when the timer is a positive value. This is a countdown timer: As long as it is greater than `0`, we set the bonus speed to an arbitrary value and reduce the timer by `1`. Otherwise, the bonus is inactive and we reset the bonus speed:

*Step Event:*

```
if (powerup_countdown > 0)
{
    powerup_speed = 10;  // Change as needed
    powerup_countdown = powerup_countdown - 1;
}
else
{
    powerup_speed = 0;  // Reset bonus speed
}

```

Please note, the timer is defined as game steps, not seconds: *n* seconds = *n* * `room_speed` steps.

Then, you change the code snippet controlling the `y` position as follows:

```
y += sign(mouse_y - y) * (global.Speedy + powerup_speed);

```

This way, your power-up logic should be up and working. Applying the power-up to the `playership` object is just a value assignment when the collision occurs:

*Collision Event:*

```
playership.powerup_countdown = 30 * room_speed;  // Power-up lasts for 30 secs

```

---
Tags: game-maker, game-maker-studio-2, effect-modifier
---


# Question
Title: How to access a ViewportTexture's depth data as an image?
I make use of ViewportTextures, kind of like rendering security cameras on screens. Now, I'd need to access the depth textures to do some comparison of images / pixels. How do I access the depth data as an image?

# Answer
Sadly, there is no built in to do this at the time of writing. Instead this is what exists:

Today, the workaround is to use yet another `Viewport`, that would output the depth information (which requires a shader that reads the depth and outputs it as color), so that you get it as a regular `ViewportTexture`. See Advanced post-processing. *And yes, that means overhead.*
> 3 votes

---
Tags: godot, image, viewport, depth
---


# Question
Title: What is surface locking and unlocking in Pygame?
I've read a little about surface locking and unlocking in pygame in Beginning Game Development with Python and Pygame. However, I still don't understand it.

I've read that it can improve the game performance, so I'm wondering about its other advantages.

So overall, what are the main uses of surface locking and unlocking ?

How does it improve performance ?

Is it necessary to lock and unlock the screen everytime I blit an image into it ?

## UPDATE :

Here is a part of the passage that I read in that book :

> Whenever Pygame draws onto a surface, it first has to be locked. When a surface is locked, Pygame has full control over the surface and no other process on the computer can use it until it is unlocked. Locking and unlocking happens automatically whenever you draw onto a surface, but it can become inefficient if Pygame has too many locks and unlocks.

## NOTE :

I'm mostly wondering about manual locks and unlocks and not just about automatic ones and btw to lock and unlock a surface manually, all is needed is :

```
surface.lock()
# applying some changes to that surface
surface.unlock()

```

# Answer
> 2 votes
Surface locking allows you to directly access the pixel data of accelerated surfaces. It's not so much about improving performance. Rather, an accelerated surface *already* has performance improvements, *but* it comes with a trade off of requiring locking & unlocking if you're going to directly change its data.

All of the built in Pygame functions will automatically lock and unlock the Surface data as needed. So for basic blitting, you don't need to worry about it.

When might you need it? Let's say you had some code that required multiple `get_at()` &/or `set_at()` calls. Each such call requires locking & unlocking the surface & according to the docs:

> Getting and setting pixels one at a time is generally too slow to be used in a game or realtime situation.

In that situation, it would likely be more performant to lock the surface once, perform any required reads & writes to the pixel data and then unlock it.

Here's what the the docs say about locking:

> On accelerated Surfaces, the pixel data may be stored in volatile video memory or nonlinear compressed forms. When a Surface is locked the pixel memory becomes available to access by regular software. Code that reads or writes pixel values will need the Surface to be locked.
>
> Surfaces should not remain locked for more than necessary. A locked Surface can often not be displayed or managed by pygame.
>
> Not all Surfaces require locking. The `mustlock()` method can determine if it is actually required. There is no performance penalty for locking and unlocking a Surface that does not need it.
>
> All pygame functions will automatically lock and unlock the Surface data as needed. If a section of code is going to make calls that will repeatedly lock and unlock the Surface many times, it can be helpful to wrap the block inside a lock and unlock pair.
>
> It is safe to nest locking and unlocking calls. The surface will only be unlocked after the final lock is released.

---
Tags: pygame, screen
---


# Question
Title: OpenGL 2D texture lookup returns zero (black)
I am trying to use a 2D texture as a lookup table for pre-computed values. In each case I set all values of the texture to 0.5 for testing.

When I use a 1D texture, it works and I get 0.5:

```
uniform sampler1D dens;
...
  return texture(dens, height01).r;
...

```

When I use a 2D texture however, I get 0.0:

```
uniform sampler2D dep;
...
  return texture(dep, vec2(height01, cos_angle01)).r;
...

```

I have tried setting cos\_angle01 to 0.5. I also tried visualising height01.

Here are the initialisations of the textures (implemented in Clojure):

<pre><code>(def size 8)
(def dens (float-array (repeat size 0.5)))
(def dep (float-array (repeat (* size size) 0.5)) )

(def dens-texture (GL11/glGenTextures))
(GL13/glActiveTexture GL13/GL_TEXTURE0)
(GL11/glBindTexture GL11/GL_TEXTURE_1D dens-texture)
(GL20/glUniform1i (GL20/glGetUniformLocation program "dens") 0)
(GL11/glTexImage1D GL11/GL_TEXTURE_1D 0 GL30/GL_R32F size 0 GL11/GL_RED GL11/GL_FLOAT (make-float-buffer dens))
(GL11/glTexParameteri GL11/GL_TEXTURE_1D GL11/GL_TEXTURE_WRAP_S GL12/GL_CLAMP_TO_EDGE)
(GL11/glTexParameteri GL11/GL_TEXTURE_1D GL11/GL_TEXTURE_MIN_FILTER GL11/GL_NEAREST)
(GL11/glTexParameteri GL11/GL_TEXTURE_1D GL11/GL_TEXTURE_MAG_FILTER GL11/GL_NEAREST)

(def dep-texture (GL11/glGenTextures))
(GL13/glActiveTexture GL13/GL_TEXTURE1)
(GL11/glBindTexture GL11/GL_TEXTURE_2D dep-texture)
(GL20/glUniform1i (GL20/glGetUniformLocation program "dep") 1)
(GL11/glTexImage2D GL11/GL_TEXTURE_2D 0 GL30/GL_R32F size size 0 GL11/GL_RED GL11/GL_FLOAT (make-float-buffer dep))
(GL11/glTexParameteri GL11/GL_TEXTURE_1D GL11/GL_TEXTURE_WRAP_S GL12/GL_CLAMP_TO_EDGE)
(GL11/glTexParameteri GL11/GL_TEXTURE_1D GL11/GL_TEXTURE_WRAP_T GL12/GL_CLAMP_TO_EDGE)
(GL11/glTexParameteri GL11/GL_TEXTURE_1D GL11/GL_TEXTURE_MIN_FILTER GL11/GL_NEAREST)
(GL11/glTexParameteri GL11/GL_TEXTURE_1D GL11/GL_TEXTURE_MAG_FILTER GL11/GL_NEAREST)
```
</code></pre>

# Answer
Now that I read my question I noticed the bug. I used GL11/GL\_TEXTURE\_1D instead of GL11/GL\_TEXTURE\_2D for the second texture, sorry:

```
(def dep-texture (GL11/glGenTextures))
(GL13/glActiveTexture GL13/GL_TEXTURE1)
(GL11/glBindTexture GL11/GL_TEXTURE_2D dep-texture)
(GL20/glUniform1i (GL20/glGetUniformLocation program "dep") 1)
(GL11/glTexImage2D GL11/GL_TEXTURE_2D 0 GL30/GL_R32F size size 0 GL11/GL_RED GL11/GL_FLOAT (make-float-buffer dep))
(GL11/glTexParameteri GL11/GL_TEXTURE_2D GL11/GL_TEXTURE_WRAP_S GL12/GL_CLAMP_TO_EDGE)
(GL11/glTexParameteri GL11/GL_TEXTURE_2D GL11/GL_TEXTURE_WRAP_T GL12/GL_CLAMP_TO_EDGE)
(GL11/glTexParameteri GL11/GL_TEXTURE_2D GL11/GL_TEXTURE_MIN_FILTER GL11/GL_NEAREST)
(GL11/glTexParameteri GL11/GL_TEXTURE_2D GL11/GL_TEXTURE_MAG_FILTER GL11/GL_NEAREST)

```
> 1 votes

---
Tags: opengl, textures, glsl
---


# Question
Title: What are the pros and cons to using Transform{position, scale, rotation} over Matrix (3x4)?
I'm using Transform in a certain case where I want extracting/changing/preserving the components {position, scale, rotation} to be straightforward - I guess that is a benefit. But when it comes to multiplication, it looks like 3x4 Matrix will be more efficient (it appears to require fewer floating-point operations) and doesn't have lots of bizarre cases to worry about (see the following code from UE's `FTransform::Multiply`):

```
A->DiagnosticCheckNaN_All();
B->DiagnosticCheckNaN_All();

checkSlow(A->IsRotationNormalized());
checkSlow(B->IsRotationNormalized());

...
if (AnyHasNegativeScale(A->Scale3D, B->Scale3D))
{
    // @note, if you have 0 scale with negative, you're going to lose rotation as it can't convert back to quat
    MultiplyUsingMatrixWithScale(OutTransform, A, B);
}
else
{
    OutTransform->Rotation = B->Rotation*A->Rotation;
    OutTransform->Scale3D = A->Scale3D*B->Scale3D;
    OutTransform->Translation = B->Rotation*(B->Scale3D*A->Translation) + B->Translation;
}

```

Am I right about the efficiency of multiplication between the two? What are other PROs and CONs I'm missing?

I'm guessing there must be full articles on this topic already, but I failed to find any.

# Answer
I'm not sure I understand your question, but I would say that they are both the same thing.

We use 4x4 matrices to represent transformations, and due to the associative property of matrix multiplication, you can represent multiple affine transformations in a single matrix, and then apply that transformation to as many points as you want.

3x4 matrices are a special case of matrices that only allow you to represent rotations, scaling, and one translation at the end. Whether using 4x4 matrices or 3x4 matrices gives you a performance advantage is disputed, and can only be confirmed by thoroughly benchmarking your specific use case.

I'm not sure exactly which functionality this `Transform` you're using offers you, but in many cases it's just a class that decomposes a 4x4 (or 3x4) matrix, allows you to modify its components (translation, rotation, scaling) separately, before converting it back to a matrix. Decomposing and re-composing a matrix requires some computations, so it could be a good idea to try not to overuse it, but sometimes the benefits of added readability can be greater than the disadvantages of a small performance penalty, so I would suggest you use whatever makes the most sense to you, especially if this is a prototype, a learning project, or a personal project.

If you want to modify one of the components of the transformation, decomposing it might be the easiest way to do so. Multiplying by another matrix on the left or the right can also be used in some cases, but it may have a different meaning from what you're expecting. I would say that multiplying by a different matrix is a slightly faster operation, compared to decomposing, modifying and re-composing, especially when the different matrix is the same for many different operations.

Keep in mind that not all matrices can be decomposed into translation, rotation and scaling. There are many more types of affine transforms, and in particular, projection matrices, that are not made out of translations, rotations and scaling, so they obviously can't be decomposed into these components.
> 1 votes

---
Tags: matrix, transformation, optimization
---