title: Why is my jump arc preview inaccurate?

text:
# Question
Title: Why is my jump arc preview inaccurate?
I'm trying to draw an arc out of dots that previews a **KinematicBody2D's** trajectory after a jump but said preview always falls short of the body's actual jump and I cannot figure out why. Below is an example gif of what I'm talking about.

And this is the code I used in the example.

```
extends Node2D

var arcPoints = 40
var pointsPerSec = 12
var startYvelocity = -500
var velocity = Vector2(200, startYvelocity)
var gravity = 300

var startPosition = Vector2(96, 544)

func _draw():

    var totalY = startPosition.y
    var velY = startYvelocity
    var calcGravity = gravity/pointsPerSec

    for p in range(arcPoints):
        velY += calcGravity
        totalY += velY/pointsPerSec

        var point = Vector2(startPosition.x+(velocity.x/pointsPerSec)*(p+1), totalY)
        draw_circle(point, 2, 'fafafa')

func _ready():
    pass

func _physics_process(delta):
    velocity.y += gravity*delta
    get_child(0).move_and_slide_with_snap(velocity, Vector2(0.0, 1.0), Vector2(0.0, -1.0))

```

# Answer
> 3 votes
By doing a preview with time increments different from your process, you're bound to have differences. For example, consider these extreme cases:

* You simulate a preview with 1 point per second: on the first step, your Yvelocty becomes -500 + 300 = -200, making it as if you started your jump with a speed of only 200 while it should be 500 in reality.
* You process the jump at 1000 frames per second: on the first step, your Yvelocty is -500 + 0.3 = -499.7, almost the "real" starting velocity.

Since actual gravity works in continuous time, you'll never have a "true" path by doing simple increments, even though the process framerate will be good enough not to notice. So you can either:

* Do your preview with the same time increments as your process. However, you don't know it precisely unless you fix your physics framerate, and it's really inefficient.
* Do your preview (and even your process) by applying the math on each point with a simple equation:
\\$y(t) = y + vy * t + \frac{1}{2} a t^2\\$ (Here in your example with y = 544, vy = -500, a = 300)

I let you guess wich solution is the best ;)

# Answer
> 1 votes
I wanted to show what applying Keelhaul's answer to a godot script would look like to try and add clarity to what the issue was. The Following is my modified script.

```
extends Node2D

var arcPoints = 120.0 #total number of points to draw
var arcFPS = 60.0
var PPF = 2.0 #points per frame

var startYvelocity = -500.0
var velocity = Vector2(200.0, startYvelocity)
var gravity = 300.0

var startPosition = Vector2(96.0, 544.0)

func _draw():

    var totalY = startPosition.y
    var velY = startYvelocity
    var calcGravity = gravity/arcFPS
    var stepsCompleted = 0

    for p in range(arcPoints*PPF):
        velY += calcGravity
        totalY += velY/arcFPS
        stepsCompleted += 1

        if stepsCompleted == PPF:
            stepsCompleted = 0
            var point = Vector2(startPosition.x+(velocity.x/arcFPS)*(p+1), totalY)
            draw_circle(point, 2, 'fafafa')

func _ready():
    pass

```

This script is very similar to the original question but doesn't just keep track of the change in velocity and position at each of the points but also keeps track of the movement between the points. This is important because the more points of movement we skip the more cumulative effect of said movement we lose. This can easily be shown by changing the **arcFPS** variable, the further it is from the *physics* frame rate the more inaccurate our arc becomes.

^Script with arcFPS and physicsFPS both at 60.

^Script with arcFPS at 12 and physicsFPS at 60. *Notice how it looks almost the same as it did in the initial question.*

Keep in mind that this way of doing it is a balancing act between accuracy and efficacy, try to find a medium that is accurate enough for your liking.

---
Tags: 2d, godot, gdscript
---


# Question
Title: Is there a reason online video games don't have "benches"?
In many physical team sports, in addition to the players deployed on the field, there are also players on the bench who the coach can sub in when the players get tired or run into unforseen circumstances. This is more common at low levels of play.

However, in online e-sports (e.g. Overwatch, League of Legends, Counter Strike), this is almost universally absent, with everyone who queues expected to play the entire duration of the game. This is not always possible, nor, in the case of solo queue, always desired. If it does exist at all, it involves players joining games in progress, which means that the subbing team is left with no one until a replacement shows up, and players being subjected to new skill ratings that they weren't originally matched up to. I have never seen the concept of one or more bench players being available from the start, known to both teams at the start, and available to sub in as needed, akin to how a physical sport would operate.

Why is this? Are there cons to such a system that would cause it to fail or cause more problems than it solves? Has this been tried before somewhere?

# Answer
Games are first and foremost designed to be entertainment for the players. Being a competitive sport and being entertaining for spectators are usually secondary concerns. Not like those physical sport events you see on TV which were gradually modified over the years to be the sport the fans want to see, not the one the players want to play. Sure, those big eSport events can be good marketing. But the money they generate for the developers is negligible compared to what they make in game sales to the masses. And those paying players care far more about *playing* a good game than *watching* one.

Just watching a game and not being able to do anything hoping some player will leave the match so you can play just isn't any fun. So you are not going to see any build-in mechanic for this.

Some games do allow spectators in the game who can join a team at any time, which could actually make this possible in an eSport setting controlled by additional rules governing player replacement. But I know of no eSport league which has a rule like that. The reason is that contrary to physical team sports, the risk for any player to suddenly leave the game due to a physical injury is rather small. So there is usually no need to replace players during the match. It is however usually possible (and anticipated by the teams) to replace players *just before* the match, because in the less professional eSport leagues it happens quite often that players just don't show up.
> 2 votes

---
Tags: game-design, online, matchmaking
---


title: Why is account sharing so bad?

text:
# Question
Title: Why is account sharing so bad?
In games where you have to use an account to sign in or otherwise authenticate yourself (e.g MMO games), it is often prohibited to share your account with other people.

For example in the World of Warcraft Official Terms of Use Agreement:

> \[...\] You may not share the Account with anyone, except that if you are a parent or guardian, you may permit one (1) minor child to use the Account when not in use by you. You are liable for all uses of the Account that has been enabled by you \[…\]

And the League of Legends Terms of Use:

> \[...\] You can’t share your account or Login Credentials with anyone. You can’t sell, transfer or allow any other person to access your account or Login Credentials, or offer to do so. You’re entirely responsible for maintaining the confidentiality of your Login Credentials. \[...\]

What is the reason for this? Is it because of legal reasons and / or security reasons? I imagine account sharing would not be a problem if there weren't some real-world consequences for the *company*, not just the end-user.

# Answer
It's important to have a firm grasp of precisely who the legal entities are in any contractual agreement, so you know who you have to sue or blame or whatever if it ever comes to that.

Less seriously, if account-sharing were permissible, then blaming "somebody else who was using the account at the time" would be a reasonable response to any punishments for violating any other rules. By prohibiting sharing that way, a company eliminates the hassle of having to deal with that argument (which is usually impossible to disprove) in response to bans. Obviously people still try to use that defense, but a company can simply point to the rule against account sharing and say "well that's not allowed either." It makes life way simpler for the GM team.

It also has a small side-benefit: it means that if you and your friend want to play, you have to buy two copies of the game, you can't buy one and share it. This is obviously also better for the company.
> 101 votes

# Answer
From both a legal & security standpoint, the single biggest factor I'm aware of is accountability. If you cannot determine who is responsible for the account, you cannot reasonably hold anyone accountable for actions related to the account. For instance, money laundering is easier if you cannot trace account ownership. Forbidding shared accounts won't prevent laundering in all forms, but it is choosing to not make it easier & demonstrates an effort on the part of the developer to not facilitate such things.

You didn't ask specifically about this aspect, but I feel it's equally important - there are also design implications to shared accounts. For instance, as a designer, you might not want players to pay others to accomplish objectives due to the impact it has on the game experience. You might not be able to full prevent such things, but you can take steps to discourage them & forbidding it via the terms of use may be part of such a solution.
> 31 votes

# Answer
In addition to all the other answers:

Prohibiting this has also the benefit of balancing the game from the point of view of players that won't be sharing their account.

Assuming that account sharing is allowed, a player who wanted to have an account only for himself could think:

> Ah, even if I dedicate my whole time to this game, and even if I play in the best way possible, there is no way I can beat those guys with shared accounts - while one sleeps and the other works, the third player plays and there is no way I can level up as much of those guys... **Therefore I don't stand a chance, and I won't even start to play this...**
> 27 votes

# Answer
Besides the legalese mentioned in other answers, there are also simple business reasons.

Some games like World of Warcraft charge people by account. If you let two people share an account, you lose 50% of your revenue.

Other games like League of Legends charge people for being allowed to use ingame content. That content is bound to each account. If you would allow account share, only one person would have to buy content which all of them could then use.

The only business model where you would not have any losses by allowing account share would be a pay-by-minute price model. But that has fallen out of fashion over 20 years ago.
> 19 votes

# Answer
It is absolutely standard that if you have an account for a service, then you are responsible for what is done with that account.

In game terms, some of the things which can be done with an account might include:

* Cheating,
* Playing disruptively,
* Insulting or threatening behaviour,
* Circumventing copy protection,
* Distributing pirated software,
* Distributing other illegal material,
* Etc.

If account sharing is permitted, then this responsibility cannot be enforced.
> 10 votes

# Answer
In addition to all the other answers, there is another reason: **Ensuring leaderboard integrity by prohibiting account sharing and multi-account usage.** A famous example is the rhythm game osu!, which states as its **first** rule:

Due to the game's ranking system ("performance points") absence of this rule would destroy the leaderboards, as a top player could easily dominate their rank range by just repeating their top scores.
> 6 votes

# Answer
In addition to the many fine answers, there is another reason.

Game companies don't want to arbitrate your personal squabbles.

If you share your account with someone, you allow them to delete your characters, sell your items, or simply change your password and lock you out.

Many people would trust some people with their account now, and would regret this decision later.

The owners of the game do not want to do arbitrating whether the old or the new email address used to reset the password is best, and whether to return the 'Sword of Awesomeness' that was sold to another account for 1 copper. It involves them putting in time and effort to decide which of their user base to annoy.
> 6 votes

# Answer
I can see a single aspect why they would ask you not to do it: *money*.

If you share your account credentials with someone you trust, but end up losing all your stuff because that someone ended up not being trustworthy, you might ask the help-desk to recover the items for you. They would have to pay an employee to trace back where your stuff is. This would cost them more money than what they have planned.

If I play with you once in a while, the only thing I see is your avatar. I don't have any way to know if it's actually you or your little brother. I trust *you*, not your brother. Imagine if you lead a guild what can happen! Sharing accounts can also be used to create havoc with other players. All of this adds confusion and unease for other players, making them less likely to play your game.

If you share your account with someone else, it means that you (your account) can be connected and play 24/7. A normal person can't do that. If the developer estimated that it will take 6 months at 8 hours a day to reach the 'end of the content', playing 24/7 means that an account will reach it in 2 months instead of 6. Imagine a bunch of gold/item farmers that get there really early, get a bunch of end-game items and sell them on eBay? The reputation of the game would take a hit, reducing the amount of paying customers.

*All of the behaviours that can be introduced by sharing an account are detrimental for the developer, either directly (they explicitly lose money), or implicitly (they lose reputation, then players, then money).*
> 5 votes

# Answer
I'm not a gamer, but my first thought was that if multiple people use the same account, any analytics collected about the user would be difficult or impossible to interpret. Not sure if games collect analytics, but figured I'd throw it out there.
> 4 votes

# Answer
I run Wildfire, a multiplayer network backend for Crysis Wars. Like other networks, we don't allow account sharing- our ToS never actually goes into detail as to why this is, but I made this decision because:

* One copy of the game per account- allowing users to share their accounts would *dramatically* skew the statistics of that account. For commercial networks, this would simply mean that they miss out on the revenue from multiple accounts purchasing a unique licence for the product.
* Accountability- if a user of the account violates the ToS, it has an impact for all users using the said user account. Separate accounts mean that only one person is banned/suspended/warned, affecting just that one person when compared to multiple people. In addition to this, allowing multiple people to use a single account would make it *very* difficult to pin the blame on a single person.
* Leaderboards- multiple people using one account would *seriously* inflate the statistics of the account (similar to my first point). By this, I mean that for Crysis Wars (an FPS) the amount of kills/deaths/points attributed to an account will be abnormally higher, and this is unfair for legitimate users.
* Security- multiplayer backend systems, like my own, log *everything* (and I mean everything). There are several security systems that I use that these logs support- one of them is that the system automatically locks-out a user if it detects that it is using multiple IP addresses at the same time. Similar systems do the same.
> 0 votes

# Answer
Additionally, in League of Legends, for example, if you were allowed to share accounts the balance in ranked queues would be a real mess. By prohibiting account sharing elo boosting is nearly non-existent, however all it takes to manipulate the system, in this case, is to use VPN.
> 0 votes

---
Tags: legal, security
---


# Question
Title: How to avoid overwriting a value in Unity?
I'm working on a Tower Defence style game, and wondering how best to handle the "resources" part. I have multiple enemies on screen at a time, and when an enemy dies, it updates a resource that allows the player to build more towers

```
var tower = Instantiate(buildables[0], center, Quaternion.identity);
var controller = tower.GetComponent<TowerController>();
controller.OnKilledEnemy += (sender, args) =>
{
    int.TryParse(goldAmount.text.Replace(",", ""), out var curr);
    curr += args.gold;
    goldAmount.text = $"{curr:n0}";
};

```

But if 2 enemies die in the same frame, wouldn't the value there miss an update?

What ways are there in Unity/C# to mitigate this problem?

# Answer
When a C# event gets invoked 2 times, then it will get executed 2 times. It doesn't happen in parallel, it happens sequentially when you call `.Invoke`, and after all the event handlers were processed, the thread of execution continues after the `.Invoke` call. There is nothing to worry about here.

Your concerns might be justified if you were using a multi-threaded game engine where methods can actually be executed multiple times in parallel. In that case it would actually be possible for two threads running on two CPU cores to read the same value at the same time and then writing back the same value at the same time. That's called a race condition and is a frustrating source of impossible to reproduce bugs. But thankfully, Unity by default runs all game mechanics on a single thread. Everything gets processed in order. So it's simply not possible for an event to get fired twice "at the exact same time". What actually happens is:

1. `Update()`-method of tower 1 is executed
2. `OnKilledEnemy` is invoked and the event handler is executed
3. `Update()`-method of tower 2 is executed
4. `OnKilledEnemy` is invoked and the event handler is executed

I wrote "Unity by default" above, because with the new Jobs system it is actually possible to implement game mechanics in a multi-threaded manner. When you **do** use jobs and **do** schedule them in parallel, then you need to keep in mind that any data shared between jobs might be subject to race conditions. But if you stick to the idiomatic programming patterns recommended for the job system, this should rarely be the case, because the job system tries its best to stop you from doing that.
> 3 votes

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


# Question
Title: File writing or scriptable object editing in unity webgl
I am using a scriptable object for saving data. I know that scriptable objects are unchangeable means we can't change and save data after runtime but is there any workaround available to update it? Or write any config file (editable for user to change it) on webgl Platform. It seems that file writing permission is not available at unity Webgl.

# Answer
> 2 votes
Sorry, but it's simply not possible for browser-based applications to write any files at all. That's just not how browser-based applications work (thankfully - just imagine what bad people could do when they could write any files they want to your local filesystem while you visit their website). When you need persistence in a Unity WebGL game, then there are basically two options.

* Use the `PlayerPrefs` class. On the webGL platform , it's implemented by the indexedDB api, which works similar to browser cookies, but allows to store a lot more data in a more efficient manner.
* Create your own webservice API which allows game clients to store and retrieve savegames stored in a database you operate. You can't do that in Unity, but there are countless technologies available for doing that. Your game can then access that API with UnityWebRequest for uploading and downloading savegames.

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


# Question
Title: How should I setup my sprites for 2D combat?
I was painting pixel sprites of a goblin (the enemies in the game). I first thought of making sprites of it for each different scenario:

facing camera, moving toward camera 1, moving toward camera 2, facing camera with sword, moving toward camera with sword 1, moving toward camera with sword 2, facing left, going left 1, going left 2 facing left with sword etc. (for a total of 18 sprites)

Then I wondered, how will I make the sword hit the player ? What if I want the goblin to have a different type of sword ? Do I have to make different sprites of it holding different weapon ?

I realised doing sprites for every scenario wasn't ideal. So my question is, how do I make this ? Should I keep the sprites I have but remove the sword from them and then add a sword sprite attached to the player sprite and animating it so it matches the players movement ? Is that the way to go ?

# Answer
You can do this with the rather new 2d animation package.

It allows you to create a skeleton for a sprite and animate that skeleton. Although that usually doesn't work too well with low-resolution pixel-art. It works better with large, painted sprites. It also doesn't work very well with turning a sprite around the y-axis, so if you need sprites facing towards and away from the camera, you might want to represent them with separate 2d sprite animations.

It also allows you to swap out sub-sprites of an animated sprite, which can be used for retargeting your animations for different weapons or other parts of a character.
> 1 votes

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


# Question
Title: How to save the Mesh from an Interactive Cloth at runtime in Unity?
At the start of a scene I have GameObject called 'sheet' positioned above a 'ball' GameObject. The sheet has an Interactive Cloth component on it and a Cloth Renderer. The Mesh for the Interactive Cloth component is a plane with a high number of vertices. At runtime the sheet drops over the ball and creates the shape I want. If I disable the Interactive Cloth component at this point the sheet mesh stay exactly as I want it but I cannot pull it out as a Prefab.

Does anyone know a way to get a copy of that shape?

For example by reading the mesh from the Interactive Cloth at runtime and then using that to change the mesh back how I want it without the Interactive Cloth component.

Any help would be greatly appreciated.

# Answer
> 1 votes
Adding a new answer because I cannot reply with a comment. PatrickSharbaughs code works for me in Unity 2019 using the Cloth component with some small changes. Basically, the state of the cloth simulation can be accessed using the BakeMesh method on the SkinnedMeshRenderer (which is a required component for the Cloth simulation).

```
using UnityEngine;
using UnityEditor;
using System.Collections;

public class SaveMeshBehaviour : MonoBehaviour
{
    public Mesh GetMesh()
    {

        Mesh newMesh = new Mesh();
        GetComponent<SkinnedMeshRenderer>().BakeMesh(newMesh);

        return newMesh;
    }
}

[CustomEditor(typeof(SaveMeshBehaviour))]
public class SaveMeshInspector : Editor
{
    public override void OnInspectorGUI()
    {
        GUILayout.BeginHorizontal();
        if (GUILayout.Button("Save"))
        {
            var saveB = target as SaveMeshBehaviour;
            if (saveB != null)
            {
                var mesh = saveB.GetMesh();

                var copy = Mesh.Instantiate(mesh);
                AssetDatabase.CreateAsset(copy, "Assets/NewMesh.asset");
                AssetDatabase.SaveAssets();
            }
        }
        GUILayout.EndHorizontal();
    }
}

```

# Answer
> 0 votes
A simple behaviour and custom inspector will help. Add this to your scripts:

```
using UnityEngine;
using UnityEditor;
using System.Collections;

public class SaveMeshBehaviour : MonoBehaviour
{
    public Mesh GetMesh()
    {
        return gameObject.GetComponent<MeshFilter>().sharedMesh;
    }
}

[CustomEditor(typeof(SaveMeshBehaviour))]
public class SaveMeshInspector : Editor
{
    public override void OnInspectorGUI()
    {
        GUILayout.BeginHorizontal();
        if (GUILayout.Button("Save"))
        {
            var saveB = target as SaveMeshBehaviour;
            if (saveB != null)
            {
                var mesh = saveB.GetMesh();

                var copy = Mesh.Instantiate(mesh);
                AssetDatabase.CreateAsset(copy, "Assets/NewMesh.asset");
                AssetDatabase.SaveAssets();
            }
        }
        GUILayout.EndHorizontal();
    }
}

```

Then in the scene add the SaveMeshBehaviour to your cloth. The custom inspctor will make the new component have a Save button. When you are playing your scene, click the save button and it will save out a mesh that is a copy of the plane.

Hope this helps!

---
Tags: unity, c#, 3d-meshes, cloth
---


# Question
Title: Get a warning about extension when compile GLSL code with glslc compiler shipped with vulkan SDK
Trying to compile my pixel shader,and a warning generated:

> D:\CS\ComputerGraphics\vulkan\WindowsProject1\>D:\ProgrammingTools\vulkan\Bin\glslc shader.frag -o frag.spv shader.frag:3: warning: '#extension' : extension not supported: GL\_KHR\_vulkan\_glsl 1 warning generated.

The following is my pixel shade code:

```
#version 460
#extension GL_ARB_separate_shader_objects : enable
#extension GL_KHR_vulkan_glsl : enable
#extension GL_EXT_debug_printf : enable
//Input
layout(location = 0) in vec3 fragColor;
layout(location = 1) in vec2 fragTexCoord;
//Output
layout(location = 0) out vec4 outColor;
//uniform
layout(set = 0,binding = 2) uniform sampler2D texSampler;
void main() {
    outColor = texture(texSampler, fragTexCoord);
}

```

how do I fix this?

# Answer
It's just a warning!(ummm...it's good to see someone care about those) and doesn't cause any issues in rendering, it just makes sure the shader adhers that glsl is being used to produce spir-v and any shader without this will be rejected by the glsl compiler, moreover glslc has many built-in features to detect such incompatible shaders so I don't think this is necessary. The following below text is from the official docs, you can read more about this extension and probably glslc documentation to see why this is being caused, for now you can safely remove `#extension GL_KHR_vulkan_glsl : enable` and compile with 0 warnings.

```
This extension is not enabled with a #extension as other extensions are.
It is also not enabled through use of a profile or #version.  The intended
level of GLSL/ESSL features, independent from Vulkan-specific usage, comes
from the traditional use of #version, profile, and #extension.

Instead, use of this extension is an effect of using a GLSL front-end in a
mode that has it generate SPIR-V for Vulkan.  Such tool use is outside the
scope of using the Vulkan API and outside the definition of GLSL and this
extension. See the documentation of the compiler to see how to request
generation of SPIR-V for Vulkan.

When a front-end is used to accept this extension, it must error check and
reject shaders not adhering to this specification, and accept those that
do.  Implementation-dependent maximums and capabilities are supplied to, or
part of, the front-end, so it can do error checking against them.

```

source : https://github.com/KhronosGroup/GLSL/blob/ab928c80851b96f3889f1287d4ce0003a9bb86e4/extensions/khr/GL\_KHR\_vulkan\_glsl.txt#L100-L114
> 3 votes

---
Tags: shaders, glsl, vulkan
---


# Question
Title: Is speed and direction generally combined into one vector, or separated into two?
Couldn't find this answered already, surprisingly.

For example, for a game (in my case a 2D top-down one), there could be advantages to doing so. For example, whenever you want to change an entity's direction, you just assign `entity.direction = unitVector` and bam, the direction is changed.

Similarly, if you want to apply a powerup that increases their speed, you just do `entity.speed += 5`, since it's a scalar value.

However, I also see advantages to keeping them combined. For one, a vector is *already* the combination of magnitude and direction, so it feels natural to combine into a single value. Secondly, it prevents desync. For example, if you have some sort of function that modifies the an entity's velocity, you have to constantly check whether you're dealing with direction or speed, and also be sure to update both values independently, which can be confusing.

How is this generally handled in the majority of cases? Are they combined, or not? And if they are combined, what are the recommended ways of changing *just* the speed, or changing *just* the direction of this combined vector value?

# Answer
The speed vector, as all vectors, is already made of a magnitude and a direction. More specifically, you can compute the magnitude and direction from the vector.
Take for example the vector \\$ \vec{v} = \begin{pmatrix} 1 \\ 1 \end{pmatrix} \\$ . You can extract the magnitude (\\$ \sqrt{2} \\$ ) and the direction (\\$\begin{pmatrix} 1 \\ 1 \end{pmatrix} \\$, 45° assuming 0° is horizontal pointing to the right).
Were you to split that info into a vector and a scalar, you'd be using a 2D vector and a float instead of just a 2d vector.

Storing the vector allows you to make the computation you need. Powerup? Multiply the vector by a scalar, it'll be the same as multiplying the magnitude. Need to change only the direction? Either use quaternions, rotation matrices or plain trigonometry depending on your engine.
> 3 votes

---
Tags: physics, mathematics, javascript, movement, vector
---


# Question
Title: How to make the snake bodyParts follow same places and directions as the player on a curved surface?
I try to make a game like the classic snake game but on a round ground (Earth). On a plane, the script works well, but when i moved it on a sphere, the bodyparts (prefabs), are not working good as you can see in the picture ( they are going right/left, but they do not sit on the spehre and i tried already to use sphere collider, box collider, rigidbody) and i dont know really how to make it so that they will follow 100% correctly the player. Thanks for help! :/ . Here i put the script for the Player and bodyparts:

```
using System.Collections;

using System.Collections.Generic;

using UnityEngine; using UnityEngine.UI;

public class PlayerMovementScript : MonoBehaviour {

protected Joystick joystick;
public float speed;
[SerializeField] private float turnFactor;
[SerializeField] private Transform planet;
public List<Transform> bodyParts = new List<Transform>();
public float minDistance = 0.25f;
public int beginSize;
public float rotationSpeed = 50;
public float timeFromLastRetry;
public GameObject bodyprefabs;
public Text currentScore;
public Text scoreText;
public GameObject deadScreen;
private float dis;
private Transform curBodyPart;
private Transform PrevBodyPart;

public bool isAlive;
 void Start()
{
 joystick = FindObjectOfType<Joystick>();
 speed = 3f;
 StartLevel();
}
public void StartLevel()
{
 timeFromLastRetry = Time.deltaTime;
 //deadScreen.SetActive(false);
 for (int i = bodyParts.Count -1; i > beginSize; i++)
 {
     Destroy(bodyParts[i].gameObject);
     bodyParts.Remove(bodyParts[i]);
 }
 bodyParts[0].position = new Vector3(0, 0.5f, 0);
 for (int i = 0; i < beginSize - 1; i++)
 {
     AddBodyPart();
 }
 bodyParts[0].position = new Vector3(0, 0.5f, 0);
 bodyParts[0].rotation = Quaternion.identity;
 currentScore.gameObject.SetActive(true);
 currentScore.text = "Score: 0";
 isAlive = true;
}
void Update()
{
 if (isAlive)
       Move();
 if (Input.GetKey(KeyCode.Q))
     AddBodyPart();
 //RotateAroundPlanet();
 var rb = GetComponent<Rigidbody>();
 //rb.velocity = new Vector3(joystick.Horizontal * 100f, rb.velocity.y, joystick.Vertical * 100f);
}
public void Move()
{
 float curspeed = speed;
 //if (Input.GetKey(KeyCode.W))
 //    curspeed *= 2;
 bodyParts[0].Translate(bodyParts[0].forward * curspeed * Time.smoothDeltaTime, Space.World);
 if (Input.GetAxis("Horizontal") != 0)
     bodyParts[0].Rotate(Vector3.up * rotationSpeed * Time.deltaTime * Input.GetAxis("Horizontal"));
 for (int i = 1; i < bodyParts.Count; i++)
 {
     curBodyPart = bodyParts[i];
     PrevBodyPart = bodyParts[i - 1];
     dis = Vector3.Distance(PrevBodyPart.position, curBodyPart.position);
     Vector3 newpos = PrevBodyPart.position;
     newpos.y = bodyParts[0].position.y;
     float T = Time.deltaTime * dis / minDistance * curspeed;
     if (T > 0.5f)
         T = 0.5f;
     curBodyPart.position = Vector3.Slerp(curBodyPart.position, newpos, T);
     curBodyPart.rotation = Quaternion.Slerp(curBodyPart.rotation, PrevBodyPart.rotation, T);
 }
}
public void AddBodyPart()
{
 Transform newpart = (Instantiate(bodyprefabs, bodyParts[bodyParts.Count - 1].position,
 bodyParts[bodyParts.Count - 1].rotation) as GameObject).transform;
 newpart.SetParent(transform);
 bodyParts.Add(newpart);
 currentScore.text = "Score: " + (bodyParts.Count - beginSize).ToString();
}
public void Die()
{
 isAlive = false;
 scoreText.text = "Your score was: " + (bodyParts.Count - beginSize).ToString();
 currentScore.gameObject.SetActive(false);
 deadScreen.SetActive(true);
}

```

# Answer
> 0 votes
If the planet and body parts are all spheres, you don't even need to use colliders or physics. Keep in mind that by definition, every single point on the surface of a perfect sphere is exactly the same distance from the center of the sphere (that distance being the sphere's radius). Using this fact and `Vector3.MoveTowards()`, we can easily implement logic to move along a sphere's surface.

```
[SerializeField] private Transform sphere; //set in Inspector
float bodyPartSpacing = 1; //change to suit the size of your body parts
float sphereRadius = 10; //change to suit the size of your sphere
void Update() {
    //other code goes here
    //[...]

    //align the snake's head to the surface of the sphere
    SetDistance(bodyParts[0], sphere, sphereRadius + bodyPartSpacing / 2f);
    //align body parts
    for (int i = 1; i < bodyParts.Count; i++) {
        curBodyPart = bodyParts[i];
        prevBodyPart = bodyParts[i - 1];
        //align to previous body part
        SetDistance(curBodyPart, prevBodyPart, bodyPartSpacing);
        //align to surface of sphere
        SetDistance(curBodyPart, sphere, sphereRadius);

        //update rotation; simply look at the previous body part
        //while maintaining "up" as directly-away-from-the-sphere
        Vector3 up = curBodyPart.position - sphere.position;
        curBodyPart.LookAt(prevBodyPart.positiion, up);
    }
}

//Move 'a' so that it is 'desiredDistance' units from 'b'
private void SetDistance(Transform a, Transform b, float desiredDistance) {
     float distance = Vector3.Distance(a.position, b.position);
     float excess = distance - desiredDistance;
     a.position = Vector3.MoveTowards(a.position, b.position, excess);
}

```

# Answer
> -1 votes
One very simple way to do this would be to only move the front ball and attach each ball to the next ball with a joint component. Here is a useful video describing all the joint components in unity: https://www.youtube.com/watch?v=MElbAwhMvTc.

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


title: Place Buildings to represent village

text:
# Question
Title: Place Buildings to represent village
I try to convert an array of Buildings into a representation of a small village. There are several different buildings in a village, like factories that are located on the outside of the village, houses that are placed around churches in the center and so on. What would be a good approach to solve such a problem? I thought about using noise but this didn't give me the expected results.

I made a little drawing on what should happen:

I put an array of Buildings like this, for example, through a function

```
{ houses: 20, churches: 3, factories: 7 }

```

And i recieve a output similar to this:

Thank you for your help and ideas

# Answer
> 5 votes
One approach is to simulate natural growth of a real village.

* Looks good and organic.
* May be iterated to expand forever.
* Easily adopts to existing terrain (rivers, forests, cliffs).

Start with a house in the middle of the area. These are your first settlers.

Choose a building type that is most needed next, considering what was built already and what is yet in the queue. For example, citizens want no more than 1 church per 5 houses.

Next, choose a good location: sample N random unoccupied locations near existing buildings and rate them based on citizens' preferences. For example, people don't like factories in the middle of the city (that is, near churches and crowded housings).

Place a building. Repeat planning and allocation until queue is exhausted. Output example (imaginary):

# Answer
> 4 votes
## Rule based placement

This approach will probably need revising once you start having more different building types and rules to their placement, but the task is assumed to be exactly as specified and should be able to expand somewhat as needed:

* List of fixed building types as input.
* Each building type comes with a set of rules for placement.
* Buildings are laid out on a regular grid.

I will now add a fourth constraint that is not explicitly specified:

* Buildings are placed in a specific order.

This is needed because some buildings depend on other buildings to be placed first.

In your sample, churches should be placed first, then the houses, then the factories.

So we adjust your array to use the new order - not to complicate with yet another data point to store:

```
{churches: 3, houses: 20, factories: 7}

```

Then, we iterate over this array.

For each element, we do the following:

### Pick a location

Iterate over all possible locations - either one by one, down and across (a standard `x,y` loop), or by picking a random unoccupied location - this is probably the better choice to avoid bias, although there are probably even better methods that I am not aware of.

### Rule function

Once a location is picked, you run a *rule function* that is unique per building type. This function either returns success or failure. On success, the building is placed and the building count is decreased by one. If the building count becomes 0 or less, move onto next building type. On failure, new location is picked and the rule function runs again - see bottom regarding infinite loops.

For a church, for example, the rule function is a random chance that becomes bigger towards the centre and smaller towards the edges - this will probably work better with the random location method, otherwise your chance would have to be highly nonlinear - nearly 1 in the centre, nearly 0 at the edges but maybe only 0.2 or something halfway through. Even then, there will likely be a bias towards whichever corner is your `0,0` on the map.

It may also be useful to store an additional grid that has a kind of a distance map to each placed church - initialised to a very large value like 9999, and once a church is placed, its corresponding grid position is set to 0, its neighbours to 1 and so on - for performance reasons maybe only going to 5 or 6 which should be enough anyway. Make sure never to overwrite a lower value with the higher one - after all it's the distance to the *closest*, not to *this specific* church that is being used.

The rule function then would make use of this value to make sure churches don't get placed too close to each other.

For a house the rule function would determine chance based on a church being nearby - nearly 1 next to one, lesser far away. It would also benefit from the "church proximity map" we created earlier.

Finally, factories can be placed at the edges with a rule function that only returns success if the location is an edge.

## Further thoughts and improvements

It may be a good idea to keep some kind of a "failure counter" to prevent infinite loops - after every failure of a rule function, it is incremented, and if it passes a high value like 1000 (this will probably need tuning and scaling based on map size), we give up on placing these buildings: the building counter is exhausted and we move on.

Some way of checking value validity - make sure total building count is not bigger than the map can fit - the above counter would prevent the worst but it's still a good idea to keep some value sanity.

# Answer
> 2 votes
With the following assumptions:

* You have a maximum number of building of each kind to place.
* You have adjacency rules (such as: House can be adjacent to House, Church and Factory; Church can be adjacent to House; and Factory can be adjacent to House and Factory).

You can do this (explanations in comments, ugly details to make it work in JavaScript at the end of the code):

```
var all_positions = GetAllPositions();
var building_counts = {Church:3,House:20,Factory:7};
var building_kinds = RemainingBuildings(building_counts);
var rules = {Church:["House"],House:["Church","House","Factory"],Factory:["House","Factory"]};

// Start position and building
var position = PickRandomItemFrom(all_positions);
var building = PickRandomItemFrom(building_kinds);
SetBuilding(position, building);
Decrement(building_counts, building);

// Set of available positions to place buildings
var free_set = [];
for (const neighbor_position of NeighborsPositions(all_positions, position))
{
    Add(free_set, neighbor_position);
}

// Place more buildings
while (free_set.length > 0)
{
     // Set of all buildings that could be placed at the position
     var possible_buildings = RemainingBuildings(building_counts);
     // If there are posible buildings to place, we are done
     if (possible_buildings.length == 0)
     {
         break;
     }

     // Pick position
     position = RemoveAtRandomFrom(free_set);
     // Check neighbors
     var free_neighbors = [];
     for (const neighbor_position of NeighborsPositions(all_positions, position))
     {
         if (HasBuilding(neighbor_position))
         {
             // We found a neighbor building
             // Update the set of possible buildings to place accordingly
             var found_building = GetBuilding(neighbor_position);
             var valid_buildings = ValidNeighborBuildings(rules, found_building);
             possible_buildings = Intersect(possible_buildings, valid_buildings);
             // Early exit if there are no possible buildings to place
             if (possible_buildings.length == 0)
             {
                 break;
             }
         }
         else
         {
             // We found a posible position to add more buildings
             Add(free_neighbors, neighbor_position);
         }
     }

     // If there are posible buildings to place, we place none
     if (possible_buildings.length == 0)
     {
         continue;
     }

     // Pick a building to place and place it
     building = PickRandomItemFrom(possible_buildings);
     SetBuilding(position, building);
     Decrement(building_counts, building);
     // Update set of available positions (only when we placed something)
     for (const free_neighbor of free_neighbors){
         Add(free_set, free_neighbor);
     }
}

// ---
// UGLY DETAILS
// ---

function GetAllPositions(){
    return document.getElementsByTagName("td");
}

function Decrement(counts, key){
    counts[key]--;
    if (counts[key] == 0){
       delete counts[key];
    }
}

function PickRandomItemFrom(items){
    return items[items.length * Math.random() << 0]
}

function RemoveAtRandomFrom(items){
    var index = items.length * Math.random() << 0;
    var result = items[index];
    items.splice(index, 1);
    return result;
}

function SetBuilding(position, building){
    const representations = {Church: "⛪", House: "", Factory: ""};
    position.innerText = representations[building];
}

function HasBuilding(position){
    return position.innerText != "_";
}

function GetBuilding(position){
    const representations = {"⛪": "Church", "": "House", "": "Factory"};
    return representations[position.innerText];
}

function RemainingBuildings(items){
    return Object.keys(items);
}

function Add(items, item){
    if (!items.includes(item)){
        items.push(item);
    }
}

function ValidNeighborBuildings(rules, building){
    return rules[building];
}

function Intersect(a, b){
   return a.filter(value => b.includes(value));
}

function AddIfNotNull(array, item){
   if (item == null){
        return;
   }

   array.push(item);
}

function GetOrNull(array, index){
    if (array == null || index < 0 || index >= array.length){
        return null;
    }

    return array[index];
}

function NeighborsPositions(all_positions, position){
    // Actually a position is a DOM element
    // And I don't use the array of all positions
    // because it does not have adjacency information
    // Instead I query the DOM
    // This is not at all what you would do for your game
    var _ = all_positions;
    var result = [];
    AddIfNotNull(result, position.nextElementSibling);
    AddIfNotNull(result, position.previousElementSibling);
    var parent = position.parentElement;
    var nextRow = parent.nextElementSibling;
    var prevRow = parent.previousElementSibling;
    var siblings = Array.from(parent.children);
    var siblingNumber = siblings.indexOf(position);
    AddIfNotNull(result, GetOrNull(nextRow?.childNodes, siblingNumber));
    AddIfNotNull(result, GetOrNull(prevRow?.childNodes, siblingNumber));
    // // Diagonals
    // AddIfNotNull(result, GetOrNull(nextRow?.childNodes, siblingNumber - 1));
    // AddIfNotNull(result, GetOrNull(nextRow?.childNodes, siblingNumber + 1));
    // AddIfNotNull(result, GetOrNull(prevRow?.childNodes, siblingNumber - 1));
    // AddIfNotNull(result, GetOrNull(prevRow?.childNodes, siblingNumber + 1));
    return result;
}
```

```
td{width:20px;}
```

```
<table>
<tr><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td></tr>
<tr><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td></tr>
<tr><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td></tr>
<tr><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td></tr>
<tr><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td></tr>
<tr><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td></tr>
<tr><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td></tr>
<tr><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td></tr>
</table>
```

Please note that this code is based on neighbors (adjacency), not on a grid. And thus it is not limited by the size of the grid. In fact, it could work on any graph.

I'm aware this does not properly capture the idea that factories must be on the outside. You may consider the initial position the "center", and use the distance to it for a weighted random that to make some buildings more common the further away from it they are. *In fact, in this implementation each buildings type has the same weight, consider taking into account the number of buildings to place for the weight.* You may also try introducing another kind of rule: this building can only be placed when there are no buildings of this other kind to place. So you can have factories be placed only when all houses are placed.

---

**Addendum: Updated the code to only place factories when there are no houses left to place.**

A factory surrounded by houses is still possible. That might happen when the code managed to leave a hole when placing houses.

```
var all_positions = GetAllPositions();
var building_counts = {Church:3,House:20,Factory:7};
var building_kinds = RemainingBuildings(building_counts);
var adjacency_rules = {Church:["House"],House:["Church","House","Factory"],Factory:["House","Factory"]};
var unlock_rules = {Church:[],House:[],Factory:["House"]};

// Start position and building
var position = PickRandomItemFrom(all_positions);
var building = PickRandomItemFrom(building_kinds);
SetBuilding(position, building);
Decrement(building_counts, building);

// Set of available positions to place buildings
var free_set = [];
for (const neighbor_position of NeighborsPositions(all_positions, position))
{
    Add(free_set, neighbor_position);
}

// Place more buildings
while (free_set.length > 0)
{
     // Set of all buildings that could be placed at the position
     var possible_buildings = AvailableBuildings(unlock_rules, building_counts);
     // If there are posible buildings to place, we are done
     if (possible_buildings.length == 0)
     {
         break;
     }

     // Pick position
     position = RemoveAtRandomFrom(free_set);
     // Check neighbors
     var free_neighbors = [];
     for (const neighbor_position of NeighborsPositions(all_positions, position))
     {
         if (HasBuilding(neighbor_position))
         {
             // We found a neighbor building
             // Update the set of possible buildings to place accordingly
             var found_building = GetBuilding(neighbor_position);
             var valid_buildings = ValidNeighborBuildings(adjacency_rules, found_building);
             possible_buildings = Intersect(possible_buildings, valid_buildings);
             // Early exit if there are no possible buildings to place
             if (possible_buildings.length == 0)
             {
                 break;
             }
         }
         else
         {
             // We found a posible position to add more buildings
             Add(free_neighbors, neighbor_position);
         }
     }

     // If there are posible buildings to place, we place none
     if (possible_buildings.length == 0)
     {
         continue;
     }

     // Pick a building to place and place it
     building = PickRandomItemFrom(possible_buildings);
     SetBuilding(position, building);
     Decrement(building_counts, building);
     // Update set of available positions (only when we placed something)
     for (const free_neighbor of free_neighbors){
         Add(free_set, free_neighbor);
     }
}

// ---
// UGLY DETAILS
// ---

function GetAllPositions(){
    return document.getElementsByTagName("td");
}

function Decrement(counts, key){
    counts[key]--;
    if (counts[key] == 0){
       delete counts[key];
    }
}

function PickRandomItemFrom(items){
    return items[items.length * Math.random() << 0]
}

function RemoveAtRandomFrom(items){
    var index = items.length * Math.random() << 0;
    var result = items[index];
    items.splice(index, 1);
    return result;
}

function SetBuilding(position, building){
    const representations = {Church: "⛪", House: "", Factory: ""};
    position.innerText = representations[building];
}

function HasBuilding(position){
    return position.innerText != "_";
}

function GetBuilding(position){
    const representations = {"⛪": "Church", "": "House", "": "Factory"};
    return representations[position.innerText];
}

function RemainingBuildings(building_counts){
    return Object.keys(building_counts);
}

function AvailableBuildings(unlock_rules, building_counts){
    var remaining_buildins = RemainingBuildings(building_counts);
    var result = Object.keys(building_counts);
    var buildings = Object.keys(unlock_rules);
    for (const building of buildings){
        for (const contraint of unlock_rules[building]){
            if (remaining_buildins.includes(contraint)){
                var index = result.indexOf(building);
                if (index !== -1) {
                    result.splice(index, 1);
                }
            }
        }
    }

    return result;
}

function Add(items, item){
    if (!items.includes(item)){
        items.push(item);
    }
}

function ValidNeighborBuildings(rules, building){
    return rules[building];
}

function Intersect(a, b){
   return a.filter(value => b.includes(value));
}

function AddIfNotNull(array, item){
   if (item == null){
        return;
   }

   array.push(item);
}

function GetOrNull(array, index){
    if (array == null || index < 0 || index >= array.length){
        return null;
    }

    return array[index];
}

function NeighborsPositions(all_positions, position){
    // Actually a position is a DOM element
    // And I don't use the array of all positions
    // because it does not have adjacency information
    // Instead I query the DOM
    // This is not at all what you would do for your game
    var _ = all_positions;
    var result = [];
    AddIfNotNull(result, position.nextElementSibling);
    AddIfNotNull(result, position.previousElementSibling);
    var parent = position.parentElement;
    var nextRow = parent.nextElementSibling;
    var prevRow = parent.previousElementSibling;
    var siblings = Array.from(parent.children);
    var siblingNumber = siblings.indexOf(position);
    AddIfNotNull(result, GetOrNull(nextRow?.childNodes, siblingNumber));
    AddIfNotNull(result, GetOrNull(prevRow?.childNodes, siblingNumber));
    // // Diagonals
    // AddIfNotNull(result, GetOrNull(nextRow?.childNodes, siblingNumber - 1));
    // AddIfNotNull(result, GetOrNull(nextRow?.childNodes, siblingNumber + 1));
    // AddIfNotNull(result, GetOrNull(prevRow?.childNodes, siblingNumber - 1));
    // AddIfNotNull(result, GetOrNull(prevRow?.childNodes, siblingNumber + 1));
    return result;
}
```

```
td{width:20px;}
```

```
<table>
<tr><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td></tr>
<tr><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td></tr>
<tr><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td></tr>
<tr><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td></tr>
<tr><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td></tr>
<tr><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td></tr>
<tr><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td></tr>
<tr><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td><td>_</td></tr>
</table>
```

This also gives me yet another idea: we can define constraints by number of neighbors. For example we could say that a factory can have one or two house neighbors, but not more. *That would also prompt some refactoring, since I would rather be working with generators (`function*` and `yield` in JavaScript). The idea would be to have a generator that gives me the neighbors, then I can pass it to a function that gives the list of valid buildings. I will not do it for this answer.*

---
Tags: 2d, algorithm, sprites, procedural-generation
---


# Question
Title: How do I resolve a collision in SAT-3D when the projection axis is zero?
I am doing SAT in 3D, right now just between cuboids/3D rects (idk the terminology). I have intersection working fully, and static collision works as long as the projection axis is not zero. But if it is zero, I am unsure how to get the minimum translation vector and overlap.

Here is the function which returns the face normals, vertices are ordered counter-clockwise starting bottom left - z for face 1, then repeat for +z, where 4 is bottom left +z:

```
    private float3[] GetAxesFromPoly( float3[] vertices )
    {
        float3[] axes = new float3[ 3 ];
        axes[ 0 ] = math.normalize( ( vertices[ 1 ] - vertices[ 0 ] ) );
        axes[ 1 ] = math.normalize( ( vertices[ 3 ] - vertices[ 0 ] ) );
        axes[ 2 ] = math.normalize( ( vertices[ 4 ] - vertices[ 0 ] ) );

        return axes;
    }

```

And here is all axes I get to test:

<pre><code>        float3[] axesA = GetAxesFromPoly( vertsA );
        float3[] axesB = GetAxesFromPoly( vertsB );

        float3[] allAxes = new float3[ 15 ];
        allAxes[ 0 ]  = axesA[ 0 ];
        allAxes[ 1 ]  = axesA[ 1 ];
        allAxes[ 2 ]  = axesA[ 2 ];
        allAxes[ 3 ]  = axesB[ 0 ];
        allAxes[ 4 ]  = axesB[ 1 ];
        allAxes[ 5 ]  = axesB[ 2 ];
        allAxes[ 6 ]  = math.cross( axesA[ 0 ] , axesB[ 0 ] );
        allAxes[ 7 ]  = math.cross( axesA[ 0 ] , axesB[ 1 ] );
        allAxes[ 8 ]  = math.cross( axesA[ 0 ] , axesB[ 2 ] );
        allAxes[ 9 ]  = math.cross( axesA[ 1 ] , axesB[ 0 ] );
        allAxes[ 10 ] = math.cross( axesA[ 1 ] , axesB[ 1 ] );
        allAxes[ 11 ] = math.cross( axesA[ 1 ] , axesB[ 2 ] );
        allAxes[ 12 ] = math.cross( axesA[ 2 ] , axesB[ 0 ] );
        allAxes[ 13 ] = math.cross( axesA[ 2 ] , axesB[ 1 ] );
        allAxes[ 14 ] = math.cross( axesA[ 2 ] , axesB[ 2 ] );
```
</code></pre>

# Answer
For anyone who might be facing a similar issue, I found the solution. As you may know we are suppose to disregard any axis which are (0,0,0) (cross product of edges from two shapes is 0), because we cannot project onto a vector of zero, as well we will not be able to get a minimum translation vector or minimum overlap.

In my code, in the loop which goes over each projection axis and projects all vertices onto it, I was early outing if the projection axis was (0,0,0), like this:

```
        for ( int i = 0; i < allAxes.Length; i++ )
        {
            float3 axis = allAxes[ i ];

            if ( axis.x == 0 && axis.y == 0 && axis.z == 0 )
                return true;
        }

```

It was detecting collisions properly, but because I was early outing I could not resolve the collision. Simple fix was to change return to continue.

I know its a silly mistake but maybe someone else new to SAT may find this useful.
> 1 votes

---
Tags: collision-detection, 3d, mathematics, separating-axis-theorem
---


# Question
Title: Given a base class and many derived classes with additional features, what's the best practice for accessing those features?
This might sound strange, but let me explain. Say I want to write a safari program.

In this safari there is an object pool of 10 animals (`Animal*`): 2 ostrich, 5 mosquitos, 2 spiders and a snake. Each of these inherits `Animal`. Both snake and spider are venomous so they have data reflecting it—let's say they additionally inherit `IVenomous`. The mosquito inherits `IFlyer`. The ostrich is left out in the cold with none of these additional features.

With venomous animals around, we'd want to prepare antivenom for the safari. So let's have `prepareAntidote()`. This function's job would be to check what kind of antivenom is needed and simply print it out. As part of implementing `IVenomous`, spider and snake each have the method `const std::string& getVenomName()`. The base `animal` class doesn't have this feature.

The issue then becomes: how do we access the `getVenomName()` method when all we know we have is a list of `Animal`, and we don't know which ones implement `IVenomous` and have a `getVenomName()` method available? What's considered good practice here?

I've considerd a brute force approach of making use of `dynamic_cast<IVenomous*>` while iterating over all animals, but this seems wasteful. And as bad is the fact that `prepareAntidote()` function needs to know what an animal is to handle the pool. So it would most probably be better for it to work on a `container<IVenomous*>&`, wouldn't it?

My idea is to have each interface's constructor register itself with some storage class which keeps a container of pointers for each interface, and de-registers itself on destruction, so we could access a list of `IVenomous` animals directly. So far an `unordered_map` looks the most reasonable for that job, with roughly constant time for access and removal, as well as not invalidating anything except on rehash. The pointer being its own key value.

It's actually the same problem with composition like components for example in games. (That's why I'm writing it here, because of that, chances may be higher to find answers here.) In this case it screams for "object pooling" of course, but let's cast aside memory locality in this case, that should be quite easy to add in later with overloading operator.

# Answer
There's nothing wrong with keeping a container of derived class observing pointers for direct and immediate access while keeping an overall base class container for management:

#include <vector>

#include "Animal.hpp"
#include "Snake.hpp"
#include "Spider.hpp"
#include "Mosquito.hpp"
#include "IVenomous.hpp"
#include "IFlyer.hpp"

std::vector<std::unique_ptr<Animal>> m_Animals{};
std::vector<IVenomous*> m_VenomousAnimals{};
std::vector<IFlyer*> m_FlyingAnimals{};

void RegisterNewSnake() {
    auto newSnake = std::make_unique<Snake>();
    auto* ptr = newSnake.get();
    m_Animals.emplace_back(std::move(newSnake));
    m_VenomousAnimals.push_back(ptr);
}

void RegisterNewSpider() {
    auto newSpider = std::make_unique<Spider>();
    auto* ptr = newSpider.get();
    m_Animals.emplace_back(std::move(newSpider));
    m_VenomousAnimals.push_back(ptr);
}

void RegisterNewMosquito() {
    auto newMosquito = std::make_unique<Mosquito>();
    auto* ptr = newMosquito.get();
    m_Animals.emplace_back(std::move(newMosquito));
    m_FlyingAnimals.push_back(ptr);
}

void RegisterNewOstrich() {
    auto newOstrich = std::make_unique<Ostrich>();
    m_Animals.emplace_back(std::move(newOstrich));
}

std::vector<IVenomous*> GetAllVenomousAnimals() {
    return m_VenomousAnimals;
}

std::vector<IFlyer*> GetAllFlyingAnimals() {
    return m_FlyingAnimals;
}

void RemoveVenomousAnimal(IVenomous* ptr) {
    m_VenomousAnimals.erase(std::remove(std::begin(m_VenomousAnimals), std::end(m_VenomousAnimals), ptr), std::end(m_venomousAnimals));
    m_Animals.erase(std::remove_if(std::begin(m_Animals), std::end(m_Animals), [ptr](const auto& a){ a.get() == ptr; }), std::end(m_Animals));
}

//Similar for RemoveSnake

//Similar for RemoveSpider

void RemoveFlyer(IFlyer* ptr) {
    m_FlyingAnimals.erase(std::remove(std::begin(m_FlyingAnimals), std::end(m_FlyingAnimals), ptr), std::end(m_FlyingAnimals));
    m_Animals.erase(std::remove_if(std::begin(m_Animals), std::end(m_Animals), [ptr](const auto& a){ a.get() == ptr; }), std::end(m_Animals));
}

//Similar for RemoveMosquito

```

> 1 votes

# Answer
If it is important is an animal venomous and how much, document it! Add `getVenomName(){ return "harmless"}` to the base class.
> 0 votes

---
Tags: c++, objects, interface
---


# Question
Title: How do I calculate impulse when an object collides with plane(fixed object)?
I've been developing simple 3D impulse-based physics engine. I calculate impulse as follows: $$j\_r = \frac{-1(1+e)v\_r\cdot\hat n} {m\_1^{-1}+\bbox\[yellow,5px,border:2px solid red\]{m\_2^{-1}}+(I\_1^{-1}(r\_1\times\hat n)\times r\_1+ \bbox\[yellow,5px,border:2px solid red\]{I\_2^{-1}(r\_2\times \hat n)\times r\_2)}\cdot \hat n} $$ where:
\\$e\\$ is restitution constant
\\$\hat n\\$ is a contact normal
\\$v\_r\\$ is relative velocity of the contact point
\\$m\\$ is mass of objects
\\$I\\$ is moment of inertia tensor
\\$r\\$ is a vector from center of mass to contact point

**Note:** I've been assigned value 0.0f to the boxed/highlighted terms in the expression when an object collides with plane.

Then update linear & angular velocity as below:
$$ \begin{align} v'\_1&=v\_1-\frac{j\_r}{m\_1}\hat n \\ v'\_2&=v\_2+\frac{j\_r}{m\_2}\hat n \end{align} $$ $$ \begin{align} \omega'\_1&={\omega}\_1-j\_rI\_1^{-1}(r\_1\times\hat n) \\ \omega'\_2&={\omega}\_2+j\_rI\_2^{-1}(r\_2\times\hat n) \end{align} $$

Those expressions are referenced from the Wikipedia *collision response* entry.

It works well when two objects collide.
However, the box object rotates strangely and continuously glide around when it collides with plane as below:

(red sphere is detected contact point)

I set contact normal as plane normal.
I assume that the expression has to be modified for the case of fixed object (ex. plane).
I've been assigned value 0.0f to the boxed/highlighted terms in the expression when an object collides with plane.
Is this approach right?
If it isn't, how can I fix this?

# Answer
> 1 votes
This issue was caused by mismatch of coordinates system.
I've assumed that my rigid body class has saved angular velocity vector as **world** coordinates
but it turns out that it was saved as **local** coordinates.
This mistake caused weird movement as above.

---
Tags: collision-resolution, physics-engine
---


# Question
Title: Objects Imported from Blender to Unreal have really zoomed Materials
I've been learning how to use Blender for UE4. I just started figuring out how to define which sides should have materials on them. In particular, I wanted this building to have different materials for the sides and top. However, when I apply the Materials, they're very zoomed in.

At first I thought it was a scale issue, but Unreal supposedly converts the models from FBX units to Unreal units. The scale of the model is exactly the same as the one I made in Blender. And yet, I have this issue.

Since it seemed like a conversion of units issue, I made sure to change Blender to *also* use centimeters just like Unreal, with no scaling or conversion, and yet the issue still arises. I have tried to find a way to shrink the material, with no luck. It seems the only way to do this would be to copy the texture and modify it, but that seems unnecessary. If I wanted to use the same building with a different material, I'd need to do that over and over again.

Is there something I'm missing when Exporting from Blender and Importing into UE4?

I am using Unreal Engine 2.25.1, and Blender 2.83.1

Thanks for your help!

# Answer
Since you're working with buildings which are fairly square, instead of UV unwrapping you can try projections. https://exposeacademy.com/5-methods-of-uvw-box-mapping-in-blender-2-8x/

Try to apply the same texture in Blender, does it appear the same as it does in Unreal? I'm pretty certain as others have suggested here, that it's not an import/scaling issue, but that your UV's are way too small (which tiles the material/maps/textures in a way that makes them appear large)
> 1 votes

# Answer
Blender's units are, by default Metric and 1.0000. Unreal's units are, by default Metric and 0.01000.

You need to go into the unit section of your Blender information, changes the units to 0.01 then try importing.
> 0 votes

---
Tags: unreal-4, blender, 3d-meshes, materials, export
---


# Question
Title: How to connect the Data Layer (Models) with the Visual/Interactive Layer (MonoBehaviours)?
I have been struggling with this dilemma for quite a while already.

Our game is complex enough that we have tons of logic in normal C# scripts that function very independently of any Unity specific component.

This logic is eventually modifying the Data Layer which is basically a batch of simple Classes with state that we call Models.

Everything works fine until we have to connect this Layer with the visualization layer (aka Unity MonoBehaviours)

These are the approaches I have tried (they all work but I am not totally satisfied with any)

## Using a MonoBehaviourWrapper

I have a MonoBehaviour class with only one property:

```
[SerializeField] DataModel _dataModel;

```

I call it `ModelMonoBehaviourWrapper`

I have a GameObject in the Scene to visualize the state of the Model I call it `ModelView`

I have a script that listens to changes in the Model and modifies the `ModelView`. I call it `ModelViewController`. This requires access to the Model to listen to changes so it has this property:

```
[SerializeField] ModelMonoBehaviourWrapper _modelMonoBehaviourWrapper;

```

I attach `ModelViewController` to the `ModelView` GameObject as component (The property \_modelMonoBehaviourWrapper remains unlinked at this moment)

I have a GameObject in the Scene as a holder of all the internal logic. I call it `SceneManager`. This GameObject has an script attached called `SceneManagerController` who is in charge of running the Game. This script has, therefore, access to the Data Models. This script has also this property:

```
[SerializeField] ModelMonoBehaviourWrapper _modelMonoBehaviourWrapper;

```

I attach a `ModelMonoBehaviourWrapper` Script as a component to `SceneManager`, then I link this Component to the property `_modelMonoBehaviourWrapper` in both: `ModelViewController` on `ModelView` and `SceneManagerController` in `SceneManager`

This way I manage to have the same Model instance connected in `ModelViewController` and `SceneManagerController`.

I initialize ModelMonoBehaviourWrapper.\_dataModel through `SceneManagerController` and I can read it from `ModelViewController`.

If you think this is over-messy I also think the same. There are also some initialization race condition problems, for example if you are trying to access to the Model (through `ModelMonoBehaviourWrapper`) in `ModelViewController` before `SceneManagerController` has initialized it. If you are careful it works though.

Here you have a diagram trying to represent this structure:

## Using a public static pointer to SceneManagerController

In a similar structure as above but instead of using the `ModelMonoBehaviourWrapper` to make the Model accessible in both Controllers I make the `SceneManagerController` public and static like this:

```
public static SceneManagerController Instance;

```

This way I can access to the `Model` from the `ModelViewController` like this:

```
SceneManagerController.Instance.GetModel();

```

This works, but I am concerned about the strong counter-intuitive dependency generated here. I would like `ModelViewController` to be depended only in the `Model` but now it is depending on this intermediate class `SceneManagerController` just to have access to the model

Diagram:

## Using the SceneManagerController as a Initializer Orchestrator

The `SceneManagerController` can contain references to all elements, not only the Data Models (that it already has), but also to all Visual GameObjects like:

```
[SerializeField] GameObject ModelView;

```

This way SceneManagerController can instantiate the `ModelViewController` and give it access to the Model and to the View element.

This way I keep `ModelViewController` only dependent to the Model. I am adding all references to the SceneManagerController what is even helpful because this way I have to only wire Component Properties in one GameObject.

I am playing with this structure right now. The problem I see is that now the `SceneManagerController` becomes too much dependent in the set up of the Scene and I can not Add/Remove Scene elements easily because they are not self-managed as it is the case in the previous above architectures.

Diagram:

I would like to know, from people with experience in similar situations, how you have solved it and what solutions you have found more solid and maintainable.

### Update 1

Answering to some questions in the comments:

**Are you using or aware of RX?**

No, I am reading now:

It looks like nice solutions to have code reacting to changes in a Model. We are solving this problem with basic EventHandlers..

But even if I integrate RX, if I understood it properly, I will have the same problem: how can I share a Model instance between my DataLayer/GameLogicLayer (where the instance has been created) and the VisualLayer (MonoBehviour scripts in the Scene GameObjects, where the the scripts are listening to changes in the instance?

**Is there specific reason for data layer being owned by a game object, as opposed to a program itself?**

Not necessarily, a part of having things separate. I am ok of having a DataManager storing all the Models.

**Is DI/IoC used for data layer?**

Yes we have different level of DI/IoC implementations

**What sort of component is responsible for creating data-layer-game-object?**

The Models instances are created in the **DataManager.cs** which acts as a factory. But they are owned by the GameScripts that needed to create them.

**Is there a controller on a data layer to communicate with a scene/engine?**

**DataManager.cs** has static public methods to instantiate Models. These methods can be accessed by the Scene/Engine scripts

# Answer
The idiomatic way of using Unity is that your should not separate your game architecture into models, views and controllers. A gameObject should contain its own data, logic and presentation, distributed among multiple MonoBehaviours, where each behaviour represents a single functionality of that gameObject. And when you have data which is shared between multiple gameObjects, that data should be in form of assets implemented as ScriptableObject's.

Nevertheless, creating an MVC architecture on top of Unity can in some cases have its advantages. Those often outweigh the drawbacks for games with mechanics which are mostly abstract and not driven by the Unity physics engine. The greatest advantage in my opinion is that having the whole state of the game in a well-encapsulated data model makes it a lot easier to implement savegames, which otherwise can get pretty ugly in Unity.

However, your particular implementation appears quite over-engineered to me. My usual approach to this pattern (when I choose to implement it) is a far simpler one:

1. Create a plain old C# class representing your whole model. I usually call this class `GameState`.
2. Give that class a `public static GameState current` property, which retrieves the current game state.The initialization problem can be solved by making this a property which initializes a default GameState when accessed for the first time ( `if (current == null) current = new GameState(); return current;`). You should also have a static method `Load(string filename)` to replace `current` with a GameState deserialized from a savegame file.
3. Give each instance of each class in your model an ID.
4. Give the GameState class public accessor methods to retrieve model entities by ID. Like `GetCharacter(int id)`, `GetCity(int id)` or `GetFaction(int id)`. Those methods *can* return the actual entity, or just as well return an interface or facade instead through which the current state of that entity can be accessed.
5. When a MonoBehavior needs to reference some class from the model, then implement it like that:

---

```
class CharacterView : MonoBehaviour {
       public int characterId = 0;
       private model.Character data;

       void Start() {
           data = GameState.current.GetCharacter(characterId);
       }

       void FixedUpdate() {
            transform.SetPositionAndRotation(
                data.currentLocation,
                Quaternion.Euler(0f, data.direction, 0f)
            );
       }
}

```

When creating an instance of this MonoBehaviour (in the editor or via the Instantiate method from a script), you then have to assign the characterId. This example script does not support changing the characterId after the object was created. Usually I don't see a need for that, because there are few situations where I would ever want to reuse one of these gameObjects for a different entity instead of just creating a new one. But if you need that (when you want to do object pooling, for example), then hide characterId behind a property which again calls `data = GameState.current.GetCharacter(characterId);` in its setter.

---

Which gets us to the next problem: Instantiating and destroying a gameObject whenever an entity is created or removed in the model.

When a controller decides to add a new entity to the model, then that usually means that you need to Instantiate a new gameObject and set the corresponding ID on each of its behaviours. But you likely don't want any `using UnityEngine` in your model *or* your controllers. You certainly want them to be as independent from the engine as possible. The best solution in my opinion is using C# events for that.

Give the GameState a bunch of public events like `onCreateCharacter`, `onRemoveCharacter` etc.. which it invokes whenever a controller does one of these things. Then have single MonoBehaviours in your scene like this one, which instantiates objects for all entities already in the model and then subscribes to those events to instantiate more or remove those it spawned before:

```
public CharacterSpawner : MonoBehaviour {

     public GameObject characterPrefab;

     private Dictionary<int, GameObject> managedCharacters = new Dictionary<int, GameObject>();

     void Start() {
          for(int id in GameState.current.allCharacterIds) {
               CreateCharacter(id);
          }
          GameState.current.onCreateCharacter += CreateCharacter;
          GameState.current.onRemoveCharacter += (id) => {
                Destroy(managedCharacters[id]);
                managedCharacters.Remove(id);
          };

     }

     private void CreateCharacter(int id) {
          GameObject newCharacter = Instantiate(characterPrefab);
          newCharacter.GetComponent<CharacterView>().characterId = id;
          managedCharacters[id] = newCharacter;
     }

}

```
> 1 votes

---
Tags: unity, c#, architecture, monobehaviour
---


# Question
Title: what is the math behind the parenting a transform in unity?
in unity when you parent an object or transform with another object, all transform(position, rotation, scale) are calculated depending on that parent object. sometimes we need to know about the local data of that transform and sometimes we need to know that data based on the world axis.

I need to know how that is implemented in math and vector functions.

# Answer
> 2 votes
Parenting an object essentially means that the object's transform now is relative to the parent's instead of the world's. If the parent object is a `body` for example and the child object is the `arm`, then the body's position in the world is defined by its `bodyTransform` and is relative to the *world coordinates* but the `armTransform` is relative to the *body's space*, which I believe is done via a change of basis on the arm object where the new basis is the body's local basis. This means that you can individually change the arm's position by changing its transform relative to the body (which is what you care about) but if the whole body moves, the arm moves with it since its `armToWorld` transform already contains the `bodyTransform` inside.

# Answer
> 1 votes
You don't really need to know how that is implemented in math and vector functions. Not having to bother with stuff like that is one of the reasons why you are using a game engine in the first place :) But if you *want* to know because it *interests* you:

Internally, Unity implements the whole data of the Transform component with a transformation matrix. A transformation matrix is a collection of 4x4 floating-point values. Encoded in these values is the translation, rotation and scale (and technically also skew, but that's rarely used in 3d graphics).

There is a way to multiply a point (represented as a Vector) with a projection matrix which results in a new point with the rotation, translation and scale applied to it. You can also multiply two projection matrices with each other to get a single new 4x4 matrix which applies the transformations of both matrices one after another. This is how the matrices of transforms in a parent hierarchy are calculated. Unity actually exposes that matrix of a transform and its parent transforms through the property localToWorldMatrix.

OK, but how exactly does that multiplication of a vector with a matrix or a matrix with a matrix work? Lots of people have already written lots of explanations for that which are far better than I could write.

---
Tags: unity, mathematics
---


# Question
Title: Position Object always at the same distance of 2 other moving Objects?
I am making a procedural animation of a worm. I have already something working:

(the green dot is the position Target, purple and red are the Head and the Tail of the Worm)

I would like to add another dot in the center of the Worm to simulate the middle body waving up and down while Head and Tail are moving like this:

I thought that it was going to be easy using some kind of 2D joint, but I tried several and I was not able to find a good result.

I was also thinking that maybe I have to make some trigonometry to calculate the possible positions of Center:

Before I over-engineer the solution what would be your approach to solve this?

# Answer
> 3 votes
My final approach has been using basic trigonometry:

I have `a` and `b` I was just needing to calculate `c`:

```
void MoveCenter()
{
    float a = maxDistance / 2.0f;
    float b = Vector3.Distance(head.position, tail.position) / 2.0f;
    float c = Mathf.Sqrt(Mathf.Pow(a, 2.0f) - Mathf.Pow(b, 2.0f));

    Vector3 headTailCenterPosition = (head.position + tail.position) / 2.0f;
    Vector3 centerTargetPosition = new Vector3(headTailCenterPosition.x, headTailCenterPosition.y + c, headTailCenterPosition.z);

    center.position = Vector3.MoveTowards(center.position, centerTargetPosition, speed * Time.deltaTime);
}

```

The result:

---
Tags: unity, trigonometry, hinge-joint
---


# Question
Title: Is it possible to record video, depth map and 6D pose of any games?
I'm not a game developer, but a researcher working on improving video quality in various contexts. For my current problem, I need to collect videos which have both RGB data as well as depth data. Video can be monocular or stereo. However, if there is egomotion, I'll need the camera pose (rotation and translation) as well. Is there any way to record all these information in any kind of games? Games can be on any platform: PC games, mobile games or VR games.

In short, I want to record gameplay but with additional information such as depth map and camera pose.

# Answer
> 4 votes
One solution is to use DLL injection. This technique facilitates attaching and executing a payload (your code) within the address space of another process (the game or graphics driver) by way of a dynamic link library (DLL).

Once the injected, your payload code would:

* intercept instructions of interest
* process them as needed (log them for later, perform calculations, etc)
* pass the instructions along to the intended recipient (allowing gameplay to continue)

This technique was used in the paper "Playing for Data: Ground Truth from Computer Games" by Richter et al. and in Matthew Fisher's research on Starcraft 2 AI. You can read their work and code for more details.

Caveat: Some developers take significant steps to detect & deter DLL injection as this same technique is sometimes used for the purposes of cheating. Furthermore, some developers attempt to limit the ways their software can be used via terms of service, user license, etc. Proceed accordingly.

---
Tags: camera, depth-buffer, virtual-reality, game-recording, screen-recording
---


title: How to implement an tooltip item cache?

text:
# Question
Title: How to implement an tooltip item cache?
I'm building a tooltip item like that

##

I would like to keep this information cached on the client side, avoiding that whenever the information is displayed it's necessary to make a request to the server, but make the cache is not the problem, the problem is that an item can have its attributes modified and the cache on the client side will show wrong information.

My question is, cache is a good idea? if yes what is the best solution?

# Answer
> 1 votes
I wouldn't worry about caching in this situation.

When the player is looking at an item they don't own, then it is not very likely that they will look at it again in a couple minutes. So caching it longer than a couple seconds is unnecessary.

When the item is in the player's inventory, then I would just provide them with full information on every item as soon as it gets changed. We are not dealing with a lot of information here. Let's take a look at the screenshot, and see how much information we actually got there:

* The icon. The image asset is likely on the client, so you just need to send an ID of the icon to use. Let's assume that your asset IDs are integers (4 byte).
* The item name. When this is a completely server-sided string, that would be 23 byte (22 plus null-terminator). It might be smarter to have a string table of item names on the client-side. That doesn't just make item names localizable, it also means you just need an index to that table (4 byte). But let's assume the worst case that the name is indeed a literal string coming from the server.
* Rarity level. 1 byte.
* "Mythic 15 Titanforged", which is I assume two enumerations which fit into a single byte and an integer (6 byte)
* Item level, another integer (4 byte)
* "Binds when picked up" and "Unique-Equipped". I don't know how many such mechanics you have in your game, but you can likely represent them with a bit-field. Let's be generous and say you got 32 of such flags an item can have. (4 byte)
* "Finger" - an enumeration representing the equipment slot. Likely fits into 1 byte.
* 3 different Integer-bonuses to different stats. 4 byte for the number and 1 byte for the enumeration of the stat, so 12 byte in total. Plus an additional byte for the number of bonuses we got. Whenever you allow `n` of something in your netcode, you need either a number or a stop-byte so the parser knows when the list stops.
* "Required level". 1 byte when your levels go to 256, 2 byte when they go to 65536. Let's be pessimistic and assume 2 byte.
* Vendor-price. Integer (4 byte). Yes, that fancy representation of gold, silver and copper coins is likely handled as a single integer internally.
* "Auction: BOP", not sure what that is, but I assume it's another price (4 byte)
* Disenchant-price. Integer (4 byte)

That leaves us with a total amount of data of a measly 71 byte. You will likely need some more data which isn't visible here as well as some padding and bookkeeping data, so let's be generous and round that to 100 byte. Do you think that sending an additional 100 byte whenever an item in the player's inventory changes will be too much for your network stack to handle? I doubt it. You could even reduce that by implementing incremental updates to item properties (only change new data for the properties which actually changed), but I doubt that this is worth the effort.

# Answer
> 0 votes
The short answer is exactly the same way you would update any other information inside your game. You will generate an update to the item tool-tip anytime that it changes and the cache will display that instead.

---
Tags: c++, mmo
---


# Question
Title: High-performance update of a bitmap grid
I need to visualize a fast paced process in .NET in 2D. I am planning to use writeable bitmap 800x40px.

The idea is like this - there are objects which are represented by very basic colours and sizes anything from 1x1 to 4x4. each takes 4x4 "cell" - they all are fixed like a chess board.

The objects move between cells and change size. Most importantly they move independently, so I cant (I can but I would like to not) have a sort of refresh rate.. I need to animate each object state change - like say pixels pouring from cell to cell. the transition time should be around 500ms.

In this period of time the states can change multiple times so I should be able to abort outdated animation, move object "instantly" to new cell and start more recent object animation which could have taken over the "old" cell..

The accuracy should be in 1-2ms intervals.

The host application is WPF .NET Framework

# Answer
> the accuracy should be in 1-2ms intervals

You are out of luck here, getting high and steady frame-rate in WPF is impossible by design. Still, you can get decent 60Hz, and anything above requires high-frequency display anyways — I expect those to be rarity in a business environment.

> I am planning to use writeable bitmap 800x40px.

`D3DImage` should be a better fit, especially for performance reasons. Drawing a NxN pixels rectangle is easy with either API.

> Most importantly they move independently, so I cant (I can but I would like to not) have a sort of refresh rate.

Objects' independence is irrelevant. So many objects could be (most probably will be) updating at same time, allocating a separate timer for each object is just unreasonable.

To set WPF to continious rendering mode, you need to subscribe for a certain event. Then in each frame you have to update animation states and redraw each particle.

> In this period of time the states can change multiple times so I should be able to abort outdated animation, move object "instantly" to new cell and start more recent object animation which could have taken over the "old" cell.

That can be easily achieved by associating a particle ("object" of yours) with an animation. Animation instructs how to interpolate particle's properties (location and size) between 2 states, it consists of 2 key-frames and a time range. When assigning new animation to a particle with existing animation, don't forget to force previous animation (copy last key-frame's properties as is, no interpolation is necessary).

On each frame a particle should re-calculate it's state from it's animation. First, calculate the animation alpha (capped at 100%) based on current time (`a = (now - Start) / Duration`), then use it to interpolate particle's properties. Once 100% alpha is achieved, delete (or deactivate) the animation.

> where would you start?

Let the code speak:

```
    record Keyframe(Point Location, int Size);

    record Animation(Keyframe From, Keyframe To, DateTime Start, TimeSpan Duration);

    class Particle
    {
        public int Id { get; }
        public Point Location { get; private set; }
        public int Size { get; private set; }

        public Animation Animation { get; set; } // null = disabled
        public void Update(DateTime now); // recalculate itself from the animation
    }

    class SimulationViewModel
    {
        List<Particle> particles;
        void Update(DateTime now); // for each particle do ...
        void Move(int ParticleId, Keyframe from, Keyframe to); // setup the animation; duration is constant, start time is now
    }

```
> 2 votes

---
Tags: 2d, animation, performance, frame-rate, .net
---


# Question
Title: Getting a surface compatible with the texture / renderer
I'm trying to convert my emulator to SDL2 (from SDL 1.2).

As I'm drawing pixel per pixel, I follow "If your game just wants to get fully rendered frames to the screen" in the migration guide: https://wiki.libsdl.org/MigrationGuide#If\_your\_game\_just\_wants\_to\_get\_fully-rendered\_frames\_to\_the\_screen

I basically do:

```
SDL_CreateWindowAndRenderer(...);
vid = SDL_CreateRGBSurface(..., bpp, ...);
texture = SDL_CreateTextureFromSurface(renderer, vid);

// ... and then later, when "blitting" ...

SDL_UpdateTexture(texture, NULL, vid->pixels, vid->pitch);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);

```

It works fine if I use 32bpp but this doesn't work for other bpp: the colors are not as expected. This is because the surface has a pixel format with the BPP I want but the texture has a different pixel format. This is problematic because:

* I have some (optional) specific scaling algorithms that require 16bpp surfaces
* I'm not sure whether it will behave the same for all users
* When not scaling with my own algorithms, the performance is better if I directly use the bpp of the display

The reason why the bpp doesn't match is that the SDL\_UpdateTexture accesses the surface data (pixels) without even looking at the pixel format and SDL\_CreateTextureFromSurface creates a texture compatible with the renderer, not caring about the surface format.

So my questions are:

* Is there a simple way to get a surface that is compatible with the renderer? \[1\]
* Is there a way to blit the surface on the texture that does the color conversion? \[2\]

\[1\] I found:

```
SDL_RendererInfo infos;
SDL_GetRendererInfo(renderer, &infos);
vid = SDL_CreateRGBSurfaceWithFormat(0, w, h, SDL_BITSPERPIXEL(infos.texture_formats[0]), infos.texture_formats[0]);

```

but it's a bit heavy, there are multiple supported so I'm not sure which one to choose and I also had some display issues that suggest the result is not really what I want.

\[2\] One idea I had is to have another surface with the format taken from \[1\] and to blit to it first for the conversion, before copying it to the texture, but I'm surprised there's no simpler way to do it.

# Answer
In the end, what I ended up doing is indeed what I suggested in the question:

* Use SDL\_GetRendererInfo to retrieve the BPP of the renderer and pass it to SDL\_CreateRGBSurface to have a surface with compatible BPP
* Create a new intermediary 16bpp surface for the scaling algorithm that need it and blit it to the surface created with the compatible BPP before calling SDL\_UpdateTexture

After a lot of searching through doc and on the web, this seems like the best way to do it.
> 0 votes

---
Tags: sdl, sdl2
---


# Question
Title: How can I add a button that opens a pop-up?
I have developed a game with a libGDX game engine. I want to create a button on the game screen and add a popup to this button. How can I do this?

My current code:

```
public class GameScreen extends BaseScreen implements ShowDictionaryEvent
{
    private Preview preview;
    public GameController gameController;
    public Dial dial;
    private BoardView boardView;
    public DialAnimationContainer dialAnimationContainer;
    private LevelEndView levelEndView;

    private Rocket rocket;
    private BombDialog bombDialog;
    public AlertDialog bombBlastDialog;

    public ExtraWordsButton extraWordsButton;

    private ImageButton shuffleButton;
    private BoardOverlay boardOverlay;
    private Feedback feedback;

    private DictionaryDialog dictionaryDialog;
    private BonusWordsIncompleteDialog bonusWordsIncompleteDialog;
    private BonusWordsCompleteDialog bonusWordsCompleteDialog;
    public SideComboDisplay sideComboDisplay;

    private Smoke smoke;
    private Ufo ufo;
    public boolean offeredBoosterInThisLevel;
    public int nextBoosterType;
    private Label goldPackBubbleLabel;

    private RemoveAdsDialog removeAdsDialog;
    public Image comboLight;;
    public CameraShaker cameraShaker;

    private DelayAction comboLightDelay;
    private SequenceAction comboLightSequence;
    private RunnableAction comboLightRunnableAction;
    public int tempComboReward;

    public GameScreen(KelimeGame wordConnectGame) {
        super(wordConnectGame);
    }

    @Override
    public void show() {

        super.show();

        setTopPanel();
        topPanel.setY(stage.getHeight());

        topPanel.topComboDisplay.setGameScreen(this);

        dialAnimationContainer = new DialAnimationContainer(KelimeGame.resourceManager);
        dialAnimationContainer.setVisible(false);
        stage.addActor(dialAnimationContainer);

        cameraShaker = new CameraShaker();

        gameController = new GameController();
        gameController.setGameScreen(this);

    }
}

```

# Answer
use the Stage class to render ui things

```
private Stage stage;

@override
public void show() {
   ...
   stage = new Stage();

   // create the button
   final ImageButton shuffleButton = new ImageButton(/*maybe need some params*/);
   shuffleButton.addListener(new ClickListener() {
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            // BUTTON ACTION
            return true;
        }
    }

   // put button in stage
   stage.addActor(shuffleButton)
   ...

   // Enable inputs for stage
   // if you need to proccess other inputs, you will need create an InputMultiplexer
   Gdx.input.setInputProcessor(stage);
}

```

in the render method:

```
@Override
public void render(float delta) {
    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    ...
    // draw stage
    stage.act(Gdx.graphics.getDeltaTime());
    stage.draw();
}

```

If you have a complex layout, use the Table class to make it easily
> 0 votes

---
Tags: java, libgdx, mobile, android-studio
---


# Question
Title: When pressing both the key then releasing any1 key then the anination is not played
i give the running animation to the character and created a flip script...when press A then player move and flip to leff and animation is played ....when press D then player move and flip to write and animation is played.. ..when i press both A and B Simultanious then animation is played but when pressing both at the same time and release one key the player moves in that direction but the animation is not playing

Here are the script of the player:

```
[SerializeField] float _xSpeed = 10f;
[SerializeField] float _jumpForce = 10f;

private Rigidbody2D _rb;
private float _movement;
private float _extraJumps;
private bool _isFacingRight;

void Start()
{
    _rb = GetComponent<Rigidbody2D>();
}

void Update()
{
    _movement = Input.GetAxisRaw("Horizontal");
}

void FixedUpdate()
{
    _rb.velocity = new Vector2(_movement * _xSpeed ,_rb.velocity.y);
    {
        if(_isFacingRight == true && _movement > 0.1f)
        {
            Flip();
        }
        else if(_isFacingRight == false && _movement < -0.1f)
        {
            Flip();
        }
    }

    if(Input.GetKeyDown(KeyCode.Space))
    {
        _rb.velocity = new Vector2(_rb.velocity.x,_jumpForce * Time.deltaTime);

    }

}

void Flip()
{

    _isFacingRight = !_isFacingRight;
    transform.Rotate(0,180f,0);

}

```

And here is the script for the animation:

```
[SerializeField] Transform _player;
private Animator _animator;

void Start()
{
    _animator = GetComponent<Animator>();
}

void Update()
{
    transform.position = _player.position;
    if (Input.GetKeyDown(KeyCode.D))
    {
        _animator.SetBool("Running", true);
    }
    else

    if (Input.GetKeyDown(KeyCode.A))
    {
        _animator.SetBool("Running", true);
    }
    else

    {
        _animator.SetBool("Running", false);
    }
}

```

# Answer
The method `Input.GetKeyDown` only returns true during the one Update where the player starts pressing the key, but not on the following updates where they hold it.

I would assume that your intention is to display the running animation while the player is holding down either A or D, and stop it when they are holding neither A nor D? In that case you might want to use the method `Input.GetKey`, which returns true as long as the player keeps holding the button You could write it like that:

```
if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D) )
{
    _animator.SetBool("Running", true);
} else {
    _animator.SetBool("Running", false);
}

```

But there is also a much shorter way to write this:

```
_animator.SetBool("Running", Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D));

```

This works because whenever you have a method which expects a `true` or `false` as a parameter, you can substitute that by a boolean condition.
> 1 votes

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