# Question
Title: Centralized Event System with arbitrary number of parameters of arbitrary types
I've coded an event queue system that supports subscribing/firing events with an arbitrary number of parameters of arbitrary types. So I basically declared a delegate that accepts arbitrary parameters using the `params` keyword. Then I declared a bunch of delegates that take up to 5 generic parameters to wrap up the actual delegate. So the subscriber can pass in functions of up to 5 parameters of any type.

Are there any significant performance concerns especially in a game since I wrapped the callback delegates 2 times? Memory usage might also be a problem (GC)?

```
public delegate void EventWrapper();
        public delegate void EventWrapper<T>(T arg);
        public delegate void EventWrapper<T1,T2>(T1 arg1, T2 arg2);
        public delegate void EventWrapper<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3);
        public delegate void EventWrapper<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
        public delegate void EventWrapper<T1, T2, T3, T4, T5>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);

        private static Dictionary<MethodInfo, EventQueue.EventHandler> listenerMapping;
        private static EventQueue eventQueue;

        public EventManager()
        {
            listenerMapping = new Dictionary<MethodInfo, EventQueue.EventHandler>();
            eventQueue = new EventQueue();
        }

        public void Update()
        {
            eventQueue.Update();
        }

        #region System Events Subscribing
        /// <summary>
        /// Fire a System Event with any number of parameters in ragnge 1~5. Make sure to match the number of parameters between firers and subscribers
        /// </summary>
        public static void FireSystemEvent(SystemEvents e, params object[] param)
        {
            PrintError(eventQueue.FireSystemEvent(e,param));
        }

        /// <summary>
        /// 0 Parameter event register. Make sure to match the number of parameters between firers and subscribers
        /// </summary>
        public static void SubscribeSysEvent(SystemEvents e, EventWrapper callback)
        {
            EventQueue.EventHandler wrapper = (object[] param) =>
            {
                if (!ValidateEventParams(param, 0, 0, e, GameEvents.None)) return;
                callback?.Invoke();
            };
            PrintError(SubscribeSys(e, wrapper, callback.Method));
        }
        public static void UnsubscribeSysEvent(SystemEvents e, EventWrapper callback) { UnsubscribeSys(e, callback.Method); }

        /// <summary>
        /// 1 Parameter event subscribing. Make sure to match the number of parameters between firers and subscribers
        /// </summary>
        public static void SubscribeSysEvent<T>(SystemEvents e, EventWrapper<T> callback)
        {
            EventQueue.EventHandler wrapper = (object[] param) =>
            {
                if (!ValidateEventParams(param, 1, 1, e, GameEvents.None, typeof(T))) return;
                callback?.Invoke((T)param[0]);
            };
            PrintError(SubscribeSys(e, wrapper, callback.Method));
        }
        public static void UnsubscribeSysEvent<T>(SystemEvents e, EventWrapper<T> callback) { UnsubscribeSys(e,callback.Method); }

```

# Answer
I'd say you're correct to have concerns about the code you've shown. Passing arguments through an `params object[]` will cause a memory allocation for the array, as well as for boxing any structs (including primitive types like numbers) and enums among the arguments. You'll then pay extra overhead to unbox them. Further, capturing these arguments in a lambda function and storing it as a delegate will allocate heap memory for that delegate.

All these allocations add execution time, and put pressure on the garbage collector. Not a lot for each call, but for a central messaging system like this, you'll likely be enqueuing and handling hundreds or thousands of events per frame, so all those little costs add up.

You'll also be paying some extra lookup costs for the dictionary - hashing the method info each time. We can skip that overhead too.

Fortunately, for something like an event system, its clients at either end pretty much always know the concrete types they want to work with:

* The code that fires an event knows what kind of event it's firing.
* The code that listens for an event knows what kind of event it's listening for.

So we can use strict typing at both ends. Then we just need a strategy to package up the data in between, so our central queue middle-man doesn't need to care about the details of the conversations it's facilitating. The curiously recurring template pattern can help us with this.

First, we can define a central queue that will hold all our events - of any type - in the order that they were issued, so we can handle them in the correct interleaved order, in case that matters for your use case.

Since the this part of the system isn't adding any information of its own, for its purposes it's just saying "Execute now" - no arguments. So a `System.Action` delegate suffices.

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

public static class EventQueue {
    static readonly Queue<Action> _queue;

    public static int Count { get => _queue.Count; }

    public static bool TryFireNextEvent() {
        if (_queue.Count == 0) return false;
        _queue.Dequeue().Invoke();
        return true;
    }

    public static void Enqueue(Action eventCall) { _queue.Enqueue(eventCall);  }
}

```

Then we'll define a template for events that need only a single argument.

Each one will maintain its own collection of listeners subscribed to that specific event type, and will stuff its arguments into a strictly typed queue, telling the central queue to let it know when to dump the next item from the queue to the listeners.

```
public abstract class Event<T> {
    static readonly Queue<T> _queue = new Queue<T>();

    static event Action<T> _listeners;

    static readonly System.Action _cachedDelegate = FireNextEvent;

    public static void Subscribe(Action<T> listener) { _listeners += listener; }
    public static void UnSubscribe(Action<T> listener) { _listeners -= listener; }

    public static void Enqueue(T eventData) {
        _queue.Enqueue(eventData);
        EventQueue.Enqueue(_cachedDelegate);
    }

    static void FireNextEvent() { _listeners?.Invoke(_queue.Dequeue()); }
}

```

We can repeat this pattern for events using two arguments, three, etc.

```
public abstract class Event<T1, T2> {
    static readonly Queue<(T1, T2)> _queue = new Queue<(T1, T2)>();

    static event Action<T1, T2> _listeners;

    static readonly System.Action _cachedDelegate = FireNextEvent;

    public static void Subscribe(Action<T1, T2> listener) { _listeners += listener; }
    public static void UnSubscribe(Action<T1, T2> listener) { _listeners -= listener; }

    public static void Enqueue(T1 first, T2 second) {
        _queue.Enqueue((first, second));
        EventQueue.Enqueue(_cachedDelegate);
    }

    static void FireNextEvent() {
        var (first, second) = _queue.Dequeue();
        _listeners?.Invoke(first, second);
    }
}

```

Now when we want to define a new concrete event type, it's a one-liner:

```
public class UnitDiedEvent : Event<UnitDiedEventData> {}

```

We can subscribe to the event like so:

```
UnitDiedEvent.Subscribe(MyListenerMethodOrDelegate);

```

And we can issue an event into the queue similarly:

```
UnitDiedEvent.Enqueue(deathData);

```

The only allocations here occur when the queue data structures need to expand. In the steady state, when your queue capacity is enough for the event volume, logging and handling events incurs no memory allocation, boxing, or dictionary lookups.

When we want to pump the queue of all events in order, we can just loop:

```
// Store the count before we start iterating, in case handling
// one event causes new events to be added to the queue.
int count = EventQueue.Count;
for (int i = 0; i < count; i++)
    EventQueue.TryFireNextEvent();

```

Of course, if you don't care about handling events in interleaved order, you can do away with the central `EventQueue` class and instead pump each concrete event type's queue at the appropriate place in your code - which gets rid of one indirection and helps improve your cache locality.
> 0 votes

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


# Question
Title: Sticking the Rigidbody2D player to a moving platform without parenting & transform fiddling
I have a player entity with Rigidbody2D component and I have a moving platform which is a kinematic Rigidbody2D. Player movement is done by setting it's velocity (`body.velocity = newVelocity`) and platform is moved via `body.MovePosition`.

I've made it so that the platform has a sensor which, when triggered, catches the Rigidbody2D of the entity that is on (currently only does that for player) and then I tried the following:

1. Moving the player along the platform with `caughtRigidbody.MovePosition`. This keeps the player on the platform but the player is unable to move. It seems that `MovePosition` overrides any velocity change on the player and keeps him on the platform indefinitely. This would be ideal if I could have this behavior but keeping player movement.
2. Moving the caught rigidbody by adding platform velocity to the body but it seems jittery and also happens to behave strangely when platform direction changes.

I got the player movement how I want it so I'm not willing to tear out the whole movement code and change the player to kinematic or something like that.

This is the relevant platform code:

```
public class MovingPlatform
{
    private void FixedUpdate()
    {
        // Only one node (initial position). Nowhere to move to
        if (worldNodes.Length == 1)
        {
            return;
        }

        // Target position reached?
        if (body.position == worldNodes[index])
        {
            // Is last (or first in backwards direction) target?
            if (direction == Direction.Forwards && index == worldNodes.Length - 1 ||
                direction == Direction.Backwards && index == 0)
            {
                // Change direction (forwards = 1, backwards = -1)
                direction = (Direction) ((int) direction * -1);
            }

            // set next target index
            index += (int) direction;
        }

        // Get target
        Vector2 target = worldNodes[index];
        // Get current platform position
        Vector2 position = body.position;
        // Calculate single-frame movement towards target
        Vector2 movementThisFrame = Vector2.MoveTowards(position, target, settings.Speed * Time.deltaTime);
        // Move platform by calculated movement
        body.MovePosition(movementThisFrame);
        // Calculate platform movement velocity (displacement / time delta)
        velocity = (movementThisFrame - position) / Time.deltaTime;
        MoveCaughtRigidbodies();
    }

    private void MoveCaughtRigidbodies()
    {
        foreach (Rigidbody2D caughtRigidbody in caughtRigidbodies)
        {
            // This keeps the player on the platform without jittering, but the player cant move
            //caughtRigidbody.MovePosition(caughtRigidbody.position + body.position - lastPosition);

            // This is spotty. It launches the player off the platform sometime when the platform changes direction
            // if (caughtRigidbody.velocity != velocity)
            // {
            //     caughtRigidbody.velocity += velocity;
            // }
        }

        lastPosition = body.position;
    }
}

```

# Answer
After some fiddling, I have implemented a variation of my earlier attempt and Anders' answer. Unfortunately Anders' answer was incompatible with my project as I am not using `MovePosition` to move my character normally. I use `velocity` or `AddForce`.

First. Instead of detecting if the actor is on a platform using a trigger collider, I've decided to use the `OnCollisionEnter2D` event and check if the contact is on top by getting a dot product between the actor contact normal and the down vector. If the resulting dot product is 1 then the actor is standing on the platform.

```
    private void OnCollisionEnter2D(Collision2D other)
    {
        if (other.rigidbody.bodyType == RigidbodyType2D.Static)
        {
            return;
        }

        IMovingGroundAware actor = other.collider.GetComponent<IMovingGroundAware>();
        if (actor == null)
        {
            return;
        }

        int count = other.GetContacts(contactPoints);
        for (int i = 0; i < count; i++)
        {
            // Check contacts to see where the contact took place
            ContactPoint2D contactPoint2D = contactPoints[i];
            // Get the dot product
            float dot = Vector2.Dot(contactPoint2D.normal, Vector2.down);
            // If the contact is at the top of the platform the dot product should be ~1
            if (dot > 0.9f)
            {
                // Set the moving ground on the actor motor so that it may be moved along
                // with the platform
                actor.SetMovingGround(this);
            }
        }
    }

```

and `OnCollisionExit2D` i set the moving ground to null

```
    private void OnCollisionExit2D(Collision2D other)
    {
        IMovingGroundAware actor= other.collider.GetComponent<IMovingGroundAware>();

        actor?.SetMovingGround(null);
    }

```

Then, on the actor which implements the `IMovingGroundAware` interface I have a method which runs after all other movement and checks if the actor is in idle state. If the actor is in idle state (no movement input) then move the actor along the moving ground using `body.MovePosition`

```
    private void FixedUpdateMovingGroundProcessing()
    {
        if (movingGround == null)
        {
            return;
        }

        // If the player is idle an is on moving ground
        if (movementStateMachine.CurrentState.Id == MovementStateId.Idle)
        {
            // Move him with the platform
            body.MovePosition(body.position + movingGround.Velocity * Time.deltaTime);
        }
    }

```

This is not perfect, but it works for my use case. If anyone has any ideas on how to improve this. Feel free to let me know.
> 0 votes

# Answer
*\[EDIT: I have written an answer above which solves the question without friction. I keep this one however since it is still valid in many situations and the comments give some context to the solution.\]*

---

As you described it the player should follow along with the platform automatically - you are using physics and that should take care of it.

Ok, I am not an expert in 2D physics but I think it is the movement system of the player which causes the error. To be more precise, you move the player by setting a fixed velocity, which cancels out the friction from the platform.

Instead of setting it like this...

```
body.velocity = newVelocity

```

...I think you need to add/subtract from the current velocity, like:

```
body.AddForce(xxx)

```

Depending on how your movement system is implemented it shouldn't be too hard to convert. You could start by simply remove your movement system and check if the character now follows the platform automatically.
> 1 votes

# Answer
Here is a simple solution on how to implement moving platforms without parenting or using the default friction. Since the requirement was not to use any friction we have to create a physical material and set the friction to 0 and add it to the rigidbody of our character (player). For 2D it must be a RigidBody2D, and it must be Dynamic since we want forces to affect it.

There are hundreds of character controlers on the Internet, this is just a simple demonstration on how to solve this question. We start with some standard initialization.

```
using System;
using UnityEngine;

public class PlatformCharacter : MonoBehaviour
{
    /// <summary>
    /// We calculate the delta-movement between each fixed update and use it to
    /// move ourself. Physicla movements should normally only be executed in FixedUpdate.
    /// </summary>
    float horizontalMovement = 0;
    float verticalMovement = 0;

    public float moveSpeed = 20f;
    Rigidbody2D ourRigidBody;
    BoxCollider2D boxColliderPlayer;
    int layerMaskGround;
    float heightTestPlayer;

    /// <summary>
    /// The ground/platform we are currently on, or <c>null</c>.
    /// </summary>
    Collider2D currentGround = null;

    /// <summary>
    /// The position of the ground in the last FixedUpdate (after we have moved our character).
    /// </summary>
    Vector3 currentGroundPosition;

    void Start()
    {
        // Get a reference to our body.
        ourRigidBody = GetComponent<Rigidbody2D>();
        // We collect our collider so we can calculate our height.
        boxColliderPlayer = GetComponent<BoxCollider2D>();
        // We do the height test from the center of the player, so we should only check
        // halft the height of the player + some extra to ignore rounding off errors.
        heightTestPlayer = boxColliderPlayer.bounds.extents.y + 0.05f;
        // We are only interested to get colliders on the ground layer. If we would
        // like to jump ontop of enemies we should add their layer too (which then of
        // course can't be on the same layer as the player).
        layerMaskGround = LayerMask.GetMask("Ground");
    }

```

Note that we collect user input in the Update() function so we don't miss any user input. In this example, we simply check if the A or D keys are down, but once you start to check if a key was just pressed or released (or similar one-time events) it is important to do it in Update().

Note that we adjust the current horizontal movement, we don't set it to a fixed value.

```
private void Update()
{
    // This is a very very simple character movement, just to show the principles.
    if (Input.GetKey(KeyCode.A))
    {
        horizontalMovement = -moveSpeed * Time.deltaTime;
    }
    if (Input.GetKey(KeyCode.D))
    {
        horizontalMovement = moveSpeed * Time.deltaTime;
    }
}

```

Any physical movements should be done in the FixedUpdate() function.

We start by doing a ground check to see if we are on a platform/ground and if so, we adjust the horizontal movement accordingly to how the platform has moved since last time. If we are in the air, or have just landed, we don't do any adjustments.

```
void FixedUpdate()
{
    // Do a ground check to see if we are on a platform, and if so, has it moved since last update?
    RaycastHit2D hit = Physics2D.Raycast(boxColliderPlayer.bounds.center, Vector2.down, heightTestPlayer, layerMaskGround);
    bool isGrounded = hit.collider != null;
    // It is soo easy to make misstakes so do a lot of Debug.DrawRay calls when working with colliders...
    Debug.DrawRay(boxColliderPlayer.bounds.center, Vector2.down * heightTestPlayer, isGrounded ? Color.green : Color.red, 0.5f);

    // Hande the ground check.
    if (hit.collider != currentGround)
    {
        // We have landed on a new platform - or are in the air.
        currentGround = hit.collider;
        if(hit.collider != null)
            currentGroundPosition = hit.collider.transform.position;
    }
    else
    {
        if(currentGround == null)
        {
            // We are still in the air (jumping or falling).
        }
        else
        {
            // We are still on the same ground. Has it moved?
            Vector2 groundMoved = hit.collider.transform.position - currentGroundPosition;
            currentGroundPosition = hit.collider.transform.position;
            // Adjust our character's desired position accordingly to how the ground has moved.
            horizontalMovement += groundMoved.x;
            verticalMovement += groundMoved.y;
        }
    }

    // We can now try to move our character (but still obeying colliders)
    ourRigidBody.MovePosition( new Vector2(ourRigidBody.position.x + horizontalMovement, ourRigidBody.position.y + verticalMovement) );

    // Reset the movement until next time.
    horizontalMovement = 0;
    verticalMovement = 0;
}

```

Note that we use the MovePosition() function to move the player. It will try to move the player to the desired position, hitting colliders/triggers as it should in a physical movement. If we hit a solid collider we might even be stopped - so exactly where the player ends up is up to the physic system.

Finally, we reset the horizontalMovement and are ready for the next loop.
> 1 votes

# Answer
I attached this script to the player and it worked for me
> 0 votes

---
Tags: unity, 2d, rigidbody, moving-platforms
---


# Question
Title: Unity mobile joystick input doesn't react to touch
I created a 3D mobile project, so I used my own joystick script, I also tried joystick from asset store. The problem is that the stick image of joystick doesn't move at all, in this case it's impossible to get input. It doesn't react on input. I searched for the problem and sollution was about raytracer on camera, I added it, still doesn't work. What is the problem? I also followed tutorials to make it step by step, so there wasn't scripts problems and it was the same...

Active input handling set to both new and old versions

# Answer
> 0 votes
You have no input modules attached to your Event System. That means you have the central router for directing events to game objects, but you're missing the parts that actually receive input events from the screen/mouse/etc. and pass them into that pipeline.

Add an "Input System UI Input Module" component to your Event System object. In its default configuration, it should already be set up to respond to both mouse and touchscreen interactions.

---
Tags: unity, mobile, joystick
---


title: Why use Animator.StringToHash?

text:
# Question
Title: Why use Animator.StringToHash?
Using Animator.StringToHash, doing something like:

```
public static readonly int MyBool = Animator.StringToHash("MyBool");

```

Could anyone explain why one would do this?

# Answer
> 7 votes
This has to do with the speed of looking up data.

When you want to assign a new value to a parameter on an animator, Unity has to find where that parameter sits in memory, to be able to put the new value in the right place.

Think of it like trying to find the right office or classroom in an unfamilar building. If someone gives you a description, "It's the room with the door labelled 'Department of Impossible'", then you have to visit every door in some sequence, checking the label on each door, until you find the right one.

But if someone gives you the room number "3042", you're in much better shape. Now you know to start on the third floor, and if a sign in the hallway says "⬅ 3001-3050" then you know to go left, not right. When you find room 3039, you might reasonably guess that your destination is another two doors down, on the other side of the hall. All this helps you find your way to the right place faster.

Analogous things happen inside the computer: having an integer index or key makes it much faster to find the right item in memory.

To avoid the long exhaustive search for a matching string name, it's common to use what's called a Hash Table (in C# you'll see them used in the `Dictionary` and `HashSet` collections). Here we take the initial label we're looking for, then run it through some math called a **hash function** that turns it into a random-looking number (called a hash), so that we (*usually*) get different numbers for different labels, but always the same number whenever we put in the same label. Then we can use the much faster number-guided lookup strategies to find the data quickly.

But running that hash function has a cost of its own - especially if we're starting with a long string. We have to loop over each character in the string and do some work on it. And if we need to ensure the hashes are always unique, as in this case, then we may have some extra work to do on top of that. All to just get a number that's always going to be the same for a given input anyway.

So instead of re-doing this hashing work every time we want to set a parameter, every frame, for every one of a hundred animated characters, we can do it just once, and store the number we get. Then later, we can just look up the parameter by number, without doing the messy string hashing work every time.

`static` ensures that only one copy of this number is stored in memory, and assigning it right in the initializer like that means we do the hashing work at start-up, just before the class is used for the first time. Then it's practically free to re-use for all our future parameter-twiddling needs.

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


# Question
Title: How to detect long press on object using Unity EnhancedTouch?
I want to implement a feature in my mobile game where if you press on a game object for a certain amount of time while not moving your finger an animation will play. I also need to be able to drag and drop objects. I have the drag and drop functionality working already, but know I also need the press and hold feature. I have this code at the moment:

```
 private void Update()
 {
    foreach (var touch in Touch.activeTouches)
    {
        // Only respond to first finger
        if (touch.finger.index == 0 && touch.isInProgress)
        {
            Ray ray = mainCamera.ScreenPointToRay(touch.screenPosition);

            RaycastHit2D hit = Physics2D.GetRayIntersection(ray);

            if (hit.collider != null)
            {
                print("Selected: " + hit.collider.name);
                // Drag game object
            }

        }
    }
}

```

This code works just like I want it. You put a finger on the screen and a ray is used to select an object that I can drag. But I am not sure where to start on the other feature described in the paragraph above, there is a startTime and a startScreenPosition property that maybe can be used for this, but I don't know how. Any help is greatly appreciated.

Thanks.

# Answer
> 1 votes
A couple of notes: Unless you specifically want to check that the user keeps their finger on the desired object at all times, I would probably only check at the beginning of the touch, as well as the moment when you want the *hold* to trigger.

You can simply compare the `startTime` property to `Time.realTimeSinceStartup` and check when a certain amount of time has passed. You then just need to take care of only calling a method or performing some action **once!**

private const float HoldTime = 0.5f;
private bool _triggeredHold = false;

private void Update()
{
    foreach (var touch in Touch.activeTouches)
    {
        if (touch.finger.index == 0 && touch.began)
        {
            _triggeredHold = false;
        }

        // Only respond to first finger
        if (touch.finger.index == 0 && touch.isInProgress)
        {
            var delta = Time.realTimeSinceStartup - touch.startTime;

            if (delta > HoldTime && _triggeredHold == false)
            {
                _triggeredHold = true;

                // Do something
            }

            // ...
        }
    }
}
```

---
Tags: unity, touch
---


# Question
Title: What algorithm is best for finding non-static nearest neighbors on a 2d grid?
A bottleneck I've hit is querying Quadtrees for finding nearby locations. It's much faster than comparing each location, but I'd like to find faster methods that work for moving locations. Profiles done have shown that this factor is the responsible for nearly 99% of all cpu time, so even microperformance improvements to the concept or alternative ideas are welcome.

# Answer
> 1 votes
An alternative I found was Spatial Hashing.

The basics work as such: If I was given a 100x100 world, it would be split into 10x10 chunks. Each chunk holds all the entities in its 10x10 world area. Searching for them is as simple as only getting the chunks guaranteed to have neighbors. For example, searching a 3x3 square (43, 43).

I did a bit more optimization and had chunks that were encompassed by a search radius to automatically add them all and only to check the distance of individuals on the edges of the 3x3 surrounding (43, 43). Some profiling shows that this spatial hashing is at least 600-2000% faster in my case, and it was exceedingly simple,

---
Tags: performance, quadtree, search
---


title: Reflection Line2D

text:
# Question
Title: Reflection Line2D
I found a video on YouTube with a sercol and a beam, and everything seems to be fine, but the beam doubles and flickers after spawning from the mirror, tell me what could be the problem, screenshot and the code is attached.

```
extends Node2D

onready var ray = $RayCast2D
onready var lain = $Node2D/Line2D

var vec = Vector2()
var max_bounces = 5

func _process(delta):
    lain.clear_points()

    vec.y-=1

    lain.add_point(Vector2.ZERO)

    ray.global_position = lain.global_position
    ray.cast_to = vec.normalized()*1000
    ray.force_update_transform()

    var prev = null
    var bounces = 0

    while true:
        if not ray.is_colliding():
            var pt = ray.global_position + ray.cast_to
            lain.add_point(lain.to_local(pt))
            break

        var coll = ray.get_collider()
        var pt = ray.get_collision_point()

        lain.add_point(lain.to_local(pt))

        if not coll.is_in_group("Mirrors"):
            break

        var normal = ray.get_collision_normal()

        if normal == Vector2.ZERO:
            break

        if prev !=null:
            prev.collision_mask = 3
            prev.collision_layer = 3
        prev = coll
        prev.collision_mask = 0
        prev.collision_layer = 0

        ray.global_position = pt
        ray.cast_to = ray.cast_to.bounce(normal)
        ray.force_raycast_update()

        bounces+=1
        if bounces >= max_bounces:
            break

    if prev !=null:
        prev.collision_mask = 3
        prev.collision_layer = 3

```

# Answer
You should be calling `ray.force_raycast_update()` when you changed `ray.cast_to`, and you should be calling `ray.force_update_transform()` when you changed `ray.global_position`. Since you changing them together, call these together too. Here:

```
    ray.global_position = lain.global_position
    ray.cast_to = vec.normalized()*1000
    ray.force_update_transform()
    ray.force_raycast_update()

```

And here:

```
        ray.global_position = pt
        ray.cast_to = ray.cast_to.bounce(normal)
        ray.force_update_transform()
        ray.force_raycast_update()

```

And with that the flickering should be gone.

---

There are other improvements we can do to the code. Notably it mixes local and global coordinates. The reason being that `cast_to` is local to `ray`. Which means instead of this:

```
var pt = ray.global_position + ray.cast_to

```

You should do this:

```
var pt = ray.to_global(ray.cast_to)

```

And since we have the `normal` in global coordinates. This is not correct:

```
ray.cast_to = ray.cast_to.bounce(normal)

```

Instead, we are going to convert `ray.cast_to` to global, then bounce it, and back to local:

```
ray.cast_to = ray.to_local(ray.to_global(ray.cast_to).bounce(normal))

```

With that, you should be able to move or rotate your `Node2D` and the laser should go with it.

---

By the way, instead of switching collision layers and mask, you can add an exception to the ray with:

```
ray.add_exception(coll)

```

And remove it with:

```
ray.remove_exception(prev)

```

Ah, and if you want to clear the exception, you call `clear_exceptions`:

```
ray.clear_exceptions()

```

---

I also want to point out that every frame you decrement `vec.y`:

```
vec.y-=1

```

*If you keep decrementing `vec.y` it will eventually go out of representable integers.*

You probably want to just give a value once. Don't forget you are normalizing and then scaling by 1000 anyway:

```
ray.cast_to = vec.normalized()*1000

```

And yes, that is local of the `ray`. Which is why moving or rotating it should also move the ray.
> 1 votes

---
Tags: 2d, raycasting, godot
---


# Question
Title: How to sort leaderboards, given wins and total games played?
The game is card game. The only results I get is wins and TGP (total games played). Losses = TGP - wins. I want to rank the players in the most fair way without making it too complex. What I have considered for now:

1. Sort by wins only: This does not work very well, as players who have played more games will be always on top, even if they lose most of the time.
2. Sort by wins / TGP: This is better, but still has flaws. A player who has 1 win and 1 game will be in front of player who has 99 wins and 100 games. What seems absurd.
3. Use 2 but limit leaderboards to players with at least X games: This will still give non fair results for players who have exceeded the limit by far.

# Answer
One option is to add a constant to both values:

```
RankScore = (Wins + Inertia) / (Total + 2 * Inertia)

```

I called this constant "Inertia" because it creates a resistance to moving up and down the ranks, especially for players who have not played many games yet. You can tune the constant up or down to control how strong the effect is.

Effectively, this models some number of past games played at a perfect 50/50 win rate. So a new player who wins their first match enters the leaderboard only a little above halfway up, instead of at the top.

As the player increases their total games played, their true wins and games played come to dominate the equation, so a player who goes on a winning streak will gradually approach the upper bound score of 1 (asymptotically — they'll never reach it, but the more games they win, the closer they'll get).

You could also make this not a constant, but a function of total games played, something like:

```
NewPlayerBias = Max(0, TrialPeriod - Total)
RankScore = (Wins + NewPlayerBias) / (Total + 2 * NewPlayerBias)

```

This way, the bias goes away entirely once the player has played at least `TrialPeriod` games. In this form, it's saying "we have too little data on you to accurately assess your rank, so we're going to hedge our bets on the assumption that you're about average, statistically". And then smoothly falling back to a simple win percentage once you're satisfied you've collected enough data to have a fair assessment.

Just to double-check that this bias hasn't made our score behave unintuitively in any cases:

* Winning during the trial period doesn't change the numerator (+1 win, -1 bias), but it does reduce the denominator by 1 (+1 game, -2 bias), so you're guaranteed your score strictly improves when you win.
* Losing during the trial period makes both numerator and denominator reduce by one. A little algebra will show that as long as the numerator and denominator are positive, and the numerator is less than or equal to the denominator, both of which are true by construction here, the score strictly decreases in this case.

So we never get a paradoxical result where losing a match makes our score go up or winning a match makes our score go down, because of the way the bias fades out.

Here's a graph showing how the rank score smooths out the wild fluctuations of a new player, for random patterns of wins and losses, converging to a regular win rate measure at the end of the trial period:
> 2 votes

---
Tags: mathematics, game-design, leaderboards, sorting, ranking
---


# Question
Title: How to support run-time shader modification/code execution?
I would like to create an educational game, part of which involves allowing the user to modify code for procedurally generating geometry on the CPU and modify shader code and see the changes they make reflected in real-time.

Unlike How can I create a shader at runtime in Unity, I can't use a workaround with if statements, since one of the learning goals is to learn how to code shaders/procedural geometry, and I want users to be able to enter genuinely arbitrary code (ideally sandboxed) to explore the space of possibilities.

My current workflow uses javascript, THREE.js, and GLSL (through webGL), which can certainly manage this kind of process, but I'm considering learning to use a large game engine (such as Unity or Unreal) to take advantage of the conveniences they offer (and so I can learn how to use a large game engine).

How can I allow runtime shader authoring in the context of a larger game engine?

# Answer
> 2 votes
**This answer is about Godot.** Since Godot games are running on the same core as the editor, they can do almost everything the editor can do. This also means that powerful modding and meta-programming is possible with Godot.

---

## Godot

This is quite an advanced topic to be the entry point for Godot. I don't think I can make a proper introduction to the engine here, so please pick up a tutorial. Yet some concepts are going to be necessary for the answer, so I feel compelled to provide a quick and dirty explanation of some of Godot idiosyncrasy, mainly similarities and differences with other engines.

First of all, there is an `SceneTree`, it has `Node`s, and each node can have a `Script` attached. Some kinds of `Node` include `Viewport`, `Camera`, `RigidBody`, `MeshInstance`, `ImmediateGeometry`, and so on.

You can have serialized branches (serialized `Node`s including children), and to that we refer as "scene". So you can instance a "scene" inside the `SceneTree`. And you can also instance a "scene" inside another "scene", because it all one `SceneTree`. So there is no "prefab"/"scene" distinction.

Also, Godot is not component based, instead of adding components to a `Node`, you add specialized `Node`s as children. Thus, again, it is all one `SceneTree`.

*Well, we are actually going to challenge the idea that there is only one `SceneTree` in this answer. So, let us say it is all - usually - one `SceneTree`.*

It is also useful to be aware of `Resources`. `Resources` are `Objects` that Godot knows how to serializase and deserialize. So, an "scene" is a `Resource`, of type `PackedScene` to be precise. `Script`s are also `Resource`s, and so are meshes and so on.

*By the way, I've been told that `Resource`s are similar to "ScriptableObjects" or "DataAssets", but more versatile.*

Godot has both reference types and value types. All reference types ultimately inherit from `Object`. Among them, some are reference counted, which inherit from `Reference`. The `Node` does not inherit form `Reference`. Instead they are manually freed. Which also means you could have a reference to a freed `Node`, which is not a `null` pointer. You can check with `is_instance_valid`.

A `GDScript` script is a `GDScript` class. Or to put it another way, `GDScript` scripts can inherit from other `GDScript` scripts. They can also inherit from built-in classes. If we don't specify, they inherit from `Reference`. So all `GDScript` scripts ultimately inherit from some built-in type.

Finally, when we attach a script to a `Node`, we need a script that inherits from the class of the `Node`. In fact, when we call `new` on a script (and I remind you that the script is class as far as other scripts are concerned), Godot will instance an `Object` of the type the built-in type the script ultimately inherits from and attach the script to it.

---

## Sandboxing?

Godot does not have proper sandboxing… And by that I mean there is no permission system or similar that restricts what the code can do. So the fact that Godot lets you do so much at runtime is a double edged sword.

However, I want to point out that you can create a separate `SceneTree` from the one you get by default. It is easy, actually:

```
var scene_tree := SceneTree.new()

```

We can call `init` on it:

```
func _ready() -> void:
    scene_tree.init()

```

*The `_ready` function will run when the `Node` and dependencies has been loaded in the `SceneTree`, I mean, the main one in this case… The one in which the `Node` with script we are talking about is.*

And with that the secondary `SceneTree` will start rendering over the main one. You can disable that if you don't want it to, with:

```
scene_tree.get_root().set_update_mode(Viewport.UPDATE_DISABLED)

```

*Be aware that the `root` of the `SceneTree` is a `Viewport`.*

Or if you prefer to have both, perhaps we can split the screen. The following code will set then side by side:

```
func resize() -> void:
    var window_size := OS.window_size
    var half_window_size := Vector2(window_size.x * 0.5, window_size.y)
    var left := Rect2(Vector2.ZERO, half_window_size)
    var right := Rect2(Vector2(half_window_size.x, 0.0), half_window_size)
    scene_tree.get_root().set_attach_to_screen_rect(right)
    get_tree().get_root().set_attach_to_screen_rect(left)

```

We want to run that code every time the window/screen resizes, so let us connect it to the `"screen_resized"` signal (and by signal I mean what you would call an "event"):

```
func _ready() -> void:
    scene_tree.init()
    get_tree().connect("screen_resized", self, "resize")

```

And while we are at it, make sure to call it at least once:

```
func _ready() -> void:
    scene_tree.init()
    get_tree().connect("screen_resized", self, "resize")
    res

```

*Be aware that this is not a typical split screen. Usually when we split the screen we want to render the same `SceneTree` on each side, perhaps form a different `Camera`. But we are not doing that here. Instead here we are rendering two entirely different `SceneTree`s. Of which, one controls the other.*

---

You can change the the scene of the `SceneTree`, for example:

```
scene_tree.change_scene("res://scenes/test/scene.tscn")

```

And we need to call into the secondary `SceneTree` each frame:

```
func _process(delta: float) -> void:
    scene_tree.idle(delta)

func _physics_process(delta: float) -> void:
    scene_tree.iteration(delta)

```

*The `_process` method will run each graphics frame. And the `_physics_process` will run each physics frame. You can establish the rate of physics frames in Project Settings.*

Finally call `scene_tree.finish()` when you are done with it.

I remind you that this secondary `scene_tree` is like the main one. It has a `root` and you can add `Node`s to it.

Then you can put all the stuff made at runtime in that other `SceneTree`. It does not give you control over what that code can do (because, again, no proper sandboxing). *So it can still make network requests, mess with the file system and stuff like that.* But it will be isolated form your own (the code on the secondary `SceneTree` does not have a way to get a reference to the main one).

**ERRATA**: There is a way: `Engine.get_main_loop` will give you the default `MainLoop` which is the `SceneTree` (the `SceneTree` class extends `MainLoop`). By the way, you can change the main loop from project settings, under Application -\> Run -\> Main Loop Type.

---

Ultimately you would probably want to parse the code from the user. This will allow you to provide pretty printing, and also making sure it does not call what it should not. You can start with the GDScript reference grammar. The documentation does not include the equivalent for the shading language, however it is basically GLSL.

---

## Creating shaders at runtime

*I'll point out that Godot has `VisualShader` but the UI to create them is not included in games. You could make your own UI for them (Based on `GraphEdit` and `GraphNode`). But this answer will cover text based shaders instead.*

To create a shader in runtime in Godot, we can follow the following approach:

1. Create a new `ShaderMaterial` object:

```
var shader_material := ShaderMaterial.new()

```
2. Create a new `Shader` object:

```
var shader = Shader.new()

```
3. Then set the shader code for the shader:

```
shader.code = """
shader_type spatial;
render_mode unshaded;

void fragment()
{
    ALBEDO = vec3(UV, 0.0);
}
"""

```

*Here I'm using `"""` for a multiline string literal. The example is an a spatial shader (so one you would use for a `MeshInstance` (3D)) that output the UV coordinates as color.*
4. Set the shader to the shader material:

```
shader_material.shader = shader

```
5. And set the shader material to where you need it:

```
$MeshInstance.set("material/0", shader_material)

```

*Here it will be the first material (`0`) of the mesh.*

*Oh, by the way, the `$` syntax is used in GDScript to reference a child `Node` by name.*

Just because you have already set the material does not mean you cannot replace the code. So, if I have already set a shader material, I can just replace the code, no hassle:

```
var shader_material = $MeshInstance.get("material/0")
shader_material.shader.code = """
shader_type spatial;
render_mode unshaded;

void fragment()
{
    ALBEDO = vec3(1.0, 1.0, 0.0);
}
"""

```

*This shader outputs pure yellow.*

Beyond that, if you want to allow users to write shader code, you could provide a text editor, take what the write, and perhaps do some string manipulation before setting it such as shown above.

Caution:

* Make sure you have a `ShaderMaterial` with a `Shader` before you try to modify its code, otherwise you are going to get an error.
* If the code is invalid you will also get an error.

In this error conditions you are going to get the default material. So they are not fatal. However, I haven't found a good way to detect them from GDScript. What the editor does is output the errors to the console. We could use logging (you can configure it on project settings, it is enabled by default) and monitor the logs, but that is not practical at all.

* When the shader compiles (when it is first seen), Godot may skip a frame. Godot 3.4.5 (currently in beta) should allow for async compilation of shaders.

---

## Creating meshes at runtime

The simplest way to generate a mesh at runtime is using a `Node` of type `ImmediateGeometry`. Its usage is similar to old school OpenGL's immediate mode.

For example, this would draw a segment (I'm assuming this is running in a script attached to the `ImmediateGeometry`):

```
clear()
begin(Mesh.PRIMITIVE_LINES)
add_vertex(Vector3.ZERO)
add_vertex(Vector3.FORWARD)
end()

```

However, despite the name and the similarity to the immediate mode, it is actually creating a mesh under the scenes. Which is why we need to call `clear` to reset it, and also why this code does not have to be in `_process` or any particular method. In fact, the coordinates of the vertex are local, and you can position the `ImmediateGeometry` like any other node.

We can, of course, make a triangle mesh with `Mesh.PRIMITIVE_TRIANGLES` instead of `Mesh.PRIMITIVE_LINES`.

And we can set:

* Vertex color with `set_color`.
* Normal with `set_normal`.
* Tangent and binormal with `set_tangent`. It takes a `Plane`, the normal of the plane is the tangent. The distance to the plane is the scale of the binormal (you probably want to pass `1.0`).
* UV with `set_uv`.
* UV2 with `set_uv2`.

You can assign a material to the `ImmediateGeometry` by setting its `material_override`. If you need more than one material, or some other features, we need to move to `SurfaceTool`.

---

To use `SurfaceTool`, create an instance:

```
var surface_tool := SurfaceTool.new()

```

Then we use `SurfaceTool` pretty similar to `ImmediateGeometry` above. So we can call `begin`, `add_vertex` and so on. Furthermore, you can set a material with `set_material` and even define bones and weights. Taking full advantage of `SurfaceTool` is beyond me, but…

What you are making is a *surface*. You are going to add these surfaces to a mesh. So have a mesh:

```
var mesh := ArrayMesh.new()

```

And then add the surface to the mesh:

```
surface_tool.commit(mesh)

```

Do that for as many surfaces as you need. Each surface can have its own material.

---

You may also be interested in `MeshDataTool` which provides some capacity to query and edit existing meshes (instead of authoring new ones).

---

## Creating and running scripts at runtime

*Godot also support visual scripting ("blueprints" style), but similar to what happens with `VisualShader`, the UI to create them is not included in games. But we have text based scripting, and that is what I'll talk about.*

You can create that a script in runtime too. Create a `GDScript` object:

```
var script:= GDScript.new()

```

Then set its `source_code`:

```
script.source_code = """
extends Node

func method() -> void:
    print("hello")
"""

```

*Yes, you could also read the `source_code` of existing GDScript scripts. On a similar note, you could have the script created at runtime inherit from another script.*

Then reload it… This time checking if it went OK is readily available:

```
if OK != script.reload():
    print("Error loading script")

```

And now you could attach it to an `Object` (e.g. a `Node`) with `set_script`. Or you can instance it directly, and use it:

```
if script.can_instance():
    var instance := script.new() as Node
    instance.method() # should print "hello"

```

---

I also want to mention `Expression` which will let you execute - as the name suggest - an expression.

Start by creating the `Expression` object:

```
var expression := Expression.new()

```

Then parse the string expression:

```
var parameters:PoolStringArray = ["p"]
if OK != expression.parse("2 + p", parameters):
    print(expression.get_error_text())

```

In this case the expression will have one parameter `"p"` which we need to pass when we want to execute it.

And, of course, execute it:

```
var argument := [5]
var result = expression.execute(arguments, null, true)
if not expression.has_execute_failed():
    print(result) # should print 7

```

The arguments are passed to the parameters according to their position in the array.

The `null` I'm passing is the `self` reference. And the `true` is enabling error output.

So `Expression` can be a way to execute something that might fail and check if it failed. *And, no, it does not work for the shader, as the error happens when Godot compiles it not when we set its code.*

# Answer
> 0 votes
Polygonjs may be interesting for this situation. It is nowhere near as complete as Unity or Unreal, but it provides a layer on top of threejs, where you can create your own shaders as well as procedural geometries with a node-based editor.

(disclaimer, I am building it)

Its core library is also open-source, so you could easily extend it if needed.

And you can edit the shaders live from the editor. But by default, when you export a scene, the shaders are not editable via Polygonjs api anymore, only via threejs api. The reason is to make sure the export scene is as optimized as possible. Happy to discuss options if that was something interesting to add.

---
Tags: shaders, procedural-generation, code-reflection
---


# Question
Title: How to support ambidextrous weapon-holding animations
I'm making an action game in Unity, where the player character can hold an item in either hand, and some objects are held in both. I want the PC to be ambidextrous, so I essentially need to be able to "mirror" hand positions, including finger orientations.

To illustrate what I mean, one of the guns in the game is a pistol with a forward grip: if the gun is held in the right hand (the grip is in the right hand), then the left hand grasps the forward grip; if the player holds the grip in their left hand, then it's vice-versa.

How I'm doing this is to have basically a copy of the hand armatures saved for each item, posed in the configuration the PC's hands should be in, and then I match those transforms when the item is held (I'm using IK to get the hands in the correct place). What I would like to be able to do is mirror those hand positions for the "left hand" hold of an object. Are there any best practices for doing things like this, having animations/poses be symmetrical or reversible or whatever you want to call it? Should I set up the PC model's rigging in a particular way, or is there some more simple way to mirror the positions?

# Answer
*Counter-Strike* is the only game I can think of that made an effort to support holding weapons left handed; they went for the simplest solution and simply mirrored the right-handed models. This requires almost zero effort but means everything on the guns is flipped; anything that is really located on the right side of the gun will be on the left side of the gun when it is mirrored, and vice-versa. Your average person won't notice or care, but gun enthusiasts can be annoyed by such details. In Unity, you can mirror a model horizontally by simply setting the scale on the X-axis to `-1`.

There are several potential ways you can use mirroring, depending on the content of your game:

* If you have fictional guns (e.g. in a sci-fi setting), you could simply design ambidextrous weapons that look about the same on both sides, so it's not obvious if the weapon is mirrored. Some real-world weapons still fit this idea; for example, the FN P90 looks pretty much the same on both sides.
* Another potential option, if the animations don't involve interacting with something on one side of the weapon/item, is to mirror the arms but not the item. For example, with your typical semi-automatic pistol, all of the animations would look fine if you mirrored the arms on the X-axis but didn't mirror the pistol (if the pistol is a child of the arms, you can set its X-axis scale to `-1` to un-mirror it).

With clever use of mirroring, you might not need separate copies of your animations for left-handed and right-handed use.
> 2 votes

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


# Question
Title: How do I check for nulls when called an event from another script?
```
 public GameObject OnComplete;
void Start()
{
    FindObjectOfType<ThirdBossSpawn>().CompletionLevelOne += OnCompletionScreen;
}

void OnCompletionScreen()
{
    OnComplete.SetActive(true);
}

public void AccomplishScreen()
{
    SceneManager.LoadScene(0);
}

```

I got nullreference error on this error `" FindObjectOfType<ThirdBossSpawn>().CompletionLevelOne += OnCompletionScreen;"` But I'm not sure how to check for nulls in terms on this situation considering "ThirdBossSpawn" is from another script

# Answer
> 0 votes
Create a class where you store all the boss references. Let's call it *BossSpawnManager* Then cache it in your script and use it

```
public BossSpawnManager bossSpawnManagerRef;

void Start()
{
      if (bossSpawnManagerRef != null)
      {
            bossSpawnManagerRef.CompletionLevelOne += OnCompletionScreen;
      }
}

```

# Answer
> 0 votes
The same way you check for nulls for *literally* anything else.

```
void Start()
{
    var thirdBoss = FindObjectOfType<ThirdBossSpawn>()

    if (thirdBoss != null) thirdBoss.CompletionLevelOne += OnCompletionScreen;
}

```

But honestly, if you're getting a null here, it means you have set up your scene incorrectly. You have a script that depends on a `ThirdBossSpawn` script when no such script instance can be found. So just suppressing the null error won't fix this more fundamental problem.

---
Tags: unity
---


# Question
Title: Passing a string as argument to Unity Job System
I have a Job that needs to take some string from main thread and use it locally.

Considering that the Job System cannot directly accept the string as an argument, is there any workaround to circumvent this limit?

Can we move the string to a `NativeArray<bytes>` and then repackage it back into the string inside the job and use it?

For now I just have an empty string as output from the `Debug.Log` below:

```
string myString = "string";
StringTest job = new StringTest
{
    // first I need a way to copy a string to array of bytes.
    inStr = new NativeArray<byte>(myString.Length, Allocator.TempJob),
};
JobHandle handle =  joba.Schedule();
handle.Complete();

```

```
public struct StringTest : IJob
{
    public NativeArray<byte> inStr;

    public void Execute(){
        string s = Encoding.ASCII.GetString(inStr.ToArray());
        Debug.Log("debug log from Job " +s);
    }
}

```

# Answer
> 1 votes
Original code does not copy data from a string to a native array of bytes. First we need to copy String data to `byte[]`, and then pass it back to a job, like this :

```
string myString = "flcw";
byte[] bytes = Encoding.ASCII.GetBytes(myString);
Debug.Log("creating  Job");
StringTest job = new  StringTest job
{
    inStr = new NativeArray<byte>(bytes, Allocator.TempJob),
};

```

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


# Question
Title: X axis intersection with inverted Y axis coordinates
I'm making a visual clue for the player to know where (and more or less when) an asteroid is going to enter the screen. For this I'm using a triangle pointing at the incoming object and color interpolation from green (far) to red (near).

My working thoughts are this:

1. Determine from which part of the screen the aerolite will enter (top, left, ...) by calculating tha angle of the spawn point of the aerolite and the center of the screen with `atan2`.
2. Asign a entering direction so the pointing arrow can stay close to the border that the aerolite will enter.
3. Calculate the entering point using slope Y intersect formula `b = y - mx` and X intersect `x = -b / m`.
4. Calculate, with the linear velocity of the aerolite, the time it will take to arrive to the entering point, so I can interpolate the colors.

So far so good for the aerolites that come from left or right directions, but **I get wrong results from the ones that come from top or bottom**. Here's the code:

```
// project a point from the position and the delta_v. Useful for working with lines / segments
const b2Vec2 point_b {aerolite_pos + delta_v};
float slope{}, distance{};
b2Vec2 intersect_point {};
// arrow: calculate the angle of attack respect to the screen's center
const auto theta {atan2Normalized(aerolite_pos.y - screen_center.y, aerolite_pos.x - screen_center.x)};
// asign an incoming direction so we can position the arrow
if (theta >= top_right && theta < top_left) {
  // TOP
  aerolite->arrow_->incoming_direction_ = Direction::Top;
  slope = (point_b.y - aerolite_pos.y) / (point_b.x - aerolite_pos.x);
  const auto y_intersect = aerolite_pos.y - (slope * aerolite_pos.x);
  intersect_point.Set(-y_intersect / slope, b2_screen_size_.y);

} else if (theta >= top_left && theta < bottom_left) {
  // LEFT
  aerolite->arrow_->incoming_direction_ = Direction::Left;
  slope = (point_b.y - aerolite_pos.y) / (point_b.x - aerolite_pos.x);
  intersect_point.Set(0.f, aerolite_pos.y - (slope * aerolite_pos.x));

} else if (theta >= bottom_left && theta < bottom_right) {
  // BOTTOM
  aerolite->arrow_->incoming_direction_ = Direction::Bottom;
  slope = (point_b.y - aerolite_pos.y) / (point_b.x - aerolite_pos.x);
  const auto y_intersect = aerolite_pos.y - (slope * aerolite_pos.x);
  intersect_point.Set(-y_intersect / slope , 0.f);

} else {
  // RIGHT
  aerolite->arrow_->incoming_direction_ = Direction::Right;
  slope = (point_b.y - aerolite_pos.y) / (point_b.x - aerolite_pos.x + b2_screen_size_.x);
  intersect_point.Set(b2_screen_size_.x, aerolite_pos.y - (slope * (aerolite_pos.x + b2_screen_size_.x)));
}
// distance from spawn point to intersect point
distance = b2Distance(aerolite_pos, intersect_point);
// calculate the time for the aerolite to enter the screen
aerolite->arrow_->time_to_enter_ = distance / delta_v.Length();

```

I've tried changing the sign, inverting formulae, googling, ... but nothing.

How can I calculate the exact point where the aerolite will enter the screen?

Edit: the aerolites always go to the center of the screen, no matter where they spawn.

# Answer
This is way too complicated.

Let's say the screen center is at `(0,0)`, the asteroid coords are `x`,`y`, and the screen size is `w`,`h`. Then this should work:

```
float x2 = x / w;
float y2 = y / h;
float s = max(abs(x2), abs(y2));
float x3 = x2 / s * w / 2;
float y3 = y2 / s * h / 2;

```

`x3`,`y3` are the desired coords.
> 3 votes

# Answer
```
const b2Vec2 point_b {aerolite_pos + delta_v};
...
slope = (point_b.y - aerolite_pos.y) / (point_b.x - aerolite_pos.x);

```

This is equivalent to:

```
slope = delta_v.y / delta_v.x;

```

I don't know more details of what the variables mean, but it's definitely not right. Maybe I can interpret it as relative coordinates from camera to `(0,0)`(delta\_view)? But you use `screen_center` as coordinates from camera later, which confuses me even more.

Given that you have a lot of magic numbers in your code(which is bad coding practice), And the use of angles will have a series of limit value problems. I recommend you to use the vector way to handle it.

The 2 diagonals of the screen rectangle(`v1`,`v2`) divide the space into 4 parts. We need to know which of the four areas the target is in. Use `Cross` to determine whether a point is on the left or right of a vector. With two results we can get the final result.

```
class Vec2:
    def __init__(self, x, y) -> None:
        self.x = x
        self.y = y

    def __sub__(self, v):
        return Vec2(self.x-v.x, self.y-v.y)

    def __truediv__(self, n):
        return Vec2(self.x/n, self.y/n)

def Cross(v1, v2):
    return v1.x*v2.y-v2.x*v1.y

if __name__ == "__main__":
    screenSize = Vec2(1920, 1080)
    centerPos = Vec2(0, 0)
    aerolitePos = Vec2(100, 100)

    v1 = screenSize
    v2 = Vec2(screenSize.x, -screenSize.y)

    isLeftTop = Cross(v1, aerolitePos-centerPos) > 0
    isRightTop = Cross(v2, aerolitePos-centerPos) > 0

    if isLeftTop:
        if isRightTop:
            print("TOP")
        else:
            print("LEFT")
    else:
        if isRightTop:
            print("RIGHT")
        else:
            print("BOTTOM")

```

There is no c++ environment at present, I use python to illustrate, I hope it helps :p
> 0 votes

---
Tags: c++, mathematics, linear-algebra, intersection, lines
---


# Question
Title: Pathfinding over network and local avoidance
I'm trying to build a little MOBA game (max 10 players) in Unity and i'm really stuck with the pathfinding / local avoidance.

Here is what i'm doing when user click to move on the map:

* Client send a MovementPacket containing the target position to the server
* The server will calculate a path using a pathfinding library
* The server will send back this packet with a list of points to all the clients
* Clients will use the same library to follow the points

This is basic and working pretty well.

But problems appears if I want obstacle avoidance between the players (like in League of Legends for example, you can't walk on other players).

Let's say the pathfinding library i'm using (Aron Granberg lib) handle local avoidance, the only "easy" solution I see is to use it on both the server and client side.

But I'm afraid it won't be in sync (for example the RVOSimulator of this library is running at a specific tick in the Update function of unity, but what happens if I have FPS drop on client side?).

Do you know a better way to handle it? It seems to be pretty complex, how do they handle it so well in other mobas ?

Thanks.

# Answer
Unfortunately syncing between games is an extremely complicated problem. There is no simple solution. There are literally entire books on this subject.

The usual solution is to have the server sync the positions of every single unit on the map to all clients multiple times a second. When the client is out-of-sync with the server, you'll need to do clientside interpolation to get things in-sync without looking jarring to the user. This might mean lying to the user about the actual position of things sometimes. This can be reduced with techniques like input prediction, lag compensation, and various other techniques depending on the game.

I believe the above option is what LoL and Dota 2 do. However for games with *a lot* of units, syncing every unit multiple times a second is not realistic. RTS games like Starcraft *(where MOBAs originally come from)* use deterministic lockstep *(more info)*, where every client computes the path independently then executes the pathfind simultaneously. This means the game must be *completely* deterministic, which is non-trivial. It also means that, when one person's computer slows down, the entire game must slow down for everyone. If you've ever seen the message "XYZ is slowing down the game" in Starcraft, that's why.
> 1 votes

---
Tags: unity, networking, path-finding
---


title: d3d11 compute shader compile failed

text:
# Question
Title: d3d11 compute shader compile failed
I want to comiple a compute shader from text, but it failed with 0x8e16d728 error.

```
// #pragma kernel CSMain //line 1,//uncomment this line will generate warning "unknown pragma kernel"

 RWTexture2D<float4> Result : register (u0);

 Texture2D<float4> ImageInput : register (t0);
 cbuffer ImageSize : register(b0) {
     int width;
     int height;
 }

[numthreads(16, 16, 1)]
void CSMain(uint3 id : SV_DispatchThreadID)
{
    uint2 size = uint2(width, height);
    // uint2 size = uint2(ImageSizes[0], ImageSizes[1]);
    uint2 flip = uint2(id.x, size.y - id.y);
    float4 flipped = ImageInput[flip];
    uint2 xy = id.xy;
    Result[xy] = flipped;
}

```

Here is the compile function :

```
static HRESULT compileCS(ID3D11Device* pDevice, int csByteLength, const char* csByteString, ComPtr<ID3D11ComputeShader>& shader) {
    HRESULT hr = E_FAIL;
    if (shader != nullptr)
    {
        return S_OK;
    }

    UINT flags = D3DCOMPILE_ENABLE_STRICTNESS;
#if defined(DEBUG) || defined(_DEBUG)
    flags |= D3DCOMPILE_DEBUG;
#endif
    // Prefer higher CS shader profile when possible as CS 5.0 provides better performance on 11-class hardware.
    LPCSTR profile = (pDevice->GetFeatureLevel() >= D3D_FEATURE_LEVEL_11_0) ? "cs_5_0" : "cs_4_0";
    const D3D_SHADER_MACRO defines[] =
    {
        "EXAMPLE_DEFINE", "1",
        NULL, NULL };
    ComPtr<ID3DBlob> shaderBlob = nullptr;
    ComPtr<ID3DBlob> errorBlob = nullptr;
    hr == D3DCompile(csByteString,
        csByteLength,
        nullptr,
        defines,
        D3D_COMPILE_STANDARD_FILE_INCLUDE,
        "CSMain",
        profile,
        flags,
        0,
        &shaderBlob,
        &errorBlob);
    if (FAILED(hr))
    {
        if (errorBlob)
        {
            const char* error = (const char*)errorBlob->GetBufferPointer();
            auto bufferSize = errorBlob->GetBufferSize();
            Log(error);
        }
        else
        {
            LogFormat("compile shader failed hr = %#08x", hr);
        }
        return hr;
    }
    Log("compile cs success");
    //编译成功
    hr = pDevice->CreateComputeShader(shaderBlob->GetBufferPointer(), shaderBlob->GetBufferSize(), nullptr, shader.ReleaseAndGetAddressOf());
    if (FAILED(hr))
    {
        Log("Create shader from blob failed!");
        return hr;
    }
    return hr;
}

```

When I uncomment line 1 in the hlsl,the error changes to another strange error code 0x8e16d8a8.

Note that errorBlob only shows warning when line 1 is uncommented, and shows nothing when commented, just the error code from hr.

I also tried compile from fxc, it can compile and generate bytecode (although when line 1 is uncommented while compiling, it generates the same "unknown pragma kernel" warning), but another error occured when calling CreateComputeShader..

Now I'm lost, can you help me?

# Answer
You are saying ‘==‘ instead of ‘=‘ when setting your HRESULT.
> 1 votes

---
Tags: directx11, compute-shader
---


title: How can I rotate the game stage?

text:
# Question
Title: How can I rotate the game stage?
I have a pseudo-game which I'm developing in 9:16, to be displayed in vertical screens. The client now needs another version in 16:9, rotated in 90º.

I tried creating a empty object, putting all my elements inside it, and rotating, but it caused a lot of positioning bugs, probably because of *localPosition vs position*.

Any help is appreciated.

Below is **what in have** vs **what I need**:

# Answer
> 1 votes
Did you consider to leave the scene as it is and simply rotate the camera by 90°?

# Answer
> 0 votes
Create a mapping between the position in the vertical screen to that in the horizontal one, so that you reposition all elements according to this mathematical mapping. i.e. : loop through all elements and apply the mapping to each one.

---
Tags: unity, 2d
---


# Question
Title: How to create a 2d array in Unity using Visual Scripting?
Found some good tutorials on how to create 2-dimensional arrays in Unity: https://owlcation.com/stem/Using-Single-and-Multi-Dimensional-Arrays-in-C-and-Unity3D

Anyone know if this is also supported in Unity's Visual Scripting?

# Answer
> 1 votes
You can do this by making your own class.

```
[System.Serializable]
public class Array2D<T>
{
    [SerializeField]
    int _width;

    [SerializeField]
    T[] _data;

    public void Initialize(int width, int height) {
        this._width = width;
        int size = width * height;
        _data = new T[size];
    }

    public T Get(int x, int y) {
        return _data[GetIndex(x, y)];
    }

    public void Set(int x, int y, T value) {
        int index = x * _width + y;
        _data[GetIndex(x, y)] = value;
    }

    int GetIndex(int x, int y) => x * _width + y;
}

```

(I've elided bounds-checking here, so if you try to index outside the dimensions of the array you'll generate an exception or access the wrong item. You can avoid this by structuring your graphs/code to ensure your accesses are always in bounds, or adding your own bounds-checking and fallback behaviour in the methods above)

Unity Visual Scripting won't pick up on custom generics on its own, so you need to stamp out a specialization of this class for each contained type you want to work with:

```
[System.Serializable]
public class Array2DInt : Array2D<int> {}

```

Then you can go to Project Settings \> Visual Scripting and add your new type to the Types section, then click "Regenerate Nodes" to produce nodes supporting this type.

Then you can make variables of this new type, initialize them to a blank array of your chosen dimensions, and get or set values at any coordinates within that range:

This creates a new 5x5 grid of zeros, fetches the value at (1, 3), which is zero, adds one to it, and assigns it back to slot (1, 3) in the grid.

(Adding a custom property drawer to give a nicer interface for inspecting/editing this type is left as an exercise for the reader )

---
Tags: unity, array
---


# Question
Title: Drawn enemy random on different position
I would like to insert random enemies in the map in different positions. It's possible?

This is how i load image of enemy: Enemy.java:

```
public class Enemy {
    public Array<Sprite> enemy = new Array<Sprite>(2);

    public void nemici() {
        Sprite mysterio;
        Sprite boss;
        enemy.add(mysterio = new Sprite(new Texture("mysterio.png")));
        enemy.add(boss = new Sprite(new Texture("boss.png")));
    }
}

```

And this is how i draw with my level1.java:

```
public class Level1 implements Screen{

    private Texture BackgroundLevel1;

    NameGame game;

    Sprite card;
    private Enemy enemies = new Enemy();

    public Level1 (NameGame game){
        this.game = game;

        enemies.nemici();
        card = enemies.enemy.random();

        BackgroundLevel1 = new Texture("BackgroundLevel1.png");
    }

    @Override
    public void show() {
    }

    @Override
    public void render(float f) {
        Gdx.gl.glClearColor(0, 0, 0, 0);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        game.batch.begin();

        //Background
        game.batch.draw(BackgroundLevel1, 0, 0, NameGame.WIDTH, NameGame.HEIGHT);

        game.batch.draw(card,200,0,100,100);  //Example

        game.batch.end();
    }

```

# Answer
> 1 votes
The idea is to store the information of an enemy into a class instance. Here is the pseudo-code of what I have in mind.

I've added pseudo-comments to the pseudo-code to explain what's going on.

```
/**
 * This holds an enemy.
 */
class Enemy:
  Sprite sprite_;
  Vec2 size_;
  Vec2 position_;

  func Enemy(string spritePath, Vec2 size): // constructor
    sprite_ = new Texture(spritePath);
    size_ = size;

/**
 * You store all of the potential enemies here. All the enemies of the same type
 * share the same values for sprite and size. We don't fill the position
 * because that is the level that will load it.
 */
static class EnemyFactory:
  Array<Enemy> enemies_;

  func EnemyFactory(): // constructor
    enemies_.add(new Enemy( "mysterio.png", new Vec2( 100,100 ) );
    enemies_.add(new Enemy( "boss.png", new Vec2( 100,100 ) );

  func GenerateOne(Vec2 position):
    Enemy newEnemy = enemies_.random().clone();
    newEnemy.position_ = position;
    return newEnemy;

class Level1:
  Array<Enemy> enemies_;

  func Level1(): // constructor
    ...
    // Start by defining all the potential spots where an enemy could spawn.
    // Ideally, you'll want to put this in an external file and load it when the
    // game starts.
    Array<Vec2d> potentialPositions;
    potentialPositions.add( new Vec2d(..., ...) )
    potentialPositions.add( new Vec2d(..., ...) )
    potentialPositions.add( new Vec2d(..., ...) )
    potentialPositions.add( new Vec2d(..., ...) )
    potentialPositions.add( new Vec2d(..., ...) )
    potentialPositions.add( new Vec2d(..., ...) )
    potentialPositions.add( new Vec2d(..., ...) )

    // Create your enemies. Your enemy types have been defined in the
    // EnemyFactory, so it's only a matter of selecting one and placing it using
    // what you've previously defined.
    //
    // Note that we remove the positions once we've used it because we don't
    // want more than one enemy at the same spot
    Vec2d enemyPosition = potentialPositions.random();
    potentialPositions.erase( enemyPosition );
    enemies_.add(EnemyFactory.GenerateOne( enemyPosition );

    enemyPosition = potentialPositions.random();
    potentialPositions.erase( enemyPosition );
    enemies_.add(EnemyFactory.GenerateOne( enemyPosition );

    enemyPosition = potentialPositions.random();
    potentialPositions.erase( enemyPosition );
    enemies_.add(EnemyFactory.GenerateOne( enemyPosition );
    ...

  func Render():
    ...
    for enemy in enemies_:
      // The data you need is stored in your class instance
      game.batch.draw(enemy.sprite_,enemy.position_,enemy.size_);

    ...

```

---
Tags: java, libgdx
---


# Question
Title: Random value is chosen 2-3 times, then after that it's always 1
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[ExecuteAlways]
public class GenerateObjects : MonoBehaviour
{
    public GameObject objectPrefab;

    [Range(1, 100)]
    public int numberOfObjects = 1;
    public int maxDepth;
    [Range(1, 100)]
    public int posX = 1, posY = 1, posZ = 1;
    [Range(1, 100)]
    public int numberOfChildrenInLevel = 1;
    public bool randomNumberOfChildren = false;

    private GameObject parent;
    private int count = 0;
    private int oldNumberOfObjects;
    private int currentDepth;

    // Start is called before the first frame update
    void Start()
    {

        oldNumberOfObjects = numberOfObjects;

        parent = GameObject.Find("Generate Objects");

        StartCoroutine(SpawnObjects());
    }

    // Update is called once per frame
    void Update()
    {
        if (oldNumberOfObjects != numberOfObjects)
        {
            StartCoroutine(SpawnObjects());
            oldNumberOfObjects = numberOfObjects;
        }
        else
        {
            StopAllCoroutines();
        }
    }

    IEnumerator SpawnObjects()
    {
        while (true)
        {
            yield return new WaitForSeconds(0);

            if (objectPrefab != null)
            {
                GameObject go = InstantiateObjects(parent.transform);
                go.tag = "Instantiated Object";
                GenerateChildren(go);
            }

            count++;

            if (count == numberOfObjects)
            {
                StopAllCoroutines();
                break;
            }

            yield return null;
        }
    }

    GameObject child;
    private void GenerateChildren(GameObject go)
    {
        if (currentDepth < maxDepth)
        {
            if (randomNumberOfChildren)
            {
                int ggg = Random.Range(1, numberOfChildrenInLevel);
                numberOfChildrenInLevel = ggg;
            }
            for (int i = 0; i < numberOfChildrenInLevel; i++)
            {
                child = InstantiateObjects(null);
                child.transform.parent = go.transform;
            }

            currentDepth++;
            GenerateChildren(child);
        }
        else
        {
            currentDepth = 0;
        }
    }

    private GameObject InstantiateObjects(Transform parent)
    {
        return Instantiate(objectPrefab,
            new Vector3(Random.Range(0, posX), Random.Range(0, posY), Random.Range(0, posZ)),
            Quaternion.identity, parent);
    }

    public void ClearObjects()
    {
        GameObject[] instantiatedObjects = GameObject.FindGameObjectsWithTag("Instantiated Object");
        foreach (GameObject go in instantiatedObjects)
        {
            DestroyImmediate(go);
        }
    }
}

```

The problem is with the `numberOfChildrenInLevel` variable.

When the flag `randomNumberOfChildren` is true, I want to generate random numbers:

```
if (randomNumberOfChildren)
{
    int ggg = Random.Range(1, numberOfChildrenInLevel);
    numberOfChildrenInLevel = ggg;
}
for (int i = 0; i < numberOfChildrenInLevel; i++)

```

For example, I set the `numberOfChildrenInLevel` value to 41 in the inspector. It's picking a random number 2-3 times, then each time after that the picked number is 1, not random anymore. I see that the Range slider of the `numberOfChildrenInLevel` is moving in the inspector back to 1. I can't figure out why it's not generating more random numbers and why it's always generating the same value of 1?

# Answer
> 3 votes
The problem is these two lines:

```
int ggg = Random.Range(1, numberOfChildrenInLevel);
numberOfChildrenInLevel = ggg;

```

Each time you run your function, the range that your random amount should roll gets smaller and smaller. And at one point it is just 1. If you want to keep it between 1 and 99, you should not save the result in the same variable that is responsible for the maximum amount

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


title: Draw more sprite but they disappear

text:
# Question
Title: Draw more sprite but they disappear
I have a array of sprite in a class "Enemy", I want to draw enemies in some positions, but when I draw one, the previous one disappears.

```
public class Level1 implements Screen{

   Vector2 position;
   private Enemy enemies = new Enemy();

   public Level1 (NameGame game){
      this.game = game;

      position = new Vector2(300,100);
      enemies.nemici();

```

And this is my for loop:

```
    for (i=0;i<enemies.enemy.size;i++){
    //Maybe i need for (Sprite s : enemy)
        game.batch.draw(enemies.enemy.get(i),position.x,position.y,100,100);
    }

```

It's only a test to draw enemy, after i will try to draw in more position

If i change position.x and position.y every iteration, for example with position = new Vector2(..,..) after the "game.batch.draw", the previous enemy disappear, but why? How can i draw all?

And this is my enemy class:

```
package com.mygdx.game;

import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.utils.Array;

public class Enemy {
    public Array<Sprite> enemy = new Array<Sprite>(14);

public void nemici() {

    //Inizializzo e aggiungo i nemici all'array
    Sprite mysterio, boss, doctorstrange, electro, goblin, ironman, lizard, mj, ned, octopus, rhyno, sandman, scorpion, scorpion2, venom;
    enemy.add(mysterio = new Sprite(new Texture("mysterio.png")));
    enemy.add(boss = new Sprite(new Texture("boss.png")));
    enemy.add(doctorstrange = new Sprite(new Texture("doctorstrange.png")));
    enemy.add(electro = new Sprite(new Texture("electro.png")));
    enemy.add(goblin = new Sprite(new Texture("goblin.png")));
    enemy.add(ironman = new Sprite(new Texture("ironman.png")));
    enemy.add(lizard = new Sprite(new Texture("lizard.png")));
    enemy.add(mj = new Sprite(new Texture("mj.png")));
    enemy.add(ned = new Sprite(new Texture("ned.png")));
    enemy.add(octopus = new Sprite(new Texture("octopus.png")));
    enemy.add(rhyno = new Sprite(new Texture("rhyno.png")));
    enemy.add(sandman = new Sprite(new Texture("sandman.png")));
    enemy.add(scorpion = new Sprite(new Texture("scorpion.png")));
    enemy.add(scorpion2 = new Sprite(new Texture("scorpion2.png")));
    enemy.add(venom = new Sprite(new Texture("venom.png")));

}

```

}

# Answer
You have many enemy sprites, but only one position variable.

In your loop, you take turns to draw every sprite *at the same position*, so they stack up and you see only one.

You do not want an instance of the enemy class to have several sprites but no position, while the single enemy position is owned by the level. This makes no logical sense whatsoever.

What you want is that a level contains many enemies, and each enemy has one sprite and one position of its own.

```
public class Enemy {
    public Sprite sprite;
    public Vector2 position;

    public Enemy(Sprite sprite, Vector2 position) {
        this.sprite = sprite;
        this.position = position;
    }
}

public class Level1 implements Screen {

    private Array<Enemy> enemies;

    public void makeEnemies() {

        enemies = new Array<Enemy>(14);

        enemies.add(new Enemy(
               new Sprite(new Texture("mysterio.png")),
               new Vector2(100, 100)
        ));

        enemies.add(new Enemy(
               new Sprite(new Texture("boss.png")),
               new Vector2(200, 100)
        ));
        // ...
    }

```

Then your loop draws each enemy at *its own* position:

```
for (i=0;i < enemies.size; i++){
    Enemy enemy = enemies.get(i);
    game.batch.draw(
        enemy.sprite,
        enemy.position.x, enemy.position.y,
        100,              100
    );
}

```
> 1 votes

---
Tags: java, libgdx
---


title: Cloud based fog of war

text:
# Question
Title: Cloud based fog of war
I'm working on a Unity 3D game that requires fog of war. It is seen from above. I was looking for help and found this: (I dont know what game it is though)

This would perfectly fit my needs but I don't know how to do it. I created a grid of flat hexagons and tried applying shaders but the results are not satisfying. If we look at the image, we can see that the clouds are made of hexagons tiles too and the texture blend with the neighbouring tiles without seams.

My needs are:

* Clouds can be tiled so that I can remove them as the player explore the world
* Texture blends with it's neighbours
* Texture tiling is non-existant or not obvious
* Animated
* Opaque (I don't want the player to be able to see through it)

I'm literally trying to do the exact same thing as the GIF. For info, I'm using URP.

Any help or clues would be very appreciated.

**EDIT:** see Mangata comment for the solution

# Answer
> 1 votes
Thanks to Mangata for finding this tutorial. It was exactly what I was looking for.

Using a small hexagonal tile I made in blender, I followed the tutorial to create the shader in ShaderGraph. In game, when a unit explores the world, I shrink (and then remove it entirely) the tile above it. Works like a charm.

---
Tags: unity, unity-shader-graph, fog-of-war, unity-urp, clouds
---


# Question
Title: How to find the mathematical relationship between 2 variables?
I am trying to find an equation that semi-accurately describes the 1 psi blast range of a nuclear explosion given the yield. I am using Nukemap on nuclearsecrecy.com to find 1 psi blast range at different yields so I can establish a relationship.

```
Kilotons | 1 PSI blast range in meters
.0001 | 50
.0002 | 70
.0003 | 80
.0004 | 90
.0005 | 90
.0006 | 100
.0007 | 100
.0008 | 110
.0009 | 110
.001  | 120
.01   | 250
.1    | 550
1     | 1180
10    | 2530
100   | 5460
1000  |11800
10000 |25300
100000|54600

```

Can anyone help me establish the relationship between yield and blast radius given these numbers? I can see that blast radius increases roughly x10 when yield increases x1000

# Answer
> 2 votes
The same strategy I explained in this answer I showed you works here too.

Take your table of numbers and paste them into a spreadsheet. (I used Google Sheets for this example)

Select the two columns and graph them as a scatterplot. (Insert \> Chart)

Select the data series and add a trend line, and fiddle with the type setting until you get a good fit. (Here I found the Power Series looked solid)

Show the equation on the chart.

From the equation, we can see the best fit line is something around
`Range = 1172 * POWER(Kiloton, 0.334)`

That 0.334 is basically 1/3, which makes sense. If the volume of the blast scales linearly with the kiloton rating, then the radius of the blast will be the cube root. That's also suggested by your observation that range increases x 10 when the kiloton rating goes up x 1000.

We can round the formula's output to the nearest 10, or the nearest 100 for the last three items, and play with the coefficient in the vicinity of 1172 until our rounded values come out as close as possible to the originals.

In this case, I found
`Range = ROUND(1176 * POWER(Kiloton, 1/3))`
reproduced the original table exactly.

# Answer
> 0 votes
You can get a rough approximation by finding the closest pair of known values that bound your value of interest and use linear interpolation to find the intermediate value. For instance, if you want to estimate the PSI for .000275 kilotons the bounding pair from the kiloton column is .0002, .0003 and the bounding pair from the PSI column is 70, 80. Since the value of interest is 75% of the way between the known kiloton values, calculate the corresponding value that would be 75% of the way between the known PSI values. In this case the result is 77.5 PSI.

The advantages of this approach are that it:

* it's easy to code & debug
* allows you to refine your tables as desired (just plug in more values)
* gives exact answers for known values

The disadvantage of this approach are that it the output is only as smooth as your lookup tables.

Here's a sample implementation in C#:

```
static double kilotonsToPSI(double k)
{
    double[] kilotons = { .0001, .0002, .0003, .0004, .0005, .0006, .0007, .0008,
                          .0009, .001, .01, .1, 1, 10, 100, 1000, 10000, 100000 };
    double[] psi = { 50, 70, 80, 90, 90, 100, 100, 110, 110, 120, 250, 550,
                     1180, 2530, 5460, 11800, 25300, 54600 };
    if(k < kilotons[0])
    {
        return psi[0];
    }
    if(k >= kilotons[kilotons.Length - 1])
    {
        return psi[psi.Length - 1];
    }
    int index = 0;
    while(kilotons[index+1] < k)
    {
        index++;
    }

    double lowerK = kilotons[index];
    double upperK = kilotons[index + 1];
    double percentage = (k - lowerK) / (upperK - lowerK);

    double lowerPsi = psi[index];
    double upperPsi = psi[index + 1];
    double diffPsi = upperPsi - lowerPsi;

    return diffPsi * percentage + lowerPsi;
}

```

For large tables, consider loading the data from file rather than hardcoding the values.

---
Tags: mathematics
---


title: reposition object in circle

text:
# Question
Title: reposition object in circle
As you can see on the image, I have a p1 and p2 objects with (x,y) coordinates which I know the values, and I know radius of all these circle objects.

However, I want to calculate new position x,y which would be p3 center point. Basically, as you can see it's p2 position + radius.

I am doing this for java game which is based on libgdx. I would appreciate any math or java language directions/examples.

# Answer
> 2 votes
For circle `p2` and `p3` to be close enough to eachother to touch, we know that the distance between them must be `2 * rs` (where `rs` is the radius of the small circles).

If we then construct a triangle from the points `p1`, `p2` and `p3`, we can divide that triagle in the middle and know that the short side of the triangle is equal to `rs`

Using the sine rule we can then figure out the angle at the center of the big circle as we have a triangle where we know two of the sides (`r` and `rs`) and one angle (the 90 degree angle we get from splitting the triangle in half).

This angle times two is the angle between `p2` and `p3`

`angle = 2.0 * asin(rs / r)`

Since we can get the angle of a `Vector2` in **libGDX** it's then easy to find the angle of `p2` and then add the `angle` calculated above, as shown in this example where the green circle is moved around and the blue position is calculated using the above method:

Full source code for a **libGDX** example:

```
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;

public class SandboxGame extends Game {
    OrthographicCamera camera;
    ShapeRenderer shapeRenderer;

    @Override
    public void create () {
        float aspectRatio = (float)Gdx.graphics.getHeight()/(float)Gdx.graphics.getWidth();
        camera = new OrthographicCamera(10.0f, 10.0f * aspectRatio);
        camera.position.set(0, 0, 0);
        shapeRenderer = new ShapeRenderer();
    }

    float b;
    @Override
    public void render() {
        b += 32.0f * Gdx.graphics.getDeltaTime();
        Gdx.gl.glClearColor(0, 0, 0, 0);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        camera.update();
        shapeRenderer.setProjectionMatrix(camera.combined);
        shapeRenderer.begin(ShapeRenderer.ShapeType.Line);

        float r = 1.0f;
        float rs = 0.4f;
        Vector2 p1 = new Vector2(1, 0.5f);
        Vector2 p2 = new Vector2(r, 0).rotateDeg(b).add(p1);
        float angleToP2 = new Vector2(p2).sub(p1).angleRad();
        float angle = 2.0f * MathUtils.asin(rs / r);
        Vector2 p3 = new Vector2(r, 0).rotateRad(angleToP2 + angle).add(p1);

        shapeRenderer.setColor(Color.RED);
        shapeRenderer.circle(p1.x, p1.y, r, 32);
        shapeRenderer.setColor(Color.GREEN);
        shapeRenderer.circle(p2.x, p2.y, rs, 32);
        shapeRenderer.setColor(Color.BLUE);
        shapeRenderer.circle(p3.x, p3.y, rs, 32);
        shapeRenderer.end();
    }
}

```

---
Tags: java, libgdx, mathematics, trigonometry
---


# Question
Title: Calculate the coordinates of an offset in 3D space knowing the initial rotation and final rotation of the object
Working on a game mod in FiveM in which I am representing bullet impacts with drawn lines in the game world along their flight path. I am getting a normalized vector and then calculating the offset from the entity, and this works well for rigid-body entities like cars but for peds with skeletons not so much. I am trying to shift and attach the impact to the damaged entity bone, but am struggling to calculate the offset given the initial rotation/position, and then the current rotation/position. I looked at quaternions, and angle of rotation, but am not sure how to translate that into a function to calculate the final coord using the originally calculated offset.

Anyone able to point me in the direction of the math I need to solve this? Essentially I am just looking for the final 3D coords, and know I need some sort of advanced math (trig, quats, etc) to find it but am struggling to understand which solution I need.

I know I basically have the following:

initial rotation of entity bone, initial position of entity bone, initial offset from entity bone, initial coordinates of offset

and

final rotation of entity bone, final position of entity bone, and the offset I need to find the coords

and need to calculate

final coords of the offset

# Answer
The gist of it is that you need a matrix transformation for the bone. Well, two:

* The one at the moment you want at the time of impact, let us call it `A`.
* And the current one, let us call it `B`.

Now, let us say you have a point `p_a` in a reference coordinates system (whatever space you have the point defined it) at the time of impact. We convert it to the space of the bone (also at time of impact):

```
p = inverse(A) * p_a

```

Then we convert that back to the reference coordinate system, but using the other matrix, so we have the current position in the reference coordinate system:

```
p_b = B * p

```

---

It appears from what you say that each transformation is described as a combination of translations and rotations. So you could create the transformation matrix by making a translation matrix and a rotation matrix and multiplying them together.

---

I don't know how exactly it is setup in what you are working with (I do not understand what you say about offset), but I expect it to be something similar to a scene tree or scene graph.

If that is the case, each object has a transformation relative to its parent. For example, the bone has a transformation relative to its parent bone, and so on, until the parent is a game object or similar, which has a transformation relative to the root of the scene, which we call global or world coordinates.

Then, if you know the path from your reference coordinate system to the bone, you can make translation matrices and rotation matrices for the transformations, multiply them together in order, and that should give you the matrix you need.

---

Do not lose track of what is positioned relative to what. I also remind you that matrix multiplication is not commutative. That means that the order matters. Fortunately it is either one order or the reverse order, so if it is not working, try flipping the multiplication order.
> 0 votes

---
Tags: rotation, vector, coordinates
---


# Question
Title: Unity - Apply different Near/Far clip plane value for different layer
I am Lerping the Near value of my camera, from 0 to 38, and it gives this result: change near clip plane effect

As you see, it gives a nice effect. But now I would like the effect to occur only for one specific layer. How can I do that?

# Answer
Playing with Near/Far clip values by layers would basically mean to render every object using a different camera. Which would probably be overkill. I think what you're looking for is a custom shader on specific objects or group of objects that would "cut" them in given depth.

Please look at this very cool tutorial on how to achieve such an effect.
> 1 votes

# Answer
You can use Camera.layerCullDistances (https://docs.unity3d.com/ScriptReference/Camera-layerCullDistances.html) to control per layer farclip plane
> 0 votes

---
Tags: unity, camera, clipping, layers
---


# Question
Title: How to inherit from a custom node of a gdnative plugin, in gdnative?
## Context

I am developing a game in gdnative and I would like to design it in several "modules", where there would be:

* a main module for the core gameplay,
* a second module that I defined as a plugin

## Approach

In my plugin there is a custom node, which needs to have a `_process` method, defined according to the need, to be used in my core gameplay module, and in the game.

But if I understand correctly Godot doesn't allow this, because it is designed to be data and component oriented, i.e. I can't create subnodes from a custom node.
Also, since both modules are in gdnative, I'm not sure if the custom type I'm going to use for inheritance is recognized at compile time.

I should rather allow to add to my custom node, a "Behavior" component that would be created in the core gameplay module, to customize its `_process` method.

Is this the right way to do it?

# Answer
> 2 votes
At some level we could argue for Godot being data oriented (e.g. the code inside the "servers", such as `VisualServer` and so on), or we can argue that the scene tree is composition (well, aggregation), and thus the children `Node`s could be considered components. However, in general Godot is object oriented.

Scripts - and including GDNative scripts - extend classes, such as `Node` and derived classes. For that, those classes must be exposed for scripting. Which means they are registered in `ClassDB`.

In is in that last point that you will run into issues. You need to make sure the classes are registered in `ClassDB` so scripts - including GDNative scripts - can use them.

It is one of the limitations of the GDNative system that its classes do not get registered into `ClassDB`, which means other scripts cannot extend them. As a result there are things that cannot be done with GDNative, and must be done as modules. *This limitation does not stem from a philosophy against object oriented programming. In fact, GDExtension \- the replacement for GDNative in Godot 4.0 - addresses this limitation.*

**Note**: When I say "module" I mean modules added to Godot source code, for which you need to build Godot with them. So, when I say "module" I don't mean GDNative. See Custom modules in C++.

Thus, to answer the question on the title: You can't inherit from a custom node of a GDNative plugin, because they do not get registered into `ClassDB`. If you want to define classes that can be inherited in C++, you should create a module (and I reiterate that by "module" I mean module, and that they require to build Godot form source), or wait for Godot 4.0.

That does not mean different GDNative scripts cannot talk to each other. However, if you are going to use C++, but you are not going to build Godot form source, nor wait for Godot 4.0… You would want to workaround inheritance.

Consider using the scene tree. You could either:

* Have the GDNative node call a method on its children.
* Or, have another node intended to have the GDNative as child, and call methods on it.

---
Tags: c++, godot, inheritance
---