# Question
Title: What is the efficient way to sync TextureProgress with a Timer not in the UI?
I want to use a `TextureProgress` which reflects the state of a Timer.

I have tried to emit signals:

* FROM: the `Node2D._process()` which owns the Timer with `emit_signal("time_left_changed", timer.time_left)`
* TO: the UI

but it seems to make huge impact on performance.

# Answer
> 5 votes
I've been trying to figure out in what ways this can be a performance problem.

*I have been unable to replicate the problem. Yet, let us see what I can do.*

First a couple notes on what happens internally:

* Godot timer will internally use the equivalent of `_process` or `_physics_process` depending on `process_mode` and will update `time_left` using `delta`. Which means that, sadly, it does not leverage any OS timers.
* `TextureProgress` inherits from `Range`, and when you set its `value`, you just set its `value`. It is when Godot has to draw it, that it computes how to place the textures.

---

First, can we improve upon `TextureProgress`?

Perhaps using a shader to create a progress bar would be better, depending on the hardware. And my guess is that on hardware where that could be an improvement, is also hardware where it does not have a real impact on performance.

We could also consider using `TextureRect`s to mimic the `TextureProgress`. However, `TextureRect` works on a similar fashion than `TextureProgress` (in fact, its logic can be more complex given the different options for stretching textures). Thus, I do not think this is an improvement either.

We could try using `_draw`, but we would end up with the same design that `TextureProgress` uses, and if we are doing it in GDScript, it won't perform better.

I don't think using an `AnimatedTexture` would be worth it either.

---

Next, can we improve upon `Timer`?

Yes, we can. First stop is `Tween`. For example, you can do something like this:

```
var tween = Tween.new()
tween.interpolate_method(self, "push_time", 0, 100, 100)
add_child(tween)
tween.connect("tween_all_completed", tween, "queue_free")
tween.start()

```

Where `push_time` emits the signal. You could also use `interpolate_property` and change the `value` of the `TextureProgress` directly.

The problem is that this is still using `_process`, and you will see little to no performance improvement.

---

Let us do better. Instead of using the `time_left` of a `Timer`, you can use the `timeout`. That is, don't set the `wait_time` to the whole duration you want, instead set it to how much time must pass for one step of the `TextureProgress`. In fact, you can connect the `timeout` directly instead of using a custom signal.

You could either use `OS.get_ticks_usec` (or `OS.get_ticks_msec`) to keep track of the start time and compute the elapsed time. Or increment the `value` by one step.

Doing this you will see that the time expend on GDScript will be greatly reduced.

---

Can we do better?

As I said at the start, the `Timer` is updating `time_left` with `delta`, either on `_process` or `_physics_process`. If we are running those anyway, we don't need all the `Timer` logic. We only need to use `OS.get_ticks_usec` (or `OS.get_ticks_msec`) so we keep track of the start time and compute the elapsed time, and use that to set the `value`.

This is somewhat close to the logic you have to begin with, since you are using `time_left`. Except Godot is updating `time_left` all the time. Instead this compute it all the time.

I'm not sure this is really more performant or not. We need to get out of the clutches of `_process` and `_physics_process`.

---

I tried something else, which is not better… But we will improve upon this:

```
class_name Stopwatch extends Node
func get_class(): return "Stopwatch"
func is_class(type:String): return type == get_class() or .is_class(type)

const seconds_per_usec:float = 0.000001

enum STATE {STOPPED, PAUSED, RUNNING}

signal tick
signal state_changed

var _start_time:int # trash when not RUNNING
var _pause_time:int # trash when not PAUSED
var _accum_time:int

export(bool)var auto_start:bool setget set_auto_start
func set_auto_start(new_value) -> void:
    auto_start = new_value
    if new_value and !is_inside_tree():
        yield(self, "ready")
        set_state(STATE.RUNNING)

var elapsed_usec:int setget _noset, get_elapsed_usec
func get_elapsed_usec() -> int:
    var now:int = OS.get_ticks_usec()
    if state == STATE.RUNNING:
        return now - _start_time + _accum_time

    return _accum_time

var elapsed_seconds:float setget _noset, get_elapsed_seconds
func get_elapsed_seconds() -> float:
    return seconds_per_usec * get_elapsed_usec()

var elapsed_ticks:int setget _noset, get_elapsed_ticks
func get_elapsed_ticks() -> int:
    return int(ticks_per_second * seconds_per_usec * get_elapsed_usec())

func _noset(_new_value) -> void:
    push_error("readonly")

var state:int setget set_state
func set_state(new_value: int) -> void:
    if state == new_value:
        return

    var now:int = OS.get_ticks_usec()
    if state == STATE.RUNNING:
        _accum_time += now - _start_time
    elif state == STATE.STOPPED:
        _accum_time = 0

    state = new_value
    if state == STATE.RUNNING:
        _start_time = now
    elif state == STATE.PAUSED:
        _pause_time = now

    _update_process()
    emit_signal("state_changed")

export(float)var ticks_per_second:float setget set_ticks_per_second
func set_ticks_per_second(new_value) -> void:
    if ticks_per_second == new_value:
        return

    ticks_per_second = new_value
    _update_process()

func start():
    set_state(STATE.RUNNING)

func start_ticking(new_ticks_per_second:float):
    set_ticks_per_second(new_ticks_per_second)
    set_state(STATE.RUNNING)

func stop():
    set_state(STATE.STOPPED)

func pause():
    set_state(STATE.PAUSED)

func is_stopped() -> bool:
    return state == STATE.STOPPED

func is_paused() -> bool:
    return state == STATE.PAUSED

func is_running() -> bool:
    return state == STATE.RUNNING

var _seconds_to_next_tick:float

func compute_seconds_to_next_tick() -> float:
    assert(ticks_per_second > 0)
    assert(state == STATE.RUNNING)
    var now:int = OS.get_ticks_usec()
    var _elapsed_seconds:float = seconds_per_usec * (now - _start_time + _accum_time)
    return ((int(_elapsed_seconds * ticks_per_second) + 1) / ticks_per_second) - _elapsed_seconds

func _ready() -> void:
    _update_process()

func _update_process() -> void:
    var should_proccess = ticks_per_second > 0 and state == STATE.RUNNING
    if should_proccess:
        _seconds_to_next_tick = compute_seconds_to_next_tick()
    set_process(should_proccess)

func _process(delta:float) -> void:
    _seconds_to_next_tick -= delta
    if _seconds_to_next_tick < 0:
        emit_signal("tick")
        _seconds_to_next_tick = compute_seconds_to_next_tick()

```

That is an "Stopwatch" node. You will see a boolean `auto_start` and a float `ticks_per_second` in the inspector panel, which I hope are self descriptive.

The node also has a `state` property that can be `0 = stopped, 1 = paused, 2 = running`, plus some convenient method `start`, `start_ticking` (which is like `start` but lets you set `ticks_per_second` as a parameter), `pause` and `stop`, which manipulate `state` (you can also set `state` directly).

Two signals: `tick` and `state_changed`. The `tick` signal will happen according to `ticks_per_second` (set `ticks_per_second` to `0` or negative to disable the signal). The signal `state_changed`, as its name suggest, will happen when `state` changes. These signals have no parameters.

There are also `is_paused`, `is_stopped` and `is_running` methods, that simply query `state`.

Finally there are `elapsed_usec`, `elapsed_seconds`, and `elapsed_ticks` which tell you how much time in microseconds, seconds and ticks (according to the current value of `ticks_per_second`) has elapsed running (time paused does not count), respectively. Note: they are not erased when the state changes to stopped, instead they are erased when going from stopped to running. So you can stop and then read the values. It is a stopwatch!

As I said, I don't think this is better. However, it is here because can improve upon this. With a `Thread`:

```
class_name Stopwatch extends Node
func get_class(): return "Stopwatch"
func is_class(type:String): return type == "Stopwatch" or .is_class(type)

const seconds_per_usec:float = 0.000001
const usec_per_second:int = 1000000

enum STATE {STOPPED, PAUSED, RUNNING}

signal tick
signal state_changed

var _start_time:int # trash when not RUNNING
var _pause_time:int # trash when not PAUSED
var _accum_time:int

var _thread:Thread

export(bool)var auto_start:bool

var elapsed_usec:int setget _noset, get_elapsed_usec
func get_elapsed_usec() -> int:
    var now:int = OS.get_ticks_usec()
    if state == STATE.RUNNING:
        return now - _start_time + _accum_time

    return _accum_time

var elapsed_seconds:float setget _noset, get_elapsed_seconds
func get_elapsed_seconds() -> float:
    return seconds_per_usec * get_elapsed_usec()

var elapsed_ticks:int setget _noset, get_elapsed_ticks
func get_elapsed_ticks() -> int:
    return int(ticks_per_second * seconds_per_usec * get_elapsed_usec())

func _noset(_new_value) -> void:
    push_error("readonly")

var state:int setget set_state
func set_state(new_value: int) -> void:
    if state == new_value:
        return

    var now:int = OS.get_ticks_usec()
    if state == STATE.RUNNING:
        _accum_time += now - _start_time
    elif state == STATE.STOPPED:
        _accum_time = 0

    state = new_value
    if state == STATE.RUNNING:
        _start_time = now
    elif state == STATE.PAUSED:
        _pause_time = now

    _update_process()
    emit_signal("state_changed")

export(float)var ticks_per_second:float setget set_ticks_per_second
func set_ticks_per_second(new_value) -> void:
    if ticks_per_second == new_value:
        return

    ticks_per_second = new_value
    _update_process()

func start():
    set_state(STATE.RUNNING)

func start_ticking(new_ticks_per_second:float):
    set_ticks_per_second(new_ticks_per_second)
    set_state(STATE.RUNNING)

func stop():
    set_state(STATE.STOPPED)

func pause():
    set_state(STATE.PAUSED)

func is_stopped() -> bool:
    return state == STATE.STOPPED

func is_paused() -> bool:
    return state == STATE.PAUSED

func is_running() -> bool:
    return state == STATE.RUNNING

func _update_process() -> void:
    var should_proccess = ticks_per_second > 0 and state == STATE.RUNNING
    if should_proccess:
        if _thread == null:
            # there is no thread, make a new one
            _thread = Thread.new()
        elif _thread.is_active():
            # found a thread running, nothing to do
            return

        # we either created a new thread, or we are restarting an exitted one
        var err = _thread.start(self, "_thread_loop")
        if err != OK:
            push_error("Failed to start Thread.")

func _thread_loop(_userdata) -> void:
    while true:
        var now:int = OS.get_ticks_usec()
        var _elapsed_usecs:int = now - _start_time + _accum_time
        var target_usecs = int((usec_per_second * (int(seconds_per_usec * _elapsed_usecs * ticks_per_second) + 1) / ticks_per_second)) + _start_time - _accum_time
        while true:
            var delay = target_usecs - OS.get_ticks_usec()
            if delay < 0:
                break

            OS.delay_usec(delay)

        if ticks_per_second <= 0 or state != STATE.RUNNING:
            break

        emit_signal("tick")

    # this should solve a race condition
    # when _update_process found the thread running while it was exiting
    _thread.call_deferred("wait_to_finish") # so is_active is false
    call_deferred("_update_process")

func _enter_tree() -> void:
    # the stopwatch may start when entering the tree
    if auto_start:
        state = STATE.RUNNING

    # the thread may start when entering the tree
    # note that children might not be ready
    _update_process()

func _exit_tree():
    # the stopwatch will stop when exiting the tree
    state = STATE.STOPPED
    if _thread == null:
        return

```

The advantage here is that it will actually sleep. Unlike `Timer` and other solutions that will be running `_process` all the time, this code tries to have the `Thread` sleep as much as possible. *There will be some high value for `ticks_per_second` where the computation of how much to sleep actually takes too much time. Remember that the point of this is have the code run less often (and thus save CPU time), not more.*

---
Tags: godot, ui-design, gdscript
---


# Question
Title: Traversing an acyclic binary tree to construct paths from a given starting node, but the paths come out wrong
The tree is an acyclic binary tree. It's composed of node objects that have a list of connections to link objects (at most 3), and link objects that have a list of connections to node objects (always 2). I am trying to construct a list of possible paths to other nodes that can be reached given a fuel budget and a fuel cost on each link. What it is supposed to do is go through each non-backtracking connection of a node, and spawn a new route and thread to investigate that, leaving the current one to end at that node and thus create a list of routes to every node in the reachable area. When executed, the list of end destinations are valid but many of the paths that are constructed to get to them are wrong, going down other branches in the tree that are extraneous or entirely outside of the reachable area bounded by the fuel budget as well as jumping between nodes that aren't directly connected. There seems to be some pattern in the errors, when going down from the root of some branches of the tree the path goes down every offshoot in order first instead of going in a straight line, and when going up the tree the path tends to go further out and make triangle shapes, often landing somewhere other than the listed destination. I have already checked the link and node connections themselves to see if they are assigned properly, and they are. What am I getting wrong?

Route class definition

```
var origin:Node
var destination:Node
var totaldV:float
var totalt:float
var dVBudget:float
var tBudget:float
var tdVRatio:float
var links:Array
var nodes:Array

func duplicate_values(originator:Route):
    origin = originator.origin
    destination = originator.destination
    totaldV = originator.totaldV
    totalt = originator.totalt
    dVBudget = originator.dVBudget
    tBudget = originator.tBudget
    tdVRatio = originator.tdVRatio
    nodes = originator.nodes
    links = originator.links

func _init(originator_route):
    if originator_route != null:
        duplicate_values(originator_route)

```

Tree traversal algorithm

```
var routes:Array
onready var root = get_node("..")

func traverse(current_node:Node, previous_route:Route):
    if previous_route == null:                             # Starts off the recursion by providing an initial node
        previous_route = Route.new(null)
        previous_route.origin = current_node
        previous_route.nodes.append(previous_route.origin)
        previous_route.dVBudget = 2000
        previous_route.totaldV = 0
    for link in current_node.connections:
        if (previous_route.totaldV + link.dV < previous_route.dVBudget &&
        !IsBacktracking(previous_route, LinkDestination(link, current_node))):   # If there is enough fuel and the link isn't backtracking, go through it.
            var working_route:Route = Route.new(previous_route)    # Copy the previous route to make the new route
            routes.append(working_route)
            working_route.destination = LinkDestination(link, current_node)
            working_route.totaldV += link.dV
            working_route.totalt += link.t
            working_route.links.append(link)
            working_route.nodes.append(working_route.destination)
            traverse(working_route.destination, working_route)
    DisplayRoutes()
    root.get_parent().pathSelectionFlag = true   # UI control boolean

func IsBacktracking(route:Route, destinationNode:Node) -> bool:
    for nodeI in route.nodes:
        if (destinationNode == nodeI):
            return true
    return false

func LinkDestination(link:Node, originNode:Node) -> Node:    # Finds the node on the other side of a link
    for nodeI in link.connections:
        if (nodeI != originNode):
            return nodeI
    return originNode

```

# Answer
> 1 votes
When you do set the arrays, here:

```
func duplicate_values(originator:Route):
    origin = originator.origin
    destination = originator.destination
    totaldV = originator.totaldV
    totalt = originator.totalt
    dVBudget = originator.dVBudget
    tBudget = originator.tBudget
    tdVRatio = originator.tdVRatio
    nodes = originator.nodes # <- here
    links = originator.links # <- here

```

They are the same array, not a copy. For that you can use `Array.duplicate`. Which would be like this:

```
func duplicate_values(originator:Route):
    origin = originator.origin
    destination = originator.destination
    totaldV = originator.totaldV
    totalt = originator.totalt
    dVBudget = originator.dVBudget
    tBudget = originator.tBudget
    tdVRatio = originator.tdVRatio
    nodes = originator.nodes.duplicate()
    links = originator.links.duplicate()

```

---
Tags: path-finding, godot, tree, gdscript
---


# Question
Title: Is a game based on a specific cellular automation a copyright infringement?
If one creates a game which is based on some cellular automation algorithm like Conway's Game of Life or Langton's Ants would that be a copyright infringement?

Are such famous algorithms protected by intellectual property rights, or as long as they aren't mentioned by their official names, the actual effect they create is free to be used?

# Answer
> 2 votes
According to the official United States copyright website:

> Copyright does not protect facts, ideas, systems, or methods of operation, although it may protect the way these things are expressed.

An algorithm falls under this statement. It may protect the way the algorithm is expressed, the main example being code, but it cannot protect the algorithm itself, as an algorithm falls under being an idea, fact, system, or method of operation.

For more elaboration, according to the BBC:

> Copyright covering algorithms can only be applied once the programmer converts the algorithm into source code. The copyright of the source code can be used to protect that code from being copied, but will not prevent others from independently creating their own source code which does the same thing.

Based on what this says, you can definitely use any algorithm, but the code can't be a *direct* copy of the original source code if such code exists. It must be made by you, but it can still legally use the same basic algorithm.

---
Tags: legal, copyright, intellectual-property
---


# Question
Title: How do I prevent my game from being detected as a virus?
I developed my own game engine and I'll refer to it as a Software Development Kit (SDK) here, for making a specific type of game.

The SDK encapsulates low level DirectX APIs. It's written in C++ and compiled on its own using Visual Studio 2019 which generates a static library file.

Under the Visual Studio 2019 compiler/debugger with remote debugging tools, I can compile, link and deploy a debug sample application to another computer and continue my development activities.

However, when I copy all the graphics files and the executable to a standalone computer (running antivirus software) and then run my sample application, the antivirus software detects my application as a virus and will go so far as to delete it from my computer.

It does so before I get so far as to change video resolution. I am running Windows 10.

This is now of concern because I would like to use the sample to solicit friends and to gauge interest in collaborating with me on a small gaming project. The sample is simply a means to test artwork by seeing it animated, so that a graphic artist can work independently with his/her own tool. They would simply have the sample application and an artwork compiler as well.

I read in another post that is several years old entitled *“Conundrum with quality and virus reports: is our game releasable?“*, in which the author had similar issues.

In that post it was recommended that the antivirus vendors should be contacted, in *hopes* that the problem would be corrected before they released their product.

Is this really the best course of action? Does anyone know how my application got into the database used by the antivirus vendor? When I contacted the vendor the analyst whom I spoke with suggested to turn the antivirus software off.

I am trying to prevent the possibility of releasing something I worked hard at, only to have it be detected as a virus after release. Is this preventable and avoidable?

Windows Protected you PC Microsoft Defender SmartScreen prevented an unrecognized app from starting. Running this app might put your PC at risk

More Info.

App: Buzz.exe Publisher: Unknown Publisher

Run Anyway or Don't Run

I select Run Anyway

---

Down Load Insight Our information on this file is inconclusive. We recommend not using this file unless you know it is safe.

Very Few Users Fewer than 5 users in the NXXXXn Community have use this file.

Buzz.exe Downloaded from http://codeload.github.com/david-harding/

Very New

File was relead less than 1 week ago

Unproven

There is not enough information about this file to recommend it.

1. Stop this program from running.
2. Remove this file from the system (recommended).
3. Run this program anyway.

More details.

File Insight

1. Details a. Developers Not available b. Version Not Available c. Identified 2/11/2021 at 4:14:23 am d. Last used 2/11/2021 at 4:21:46 am e. Startup item No
2. Origin a. https://codeload.github.com/david-harding/sample/zip/main b. Downloaded file buzz from github.com c. File Created Buzz.exe

More Info Taked me to the AV web site to rate the binary

Click 3. Run this program anyway.

Program runs normally.

++++ I am now using only a release version of my sample executable and the original reported issue has not gone away. The problem is chronic. I am not able to unzip the file downloaded from GitHub on my development computer, the AV software removes the .exe file immediately. I have not done exhaustive testing with USB devices etc. The message above indicates that the file is not trusted.

I am going to digitally sign my sample file with a certificate that is trusted by a trust provider. If the certificate is not too expensive. I tested with a sample PFX, which is included in VS 2019.

I found the following article useful. https://docs.microsoft.com/en-us/dotnet/framework/tools/signtool-exe#sign If anyone has any suggestions on ordering a PFX cert, I would appreciate suggestions. It looks like that is what is needed here. I will report back when this issue is resolved. Thanks for everything so far.

# Answer
The short answer is that the issue I had originally reported with my game being detected as a virus is resolved. I obtained a code signing certificate, from a trusted root certificate authority. Not a PFX certificate, like I had originally thought was necessary. I am afraid I will not be going into too many specific details regarding my individual case. The reason for not being forthcoming is due to not having been granted permission to discuss the process by the vendors. And obtaining a code signing certificate may be different for individual cases and vendors. But I can say that the process took a few months. And not due to anyone or any organization not doing their part. The process just takes a few months. The most important part of the process is to be properly scrutinized to insure you are doing legitimate software development work. The basic steps I performed are as follows:

1. Secure a software reseller, for the purpose of obtaining a code signing certificate, NOT a PFX certificate that I would install on a web server. This took a lot of calling around. And my hat is off to the reseller that was willing to work with me, since I was not an established client, and the commission was probably not extremely high, given the duration. They will certainly get all my future business.
2. Establish a legitimate business.
3. Establish my business presence with a web site, and company email address.
4. Register my business with several well know business registers on the Internet.

For smaller game studios such as mine, I recommend you perform above steps 2,3, and 4 before 1. I am sure I caused confusion because I was asking the reseller for a PFX certificate but had described the problem statement as one in which I wanted to digitally sign binary files. In conclusion, now when I display the file properties of my windows binary by right clicking the file, I now have the all too familiar “Digital Signatures” tab, which indicates the file has been signed. Now I have a lot to read on securing my private key and token, essential security hygiene. Thank you to all who will go nameless, your truly awesome.
> 2 votes

---
Tags: directx, visual-studio, distribution
---


# Question
Title: Would making a satirical version of someone else's character get me sued?
Licensing the rights to a popular character is definitely a hard process. Rather than licensing the rights to (insert hero here), what if I were to make a satirical version of the IP owner's character(s) like *Spaceballs* did? What sort of legal trouble could I face for making a satirical rip-off of a character?

# Answer
Anyone can sue you for anything. The question is not just if you would have the legal standing to win, but also if you could afford to fight a lawsuit. Because defending against a copyright or trademark lawsuit is expensive, and you need to pay your lawyers up-front.

In some (not all) jurisdictions, "satire" is a possible fair-use exception from copyright. But that does not mean that every court will see your satire as satire, and not possibly as infringement at best or defamation at worst. So when you can not afford a good lawyer, then you should be very careful about using other people's IP in the hope that saying it's a satire will protect you.

By the way, when Mel Brooks made Spaceballs, he actually did negotiate with Lucas Film about how far he could go without them sending their lawyers after him. Part of that agreement was that there would be no merchandise for Spaceballs and that he would hire their subsidiary *Industrial Light & Magic* for the special effects.
> 1 votes

---
Tags: legal, copyright, character-development
---


# Question
Title: add random force and direction to rigidbodies every x seconds
i need to add a `windForce` to multiple `rigidbodies`, with random direction and random force every x lapse of time. I'm using `InvokeRepeating` to update the `windDirection` so that the rigidbodies can be pushed in a different direction every x seconds.

Here's the code:

```
void windRotate()
{
    windDirection.y = Random.Range(0, 360);
    transform.Rotate(windDirection * smooth);

    if (objectsInWind.Count > 0)
    {
        foreach (Rigidbody rigid in objectsInWind)
        {
            rigid.AddForce(windDirection * 10);
        }

    }
}

```

This way the rigidbodies don't receive any force. I guess the system does not recognize the `Vector3` Update of `windDirection`, so I need to recalculate it, bit I was not able. On the other hand if I use this:

```
rigid.AddForce(Vector3.Up* 10);

```

the rigidbodies moves but in one direction only, and it's not updated on the next `windDirection` change. I tried playing with the various Vector3 values (up, right etc..) and different force methods (`AddRelativeForce`) but nothing changed.

By using `Debug.Log(windDirection);` i know that `windDirection` is updating correctly ever 3 seconds, so it should also be updated in my methods when i apply the force, but id does not work.

Any suggestion? Thanks

# Answer
> 0 votes
It looks like you want something like this:

```
// This is an angle triplet, not a cartesian vector, so don't call it "direction".
// Also, since you're applying a relative rotation, you probably want your range
// to be symmetric about zero, so you rotate clockwise as often as counter-clockwise.
windAngle.y = Random.Range(-180, 180);

transform.Rotate(windAngle * smooth);

Quaternion windOrientation = Quaternion.Euler(windAngle);

// Now we've converted our angles to a cartesian vector pointing in that direction.
Vector3 windDirection = windOrientation * Vector3.forward;

foreach (Rigidbody rigid in objectsInWind)
{
     rigid.AddForce(windDirection * 10);
}

```

Or, if you want to use the direction your object is facing, you can get that easily with `transform.forward`:

```
foreach (Rigidbody rigid in objectsInWind)
{
     rigid.AddForce(transform.forward * 10);
}

```

---
Tags: unity, rigidbody
---


# Question
Title: Getting the point of intersection from this fast ray box intersection algorithm
I have seen lots of such algorithms that return a Boolean value, but I also need to get back the intersection point and ray length.

I am looking into this example, but I'm not sure how I can extract the point of intersection from it.

I did a small experiment in JS https://jsfiddle.net/j7htk96n/ . I assumed `tmin` is the needed distance (or intersection point parts), but doesn't seem so.

```
function intersection(b, r) {
    var t1 = (b.min[0] - r.origin[0])*r.dir_inv[0];
    var t2 = (b.max[0] - r.origin[0])*r.dir_inv[0];

    var tmin = Math.min(t1, t2);
    var tmax = Math.max(t1, t2);

    console.log(tmin);

    for (var i = 1; i < 3; ++i) {
        t1 = (b.min[i] - r.origin[i])*r.dir_inv[i];
        t2 = (b.max[i] - r.origin[i])*r.dir_inv[i];

        tmin = Math.max(tmin, Math.min(t1, t2));
        tmax = Math.min(tmax, Math.max(t1, t2));
        console.log(tmin);
    }

    return tmax > Math.max(tmin, 0.0);
}

var box = {
 min: [0,0,0],
 max: [5,5,5]
};

var ray = {
 origin: [-2,-2,0],
 dir_inv: [0.66667,0.33333,0.66667]
};

console.log(intersection(box, ray));
```

# Answer
> 1 votes
Let's update your function to return the time of intersection if there is one, or a negative value otherwise. This will treat rays that start inside the box as non-intersecting, but you can output `max(tmin, 0)` instead of `tmin` if you want to count the ray origin inside the box as an honorary intersection.

```
function intersection(b, r) {
    var t1 = (b.min[0] - r.origin[0])*r.dir_inv[0];
    var t2 = (b.max[0] - r.origin[0])*r.dir_inv[0];

    var tmin = Math.min(t1, t2);
    var tmax = Math.max(t1, t2);

    console.log(tmin);

    for (var i = 1; i < 3; ++i) {
        t1 = (b.min[i] - r.origin[i])*r.dir_inv[i];
        t2 = (b.max[i] - r.origin[i])*r.dir_inv[i];

        tmin = Math.max(tmin, Math.min(t1, t2));
        tmax = Math.min(tmax, Math.max(t1, t2));
        console.log(tmin);
    }

    return tmax > Math.max(tmin, 0.0) ? tmin : -1;
}

```

Then we can check for a hit and report the position like so:

```
var t = intersection(box, ray);

if (t >= 0) {
    var point = ray.origin.slice();
    for (var i = 0; i < 3; ++i) P
        point[i] += t / ray.dir_inv[i];
    }

    // TODO: do something with the intersection point.
}

```

If you store the non-inverted direction as part of your ray structure, then you can replace that `/ ray.dir_inv[i]` with `* ray.dir[i]` instead.

The distance along the ray where the hit occurred is `tmin` times the length of the direction vector. (So if you use a unit vector for your direction, then `tmin` is automatically the distance you need)

---
Tags: 3d, algorithm, geometry, raycasting, aabb
---


# Question
Title: Removing all destroyed objects from a list
I am a little confused on deleting objects in a List. I realise that clearing the list doesn't destroy the gameobject in Unity. Hence I have written this routine to destroy and remove:

```
//clear all block sprites away
for (int i = 0; i < blockSprites.Count; i++)
{
    Destroy(blockSprites[i]);
}
blockSprites.Clear();

```

But what if I only wanted to destroy *some* of the elements (a variable amount)?

In that scenario the List.Clear() function wouldn't work. Would I have to make another list of indexes in order to go through destroying and removing from the list in two sweeps. Or is there a better way?

# Answer
> 4 votes
Once a game object has been destroyed, it will compare as equal to null. So you can use `List<T>.RemoveAll()` to remove all the elements that compare as equal to null.

```
blockSprites.RemoveAll(s => s == null);

```

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


# Question
Title: How can I prevent the camera going out of bounds?
I've been working on a Mario Bros clone for the first level, trying to learn how to make games with `SpriteKit`.

I'm trying to use an `SKCameraNode` so that I can move the player along a bigger world. However, when moving the player to the left or the right, the camera that follows the player moves out of the bounds of the scene:

I've found answers at Stack Overflow using `SKConstraints`. However, the code is using a `WorldLayer` that I don't have and don't know what nodes to add to it. Furthermore, that code is from over 5 years ago, and I've found that most of the answers from back then are now easier to implement, just like what this site (where I took the code to implement the camera) says:

> In the good old days it used to take quite a bit of math to create the illusion that the player is moving around a bigger “world”. I’ve been playing around with SpriteKit recently and today I learned how easy it is to actually create that effect using the SKCameraNode.

```
import SpriteKit
import GameplayKit

class GameScene: SKScene {
    private var player = SKSpriteNode()
    private var bg = SKSpriteNode()
    private var leftArrow = SKSpriteNode()
    private var rightArrow = SKSpriteNode()
    private var floor = SKSpriteNode()
    private var isLeftTouched = false
    private var isRightTouched = false
    private var selectedNodes: [UITouch:SKSpriteNode] = [:]
    private var cam = SKCameraNode()

    override func didMove(to view: SKView) {
        self.camera = cam
        self.addChild(cam)
        self.physicsBody = SKPhysicsBody(edgeLoopFrom: self.frame)

        addBackground()
        addFloor()
        addPlayer(xOffset: 0, yOffset: 0)
        addControls()
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first! as UITouch
        let positionInScene = touch.location(in: self)
        let touchedNode = self.atPoint(positionInScene)

        for touch in touches {
            let location = touch.location(in:self)
            if let node = self.atPoint(location) as? SKSpriteNode {
                if let name = touchedNode.name {
                    selectedNodes[touch] = node
                    if name == "left" {
                        isLeftTouched = true
                    } else if name == "right" {
                        isRightTouched = true
                    }
                }
            }
        }

        if let name = touchedNode.name {
            if name == "left" {
                isLeftTouched = true
            } else if name == "right" {
                isRightTouched = true
            }
        }
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            if selectedNodes[touch] != nil {
                if selectedNodes[touch]?.name == "left" {
                    isLeftTouched = false
                } else if selectedNodes[touch]?.name == "right" {
                    isRightTouched = false
                }
                selectedNodes[touch] = nil
            }
        }
    }

    override func update(_ currentTime: TimeInterval) {
        // Called before each frame is rendered
        let x = player.position.x + (isRightTouched ? 5 : -5)
        let position = CGPoint(x: x, y: player.position.y)
        if position.x >= self.frame.maxX || position.x <= self.frame.minX {
            return
        }
        if isLeftTouched {
            runIn(direction: Direction.LEFT)
        }
        if isRightTouched {
            runIn(direction: Direction.RIGHT)
        }

        updateCameraPosition()
    }

    // MARK: INTERACTION METHODS

    func runIn(direction: Direction) {
        player.physicsBody?.applyImpulse(CGVector(dx: direction == Direction.RIGHT ? 2 : -2 ,
                                                  dy: 0))
    }

    func updateCameraPosition() {
        cam.position = CGPoint(x: player.position.x, y: self.frame.midY)
    }

    // MARK: UI METHODS

    func addBackground() {
        let bgTexture = SKTexture(imageNamed: "bg")
        //let floorTexture = SKTexture(imageNamed: "floor")

        bg = SKSpriteNode(texture: bgTexture)
        bg.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
        bg.size.height = self.frame.height
        bg.zPosition = -10

        self.addChild(bg)
    }

    func addFloor() {
        let floorTexture = SKTexture(imageNamed: "floor")
        floor = SKSpriteNode(texture: floorTexture)
        // Divide the height of the texture by 2 so it doesn't sink below the screen
        floor.position = CGPoint(x: self.frame.midX,
                                 y: self.frame.minY + floorTexture.size().height / 2)
        floor.zPosition = -9

        floor.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: floor.frame.width,
                                                              height: floor.frame.height))
        floor.physicsBody?.isDynamic = false

        self.addChild(floor)
    }

    func addPlayer(xOffset: CGFloat, yOffset: CGFloat) {
        let playerTexture = SKTexture(imageNamed: "player")

        player = SKSpriteNode(texture: playerTexture)
        player.position = CGPoint(x: self.frame.midX,
                                  y: self.frame.midY)

        player.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: player.frame.width, height: player.frame.height))
        player.physicsBody?.allowsRotation = false
        player.physicsBody?.isDynamic = true

        self.addChild(player)
    }

    func addControls() {
        addLeftArrow()
        addRightArrow()
    }

    func addLeftArrow() {
        let leftTexture = SKTexture(imageNamed: "left")
        leftArrow = SKSpriteNode(texture: leftTexture)

        leftArrow.name = "left"
        leftArrow.position = CGPoint(x: calculateXOffset(for: leftArrow, from: self.frame.minX, offset: 100),
                                     y: calculateXOffset(for: leftArrow, from: self.frame.minY, offset: 50))

        cam.addChild(leftArrow)
    }

    func addRightArrow() {
        let rightTexture = SKTexture(imageNamed: "right")
        rightArrow = SKSpriteNode(texture: rightTexture)

        rightArrow.name = "right"
        rightArrow.position = CGPoint(x: calculateXOffset(for: rightArrow, from: self.frame.minX, offset: 200),
                                      y: calculateXOffset(for: rightArrow, from: self.frame.minY, offset: 50))

        cam.addChild(rightArrow)
    }

    // MARK: UTILITY FUNCTIONS

    func calculateXOffset(for asset: SKSpriteNode, from coord: CGFloat, offset: CGFloat) -> CGFloat {
        let width = asset.frame.width

        return coord + offset + width;
    }

    func calculateYOffset(for asset: SKSpriteNode, from coord: CGFloat, offset: CGFloat) -> CGFloat {
        let height = asset.frame.height

        return coord + offset + height;
    }
}

```

Is there an easier way nowadays to deal with this problem? If so, what is it? If not, how could I implement this using constraints to my game?

# Answer
How about simply adding a condition in `updateCameraPosition`? You'll obviously need to define `leftBoundary` and `rightBoundary`, but you get the idea.

```
func updateCameraPosition() {
  if player.position.x > leftBoundary && player.position.x < rightBoundary {
      cam.position = CGPoint(x: player.position.x, y: self.frame.midY)
  }
}

```
> 1 votes

---
Tags: camera, ios, spritekit, swift
---


# Question
Title: How can I make the player smoothly rotate and return to a collider once it exits it?
When the player exits the collider area, it slows down then stops. At this point I want the player to start rotating and start moving back inside the colliding area.

The exit and the slow down are working but the rotation is not working and I'm not sure how to make him start moving again slowly to max speed when entering back.

The main goal is to prevent the player to leave the marked colliding area with some slow down and rotation.

This is my code:

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

public class PlayerSpaceshipAreaColliding : MonoBehaviour
{
    private float timeElapsed = 0;
    private float lerpDuration = 3;
    private float startValue = 1;
    private float endValue = 0;
    private float valueToLerp = 0;
    private Animator playerAnimator;
    private bool exitSpaceShipSurroundingArea = false;

    // Start is called before the first frame update
    void Start()
    {
        playerAnimator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        if (exitSpaceShipSurroundingArea)
        {
            SlowDown();

            if (playerAnimator.GetFloat("Forward") == 0)
            {
                transform.rotation = Quaternion.Inverse(transform.rotation);
            }
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.name == "CrashLandedShipUpDown")
        {
            exitSpaceShipSurroundingArea = false;
            Debug.Log("Entered Spaceship Area !");
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.name == "CrashLandedShipUpDown")
        {
            exitSpaceShipSurroundingArea = true;
            Debug.Log("Exited Spaceship Area !");
        }
    }

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

        valueToLerp = 0;
    }
}

```

For the rotation I did:

```
    transform.rotation = Quaternion.Inverse(transform.rotation);

```

but it keeps rotating non stop and not slowing smoothly like using Lerp.

# Answer
> 0 votes
You could try using the sine function to what I think you want. You could then attach a rotation lerp to smooth it out. Here is a script for what this would look like (you have to implement this):

```
Quaternion a;//the start
Quaternion b;//and end point.
float period = 2f;//amount of seconds to rotate back and forth.

void Update()
{
  float cycles = Time.time / period;
  float amplitude = Mathf.Sin(Mathf.PI * 2 * cycles);
  amplitude /= 2;
  amplitude += 0.5f;
  transform.rotation = Quaternion.Slerp(a, b, amplitude);
}

```

Basically, you get the amount of cycles after `period` seconds. Then, you get a value from -1 to 1 (changing based on cycles because our use of sine). We don’t want that because `Quaternion.Slerp` takes a value from 0 to 1 as its third argument, so we divide by two (to get a value from -0.5 to 0.5), then add 0.5 (to get a value from 0 to 1). We the use `Quaternion.Slerp` to rotate between both points based on this 0 to 1 value.

---

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


# Question
Title: Unity ECS: Is it bad to use variable data within SystemBase?
I'm currently trying to port a flight dynamics model that I've implemented in Rust to Unity. The original FDM utilized the Hecs ECS, and I plan on implementing this same model in Unity using the ECS framework provided by the engine.

The main issue I keep running into is how to access state data (a struct containing locations, velocities, and various other components like bank angle, throttle and flap) associated with my aircraft entity. In the rust version of this model, my main function begins by instantiating this state struct (among other variables) with the necessary starting values, and continues into an infinite loop (the "game" loop, so to speak) in which keyboard states are checked, the state struct is updated according to the various inputs, and the entity is updated with Rust's equivalent of a "ForEach" function.

However, when I create a system in Unity, the equivalent of the game loop seems to be the "OnUpdate" function. This becomes an issue because I need to be able to instantiate (and access) the state struct outside of the "ForEach" function. I thought about placing the instantiation of the state struct inside of a "Start" function, but that would require some sort of variable local to the class (which, from what I recall, is not ideal when creating a system, which shouldn't contain data, but rather the logic).

I guess what I'm trying to ask is this: is it a good idea (or even possible within a class that uses SystemBase, for that matter) to create a variable within the class itself (and not within a function, for instance) that can be used by both my "Start" and "OnUpdate" functions? If not, is there a workaround for this? Or, since the state struct is not attached to the actual entity (since the only data associated with the aircraft within the world is its translation data), and only serves to help in the helper functions for the equations of motion, would it be acceptable?

Thanks in advance! I'll include the code snippets of the rust implementation below. If I omitted anything important, I apologize. I've been trying to figure out how to explain this problem as concisely as I can, so I may have missed some important detail.

```
use std::{process, thread, time::Duration};
use gphys::palmer::fdm::{Properties, State, eom};
use hecs::*;
use console::Term;
use device_query::{DeviceQuery, DeviceState, Keycode};

#[derive(Debug)]
struct Position {
    x: i32,
    y: i32,
    z: i32
}

#[derive(Debug)]
struct Velocity {
    vx: i32,
    vy: i32,
    vz: i32
}

fn check_ranges(state: &mut State) {
    // throttle range bounds enforcement
    if state.throttle > 1.0  { state.throttle = 1.0; }
    if state.throttle < 0.0  { state.throttle = 0.0; }
    // angle of attack bounds enforcement
    if state.alpha > 20.0    { state.alpha = 20.0;   }
    if state.alpha < 0.0     { state.alpha = 0.0;    }
    // bank/roll angle bounds enforcement
    if state.bank > 20.0     { state.bank = 20.0;    }
    if state.bank < -20.0    { state.bank = -20.0;   }
    // flap deflection bounds enforcement
    if state.flap > 40.0     { state.flap = 40.0;    }
    if state.flap < 0.0      { state.flap = 0.0;     }
}

#[allow(dead_code)]
fn print_state(term: &Term, state: &State) {
    // velocity information
    let vx = state.q[0];
    let vy = state.q[2];
    let vz = state.q[4];
    // position information
    //let x = state.q[1];
    //let y = state.q[3];
    let z = state.q[5];

    let heading = vy.atan2(vx).to_degrees();
    let vh: f64 = (vx * vx + vy * vy).sqrt();
    let climb_angle = (vz / vh).atan().to_degrees();
    let air_speed = (vx * vx + vy * vy + vz * vz).sqrt();

    let s = format!("Throttle: {:>3.1}% | Angle of Attack: {:>3.1} deg | Bank Angle: {:>3.1} deg | Flap Deflection: {:>3.1} deg | Heading: {:>3.1} deg | Climb Angle: {:>3.1} deg | Air Speed: {:>3.1} | Climb Rate: {:>3.1} | Altitude: {:>3.1}",
                    (state.throttle * 100.0).round(),
                    state.alpha,
                    state.bank,
                    state.flap,
                    heading,
                    climb_angle,
                    air_speed,
                    vz,
                    z);

    term.clear_line().unwrap();
    term.write_str(&s).unwrap();
}

fn spawn_entity(world: &mut World, state: &State) {
    let pos = Position {
        x: state.q[1] as i32,
        y: state.q[3] as i32,
        z: state.q[5] as i32
    };
    let velocity = Velocity {
        vx: state.q[0] as i32,
        vy: state.q[2] as i32,
        vz: state.q[4] as i32
    };
    world.spawn((pos, velocity));
}

fn update_entity(world: &mut World, state: &State) {
    for (_id, (pos, velocity)) in &mut world.query::<(&mut Position, &mut Velocity)>() {
        // Update positions
        pos.x = state.q[1] as i32;
        pos.y = state.q[3] as i32;
        pos.z = state.q[5] as i32;
        // Update velocities
        velocity.vx = state.q[0] as i32;
        velocity.vy = state.q[2] as i32;
        velocity.vz = state.q[4] as i32;
    }
}

#[allow(dead_code)]
fn print_entity_debug_tool(term: &Term, world: &mut World) {
    // Function I used when testing this file to make sure that the entity is being written to properly.
    // Uncomment this function wherever it appears in the main loop to see the results.
    // Also recommended to comment out the fdm console term output to better see these results.
    // Doing so might generate a few "function is never used" errors for the omitted functions.
    for (id, (pos, velocity)) in &mut world.query::<(&Position, &Velocity)>() {
        let s = format!("Entity ID: {:?} ||  {:?} ||  {:?}",
                        id,
                        pos,
                        velocity);
        term.clear_line().unwrap();
        term.write_str(&s).unwrap();
    }
}

fn main() {
    // Cessna 172 properties
    let prop = Properties {
        wing_area: 16.2,
        wing_span: 10.9,
        tail_area: 2.0,
        cl_slope0: 0.0889,      // slope of Cl-alpha curve
        cl0: 0.178,             // intercept of Cl-alpha curve
        cl_slope1: -0.1,        // post-stall slope of Cl-alpha curve
        cl1: 3.2,               // post-stall intercept of Cl-alpha curve
        alpha_cl_max: 16.0,     // alpha when Cl=Clmax
        cdp: 0.034,             // parasite drag coefficient
        eff: 0.77,              // induced drag efficiency coefficient
        mass: 1114.0,
        engine_power: 119310.0,
        engine_rps: 40.0,       // revolutions per second
        prop_diameter: 1.905,
        a: 1.83,                //  propeller efficiency coefficient
        b: -1.32,               //  propeller efficiency coefficient
    };

    // simulation data (inputs/outputs)
    let mut state = State {
        time: 0.0,         // time
        q: [0.0; 6],       // ODE results
        bank: 0.0,         // roll angle
        alpha: 4.0,        // pitch angle
        throttle: 0.0,     // throttle percentage
        flap: 0.0,         // flap deflection
    };

    let mut world = World::new();
    spawn_entity(&mut world, &state);

    let device_state = DeviceState::new();
    let mut prev_keys = vec![];
let term = Term::stdout();
const FRAME_RATE : u64 = 60;           // hertz
const DT: f64 = 1.0/FRAME_RATE as f64; // seconds
loop {
    // compute equations of motion
    eom(&prop, &mut state, DT);
    // Comment out this print function if "print_entity_debug_tool" is uncommented below for better readability
    print_state(&term, &state);

    // Update entity after eom
    update_entity(&mut world, &state);

    // Considered adding an "update_entity()" function call here, but figured just one call after the range check should be necessary

    // update state
    let keys = device_state.get_keys();
    if keys != prev_keys {
        if keys.contains(&Keycode::E) {
            state.throttle += 0.1;
        } else if keys.contains(&Keycode::D) {
            state.throttle -= 0.1;
        } else if keys.contains(&Keycode::Up) {
            state.alpha += 1.0;
        } else if keys.contains(&Keycode::Down) {
            state.alpha -= 1.0;
        } else if keys.contains(&Keycode::Left) {
            state.bank -= 1.0;
        } else if keys.contains(&Keycode::Right) {
            state.bank += 1.0;
        } else if keys.contains(&Keycode::L) {
            state.flap -= 1.0;
        } else if keys.contains(&Keycode::K) {
            state.flap += 1.0;
        } else if keys.contains(&Keycode::Q) {
            process::exit(0);
        }
        check_ranges(&mut state);
    }
    // Update entity after range check to ensure entity is also within bounds
    update_entity(&mut world, &state);

    // Remove the commented-out function to show entity values being written to
    //print_entity_debug_tool(&term, &mut world);

    prev_keys = keys;
    thread::sleep(Duration::from_millis((DT*100.0) as u64));
}
}

```

And here's the function containing the equation of motion helper functions:

```
use std::f64::consts::PI;
static G: f64 = -9.81;

#[derive(Debug, Default)]
pub struct Properties
{
    pub wing_area: f64,
    pub wing_span: f64,
    pub tail_area: f64,
    pub cl_slope0: f64,      // slope of Cl-alpha curve
    pub cl0: f64,            // intercept of Cl-alpha curve
    pub cl_slope1: f64,      // post-stall slope of Cl-alpha curve
    pub cl1: f64,            // post-stall intercept of Cl-alpha curve
    pub alpha_cl_max: f64,   // alpha when Cl=Clmax
    pub cdp: f64,            // parasite drag coefficient
    pub eff: f64,            // induced drag efficiency coefficient
    pub mass: f64,
    pub engine_power: f64,
    pub engine_rps: f64,     // revolutions per second
    pub prop_diameter: f64,
    pub a: f64,              //  propeller efficiency coefficient
    pub b: f64,              //  propeller efficiency coefficient
}

#[derive(Debug, Default)]
pub struct State
{
    pub time: f64,         // time
    pub q: [f64; 6],       // ODE results

    pub bank: f64,         // roll angle
    pub alpha: f64,        // pitch angle
    pub throttle: f64,     // throttle percentage
    pub flap: f64,         // flap deflection
}

//-----------------------------------------------------
// calculates the forces associated with an aircraft
// given a set of properties and current state
//-----------------------------------------------------
fn plane_rhs(prop: &Properties, state: &State,
             q: &[f64; 6], delta_q: &[f64; 6],
             dt: f64, q_scale: f64,
             dq: &mut [f64; 6])
{
    // property convenience variables
    let wing_area = prop.wing_area;
    let wing_span = prop.wing_span;
//    let tail_area = plane.tail_area;
    let cl_slope0 = prop.cl_slope0;
    let cl0 = prop.cl0;
    let cl_slope1 = prop.cl_slope1;
    let cl1 = prop.cl1;
    let alpha_cl_max = prop.alpha_cl_max;
    let cdp = prop.cdp;
    let eff = prop.eff;
    let mass = prop.mass;
    let engine_power = prop.engine_power;
    let engine_rps = prop.engine_rps;
    let prop_diameter = prop.prop_diameter;
    let a = prop.a;
    let b = prop.b;

    // state convenience variables
    let alpha = state.alpha;
    let throttle = state.throttle;
    let flap = state.flap;

    // convert bank angle from degrees to radians
    // angle of attack is not converted because the
    // Cl-alpha curve is defined in terms of degrees
    let bank = state.bank.to_radians();

    // compute the intermediate values of the dependent variables
    let mut new_q : [f64; 6] = [0.0; 6];
    for i in 0..6 {
        new_q[i] = q[i] + q_scale * delta_q[i];
    }

    // assign convenenience variables to the intermediate
    // values of the locations and velocities
    let vx: f64 = new_q[0];
    let vy: f64 = new_q[2];
    let vz: f64 = new_q[4];
    let _x: f64 = new_q[1];
    let _y: f64 = new_q[3];
    let z: f64 = new_q[5];
    let vh: f64 = (vx * vx + vy * vy).sqrt();
    let vtotal: f64 = (vx * vx + vy * vy + vz * vz).sqrt();

    // compute the air density
    let temperature: f64 = 288.15 - 0.0065 * z;
    let grp: f64 = 1.0 - 0.0065 * z / 288.15;
    let pressure: f64 = 101325.0 * (grp.powf(5.25));
    let density: f64 = 0.00348 * pressure / temperature;

    // compute power drop-off factor
    let omega: f64 = density / 1.225;
    let factor: f64 = (omega - 0.12)/  0.88;

    // compute thrust
    let advance_ratio: f64 = vtotal / (engine_rps * prop_diameter);
    let thrust: f64 = throttle * factor * engine_power * (a + b * advance_ratio * advance_ratio) / (engine_rps * prop_diameter);

    // compute lift coefficient - the Cl curve is modeled using two straight lines
    let mut cl: f64;
    if alpha < alpha_cl_max {
        cl = cl_slope0 * alpha + cl0;
    } else {
        cl = cl_slope1 * alpha + cl1;
    }

    // include effects of flaps and ground effects
    // -- ground effects are present if the plane is within 5 meters of the ground
    if flap == 20.0 {
        cl += 0.25;
    }
    if flap == 40.0 {
        cl += 0.5;
    }
    if z < 5.0 {
        cl += 0.25;
    }

    // compute lift
    let lift: f64 = 0.5 * cl * density * vtotal * vtotal * wing_area;

    // compute drag coefficient
    let aspect_ratio: f64 = wing_span * wing_span / wing_area;
    let cd = cdp + cl * cl / (PI * aspect_ratio * eff);

    // compute drag force
    let drag: f64 = 0.5 * cd * density * vtotal * vtotal * wing_area;

    // define some shorthand convenience variables for use with the rotation matrix
    // compute the sine and cosines of the climb angle, bank angle, and heading angle

    let cos_w: f64 = bank.cos();
    let sin_w: f64 = bank.sin();

    let cos_p: f64;   //  climb angle
    let sin_p: f64;   //  climb angle
    let cos_t: f64;   //  heading angle
    let sin_t: f64;   //  heading angle
    if vtotal == 0.0 {
        cos_p = 1.0;
        sin_p = 0.0;
    } else {
        cos_p = vh / vtotal;
        sin_p = vz / vtotal;
    }

    if vh == 0.0 {
        cos_t = 1.0;
        sin_t = 0.0;
    } else {
        cos_t = vx / vh;
        sin_t = vy / vh;
    }

    // convert the thrust, drag, and lift forces into x-, y-, and z-components using the rotation matrix
    let fx: f64 = cos_t * cos_p * (thrust - drag) + (sin_t * sin_w - cos_t * sin_p * cos_w) * lift;
    let fy: f64 = sin_t * cos_p * (thrust - drag) + (-cos_t * sin_w - sin_t * sin_p * cos_w) * lift;
    let mut fz: f64 = sin_p * (thrust - drag) + cos_p * cos_w * lift;

    // add the gravity force to the z-direction force.
    fz = fz + mass * G;

    // since the plane can't sink into the ground, if the altitude is less than or equal to zero and the z-component
    // of force is less than zero, set the z-force to be zero
    if z <= 0.0 && fz <= 0.0 {
        fz = 0.0;
    }

    // load the right-hand sides of the ODE's
    dq[0] = dt * (fx / mass);
    dq[1] = dt * vx;
    dq[2] = dt * (fy / mass);
    dq[3] = dt * vy;
    dq[4] = dt * (fz / mass);
    dq[5] = dt * vz;
}

//-----------------------------------------------------
// solves the equations of motion using the Runge-Kutta
// integration method
//-----------------------------------------------------
pub fn eom(prop: &Properties, state: &mut State, dt: f64)
{
    let mut q : [f64; 6] = [0.0; 6];
    let mut dq1 : [f64; 6] = [0.0; 6];
    let mut dq2 : [f64; 6] = [0.0; 6];
    let mut dq3 : [f64; 6] = [0.0; 6];
    let mut dq4 : [f64; 6] = [0.0; 6];

    // retrieve the current values of the dependent and independent variables
    for i in 0..6 {
        q[i] = state.q[i];
    }

    // compute the four Runge-Kutta steps, then return
    // value of planeRightHandSide method is an array
    // of delta-q values for each of the four steps
    plane_rhs(&prop, &state, &q, &q, dt, 0.0, &mut dq1);
    plane_rhs(&prop, &state, &q, &dq1, dt, 0.5, &mut dq2);
    plane_rhs(&prop, &state, &q, &dq2, dt, 0.5, &mut dq3);
    plane_rhs(&prop, &state, &q, &dq3, dt, 1.0, &mut dq4);

    // update simulation time
    state.time += dt;

    // update the dependent and independent variable values
    // at the new dependent variable location and store the
    // values in the ODE object arrays
    for i in 0..6 {
        q[i] = q[i] + (dq1[i] + 2.0 * dq2[i] + 2.0 * dq3[i] + dq4[i]) / 6.0;
        state.q[i] = q[i];
    }
}

```

# Answer
> 0 votes
Just adding an answer based on the little bit of digging I've been doing. It seems that it's normal practice to have helper functions and monobehaviors in a Unity ECS-based game. For instance, the GameManager monobehavior I used to set up my scene is one such acceptable method. Helper functions like the script I made to handle the Runge-Kutta integration methods for motion are also acceptable to have within a Unity ECS project.

---
Tags: unity, entity-component-system, rust
---


# Question
Title: Using UPawnMovementComponent to control a Pawn with Keyboard sharing code between Pawns
I've just started to learn Unreal and reading the tutorial Components and Collisions I have found that they use the `UPawnMovementComponent` to control their `Pawn`.

Before reading this tutorial I have added the code to move the Pawn inside its C++ code:

```
#include "Paddle.h"
#include "Components/BoxComponent.h"
#include "Components/StaticMeshComponent.h"

// Sets default values
APaddle::APaddle()
{
    // Set this pawn to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;

    // Set this pawn to be controlled by the lowest-numbered player
    AutoPossessPlayer = EAutoReceiveInput::Player0;

    VisualComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("VisualComp"));
    RootComponent = VisualComponent;

    // Removed for brevety

    CurrentVelocity.Z = 0.0f;

}

// Called when the game starts or when spawned
void APaddle::BeginPlay()
{
    Super::BeginPlay();

}

// Called every frame
void APaddle::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);

    // Handle movement based on our "MoveZ" axis.
    if (!CurrentVelocity.IsZero())
    {
        const FVector NewLocation = GetActorLocation() + (CurrentVelocity * DeltaTime);
        SetActorLocation(NewLocation);
    }

}

// Called to bind functionality to input
void APaddle::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
    Super::SetupPlayerInputComponent(PlayerInputComponent);

    // Respond every frame to the values of our movement.
    InputComponent->BindAxis(TEXT("MovePaddle"), this, &APaddle::Move_ZAxis);
}

void APaddle::Move_ZAxis(float AxisValue)
{
    CurrentVelocity.Z = FMath::Clamp(AxisValue, -1.0f, 1.0f) * 100.0f;
}

```

A **Tip** from that tutorial says:

*Pawn Movement Components have some powerful, built-in features to help with common physics functionality, and are **a good way to share movement code between many Pawn** types. Using Components to **separate functionality is a good practice to reduce clutter** as your project grows and your Pawns become more complex.*

They say that using `Pawn Movement Components` is a good way to share movement code between many Pawn but they have the same code than me inside their Pawn component:

```
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.

#include "CollidingPawn.h"
#include "CollidingPawnMovementComponent.h"
#include "UObject/ConstructorHelpers.h"
#include "Particles/ParticleSystemComponent.h"
#include "Components/SphereComponent.h"
#include "Camera/CameraComponent.h"
#include "GameFramework/SpringArmComponent.h"

// Sets default values
ACollidingPawn::ACollidingPawn()
{
    // Set this pawn to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;

    // Removed for brevety

    // Take control of the default player
    AutoPossessPlayer = EAutoReceiveInput::Player0;

    // Create an instance of our movement component, and tell it to update our root component.
    OurMovementComponent = CreateDefaultSubobject<UCollidingPawnMovementComponent>(TEXT("CustomMovementComponent"));
    OurMovementComponent->UpdatedComponent = RootComponent;
}

// Called when the game starts or when spawned
void ACollidingPawn::BeginPlay()
{
    Super::BeginPlay();

}

// Called every frame
void ACollidingPawn::Tick( float DeltaTime )
{
    Super::Tick( DeltaTime );

}

// Called to bind functionality to input
void ACollidingPawn::SetupPlayerInputComponent(class UInputComponent* InInputComponent)
{
    Super::SetupPlayerInputComponent(InInputComponent);

    InInputComponent->BindAction("ParticleToggle", IE_Pressed, this, &ACollidingPawn::ParticleToggle);

    InInputComponent->BindAxis("MoveForward", this, &ACollidingPawn::MoveForward);
    InInputComponent->BindAxis("MoveRight", this, &ACollidingPawn::MoveRight);
    InInputComponent->BindAxis("Turn", this, &ACollidingPawn::Turn);
}

UPawnMovementComponent* ACollidingPawn::GetMovementComponent() const
{
    return OurMovementComponent;
}

void ACollidingPawn::MoveForward(float AxisValue)
{
    if (OurMovementComponent && (OurMovementComponent->UpdatedComponent == RootComponent))
    {
        OurMovementComponent->AddInputVector(GetActorForwardVector() * AxisValue);
    }
}

void ACollidingPawn::MoveRight(float AxisValue)
{
    if (OurMovementComponent && (OurMovementComponent->UpdatedComponent == RootComponent))
    {
        OurMovementComponent->AddInputVector(GetActorRightVector() * AxisValue);
    }
}

void ACollidingPawn::Turn(float AxisValue)
{
    FRotator NewRotation = GetActorRotation();
    NewRotation.Yaw += AxisValue;
    SetActorRotation(NewRotation);
}

void ACollidingPawn::ParticleToggle()
{
    if (OurParticleSystem && OurParticleSystem->Template)
    {
        OurParticleSystem->ToggleActive();
    }
}

```

They have the same `SetupPlayerInputComponent` method and also three methods to move the Pawn inside the Pawn class. I don't know how they are going to share move code between Pawn if the code is inside each Pawn and how we can separate functionality if all the movement code is inside the Pawns.

How can I use `UPawnMovementComponent` to control a Pawn with Keyboard sharing that code with other Pawns?

# Answer
> 0 votes
A UPawnMovementComponent is a class, from which you create your own custom movement component. You can't call it directly to move anything.

What this means is you can assign that custom movement component you made to as many actors as you want and have them move them.

---
Tags: c++, movement, unreal-4, keyboard
---


# Question
Title: RunUAT Error: Automation was unable to run successfully (unreal engine 4.26.2)
I have completed my setup in Mac OS and configured all android dependencies like SDK, NDK, and JDK. but whenever I tried to package my project it shows an error I tried with a completed fresh project but the result is the same

LogMainFrame: Selected target: MyProject
LogLauncherProfile: Unable to use promoted target - ../../../../../Documents/Unreal Projects/MyProject/Binaries/Android/MyProject-Android-Shipping.target does not exist.
UATHelper: Packaging (Android (Multi:ASTC,DXT,ETC2)): Running AutomationTool...
UATHelper: Packaging (Android (Multi:ASTC,DXT,ETC2)): Running bundled mono, version: Mono JIT compiler version 5.16.0.220 (2018-06/bb3ae37d71a Fri Nov 16 17:12:11 EST 2018)
UATHelper: Packaging (Android (Multi:ASTC,DXT,ETC2)): Start UAT: mono AutomationTool.exe -ScriptsForProject=/Users/aakash/Documents/Unreal Projects/MyProject/MyProject.uproject BuildCookRun -nocompileeditor -installed -nop4 -project=/Users/aakash/Documents/Unreal Projects/MyProject/MyProject.uproject -cook -stage -archive -archivedirectory=/Users/aakash/Docu
ments/Unreal Projects/MyProject -package -ue4exe=/Users/aakash/unreal/UE_4.26/Engine/Binaries/Mac/UE4Editor.app/Contents/MacOS/UE4Editor -ddc=InstalledDerivedDataBackendGraph -pak -prereqs -nodebuginfo -targetplatform=Android -cookflavor=Multi -build -target=MyProject -clientconfig=Shipping -utf8output
UATHelper: Packaging (Android (Multi:ASTC,DXT,ETC2)): Parsing command line: -ScriptsForProject="/Users/aakash/Documents/Unreal Projects/MyProject/MyProject.uproject" BuildCookRun -nocompileeditor -installed -nop4 -project="/Users/aakash/Documents/Unreal Projects/MyProject/MyProject.uproject" -cook -stage -archive -archivedirectory="/Users/aakash/Documents/Un
real Projects/MyProject" -package -ue4exe=/Users/aakash/unreal/UE_4.26/Engine/Binaries/Mac/UE4Editor.app/Contents/MacOS/UE4Editor -ddc=InstalledDerivedDataBackendGraph -pak -prereqs -nodebuginfo -targetplatform=Android -cookflavor=Multi -build -target=MyProject -clientconfig=Shipping -utf8output
UATHelper: Packaging (Android (Multi:ASTC,DXT,ETC2)): Using xbuild. Install Mono 5.0 or greater for faster builds!
UATHelper: Packaging (Android (Multi:ASTC,DXT,ETC2)): Setting up ProjectParams for /Users/aakash/Documents/Unreal Projects/MyProject/MyProject.uproject
UATHelper: Packaging (Android (Multi:ASTC,DXT,ETC2)): ********** BUILD COMMAND STARTED **********
UATHelper: Packaging (Android (Multi:ASTC,DXT,ETC2)): Running: mono "/Users/aakash/unreal/UE_4.26/Engine/Binaries/DotNET/UnrealBuildTool.exe" MyProject Android Shipping -Project="/Users/aakash/Documents/Unreal Projects/MyProject/MyProject.uproject"  "/Users/aakash/Documents/Unreal Projects/MyProject/MyProject.uproject" -NoUBTMakefiles  -remoteini="/Users/aak
ash/Documents/Unreal Projects/MyProject" -skipdeploy -Manifest="/Users/aakash/Documents/Unreal Projects/MyProject/Intermediate/Build/Manifest.xml" -NoHotReload -log="/Users/aakash/Library/Logs/Unreal Engine/LocalBuildLogs/UBT-MyProject-Android-Shipping.txt"
UATHelper: Packaging (Android (Multi:ASTC,DXT,ETC2)):   PLATFORM_ANDROID_NDK_VERSION = 220200
UATHelper: Packaging (Android (Multi:ASTC,DXT,ETC2)):   NDK toolchain: r22b, NDK version: 22, GccVersion: 4.9, ClangVersion: 11.0.5
UATHelper: Packaging (Android (Multi:ASTC,DXT,ETC2)):   Parsing headers for MyProject
UATHelper: Packaging (Android (Multi:ASTC,DXT,ETC2)):     Running UnrealHeaderTool "/Users/aakash/Documents/Unreal Projects/MyProject/MyProject.uproject" "/Users/aakash/Documents/Unreal Projects/MyProject/Intermediate/Build/Android/MyProject/Shipping/MyProject.uhtmanifest" -LogCmds="loginit warning, logexit warning, logdatabase error" -Unattended -WarningsAs
Errors -abslog="/Users/aakash/Library/Logs/Unreal Engine/LocalBuildLogs/UHT-MyProject-Android-Shipping.txt" -installed
UATHelper: Packaging (Android (Multi:ASTC,DXT,ETC2)):   Reflection code generated for MyProject in 17.2330787 seconds
UATHelper: Packaging (Android (Multi:ASTC, DXT,ETC2)):   Compiling Native 32-bit code with NDK API 'android-22'
UATHelper: Packaging (Android (Multi:ASTC,DXT,ETC2)):   Writing manifest to /Users/aakash/Documents/Unreal Projects/MyProject/Intermediate/Build/Manifest.xml
UATHelper: Packaging (Android (Multi: ASTC, DXT, ETC2)):   Building MyProject...
UATHelper: Packaging (Android (Multi:ASTC,DXT,ETC2)):   Performing 7 actions (8 in parallel)
UATHelper: Packaging (Android (Multi:ASTC,DXT,ETC2)):   [1/7] clang++ SharedPCH.Engine.ShadowErrors.h [armv7]
UATHelper: Packaging (Android (Multi:ASTC,DXT,ETC2)): Took 106.882652s to run mono, ExitCode=6
UATHelper: Packaging (Android (Multi:ASTC,DXT,ETC2)): UnrealBuildTool failed. See log for more details. (/Users/aakash/Library/Logs/Unreal Engine/LocalBuildLogs/UBT-MyProject-Android-Shipping.txt)
UATHelper: Packaging (Android (Multi:ASTC,DXT,ETC2)): AutomationTool exiting with ExitCode=6 (6)
UATHelper: Packaging (Android (Multi: ASTC, DXT, ETC2)): RunUAT ERROR: AutomationTool was unable to run successfully.
PackagingResults: Error: AutomationTool was unable to run successfully.
PackagingResults: Error: Unknown Error
LogSlate: Window 'Output Log' being destroyed
LogSlate: Window 'Output Log' being destroyed
LogSlate: Window 'Project Settings' being destroyed```

# Answer
It was mac OS issue It is restricting the execution of the clang++ file

I resolved it by the following process

1. cancel the warning
2. got to **system preferences** \>\> **Security & Privacy**
3. here you will find the **general** tab
4. here you can see the list of restricted files. Allow the **clang++** file
5. go back and try to package again
> 1 votes

---
Tags: android, unreal-4, unreal, build-process
---


# Question
Title: Rotating 3D Object Towards Swipe Direction
I have a character that has a constant speed, and I want to be able to change its direction with swipe gestures, The exact same mechanism implemented here.

I managed to do that for movement only, without taking into account the rotation, but I want to create this mechanism in such way that the rigidbody will have constant force in the `transform.forward` direction, and the Y rotation will change according to the swipe gestures, so the character will always move forward in local space, but will face towards different direction according to the assigned rotation.

I couldn't find a proper way of finding the desired rotation by the swipe direction.

How can I achieve this logic?

# Answer
> 1 votes
I found a solution using `Quaternion.LookRotation()` \- I used it to translate the swipe gesture to a Vector3 that is representing the direction. I used this code inside the `Update()` method to retrieve the user's input:

```
            if (Input.touchCount > 0)
            {
                currDirectionX = Input.touches[0].deltaPosition.x;
                currDirectionZ = Input.touches[0].deltaPosition.y;
            }
            moveDirection = new Vector3(currDirectionX, 0f, currDirectionZ).normalized;

```

and this code inside the `FixedUpdate()` method to rotate towards the desired rotation, while constantly moving forward in local space:

```
    Quaternion targetRot = Quaternion.LookRotation(moveDirection);
    this.transform.rotation = Quaternion.RotateTowards(this.transform.rotation, targetRot, 8f);
    rb.AddForce((speed * transform.forward) - rb.velocity, ForceMode.VelocityChange);

```

---
Tags: unity, rotation
---


# Question
Title: How to use vertex and fragment shaders without using VBOs and VAOs?
Recently, I am trying to make a 3D game in LWJGL 2, not LWJGL 3, just because I am more familiar with LWJGL 2. Since LWJGL decided to shut down their legacy wiki website, I've been researching alot lately on adding shaders. The thing is, most of these tutorials use VBOs and VAOs to render objects.

I am trying to use vertex and fragment shaders to edit the objects. Yes, I am using the depreciated methods `glBegin();` and those rendering methods to draw shapes. I am not sure if this affects the use of shaders or not, so that is why I am asking this question.

If anyone wants to know, I am using the depreciated methods because I don't want to really use VAOs and VBOs, I know it reduces performance to use the depreciated methods, but I am fine with this for now.

# Answer
> 0 votes
There's nothing special you need to do for this - shaders work just fine with glBegin/glEnd code.

You create and bind shaders in the normal way, set uniforms in the normal way. You still need to pay attention to the parts of the OpenGL pipeline that shaders replace, but that's the case no matter how you do your vertex submission.

For reading your vertex data in your vertex shader, you might find it easier to use the legacy built-in vertex attributes (https://www.opengl.org/sdk/docs/tutorials/ClockworkCoders/attributes.php) but if you wanted you could use standalone glVertexAttrib calls with glBegin/glEnd too.

# Answer
> 0 votes
1. First, make your classes to load the shader files. There should be methods to start/stop the shader, to wash (cleanup) the shader and to grab the shaders' program ID.
2. In your MainLoop (gameloop) After starting the shader for an object, type this in:

`GL20.glUniformXf(GL20.glGetUniformLocation(shader.getProgID(), variablename), a);`

Where `variablename` is the name of your uniform variable in either shader file (vertes or fragment), where `X` is specified uniform (4, 2, 1, etc), and where `a` is the number you want to set it to (what the variable will equal to)

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


# Question
Title: How to integrate images into text lines in Unity?
Here are two screenshots from Stellaris, where images are seamlessly integrated into the text. How can I achieve this in Unity?

# Answer
The regular Text component unfortunately can't do that, at least not on a UI canvas and without some nasty hacks. But TextMeshPro can. I really recommend using TextMeshPro over the classic Text component anyway, because it is superior in basically every way. The only thing which still justifies the existence of the classic Text component is backwards compatibility.

1. Create an image asset with all the icons you need (aka "sprite atlas")
2. Import the image as a "Texture Type: Sprite" with "Sprite Type: Multiple".
3. Slice the image into sprites using the sprite editor (requires importing the 2D Sprite package from the package manager). Set the "Pivot" of every sprite to "Bottom Left" (otherwise the sprites will not align properly with the text).
4. Right-click on the image asset in your project window and select Create \> TextMeshPro \> Sprite Asset
5. Create a "Text - TextMeshPro" gameObject on your canvas. When you already have one, make sure that you still have "Rich Text" enabled (it's hidden under "Extra Settings").
6. Assign that sprite asset to your TextMeshPro component. The setting is hidden under "Extra Settings". Or alternatively, if you want to use the same set of icons for all texts in the game, Go to Edit \> Project Settings \> Text Mesh Pro \> Settings and set the default sprite asset to the asset you just created.
7. You can now refer to sprites in your sprite asset by writing `<sprite=number>` into the text of your text object, where "number" is the sprite number from your sprite atlas. You can also explicitly name sprites in your TextMeshPro Sprite Asset and then refer to them as `<sprite name="spritename">`.

For example, if the second tooltip from the screenshot in the question were a TextMeshPro text, then its text would read something like this in the editor:

```
Pop Amenities Usage (<sprite name="populaton"> <color="yellow">52</color>): <color="red">52</color>

```
> 6 votes

---
Tags: unity, c#, gui, text
---


title: How to extend a line to infinity?

text:
# Question
Title: How to extend a line to infinity?
In my game I have a line that simulates the trajectory of a gun shot, fired by the main character.

The line starts at the character and ends at the mouse position at the moment of the click.

What happens is that sometimes the click is before the target. So the line does not extend to the target. I wish I could extend the line, at least to the end of the room.

**What happens:**

**What I would like to happen:**

**Line:**

```
(x1,y1,x2,y2)

(obj.x,obj.y,mouse_x,mouse_y)

```

---

**Attempt based on liggiorgio's answer:**

# Answer
> 1 votes
The problem is simpler than it looks.

I had already seen something similar looking for a laser. But this was done using objects, increasing their scale on the x-axis and changing the rotation.

Based on that, I looked for angled lines and I found this:

**Link:**

https://forum.yoyogames.com/index.php?threads/how-to-draw-a-line-at-an-angle-from-point-x-y.33230/

**New Line:**

```
draw_line(x1,y1,x2,y2);

aux=point_direction(obj.x,obj.y,mouse_x,mouse_y);

auxDsin=dsin(aux);
auxDcos=dcos(aux);

draw_line(obj.x,obj.y,obj.x+(1920*auxDcos),obj.y+(-1920*auxDsin));

```

I used 1920 because it is the size of the screen.

# Answer
> 1 votes
You can draw a line along a given direction using the `lengthdir_*()` functions.

First, you find out the direction from your object towards the mouse pointer with `point_direction()`:

```
var dir = point_direction(obj.x, obj.y, mouse_x, mouse_y);

```

Then, you draw a line with this direction (in the object's *Draw Event*):

```
var len = 1920;
var to_x = lengthdir_x(len, dir);
var to_y = lengthdir_y(len, dir);
draw_line(obj.x, obj.y, obj.x + to_x, obj.y + to_y);

```

The line starts at point (`obj.x`, `obj.y`) and has direction `dir` (in degrees) and length `len`. The length can be changed as it better suits your needs, since GM:S doesn't let you pick infinity as a numeric value.

---
Tags: game-maker, lines
---


# Question
Title: How to know if an overriden method calls its super method or not?
Consider this situation, where a Player class inherits from a more general Actor class:

## Actor.gd

```
class_name Actor extends KinematicBody2D

func _ready():
    print("I am an actor")
    _foo()

func _foo():
    print("I was thinking I was an actor")

```

## Player.gd

```
class_name Player extends Actor

func _ready():
    print("I am a player")

func _foo():
    print("I was thinking I was a player")

```

---

When one instantiate a player in a scene, we have this output:

```
I am an actor
I was thinking I was a player
I am a player

```

How to know when a method will call its super class?

# Answer
## On the mechanism of Ready

The underlying mechanism for Godot calling `_ready` are notifications.

What a script observes is the following:

* Godot calls `_notification` with `NOTIFICATION_POST_ENTER_TREE` (27).
* Godot initializes any onready variables.
* Godot calls `_ready`.
* Godot calls `_notification` with `NOTIFICATION_READY` (13).
* Godot emits the ready signal.

The mechanism is in `Node::_propagate_ready` (source):

* First it will call `_propagate_ready` on the children nodes, recursively.
* Then it calls `notification` with `NOTIFICATION_POST_ENTER_TREE`.
* Then it calls `notification` with `NOTIFICATION_READY`
* Finally it emits the ready signal.

Somewhere lost in there is when it calls `_ready`. We find that where `Node` handles the notification `NOTIFICATION_READY` (source).

When the `Node` gets `NOTIFICATION_READY`, it connects the handlers for `_input`, `_unhandled_input`, `_unhandled_key_input`, `_process`, and `_physics_process` (only if you declared them). Then it calls `_ready`. Will get back to that.

Thus, children nodes will get `NOTIFICATION_READY` first, and thus they will get their `_ready` called first.

---

## Ready and derived classes

But all of that is without talking about inheritance. *To be clear, I've been talking about children nodes in the scene tree, not derived classes.*

The script is, well, an instance of the class `Script`. A `Node` *has a* `Script`. And there are different derived classes of `Script` for each language. We want `GDScript`.

This is important, because, for example, if it were `CSharpScript` it would use the inheritance mechanism of C#, and there you need to call `base._Ready`. *Of which there are examples, as pointed out by Vaillancourt.*

---

Let us look at the call of `_ready` again (source):

```
get_script_instance()->call_multilevel_reversed(SceneStringNames::get_singleton()->_ready, NULL, 0);

```

So, we get an instance of `Script` (of `GDScript` for our case), an we call `call_multilevel_reversed` on it.

This is how `call_multilevel_reversed` looks like (source):

```
void GDScriptInstance::_ml_call_reversed(GDScript *sptr, const StringName &p_method, const Variant **p_args, int p_argcount) {

    if (sptr->_base)
        _ml_call_reversed(sptr->_base, p_method, p_args, p_argcount);

    Variant::CallError ce;

    Map<StringName, GDScriptFunction *>::Element *E = sptr->member_functions.find(p_method);
    if (E) {
        E->get()->call(this, p_args, p_argcount, ce);
    }
}

void GDScriptInstance::call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount) {

    if (script.ptr()) {
        _ml_call_reversed(script.ptr(), p_method, p_args, p_argcount);
    }
}

```

As you can see, calling it will result in calling it on the base class *first*, recursively.

And there is the behavior you observe: Godot calls `_ready` on the base class, and then `_ready` on the derived class.

---

What about `_foo`? It is not special, Godot does not call it, it is a regular virtual call.

---

## How to avoid the logic on the base \_ready to run

The first answer is: Don't put it on ready.

You can do this:

**Actor.gd**

```
class_name Actor extends KinematicBody2D

func _ready():
    __ready()

func __ready():
    print("I am an actor")
    _foo()

func _foo():
    print("I was thinking I was an actor")

```

**Player.gd**

```
class_name Player extends Actor

func __ready():
    print("I am a player")

func _foo():
    print("I was thinking I was a player")

```

Since `__ready` is not one of the functions that Godot calls, it gets overriden as expected, and only the one on the derived class runs.

Drawback: you need to remember to use `__ready`.

---

This is arguably a cleaner way:

**Actor.gd**

```
class_name Actor extends KinematicBody2D

func _ready():
    if !get_script().resource_path.ends_with("Actor.gd"):
        return

    print("I am an actor")
    _foo()

func _foo():
    print("I was thinking I was an actor")

```

**Player.gd**

```
class_name Player extends Actor

func _ready():
    print("I am a player")

func _foo():
    print("I was thinking I was a player")

```

As you can see, this approach requires nothing special of the derived class.

Note: `get_script().resource_path` will not end in `"Actor.gd"` if it is a build-in script on a scene (It is a reasonable assumption that it isn't, since build-in script can't have class names). Also using `get_script().resource_path` will not work if the script is not loaded from a `resource_path` (e.g. it was created in runtime).

---

Thus, How to know if an overriden method calls its super method or not?

Well, given that we can call the method on the base class with the -let us call it- dot notation (e.g. `.method()`), checking if a method does it, would require source code analysis. However, if the question is how to know if an overriden method class its super method *by default*. Then the answer is that it does not. Instead there are some methods that Godot call differently.
> 7 votes

# Answer
I'm not an expert in gdscript/godot, but here is what I presume:

`_ready` being a "core" function acts similarly as a constructor. Typically (at least with a language like c++), when a new object is created, the most-parent constructor is called first, to make sure that the object is constructed when the child classes' constructor is called. The child not yet being constructed, if the function `foo` is called in the parent's constructor, it's the parent class's `foo` that will be called.

Although we have similarities here, it's not exactly the same.

`_ready` being a utility function, it will be called in order of the most parent's to the most child by the framework, making sure that what's "initialized" in the parents is initialized for the children--just like a constructor. However, unlike it would be the case in a constructor, all the objects having already been created, the "most overridden" function `foo` will hide all those that have been defined its ancestors.

Taking a look at the source code, there are multiple occurrences where a "child" `_Ready()` will call it's `base._Ready()` as the first thing it does, so it appears this is consistent with the theory.

---

*How to know if an overriden method calls its super method or not?*

It's probably safe to say that the "top ancestor" will have it's `_ready` function called first, down to the "most overridden" `_ready` function. This behaviour will likely be the same for `_init`, although I have not found anything relevant about it.

For the other cases, the normal "hiding" will be done, and you'll call the the "most overridden" `foo` function.
> 2 votes

---
Tags: godot, gdscript
---


# Question
Title: How to disconnect all signals of an emitter?
This a follow-up question of this one

I want to disconnect multiple signals before using `queue_free()`.

In docs we have:

```
void disconnect ( String signal, Object target, String method )

```

Is it possible to disconnect all signals of an emitter without using the names of the signals or methods involved?

# Answer
> 9 votes
You can get the list of signals with `get_signal_list`:

```
var signals = node.get_signal_list();
for cur_signal in signals:
    print(cur_signal.name);

```

Then you can get the list of connections for each one with `get_signal_connection_list` to find where those signals are connected to:

```
var signals = node.get_signal_list();
for cur_signal in signals:
    var conns = node.get_signal_connection_list(cur_signal.name);
    for cur_conn in conns:
        print(cur_conn.signal);
        print(cur_conn.target);
        print(cur_conn.method);

```

That is the information of signal connections that connect *from* an object. Which you need to disconnect them:

```
node.disconnect(cur_conn.signal, cur_conn.target, cur_conn.method)

```

---

On the other hand, if you want the information of signal connections that connect *to* an object, you can use `get_incoming_connections` instead:

```
var conns = node.get_incoming_connections();
for cur_conn in conns:
    print(cur_conn.signal_name);
    print(cur_conn.source);
    print(cur_conn.method_name);

```

Disconnecting them would be:

```
cur_conn.source.disconnect(cur_conn.signal_name, node, cur_conn.method_name)

```

---
Tags: godot, gdscript, messaging
---


# Question
Title: How do signals work when queue_free is called?
Consider this setup:

```
* KinematicBody2D (Player)
|- Sprite (icon.png)
|- VisibilityNotifier2D

```

With `Player.gd`:

```
class_name Player extends KinematicBody2D
signal unvisible

onready var visibility_notifier :VisibilityNotifier2D = $VisibilityNotifier2D

func _ready() -> void:
    visibility_notifier.connect("screen_exited", self, "__on_screen_exited")

func __on_screen_exited() -> void:
    emit_signal("unvisible")

```

Now I have a template `Level.gd`:

```
* Node2D (Level)
|- Player

```

```
extends Node2D

onready var player :Player = $Player

export var debug_no_enemy  = false
export var debug_no_player = true

func _ready() -> void:
    player.connect("unvisible", self, "_reset_level")
    if debug_no_player:
        player.queue_free()

func _reset_level() -> void:
    print("reset")
    get_tree().reload_current_scene()

```

The `print` statement proves that this setup make a kind of infinite loop of reset because the signal `screen_exited` is still emited when the player is `queue_free`.

Is it expected?

---

I am even more surprised with this modified version which produces the same thing:

```
func _ready() -> void:
    if debug_no_player:
        player.queue_free()
    player.connect("unvisible", self, "_reset_level")

```

# Answer
The simple solution is to not emit the signal if the node is queued for deletion:

```
func __on_screen_exited() -> void:
    if !is_queued_for_deletion():
        emit_signal("unvisible")

```

Note that this is happening before the node is freed. Using `queue_free` ensure all the steps needed to remove the `Node` safely happen between frames.

After the `Node` is removed from the Scene, Godot will disconnect signals from it, and then disconnect signals to it, then finally release the Node.

At the point you get this notification, the `Node` has disappeared because it is removed from the scene, but it has not been disconnected yet.

---

You are, of course, reloading the scene, which causes the loop:

```
func _reset_level() -> void:
    print("reset")
    get_tree().reload_current_scene()

```

Presumably, if you are running on a debug mode where there is no player, then the removal of the player should not cause the scene to reload. Thus:

```
func _ready() -> void:
    if debug_no_player:
        player.queue_free()
    else:
        player.connect("unvisible", self, "_reset_level")

```

Although, I'd argue for making the player its own scene and instance it (and connect its signals) only if `debug_no_player` is `false`, instead of removing the player if `debug_no_player` is true.
> 2 votes

---
Tags: godot, memory, gdscript, messaging
---


# Question
Title: How to flip sprite and all collision children of a KinematicBody2D at the same time?
I have tried to use the `scale` property of `KinematicBody2D` to flip at the same time the sprite and the collision/area/raycast children. For flipping, one just has to set `scale.x = -1`.

If it works in the editor, it does not work properly because the engine seems to reset `scale.x` to 1 each frame (as stated here):

---

NB: Here the original sprite is looking left (that is why it is blinking when going to the right, not very didactic sorry).

---

How to do the same without flipping every collision children one by one?

# Answer
> 1 votes
This is a great workaround I have found here:

```
func _physics_process(delta: float) -> void:
    if is_on_wall():
        _direction *= -1
    var scale_x_transorm = 1
    if _direction.x > 0: scale_x_transorm = -1
        set_transform(Transform2D(  Vector2(scale_x_transform, 0         ),
                                    Vector2(0,                 1         ),
                                    Vector2(position.x,        position.y)))

```

More details here, on how transformations work.

# Answer
> 1 votes
Usually, if we only need to flip the `Sprite`, we can use `flip_h` on the `Sprite`. However, given that we also want to flip `RayCast2D`, `Area2D` and other stuff, that solution won't work.

As you noticed, we cannot flip the scale of the `KinematicBody2D` because Godot resets it when it moves. However, we can flip the scale of a `Node2D` that has the `KinematicBody2D` as child, or that is child of a `KinematicBody2D`.

In this case, I suggest to have use an auxiliary `Node2D` as child of the `KinematicBody2D`, just to be flipped, let us call it `Inner`. So your scene tree would go like this:

```
KinematicBoyd2D
├─CollisionShape2D
└─Inner
  ├─Sprite
  ├─RayCast2D
  ├─Area2D
  │ └─CollisionShape2D
  └─OtherStuff

```

And then you can flip that `Inner`, for example with the sign of the horizontal velocity of the `KinematicBody2D`:

```
var dir := Vector2(100, 0)

func _physics_process(_delta: float) -> void:
    var vel = move_and_slide(dir, Vector2.UP)
    $Inner.scale.x = sign(vel.x) if vel.x != 0.0 else 1.0

    if is_on_wall():
        dir = -dir

```

*Notice ternary operation to prevent `scale.x` to be `0.0`.*

And yes, that would mean that the `CollisionShape2D` (or `CollisionPolygon2D`) of the `KinematicBody2D` won't be flipped along. It has to be a direct child of the `KinematicBody2D`. Hopefully it is symmetric and that is not a problem.

Worst case, you have two things to flip: `Inner` and the `CollisionShape2D` (or `CollisionPolygon2D`).

```
var dir := Vector2(100, 0)

func _physics_process(_delta: float) -> void:
    var vel = move_and_slide(dir, Vector2.UP)
    var x_scale = sign(vel.x) if vel.x != 0.0 else 1.0
    $Inner.scale.x = x_scale
    $CollisionShape2D.scale.x = x_scale

    if is_on_wall():
        dir = -dir

```

Be careful flipping a non-symmetric `CollisionShape2D` (or `CollisionPolygon2D`), which may result in some undesired collisions. *This has worked for me with some `CollisionPolygon2D`, but not all (I also had some get temporarily stuck when flipped, seems to happen when the collision is on a single point, your mileage may vary).*

*If you need to have child `KinematicBody2D`, they can be inside `Inner` too.*

---
Tags: animation, godot, gdscript
---


# Question
Title: How to make a Google Play app with paid and free-with-in-app-purchasing versions?
I want to implement an IAP system as well as a fully paid one in my game.

There are about 8 levels in my game. I want the paid version to cost around $4 and in case of IAP, each level can be unlocked for 0.99 cents.

Do I have to create two separate apps (one for paid and one for IAP) or can I have both of these in a single app? The user can then decide if they want to buy the entire game or unlock a few levels using the IAP feature.

# Answer
I find this model odd... I'm a new user, and I have to decide early on if I want to buy one level or 8. If I buy one, that money is wasted if I determine later I want all of them.

I recommend having the game be free with (for example) 2 levels, but IAP to unlock the other 6. So I can try it, and buy more if I want. Choose between one IAP for all 6, or 6 IAPs, each for one level. Because you can't do dynamic pricing if they've already bought levels, this is a better route.
> 1 votes

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


# Question
Title: How to check if a point is on the plane given bottom-right point, top-left point, normal and the quaternion rotation of the plane
I know the world positions of A and B.

We are also given the vector normal and the quaternion rotation of the plane

How do I check if a point lies on the plane?

# Answer
Let's assume your quaternion is set up so that it rotates the z+ vector to point along the plane normal, the y+ vector along the rectangle's "up" axis, and the x+ vector along the rectangle's "right" axis.

(This is what you'd get in Unity with `Quaternion.LookRotation(planeNormal, Vector3.up)`, for example, assuming you want the rectangle's vertical axis to align as close to the world up direction as it can. That assumption, and the `Vector3.up` that encodes it, is the fourth piece of information we need, as I was decribing in our chat)

Then we can work this out very simply:

```
Vector3 ClosestPointOnPlane(Vector3 point, Quaternion orientation,
                            Vector3 topLeft, Vector3 bottomRight) {

    Quaternion inverse = Quaternion.Inverse(orientation);

    Vector3 inRectangleSpace = inverse * (point - topLeft);

    Vector3 limit = inverse * (bottomRight - topLeft);

    inRectangleSpace.x = Mathf.Clamp(inRectangleSpace.x, 0, limit.x);
    inRectangleSpace.y = Mathf.Clamp(inRectangleSpace.y, limit.y, 0);
    inRectangleSpace.z = 0;

    return (orientation * inRectangleSpace) + topLeft;
}

```

Now you can compare the returned point to the one you gave it. If they're within the threshold you deem "close enough" you can count the point as being in the rectangle.

Because we don't have infinite-precision real numbers, many points on the rectangle won't be exactly representable, so doing it this way lets us count points that are not strictly "on" the rectangle, but as close as we can reasonably get with our number format and the rounding in our arithmetic.
> 1 votes

---
Tags: mathematics, vector, geometry, intersection, position
---