title: How to make an actual idle game fun?

text:
# Question
Title: How to make an actual idle game fun?
I'm making an Idle RPG with a roguelite element.

I want this game to be a true idle game and not like most other idle games where you have to click an upgrade every 10 seconds to keep progressing. It's also not going to be an incremental game.

I have a very basic demo right now that consists of:

My primary game loop:

* start adventure
* watch as your character kills monsters and gathers resources
* go back to town to use the found resources to become stronger

Every 5/10/25/100 zones you will encounter a boss that is a lot harder to kill 5: mini-boss (again at 15, 35, 45, ...) 10: medium-boss (again at 20, 30, ...) 25: big-boss (again at 50 & 75) 100: major boss

You need to kill 5 monsters in each zone to (automatically) progress to the next zone. There is no going back, the only action you can take is going back to town, which will force you to start again from zone 1. Each zone the monsters become slightly stronger.

At some point during the adventure, the character will run out of health and will be forced to go back to town. At the beginning of the game this is very fast, less than a minute. But as you upgrade your character this takes longer and longer. You can choose to go back at any point, for example: if you have enough resources for an upgrade you want.

There's a store in town that allows you to buy new items with the coins you found from killing monsters.

Each time you restart the adventure you start again from the first zone. I'm not sure this is a good mechanic. It feels really boring to have to progress through all the zones again. I can easily add mechanics to speed this up or even skip it though.

Ideas I'm thinking about:

* Remove health and just allow players to choose when to go back to town when it becomes too slow to kill the monsters
* Add healing items or respawn items that allow you to continue
* Add teleport items that allow you to continue from a specific zone instead of having to start from 1
* Add boss fight items that allow you to fight a boss
* Add items that require you to kill 1 less monsters each zone to progress (min 1)
* Add items that let you skip zones - optionally up to a maximum zone where it would stop working
* Or just plain let players continue where they stopped, or near there?

I've been playing a lot of Clicker Heroes and though it's an "idle" game, you're constantly clicking upgrades, which is what keeps the game fun and engaging.

How would I do this for my game, I actually want to make it so you don't have to interact with it for hours and so it's a true idle game that you can have open while playing other games.

It feels like something important is missing or I'm doing something wrong. Any tips?

# Answer
> 1 votes
Key points for any idle game are;

1. It must be idle and running even when not being interacted with. In a browser setting that means that even when switched to another tab the game should still run.
2. Great art and polish will make any game better and more fun to look at. Polish is like explosions, shaking, lighting and shadows.
3. The best idle games are ones with the least amount of interaction and yet keep the player into it, many values constantly seen going up helps this.

With what you described I would not make many zones, but rather one giant arena, that you can leave to go to town. And so the only mechanic would be walking, the player would be able to walk into the arena and just stand there auto attacking, all kinds of different attacks based on upgrades, walk if they want to, and walk out to town and up to shops when ready. In town magic power could recharge, go up, perhaps indefinitely, and in the arena, the player uses magic power until it is up, and also swings a sword or whatever physical attack. That way something would happen both in town and in the arena, even if they just stood still.

---
Tags: game-design, game-mechanics, game-loop
---


# Question
Title: Aim projectile to intercept moving target from a moving ship
So I have created spaceship shooter game where ships have turrets on them . Now I want those turrets to shoot a moving target meaning I want the projectile to intercept and hit the target that is headed in some direction. Every projectile has its own speed which is constant. Also the ship which has the turret is also moving at a constant speed.

So far I have made this:

```
Vector2 toTarget = targetShip.GlobalPosition - Player.currentShip.GlobalPosition;
Vector2 targetVel = (targetShip.dir.Normalized() * targetShip.speed * delta) - (Player.currentShip.dir.Normalized() * Player.currentShip.speed * delta);
float distance = toTarget.Length();

float a = targetVel.Dot(targetVel) - (projectile.speed * projectile.speed);
float b = 2 * targetVel.Dot(toTarget);
float c = -distance * distance; //toTarget.Dot(toTarget);

float p = -b / (2 * a);
float q = Mathf.Sqrt((b * b) - 4 * a * c) / (2 * a);

float t1 = p - q;
float t2 = p + q;

if (t1 < 0 && t2 < 0)
{
    return;
}

float timeToInterception = 1;
if (t1 > 0 && t2 > 0)
    timeToInterception = Mathf.Min(t1, t2);
//else
    //timeToInterception = Mathf.Max(t1, t2);

Vector2 aimSpot = targetShip.GlobalPosition + targetVel * timeToInterception;
dir = aimSpot - GlobalPosition;
GlobalRotation = Mathf.LerpAngle(GlobalRotation, dir.Angle(), turnRate * delta);

```

The Global Rotation is where the turret will look at and it shoots from its barrel. The method kinda works and sometimes does not work(the projectiles shoot behind the moving target). `Vector2 targetVel = ( targetShip.dir.Normalized() * targetShip.speed * delta) - (Player.currentShip.dir.Normalized() * Player.currentShip.speed * delta);` that part is me calculating velocities I am not sure if its correct...

I commented out the `else` part because the turrets just disappear from my ship if I let that be there and I am also uneducated why.

I've read THIS answer from this forum but I don't understand it especially his edit part. In his edit part I don't understand where to plug that projectile velocity. Also why is my turret disappearing when I uncomment `else` in my code?

If someone can give me some explanation I would be very thankful!

# Answer
> 0 votes
Leading a Target from Howling Moon Software

This tutorial helped me and it works great now! Thanks @DMGregory for the link!

This is how my code looks now:

```
Vector2 toTarget = (targetShip.GlobalPosition) - GlobalPosition;
Vector2 targetVel = (targetShip.dir.Normalized() * targetShip.speed);
Vector2 gunVelocity = (ownerShip.dir.Normalized() * ownerShip.speed);
Vector2 vr = targetVel - gunVelocity;

float t = AimAhead(toTarget, vr);

if (t > 0f)
{
    Vector2 aimPoint = targetShip.GlobalPosition + targetVel * t;
    dir = aimPoint - GlobalPosition;
    GlobalRotation = Mathf.LerpAngle(GlobalRotation, dir.Angle(), turnRate * delta);
}

```

The function AimAhead is the one that calculates everything:

```
float a = vr.Dot(vr) - (projectile.speed * projectile.speed);
float b = 2 * vr.Dot(toTarget);
float c = toTarget.Dot(toTarget);

float det = b * b - 4 * a * c;

if (det > 0f)
{
    return 2 * c / (Mathf.Sqrt(det) - b);
}
else
{
    return -1f;
}

```

# Answer
> 0 votes
You need to add

```
Vector3 projectileDirection = aimPoint - (ownerShip.GlobalPosition + gunVelocity * t);

```

to account for the ship's own speed and direction, so we subtract that speed from the final projectile direction to actually hit the target correctly.

---
Tags: 2d, mathematics, vector, godot, linear-algebra
---


# Question
Title: Converting a real-time game with regeneration into a turn-based one?
I'm wanting to make a text-based game, it'll be about managing families like the sims games.

I'm running into innumerable problems with such. One is how to make it turn-based. I know its technically possible to make a real-time text-based games (MUDs do it all the time), but I think that wouldn't work well here due to the sheer number of possible and elaborate commands. On a side note, I'm thinking I'm going to need a text parser for this to give you an idea.

Anyway, in sims-like games the characters have needs that perpetually decay. These have to be re-filled by using furniture items such as beds and fridges and whatnot. Problem is having something like turns last a second would create FAR too many turns for a single in-game day. I was thinking 15-minute turns would be better, though even that's a bit much. Yeah, its silly that it would take 15 minutes to use the toilet, but what can you do? Really the only reason I'm accepting that is because the characters will either be at work/school or sleeping for 2/3 of the day, so that's only at most about 30 commands you'd have to issue per character per in-game day.

The biggest problem really though is differentiating items. In sims games, items come in different tiers, with each restoring your needs at different rates proportional to how much they cost. With 15 minute turns though, it would seem strange for any items to take more than a turn or two to fully fill a need.

I sort of have the same problem with clothing. Yeah, they don't restore stats, but simply ignoring it didn't really feel quite right. The reason I'm bringing this up is that I solved this by having clothing serve different functions. They're distinguished by expense, which affects how easy it is to build relationship scores (higher normally being better of course). They can also be differentiated by function. Do you want to stay warm or cool? How do you want people to perceive this npc? This actually gives a surprising number of options.

With furniture though, the only thing I could think of is to improve environment score (basically, characters are happier the higher this score is, which is based on the items in the room, along with how clean it is). Skill-building items can be distinguished by their effectiveness, but what about items that just restore needs like chairs, stoves, beds, tubs, etc... What, do I need to make it so they have to take a shower for a full 2 hours if they buy the cheapest one? A really big problem is beds, since spending at least 6 or 7 hours in them should all restore your energy to full. Really, I don't recall that number actually mattering in the real game (I haven't been able to play the sims 2 in over 10 years now though, so I can't remember much of that game's mechanics).

How can I do this? Should I just go with the environment score thing? Should I make it so characters don't have a cap on their needs, so more expensive items can push them well above what cheaper items could? Or maybe just make it hard for characters to full max their needs using 'junk' items? Honestly, that could come in handy for certain things, but that could make it hard to play the game when all your characters can only get their needs up to half full.

I really don't know what to do...

edit: Thinking about things I could apply, maybe there is a few things. I could make objects break more often depending on how cheap they are. In light of that, I could also give items a finite lifespan, so they have to be replaced after a while. That could have the added benefit of fixing the issue these games have where there's not much else to do once you have everything. Items that require skills to use could have a cap to what they can do. In the Sims 2 for example, microwaves and toaster ovens could only cook a small portion of the available meals. If you had a high cooking skill, you needed a proper stove to get the most out of it. There's also skill-building items that I already mentioned. This doesn't help with everything though; what about things like chairs and countertops? Countertops in particular in the Sims 2 only really differed in their aesthetic and environment score. Chairs could have different comfort ratings I guess, maybe?

In line with that, I thought maybe it would be fine for some needs to take literal hours to re-fill. If you're 'fun' is bottomed out, maybe you do need to just spend the entire weekend goofing off to refill it before you have to go to work again Monday.

So this leaves me with items that either don't require a skill, don't build a skill, or recover a skill that shouldn't take long to re-fill. Everything else would only have to differ in environment score unless I implemented a breaking mechanic of some sort. Guess that would be fine for countertops and tables and other such things (though tables I guess could differ in how many people can sit at them, but if you can do that why then buy a table with seating for 8 when you can just buy two small tables with seating for 4 each?).

This is getting annoying...

# Answer
> 2 votes
Maybe the best solution is to break the game down into *actions*, not turns. Whenever a character is not doing something, the clock would pause and wait for you to enter a command. Then time would pass based on the commands you entered.

For example, let's say your household consists of Joe and Sally. At noon, both of them are inactive. You tell Joe to take a shower; with the particular shower and accessories he has, this will take 30 minutes. However, Sally isn't active, so after giving Joe the "shower" command, the time remains at noon until you give Sally a command.

You tell Sally to check the mail, which takes 7 minutes. Since all members of the household are now busy, time advances forward 7 minutes. Now it's 12:07, Sally is done checking the mail, and Joe has 23 minutes left on his shower.

You tell Sally to make lunch, which will take 25 minutes. Then time advances 23 minutes until Joe is done with his shower; now it's 12:30, and Sally has 2 minutes left until she finishes cooking.

Meters would be updated as actions take place. Let's say that you have a smart speaker to play music in the bathroom. Then Joe would have accrued 30 minutes of entertainment while in the shower. At the same time, his food meter would have depleted by 30 minutes. Luckily, Sally's just about done with lunch, so he'll be able to eat soon.

You tell Joe to get dressed, which will take 5 minutes. The clock advances by 2 minutes, to 12:32, then pauses for you to give Sally a new command (since she just finished cooking). There isn't anything important she can do in the three minutes until Joe's ready, so you tell her to wait for 3 minutes. Now it's 12:35, both characters are ready, and you can tell them to eat lunch.

---
Tags: game-design, text-based
---


# Question
Title: Can I render at 50fps instead of 60fps, what are the drawbacks?
When reading on frame rate, I usually encounter the following suggestions:

* render as fast as possible
* render to 60 fps

I want to make a 2d game that runs in slow computers, and i've been surprised by how Cave Story smooth is and that it runs at 50 fps. Maybe. there is not much difference between 50 and 60, but if i dont have a reason to use 60, i'd rather set my frame rate to 50.

I'd like to know the drawbacks of this approach, specially applied to my usecase.

# Answer
*Specifically for display refresh rate*, it's not really much of a choice, it's more of a mandate, and there's no reason not to go for this. The reason is that a lot of underlying technologies / rendering engines opt for syncing with the hardware (vsync) which typically updates at about 60Hz (this figure primarily for historical reasons - it was closely associated with the frequency of AC current in the days of analog television - see PAL / NTSC).

Understand the reason behind vsync: Without it, you may get partway through painting a frame before a hardware update triggers, leading to *tearing* that you may have seen in windowed games. At best, you'll get frames that don't tear, but also don't sync nicely to your monitor's rate, resulting in a less-than-ideal feel.

Also remember that your logic update rate is **not** mandated by your visual update rate; but if your main loop is driven by the display refresh rate, as in e.g. Android, then best make your logic update evenly divisible into display rate, e.g. for 60Hz display refresh, it's easy enough to do logic 1 in 2 frames (30Hz), or even 1 in 3 frames (20Hz).
> 1 votes

# Answer
The drawback of using 50 fps is unless you are running on a variable rate display, there will either be tearing or duplicate frames.

Pixel deliberately picked 50 fps, because back when he was writing games, not all computer monitors ran at 60 fps. Sometimes it was 65, or 75, or even 90.

So by selecting 50, he ensured that it would duplicate frames on all computers, and only someone who ran their monitor at 100 fps would get a perfectly stable frame rate, and no one did that at the time. Even really high end was 90. It's also why the game feels floaty and weird.

Nowadays everyone has flatscreens, and pretty much any of them will take 60fps and do the right thing.
> 1 votes

---
Tags: frame-rate
---


# Question
Title: Why does my Roblox game delete all parts when testing?
I'm working on a Roblox game, but whenever I test it, none of the parts I added in the game display in the Explorer or in the game itself. It works perfectly fine when I view it in the studio, though. Here is the only script that I have running in game:

```
local cam = workspace.CurrentCamera
cam.CameraType = Enum.CameraType.Scriptable
wait(0.1)
cam.CameraType = Enum.CameraType.Scriptable
cam.CFrame = CFrame.new(Vector3.new(-122.911, 43.925, -46.551))
--cam.CFrame.Rotation = CFrame.new(Vector3.new(-31.43, -174.653, 0))

```

Any help is appreciated!

# Answer
The parts were just unanchored
> 0 votes

---
Tags: lua, roblox
---


# Question
Title: Parameter "current->parent" is null, don't see why
I'm using Godot for my current project, and it's been going great; but there's a bug I don't understand. I have a certain very simple script on my title screen:

```
extends Node3D

func _input(event):
    if event.is_action("jump"):
        get_tree().change_scene_to_packed(preload("res://scene/Level.01.tscn"))

```

That's all of it, and its job is to simply change the scene to the preloaded first stage when the jump key is pressed. It does work.

However, I consistently get an error message, referencing C++ code, when I run my program (even though behavior is fine). It's triggered by this script.

```
E 0:00:03:0209   Title Screen.gd:6 @ _input(): Parameter "current->parent" is null.
  <C++ Source>   scene/gui/rich_text_label.cpp:3622 @ pop()
  <Stack Trace>  Title Screen.gd:6 @ _input()

```

If I had to guess, I'd say it was arguing that the current node's parent was not set. That actually almost makes sense, as it's on a root node for the title screen. However, I do not understand why changing a scene would require it to be set in the first place. I'm not asking about the parent.

I don't like to leave warnings and errors hanging, even if they don't seem to be causing any problems. Is this a quirk of Godot, or am I looking at an actual error in my code?

# Answer
Found it, thanks to @Mangata. It *is* a weird bug.

My help boxes had default text using \[dropcaps\] on a single letter, terminated immediately afterward; but the terminator seemed to fail to register that there was a parent. Harmless enough but non-zero, so I'll be testing and reporting it.

Additionally, it seems to have nothing to do with my title.

To be specific, the problem is that Godot is attempting to pop() a bbcode tag, but is not yet seeing one, so it is exiting with an error message but continuing business as usual. It should see one, and does in fact function correctly for dropcaps, so this is just a weird collection issue, if I had to guess.
> 4 votes

---
Tags: godot, levels, gdscript, tree, hierarchy
---


# Question
Title: Unity ObjectPool<T> CountActive is not decreasing after a destroy is called
I have made a loop to spawn and despawn a basic sphere gameobject. The issue is that when spawning goes over the max size, it does not decrease the `ActiveCount` when removed. Is this a Unity bug or am I missing something?

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

public class Monopooltest : MonoBehaviour {
  public int capacity = 1;
  public int maxSize = 3;
  public ObjectPool<GameObject> pool;
  public List<GameObject> activeObjs;
  public int active;
  public int inactive;
  private void Update() {
    active = pool.CountActive;
    inactive = pool.CountInactive;
  }
  public GameObject prefab;

  protected Coroutine loopCo;
  public IEnumerator Loop() {
    while(true) {
      Spawn(5);
      yield return null;
      Despawn(5);
      yield return null;
    }
  }

  private void Awake() {
    pool = new(
      () => Instantiate(prefab),
      (obj) => { obj.SetActive(true); activeObjs.Add(obj); },
      (obj) => { obj.SetActive(false); activeObjs.Remove(obj);},
      (obj) => Destroy(obj),
      true,
      capacity,
      maxSize
    );
  }
  private void OnEnable() {
    loopCo = StartCoroutine(Loop());
  }
  private void OnDisable() {
    StopCoroutine(loopCo);
    while(activeObjs.Count > 0) {
      Despawn();
    }
    loopCo = null;
  }
  void Spawn() {
    pool.Get();
  }
  public void Despawn() {
    var obj = activeObjs.Pop();
    pool.Release(obj);
  }
  void Spawn(int num) {
    for(int i = 0; i < num; i++) {
      Spawn();
    }
  }
  void Despawn(int num) {
    for(int i = 0; i < num; i++) {
      Despawn();
    }
  }
}

```

# Answer
You can find the source code for ObjectPool here.

Taking a look at the code, we can see `CountAll` (from which `CountActive` is computed on demand) is incremented when a new instance of the pooled type is created, but never decremented anywhere, even when `m_ActionOnDestroy` is invoked.

We could fix this with a one-line change:

```
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public void Release(T element)
    {
        if (m_CollectionCheck && (m_List.Count > 0 || m_FreshlyReleased != null))
        {
            if (ReferenceEquals(element, m_FreshlyReleased)) {
                throw new InvalidOperationException("Trying to release an object that has already been released to the pool.");
            }
            for (int i = 0; i < m_List.Count; i++)
            {
                if (ReferenceEquals(element, m_List[i]))
                    throw new InvalidOperationException("Trying to release an object that has already been released to the pool.");
            }
        }

        m_ActionOnRelease?.Invoke(element);
        if(m_FreshlyReleased == null)
        {
            m_FreshlyReleased = element;
        }
        else if (CountInactive < m_MaxSize)
        {
            m_List.Add(element);
        }
        else
        {
            m_ActionOnDestroy?.Invoke(element);
            CountAll--;   // Fix to permanent count increase above max size
        }
    }

```

So yes, this looks like a Unity bug worth reporting.

I *could* see this being argued as a deliberate API design choice (albeit not one I'd agree with) along one of three lines:

* The pool can't make any guarantees about what happens to destroyed objects. *It* doesn't hold a reference to them, but others might, so far all it kmows they're still taking up memory and haven't been garbage collected. So, reducing `CountAll`/`CountActive` in this case could be a misleading signal, and they choose to report the most pessimistic/conservative value they can guarantee is not an under-count.
* Hitting the max size is an exceptional case that should be avoided in an app that uses the pool correctly. When objects *are* created above the max, having `CountAll` (and by extension `CountActive` which is calculated from it) stay persistently high afterward makes this issue easy to detect, even after a transient spike of creation and releasing passes. It could be argued the fix above masks the symptom of the issue without addressing the root problem of spawning over max in the first place.

Okay, but then just add a `CountDestroyed` and subtract that when getting `CountActive`? But now we've increased the memory footprint of every pool to support an out-of-contract use case. Users can implement their own counting in `actionOnDestroy` if they need an accurate count in that case.
* Or maybe either of these fixed is *just* enough to break inlining in some cases and add a measurable cost in performance-critical code even when the max isn't hit? That would be unfortunate.

I don't *agree* with these arguments, but they're pushback you could conceivably get to proposing the fix above — and the only reasons I can imagine it hasn't already been fixed. I'd argue that at the very least, this API design is misleading, and `CountActive` should say `CountActiveOrDestroyed` or explicitly call out this case in the documentation, if a fix like the one above were to be rejected.
> 1 votes

# Answer
I manage my problem about Unity's Object Pooling system with a way I don't like too much. The code snippet below.

```
private void GenerateByAid() {
    //The number of pooled objects which are in the list
    List<EnemyBlock> li = new List<EnemyBlock>();
    for (int i = 0; i < _poolMax; i++) {
        EnemyBlock eb = _pool.Get();
        li.Add(eb);
    }

    for (int i = li.Count - 1; i >= 0; i--) {
        li[i].PushBack2Pool();
        li.RemoveAt(i);
    }
    Debug.Log("List range : " +  li.Count);
}

private void GenarateByTime() {
    //Take instance from the pool in period
    _generatorTimeMeter += Time.deltaTime;
    if (_generatorTimeMeter > _generationTimeInterval) {

        _pool.Get();
        _generatorTimeMeter = 0;
    }
}

void Update() {
    GenarateByTime();

    _numberOfPooled = _pool.CountAll;
    _numberOfActive = _pool.CountActive;
    _numberOfInactive = _pool.CountInactive;
}

void Start() {
    _pool = new ObjectPool<EnemyBlock>(
        CreateElement,
        GetFromPool,
        Return2Pool,
        DestroyWhenOverCapacity,
        false,
        _poolCount,
        _poolMax);

    GenerateByAid();

    _numberOfPooled = _pool.CountAll;
    _numberOfActive = _pool.CountActive;
    _numberOfInactive = _pool.CountInactive;
}

```

This gives me the correct numbers and also I can generate them at once and store them as `gameObject.setActive(false)` before I use.
> 0 votes

---
Tags: unity, c#, object-pools
---


# Question
Title: How can I fix a 7 Days To Die A21 vehicle modding error?
I am trying to make a mod in 7 Days To Die A21 that adds in vehicles, and I have hit a bit of a snag. Whenever the vehicle gets spawned in, it throws a ton of red text.

The error reads "NullReferenceException: Object reference not set to an instance of an object".

When I check the actual log file, it says:

```
    NullReferenceException: Object reference not set to an instance of an object
  at EntityVehicle.Init (System.Int32 _entityClass) [0x00070] in <d7dcfa4979674f179c13273f8b30b551>:0
  at EntityDriveable.Init (System.Int32 _entityClass) [0x00000] in <d7dcfa4979674f179c13273f8b30b551>:0
  at EntityFactory.CreateEntity (EntityCreationData _ecd) [0x004c2] in <d7dcfa4979674f179c13273f8b30b551>:0
  at EntityFactory.CreateEntity (System.Int32 _et, System.Int32 _id, ItemValue _itemValue, System.Int32 _count, UnityEngine.Vector3 _transformPos, UnityEngine.Vector3 _transformRot, System.Single _lifetime, System.Int32 _playerId, System.String _skinName, System.Int32 _spawnById, System.String _spawnByName) [0x0001b] in <d7dcfa4979674f179c13273f8b30b551>:0
  at EntityFactory.CreateEntity (System.Int32 _et, System.Int32 _id, UnityEngine.Vector3 _transformPos, UnityEngine.Vector3 _rotation) [0x0000c] in <d7dcfa4979674f179c13273f8b30b551>:0
  at EntityFactory.CreateEntity (System.Int32 _et, UnityEngine.Vector3 _transformPos, UnityEngine.Vector3 _rotation) [0x00000] in <d7dcfa4979674f179c13273f8b30b551>:0
  at ItemActionSpawnVehicle.ExecuteAction (ItemActionData _actionData, System.Boolean _bReleased) [0x0016f] in <d7dcfa4979674f179c13273f8b30b551>:0
  at ItemClass.ExecuteAction (System.Int32 _actionIdx, ItemInventoryData _data, System.Boolean _bReleased, PlayerActionsLocal _playerActions) [0x0055b] in <d7dcfa4979674f179c13273f8b30b551>:0
  at Inventory.Execute (System.Int32 _actionIdx, System.Boolean _bReleased, PlayerActionsLocal _playerActions) [0x00037] in <d7dcfa4979674f179c13273f8b30b551>:0
  at PlayerMoveController.Update () [0x026b0] in <d7dcfa4979674f179c13273f8b30b551>:0

NullReferenceException: Object reference not set to an instance of an object
  at EntityVehicle.CheckForOutOfWorld () [0x00171] in <d7dcfa4979674f179c13273f8b30b551>:0
  at EntityVehicle.PhysicsFixedUpdate () [0x0032a] in <d7dcfa4979674f179c13273f8b30b551>:0
  at EntityVehicle.FixedUpdate () [0x00000] in <d7dcfa4979674f179c13273f8b30b551>:0

```

And it eventually repeats.

I have tried built in game models, it threw the same error, even when I copy the actual XML code of the vehicle over to mine. I used someone else's model temporary, and it kept doing it again. When I copied that same person's model, code, and inserted it all directly into my mod, without modifying any part of it, it ran, but now I want to actually use my model, sounds, code, and it's being stubborn.

I set up my prefab for the vehicle exactly how it was done here: https://www.youtube.com/watch?v=1qlX15Kste0, but the issue still persists. I feel like I am overlooking an very important detail, but I'm not sure what it is.

Edit: I fixed the previous error. Now I think it's a physics error because it just flies. How do I fix this?

# Answer
I fixed this issue by changing:

```
<property class="chassis">
    <property name="class" value="Chassis"/>
    <property name="display_name" value="chassis"/>
    <property name="slot_type" value="chassis"/>
    <property name="mesh" value="Body"/>
    <property name="transform" value="Mesh/Body"/>
    <property name="paint" value="Body"/>
</property>

```

to:

```
<property class="chassis">
    <property name="class" value="Chassis"/>
    <property name="display_name" value="chassis"/>
    <property name="slot_type" value="chassis"/>
    <property name="mesh" value="m26pershingeagle7"/>
    <property name="transform" value="Mesh/car_mesh/m26pershingeagle7"/>
    <property name="paint" value="m26pershingeagle7"/>
</property>

```
> 1 votes

---
Tags: modding
---


# Question
Title: How to make TextMeshProUGUI truncate the left part (beginning) of a line?
I'm trying to display file names including their directory. When the file path gets too long for the text box, I want to align it right, because the filename is more important than the directory.

I can change the alignment, but the text is still truncated on the right hand side, instead of culling the beginning of the line. Is there a way to do that without using masks?

I'm also having a hard time detecting overflow. For some reason it is only set to true if I have wrapping enabled, which I don't want.

# Answer
The method with

```
x = characterInfo[i].info.vertex_BL.position.x;

```

failed for some rect settings, so I fell back to @DMGregory's xAdvance method. I did modify it to be used with input fields as well:

```
static void truncateText(TMP_InputField inputField){
    TMP_Text textField = inputField.textComponent;
    string text = textField.text;
    int lastIndex = text.Length - 1;
    if (lastIndex < 10) //isNullOrEmpty as well as isNullOrWhitespace do not return true reliably
    {
        return; // 8 chars always fit
    }
    // force it to calculate the character layout.
    textField.ForceMeshUpdate();
    TMP_TextInfo textInfo = textField.textInfo;

    // Get the range between the first and last character in the line.
    float start = textInfo.characterInfo[0].origin;
    float end = textInfo.characterInfo[lastIndex].xAdvance;
    float budget = textField.rectTransform.rect.width;

    int i;
    for (i = lastIndex; i > -1; i--)
    {
        TMP_CharacterInfo info = textInfo.characterInfo[i];
        start = info.origin;
        if (end - start > budget) break;
    }

    // Take only characters to the right of our first overflow.
    inputField.SetTextWithoutNotify(text.Substring(i + 1));
}

```

This method assumes, you have already set the text of the input field's text component and stored it somewhere, if you ever need it again. Also: don't forget to restore the original text, if a user clicks into the field (On Select)
> 1 votes

# Answer
We could do this with a script that takes the text on behalf of the TextMeshPro, tries to layout the full string, and if it doesn't fit, takes only the subset of characters at the end of the string that does fit, and passes those on to the TextMeshPro instead.

```
using UnityEngine;
using TMPro;

[RequireComponent(typeof(TMP_Text))]
public class LeftElidedText : MonoBehaviour
{
    // Cache the full text, so our truncation doesn't destroy our only copy.
    [SerializeField]
    string _text;
    public string text {
        get => _text;

        set {
            if (_text == value) return;

            _text = value;
            UpdateText();
        }
    }

    [SerializeField, HideInInspector]
    TMP_Text _textMesh;

    void UpdateText() {
        if (string.IsNullOrWhiteSpace(_text)) {
            _textMesh.text = "";
            return;
        }

        // Apply the whole text to the TextMeshPro and
        // force it to calculate the character layout.
        _textMesh.text = _text;
        _textMesh.ForceMeshUpdate();
        var info = _textMesh.textInfo;

        // Get the range between the first and last character in the line.
        var start = info.characterInfo[0].origin;
        var last = info.lineInfo[0].lastCharacterIndex;
        var end = info.characterInfo[last].xAdvance;

        // Compare against our space budget in the Text's bounding rectangle.
        var budget = _textMesh.rectTransform.rect.width;

        // If the text fits already, accept it as is.
        if (end - start <= budget) return;

        // Otherwise, scan back until we find the first character that overflows.
        int i;
        for (i = last; i >= 0; i--) {
            var c = info.characterInfo[i];
            start = c.origin;
            if (end - start > budget) break;
        }

        // Take only characters to the right of our first overflow.
        _textMesh.text = _text.Substring(i + 1);
    }

    // Handle invoking the setter in-editor.
#if UNITY_EDITOR
    string _previousText;
    void OnValidate() {
        TryGetComponent(out _textMesh);

        if (_text != _previousText) {
            UpdateText();
        }
        _previousText = _text;
    }
#endif
}

```
> 1 votes

# Answer
I would recommend using this method instead, which is for measuring a string without setting it:

> Vector2 TMP\_Text.GetPreferredValues(...)

https://docs.unity3d.com/Packages/com.unity.textmeshpro@3.2/api/TMPro.TMP\_Text.GetPreferredValues.html?q=preferred
> 1 votes

---
Tags: unity, unity-ui, text-mesh-pro
---


# Question
Title: Intuitively, why is 3.5 the average (mean) roll of a six-sided die?
Every page I could find on the web that answers this question explains it with Expected Value statistic probability math.

$$(1 * \frac 16) + (2 * \frac 16) + (3 * \frac16) + (4 * \frac16) + (5 * \frac16) + (6 * \frac16)$$

O...K... so we have a mathematical formula that tells us the average/mean/expected value but can't we explain it more simply? We have one die with six sides and every time you roll it, one of those six sides has the possibility of being rolled. Without math, why is the Expected Value 3.5?

# Answer
First of all, I wrote a simple program to verify with empirical data that on average we do get a roll of 3.5. (As you tweak the TOTAL\_ROLLS closer to 0, the average becomes increasingly unreliable. Although, even at 100 it was still always close to 3.5. But at 10, the average was all over the place.)

```
/*
 * Testing mean of 3.5 for single die roll.
 */

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define TOTAL_ROLLS 100000

int
main()
{
    int roll_total = 0;

    srand(time(0));

    for (int i = 0; i < TOTAL_ROLLS; ++i)
    {
        int r = rand() % 6;
        roll_total += r + 1;
    }

    double mean = roll_total / (double) TOTAL_ROLLS;

    printf("mean: %f\n", mean);

    return(0);
}

```

Running it few times does in fact verify:

```
mean: 3.496850
mean: 3.502040
mean: 3.497710
mean: 3.497710
mean: 3.503410
mean: 3.494730
mean: 3.494730

```

Now we have a mathematical formula (given in the question) and a program that both tell us the average is 3.5. But WHY?!

## The Answer

The most simple explanation I could come up with is represented in the following image. We have 3 die on the left: 1, 2, 3. And we have 3 die on the right: 4, 5, 6. So what number is exactly in the middle? **3.5**!
> 7 votes

# Answer
I think the most intuitive answer is to simply sum up the dots on each side and divide by the number of sides:

```
sum(1,2,3,4,5,6)/6 = 3.5

```

That's the basic meaning of an average (measure of central tendency). And in the case you are describing, it is true that 3.5 falls between 3 and 4, i.e. 3.5. However, if you have some other variations of dots on each side of the die (think of an unfair die), the average may not be in the middle, e.g.:

```
sum(1,1,2,3,5,6)/6 = 3

```

The true middle however, can always be found with the `median`.

I thought adding a plot that shows how these two long run averages converge to the calculated mean values would be helpful too.
> 1 votes

---
Tags: mathematics, random
---


# Question
Title: Unity Tilemap.BoxFill is not filling correctly
So I have a tilemap that already has tiles on it. What I want is to clear it all out and create a solid rectangle of one tile, with which the rest of the monobehaviour will 'carve out' to create a cave complex.

So in my Start() I begin with:

```
tilemap.ClearAllTiles();

tilemap.BoxFill(Vector3Int.zero, wallTile, -mapSize, -mapSize, mapSize, mapSize);

```

Let's say mapSize is 8, and "tilemap" is a reference to a Tilemap that previously had some tiles on it. I expect to see all the prior tiles removed, and a new filled area of "wallTile" that goes from -8,-8 to 8,8

Instead I get a single tile at 0,0,0 and that's it.

If I leave out the ClearAllTiles(), it does nothing; the old tiles remain, and no new tiles are placed at all. The only way it seems to do anything is if the tilemap was empty before in the scene, but I need to work with a tilemap that was previously in use.

Any suggestions on what I'm doing wrong?

# Answer
So turns out the tilemap's bounds were being reset to nothing. Any attempt to fill outside of the bounds will fail, and trying to fill on top of a cell that's got a tile will also fail.

The work-around was to clear the tiles, place a tile at the upper left and bottom right of the area I was going to fill ( which would resize the bounds). Then I could box fill the tilemap. There doesn't seem to be a way to enlarge the bounds of the tilemap any other way.
> 2 votes

# Answer
```
_tilemapFlour.ClearAllTiles();
_tilemapFlour.origin = Vector3Int.zero;
_tilemapFlour.size = new Vector3Int(_size, _size);
var endPosition = _tilemapFlour.origin + _tilemapFlour.size;
_tilemapFlour.BoxFill(endPosition, _tileBase, _tilemapFlour.origin.x, _tilemapFlour.origin.y, endPosition.x, endPosition.y);
_tilemapFlour.ResizeBounds();

```
> 0 votes

---
Tags: unity, tilemap
---


# Question
Title: Is it possible to do conditional compilation in Godot at this time, via export settings?
In a number of other engines I've worked with, including Unreal and Unity, there's been support for not only preprocessor commands, but conditional compilation based on platform. As an example, in Unity, I could do this:

```
#if UNITY_STANDALONE_WIN

```

And, the following code, until the `#endif`, would only be included if I was compiling for the Windows platform. This is very similar to building with something like `gcc` and including the `-D` flag for directives, so it isn't new. Additionally, I've noted that when compiling on Godot, I can include the same platform multiple times, allowing for variation.

Suppose I wanted to compile a demo version of my game, using the Godot engine, which only included the first few levels; and a full, premium version, which included the whole thing. I would want both to have feature parity. If I could detect which export template I was using, I could automatically cut the demo off at the correct point, and build the premium version for the full game, at the same time, by selecting "Export All..." compared to manual changes or multiple projects, that's a big win for me.

Currently I'm using the non-Mono version of Godot, and GDScript with occasional GDExtensions C++. GDScripts fundamental design principles preclude a precompiler like C's, but changing a field based on export settings would be more than enough for me. I'm open to C# answers, but I ultimately need to get it to work with GDScript. Can someone help me figure out how to change values based on export template so I can be selective when building my code?

# Answer
> 1 votes
Searching for "Godot conditional compilation" led me to this GitHub discussion proposing the feature, though to less-than-rave reviews.

In the comments, someone linked a proposal to preprocess scripts based on feature tags, which is currently "Open", though similar issues have been closed in the past.

Another user, dalexeev, commented that they have made a preprocessor plugin that performs this function. I have not used this and cannot vouch for it personally, though it's been updated within the past 6 months, so it seems to be relatively recently maintained.

---
Tags: godot, cross-platform, gdscript, build-process, settings
---


title: My collisions won't work

text:
# Question
Title: My collisions won't work
I have been banging my head against this one for a while. I am trying to implement a pickup mechanic, using OnTriggerEnter2D, however I cannot get it to work, my player just runs past the coin.

Code:

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

public class gemMovement : MonoBehaviour
{
    // variables
    private Vector2 startPosition;
    private Vector2 endPosition;
    private int speed = 4;
    private float maxDistance = 0.15f;
    private int count = 0;
    public TextMeshProUGUI countText;

    private void Start()
    {
        startPosition = transform.position;
        endPosition = transform.position;
    }

    private void Update()
    {
        endPosition.y = startPosition.y + (maxDistance * Mathf.Sin(Time.time * speed));
        transform.position = endPosition;
    }

    void SetCountText()
    {
        countText.text = "Count: " + count.ToString();
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.CompareTag("Pickup"))
        {
            Debug.Log("Pickup");

            other.gameObject.SetActive(false);
            count++;

            SetCountText();
        }
    }
}

```

A little bit of help would be very much appreciated, thank you.

# Answer
> 2 votes
You said that you used `OnTriggerEnter2D()` in your description, but your code actually uses `OnTriggerEnter()`, which isn't compatible with 2D colliders.

# Answer
> 2 votes
This seems like a rather easy fix. On your `gemMovement` you check if the other tag is `Pickup` but if a collision happens, this is going to be the player. So either the method should go as it is on the player or you need to check if the coin is colliding with the player.

You probably do not want to deactivate the player on collision as well.

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


# Question
Title: Can somebody please explain why my illumination is inconsistent?
100% not a graphics guy here.

Problem Demonstration.

Randomly discovered this when showing the project to a friend after not touching it for over a month (been working on other stuffs). First I noticed that either the flashlight was super dim, or the main material of the room was a tad darker than it should be: things weren't being illuminated enough by it. Then I noticed that in this small pillar setup the spotlights aimed down at the pillars weren't working, at all. Upon tinkering I discovered that they were working after all, but only at specific ranges/distances/angles/whatevers. No idea what triggered this: the first backup without this glitch was made in the middle of some basic level design work. The project uses built-in RP, Unity 2021.3 (originated in 29, updating to 31 changed nothing).

I would love to save this project. Since it is to become much bigger (hopefully), in case this happens again I need a better solution (and understanding of wtf happened) than just carefully rebuilding everything one asset at a time in a new project. Without one, I might as well switch engines now, but I'm trying to avoid that for this one last Unity project because time and laziness.

* As far as I can tell, all project settings between that one perfectly working backup and the latest messed up version are identical;
* Material settings are identical;
* Point lights work as expected, I believe, but as was discovered with the flashlight, it seems lighting in general isn't quite working as it was set up. Kinda like what happens when you switch to URP from setting everything up in built-in RP;
* Newly created spot lights in this project work in the same flickery fashion;
* Exporting the entire project and importing it into a new one doesn't help, so I assume the problem is tied to one of the assets..? However --\>
* Removing all optional packages didn't help;
* Removing all other objects from the hierarchy didn't help;
* I assume I am missing something stupidly obvious and ready to absorb the knawledge (☝).

**EDIT**. Nope, no idea. I ended up putting a band-aid on it: adjusted the ranges to random values at which the lights randomly start working (works fine for now but would be very annoying to create new things with this bug around). About time I switched to Unreal anyway: not interested in paying Unity taxes. Big thanks to everyone who tried to help!

# Answer
> 0 votes
The solution is to put a band-aid on it temporarily: either avoid using spot lights or adjust their ranges to values where they randonly start working (as long as the objects/lights don't move around you'll be fine), and then either keep working with this in mind or switch to Godot or Unreal.

---
Tags: unity, graphics, lighting
---


# Question
Title: How can I make colliders-only visible in Godot?
Specifically, I'm looking for any way to see a collision-only item from a Mesh Library in a GridMap. (The tag says "tile map", which it technically isn't; but there's no option for a grid map and this seems close enough.) There's no mesh to draw, so I'm left guessing, or discovering by trial and error, where it is. Then I make a note and adjust it or remove it before my next run. Clearly this isn't the most efficient way of working.

If I could get the collision meshes alone rendered in the scene, this would make it trivial to use.

# Answer
Seems I actually can find invisible meshes relatively easily by switching display mode to "Display Overdraw", which is great. There's still a little guesswork as to where to look, but that's no big deal.
> 1 votes

---
Tags: collision-detection, tilemap, godot, meshcollider, visibility-determination
---


# Question
Title: libgdx resize works fine, except on setWinowedMode
I'm a bit baffled by a specific bit of behaviour in LibGDX.

The resize method of my screens is as simple as can be, because right now I don't need anything more:

```
    override fun resize(width: Int, height: Int) {
        log.info { "Window resize to $width x $height" }
        stage.viewport.update(width, height, true)
    }

```

It works perfectly, *if I resize the window manually*. If I however change the size programmatically by calling setWindowedMode(), the blasted thing doesn't seem to do *anything*. I can clearly see in the log that it's being executed, that much is fine, but my viewport doesn't care. If I go and manually change the size of the window by whatever amount, everything goes "plop" and falls into place.

Sooo... Why is this not working when I call setWindowedMode()? It feels like resize is getting called too early in the event queue and that therefore the changes have no effect, but that's purely speculation. What am I supposed to use instead or in addition of setWindowedMode() to make the viewport do its job?

# Answer
Ok, it was an oversight on my part. I had an old line of code lying around from back when I experimented, that updated the viewport with the old dimensions after `resize()` was called when I changed the setting in the menu.
> 1 votes

---
Tags: libgdx
---


# Question
Title: Efficiently Computing a Composed Affine Transform
Given two affine transformations in 3D (i.e., TRS transforms) called T0 and T1, each represented by a translation vector (t), quaternion (r) and scaling vector (s).

Now, say that I want to compute the composed transform, i.e., creating the single transform that corresponds to T1(T0(\*)).

One (naive) way is to simply setup the 3x4 matrix corresponding to this transform, extract the translation vector and combined scaling/rotation matrix and then use polar decomposition to split that matrix into the scaling vector and quaternion. This decomposition however is rather costly computation-wise, is it possible to compute the new scaling vector and quaternion without this operation?

# Answer
Unfortunately this is not possible to do in the most general case. That's because the set of TRS transformations is not closed under composition. Applying one {Translation, Rotation, axis-aligned Scale} transformation followed by another may result in a transformation this is not itself expressible as a single {Translation, Rotation, axis-aligned Scale} trio.

The problem cases arise whenever these two criteria are *both* met:

* the first/inner transformation has a rotation that's not expressible as a series of 90° rotations about the coordinate axes
* AND the second/outer transformation has a non-uniform scale

This combination results in a net scale that is diagonal to the object's local coordinate axes, so it can't be expressed with a single axis-aligned scale vector.

It can still be expressed as a matrix, since matrix transformations are more general than TRS transformations (able to include shears). The set of matrix transformations *is* closed under composition (matrix multiplication).

This is the reason why in Unity's transformation API, there are properties for "local" position, rotation, and scale, but for "global" there's only position and rotation. The global scale property is called `lossyScale` to communicate that it can no longer be guaranteed to fully represent the scaling applied when multiple transformations are stacked.

If you can guarantee that the later transform(s) will only ever apply uniform scale, then you can compose the transformations like so:

$$ \begin{align} \bf T\_0: & \vec t\_0 \quad & \bf T\_1: &\vec t\_1\\ &\bf r\_0 & & \bf r\_1\\ & \vec s\_0 & & \vec s\_1 = \begin{bmatrix}u\\u\\u\end{bmatrix} \end{align} $$

$$ \begin{align} \bf T\_c &= \bf T\_1 \circ \bf T\_0\\ \vec t\_c &= \vec t\_1 + u\left(\bf r\_1 \circ \vec t\_0 \right) \\ \bf r\_c &= \bf r\_1 \circ \bf r\_0\\ \vec s\_c &= u \vec s\_0 \end{align} $$

This special case (non-uniform scales only at the leaf level) is one we often want to enforce in game object transformation hierarchies for other reasons anyway (eg. skeletal animations or physics), so you may find it's not too onerous to stick to this subset and benefit from easy TRS composition producing TRS outputs.
> 2 votes

---
Tags: transformation
---


# Question
Title: Implementing building structures in a text-based game?
Basically, I'm trying to make a text-bases sims-like game. Obviously, making a text version of a graphical game while keeping it actually interesting to play is proving quite difficult.

One of my biggest problems is handling building. Initially, I was thinking of just letting furniture be purchased and just assume the house had room for everything. However, I was hoping to incorporate something equivalent to the legacy and apocalypse challenges for The Sims 2 (they were the ways I preferred to play the game). Problem is, these come with building restrictions that would be hard to ignore.

For instance, the 'middle of nowhere' 'handicap' for the legacy challenge forbids you from placing more than 2 segments of a construction per day. Meaning only 2 wall segments, windows, doors, etc, IN TOTAL per day. It also applies a one-furniture per day restriction, but not having that other feature I think nerfs the handicap too much. The apocalypse challenge is worse, because its NOT an optional feature. No structure in this challenge can be more than 8x8 tiles in size. You are allowed to build upper floors and basements though. I didn't see much point in implementing that latter feature obviously, but as I said it would be hard to ignore this. Its basically the entire part of the 'politics' restriction (a section of rules that must be followed until a character reaches the top of the politics career).

I'm starting to think this thing being 100% text-based is simply not doable. Perhaps it would be better for me to actually have some graphical element to the thing; at least make it so you can plan out structures. Thinking about that, maybe using pygame wouldn't be such a bad idea. I've had innumerable issues with it, but honestly it would probably do fine for a turn-based game. Also, it would make the whole text-based thing easier; I could just erase text and replace it rather than using the 'print' command to go to the next screen. This would also give me the option of having buttons and even using the mouse, which could be handy honestly. Of course, if I do that, what's the point of making the thing text-based? Why not just have it all be graphical? Outside of the fact that I could never hope to make enough assets for such a game even if I could.

Do I need to just add some graphical elements to this thing to some extent? Is there a way I can still do something like this using just text? Could I replace these mechanics with something else that would allow me to dodge having to put BUILDING ELEMENTS IN A TEXT GAME? Maybe I could come up with something else for the politics restriction? Or maybe just change it out for another career with a completely different theme? And what about that legacy handicap? Should I just not implement that? That would be easy, though I would prefer to put another handicap in there to replace it. You can still look up the rules for the Sims 2 Legacy and Apocalypse Challenges if you need to see what they already require. Note that they're not perfectly identical to the sims 3 and sims 4 equivalents, due the games not being identical in mechanics (obviously).

edit: If you don't want to look up the rules, I'll try to summarize things as best I can. In the Legacy challenge for The Sims 2, you're trying to play the game for 10 generations, while trying to accomplish various achievements (for lack of a better word) along the way. Handicaps are optional rules you can choose to follow in exchange for more points in the end. Handicaps always place some sort of restriction on your household in exchange for these extra points. Some handicaps include things like all sims must be fit before they reach adulthood and be obsessed with fitness, they must all share a hobby, you may only issue up to 3 commands to your characters per day, or the most extreme of all you have to play by the apocalypse challenge rules at the same time! If it matters, I was thinking of adding more of my own (namely a handicap called 'infiltration', where every generation must be born via alien abduction, a challenge that the original game doesn't even allow because sims born this way can't be impregnated by aliens themselves, making the chain impossible to continue).

Regarding the apocalypse challenge, it works by locking most of the game's features behind careers. These can include everything from certain social actions to most often furniture items. You unlock things by reaching the top of the game's various careers. The goal is to reach the top of every career and unlock everything. The problem with replacing the restrictions with the politics career is that virtually nothing is allowed at the start already (mainly due to the sheer number of new careers added by the expansions, the challenge was actually made before any of the expansions came out, and only became harder as a consequence). To give you an idea, you're straight not allowed to purchase furniture from most of the categories (for instance, the only items you can purchase that can fill the hygiene need are sinks), you can only use the lowest tiers of certain items, you can't even marry until you've completed at least one career. Point is, literally removing anything else would actually render the challenge impossible to complete. You literally have only the bare necessities and nothing more to complete this challenge. Essentially, politics would have to be implemented as-is, or the whole career just cut from the game in general. Obviously, I'm at an impasse with this.

edit2: thinking about it, I could just remove the handicap for the Legacy mode. This however doesn't solve the problem with the Apocalypse challenge. Still, either way I need to come up with a way to do this in a purely text-based game, add graphics, or find some alternative I can replace it with.

edit3: Thinking about it again, perhaps this simply isn't the best sort of game for this sort of challenge. Why not just make a game specifically designed around rebuilding the world after an apocalypse? This does remove an entire planned game mode from my game, though I was thinking of adding other challenges anyway. It also removes one of the few handicaps that offers more than 1 point to the final score for the Legacy challenge, but oh well. Guess I'll have to add 4 points worth of other handicaps to replace it, and everything will be the effectively the same. Or maybe I could just ignore it entirely. My game won't be a complete clone of the sims 2 anyway, so its not like I'm not having to ditch a few other handicaps and rules anyway.

edit4:Looking over the handicaps for the Legacy challenge, I wouldn't be able to incorporate more than half of them without having buildings. A particularly problematic one is the 'hypochondriac' handicap, which requires one, among many things, to quarantine a sick sim in a single room for a whole week. Not only would I need buildings for this, I would also need a freaking pathfinding algorthm.

I'm beginning to question if this can even be done. It appears the legacy challenge actually needs buildings more than the freaking apocalypse challenge. Maybe I need to make my game and come up with its own equivalent to the legacy and apocalypse challenges. I would need to fully replicate all the functionality of the Sims 2 for me to use these challenges as-is. Aside for the legal issues this may cause (not that I was planning on releasing my game for profit, actually I was just making it so I could play the Sims 2 again). Its not possible to fully replicate all its functions in a text game anyway, and looking over strategy guides the game had far, far more features than I was aware of when I played it. I probably only explored less than half of that game's features despite playing it for years.

Sorry for the tangent, guess I need to just make my own game without trying to figure out how to implement everything from its inspiration, and then come up with my own game modes that are actually fully compatible with it.

# Answer
> 1 votes
The big advantage of text-based games is that most of the gameplay happens in the player's head. That means you can often abstract complex game mechanics to a point where they become trivial to design and implement, without it affecting the players suspension of disbelieve.

For example, let's take the furniture building system. How could this mechanic be described in an abstract way?

* The player can acquire furniture
* The dwellings of the player only has a limited amount of space
* Each acquired furniture takes up space, which means that the amount of furniture the player can own is limited.

In a visual game, you would implement that with a 2d (or even 3d) space where players move and place furniture items that must not overlap with each other or with walls. The player is going to need a solid UI to place those things. Pathfinding and adjacency effects might have to be considered. This can be a feature that can get pretty complex to design and implement. And we haven't even talked about the art assets yet.

But in a text-based game, you can get away with a much simpler implementation. You can make "living space" simply a scalar resource.

* The dwellings of the player has x units of space
* Each piece of furniture takes up y units of space.
* By comparing x and y, you can calculate a "crampedness factor" that can be used to affect the sim's quality of life.

Example:

```
You are living in a tiny (25 m²) apartment.

In your apartment you have:
* Small Bed (2 m²)
* Medium wardrobe (2 m²)
* Wilting Houseplant (1 m²)
* High-tech refrigerator (1 m²)
* Cook-o-matic 2000 stove (1 m²)
* Kitchen counter (2 m² )
* Kitchen sink ( 1 m² )
* Large dining table ( 4 m² )
* Bathtub with shower ( 2 m² )
* Basic Toilet ( 1 m² )
* Basic sink with mirror ( 1 m² )

With 18 / 25 m² occupied by furniture, your apartment feels EXTREMELY CRAMPED to live in.

1 => manage furniture
2 => go furniture shopping
3 => look for a bigger apartment
4 => back

```

Regarding the "middle of nowhere challenge" and "apocalypse mode": Instead of trying to get as close as possible to the original mechanics from the game you are trying to replicate, it might be better to approach these from a different angle.

1. What exactly is the fantasy those game modes are supposed to convey?
2. How can that fantasy be sold in a text-based game?

I have never played The Sims and I never heard of these self-imposed challenges. But I assume that the idea is to simulate a sim trying to survive without human civilization. Instead of looking at this through the lense of the building system, it might be better to take a more holistic view of how such a situation could be represented using *all* the game mechanics you have available, and not just building. Remember, this is *your* game. You are not bound to the restrictions of modders or people coming up with self-imposed challenges. You can alter the very foundation of the game to craft the experience you want.

Again, I don't know your game and I don't know your inspiration. But I would imagine that the primary challenge would be that procurement of food and furniture becomes a lot more difficult in such a world, which could be represented with a much higher time investment for doing this.

---
Tags: game-design, text-based
---


# Question
Title: Efficently Computing the Inverse Affine Transform
Given a single affine transformation in 3D (i.e., TRS transforms) that is represented by a translation vector (t), quaternion (r) and scaling vector (s).

Is there some way of efficiently computing the inverse transform, while maintaining the same representation?

I initially thought that this was a simple as inverting each component, but a simple test with the resulting 4x4 matrices for these transforms clearly shows that this is incorrect. E.g., the transform:

```
A  := ({t=(10, 1, 0), r=(0.97, 0.26, 0, 0), s=(5, 5, 5)}
B  := inv(A)       // {t=(-10, -1, 0), r=(0.97, -0.26, 0, 0), s=(0.2, 0.2, 0.2)}
ma := A.to_mat4()  // { { 5 0 0 10 } { 0 4.3 -2.5 1 } { 0 2.5 4.3 0 } { 0 0 0 1 } }
mb := B.to_mat4()  // { { 0.2 0 0 -10 } { 0 0.17 0.1 -1 } { 0 -0.1 0.17 -0 } { 0 0 0 1 } }
i  := ma * mb      // { { 1 0 0 -40 } { 0 1 0 -3.33013 } { 0 0 1 -2.5 } { 0 0 0 1 } }
                   // Clearly not the identity matrix

```

Is this actually possible to do in some way? If not, are there some circumstances under which this can be done?

# Answer
> 2 votes
when you have the transform split into components you apply them one at a time to an object:

```
o1 = object.scale(trs.scale);
o2 = o1.rotate(trs.quaternion);
o3 = o2.translate(trs.translate);

```

Or in other' words the final equivalent transformation matrix for this order is `M = Trans*Rot*Scale`

However the inversion rule requires that you swap the operands of the multiply when you invert it

```
inv(M) = inv(Trans*Rot*Scale) = inv(Scale)*inv(Rot)*inv(Trans)

```

Which is the wrong order

Uniform scale and rotate will be commutative with each other so that is not an issue.

In the end you need to find a translation such that `T_result*inv(Rot)*inv(Scale) == inv(Scale)*inv(Rot)*inv(Trans)`

Some basic matrix multiplications on both sides gives me:

```
T_result*inv(Rot)*inv(Scale)*Scale  == inv(Scale)*inv(Rot)*inv(Trans)*Scale
T_result*inv(Rot)*Rot               == inv(Scale)*inv(Rot)*inv(Trans)*Scale*Rot
T_result                            == inv(Scale)*inv(Rot)*inv(Trans)*Scale*Rot

```

---
Tags: transformation
---


# Question
Title: How can I change scenes when the player touches another CollisionShape2D in Godot 3.5?
I need to know how I can change scenes in Godot 3.5 when the player ***touches*** another `CollisionShape2D`.

I've tried this:

```
extends Area2D

func _on_Area2D_body_entered(_body):
    print("changed")
    get_tree().change_scene("res://World2.tscn")

```

`print()` is to check if it has changed the scene and it did change the scene but it seems to change right from the start.

I also got this error:

> Missing connected method '\_on\_Area2D\_body\_shape\_entered' for signal 'body\_shape\_entered' from node 'World/Area2D' to node 'World/Area2D'

# Answer
> 0 votes
I suspect the reason why your scene transition triggers immediately is the signal you're currently intercepting.

I assume the method `_on_Area2D_body_entered()` is in the player script. The `body_entered()` signal is emitted when a `PhysicsBody2D` or a `TileMap` enters an `Area2D`, so your player is probably triggering it by simply standing on the floor, if any.

> ...when the player ***touches*** another `CollisionShape2D`.

Actually, `CollisionShape2D` only provide a collision shape to `CollisionObject2D`-derived Nodes. While based on *CollisionShapes*, collisions occur among *Nodes*. There are two main categories of collision signals: areas and bodies. They allow you to know **just** what area/body a given Node collided with, or **both** the involved area/body **and** which particular collision shape collided.

If your colliding object only uses one `CollisionShape2D` and requires no physics, you can keep things simple and detect the `area_entered()` signal instead. Moreover, you can move the scene transition logic to the "teleporter" Node in a new script, since scene changing has now become its responsibility, and the player will implement the logic for collisions that only affect its movement or interaction.

Here's a handy script for your "teleporter" object, which in fact I called *Teleporter* and saved as a separate scene:

```
extends Area2D

export var go_to_scene: PackedScene

func _on_Teleport_area_entered(area: Area2D):
    if area.name == "Player":
        get_tree().change_scene_to(go_to_scene)

```

In the Teleporter scene (NOT your level scene), if you connect the `area_entered()` signal to the method above, you'll have it detect the player entering its collision shape wherever you instantiate the teleporter. Also, exporting the `go_to_scene` variable as a `PackedScene` allows you to quickly select the next scene from the Inspector, by clicking on its input field, then *Quick Load*:

---
Tags: collision-detection, scene, gdscript, godot-3
---


# Question
Title: Convert Wavefront (OBJ) faces into triangles for drawing with OpenGLES
I wrote a simple Wavefront parser in C++ that loads `v`, `vn`, `vt` and `f` into `std::vectors`.

The most `f` lines in my `.obj` file contain four triples like this:

```
    f 601/10518/265 10522/10517/265 10521/10516/265 602/10515/265

```

obviously, if I have four triples I create two triangles.

But I do not understand well enough what to do with the last `f` line in my `.obj` file that contains about 700 triples:

```
    f 3229/3228/1 3456/3227/1 3455/3280/1 3508/3279/1 3507/3332/1 3560/3331/1 3559/3384/1 3612/3383/1 3611/3436/1 3664/3435/1 3663/3488/1 3716/3487/1 3715/3540/1 3768/3539/1 3767/3592/1 3820/3591/1 3819/3644/1 3872/3643/1 3871/3696/1 3924/3695/1 ....

```

From wikipedia: OBJ files also support free-form geometry which use curves and surfaces to define objects, such as NURBS surfaces.

Is this line a some kind of this NURBS surfaces? If yes what lib can I use for them?

How to convert it to triangles? (For drawing with OpenGLES).

Can I use `GL_TRIANGLE_STRIP` or `GL_TRIANGLE_FAN`?

Below I provided a trivial plane example that I load successfully:

```
    # Blender 3.6.5
    # www.blender.org
    mtllib plane.mtl
    o Plane
    v -1.000000 0.000000 1.000000
    v 1.000000 0.000000 1.000000
    v -1.000000 0.000000 -1.000000
    v 1.000000 0.000000 -1.000000
    vn -0.0000 1.0000 -0.0000
    vt 0.000000 0.000000
    vt 1.000000 0.000000
    vt 1.000000 1.000000
    vt 0.000000 1.000000
    s 0
    f 1/1/1 2/2/1 4/3/1 3/4/1

```

but my real-life mesh is too long to add there, I exported it in Blender from this:

# Answer
As we hashed out in the comments, that 700-entry line seems to be the middle face of your tile: a square with something like 174 T-junctions on each side would give you the 700-entry line you're seeing.

All those T-junctions are vertices in one big polygon (an n-gon, or specifically a 700-gon), so we need to break it into triangles for rendering just like we do for quads.

If you have a list of vertices in order around the perimeter of a convex polygon, you can triangulate it into a strip by alternating two steps:

* Take two vertices from the end of the list and one from the start to make a triangle. Remove one vertex from the end of the list.

```
MakeTriangle(startIndex, endIndex - 1, endIndex);
endIndex--;

```
* Take two vertices from the start of the list and one from the end to make a triangle. Remove one vertex from the start of the list.

```
MakeTriangle(startIndex, startIndex + 1, endIndex);
startIndex++;

```

(Note that this reduces to the same thing you're already doing if the input has 3 or 4 vertices. I've expressed the code examples above as shifting indices for the start and end instead of removing a vertex and shifting the rest of the list down, for efficiency.)

To avoid degenerate triangles, you may need to cycle the list (move vertices from the end to the start) so that the first triangle you pick has non-zero area. In the case of the big square face in the image, that means starting in one of the corners, so that the alternating steps above give you zig-zag cuts diagonally across it.

You can also build a fan by using just one of these steps repeatedly, but this will tend to give you more long and skinny triangles, including many with zero area in the example from the image. The strip strategy helps balance out the sizes.

In general though, you want to do most of the hard work of triangulating the mesh in the DCC (Digital Content Creation) software like Blender *before* importing the content into your game/engine. These tools are designed for this work, and have the structure/adjacency information available to do higher-order operations, handle non-convex polygons, etc. Digesting your meshes into quads and triangles before import lets you keep your game or engine's import code simpler (and faster!) and can give you higher quality results, as artists can control exactly how those complex n-gons get triangulated, rather than leaving it up to one fixed algorithm.

In this case, an artist working in Blender could notice that most of the edges along the straight sides of the tile are unnecessary and remove them, so the top face becomes just a single big quad without T-junctions all along its length. This reduces your polygon and vertex counts for better rendering performance.

The resulting topology would look like this, all quads, no n-gons:

```
▦▤▦
▥□▥
▦▤▦

```
> 1 votes

---
Tags: opengl-es, obj
---


# Question
Title: Complexities regarding starting resources
My text-based game will be a sims clone. I'm having problems though deciding what resources the player should start out with.

I'm wanting to implement a form of the legacy challenge from the Sims 2, but I'm having problems doing so due to the differences between The Sims 2 and my game.

In the vanilla start, you start as a college student and end up with $4800 (the game uses a fictional currency, but obviously you can't type the symbol for that). If you chose the eXtreme start (that IS how its supposed to be spelled), you instead start out as an adult (aka, post-college adult) with $1500. Either way, you have the option of starting with a 'legacy tree' on top of either to these options, meaning you have to plant an orchard tree on your lot at the start and it has to stay there the entire run. This tree costs $1200, so obviously this eats up a lot of cash.

Here are the differences between my game and The Sims 2 that makes this hard to implement:

College isn't a separate 'life stage' like it is in The Sims 2. The reason it was implemented in such an odd way was because it was actually added in an expansion. In my game, college will just be something any adult character can do whenever and as many times as they please. This obviously poses a problem. This means that in my game, you always start as an adult regardless. Going through college also requires you to build up skills. In The Sims 2, pre-made characters always start off with no skills at all regardless of their age. So in the eXtreme start, you're starting not only with less money and no degree, but also no skills. College is also a time for you to make friends, and even find your future spouse. With the eXtreme start, you won't have even that, you're just a blank slate. Obviously, having you start off by default as an adult would be rather problematic. Oh, and you can take back items with you from college in The Sims 2, this also means you actually start off with far more resources since you can easily buy all the furniture your house will use; you just need to pay for the structure itself.

I did think of a way to fix this, but I'm not 100% happy with it. I was thinking of implementing the dorm mechanic The Sims 2 has. Basically, in the vanilla start you start off enrolled and living in a dorm. You also start off with enough money to pay your tuition, so no need to worry about that (in the Sims 2, you actually can't have a job while you're at college, though there are ways to earn money, mostly by getting top grades). Outside of this, to send someone off to college you would need to generate enough funds to pay the tuition over the several years they're going to be there up front (this wasn't a part of the sims 2, despite you starting with a rather generous amount of cash upon arriving at college). This money will go with the sim, and they can spend or mis-spend it as the player sees fit. Things could get complicated if you fail a semester though, since you'll end up staying there longer to get your degree if that happens.

I'm not too happy with this though. It all feels rather clunky. Really, I'm just trying to implement a challenge from another game into mine. Its like I'm trying to make this thing compatible with a mod from another game.

Going to college would probably require quite a huge investment, so it wouldn't be easy to pull off. Also, if you did start with the eXtreme start, that doesn't mean you can't go to college afterwards. In The Sims 2, you can only get one degree, and once you're a full adult you can never apply even if you didn't in the past (that's because you can only sign up to college as a teen, and in the base game they directly aged into adults, this is why the 'young adult' stage had to be implemented in such a weird way). So and eXtreme start founder could still get the degree anyway, and get part of its benefits. Also, the eXtreme start with have a boon; since you're not starting at college, you would start the challenge/game mode in full with a younger character, giving you more time to do things. This is supposed to be a handicap; something you do to make the game harder in exchange for a higher possible final score. At best in my game, it would be more of a trade-off. eXtreme would just mean you don't start off in college, but instead save it for a later date. You would have less starting money to, but this would still be a trade-off rather than a pure detriment.

I don't know what I could do about this. And no, I can't just change the handicap to say your characters can never attend college; many of the possible points you can score require you to do so. This handicap would thus actually reduce your score, by making it impossible to get some of the possible achievements you need to score.

The only way I see to implement this would be to just straight copy how college works in the Sims 2, which was itself kinda wonky. Its sorta a problem with the game; as expansions came out and new features were added the thing ended up being turn into a conglomerate game with multiple conflicting mechanics. There's actually two different skill systems in the game. There's also the hobbies thing which does the same thing as interests but with different nuances, and they both exist side-by-side in the game! Its actually a bit of a mess. I wasn't looking to copy the game whole-sale; I was planning on addressing some of its issues (though most of those would be glitches that don't really alter the gameplay, such as fixing it so you don't corrupt your save if you marry certain npcs).

Oh, and if that's not enough, I wasn't planning having the game spawn you on an empty lot like the Sims 2 does. I was planning on using a pre-made house, just to save the annoyance of having to build the same starting house over and over. I guess I could ditch this and give you a blank lot you could put whatever you want on, but I sorta don't like the annoyance, especially since this game being text-based, it means there isn't really any design; you would just be 'purchasing' rooms with a certain amount of space and items to put in them. The game isn't even going to take into account how the rooms are connected, or how they're shaped, or even if they're on the same floor or not.

The point of this handicap is to make the start harder. You don't have any skills, you did no networking before starting, and you brought nothing back with you and to boot have less money to start with. The legacy tree thing adds another wrinkle, though that could be implemented easily by just lowering your starting money when you get to the lot where you'll actually be building your mansion in exchange for some free food and an extra point in the end. Maybe I could say that if you do the eXtreme start and have the legacy tree, you start off dead broke and essentially live as a homeless person until you make some cash (you COULD in theory do that in my game the way I'm thinking of designing it, though The Sims 2 didn't really let you do that).

How else could I implement this into my game? I'm really at a loss.

What can I do about all this? How do I handle this differing start in a game that doesn't have the wonky aging system The Sims 2 did?

# Answer
Determining the starting resources most games is a matter of play testing:

1. Pick some initial value(s)
2. Play test, noting the impact of choices from step 1.
3. If needed, revise choices based on impact & repeat step 2.

Since you're taking inspiration from an existing title, using similar starting values might be reasonable. But since you're altering some mechanics, you probably need to tune your starting values differently.

A common tuning heuristic is to use doubling & halving to gradually zero in on good values. For instance, if a value seems too low, double it until it's not. When you over shoot, you have bounded the problem. Once it's bounded you can take the middle between the last "too high" value & the last "not high enough value".

Log the values values as you tune. I suggest keeping them in a CSV type spreadsheet or text file and keeping that in the repository with your code. In the event that you need to roll back, you'll have a set of data that accompanied that version of the project.

In addition the resources parameters, you'll need some indication of how good they were. This is going to vary, but if possible I would suggest something more fine grained than a simple good / bad. You might want to have a subjective five star rating system. You may also want to keep track of how quickly the game reached a win or fail state. There are two reasons I suggest keeping more than just the final good values.

First, the doubling / halving heuristic doesn't account for synergies. Adjusting one resource may unbalance another. If you need to go back and tweak a previously tuned resource, logging a little more data will make it easier to look for things that are in the "vicinity" of previously known good values. It won't remove all the work, but it will give you more to go on than guessing.

The second reason is to address something from your other posts: challenge modes. Tracking the data allows you to move away from ideal starting conditions towards sub-optimal, but still winnable starting conditions. From there you can come up justifications that fit the feel of your game. A realistic game might limit trees due to emerald ash borer outbreaks whereas something less serious might just make a quip about how it was time for all the trees to leave. You can brainstorm the fiction to fit the data and the challenge will still work because you know the parameters are tough, but potentially winnable. This isn't to say you can't develop some challenges story-first. But since you're already collecting playtest data, you may as well leverage it in multiple ways.
> 1 votes

---
Tags: game-design, text-based
---


title: Fade edges of 2D spline-mesh

text:
# Question
Title: Fade edges of 2D spline-mesh
I'm re-writing my Unity game in Raylib and are trying to recreate a path/road-shader I made with Shader Graph.

The first picture is how it looks in Unity, with faded/blurred edges. The path is a 2D spline-mesh created as you can see in the second picture. The third image is a spline-mesh created the same way in Raylib.

Does anyone have an idea how to get faded edges with GLSL-code?

The Shader Graph looks like this:

I'm new to GLSL and have been at this for days. I would really appreciate any help!

Edit:

I also tried to manually convert the shader. Here is an example where I tried to convert the Shader Graph.

Vert:

```
in vec3 vertexPosition;
in vec2 vertexTexCoord;

uniform mat4 mvp;
uniform mat4 matModel;

out vec2 fragTexCoord;
out vec3 fragPosition;

void main() {
      fragTexCoord = vertexTexCoord;
      fragPosition = vertexPosition;

      gl_Position = mvp * vec4(vertexPosition,1.0);
}

```

Frag:

```
in vec2 fragTexCoord;
in vec3 fragPosition;

uniform sampler2D texture0;

uniform float width;
uniform float blur;

void main()
{
      vec4 texColor = texture2D(texture0, fragPosition.xy);
      vec2 halfVec = vec2(0.5, 0.5);
      float dist = distance(fragTexCoord, halfVec);

      float smoothstep1 = smoothstep(width,blur,dist);

      gl_FragColor = vec4(texColor.xyz, smoothstep1);

}

```

The result is this:

Or this, depending on width- and blur-parameters

Edit 2:

I translated the Shader Graph-code node by node and the result was basically what I already wrote i GLSL. The part I can't figure out is this Shader Graph-generated code.

(I simplified it from 5 to 2 lines and shortened the variable names)

```
UnityTexture2D unityTex =  UnityBuildTexture2DStructNoScale(_Texture2D);
float4 texColor = SAMPLE_TEXTURE2D(unityTex.tex,UnityBuildSamplerStateStruct(SamplerState_Linear_Repeat).samplerstate, unityTex.GetTransformedUV((IN.WorldSpacePosition.xy) / _Size));

```

Does anyone know what GetTransformedUV does? I cant find any information on UnityTexture2D by googling.

# Answer
> 0 votes
I finally made it work with a kind of hack.

Because its 2D and unlit I don't need to use normals. So I saved the center of the spline in the normals of the mesh. Then I can fade the edges based on the distance between the center and each vertex.

I get the same result as the Shader Graph in Unity.

I guess It's possible to store the data and pass it to the shader some other way, but I couldn't think of any.

---
Tags: unity, opengl, shaders, glsl, raylib
---


# Question
Title: Improve performance of server updating game state
I have a Node.js game that sends update packets to players every 30ms.

The code I currently use works this way:

1. Get the entities within each player's vision.
2. Create a temporary object that stores only the necessary properties of the entities that need to be sent.
3. Compare this object to the entity that the client knows to get the differences.
4. Compress using pako, and send to the client

This code takes about 2 milliseconds to run for 100 visible objects, but this is too slow as the server will be unable to handle more than 15 players.

Comparing to get the changed properties (step 3) took the longest time to execute.

What changes do I need to make?

# Answer
As DMGregory said, You can locate the performance problems of each step, or try another communication protocol and programming language. But I think the more significant problem is that your synchronization solution is not suitable for handling a large number of players on the same screen.

For cases like this, such as MMOs, an algorithm called **AOI**(Area Of Interest) is often used. I don't know if this is an official term as search engines don't give many valid results. Anyway I will introduce this method here.

The basic idea of AOI algorithm is as follows:

1. Divide the space into 2D or 3D grids. Each grid object records a list(`the observed`) of entities which are in the grid, and a list(`observers`) of entities whose field of view covers the grid.
2. When an entity moves, check whether the grid it is in has changed. If it has changed, move it from the `the observed` list of the previous grid to the new grid.
3. When a client's field of view changes, remove it from the `observer` list in the grids those are no longer covered by the field of view, and add it to the new grids those are covered by the field of view.
4. When an entity's properties change, mark it as dirty.
5. In a new tick, traverse all grids and synchronize all dirty entities in a grid to all observers of this grid. And clear dirty mark of all.
6. When a new observer joins the grid, the **full data** of all entities in `the observed` is synchronized to it. When an observer leaves the grid, send the observer a list of IDs of `the observed`, so that the client will delete them and no longer treats them as objects being tracked.

This will solve most of the problems you describe:

> Get the entities within each player's vision.

No more repeated searches for entities within the field of view. Only the changes in the field of view coverage grid need to be calculated. This is much less computationally intensive

> Create a temporary object that stores only the necessary properties of the entities that need to be sent.

The temporary object is still required, but the temporary object becomes unique per entity. There is no need to create a lot of new objects (allocate memory) every tick. You can reset this object after clearing the dirty mark.

> Compare this object to the entity that the client knows to get the differences.

For all players in the grid, the synchronization data they need to receive is the same, and there is no need to repeat comparisons.

> Compress using pako, and send to the client

All observers in the same grid need to receive the same data. Data for each dirty entity is compressed only once.

If AOI is used, it will bring considerable performance improvements. Here are a few more tips:

1. The appropriate size value of the AOI grid needs to be tested. So make it configurable. It is best not to be larger than the actual field of view size of the client, because the minimum number of grids covered by the field of view is 4. If the grid size is too large, it will cause redundancy of transmitted data. If the grid size is too small, grid maintenance costs will increase.
2. Since entities will only move to adjacent grids, using a cross-linked list instead of a two-dimensional array will bring performance improvements.
3. A large amount of practice has shown that(I think) the importance of in-game data is inversely related to the frequency of its changes. Dirty data could be grouped according to its importance. They can have different synchronization frequencies. For example, entity positions can be synchronized to the client when they are created and velocity changes(or/and every 100 ticks), and the client can predict and interpolate the rest of the time. At the same time, important data such as entity HP and death status can be synchronized every tick.
> 1 votes

---
Tags: javascript, performance, client-server, synchronization, node.js
---


# Question
Title: Implementing proportional navigation in 3D
Good afternoon guys,

a = N * λ' * V

is the formula for the commanded acceleration required to hit the target,
where N is the proportionality constant, λ' is the change in line of sight and V is the closing velocity.

**Data I natively have**:

\[x,y,z\] position of both missile and target;
\[vx,vy,vz\] velocity vector of both missile and target;
\[x,y,z\] vector which points from missile to target and opposite;
This is set by me but still: maximum speed of missile.

**Data I can get with some calculations**:

Vertical angle between missile and target (and opposite) ; Horizontal angle between missile and target (and the other way around).

That's the reference system of the game:

* λ' or the derivative with respect to time of the Line of Sight it's a concept I really didn't understand... its unit should be, in theory, Hz or (s^-1) since m/s^2 = λ' * m/s -\> λ' = 1/s
* V should be pretty easy to calculate: V = v(missile) - v(target) OR
Vx = (v(missile) - v(target)) * cos (x0y)
Vy = (v(missile) - v(target)) * sin (y0z)
Vz = (v(missile) - v(target)) * cos (y0z)
* N well it's a scalar number, usually 3.

The computed acceleration will then be passed to a RK4 integrator which will move the interceptor towards its target.
To steer the missile, I will simply change its velocity vector at every update (every 1/60th of a second) and its orientation accordingly. *For example*: if the missile has a velocity of \[0,100,0\], he's going 100 m/s due y+ axis. If at the next frame it should slightly turn right, then he'll be going to have a velocity of \[10,99,0\] and so on.

That's the only thing left to finish off my little thesis and unfortunately I'm stuck here. In the meantime, thank you very much!

Here's a video I made, but it doesn't still actually use the Proportional Navigation law: it checks if the missile is "aligned" to its target and eventually correct its route.
That's my actual code: pastebin

That's what i've come up with but sadly doesn't work as expected:

```
params ["_n","_missile","_target"];
private "_a";

_vm = velocity _missile;
_rm = getPosASLVisual _missile;

_vt = velocity _target;
_rt = getPosASLVisual _target;

_vr = _vt vectorDiff _vm;
_r = _rt vectorDiff _rm;

_omega = (_r vectorCrossProduct _vr) vectorMultiply (1/(_r vectorDotProduct _r));

_a = (_vr vectorCrossProduct _omega) vectorMultiply _n;

_a

```

Similar questions:
Finding the components of Proportional Navigation in 2D

# Answer
> 1 votes
I know this is a "little" late, but as they say better late than never; so for those still searching for an answer to this topic...

The most simplistic proportional navigation implementation in 3D would be a 3-DOF point mass kinematic model, and there happens to be a 100% Python 3 variant **propNav** available on GitHub. There is no reason to attempt a 3-DOF or 6-DOF dynamic model if one does not grasp the concepts presented in a 3-DOF kinematic model of ideal proportional navigation guidance. If a higher fidelity model is needed, I recommend reference \[6\] cited in the **propNav** README as a good starting point for creating a 3-DOF dynamic model.

---
Tags: physics, 3d, vector, integration, kinematic
---


# Question
Title: Order of updates in falling sand simulation
Looking into the classic "falling sand" simulation I've run into a question that I couldn't find addressed anywhere.

Most people appear to agree that the update has to go bottom-up, because then an entire vertical column of sand can move down one pixel per update (because sand pixels that initially have a sand pixel beneath them can still fall down in the same update after that lower sand pixel was moved down earlier.)

(On the other hand if the update is top-down then only sand pixels with an air pixel will move down, leading to a slower trickle-down where each sand pixel has to wait for an air pixel to appear beneath it, leading to alternate air-sand falling down slower, hope this is clear.)

Now my question is, if I have other pixel types that move up, like smoke or steam, then it feels like everything is inverted and the update order should be top-down!

Now I don't see how to run the update both to-down and bottom-up at the same time. Is there a "standard" solution to this problem? Can double-buffering help, and if so, how?

# Answer
I don't know much about the technicalities of simulation design, but it seems to me that you could update all the sand-like particles from the bottom up, and then update all the steam-like particles from the top down. This means that if steam and sand would try and enter the same spot then the sand would always win, but unless you are planning some very weird physics, that's an intuitive result.

Alternatively, make the artistic decision that steam rises more slowly and spaced out than sand does in your simulation.
> 2 votes

# Answer
The default method is to just always process cells from bottom-left to top-right to handle the problem of realistic physics. One particular youtuber MARF has documented his process for this in the following video, including vertically travelling particles.

At no point does he nor anyone else recommend any different form of per-pixel traversal for processing other than bottom-left to top-right. You give and you take. Double buffering would help, but would not be worth the excess processing time to accomplish it.

The only thing I would note is that you should utilize the power of JFAs (jumpflood surfaces) and SDFs (signed-distance fields) for distance checks rather than doing per-pixel texture fetches. You can generate a JFA/SDF of an image, see this GODOT 2D GI article for information.

This works well because empty space will give you the distance to the nearest surface and... we don't need to check the status of empty space anyways.
> 1 votes

---
Tags: physics
---