# Question
Title: How to encourage players to fight nearby players instead of clustering into mega-factions?
My game is a location-based RTS game with roughly 150 players on 5 continents. Players can create and join alliances essentially at whim, and the players use discord for communication.

There is a dilemma, though: at present, all players in the USA are allied, and all players outside the USA are allied. The players inside the USA typically ally only when there is a threat, other than that they are constantly infighting, which is good.

However, players outside the US want to be allies and resist fighting eachother under any circumstance. They also actively work to stifle combat globally to maintain "peace."

My question is, how can I get them to fight eachother? This is only a problem when the non-US players have the majority of the power, because when the US players have the power, they infight constantly. I can't just limit the size of alliances, because the non-US players will simply break into many smaller alliances but will still fly the same flag.

Some ideas I have considered:

* Give players random targets to kill. If they kill the target/destroy the target's structures, they get extra reward.
* Remove the ability to create and join alliances, instead have several pre-determined factions players are placed into depending on geographic location. (Or on some other factor, or randomize it altogether.) Players could still jockey to be the leader of their faction.

I would appreciate any input you guys might have and I am happy to provide more information as necessary.

# Answer
One idea you could consider is implementing a mechanic that encourages players to compete for resources. If non-US players are able to maintain peace and work together, they may have an advantage in terms of resource acquisition and management. By introducing competition for resources, you may be able to encourage players to engage in conflict with one another.

Another option you could consider is implementing a ranking or leaderboard system that rewards players for attacking and defeating other players. This could incentivize players to engage in combat in order to climb the leaderboard and earn rewards.

You could also consider introducing events or challenges that require players to work against one another in order to complete them. This could provide a temporary reason for players to engage in conflict and give them a chance to compete against one another.

Ultimately, the solution will depend on the specific mechanics and dynamics of your game. You may want to consider collecting feedback from your players and experimenting with different approaches to see what works best in your specific game.
> 0 votes

---
Tags: game-design, game-mechanics, balance
---


# Question
Title: Run the most recent call of the function
Here's the code:

```
extends ColorRect

onready var label = $Label
onready var colorRect = self

var textPiece = ''

func text(value):
    colorRect.visible = true
    textPiece = ''
    for i in range(len(value)):
        textPiece += value[i]
        label.text = textPiece
        yield(get_tree().create_timer(0.05), "timeout")
    yield(get_tree().create_timer(5.0), "timeout")
    colorRect.visible = false

func _ready():
    colorRect.visible = false

```

I want to be able to use the function `text('test')` but then use `text('anothertext')` AGAIN, and cancel out the other function.

Basically, I expect the text function to run text('test'), but if I use the function again when it's still running text('test'), I want it to run the most recent call instead.

# Answer
So, the issue is that you are creating and dispatching timeouts.

To do this, you would want a couple things:

* A single ticking timer. Which will call a method on a fixed interval.
* Store the text you actually want to put.

The method would add a character from the text each time (you can use the length of `Label.text` to figure out where you are on it).

*However, just don't do it that way.*

---

Since this kind of text animation is common in games, Godot `Label` has a `visible_characters` property.

So you can change the `Label.text` and animate `Label.visible_characters`.

Furthermore a good way to do that animation is with a tween. I'll be using the new tween API (Godot 3.5+) here.

```
func text(value:String) -> void:
    label.text = value
    label.visible_characters = 0
    var tween := get_tree().create_tween()
    tween.tween_property(label, "visible_characters", len(value), 0.05 * len(value))

```

Here `tween_property` will change the value of a property (`visible_characters`) from the value it had when you called it (`0`) to the value we specify (`len(value)`), and it will do so increasingly during the specified time duration (`0.05 * len(value)`).

---

We can go ahead and use the same `tween` to wait and hide the `ColorRect`:

```
func text(value:String) -> void:
    colorRect.visible = true
    label.text = value
    label.visible_characters = 0
    var tween := get_tree().create_tween()
    tween.tween_property(label, "visible_characters", len(value), 0.05 * len(value))
    tween.tween_interval(5.0)
    tween.tween_callback(colorRect, "hide")

```

---

And since we don't want the previous one to continue running, we will store a reference to it, so we can stop it when we want to start a new one:

```
var tween:SceneTreeTween

func text(value:String) -> void:
    if tween != null:
        tween.stop()

    colorRect.visible = true
    label.text = value
    label.visible_characters = 0
    tween = get_tree().create_tween()
    tween.tween_property(label, "visible_characters", len(value), 0.05 * len(value))
    tween.tween_interval(5.0)
    tween.tween_callback(colorRect, "hide")

```
> 2 votes

---
Tags: godot
---


# Question
Title: How to add new animations to the same model in godot?
I'm new and learning godot now, I was following a tutorial and then realized I did not animate any idle animation, I can go back into blender and animate it then export it, it's not a problem.

But what is the process? I already did all this stuff and I don't want to break everything just trying to add a new idle animation, is it ok if I just load a new file with all the old animations + the new one or is there a better and more precise way?

I already google this and apparently I'm not the first person to ask this but no one seems to know.... should I just switch to Unity or other game engines because of this?

# Answer
> 1 votes
> I already did all this stuff and I don't want to break everything just trying to add a new idle animation, is it ok if I just load a new file with all the old animations + the new one or is there a better and more precise way?

It depends on what is "all the stuff".

If you:

* Created an scene where you instantiate your model: you can replace the model.
* Created a new scene derived from the model and used that: you can replace the model.
* Saved your model as a Godot scene: you will have to do the stuff again.

When you import your model, some resources will be externals. The changes you made to them in Godot will be preserved when you replace the model. *By default meshes are internal, animations are internal, and materials are external.* Refer to the import settings of the model.

*I would like to point out that Godot 4 gives you much more control on how you import the model, plus it can work with .blend files if you configure the path to your blender executable.*

---

> But what is the process?

About saving the model as a Godot scene… After being aware of all the workflow issues it causes, I would only consider it if I will not be doing more modifications to the model, because the game is basically done, and you are getting ready for a release… And then only if the model is having issue loading on the exported game (not saving the model file can reduce the size of the exported game and give you an smoother load, your mileage may vary).

As per inheritance, I find it more error prone, and also there has been bugs related to propagating changes to inherited scenes. So I rather a void it.

So I opt for composition. I create a new scene where I instantiate the model. In this scene I create whatever else I need using it. In particular I would enable editable children if I want to add something inside the model scene (e.g. inverse kinematics or bone attachments). And the rest of the project will only use this new scene. Then re-importing the model is no issue.

*This composition approach can be extended further. The most extreme example I can think of is like this: a version of the scene that has game logic (AI, Inputs, etc), which instantiate a version of the scene that has physics (colliders, ray-casts, etc), which instantiates a version of the scene that has graphics (bone attachments, particle effects, etc), which instantiates the model scene.*

---

> is it ok if I just load a new file with all the old animations + the new one or is there a better and more precise way?

Yes, that is what you would do.

---

Now, let us say, you messed up… You have saved the model as a Godot scene, and you are not referencing the model file anywhere (at which point you can remove the model file from the project).

You can add the new file, Godot will import it. Then:

* Open the model.
* Select the `AnimationPlayer`.
* On the "Animations" panel select the animation you want.
* Click the bottom "Animation" (on the left of the animation list drop down) and select "Save as...". This will save the animation to a file.

Then you can go to your old scene and follow similar steps. Except instead of "Save as..." select "Load" and pick the file you saved.

**Note**: This does not do proper animation re-targeting. But assuming the skeleton is the same, there should be no issue.

---

> should I just switch to Unity or other game engines because of this?

As you have figured out this is a common confusion for a beginner in Godot. I messed it up myself and learned to dealt with it.

I'd argue the hassle is nothing compared to recreating a game.

And as I said above, I recommend you instantiate the model scene (not inheriting from it, and no saving it as a Godot scene) to avoid problems in the future. And then it is no hassle.

At the end the decision is up to you. If you want to change engines, you don't need somebody from the Internet to tell you.

---
Tags: godot
---


# Question
Title: How do child/parent nodes work in Godot?
I apologize if this question is silly. I'm extremely new to Godot (and programming in general), and I've just managed to wrap my head around object-oriented programming.

The inheritance tree when it comes to the class of nodes makes sense to me. (Node2D \< CanvasItem \< Node \< Object, that sort of thing.) No problem there.

However, I'm having trouble wrapping my head around parent-child relationships between nodes in the scene tree. Because clearly a child node doesn't inherit the class of its parent or anything. It does seem to be...maybe not "inheriting," but affected in some way by the transforms, visibility, and so on of its parent. If that sort of thing were as far as it went, I think I'd be okay (it seems similar to how "parenting" works in Blender). It also seems to have some sort of file-system folder sort of thing going on, which I can also understand for purely organizational reasons. (Like how you can in a script treat the node tree like a file path, sort of.)

But then there are some nodes that say they require a certain child and/or parent to function at all. I don't understand at all what's going on here. Do certain nodes just need to talk to other nodes, and have built in "if I have that node as a child, I'm using it" sorts of things going on? Or is there some sort of inherent "this node is MY CHILD/PARENT, and therefore...something!" And why would a node require a child to work at all? I'm so confused.

Scenes as a whole seem to just be a root node with some children, so is any parent node basically just a scene (except not officially called one and maybe missing some of the instance-functionality that comes with it)?

TL,DR: What do parent nodes get from children, and what do child nodes get from parents? Is it only stuff like transforms, visibility, existing-in-the-scene-tree, etc.? Or is there more? I'd appreciate as complete a list as possible. Thanks so much!

# Answer
> 7 votes
> clearly a child node doesn't inherit the class of its parent or anything. It does seem to be...maybe not "inheriting," but affected in some way by the transforms, visibility, and so on of its parent.

This is correct.

---

> If that sort of thing were as far as it went, I think I'd be okay (it seems similar to how "parenting" works in Blender).

For clarity: it is compositional. Each `Node` has an aggregation (as understood in OOP) of children `Node`s. Which creates a tree. And there are things that are propagated through the tree (e.g. visibility and transformations). Which also includes the way some callbacks propagate (which is not a thing in blender), for example Godot will call `_ready` on the children before calling it on the parents.

---

> It also seems to have some sort of file-system folder sort of thing going on, which I can also understand for purely organizational reasons.

It has nothing to do with the file system.

With that said, you can instantiate scenes in the tree in the editor, and it makes sense for some files to be stored in the same folder as the scene that uses them.

---

> (Like how you can in a script treat the node tree like a file path, sort of.)

I believe you mean the `$` syntax, it is syntactic sugar for `get_node`. It uses a scene node path, so it is effectively a query on the scene tree. *And unrelated to the file system.*

---

> But then there are some nodes that say they require a certain child and/or parent to function at all. I don't understand at all what's going on here. Do certain nodes just need to talk to other nodes, and have built in "if I have that node as a child, I'm using it" sorts of things going on?

Basically, yes.

Any node can post a warning on their own logic, which might include checking what nodes they have as children. And some nodes care about the children they have because they use them in some special way. Furthermore, they might not be fully functional without them.

---

> Or is there some sort of inherent "this node is MY CHILD/PARENT, and therefore...something!"

I'm not sure what you are imagining here. But I'm going a limb and say yes. Whatever you are thinking is likely possible, and likely already been done.

Some Nodes care about its parent (instead of the parent caring about the children). For example the `BoneAttachment` must be a child of an `Skeleton`.

---

> And why would a node require a child to work at all? I'm so confused.

Some `Node`s use information from the children. For example, the physic bodies will use the colliders it has as children. *And they will warn you if they don't have one, because a physics body cannot get collisions if it does not have colliders, and without collisions a physics body is of little use.*

Some `Node`s will manipulate the children. For example, the `Container`s will re-arrange the children `Control`s. *However they don't require them, an empty container is not a warning.*

---

> Scenes as a whole seem to just be a root node with some children, so is any parent node basically just a scene (except not officially called one and maybe missing some of the instance-functionality that comes with it)?

Scenes are node (Godot does not have a `Scene` class).

What will make Godot show a `Node` as a scene is whatever or not it is saved to a separate file. In other words, a scene file serializes a `Node` with its children, unless the children are serialized to a different scene file.

And, of course, Godot does not only serialize nodes to scene files, it also loads them and instantiate them.

---

> TL,DR: What do parent nodes get from children, and what do child nodes get from parents? Is it only stuff like transforms, visibility, existing-in-the-scene-tree, etc.? Or is there more? I'd appreciate as complete a list as possible. Thanks so much!

As I mentioned, the `Node` class has an aggregation of children `Node`s.

The `SceneTree` class has a root `Node`, and the recursive aggregation of children creates a the tree.

Going further The `SceneTree` class will call methods on all the nodes on said tree (For example `_process`).

Beyond that, other classes that inherit from `Node` might use the children in different ways. For example objects of the `Spatial` will figure out their `global_transform` from the `transform` of their parents, recursively. And more specialized `Node`s might use their children or parent relationships in more specialized ways.

If you think about it, your scenes are very specialized `Node`s for your game. And you attach a script to the root of your scene that uses its children in very specialized ways (for example, it might play different animations in an `AnimationPlayer` depending on user input).

---

I should point out that not all communication between nodes should be done this way.

Note that when you instantiate your scene, you know it has all the `Node`s the way you set them in the editor, so it is OK for your code on them being there (unless there is some code that might remove them).

But when you want to communicate from an scene to another, relying on them being couples them (note that it is very easy to break the code by modifying the scenes, i.e. it is fragile), so it might be better to use signals.

Signals, however are one way messages. A node can send information to other nodes using signals, but not get a reply. In fact there might not be nodes listening to the signal.

Thus, when a `Node` needs information from other nodes, it is better to call methods on them. And how does it find the other nodes? It need to query the scene tree.

* It is convenient to use the children, since that makes it easier to bundle them together in a scene.
* However another option is use a `NodePath` property (for an example of this see the `RemoteTransform` class).
* It is also possible to use node groups. However nothing in Godot use them by default.

---

The other side of the question is this: If a `Node` needs information from other `Node`s, why make them separate `Node`s to begin with? And the answer to that is polymorphism and specialization: The other `Node`s can be of different classes, that can be extended independently.

For a classic OO example: A car needs wheels to work, but not to exist. And the wheels can exist without being part of a car. So you make the car have an aggregation of wheels. The wheels are children of the car. Plus you can change the wheels of the car, and create different kinds of specialized wheels without having to redesign the car.

---
Tags: godot
---


# Question
Title: Why is this code keeping the listener which should be removed instead?
I am having some issues figuring out why this code still lets `btn_1` call the function `setstate3()`.

There is a function `update()` with a code check for `(setstate == X)` within. When it gets to `if (setstate == 5)` and `if (setstate == 6)`, I want to remove the listeners.

The story ends that that point and will need a restart or whatever - for testing I want those buttons to be inactive at this point.

If I just turn off both listeners at `if (setstate == 1)`, the button becomes inactive. However, for some reason that doesn't work if I do so at `if (setstate == 5)` or `if (setstate == 6)` in the code. I expected it to work if you removed the listener inside the function it calls in the first place. It's not even throwing any error at all.

I did some research and had different attempts at cloning the element (apparently that will kill all listeners on an object), but I can't get that to be recognised as a command.

Any help would be greatly appreciated - have a great day

```
class Game {
constructor (exportRoot, stage) {
    this.root = exportRoot
    this.stage = stage
    this.str1 = "start"
    this.strOp1 = "1"
    this.strOp2 = "2"
    this.init()
    this.setstate
    this.randomNumber

}

    init () {
    const game = this
    this.main_Txt = this.root.main_Txt
    this.op_1 = this.root.op_1
    this.op_2 = this.root.op_2
    this.root.start_bt.on('click', function () { game.update() })
    this.setstate = 0
};
 update () {
    if (this.setstate == 0) {
    this.str1 = 'You have had a really big weekend camping.  In fact as you are driving home through the dark forest you can hardly keep you eyes open.  The stereo is playing your favourite song but suddenly it cuts out.  There is a huge bright purple light in the sky and your car sputters to a stop.  The stereo is dead and all the lights are out.'
        this.strOp1 = 'Try to fix your car'
        this.strOp2 = 'Start walking'
        this.root.start_bt.visible = 0
        this.root.mc_2.visible = false
        this.root.btn_1.on('click', function () { game.setstate1()})
         //this.root.btn_2.on("click", function(){ game.setstate2(); })
    } else if (this.setstate == 1) {
       this.str1 = 'You get out and open the hood, its hard to see but there is still some purple glow in the sky.  You wonder what that big light came from and what is going on.  All of a sudden there is some moaning and some noises from the underbrush and a zombie stumbles out onto the road.'
        this.strOp1 = 'Fight the zombie'
        this.strOp2 = 'Ask him to help fix the car'
        this.root.mc_1.visible = false
        this.root.mc_2.visible = true
        this.root.btn_1.on('click', function() { game.setstate3() })
         //this.root.btn_2.on("click", function(){ game.setstate2(); })
    } else if (this.setstate == 5) {
        this.str1 = 'You try to fight but the zombie overpowers you and eats your brain.'
        this.strOp1 = "dead"
        this.strOp2 = "dead"
        this.root.mc_1.visible = false
        this.root.mc_2.visible = false

        //this.root.btn_2.on("click", function(){game.setstate2();  })
     } else if (this.setstate == 6) {
        this.str1 = "lost"
        this.strOp1 = "dead"
        this.strOp2 = "dead"
        this.root.mc_1.visible = false
        this.root.mc_2.visible = false

         //this.root.btn_2.on("click", function(){ game.setstate2(); }
             }
    this.setText();
}
    chooseNumber () {
    this.randomNumber = Math.floor(Math.random() * 10) + 1
}
    setText () {
    this.main_Txt.text = this.str1;
    this.op_1.text = this.strOp1;
    this.op_2.text = this.strOp2;
}
    setstate1 () {
     this.root.btn_1.off('click', function  (){ game.setstate1() })
    console.log('setstate1')
    this.setstate = 1
    this.update();
}
    setstate3 () {
        this.root.btn_1.off('click', function  (){ game.setstate3() })
        this.chooseNumber();
        if (this.randomNumber >= 5) {
    console.log('setstate5');
    this.setstate = 5;
    this.update();

    } else {
    console.log('setstate6');
    this.setstate = 6
    this.update()
    }
  }
}

```

# Answer
> 0 votes
You can not remove a listener is EaselJS via `.off` by just passing a closure with the same sourcecode as you used in `.on`. The framework can not tell that it is in fact the same function you set previously. (because technically it's a completely different function which just happens to do the same thing).

As the documentation says:

> IMPORTANT: To remove a listener added with on, you must pass in the returned wrapper function as the listener.

The "wrapper function" the documentation talks about is the return value of `.on`. So if you later want to remove an event listener with `.off` , you need to capture that return value so you can do so later.

```
this.btn_1_listener = this.root.btn_1.on('click', function () {
    game.setstate1()
})

/* ... */

this.root.btn_1.off('click', this.btn_1_listener)

```

or alternatively, if you are certain that there are no other listeners on the button you might want to stay active, you can just remove all listeners with:

```
this.root.btn_1.removeAllEventListeners('click');

```

---
Tags: javascript, html5, html-canvas, easeljs
---


# Question
Title: Are Yields a Bad Code Practice in GDScript?
I understand that the title is a bit vague, but I'd like to get a better sense of where it is appropriate to use `yield()`. Up until recently I wasn't even aware of `yield()`, but now that I know it exists, I've been using it a lot. Too much, I suspect. Take the following code for example:

```
#NPC set up
if hide_gameplay_npcs or hide_player:
    GUI.fade_out(1.0)
    yield(GUI,"fade_out_complete")

    if hide_gameplay_npcs: toggle_character_group(Globals.group_gameplay_npcs, false)
    if hide_player: toggle_character_group(Globals.group_player, false)
    yield(get_tree().create_timer(0.5),"timeout")

    GUI.fade_in(1.0)
    yield(GUI,"fade_in_complete")

```

Previously, this code would have been a massive headache. I need to hide these characters in between a lot of other set-up work, so I would have had to separate this functionality into a bunch of small, conditional functions held together by signal connections. Yield completely solves this problem and lets me keep one logical grouping of functionality together in one place.

The problem is that using this many yields in one code block is setting off huge red flags. It's more a hunch than anything, but this block of code feels like something that's easy to write, but bad in practice.

Am I missing something? Are there gotchas to `yield()` that I need to be aware of? Rules of thumb? I know not to use `yield()` in `_process()` or any other constantly recurring function, and to not use it on nodes that could easily be destroyed. But is there something else I'm missing?

# Answer
> 8 votes
## Code Smell

We have a term for what you describe: it is a code smell.

Sometimes `yield` can be an indication of a bigger problem. Also there are cases where using `yield` is not safe.

However, I don't think the example is a bad use of `yield`. In particular I would worry if:

* Can `GUI` be freed prematurely?
* Can something else interact with `GUI` messing up this code?

---

> Are there gotchas to yield() that I need to be aware of?

Yes. There are a couple:

* No cancellation: you yield on a signal and there is no way to cancel that.
* No auto-disconnection: if the object that yielded is freed, you have a runtime error.

Not so much a gotcha of `yield`, but of the scene tree timers: they don't pause when you pause the game (`get_tree().paused = true`).

---

## Rules of thumb

> Rules of thumb?

Using `yield` on the correct object and signal will avoid timing issues. For example, if you need to wait for an `AudioStreamPlayer` to finish, yield on the `AudioStreamPlayer` instead of creating a timer.

Using `yield` on signals that must happen (that nothing will prevent the signal from happening) will avoid the code from being awaiting until tear down. *The `AudioStream` loops and never finishes, oops.*

*Addendum*: I should mention that there is a delay when playing audio, so if you play audio on a finished signal of another audio, there is an audible gap (there is a silence, I mean). But a timer won't fix that (they don't have enough temporal resolution). You need a thread sleeping for the appropriate time. Thankfully, we rarely need that much precision. Try audio tracks in the `AnimationPlayer` instead (and queue animations if needed).

**No cancellation**

Sometimes you want to convert your yielding code into a state machine in `_process`.

Also, avoid `yield` inside a process that needs to cancel its prior execution (if there is a chance you will call the method before the prior execution finished, and it needs to operate on the same objects). *In that case I suggest to use tweens, or animations (notice the call method tracks in the `AnimationPlayer`).*

**No auto-disconnection**

Since there is no auto-disconnection, use `yield` on things that will be there:

* The same object.
* The scene tree.
* Objects created for it.

Once you start yielding on other `Node`s you can start worrying. Is there a way for the other node to be freed independently? Can it happen while the code is awaiting in a yield?

* Yielding on an autoload is probably fine (you won't free those, right? RIGHT?).
* Yielding on children nodes might be fine, if there is no way for a `queue_free` or `free` to get them.
* Avoid yielding on anything else, even if there is no `queue_free` or `free` that can get them, if the yield can be ongoing during tear down (when the scene is being unloaded).

*Every `Node` will be destroyed at the end.*

---

**Error example**

I decided to make a minimal example where `yield` fails. It looks like this:

```
func _ready() -> void:
    get_tree().change_scene("res://some_scene.tscn")
    yield(get_tree().create_timer(0.1), "timeout")
    print("DONE")

```

If the path to the scene is invalid, that is the error you get.

But if the scene path is valid, after requesting the scene change the code will create the timer. While the code is awaiting the timer, the scene changes. And when the timer emits the `"timeout"` signal, Godot will try to resume this code it is already gone since the scene changed, and that is the error.

Note that it didn't require to access another `Node`.

I also tried yielding on a signal from a `Node` that is being freed:

```
$other_node.queue_free()
yield($other_node, "some_signal")
print("DONE") # never happens

```

And to my surprise instead of an error, `yield` never returned.

What reminds an error is freeing the same `Node`:

```
queue_free()
yield($other_node, "some_signal")
print("DONE")

```

---

## Refactoring yield

You might want to refactor to using signals connections. *Signal connection auto-disconnect when the objects are freed.*. In particular with `CONNECT_ONESHOT` (which auto-disconnect when they are fired).

However, be aware you cannot have the same method of the same object connected to same signal multiple times. Which means that sometimes it is better to create an object - of a custom class - to represent the process. Once every process has an object, you can connect to its method without worry of collision.

If you are using `yield` in a loop, the refactor becomes a bit more complicated, but it is worth it. You need to rotate (unroll) the instructions so that the check to continue iterating happens where the `yield` is… Which also means you might have to repeat some instruction before the loop. Then you make a method for the iteration of the loop, and another method for the lead up to the loop. So the lead up method connects to the iteration method, and the iteration method connects to itself.

*I want to mention that Godot 4 has anonymous functions ("lambda" functions), so you can do all of this inline, and you can avoid the extra class.*

---

**On return values**

Know that a method that uses `yield` returns a `GDScriptFunctionState` that has a `completed` signal. So you can do this:

```
yield(my_method(), "completed")

```

But the method only returns `GDScriptFunctionState` if it yields. Thus, make sure you can predict if a method will yield from its arguments. The easy way to do this is to make sure your methods either always yield, or never yield. This is so you know when and how you can yield on the method when calling it.

If you migrate said method to not use `yield`, you can make it return an object with a "completed" signal, and you don't have to change the way you call it. Furthermore, the object it returns might be itself, in which case you might need to do this:

```
call_deferred("emit_signal", "completed")

```

This is because the signal must happen after the method returned for yield to get it.

---

I'll also point out that `yield` returns. It returns the first argument (if any) it gets from the signal. So you can do this:

```
var my_var = yield(my_method(), "completed")

```

Which is how it works if the method uses `yield` and also returns.

If the method does not use `yield`, but instead returns an object that has the signal, that object would have to emit it the signal like this

```
emit_signal("completed", result)

```

And if the method is returning the same object, then you want do this:

```
call_deferred("emit_signal", "completed", result)

```

---
Tags: architecture, godot, gdscript
---


# Question
Title: How to move blocks down to fill the gap after clearing a row in Tetris?
I'm working on a Tetris clone. When I clear a line, my code does this:

I want to move the squares down + 1.

My code is:

```
verify_val = defaultdict(list)
    for val in grid:
        x, y = val
        if (x,y) in grid:
            if grid[(x,y)] != "white":
                verify_val[y].append(x)

    # list of rows
    compare_l = [x for x in range(x_left, x_right, 1)]
    compare_l.sort()
    lines = 0

    pos = []
    change = False

    pos_n = []

    for y in verify_val:
        verify_val[y].sort()
        #compare if rows are full
        if verify_val[y] == compare_l: # it was the rows, full
            lines += 1
            for x in verify_val[y]:
                pos.append((x,y))
            change = True
        else:
            if (x,y) not in pos_n:
                for x in verify_val[y]:
                    pos_n.append((x,y))

    if change:
        for x,y in pos_n:
            grid[(x,y)] = grid[(x,y-1)]

```

# Answer
Well I got it, my problem is that I was doing operations on the same grid.
> -2 votes

---
Tags: python, pygame, tetris
---


# Question
Title: Shaking UI World Space element when keeping it centered between 2 objects
So I have a ship in the game, and I can click on a Sail to make a World Space UI panel appear. The panel will follow the selected sail and also always Billboard towards the camera.

The problem I have is that the UI element will start shaking after a few seconds of gameplay. World Space position of the objects is near Origin (0,0,0) so this is not a floating point issue I think?

The camera can freely rotate around the ship, so the UI element needs to keep track of the moving sail(because the ship is moving) but also keep track of the camera position.

My code:

```
public class UIWorldSpacePanel : MonoBehaviour
{
    Camera cam;

    public MeshFilter FollowMesh;
    public float MidDistance = .5f;
    void Start()
    {
        cam = Camera.main;
    }
    void FixedUpdate()
    {
        transform.position = Vector3.Lerp(FollowMesh.transform.position, cam.transform.position, MidDistance);

        transform.LookAt(cam.transform.position);
    }
}

```

I also tried this:

```
void FixedUpdate()
{
    Vector3 oldPos = transform.position;
    Vector3 newPos = Vector3.Lerp(FollowMesh.transform.position, cam.transform.position, MidDistance);
    transform.position = Vector3.MoveTowards(oldPos, newPos, Time.deltaTime);

    transform.LookAt(cam.transform.position);
}

```

But this doesn't work as the UI element just flies away into the distance, it wont do that if I turn off billboarding, but that's useless...

Putting the code in Update or FixedUpdate doesn't seem to fix the issue either.

# Answer
> 0 votes
Using `LateUpdate` instead of `FixedUpdate` fixed the problem for me:

```
void LateUpdate()
{
    //code
}

```

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


# Question
Title: Deactivate a list of gameobjects before building
I want to deactivate a list of game objects in about 10 different scenes each time **before the build process.** I don't want them to be deactivated in the editor since these game objects are significant parts of the level. Currently, this deactivation process is done on awake, but this is too demanding for some CPUs and leads to stutters when reloading the scene.

So I was looking into "IPreprocessBuild" to do this just before I run the build process but I could not make it work.

How would you approach this?

# Answer
> But the EditorOnly Tag does not work for my case since these gameobjects are level parts that I will activate later. Therefore they need to be in the build but they should be deactivated when the scene loads.

The easiest way to do this is with a simple script:

```
public class HideOnAwake : MonoBehaviour {
    void Awake() {
        gameObject.SetActive(false);
    }
}

```

but this approach can have performance issues if there are a lot of objects to hide; it sounds like you already tried this and encountered those issues:

> Currently, this deactivation process is done on awake, but this is too demanding for some CPUs and leads to stutters when reloading the scene.

One thing you could potentially try to is use the scene hierarchy to reduce how often you need to use this `HideOnAwake` script. For example, rather than putting `HideOnAwake` on 100 different objects, you might put the script on one parent object and then make the 100 different objects all children of that one parent. Deactivating the parent will also deactivate all of the children.

If that approach doesn't work, then a build script seems like the best approach to me. However, you haven't given us any information on what you tried with the build script or why it didn't work, so it's difficult to give you guidance in this area. Here's a rough outline of how you might approach it:

1. Create a component script called `HideForBuilds` with no functionality: `public class HideForBuilds : MonoBehaviour {}`
2. Attach `HideForBuilds` to each GameObject that should be hidden.
3. Create a build script roughly along these lines:

```
public class BuildPreprocessor : IPreprocessBuildWithReport {
    private string[] scenePaths = { "Assets/Scene1.unity", "Assets/Scene2.unity" };
    public int callbackOrder { get { return 0; } }
    public void OnPreprocessBuild(BuildReport report) {
        //open each scene and hide the objects we want to hide
        foreach (var scenePath in scenePaths) {
            EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Single);
            var objects = GameObject.FindObjectsOfType<HideForBuilds>();
            foreach (var obj in objects) {
                obj.gameObject.SetActive(false);
            }
            //save changes to scene
            EditorSceneManager.MarkAllScenesDirty();
            EditorSceneManager.SaveOpenScenes();
        }
    }
}

```
> 1 votes

# Answer
One easy and efficient way to exclude objects from a built game is to tag them with the `EditorOnly` tag:

Objects with this tag will be present when editing the game or previewing it in Play Mode, but will be stripped from the game during the build process so they are not present in the version of the game you distribute to players.

Because these objects are completely stripped out, there's no runtime cost to load them and then deactivate them at scene start-up.

However, it also means these objects are completely erased from the build, not just deactivated. So if you wanted the objects to be present but inactive (and possibly later activated), then a build pre-process is the way to go. If you need help with that, you should edit your question to show how you've tried to write your pre-process function and where specifically you've encountered difficulty making it work the way you want.
> 0 votes

---
Tags: unity, build-process, build
---


title: Why is it so bad to optimize too early?

text:
# Question
Title: Why is it so bad to optimize too early?
After looking into optimization a bit, I have discovered (literally everywhere) that it seems to be a universally recognized sin to optimize a game too early.

I really don't understand this, would it not be incredibly difficult to change some of the core structures of the game at the end, rather than developing them the first time with performance in mind?

I get that waiting until the game is finished will tell you if you even need optimizations, but shouldn't you do it anyway, after all, it could widen the variety of devices the game could run on, which would increase the number of potential players.

Could someone explain to me why it's such a bad idea to optimize too early?

# Answer
> 245 votes
**Preamble:**

A few objections have been raised in the comments, and I think they largely stem from a misunderstanding of what we mean when we say "premature optimization" - so I wanted to add a little clarification on that.

"Don't optimize prematurely" does *not* mean "write code you know is bad, because Knuth says you're not allowed to clean it up until the end"

It means "don't sacrifice time & legibility for optimization until you know what parts of your program actually need help being faster." Since a typical program spends most of its time in a few bottlenecks, investing in optimizing "everything" might not get you the same speed boost as focusing that same investment on just the bottlenecked code.

This means, *when in doubt*, we should:

* Prefer code that's simple to write, clear to understand, and easy to modify for starters
* Check whether further optimization is needed (usually by profiling the running program, though one comment below notes doing mathematical analysis - the only risk there is you also need to check that your math is right)

A premature optimization is *not*:

* Architectural decisions to structure your code in a way that will scale to your needs - choosing appropriate modules / responsibilities / interfaces / communication systems in a considered way.
* Simple efficiencies that don't take extra time or make your code harder to read. Things like using strong typing can be both efficient and make your intent more clear. Caching a reference instead of searching for it repeatedly is another example (as long as your case doesn't demand complex cache-invalidation logic - maybe hold off on writing that until you've profiled the simple way first).
* Using the right algorithm for the job. A\* is more optimal and more complex than exhaustively searching a pathfinding graph. It's also an industry standard. Repeating the theme, sticking to tried-and-true methods like this can actually make your code easier to understand than if you do something simple but counter to known best practices. If you have experience running into bottlenecks implementing game feature X one way on a previous project, you don't need to hit the same bottleneck again on this project to know it's real - you can and should re-use solutions that have worked for past games.

All those types of optimizations are well-justified and would generally not be labelled "premature" (unless you're going down a rabbit hole implementing cutting-edge pathfinding for your 8x8 chessboard map...)

So now with that cleared up, on to *why* we might find this policy useful in games specifically:

---

In gamedev especially, iteration speed is the most precious thing. We'll often implement and re-implement far more ideas than will ultimately ship with the finished game, trying to "find the fun."

If you can prototype a mechanic in a straightforward & maybe a bit naive way and be playtesting it the next day, you're in a much better position than if you spent a week making the most optimal version of it first. Especially if it turns out to suck and you end up throwing out that feature. Doing it the simple way so you can test early can save a ton of wasted work optimizing code you don't keep.

Non-optimized code is also generally easier to modify and try different variants on than code that's finely-tuned to do one precise thing optimally, which tends to be brittle and harder to modify without breaking it, introducing bugs, or slowing it way down. So keeping the code simple and easy to change is often worth a little runtime inefficiency throughout most of development (we're usually developing on machines above the target spec, so we can absorb the overhead and focus on getting the target experience first) until we've locked down what we need from the feature and can optimize the parts we now know are slow.

Yes, refactoring parts of the project late in development to optimize the slow spots can be hard. But so is refactoring repeatedly throughout development because the optimizations you made last month aren't compatible with the direction the game has evolved since then, or were fixing something that turned out not to be the real bottleneck once you got more of the features & content in.

Games are weird and experimental — it's hard to predict how a game project and its tech needs will evolve and where the performance will be tightest. In practice, we often end up worrying about the wrong things — search through the performance questions on here and you'll see a common theme emerge of devs getting distracted by stuff on paper that likely is not a problem at all.

To take a dramatic example: if your game is GPU-bound (not uncommon) then all that time spent hyper-optimizing and threading the CPU work might yield no tangible benefit at all. All those dev hours could have been spent implementing & polishing gameplay features instead, for a better player experience.

Overall, most of the time you spend working on a game will not be spent on the code that ends up being the bottleneck. Especially when you're working on an existing engine, the super expensive inner loop stuff in the rendering and physics systems is largely out of your hands. At that point, your job in the gameplay scripts is to basically stay out of the engine's way - as long as you don't throw a wrench in there then you'll probably come out pretty OK for a first build.

So, apart from a bit of code hygiene and budgeting (eg. don't repeatedly search for/construct stuff if you can easily reuse it, keep your pathfinding/physics queries or GPU readbacks modest, etc), making a habit of not over-optimizing before we know where the real problems are turns out to be good for productivity - saving us from wasting time optimizing the wrong things, and keeping our code simpler and easier to tweak overall.

# Answer
> 44 votes
*Note: this answer began as a comment on DMGregory's answer, and so doesn't duplicate the very good points he makes.*

> **"Would it not be incredibly difficult to change some of the core structures of the game at the end, rather than developing them the first time with performance in mind?"**

This, to me, is the crux of the question.

When creating your original design, you *should* try to design for efficiency - at the top level. This is less optimisation, and is more about structure.

Example:
You need to create a system to cross a river. The obvious designs are a bridge or a ferry, so which do you choose?
The answer of course depends on the size of the crossing and the volume of traffic. This isn't an optimisation, this is instead starting out with a design suited for your problem.

When presented with design choices, you pick the one best suited to what you want to do.

So, let's say that our volume of traffic is fairly low, so we decide to build two terminals and buy in a ferry to handle the traffic. A nice simple implementation.
Unfortunately, once we have it up and running, we find that it is seeing more traffic than expected. We need to optimise the ferry! (Because it works, and building a bridge now isn't a good plan)

Options:

* Buy a second ferry (parallel processing)
* Add another car deck to ferry (compression of traffic)
* Upgrade the ferry's engine to make it faster (re-written processing algorithms)

This is where you should attempt to make your original design as modular as possible.
All of the above are possible optimisations, and you could even do all three.
But how do you make these changes without large structural changes?

If you have a modular design with clearly defined interfaces, then it *should* be simple to implement these changes.
If your code is not tightly coupled, then changes to modules don't affect the surrounding structure.

Let's take a look at adding an extra ferry.
A 'bad' program might be built around the idea of a single ferry, and have the dock states and ferry state and position all bundled together and sharing state. This will be hard to modify to allow for an extra ferry being added to the system.
A better design would be to have the docks and ferry as separate entities. There isn't any tight coupling between them, but they have an interface, where a ferry can arrive, unload passengers, take on new ones, and leave. The dock and ferry share only this interface, and this makes it easy to make changes to the system, in this case by adding a second ferry. The dock doesn't care about what ferries there actually are, all it is concerned with is that something (anything) is using its interface.

Summary:

* Try to design for efficiency in the first place.
* When presented with two choices, you pick the more efficient one.
* Write your code as modularly as possible with well-defined interfaces.

You can then change the mechanisms within each module without restructuring the entire codebase when you need to optimise.

# Answer
> 25 votes
"Do not optimise early" doesn't mean "pick the worst possible way to do things". You still need to consider performance implications (unless you're just prototyping). The point is not to cripple other, more important things at that point in development - like flexibility, reliability etc. Pick simple, safe optimisations - choose the things you limit, and the things you keep free; keep track of the costs. Should you use strong-typing? Most games did and work fine; how much would it cost you to remove that if you found interesting uses of the flexibility for gamemplay?

It's much harder to modify optimised code, especially "smart" code. It's always a choice that makes some things better, and others worse (for example, you might be trading CPU time for memory usage). When making that choice, you need to be aware of all the implications - they might be disastrous, but they can also be helpful.

For example, Commander Keen, Wolfenstein and Doom were each built on top of an optimized rendering engine. Each had their "trick" that enabled the game to exist in the first place (each also had further optimizations developed over time, but that's not important here). *That's fine*. It's okay to heavily optimize the very core of the game, the think that makes the game possible; especially if you're exploring new territory where this particular optimized feature allows you to consider game designs that weren't much explored. The limitations the optimization introduces may give you interesting gameplay as well (e.g. unit count limits in RTS games may have started as a way to improve performance, but they have a gameplay effect as well).

But do note that in each of these examples, the game couldn't exist without the optimization. They didn't start with a "fully optimized" engine - they started with the bare necessity, and worked their way up. They were developing new technologies, and using them to make fun games. And the engine tricks were limited to as small part of the codebase as possible - the heavier optimizations were only introduced when the gameplay was mostly done, or where it allowed an interesting new feature to emerge.

Now consider a game you might want to make. Is there really some technological miracle that makes or breaks that game? Maybe you're envisioning an open-world game on an infinite world. Is that *really* the central piece of the game? Would the game simply not work without it? Maybe you're thinking about a game where the terrain is deformable without limit, with realistic geology and such; can you make it work with a smaller scope? Would it work in 2D instead of 3D? Get something fun as soon as possible - even if optimizations might require you to rework a huge chunk of your existing code, it may be worth it; and you might even realize that making things bigger doesn't really make the game better.

As an example of a recent game with lots of optimisations, I'd point to Factorio. One critical part of the game are the belts - there are many thousands of them, and they carry many individual bits of materials all around your factory. Did the game started with a heavily-optimised belt engine? No! In fact, the original belt design was almost impossible to optimise - it kind of did a physical simulation of the items on the belt, which created some interesting things you could do (this is the way you get "emergent" gameplay - gameplay that surprises the designer), but meant you had to simulate every single item on the belt. With thousands of belts, you get tens of thousands of physically-simulated items - even just removing that and letting the belts do the work allows you to cut the associated CPU time by 95-99%, even without considering things like memory locality. But it's only useful to do that when you actually reach those limits.

Pretty much everything that had anything to do with belts had to be remade to allow the belts to be optimised. And the belts needed to be optimised, because you needed a lot of belts for a large factory, and large factories are one attraction of the game. After all, if you can't have large factories, why have an infinite world? Funny you should ask - early versions *didn't* :) The game was reworked and reshaped all over many times to get where they are now - including a 100% ground-up remake when they realized Java isn't the way to go for a game like this and switched to C++. And it worked great for Factorio (though it was still a good thing it wasn't optimised from the get-go - especially since this was a hobby project, which might have simply failed otherwise for lack of interest).

But the thing is, there *are* lots of things you can do with a limited-scope factory - and many games have shown just that. Limits can be even more empowering for fun than freedoms; would Spacechem be more fun if the "maps" were infinite? If you started with heavily optimised "belts", you would pretty much be forced to go that way; and you couldn't explore other design directions (like seeing what interesting things you can do with physics-simulated conveyor belts). You're limiting your potential design-space. It may not seem like that because you don't see a lot of unfinished games, but the hard part is getting the fun right - for every fun game you see, there's probably hundreds that just couldn't get there and were scrapped (or worse, released as horrible messes). If optimisation helps you do that - go ahead. If it doesn't... it's likely premature. If you think some gameplay mechanic works great, but needs optimisations to truly shine - go ahead. If you don't have interesting mechanics, *don't optimise them*. Find the fun first - you will find most optimisations don't help with that, and are often detriminal.

Finally, you have a great, fun game. Does it make sense to optimise *now*? Ha! It's still not as clear as you might think. Is there something *fun* you can do instead? Don't forget your time is still limited. Everything takes an effort, and you want to focus that effort on where it matters most. Yes, even if you're making a "free game", or an "open source" game. Watch how the game is played; notice where the performance becomes a bottleneck. Does optimising those places make for more fun (like building ever bigger, ever more tangled factories)? Does it allow you to attract more players (e.g. with weaker computers, or on different platforms)? You always need to prioritise - look for the effort to yield ratio. You'll likely find plenty of low-hanging fruit just from playing your game and watching others play the game. But note the important part - to get there, *you need a game*. Focus on that.

As a cherry on top, consider that optimisation never ends. It's not a task with a little check mark that you finish and move on to other tasks. There's always "one more optimisation" you can do, and a big part of any development is understanding the priorities. You don't do optimisation for optimisation's sake - you do it to achieve a particular goal (e.g. "200 units on the screen at once on a 333 MHz Pentium" is a great goal). Don't lose track of the terminal goal just because you focus too much on the intermediate goals that might not even be pre-requisites for the terminal goal anymore.

# Answer
> 9 votes
A lot of the answers seem to be focusing a lot on the performance aspect of "optimization" while I myself like to look at optimization and the whole ordeal of optimizing too early at a more abstract level.

Humor me as I attempt to elaborate on my perspective with the help of polyominoes.

Suppose we have some fixed boundaries set by the framework or engine we're working with.

We then proceed to create our first layer/module of the game like so.

Moving onwards we build our second layer/module.

At this point, we might notice that there is some space available between the two modules and we might be tempted to optimize it to make full use of the boundaries allotted to us.

Perfect, now the application is fully utilizing the resources available to us, the application is better, good right?

We proceed to build the third layer/module of our application and suddenly we come to a realization (perhaps even one we could not have foreseen during initial planning) that the 3rd layer/module is not working for us.

We search for an alternative, we find one, and in the end, this also requires us to change the 2nd module of our application since it's incompatible with our newly selected 3rd module. (Thankfully it's somewhat compatible with our 1st module so we don't have to re-write everything from scratch.)

So we put it all together...

Hmm, can you see what happened?

By optimizing too early we now have actually made things worse efficiency-wise since what we optimized against is not what we ended up with down the line.

And if we would have wanted to add some additional modules or extra tidbits afterward, we might no longer have the capacity to do them at this point.

And adjusting the lowest level of our system is no longer that feasible since it has been buried under all of the other layers.

If, however, we would have opted to wait with our urge to optimize it immediately we would have ended up with something like this:

And now if we perform the optimization at this point we get something satisfying to look at.

Hopefully at least some of you had as much fun reading this as I had fun making this :) and if you now feel like you have a better grasp on the subject - all the better.

# Answer
> 8 votes
**Money.**

It comes down to that. Money. Since time is money\*, the more time you spend on activities that are not guaranteed to generate more money (i.e. you can't consider these activities as *investments*), the more money you risk wasting, and the less money you'll make with the game.

Here are some more *potential* side effects of optimizing too early, and reasons why you should avoid it:

* Your colleagues hate you because you play in your sandbox with your toys while they work hard to get features in.
* The delays displease the higher management, and make the team miss delivery dates, which causes the game to be released in the spring instead of before the holiday season, which in turn causes the game to not sell enough. And because of this, the head office decides to shut-down the studio, effectively making you jobless. And no job means no money. (And since no one likes you because you spent too much time doing early optimization, no one wants to write a positive review on your work for you on LinkedIn, which will keep you out of money for a longer time.)

<sup>* Other answers have highlighted well enough the 'time' part</sup>

---

As a side note, *generally*, experience helps determining what is and what is not premature optimization and what has value for the business and what has not.

For instance, if you've worked on game A, and realized by the end of the project that the feature XYZ was particularly heavy on your game loop, and you eventually start to work on game B which has the exact same feature, deciding to rewrite the feature and optimizing it from the start is not really premature optimization, as you *know* it will be a bottleneck if nothing is done.

# Answer
> 6 votes
Optimization is, by definition, the process of increasing the efficiency of a solution up to the point where it looses its efficacy. This process implies then a reduction of the solution's space.

At an early stage of software development there can still be "hidden requirements": if you reduces too much the space of your solution you might end up in a situation in which you are unable to satisfy a "hidden requirement" when it pops-up at a later stage of development, compelling you then to modify the architecture adding in this way instability and a possible bunch of undesidered behaviours.

The idea is then to get the entire solution working and only then, when all the requirements are fixed and implemented, tighten the code. You will see then, that a lot of optimizations you would have lightheartedly implemented at once while coding, are now no longer feasable due to the interaction with late requirements.

The real space of the solution is always bigger than the one we expect at the beginning because we cannot have a perfect knowledge of a very complex system.

Make it work first. Then tighten the ropes.

# Answer
> 2 votes
In short, very often optimizing early becomes wasted effort if you want to change things later, and then it turns out you've optimized away the easily changeable code structures into something much lower level, and you now need to change it back to a high level approach, and optimize the result once again.

This is a common mistake for newbie developers who like to focus on getting pleasure from "having done useful work", like optimization, not thinking about if it's the right time to do it. As you gain experience programming big projects like games, you'll learn when it's warranted to optimize the existing codebase, and when it is too soon. Don't be afraid to make this mistake, you'll only benefit by learning from it.

In general, only optimize if you really can't work with the development build right this moment. Like if you're creating and deleting millions of objects 60 times per second.

So, I'd say it's good, in terms of learning experience, to optimize early a few times :p

# Answer
> 2 votes
Optimization focuses on making the computer work best on the code while development requires making the programmer work best on the code.

Optimization does not bring out insights. It makes the computer work less and the programmer more.

Of course, there are different categories, like with designing a car. Nothing wrong with optimizing an engine before you build your first chassis, but optimizing the chassis before you don't know the shape of the engine may end up a waste of time. Modularity and specs can get a number of places viable for optimization work even before the product as a whole gets assembled.

# Answer
> 2 votes
I strongly disagree with all of those statements that code shouldn't be optimized at early stages. It depends on what stage you are. If this is MVP - prototype and you are just trying to look at the game which takes from 1 to 2 weeks, that you ready to rewrite everything you already wrote. Yeah, optimization doesn't matter. But if you already are working on a game that you know will be release, it should have optimized code all along. The tales that people say about new features and things that could be added is missconception. It's poorly designed code architecture rather than optimized code. You don't need to rewrite anything to add new elements if you have nice code design.

For example, if you have a A\* pathfinding algorithm, wouldn't it be better to write it the most optimal way you can? Rather than later changing half of the code you have because you had to make some changes in the algorithm because now it needs another method calls and callbacks? And if you already have an optimized code from start it will save you a lot of time. Because you can draw yourself relations between objects and how they interact, instead of blindly making tons of new scripts and making up all connections right away - this leads to unclear sphagetti code.

The last thing I want to add is that later, even if you don't want to make the game anymore, you have your optimized A\* algorithm that you can use for your next games. Reusability. For example, many games have inventory, pathfinding, procedural generation, interactions between npc, fighting system, AI, Interface interaction, input management. Now you should ask yourself - "How many times have I rewritten those elements from scratch?" They are 70-80% of the game. Do you really need to rewrite them all the time? And what if they are unoptimized?

# Answer
> 0 votes
Short and simple answer:

1. A feature you optimize now might be a feature you throw out or replace later.
2. If you spend too much time optimizing, you might never finish your game.

---
Tags: performance, optimization
---


title: Setting animation from variable start

text:
# Question
Title: Setting animation from variable start
So I have a fun little animation where this monkey swings his feet however ! I am not sure where he will be in this animation when the player hands him this coconut which should trigger another animation that returns him to a stationary position.

In Unity how can I take the characters current position and use it as the start position for the animation ?

# Answer
> 1 votes
> I am not sure where he will be in this animation when the player hands him this coconut which should trigger another animation that returns him to a stationary position.

That doesn't matter if you manage the animations using the Animator component. The Animator component already supports transitions with animation blending. Just create a transition from one animation state to another.

---
Tags: unity, animation
---


# Question
Title: Should a swinging sword be part of the player sprite, or its own separate sprite?
Should the sword be part of the player sprite and therefore share the same hitbox that is widened when attacking?

or

Should the attack animation be separate from the player sprite therefore having its own hitbox?

To illustrate:

What would you recommend and why? What are the pros and cons of each?

# Answer
It is usually favourable to separate the collision hit boxes to allow for independent collisions.

For example, did the sword hit the target or did the target hit the player?

For single player games, the former is always true. In multiplayer, timing is key.
> 1 votes

---
Tags: collision-detection, sprites, game-mechanics, collider, top-down
---


title: Monogame - When to reuse buffers?

text:
# Question
Title: Monogame - When to reuse buffers?
So - how do these work exactly?

Right now I am making a buffer and setting the data every frame for my object, but I heard you can reuse the buffer, too. If the object is not changing in any way besides it's position, can you reuse the same buffer every frame, or do you have to remake it?

I've also heard you can simply change the position in a shader - is this the way to go?

As far as I'm aware, if the object moves, you need to do this every draw call:

```
vertexbuff = new VertexBuffer(GraphicsDevice, VertexPositionColor.VertexDeclaration, _vertices.Length, BufferUsage.WriteOnly);
vertexbuff.SetData(_vertices, 0, _vertices.Length);
GraphicsDevice.SetVertexBuffer(vertexbuff);

```

At least, that's how it worked when I tried. Is there a way not to do this every frame or am I approaching this the only way possible?

# Answer
> 0 votes
You can re-use the pointer to the buffer each step, but internally, the entire buffer is sent to the video card every step.

This restriction is a vestige of the original XNA behaviour.

Without some major wizardry, pointers across contexts are not possible at this time.

DX12 and Vulkan when implemented will solve this issue

A vertex shader parameter could handle the movement.

---
Tags: shaders, monogame, vertex-buffer
---


# Question
Title: How would I find the SDK folder for Android Studio so I can build my Unity project?
So I've been trying to build my unity project for android, but my problem is that I don't know how to find the Android SDK. I have the old developer bundle installed, when it was still the one with eclipse, but this version is not supported by Unity. So, I installed the latest version of Android Studio, the new official Android IDE, but the SDK folder is not in the same place as the rest of the program. How would I find the SDK folder for Android Studio so I can build my Unity project?

# Answer
the sdk may be hidden in the AppDatafolder (the folder itself was hidden).

If you want to look for AppData, but can't find it, open explorer and type %appdata%, press enter. It will show the hidden files. Path will look like this; C:\Users\Your.name\AppData\Local\Android\sdk1 Now that you have found the sdk, go back in to unity and click EDIT / Preferences / External Tools. You will see a field for Android SDK location - enter the path in that field.
> 11 votes

# Answer
*File* -\> *Other settings* -\> *Default Project Structure* menu invokes dialog box where you can see *Android SDK Location*.

It's `~/Library/Android/sdk` on MacOS and `~/Android/Sdk` on Linux, according to this comment.
> 3 votes

# Answer
You must follow this thread and it works! I just renamed the old "tools" folder to "tools\_old", downloaded the correct file from http://www.livecode-blog.de/forums/topic/android-sdk-installieren/#post-1056 and extracted the "tools" folder from the .zip file into SDK. After selecting the SDK folder (parent to "tools" folder), Livecode version 8.1.5 did compile the Android app without any more errors!
> 0 votes

# Answer
If you installed the SDK manually through command line, it's nice to know Unity asks for the root folder of the SDK, at least in Unity 2018.3.

So, if you installed it in

```
C:/sdk-tools-windows

```

it's that folder what Unity asks for, and not `C:/sdk-tools-windows/platforms/android-28` for example. It took me a while to get it!
> 0 votes

# Answer
Go to SDK manager UnTick the Hide Obsolete packages and then go to SDK tools section and Download the SDK tools (Obsolete) then you will have a tools folder

!! MAKE SURE TO UNCHECK THE HIDE OBSOLETE PACKAGES!!
> 0 votes

# Answer
Go C:/user/username/appdata/local/sdk but some time it may be hiden if this floder hiden studio give error message like SDK tool directry missing
> -2 votes

# Answer
I went to *"File \> Project Structure \> SDK Location*" and checked *"Use embedded JDK"*, and the error went away for me.
> -2 votes

---
Tags: unity, android
---


# Question
Title: Visual stutter from "Editor Loop" on project with few assets
I have a plane, a first person camera, and a player controller in a scene. There's a weird stutter in the game preview even though there are not a lot of assets in the project, average FPS, and don't see lag on other heavier projects. I tried changing the asset and replacing with a cube, still see the lag.

Any idea what could be causing this? Game is not GPU bound.

Environment

* Windows 10 NVIDIA GeForce RTX 3060
* Intel(R) UHD Graphics
* Unity 2021.3.14f1
* DX 11

Steps to reproduce:

1. Add plane + lighting settings (turned off lightbox and changed environment color to black)
2. Add capsule
3. Add player controller script
4. Add first person camera script
5. Add tree fbx
6. Add audio source to tree fbx
7. See visual stutter
8. Tried deleting tree fbx and added cube to see if I
still get the visual stutter - still there
9. Tried deleting first person camera script - visual stutter still there

I think its a hardware issue because i see the visual stutter just moving assets in the game preview without running it. but i dont see it running other projects.

Player Controller script

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

public class PlayerController : MonoBehaviour
{
    // The speed at which the character moves
    public float moveSpeed = 5.0f;

    // Update is called once per frame
    void Update()
    {
        UpdatePlayer();
    }

    void UpdatePlayer()
    {
        // Get the input axis for horizontal movement
        float horizontalInput = Input.GetAxis("Horizontal");

        // Get the input axis for vertical movement
        float verticalInput = Input.GetAxis("Vertical");

        // Calculate the movement vector
        Vector3 movement = new Vector3(horizontalInput, 0, verticalInput) * moveSpeed * Time.deltaTime;

        // Move the character
        transform.position += movement;
    }
}

```

First Person Camera script

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

public class FirstPersonCamera : MonoBehaviour
{
    // Variables
    public Transform player;
    public float mouseSensitivity = 2f;
    float cameraVerticalRotation = 0f;

    bool lockedCursor = true;

    void Start()
    {
        // Lock and Hide the Cursor
        Cursor.visible = false;
        Cursor.lockState = CursorLockMode.Locked;

    }

    void Update()
    {
        // Collect Mouse Input

        float inputX = Input.GetAxis("Mouse X")*mouseSensitivity;
        float inputY = Input.GetAxis("Mouse Y")*mouseSensitivity;

        // Rotate the Camera around its local X axis

        cameraVerticalRotation -= inputY;
        cameraVerticalRotation = Mathf.Clamp(cameraVerticalRotation, -90f, 90f);
        transform.localEulerAngles = Vector3.right * cameraVerticalRotation;

        // Rotate the Player Object and the Camera around its Y axis

        player.Rotate(Vector3.up * inputX);

    }
}

```

Edit Mode

Play Mode

# Answer
> 0 votes
I rebuilt the game in 2020.3.43f1 URP and the stutter stopped.

---
Tags: unity, lag
---


# Question
Title: How do I create a view matrix directly from a quaternion and a position vector?
Given a quaternionic camera such that:

```
typedef struct
{
    vector3 upReference;
    vector3 rightReference;
    vector3 forwardReference;

    vector3 position;
    quaternion orientation;

    float pov;
} camera_t;

```

Where:

* upReference, rightReference, forwardReference are always (0,1,0, 1,0,0, 0,0,-1) respectively
* pov is the viewing angle

and quaternion is:

```
typedef struct
{
    float x, y, z, w;
} quaternion;

```

Is there some way to create a view matrix directly from all of this and skip gluLookAt?

# Answer
> 1 votes
The three columns of a 3x3 rotation matrix (or the upper 3x3 block of a 4x4 rotation-and-translation matrix) can be thought of as the images of unit vectors in the x+, y+, and z+ directions, respectively, after rotation.

That means we can find the first column by rotating the vector \\$(1, 0, 0)\\$ by the quaternion \\$q\\$:

$$\begin{align} q (1i + 0j + 0k + 0) q^{-1} &= (q\_xi + q\_yj + q\_zk + q\_w) (i) (-q\_xi - q\_yj - q\_zk + q\_w)\\ & = (q\_x^2 - q\_y^2 -q\_z^2 + q\_w^2)i + 2(q\_xq\_y + 2q\_zq\_w)j + 2(q\_xq\_z - 2q\_yq\_w)k\\ \end{align}$$

And we can repeat this for each of the other columns, and use the fact that \\$\\|q\\| = 1\\$ to simplify the terms with the squares into the equivalent \\$q\_x^2 - q\_y^2 -q\_z^2 + q\_w^2 = 1 - 2(q\_y^2 + q\_z^2)\\$ and similar for the other axes. That gives us this 3x3 rotation matrix \\$R\\$ that does the same job as the quaternion \\$q\\$:

$$R = 2 \begin{bmatrix} \frac 1 2 - q\_y^2 - q\_z^2 & q\_xq\_y -q\_zq\_w & q\_xq\_z + q\_yq\_w\\ q\_xq\_y +q\_zq\_w & \frac 1 2 - q\_x^2 - q\_z^2 & q\_yq\_z -q\_xq\_w\\ q\_xq\_z -q\_yq\_w & q\_yq\_z + q\_xq\_w & \frac 1 2 - q\_x^2 - q\_y^2 \end{bmatrix}$$

But of course for a view matrix, we want the *inverse* of this rotation. But for a pure rotation matrix where all columns are orthogonal unit vectors, that's just the transpose:

$$R^T = 2 \begin{bmatrix} \frac 1 2 - q\_y^2 - q\_z^2 & q\_xq\_y +q\_zq\_w & q\_xq\_z - q\_yq\_w\\ q\_xq\_y - q\_zq\_w & \frac 1 2 - q\_x^2 - q\_z^2 & q\_yq\_z +q\_xq\_w\\ q\_xq\_z + q\_yq\_w & q\_yq\_z - q\_xq\_w & \frac 1 2 - q\_x^2 - q\_y^2 \end{bmatrix}$$

Now to translate this back so that some position vector \\$\vec p = (p\_x, p\_y, p\_z)\\$ gets mapped to the origin, we can take the image of \\$\vec p\\$ after rotation by \\$R^T\\$:

$$\vec p^\prime = R^T \vec p = 2\begin{bmatrix} p\_x(\frac 1 2 - q\_y^2 - q\_z^2) + p\_y(q\_xq\_y + q\_zq\_w) + p\_z(q\_xq\_z - q\_yq\_w)\\ p\_x(q\_xq\_y - q\_zq\_w) + p\_y(\frac 1 2 - q\_x^2 - q\_z^2) + p\_z(q\_yq\_z +q\_xq\_w)\\ p\_x(q\_xq\_z + q\_yq\_w) + p\_y(q\_yq\_z - q\_xq\_w) + p\_z(\frac 1 2 - q\_x^2 - q\_y^2) \end{bmatrix}$$

And subtract it to get the fourth column of our 4x4 view matrix \\$V\\$:

$$V = \begin{bmatrix}R^T &-\vec p^\prime\\ 0 \\, 0 \\, 0 & 1\end{bmatrix}$$

# Answer
> 0 votes
Try this below:

XMMATRIX is transpose of the transform matrix, so you read it as column,row

```
XMMATRIX viewMatrix = XMMatrixRotationQuaternion(v_quaterion);
XMFLOAT4X4 f_view;
XMStoreFloat4x4(&f_view, viewMatrix);
f_view._41 = mPosition.x * f_view._11 + mPosition.y * f_view._21 + mPosition.x * f_view._31;
f_view._42 = mPosition.x * f_view._12 + mPosition.y * f_view._22 + mPosition.x * f_view._32;
f_view._43 = mPosition.x * f_view._13 + mPosition.y * f_view._23 + mPosition.x * f_view._33;
viewMatrix = XMLoadFloat4x4(&f_view);

```

You need to multiply the translation vector by the rotation first

# Answer
> 0 votes
Another way to do it, if you already have the quaternion-rotation of a vector:

```
x = q.rotate (1,0,0)
y = q.rotate (0,1,0)
z = crossprod(x,y)
matrix = { x,y,z,p };

```

It's definitely not the fastest way to do it. But it's one that is easy to understand.

---
Tags: transformation, quaternion
---


# Question
Title: glm::perspective() with wide field of view
I'm still pretty new to this GL stuff, but I've managed to put together some C and C++ code that allows me to construct simple 3D objects consisting of line segments and display them on my laptop using GLFW and the glm library. I've hooked in enough keyboard callbacks to allow me to navigate the position and orientation of an observer via glm::lookAt(). A couple of the keys allow me to grow or shrink the field of view value that gets passed to glm::perspective(), like so:

```
float field_of_view; // degrees, not radians

        glm::mat4 proj = glm::perspective(
            glm::radians(field_of_view),    // field of view
            1920.0f / 1080.0f,      // aspect ratio
            0.0f, 100.0f            // near and far clipping planes
        );

```

From my experience as an amateur photographer, I know that if one takes a photo with a camera with a wide angle lens of a scene that contains straight line near the periphery of the field of view, the physically straight lines will appear bent in the photo. They bow outward so as to create a more circular shape around the center of view.

But when I modify the field of view that gets passed to glm::perspective() such that it is a high value (approaching 180 degrees), with an orientation such that the straight line segments appear near the edges of the field, the rendered line segments never bend like I'd see with a real camera and wide angle lens. Instead, the lines remain straight but appear to get very long.

This creates very unnatural looking images.

Is there some other glm function that I should call instead in order to make the rendered lines curved like I'd expect to see in real life?

Thanks

# Answer
The distortion you see with a real lens isn't from the wide field of view itself, but from the the way the lens warps the light. A wide field of view makes this effect much more noticeable, but it's present at narrower angles too. If you used a pinhole camera, the results would be much closer to the straight lines you see in the computer rendering.

That's because we're using linear perspective, which models the camera's aperture as an infinitely small point - similar to the hole of a pinhole camera. All the transformations the view and perspective matrices do are *linear* transformations - they can only map straight lines to straight lines. Mathematically, a matrix can't do anything else. So no value that `glm::perspective()` or any drop-in replacement could produce would give you the curved lines you're looking for.

Similarly, the rasterizer in your GPU will only rasterize straight-sided polygons joining the vertices. So even if we add a non-linearity to the transformation of the vertices, you still won't get a rounded curve unless you subdivide the meshes finely (or use tessellation on the fly).

The most common way to implement these curving effects in games is to render to an off-screen buffer using conventional linear perspective, then apply a post-processing pass where we read that rendered image as a texture, applying a barrel or pincushion distortion to the sampling coordinates to bend the image that's presented to the screen.
> 2 votes

# Answer
Excellent explanation DMGregory. I'd only add that, for nearly 180° no barrel or cushion is enough, so I'd suggest this general way. Draw the scene six times to the six textures of a cube map, each one with proper modelview of the six cardinal views and FoV of 90°x90° - the eye is at the center of the cube. Then, implement a fragment shader picking up the right texel of the cube map depending on the ray direction along the two directions of a full-viewport quad. As an example, that's mine:

```
uniform samplerCube cubemapTexture;
uniform vec2 viewport_res;
uniform float y_stereo_offset;

void main()
{
    vec2 coord = (gl_FragCoord.xy - vec2(0., y_stereo_offset)) / viewport_res.xy;
    vec2 thetaphi = ((coord * 2.0) - vec2(1.0)) * vec2(3.1415926535897932384626433832795, 1.5707963267948966192313216916398) * vec2(-1,-1);
    vec2 c = cos(thetaphi), s = sin(thetaphi);
    vec3 rayDirection = vec3(c.y * c.x, s.y, c.y * s.x);
    gl_FragColor = textureCube(cubemapTexture, rayDirection);
    gl_FragColor.a = 1.0;
}

```

All the magic is done by `textureCube` \- polar to cartesian conversion, and pick the texel from the right map among the six. `y_stereo_offset` can be 0 for non up-below rendering of stereo pairs.
> 1 votes

---
Tags: opengl
---


# Question
Title: D3D11 ERROR ("invalid arguments") from HLSL shader
I am using MonoGame 3.8.1.303 with Windows/DirectX. I am just rendering a `TriangleList` using `DrawIndexedPrimitives`, but I am always getting this error when starting my game:

> D3D11 ERROR: ID3D11Device::CreateInputLayout: The provided input signature expects to read an element with SemanticName/Index: 'SV\_POSITION'/0, but the declaration doesn't provide a matching name. \[ STATE\_CREATION ERROR #163: CREATEINPUTLAYOUT\_MISSINGELEMENT\]
>
> Exception thrown at 0x00007FFDAF45CD29 in realtimestrategy.exe: Microsoft C++ exception: \_com\_error at memory location 0x0000008CF917D388. Exception thrown: 'SharpDX.SharpDXException' in
>
> SharpDX.Direct3D11.dll HRESULT: \[0x80070057\], Module: \[General\], ApiCode: \[E\_INVALIDARG/Invalid Arguments\], Message: The parameter is incorrect.

This is my vertex declaration:

```
public struct VertexTypePosTxtBlend : IVertexType
{
    public VertexTypePosTxtBlend(Vector3 pos, Vector2 txtCoord, Color blend)
    {
        this.pos = pos;
        this.txtCoord = txtCoord;
        this.blend = blend;
    }

    public Vector3 pos;
    public Vector2 txtCoord;
    public Color blend;

    public static readonly VertexDeclaration VertexDeclaration = new VertexDeclaration
    (
        new VertexElement(sizeof(float) * 0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0),
        new VertexElement(sizeof(float) * 3, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0),
        new VertexElement(sizeof(float) * 5, VertexElementFormat.Color, VertexElementUsage.Color, 0)
    );

    readonly VertexDeclaration IVertexType.VertexDeclaration => VertexDeclaration;
};

```

This is my HLSL shader:

```
float4x4 World;
float4x4 ViewProjection;
texture UserTexture1;
texture UserTexture2;
texture UserTexture3;
texture UserTexture4;

sampler userMap1 = sampler_state
{
    texture = <UserTexture1>;
};

sampler userMap2 = sampler_state
{
    texture = <UserTexture2>;
};

sampler userMap3 = sampler_state
{
    texture = <UserTexture3>;
};

sampler userMap4 = sampler_state
{
    texture = <UserTexture4>;
};

struct VS_INPUT
{
    float3 Position : SV_POSITION0;
    float2 Texcoord : TEXCOORD0;
    float4 Blend : COLOR0;
};

struct VS_OUTPUT
{
    float4 Position : SV_POSITION0;
    float2 Texcoord : TEXCOORD0;
    float4 Blend : COLOR0;
};

VS_OUTPUT vs_main(VS_INPUT Input)
{
    VS_OUTPUT Output;
    Output.Position = mul(Input.Position, mul(World, ViewProjection));
    Output.Texcoord = Input.Texcoord;
    Output.Blend = Input.Blend;
    return Output;
}

float4 ps_main(VS_OUTPUT Input) : SV_TARGET
{
   return tex2D(userMap1, Input.Texcoord) * Input.Blend.r
        + tex2D(userMap2, Input.Texcoord) * Input.Blend.g
        + tex2D(userMap3, Input.Texcoord) * Input.Blend.b
        + tex2D(userMap4, Input.Texcoord) * Input.Blend.a;
}

technique
{
    pass
    {
        PixelShader = compile ps_4_0_level_9_1 ps_main();
        VertexShader = compile vs_4_0_level_9_1 vs_main();
    }
}

```

# Answer
I changed all declarations in the shader from `SV_POSITION0` to `POSITION0` and it works now. I do not understand why, since in another project `SV_POSITION0` was working fine and I also was thinking that `SV_POSITION0` was the more correct one for new shader model \>=4.0.
> 1 votes

---
Tags: shaders, directx, monogame, hlsl, sharpdx
---


# Question
Title: How will you go about designing A* pathfinding for a pong game?
I want to design A\* path finding in the pong 2d game. As far as I know I can just simply design an Ai as in

```
if ball.vector.y>player.vector.y
         moveplayeruo()

else
         moveplayerdown()

```

Is there any possible way to implement A\* on a pong game?

# Answer
> 3 votes
You *could* use A\*, but it's not a good choice.

As shown in this excellent answer covering how A\* works, A\* is an algorithm for finding the shortest paths between nodes in a graph. A general graph is often shown as something like this:

However, this is also a equally valid graph:

As such, you *could* apply A\* to this, and that would give you the shortest path from the `A` node to the `F` node. But if we know that all of the nodes are constrained to the X axis, we can use a much simpler, faster algorithm. In this case, we can simply look at the X coordinate of the neighbors for the current node & select the one that is closer to our target.

Similarly as you identified in your question, the code:

```
if (ball.vector.y > player.vector.y)
    movePlayerUp();
else if (ball.vector.y < player.vector.y)
    movePlayerDown();

```

Is a perfectly reasonable way to implement pong AI.

There are often many *possible* ways to solve a problem, but not all solutions are equally suited to different versions of the same problem. In this case, I would say that despite being a popular, fast, robust way to solve many types of pathfinding, A\* is poorly suited to the pathfinding problem of directing a pong paddle toward the ball because it is unnecessarily complex. It would work, but it is ill suited to this task.

---
Tags: c++
---


# Question
Title: Can MoonSharp call functions from static classes?
I'm using MoonSharp to add Lua scripting to my game. One use case involves calling a static artificial intelligence function from a static class I've implemented in C#. I know you can easily call static **functions** using MoonSharp, but can those functions be called if the **class** is static?

I haven't been able to find an answer so far through Google or on this site. My own experimentation with code hasn't been successful either. There are pretty simple workarounds for the problem I'm asking about (like making the AI class not static), but I'd prefer to avoid them.

# Answer
One soulution could be creating a static callback function that in turn calls the function on the staic c# class

so for exmple

```
private staic void AiCallback(int anArgument)
{
   AiClass.DoAi(anArgument);
}

private static void RegisterAiFunction(Script aLuaScript)
{
   aluaScript.Globals["DoAi"] = (func<void, int>)AiCallback;
}

private static void DoLua(string someLuaCode)
{
   Script script = new Script();
   script.DoString(someLuacode);
}

```

where AiClass would be your static class
> 2 votes

# Answer
I know this is an old post, but here is an example of automatically grabbing all public static methods from a class named "LuaGlobalFunctions" that automatically adds them as delegate functions to MoonSharps Script.Globals:

```
// Get global methods (must be public) and add them to the script.Globals
MethodInfo[] globalMethods = typeof(LuaGlobalFunctions).GetMethods(BindingFlags.Public | BindingFlags.Static);

foreach (var method in globalMethods)
{
    // Get name, parameters and return type so we can build a delegate
    string name = method.Name;
    Type[] parameters = method.GetParameters().Select(p => p.ParameterType).ToArray();
    Type returnType = method.ReturnType;

    // Build a delegate and add to globals with the name of the method, use the correct delegate type based on the return type
    if(returnType == typeof(void))
    {
        Delegate del = Delegate.CreateDelegate(Expression.GetActionType(parameters), method);
        script.Globals[name] = del;
    }
    else
    {
        Delegate del = Delegate.CreateDelegate(Expression.GetFuncType(parameters.Concat(new Type[] { returnType }).ToArray()), method);
        script.Globals[name] = del;
    }
}

```

Note the following using statements must be used:

```
using System;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using MoonSharp.Interpreter;

```
> 1 votes

---
Tags: c#, scripting, lua
---


# Question
Title: How can I draw a trajectory of an orbit?
With the following code, I either get a straight line or no line at all. I have tried almost the same thing in Unity and I get something that looks like orbiting, but here I get nothing.

How can I fix my code to draw a trajectory?

```
func _update_trajectory(delta):
    line.clear_points()
    var line_points = []
    var pos = mousePosition

    #starting velocity 200 for now
    var xAxis=200
    var yAxis =200

    var vel = Vector2(0,100)
    var vecR = sunGravity.position-pos
    var gravityForce = (vecR).normalized()
    var angle= 0

    var lastPos = pos +velocity.normalized()
    for i in range(1,MAX_POINTS-1):
        line_points.append(pos)

        vel+=Rigidbody_test(pos)
        lastPos=pos
        pos += vel*delta

    line.points=line_points

func Rigidbody_test(pos1:Vector2):
   var planetPos = sunGravity.position
   var dir=planetPos-pos1
   var dis = dir.length_squared()
   var forceMag=2*g_constant*((sunGravity.mass*currentMass)/dis)
   var force =dir.normalized()*forceMag
   return force

```

# Answer
> 0 votes
I have fixed my issue by increasing gravity constant so instead of having 0.0006 or whatever I just increased it to something like 274 which actually showed the curvature.

---
Tags: godot, gdscript, trajectory
---


# Question
Title: WebViewControl.java:122 cannot find symbol when packaging Unreal 4 game for Android
Whenever I try to package my project for Android I get this.

```
Z:\app\src\main\java\com\epicgames\ue4\WebViewControl.java:122: error: cannot find symbol

```

My setup:

* Android SDK build tool: 31.0.0
* NDK: 21.4
* Android SDK command line tool: 5.0

What else can I do?

# Answer
> 0 votes
You can try remove 33 SDK with Android Studio, like on this video https://youtu.be/Xq0AcQ1msTg

---
Tags: android, unreal-4, mobile
---


title: Drawing at floating point position

text:
# Question
Title: Drawing at floating point position
The library I am using (SDL2) only supports drawing to `int` positions. I am currently storing my objects positions as `double`, and would like to render them. Should I round the value to int, i.e. `0.5 => 1`, or simply cast it to `int`, i.e. `0.5 => 0`?

# Answer
Maybe this answer will not suit your question, but I assume that you want to have float movement precision even when SDL rectangles support only integer values.

One of the tricks you can do is to have a float/double variables to track some kind of "virtual" position in your world. In your case it means having a struct **SDL\_Rect** and some **float vector**. For example:

```
//Custom made generic type
Vector2<float> _position;

//SDL struct
SDL_Rect _rect;

void Object::init(float x, float y,SDL_texture* text)
{
    _position.x = x;
    _position.y = y;

    _rect.x = (int)x;
    _rect.y = (int)y;

    _texture = text;
}

```

And then the update function would look like this:

```
void Object::update(float deltaTime){

    _position.x += 5.0f * deltaTime;
    _position.y += 5.0f * deltaTime;

    _rect.x = (int)_position.x;
    _rect.y = (int)_position.y;
}

```

That way you don't lose the movement precisions the floats have. Then you can use this position vector also for collision checks, where instead of checking SDL\_Rects (in case of Rectangular collision) you check their position vectors+dimensions.
> 4 votes

# Answer
There's a simple way to render a rectangle with floating point coordinates but for some reason it's documentation is not available on the wiki. A commit was done to add this feature on October 22, 2018. Atleast SDL 2.0.10 required.

```
SDL_FRect box = {11.5, 1.2, 10.5, 11.252};
SDL_RenderFillRectF(renderer, &box);

```

<sup>*A simple demonstration of how it can be used for rendering.*</sup>
> 4 votes

# Answer
SDL2 has full range of function equivalents for `float` types here back in 2023 and if you want smooth movement like `position.x += (x*delta)/speed` this functions are here to help:

Basically what I have used so far is:

`SDL_FRect` \- Rectangle struct

`SDL_RenderCopyExF` \- For advanced rendering

`SDL_RenderCopyF` \- For simple rendering

This is additional functions I also use:

`SDL_RenderDrawRectF` \- For drawing rectangle

`SDL_RenderFillRectF` \- For filling rectangle

And I believe it is a deception but it feels like float type functions work faster (In fact they might be converting floats to integers I have never looked into a function sources)
> 1 votes

---
Tags: rendering, c, sdl2
---


# Question
Title: Saving .png from render texture results in much darker image
I wrote a script that saves a render texture to a .png.

However, the results are not very good, the .png is always much darker than the Render texture is in Unity. How can I fix this so that there is no attempt at color correction?

Script:

```
 [SerializeField]
     RenderTexture rt;

     [SerializeField]
     string fileName;

     [Button("Save png")]
     public void SavePNG()
     {
         var tex = new Texture2D(rt.width, rt.height);
         RenderTexture.active = rt;
         tex.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
         tex.Apply();

         var path = "Assets/Textures/Rendered textures/" + fileName + ".png";
         File.WriteAllBytes(path, tex.EncodeToPNG());
         Debug.Log("Saved file to: " + path);
     }

```

# Answer
So I managed to get it working thanks to advice from DMGregory. Since sRGB is a readonly field, you have to create a rendertexture in code. Here is my full code:

```
[SerializeField]
RenderTexture rt;

[SerializeField]
Camera cam;

[SerializeField]
string fileName;

[Button("Save png")]
public void SavePNG()
{
    RenderTexture mRt = new RenderTexture(rt.width, rt.height, rt.depth, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB);
    mRt.antiAliasing = rt.antiAliasing;

    var tex = new Texture2D(mRt.width, mRt.height, TextureFormat.ARGB32, false);
    cam.targetTexture = mRt;
    cam.Render();
    RenderTexture.active = mRt;

    tex.ReadPixels(new Rect(0, 0, mRt.width, mRt.height), 0, 0);
    tex.Apply();

    var path = "Assets/Textures/Rendered textures/" + fileName + ".png";
    File.WriteAllBytes(path, tex.EncodeToPNG());
    Debug.Log("Saved file to: " + path);

    DestroyImmediate(tex);

    cam.targetTexture = rt;
    cam.Render();
    RenderTexture.active = rt;

    DestroyImmediate(mRt);
}

```
> 4 votes

# Answer
There are several possible reasons why this could occur. Here are a few.

1. Unity is displaying the real-time rendered image in a different color space then it uses when drawing the PNG, due to some internal color management quirk. If this is the case, DMGregory's comments should point you in the right direction.
2. Your operating system or image editor (it's not clear how you're viewing the PNG) uses a color profile that isn't applied to Unity. If you're on Windows 10, search for the "Color Management" utility and open it to see what color profile your PC is using (if any). If you're viewing the image in an image editing application such as Photoshop, check the application's color profile settings, and see if the image looks different when viewed with different software (e.g. Windows Photos vs Photoshop vs Paint)
3. Your video card drivers apply color correction settings that aren't the same between desktop and 3D. To determine this, you'll have to check your video card drivers.
> 1 votes

# Answer
Select your Render Texture and mark it as SRGB in debug properties:
> 1 votes

---
Tags: unity
---