# Question
Title: detect collision between two circles and sliding them on each other
I'm trying to detect collision between two circles like this:

```
var circle1 = {radius: 20, x: 5, y: 5}; //moving
var circle2 = {radius: 12, x: 10, y: 5}; //not moving

var dx = circle1.x - circle2.x;
var dy = circle1.y - circle2.y;
var distance = Math.sqrt(dx * dx + dy * dy);

if (distance < circle1.radius + circle2.radius) {
    // collision detected

}else{
    circle1.x += 1 * Math.cos(circle1.angle);
    circle1.y += 1 * Math.sin(circle1.angle);
}

```

Now when collision is detected I want to slide the `circle1` from on the `circle2` (`circle1` is moving) like this:

--circle1---------------------------------circle2-------------------------

I could do this by updating the angle of `circle1` and Moving it toward the new angle when collision is detected.

Now My question is that how can I detect whether to update/increase the angle or update/decrease the angle based on which part of `circle2` `circle1` is colliding with ??

I would appreciate any help

# Answer
**TL-DR:**

1. Get vector from `circle2` to `circle1`.
2. Get its heading.
3. Use that heading to determine which Cartesian quadrant the collision occurred in.
4. Based on the direction `circle1` is heading, turn left or right based on which side of `circle2` `circle1` touched to steer away from the other circle.

---

If you have the `x` and `y` of both circles, you could see which 'quadrant' of the non-moving circle the moving circle hits, and go from there.

Use some simple vector math. Get a vector in `(x, y)` from the centre of the non-moving circle to the moving one. It will be handy ot know that the vector going from A to B is $$\vec{C} = \vec{B} - \vec{A}$$ and the heading of a vector (in computing, anyways, I'm not sure about regular linear algebra) is `atan2(c.y, c.x);`. This is a built in Javascript function. This is how `p5.js` does it, and where I got this from.

---

Get vector which points from `circle1` to `circle2`:

```
let vecBetweenX = circle2.x - circle1.x;
let vecBetweenY = circle2.y - circle1.y;

```

Get its heading:

```
let heading = Math.atan2(vecBetweenY, vecBetweenX);
// or in degrees:
heading = heading * 180 / Math.PI;

```

Based on how the `atan2` function returns angles, get it's quadrant by checking where in the unit circle it falls:

```
let quadrant;
if (heading <= 0 && heading > -1 * Math.PI / 2) quadrant = 0;
else if (heading <= -1 * Math.PI / 2 && heading >= -1 * Math.PI) quadrant = 1;
else if (heading >=  0 && heading < Math.PI / 2) quadrant = 3;
else if (heading >= Math.PI / 2 && heading <= Math.PI) quadrant = 2;

// or in degrees:

let quadrant;
if (heading <= 0 && heading > -90) quadrant = 0;
else if (heading <= -90 && heading >= -180) quadrant = 1;
else if (heading >=  0 && heading < 90) quadrant = 3;
else if (heading >= 90 && heading <= 180) quadrant = 2;

```

This tells you which quarter of the non-moving circle the moving circle has hit, with

* `quadrant = 0` being the top right;
* `quadrant = 1` being the top left;
* `quadrant = 2` being the bottom left;
* `quadrant = 3` being the bottom right.

Then, based on what direction the moving circle is headed, change the angle. I'm not sure how you're implementing the angle of the moving circle, so here's some pseudo-code, assuming you're going to increase or decrease `circle1.angle` when you want to turn.

```
if ( /*circles touch*/ ) {
  if (circle.angle == /*moving right*/ ) {
    /* should only ever touch quadrant 1 or 2 if it's moving right */
    angle += (quadrant == 1 /*touch top left*/) ? /*turn left*/ : /*turn right*/;

  } else if (circle.angle == /*moving left*/ ) {
    /* should only ever touch quadrant 0 or 3 if it's moving right */
    angle += (quadrant == 0 /*touch top right*/) ? /*turn right*/ : /*turn left*/;

  } else if (circle.angle == /*moving down*/ ) {
    /* should only ever touch quadrant 0 or 1 if it's moving down */
    angle += (quadrant == 0 /*touch right-hand-side*/) ? /*turn left*/ : /*turn right*/;

  } else if (circle.angle == /*moving up*/ ) {
    /* should only ever touch quadrant 2 or 3 if it's moving up */
    angle += (quadrant == 2 /*touch left-hand-side*/) ? /*turn left*/ : /*turn right*/;
  }
}

```

---

I hope I understood what you're asking. This is the most intuitive solution that comes to my mind without using an actual physics engine/rigid collisions.
> 2 votes

---
Tags: collision-detection, javascript
---


# Question
Title: How are real world car characteristics translated to in-game?
I am just entering the world of game development, starting with the racing genre of games.

Let me clarify that this question is not about car modelling or external detailing; it is about the way a car drives, handles, and the way it feels (how heavy or torque-y it is, or how fast and nimble it is, the way it moves in place when you hit the brakes, etc.) in-game.

I am looking to understand the process game developers take to translate real world car characteristics and physics into in-game cars. I am not talking specifically about simulation games; I'm including even arcade games where driving a muscle car feels very different from driving a tuner, or a sports car, or super and hyper cars.

Questions such as the following arise:

(1) Do developers have get their hands on a car physically in order to be able to map it into an in-game car? When they drive it around, what metrics are they looking to capture so their in-game car can feel as true to the real one?

(2) What if they can't get a physical car, or if the car is a concept with no drivability? What metrics, data and telemetry should the car manufacturer supply in order for the car to be represented in-game?

(3) Within cars of the same kind, such as muscle cars, how do developers ensure that a Ford Mustang, a Dodge Challenger, a Chevrolet Camaro, all feel sufficiently distinct from each other in-game? How do they ensure a Porsche 911 Turbo, a 911 GT3, a 911 GT2 all feel different, just as the real cars do?

# Answer
> 1 votes
> (1) Do developers have get their hands on a car physically in order to be able to map it into an in-game car? When they drive it around, what metrics are they looking to capture so their in-game car can feel as true to the real one?

No. it definitely won't "feel" the same for starters, since your behind is probably in a stationary seat, not in the seat of a moving car. which feels *very* different.

That aside, Developers having to get their hands on the actual cars also seems unlikely. The guys who made Forza didn't crash a whole set of multi million dollar cars to see how it would behave. The vehicles are modeled after their dimensions, their materials, their weight distribution, downforce, you name it. Most of this information is readily available from the automotive manufacturers themselves. Plug that information into a decent physics simulation, and you should have a decent approximation of how the car handles in real life.

Not to mention it would make the simulation inaccurate, since you might taint the model with a personal bias.

> (2) What if they can't get a physical car, or if the car is a concept with no drivability? What metrics, data and telemetry should the car manufacturer supply in order for the car to be represented in-game?

If that concept has known parameters (has been in a wind tunnel, has a weight distribution and power ratio that can be estimated with a decent amount of certainty) you can already make a good "guess" on what the car would handle like, just by plugging those into your sim framework. Obviously, if there is no drivable model there will not be any telemetry, so you will have some degree of inaccuracy, but you could plug existing, ready-made stuff like existing suspension models etc. in to fill up the gaps.

> (3) Within cars of the same kind, such as muscle cars, how do developers ensure that a Ford Mustang, a Dodge Challenger, a Chevrolet Camaro, all feel sufficiently distinct from each other in-game? How do they ensure a Porsche 911 Turbo, a 911 GT3, a 911 GT2 all feel different, just as the real cars do?

I think i already answered this question twice over. These models 'feel' different bevause they have different bodies, different downforce, different engines, drive trains, weight distributions, suspension models. If your model is complete enough, no two cars (no matter how closely related) will 'feel' the same.

---
Tags: physics, models, car, racing, modelling-techniques
---


# Question
Title: Physics engine and rigidbody sleep optimization
I am trying to add sleep optimization to my little physics engine(just for learning). I use SAT for collision detection that returns penetration normal and depth without contact points. Objects are put to sleep after 180 frames if their velocity is less then eps. When objects are stacked and in sleeping state when i add velocity to the bottom object, objects on top remain in sleep mode and just float in the air. Can sleeping be implemented without contact points at all? This is done in 3d.

This is collision loop:

```
void Physics::updateReal(float dt){
    auto& rbs = EntitySystem::instance()->_rigidbodies;

    for (auto rb : rbs) {
        if(rb->isAwake())
            rb->integrate(dt);
    }

    for (int i = 0; i < 1; ++i) { //can be called multiple times per frame to improve stability
        blackList.clear();
        //std::cout << "########" << std::endl;
        for (auto rb : rbs) {
            if (!rb->isAwake() || rb->_inverseMass == 0.0f) continue;       //skip static and sleeping rbs

            //colliders c1 of current rigidbody
            std::vector<Collider*> RBColliders; rb->thisEntity()->getColliders(RBColliders);

            for (auto c1 : RBColliders) {
                glm::vec3 o, d; c1->getAABB(o, d); std::vector<BVHTreeContainee*> colliders2;
                SpatialPartitioning::instance()->queryAABB(colliders2, o, d, BVH_COLLIDERS);

                for (BVHTreeContainee* c2bvh : colliders2) {
                    auto c2 = (Collider*)c2bvh;
                    if (!c2->isRigidbody()) continue;
                    if (c1 == c2) continue;
                    if (c1->getEntity() == c2->getEntity()) continue;

                    //std::cout << c1->getEntity()->gameObject()->name << " AND " << c2->getEntity()->gameObject()->name << std::endl;
                    collide(c1, c2);
                }
                //blackList.push_back(c1);  //c1 is all tested
            }
        }
    }
}

```

This is integration of rigidbody:

```
void Rigidbody::integrate(float dt){
    if (_inverseMass == 0.0f) return;
    auto trans = thisEntity()->transform();

    //sleep
    if (glm::length(_velocity) < 3.5f)  ++_sleepStage;
    else                                _sleepStage = 0;

    if (_sleepStage > 180) { _awake = false; return; }

    std::cout << "# " << glm::length(_velocity) << " " << _sleepStage << std::endl;

    //euler integration of position
    _velocity.y -= _gravity * dt;           //rhs = ubrzanje * dt, lhs = brzina
    trans->addPosition(_velocity * dt);     //rhs = brzina * dt, lhs = pozicija
}

```

This function is called to resolve collision:

```
inline void Physics::collisionResolution(Collider* c1, Collider* c2, glm::vec3 mtvAxis, float mtvDist, bool flip){
    auto A = c1->getRigidbody();
    auto B = c2->getRigidbody();

    //COLLISION RESOLUTION
    if (flip) mtvAxis *= -1.f;
    mtvDist /= 2.f;

    if(A->_inverseMass > 0.0f && A->isAwake())
        c1->getEntity()->transform()->addPosition(mtvAxis * mtvDist);
    if(B->_inverseMass > 0.0f && B->isAwake())
        c2->getEntity()->transform()->addPosition(-mtvAxis * mtvDist);

    //LINEAR IMPULSE
    glm::vec3 rv = A->_velocity - B->_velocity;
    float velAlongNormal = glm::dot(rv, mtvAxis);
    if (velAlongNormal > 0.0f) return;

    float e = 0.2f;
    float j = -(1.0f + e) * velAlongNormal;
    j /= A->_inverseMass + B->_inverseMass;

    glm::vec3 impulse = mtvAxis * j;

    glm::vec3 impulseA = impulse * A->_inverseMass;
    glm::vec3 impulseB = impulse * B->_inverseMass;

    A->setAwake();  //sets _awake to true
    A->_velocity += impulseA;

    B->setAwake();
    B->_velocity -= impulseB;

    //FRICTION
    glm::vec3 t = rv - (mtvAxis * velAlongNormal);

    if (glm::length(t) == 0.0f) return;
    t = glm::normalize(t);

    float jt = -glm::dot(rv, t);
    jt /= A->_inverseMass + B->_inverseMass;
    if (jt == 0.0f) return;

    float friction = glm::sqrt(0.03f);
    if (jt > j * friction)
        jt = j * friction;
    else if (jt < -j * friction)
        jt = -j * friction;

    glm::vec3 tangentImpuse = t * jt;
    A->_velocity += tangentImpuse * A->_inverseMass;
    B->_velocity -= tangentImpuse * B->_inverseMass;

    //ANGULAR IMPULSE
    //THE DARKEST BLACK MAGIC
}

```

# Answer
~~What if you detect "stillness" not via velocity, but via forces instead?~~

~~When laying on top of the stack, the block's aggregate force is zero, as the gravity force and the supporting force from block below will cancel each other out perfectly.~~

So yeah, you don't want collision tests when sleeping, indeed.

Maybe the system can keep track of which rigid bodies it was touching at the moment it went to sleep?

If any of those start to move, that body would need waking up again.

It would get a bit messy to express in code though, as it is a variable length list.
> 1 votes

---
Tags: physics-engine, rigidbody
---


# Question
Title: How to add global variables to a global list and then call the elements in a second scene in Unity, c#
I have the following problem with my app. I have a scene where the player is adding products with prices, by using strings. They are added to a Global Control file, which saves the data. Then, in this GlobalControl file, I want to add each of this strings in a list, so this way in the next scene I can call them and add them to a ScrollView, similar to order preview. Unfortunately, I can't manage to make it the right way and to add more than one item to the Order Preview.

My code is the following: Scene one:

```
public void addToOrder()
{

    if (m_currentSelectedModel <= 33)

    {
       GlobalControl.orderContent =
       menuItemNamesString[m_currentSelectedModel];
       GlobalControl.priceContent =
       menuItemPriceString[m_currentSelectedModel];
    }

}

```

My GlobalControl is the following:

```
public class GlobalControl : MonoBehaviour
{
    public static GlobalControl control;

    //the global variables

    static public string orderContent;
    static public string priceContent;

    //global lists
    static public List<string> orderItemsList = new List <string>();
    static public List<string> orderPricesList = new List <string>();

    void Awake()
    {
        if (control == null)
        {
            DontDestroyOnLoad(gameObject);
            control = this;
        }

        else if (control != null)

        {
            Destroy(gameObject);
        }

    }

    private void Start()
    {

        //adding the current selection to the respective list
        if (orderContent != null)
        {
            orderItemsList.Add(orderContent);
        }

        if (priceContent != null)
        {
            orderPricesList.Add(priceContent);
        }

    }

```

And last my OrderPreviewManager, which is in scene 2, is:

```
void Start ()
{
    //my current solution, which does not retrieve a variable from a list

    curOrderContent = GlobalControl.orderContent;
    curPricetContent = GlobalControl.priceContent;

    AddSelectedItemToOrder();
    AddSelectedItemPriceToOrder();
}

//the two methods for adding the string to text components into a scroll
  view

void AddSelectedItemToOrder()
{
    GameObject gameObject = new GameObject("Child");
    gameObject.transform.SetParent(orderContentView.transform);

    gameObject.AddComponent<Text>().text = curOrderContent;
    gameObject.GetComponent<Text>().font =
    Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font;
    gameObject.GetComponent<Text>().color = Color.black;
    gameObject.GetComponent<Text>().fontSize = 20;
}

  //similar to the previous method but for the prices

void AddSelectedItemPriceToOrder()
{
    GameObject gameObject = new GameObject("Child");
    gameObject.transform.SetParent(pricetContentView.transform);

    gameObject.AddComponent<Text>().text = curPricetContent;
    gameObject.GetComponent<Text>().font =
    Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font;
    gameObject.GetComponent<Text>().color = Color.black;
    gameObject.GetComponent<Text>().fontSize = 20;
}

```

My question is: why does this only insert one item in scene 2?

# Answer
> 2 votes
You can get rid of quite a bit of extra stuff, and just use a for loop to iterate through the lists.

### Scene one

There's no reason to use `orderContent` or `priceContent`. Just add to the list directly.

```
public void addToOrder()
{
    if (m_currentSelectedModel <= 33)
    {
       GlobalControl.orderItemsList.Add( menuItemNamesString[m_currentSelectedModel]);
       GlobalControl.orderPricesList.Add( menuItemPriceString[m_currentSelectedModel]);
    }
}

```

### GlobalControl

`control`, `orderContent`, and `priceContent` are redundant. You can get rid of them. Also, get rid of `Awake` and `Start`. Making everything static in GlobalControl makes instantiating it redundant. This also means it does not need to be a `MonoBehavior`.

As recommended by *Olivier Jacot-Descombes*, it is good form to make these lists `readonly`, so that there is a guarantee that any reference to one of these objects is always up-to-date.

```
public class GlobalControl
{
    public static readonly List<string> orderItemsList = new List <string>();
    public static readonly List<string> orderPricesList = new List <string>();
}

```

### OrderPreviewManager, which is in scene 2

Add a parameter to the `AddxToOrder` methods. Then, use a for loop to iterate through the lists in `Start`:

```
void Start ()
{
    for (int i = 0 ; i < GlobalControl.orderItemsList.Count ; i++) {
        string item = GlobalControl.orderItemsList[i];
        string price = GlobalControl.orderPricesList[i];

        AddSelectedItemToOrder(item);
        AddSelectedItemPriceToOrder(price);
    }
}

//the two methods for adding the string to text components into a scroll
 view

void AddSelectedItemToOrder(string item)
{
    GameObject gameObject = new GameObject("Child");
    gameObject.transform.SetParent(orderContentView.transform);

    gameObject.AddComponent<Text>().text = item;
    gameObject.GetComponent<Text>().font =
    Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font;
    gameObject.GetComponent<Text>().color = Color.black;
    gameObject.GetComponent<Text>().fontSize = 20;
}

//similar to the previous method but for the prices

void AddSelectedItemPriceToOrder(string price)
{
    GameObject gameObject = new GameObject("Child");
    gameObject.transform.SetParent(pricetContentView.transform);

    gameObject.AddComponent<Text>().text = price;
    gameObject.GetComponent<Text>().font =
    Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font;
    gameObject.GetComponent<Text>().color = Color.black;
    gameObject.GetComponent<Text>().fontSize = 20;
}

```

# Answer
> 0 votes
In unity, if you want to keep something across multiple scenes, use this:

```
void Awake(){
DontDestroyOnLoad(this.gameObject);
}

```

This will make the object its attached to, in this case your globals, remain in any scene called, until either you destroy the object manually or you close the application.

Once this is done, you will need to set it a tag. Then grab it by its tag by using:

```
GlobalControl globals = GameObject.findObjectWithTag("global").getComponent<GlobalControl>();

```

**Note**: I am assuming your tag is `global`, you will use this in the awake of the OTHER script. any variables you want access to must be public. Then, you can use:

```
global.orderItemsList.Add("Your new string");

```

or any other such public method.

Also note that, loading the scene with this object more than once will cause things to work in unexpected ways.

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


# Question
Title: When is it possible to discontinue the Unity 3D paid license?
Lets assume we have created and published in some stores (Steam, Epic, etc) a game made with Unity paid license.

Case 1. The game was soo dull and tedious that we sold less than a thousand copies during a sufficient period (like a year). Our revenue is not even close to the $100K revenue threshold (when at least Unity Plus is required).

Case 2. The game was quite well and reached $100K+ revenue in the past but now we allmost have no sales.

After what term may we downgrade to Personal?

Should we remove our game from stores, leave it as it is or rebuild it using the free engine version and republish?

I'm not trying to fool. The questions are more about situation when you want to quit gamedev hobby or it is too small to pay even $25 monthly for years.

# Answer
First of all you don't need to unpublish a game, i.e. If you have used a paid Unity license, say "Plus", to build and publish a game, and didn't earn at least 100K+ in the past year, you don't need to unpublish it in order to downgrade to "Personal".

However, if you downgrade to "Personal" and make any modifications to the game that was published using "Plus", the next build will be with the "Personal" license, and the corresponding update published will be a "Personal" version, i.e. with the Unity Splash Screen (no customization), as well as all other "Plus" features removed.

Please refer to Terms of Service:

**Article "4.2 Your Content"** (you own the content you create, hence you cannot be forced to unpublish something you own)

and

**Article "5.3 Subscription Terms"** (subscriptions can be cancelled after commitment period). Therefore, if you cancel, you still own the content.

and

**Article "6. Compliance"** (Unity or its representatives can inspect your systems at your facilities or remotely, so Unity can verify if your revenue/funding corresponds to your active license. Therefore, your active/current license must correspond to your revenue/funding in the last 12 months, in order to comply with the TOS). For more detailed description of the 12 months period see also **Tier Eligibility** in the Unity Software Additional Terms: "Tier Eligibility is measured for the most recent twelve (12) month period, etc."

Also please refer to the FAQ:

"**Do I own the content I create with my subscription?** =\> Yes, you fully own the content you create with a Unity subscription, also if you stop subscribing to Unity."

and

"**Will my subscription automatically renew?** =\> .... ... If you do not wish to continue on a flex plan, you can choose expire your subscription after its commitment period. If you choose to expire your plan, your version of Unity will switch to Personal.".

You can always contact Unity Sales to ask them any question directly, they are very helpful: https://unity3d.com/contact/get-in-touch
> 1 votes

# Answer
I'm not a lawyer, I know nothing about what I'm talking about, standard disclaimer. But there's a pretty simple answer to your question:

Assuming that you do not need the Unity 3D paid license for anything else, and that this is your own project:

> **if you are an individual using the Unity Software, but not providing services to a third party**, your Total Finances are the amount generated in connection with your use of the Unity Software. In this case, **your Total Finances would not include amounts you generate from other work** (for example, if your day job is as a zookeeper). – Terms of Service

This means that you can discontinue the Unity 3D paid license if there's no chance of it giving you that much revenue, **e.g. if you make the game *gratis* (free)**. If you're not making any money, you don't need to give Unity a share, regardless of how many people have the game! If you don't think you're going to get many more sales on the games, I don't see why you *shouldn't* make them free (except possibly if it'd make people wait for the game to be free and not buy games from you any more) but I also don't see the point, since if you're not going over the limit anyway you aren't making enough money anyway... but it's the safest route.

Of course, you *could* go the sadder route and stop selling the game entirely. But isn't the whole point of the 'net that you *don't* have to do that?
> 0 votes

---
Tags: unity, licensing
---


# Question
Title: Can a prefab of a complete Unity scene be created?
Can we create a prefab out of a complete unity scene, so that we can instantiate the complete scene like we instantiate gameobjects in unity.

# Answer
> 6 votes
1. Create an empty gameobject at the root level of your scene
2. Move all other objects in the scene to be children of that object
3. Drag that object into your assets folder to make it a prefab

Now you have a prefab containing everything in the scene.

Side note: This method may require nested prefabs if you already have prefabs in the scene. This is only supported in 2018.3 or higher. Here's the documentation on the matter. Also, quoted from this link:

> The new Prefab workflows, which are available in Unity 2018.3, allow you to split up Prefabs on a granular level. This gives you greater flexibility, increases your productivity and enables you to work confidently without worrying about making time-consuming errors.

---
Tags: unity
---


# Question
Title: Wave spawner, wave number and word length
I'm trying to create a falling word typing game like z-type.

I have used the code provided here : https://github.com/Brackeys/Falling-Words-Typing-Game

In the WordSpawner.cs file, I'm trying to set the limit of the length of words that are displayed. for eg. in the first 15 seconds I want the length of words to be 3/4 and between 15-30 seconds 5/6 and after that any random length from 3 - 9. Is there any way to achieve this?

Also, I want to show the wave number on the screen like in the z-type game. How can I achieve this functionality.

This is the script from the tutorial for the word spawner:

```
public GameObject wordPrefab;
public Transform wordCanvas;

public WordDisplay SpawnWord () {

Vector3 randomPosition = new Vector3(Random.Range(-2.5f, 2.5f), 7f);
GameObject wordObj = Instantiate(wordPrefab, randomPosition, Quaternion.identity, wordCanvas);
WordDisplay wordDisplay = wordObj.GetComponent<WordDisplay>();
return wordDisplay;

}

```

The list of words is an array that contains about 50 words. This list is in a separate file, WordGenerator.

```
private static string[] wordList = {   "walking", "rabbit", "bob", "save", "pablo",...... };

public static string GetRandomWord ()
{
int randomIndex = Random.Range(0, wordList.Length);
string randomWord = wordList[randomIndex];

return randomWord;
}

```

Then there is the WordManagerscript that tracks the active word,word spawner etc. Here is the code for the word to be added:

```
public void AddWord ()
{
Word word = new Word(WordGenerator.GetRandomWord(),
wordSpawner.SpawnWord());
wordsList.Add(word);
}

```

**Edit**

I have been trying to get the word spawner to work but to no avail. I had followed some word spawner tutorials but doesn't seem to work as the SpawnWord() method is used by another class i.e the word manager class....

```
public WordSpawner wordSpawner;

public  bool hasActiveWord;
public  Word activeWord;

public void AddWord()
{
    WordDisplay wordDisplay = wordSpawner.SpawnWord();

    Word word = new Word("boat", wordDisplay);//WordGenerator.GetRandomWord()

    Debug.Log(word.word);

    words.Add(word);

```

I'm not able to get this to work.....

# Answer
> In the WordSpawner.cs file, I'm trying to set the limit of the length of words that are displayed. for eg. in the first 15 seconds I want the length of words to be 3/4 and between 15-30 seconds 5/6 and after that any random length from 3 - 9. Is there any way to achieve this?

You could try checking the length of the word, and if not compatible, find another word. A string's length (the number of characters in said string), which happens to also be a word can be retrieved with `String.length`.

To get the time since something has happened, simply save the value of `Time.time` when said 'something' (ie. when the game starts) happens. You can then find the elapsed time by simply subtracting that stored value from the current `Time.time`. It is usually done in the `Update()` function.

> Also, I want to show the wave number on the screen like in the z-type game. How can I achieve this functionality.

Just add a variable to store the number and you can display it onto a `Text` label by setting the value of `Text.text`.
> 0 votes

---
Tags: unity
---


# Question
Title: Changing button position makes it move drastically
I have a button prefab that I'm instantiating like so:

```
GameObject button = Instantiate(Resources.Load("UI/Canvas/Button"), ReferenceToCanvasPanelRectTransform.transform) as GameObject;

```

This part works fine and the button is centered in the panel.

I would like to move the button a little bit though and lets say that the position of the button right now is (0, 0, 0).

If I get the button's RectTransform and attempt to move it like so:

```
RectTransform btn = button.GetComponent<RectTransform>();

btn.position = new Vector2(-20, 20);

```

it makes the button's position move to (-1051.05, 1149.5, -5679).

Why does it move so drastically and why does the Z position even change?

# Answer
`btn.position` sets the absolute position in the world space coordinates, not canvas space. To move it on canvas, relative to anchor, use `btn.anchoredPosition`.

Also, `CanvasScaler` has an effect on how different world coordinates are from canvas coordinates.

Your `CanvasPanel` might be set not as `ScreenOverlay` but as rendered in world space and might even be not centered in the world (`CanvasPanel.transform.position != Vector3.zero`). That's why when you change the absolute position of `btn` it shows very different numbers.

If you want to change `transform.position` relative to current position, use `transform.Translate(x, y, z)` method. It moves the object by x, y, z coordinates from current position.

But for UI elements, stick with `rectTransform.anchoredPosition`. It makes your life so much easier...
> 3 votes

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


# Question
Title: How to stop camera rotation after reaching a specific angle?
I have a camera in my scene that I want to rotate around the player. The rotation is done when the camera rotation state is at CameraRotation.Left or CameraRotation.Right and CameraRotation.None indicates that the camera should stop rotating and just follow the player.

I want the camera to rotate around the player and stop after it reaches a specific angle (180 degrees) in the y axis in the CameraRotation.Left or CameraRotation.Right from the position the camera was at the start of the rotation. It would also be helpful if some direction is given on how to edit the SmoothFollow() method so that it follows the player with the camera still rotated.

The problem is I'm not familiar with rotations and not sure whether to use Euler angles or quaternions so any tips would help.

```
private void LateUpdate()
{
    if (GameManager._RotateCamera == CameraRotation.None)
    {
        SmoothFollow();
    }
    else if (GameManager._RotateCamera == CameraRotation.Left)
    {
        transform.RotateAround(player.transform.position, Vector3.up, rotationSpeed * Time.deltaTime);
    }
    else if (GameManager._RotateCamera == CameraRotation.Right)
    {
        transform.RotateAround(player.transform.position, Vector3.down, rotationSpeed * Time.deltaTime);
    }
}

// Make the Camera follow the player smoothly
private void SmoothFollow()
{
    Vector3 desiredPoistion = player.position + offset;
    Vector3 smoothedPosition = Vector3.SmoothDamp(transform.position, desiredPoistion, ref velocity, smoothSpeed);

    transform.position = smoothedPosition;

    transform.LookAt(player.transform);
}

```

# Answer
You need to add a variable to keep track of how much rotation has already occurred.

```
private float cumulativeRotation = 0f;

```

When you start rotating, make sure that it is set it to zero if it isn't already:

```
cumulativeRotation = 0f;

```

Then, in your update, compare how much rotation is left (`180f - cumulativeRotation`) vs. how much rotation you can do based on the rotation speed (`rotationSpeed * Time.deltaTime`) and do the lesser one. Whatever you choose, add that value to the cumulativeRotation.

Then, if `cumulativeRotation >= 180f` ( I like to avoid using `==` between floats), you can end rotation. I assume here that we can do that by just using `GameManager._RotateCamera = CameraRotation.None);` but you may have a better way. Optionally, reset the `cumulativeRotation` tracker to `0f` once rotation is complete.

```
private void LateUpdate()
{
    if (GameManager._RotateCamera == CameraRotation.None)
    {
        SmoothFollow();
    }
    else {
        float rotationThisFrame = Mathf.Min(
                180f - cumulativeRotation,
                rotationSpeed * Time.deltaTime);
        if (GameManager._RotateCamera == CameraRotation.Left)
        {
            transform.RotateAround(player.transform.position, Vector3.up,
                    rotationThisFrame );
        }
        else if (GameManager._RotateCamera == CameraRotation.Right)
        {
            transform.RotateAround(player.transform.position, Vector3.down,
                    rotationThisFrame );
        }

        cumulativeRotation += rotationThisFrame;

        if (cumulativeRotation >= 180f) {
            // We are done rotating. Stop rotating on further frames.
            GameManager._RotateCamera = CameraRotation.None;

            // Reset cumulativeRotation tracker for next time.
            cumulativeRotation = 0f;
        }
    }
}

```
> 0 votes

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


# Question
Title: Is it possible to use a string somehow converted to match name of a bool?
I have a Json file holding data for my LineData type i created.

```
[Serializable]
public class LineData
{
public string lineID;
public string lineDialog;
public float lineDuration;
public string condition;
}

```

Note the last one, 'condition', that is what I hope to use to hold a name of a specific bool in my code, so that the line can only be spoken when that bool is true.

Is this a decent way to achieve this? Or is it even possible? I've read about making 'custom markup' on my Json things like (!!) and (-\>) built in the text to mean stuff in my code, but I don't know where to start with it and cannot find any tutorials (I've only seen it on some Youtube GDC lecture style videos from professional game developers working for companies)

But failing the custom markup thing, if I can somehow use the string of the name of the bool, and use that to check the state of it's corresponding bool in the code, that would be enough for me so far.

Any ideas or help is fantastic and very welcome. Many thanks!!!

(PS. The json looks like this (Im sure you don't need it, but just in case)):

```
{ "lineDatas":
[
{
    "lineID": "BEDROOM_DAVE_0001",
    "lineDialog": "Yaawwn, up i get for another fun packed day.",
    "lineDuration": 3,
    "condition": ""
},
{
    "lineID": "BEDROOM_DAVE_0002",
    "lineDialog": "Well I think I need a cigarette before I get to work!",
    "lineDuration": 3,
    "condition1": "notSmokedCig"
}
]
}

```

# Answer
Storing your boolean condition variables in a dictionary keyed by strings as Patrick Hughes recommends will work just fine, but it can lead to your code being "stringly typed"

If we don't know the full set of condition variables until runtime (eg. if we're running mods/scripts that added more content beyond what's in the compiled game), then this might be the best we can do.

But for stuff that's known at compile time, using strings means relying unnecessarily on every bit of code that reads or writes a particular condition flag to spell & capitalize it identically (or responsibly use the right constant instead of bodging in a literal). A single typo in a string literal somewhere can introduce insidious bugs that the compiler won't be able to detect for you. Also, strings are needlessly heavy to store/compare/hash if a simpler type will do.

We can improve on this method by using an enum to define our variable "slots":

```
public enum Condition : int {
    HasNotSmokedCigarette,
    HasPetParakeet,
    KnowsTheMacarena,
    SpeaksEsperanto,
    /* ... add more conditions here */
    ConditionsCount
}

```

By making the enum backed by an integer type like this, we can cheat a little and use the enum directly as an index into an array of values, and skip the hashing / redundancy of a Dictionary entirely. Putting a "count" entry at the end lets us easily keep the array the right size:

```
bool[] conditionValues = new bool[(int)Condition.ConditionsCount];

```

Now we can get & set bools in one of these slots using:

```
void SetCondition(Condition condition, bool value) {
    conditionValues[(int)condition] = value;
}

bool GetCondition(Condition condition) {
    return conditionValues[(int)condition];
}

```

We can call these using the enum values like so, keeping compile-time checking & error reporting throughout:

```
SetCondition(Condition.HasPetParakeet, true);

```

And finally, the part we've all been waiting for: we can still look them up from strings when necessary:

```
bool GetCondition(string conditionName) {
    if(string.isNullOrEmpty(conditionName))
        return true;

    Condition condition;
    if(System.Enum.TryParse(conditionName, out condition))
        return GetCondition(condition);

    Debug.LogErrorFormat("Tried to check non-existent condition named {0}", conditionName);
}

```
> 4 votes

# Answer
It's not uncommon to store the variables used by the scripting system in a `Dictionary` with a `string` key. In my opinion, the "stringly typed" argument does not apply in this case, because you already got stringly typing in your JSON data and you won't be able to verify those at compile-time. If you want to confirm that there are no mistyped variable names in your script files, add a way to declare variables to them and do a validation at load-time (Btw: I made the experience that building a sophisticated validation system into your JSON loaders is usually well worth the time investment).

But if you really want the variables in your script files to map to "real" variables on the C# side, then you can use reflection to get the value of a member-variable by its name stored in a string at runtime.

For example, assume you have an object `GameState state` with a field `public bool notSmokedCig` and you have a `string condition` with the value of `"notSmokedCig"` at runtime, you can do this:

```
bool conditionIsTrue = (bool) typeof(GameState).GetField(condition).GetValue(state);

```

I am looking forward to playing your game.
> 2 votes

---
Tags: unity, c#, dialogue-tree
---


# Question
Title: Vulkan rendering of Minecraft-like world in C++
I decided on using 16x16x16 (4096 total) chunks of blocks.

Problem is with textures. First idea was about **texture atlas** but it would require a lot of calculation and possible problems in dividing UV (1) by atlas size (power of 2). Then I was thinking about using **array of textures** or **`sampler2darray`**.

I do not have fixed amount of textures and I reserved `uint16` (`65,535`) for block-only textures (those textures are not used anywhere else, even items have their own item-only textures). All those textures are loaded before the world (based on loaded "mods").

I got so far that **array of textures** should be best solution because they support different resolutions (8x8, 16x16, 32x32, 64x64...) without duplicated pixels (which **`sampler2darray`** would require when even 1 texture has higher resolution because all textures would be re-scaled to fit it).

Problems I found with **array of textures** are:

* the length must also be defined in shader (which I would need to recompile at runtime)
* limited length (`256` to `2048` based on vulkan.gpuinfo.org but even Minecraft has `229` block types, some with multiple textures)

Advantages are:

Which type of storage for textures is best in this case?

Or should I separate faces by textures, create VkPipeline for each texture and render them one by one?

EDIT: Each block has at least 1 texture (most time unique) but can be higher then 6 (different texture for each face) when 1 block is made of multiple cubes = non-solid.

# Answer
2D Image Limit is 8192. That means much more textures then using any type of array.

Using this for only 1 atlas means:

* `16x` ~ 262,144
* `32x` ~ 65,536
* `64x` ~ 16,384
* `128x` ~ 4,096
* `256x` ~ 1,024
* `1024x` ~ 256

`16x` means 16x16 pixels per texture, `32x` means 32x32 and so on.

Exceeding this limit would require creating more VkImage -\> VkPipeline (and when rendering chunks, split it into more meshes).

Because of this, I may settle on keeping only 1 atlas. `32x` textures means average of 2 textures per block (`32,767`, maximum of `int16_t` used for block IDs), `16x` ~ 8 textures per block, `64x` ~ 1 texture per 2 blocks.

This will also limit servers to use lower resolution or less block, further decreasing impact on performance.
> 0 votes

---
Tags: c++, textures, voxels, texture-atlas, vulkan
---


# Question
Title: AndroidManifest file was deleted by accident
I deleted the AndroidManifest file of my project which was located in Assets\Plugins\Android , so I tried creating new project and copying the Assets and everything but it seems that something is missing ,it's perfectly working in the editor , but as apk there are few things aren't working, I can't figure out why, and there isn't even a Plugins folder in my new project !

# Answer
> 1 votes
If you happen to have some version of an apk that does work, it is possible to recover the AndroidManifest.xml from it.

Using apktool you can decompile the apk and get at some form of the original file. Note that it won’t have any comments that may have been in the original, and if you had any entries that explicitly remove automatically added elements using `<... tools:node="remove">` they would be no longer be present, but it should otherwise be identical.

The specifics of how to use apktool are documented on its website, but the general gist is

```
apktool d myapp.apk

```

Which will create a folder named myapp in the same place with all the files in it

---
Tags: unity, android
---


# Question
Title: Orthographic Viewport whose bounds are equal to screen Window bounds?
Ive been rattling my head trying to figure out how to do this. I am not working on a 3D application so I did not expect to need to understand transforms, projections, or viewports.

Essentially what I want to do is to setup my viewport, view, & projection so that whenever I call `GraphicsDevice.DrawPrimatives()` the values of the VertexPosition's position can be pixel values. For example, If I wanted to draw a rectangle that bordered the screen I would do:

```
VertexPositionColor[] vertices = new VertexPositionColor[5];
vertices[0] = new VertexPositionColor(new Vector3(0, 1080, 0), Color.Red);
vertices[1] = new VertexPositionColor(new Vector3(1920, 1080, 0), Color.Red);
vertices[2] = new VertexPositionColor(new Vector3(1920, 0, 0), Color.Red);
vertices[3] = new VertexPositionColor(new Vector3(0, 1080, 0), Color.Red);
vertices[4] = new VertexPositionColor(new Vector3(0, 1080, 0), Color.Red);

```

As of right now, if i do:

```
VertexPositionColor[] vertices = new VertexPositionColor[5];
vertices[0] = new VertexPositionColor(new Vector3(-1, 1, 0), Color.Red);
vertices[1] = new VertexPositionColor(new Vector3(1, 1, 0), Color.Red);
vertices[2] = new VertexPositionColor(new Vector3(1, -1, 0), Color.Red);
vertices[3] = new VertexPositionColor(new Vector3(-1, -1, 0), Color.Red);
vertices[4] = new VertexPositionColor(new Vector3(-1, 1, 0), Color.Red);

```

I get:

How do I set it up so that my VertexPosition coordinates are 1:1 with pixels?

# Answer
To do this, you need to set the correct projection value in your BasicEffect. Key to this projection is to align the matrix with the coordinate system you want to use (so 0,0 is the top left corner). Set it up like this:

```
        basicEffect = new BasicEffect(GraphicsDevice);
        basicEffect.VertexColorEnabled = true;
        basicEffect.Projection = Matrix.CreateOrthographicOffCenter
        (0, Screen.Width,     // left, right
        Screen.Height, 0,    // bottom, top
        0, 1);

```

In your case for a 1920x1080 display:

```
        basicEffect.Projection = Matrix.CreateOrthographicOffCenter
        (0, 1920,     // left, right
        1080, 0,    // bottom, top
        0, 1);

```

Now you can set your vertice coordinates to 0,0 (top left) and 1920,1080 (bottom right). This lines exactly up with the regular spriteBatch settings so you can mix those vertex graphics with sprites, using the same coordinate system.

Keep in mind that the projection "screen" values need to be the same with the backbuffer size (this is the reason I set the projection with values that correspond to the actual window size instead of *magic numbers*).
> 1 votes

---
Tags: c#, monogame
---


# Question
Title: Spine runtime for libgdx clipped rendering issue
I've started to play with the Spine for libgdx runtime in Java.

But I can't seem to render without some sort triangular clipping.

The code is based on the Spine examples:

```
public class AnimalTest extends ApplicationAdapter {

   OrthographicCamera camera;
   PolygonSpriteBatch batch;
   SkeletonRenderer renderer;

   TextureAtlas atlas;
   Skeleton skeleton;
   AnimationState state;

   public void create () {

      camera = new OrthographicCamera();

      batch = new PolygonSpriteBatch();

      renderer = new SkeletonRenderer();

      atlas = new TextureAtlas(Gdx.files.internal("animals/Animals.atlas"));
      SkeletonJson json = new SkeletonJson(atlas); // This loads skeleton JSON data, which is stateless.

      SkeletonData skeletonData = json.readSkeletonData(Gdx.files.internal("animals/Animals.json"));

      skeleton = new Skeleton(skeletonData); // Skeleton holds skeleton state (bone positions, slot attachments, etc).
      skeleton.setSkin("5");

      skeleton.setX(1000);
      skeleton.setY(-400);

      AnimationStateData stateData = new AnimationStateData(skeletonData); // Defines mixing (crossfading) between animations.

      state = new AnimationState(stateData); // Holds the animation state for a skeleton (current animation, time, etc).

      state.setAnimation(0, "idle", true);
   }

   public void render () {

      state.update(Gdx.graphics.getDeltaTime()); // Update the animation time.

      Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

      state.apply(skeleton); // Poses skeleton using current animations. This sets the bones' local SRT.
      skeleton.updateWorldTransform(); // Uses the bones' local SRT to compute their world SRT.

      // Configure the camera, SpriteBatch, and SkeletonRendererDebug.
      camera.update();
      batch.setProjectionMatrix(camera.combined);

      batch.begin();
      renderer.draw(batch, skeleton); // Draw the skeleton images.
      batch.end();

   }

   public void resize (int width, int height) {
      camera.setToOrtho(false);
   }

   public void dispose () {
      atlas.dispose();
   }

}

```

# Answer
Found the culprit to my own problem.

Apparently the default skin in the exported json from spine had an attachment with clipping. The renderer on iOS with Cocos2D ignored this for some reason so this never was an issue before.

```
"Clipper": {
            "Clipper": {
                "type": "clipping",
                "end": "Clipper",
                "vertexCount": 4,
                "vertices": [ -712, 1424, -712, 655.21, 1363.21, 1424, 1363.21, 655.21]
            }
        }

```
> 1 votes

---
Tags: java, libgdx, spine
---


title: Unity pixel art distorted sprites

text:
# Question
Title: Unity pixel art distorted sprites
I have a problem rendering my pixel art sprites properly in Unity. So far I have one character in a sprite-sheet I made, with frames of size 64x64. The actual sprite is roughly 32x32 but I left room for movement in animations. I import the sheet following pixel perfection procedures I found on the internet using these settings:

As for the orthographic camera I set its size using this formula:

orthoCameraSize = screenHeight / (2 * 32)

If I zoom on the sprite in scene it looks fine but when in game it gets rendered quite poorly (in game / in scene pics below):

What could be the source of the problem? I applied every good practice advice I could find on the web... Thanks for your help!!!!

# Answer
> 1 votes
You should change your formula for the ortho size to Camera Size = x / ((( x / y ) * 2 ) * s )

Where: x = Screen Width (px) y = Screen Height (px) s = Desired Height of Photoshop Square (px)

# Answer
> 1 votes
Should be the same problem / answer as this:

How do I move the camera in full pixel intervals?

Basically to fix this issue:

1. Your sprites-pixel in Unity-Units should be reasonable. ( For example: If your sprite has a width of 10, it should be as wide as "10 unity-units" for example. Or 100. or 1. or 0.1f. But not 1.5234f)
2. Your sprites should only move in full-pixel-steps if (1.) is not possible.
3. Your Camera should also only move in a full pixel- steps if (1.) is not possible
4. Your Resolution should be in full numbers (x = 50.5f is wrong)
5. Your Resolution should have even numbers
6. Your Camera-Y-Rotation and Camera-X-Rotation should be 0
7. Your Camera-Projection should be Orthographic
8. Your "Size" should be like this : https://indiehoodgames.wordpress.com/2013/07/27/pixel-perfect-calculator-for-orthographic-camera-unity3d/

# Answer
> 1 votes
check the scale slider in game window it must be x1 for better quality

# Answer
> 0 votes
Try turning off anti-aliasing completely in the project settings.

Edit -\> Project Settings -\> Quality

Here, disable Anti Aliasing, and Anisotropic Textures.

# Answer
> -3 votes
Try setting the compression to rgba 24bit (override default) and filter mode to point.

---
Tags: unity, pixel-art
---


# Question
Title: Trouble creating a "Game Log" for a text-based RPG
I've made significant progress porting my game from print-output to Pygame over the last few days, and I think I'm almost there!

Unfortunately, I'm beginning to suspect one of the methods I'm using to display my output is deeply flawed when it comes to what I eventually want it to do.

My goal is to create a "Game log" that displays the output from the most recent actions the player has taken.

For example, if the player entered a cabin, searched the cabin, then picked up the key they found there, I would like the gamelog to display

*You enter the cabin*

*You find a Rusty Key*

*You take the Rusty Key*

Currently, any time the gamelog updates, it replaces the previous output. This poses several issues:

1.) In a game of this style, a player can easily forget what the last few things they've done are. Not being able to see recent actions can be tedious and annoying to the player.

2.) The method I use to allow players to check their inventory works through a for-loop. With the way the gamelog works right now, only the most recently picked up item will display.

3.) In some situations, the info I need to display in this output is contained in a set. This system for displaying output can not take sets as an argument.

The code below is what I'm using to generate the output. This comes from this set of functions called "Pygame\_Functions"

https://github.com/StevePaget/Pygame\_Functions

which has been quite helpful.

I'm beginning to think that this may not be the best way to achieve what I'm trying to do. It seems like this is only really effective for rendering a singular message.

```
class newLabel(pygame.sprite.Sprite):
    def __init__(self, text, fontSize, font, fontColour, xpos, ypos, background):
        pygame.sprite.Sprite.__init__(self)
        self.text = text
        self.fontColour = parseColour(fontColour)
        self.fontFace = pygame.font.match_font(font)
        self.fontSize = fontSize
        self.background = background
        self.font = pygame.font.Font(self.fontFace, self.fontSize)
        self.renderText()
        self.rect.topleft = [xpos, ypos]

    def update(self, newText, fontColour, background):
        self.text = newText
        if fontColour:
            self.fontColour = parseColour(fontColour)
        if background:
            self.background = parseColour(background)

        oldTopLeft = self.rect.topleft
        self.renderText()
        self.rect.topleft = oldTopLeft
        updateDisplay()

    def renderText(self):
        lineSurfaces = []
        textLines = self.text.split("<br>")
        maxWidth = 0
        maxHeight = 0
        for line in textLines:
            lineSurfaces.append(self.font.render(line, True, self.fontColour))
            thisRect = lineSurfaces[-1].get_rect()
            if thisRect.width > maxWidth:
                maxWidth = thisRect.width
            if thisRect.height > maxHeight:
                maxHeight = thisRect.height
        self.image = pygame.Surface((maxWidth, (self.fontSize+1)*len(textLines)+5), pygame.SRCALPHA, 32)
        self.image.convert_alpha()
        if self.background != "clear":
            self.image.fill(parseColour(self.background))
        linePos = 0
        for lineSurface in lineSurfaces:
            self.image.blit(lineSurface,[0,linePos])
            linePos+=self.fontSize+1
        self.rect = self.image.get_rect()

```

And this bit here is the function I'm using to update the output after each player action.

```
def changeLabel(textObject, newText, fontColour=None, background=None):
    textObject.update(newText, fontColour, background)

```

My general concept for how to get my gamelog made is that each of these output statements needs to be inserted into the first spot of a list.

Then, display the whole list, and pop off items from the list once they reach a set limit.

If anything on this needs to be clarified, or if other parts of my code are required to understand what my issue is, I'll update this post with whatever is requested.

# Answer
So there's a couple steps to this:

1. You need a list to handle the log messages.
2. You need a function to print events to the list. How you do this is up to you, but it needs to be a function you can call whenever these events happen. Something as simple as a custom print function works just fine. Here's a quick idea of how to make the log itself:

list = \[\]

def console\_print(message): list.append(message)

console\_print("Test")

Then it gets harder because you need to display it as part of the UI. So you need to pick your dimensions and measure it out and determine how many lines of whatever sized font you are going to use. If it is turn based this is all a little easier to do because you can just update it every turn. I personally prefer to blit UI elements separately with pygame, so my order of display would be something like this for each turn:

1. Create a list of n messages where n is the number of lines you can fit in your display element.
2. Take the last n elements from your log list and append them to the new list.
3. Create a surface the size of your UI element.
4. For n lines that you want to display, use font.render to add a line. You'll need to calculate the X and Y coordinates for each one which is a little trial and error.
5. Now that you have this surface and you've rendered lines of font onto it, you can blit it back to your main surface as part of your update() process. You would ideally do this each turn, and not just for your log but for every UI element.

Putting UIs together with pygame is my favorite part of it. Anything is possible once you start getting your head wrapped around blitting surfaces on top of surfaces. Custom-design your update() method for your game and your UI! I'll dig up the last console I made next time I'm at my PC so you can see some real code. I'm no expert but I can help you here. Good luck!

Edit: I'm having a very hard time getting my little python snippet to indent properly on the Stack Exchange app. Sorry.

Edit #2: Alright I got home and whipped up a little example. I'm not the best at being "pythonic" but here you can hopefully see how I create a surface for the log, populate it with rendered text, and THEN blit it onto the main surface (which for this example is just a black space). Dividing your pygame UI up into HUD sections is a big part of jumping from making text-based programs to working with pygame's surfaces. Please forgive my use of magic numbers.

```
# A little pygame console
# press "t" to add messages to the continuously updatding HUD element

import pygame

pygame.init()

# constants
RES = (800, 600)
FPS = 30

MAIN_SURFACE = pygame.display.set_mode(RES)
CLOCK = pygame.time.Clock()

pygame.display.set_caption("Example Console UI Element")

the_font = pygame.font.Font(None, 32)

message_log = []

def console_print(message):
    message_log.append(message)

def update_log():
    # create a surface for the log:
    # This one the same width as the RESOLUTION and 1/3 the height
    log_surf = pygame.Surface((RES[0], RES[1] // 3))
    log_surf.fill((80, 80, 80))
    # Populate it with, say, the last three messages:
    # Note: You could do this in a more elegant loop if you wanted to.
    #       You would probably be served by checking to see if you have any messages at all before
    #       searching through the message log, to avoid looking for elements that aren't in the list.
    #       for this example I added 3 placeholder messages at the start of the main function
    #       to avoid that problem here.
    new_log = []
    m1 = message_log[-1]
    m2 = message_log[-2]
    m3 = message_log[-3]
    new_log.append(m1)
    new_log.append(m2)
    new_log.append(m3)
    font_y = 0
    for m in new_log:
        message = the_font.render(m, False, (255, 255, 255))
        log_surf.blit(message, (0, font_y))
        font_y += 34  # gives a little padding for the next message
    # blit it to the main surface in a spot where it'll fit snugly:
    # sorry for the magic numbers, ideally you would pre-define these positions
    # as variables
    MAIN_SURFACE.blit(log_surf, (0, 400))

def update():
    MAIN_SURFACE.fill((0, 0, 0))
    update_log()
    pygame.display.flip()

def main():

    console_print("Placeholder message 1")
    console_print("Placholder message 2")
    console_print("Placeholder message 3")

    messages = 0

    running = True
    while running:
        for event in pygame.event.get():
            if event.type is pygame.QUIT:
                running = False
            if event.type is pygame.KEYDOWN:
                if event.key == pygame.K_t:
                    # advance the turn as an example
                    messages += 1
                    console_print("Message # " + str(messages))
                    # test in the terminal
                    print("Message # " + str(messages))

        update()

        CLOCK.tick(FPS)

    pygame.quit()

if __name__ == "__main__":
    main()

```

There you go! By messing around with the numbers here you can hopefully get a feel for messing with surface dimensions. I apologize in advance if this is stylistically bad but it's worked well for me in many projects. Pygame has built-in sub-surface capabilities but I have not deeply explored those at all. Hard-coding your dimensions is not a bad way to start, I feel. I hope that helps and good luck!
> 2 votes

# Answer
You can easily shorten the code and find a better setup by putting the last x actions in a list y indices long. Every time there is a new action, the system will shift them closer to one end of the list and cut out the oldest one. The method is quite simple:

make a loop that starts at the last indice:

```
i = len(your_list_here) #Replace your_list_here with the text list of previous actions
while i > 0: #need to do a loop for all indicies
    i -= 1 #You have to do this task first, or else the program wacks out
    if i > 0:
        ylh[i] = ylh[i-] #I decided to shorten your_list_here for easier time typing
    else:
        ylh[i] = new_string

```

so then you would make a new array that updates the text through watever method you use.
> 1 votes

---
Tags: python, rpg, text, ui-design
---


# Question
Title: NodeJS client gameloop running slightly faster than server gameloop
So I'm working on a real time multiplayer game in NodeJs (Client and Server). Both loops handle the same "physics" (movement at a constant rate) and both are running at 40hz or 40 times per second. I am using setInterval on both client and server with a delay of 40ms. The issue is that my server average delta between each tick is ~41 and my client average delta between each tick is ~40. This leads to results like this:

See in the last result, there is a difference of 46 ticks meaning the client is rendering about 1.8 seconds ahead of server time. My first guess on solving this is to sync the client every so often but that would lead to it "teleporting" backwards quite often due to how much it is desyncing.

# Answer
Rather than coupling the time component of your physics engine with this abstract notion of a game loop tick, could you use the system time? One second on machine X will always be the same as one second on machine Y.

```
let currentTime = Date.getTime();

// Then in your loop
let previousTime = currentTime;
currentTime = Date.getTime();
let delta = currentTime - previousTime;

```
> 0 votes

---
Tags: networking, game-loop, node.js, synchronization, realtime
---


# Question
Title: ASSIMP OpenGL collada and Skeletal Animation
first of all i would like to say that i read everything out there and still did not figure it out quite yet.

In my project i need to implement a skinning technique, but before going there i need to get the standar Linear Blend Skinning working.

I'm using assimp to load my model. For testing purposes my model is a cylindre with a single mesh and 2 bones. There are no animations, the goal of my demo is to manually move the bones.

I read every tutorial/article outhere about assimp and skeletal animation. So i think i got the loading part right. I got the mTransformation from the nodes and got the offsetMatrix from the meshes with the same name (i used a map to store the bones/names).

i did some printing to verify my structure and i'm loading the correct info, i'm getting identity matrices everywhere (wich i think is normal since there is no animation and it's just a simple mesh).

The part i could not figure out still , is how i apply these transformations to my vertices. This point affects the loading too ,when i apply a scale/translation on a mesh in blender i can't get it in my renderer.

in my bones i store 2 matrices and i have a third one that represents the final transformation. I did not understand how i would compute this one, i saw some people using and inverse of the root transform and i have a hard time coding something i don't understand.

```
struct Weights
{
    uint vertexID;
    float weight;
};

struct Bone
{
    Bone():parent(nullptr){}
    ~Bone()
    {
        for(auto p: children)
                delete p;
    }

    std::string name; // bone name

    QMatrix4x4 nodeTransform; //Transformation of the node
    QMatrix4x4 offsetMatrix;    // Going into the bone's space
    QMatrix4x4 finalTransfrom; // where we store the final transfrom

    QVector<Weights> boneWeights; // bone wheights

    Bone *parent; // pointer to the parent node nullptr if root
    QVector<Bone*> children; // storing pointers to the children
};

```

thank you for help !

# Answer
> 1 votes
I was implementing the skeletal animation code recently, while not for Collada, I did it for GLTF, which is similar to Collada (also from Khronos), although it uses JSON + binary data rather than XML.

The understanding is the most important part. Once you understand the theory, the code will flow naturally. For skeletal animation, you need a mesh and a set of bones. Each vertex of the mesh has to include N weights (floats) and N bone indices (ints). Value of N depends on your usecase, usually 4 is used. You pass the weights and bone indices to your vertex shader as vertex attributes (vec4 weights and ivec4 bone indices, for example).

As for the bones themselves, they have matrices. For skinning, each bone needs to know it's "inverse bind pose" matrix (mOffsetMatrix in assimp) and global pose matrix.

In the end, you will do a transformation like this in the vertex shader:

for (int i = 0; i \< 4; i++) position += weights\[i\] * globalPose\[bone\_indices\[i\]\] * invBindMatrix\[bone\_indices\[i\]\] * vertex.position;

Global pose matrix can be calculated from local pose matrices. Each bone has one, local pose matrix is the matrix that you obtain from currently running animation, it describes the translation/rotation of the bone in bone local space. To get global pose matrices, you just start with the root bone. Set the root bone global pose matrix to local pose matrix (because it has no parent). Go down the bone hierarchy, and calculate global pose matrix as parent global pose matrix multiplied with the local pose matrix.

Skeletal animation is one of those things you randomly write code, try to piece together samples from tutorials, until suddenly you have the eureka moment, grasp the theoretical part and order of transformations and suddenly it all seems obvious to you.

# Answer
> 0 votes
I'm just starting to piece this together myself, but I've managed to apply transformations to bones by exporting them as collada files. Nothing else works AFAIK. This does not work for me with fbx.

Here is the "formula" as I understand it:

```
bone_transform = inverse(mRootNode->mTransformation) * aiBoneNode->parent->mTransformation * animation->RST matrix * aiBone->mOffsetMatrix;

gl_Position = MVP * bone_transform * vertex;

```

I'll try and elaborate, minus all of the code I used to traverse aiScene... First, you need to get the offset matrix from the bone:

```
scene->mMeshes[1]->mBones[idx]->mOffsetMatrix)

```

Next, look up the transform matrices:

```
parentTransform(transform, scene->mAnimations[idx]->mChannels[cIdx]->mNodeName);
inline void parentTransform(glm::mat4 &result, aiNode* node) {
  if (node->mParent != 0x0) {
    glm::mat4 tmp = aiMatrix4x4ToGlm(&node->mParent->mTransformation);
    result = tmp  * result;
    parentTransform(result, node->mParent);
  }
}

```

Then, get the keyframe transformation:

```
                            glm::quat key_rotate(
                                scene->mAnimations[idx]->mChannels[cIdx]->mRotationKeys[0].mValue.w,
                                scene->mAnimations[idx]->mChannels[cIdx]->mRotationKeys[0].mValue.x,
                                scene->mAnimations[idx]->mChannels[cIdx]->mRotationKeys[0].mValue.y,
                                scene->mAnimations[idx]->mChannels[cIdx]->mRotationKeys[0].mValue.z
                            );

                            glm::mat4 key_translate = glm::translate(
                                glm::mat4(1.0f),
                                glm::vec3(
                                    scene->mAnimations[idx]->mChannels[cIdx]->mPositionKeys[0].mValue.x,
                                    scene->mAnimations[idx]->mChannels[cIdx]->mPositionKeys[0].mValue.y,
                                    scene->mAnimations[idx]->mChannels[cIdx]->mPositionKeys[0].mValue.z
                                )
                            );

```

Next, mash it all together:

```
                                m_scenes[mIdx]->m_bones[bIdx].keyframe_transformation =

                                glm::inverse(aiMatrix4x4ToGlm(&scene->mRootNode->mTransformation)) *
                                //aiMatrix4x4ToGlm(&scene->mRootNode->mTransformation) *
                                transform *
                                //aiMatrix4x4ToGlm(&scene->mRootNode->mChildren[0]->mTransformation) *
                                key_translate *
                                glm::mat4_cast(key_rotate) *
                                m_scenes[mIdx]->m_bones[bIdx].offsetMatrix;

```

Send it to your vertex shader:

```
gl_Position = proj_matrix * mv_matrix * bones[boneId] * vec4(position, 1.0);

```

And voilà.

---
Tags: transformation, skeletal-animation, assimp, model-loader
---


title: Ecliptic rotation around parent object

text:
# Question
Title: Ecliptic rotation around parent object
It seems to be answers.unity.com not working for a couple of days, so I ask my question here.

Well, I'm using Unity and I have two objects (A and B). Object A is a parent of object B and object B is rotating around object A executing RotateAround function.

And everything is fine until I rotate the object A. In this situation I get a mess I can't explain because of lack of geometry knowledge.

**But I have to be able to rotate object A with object B keeps its round ecliptical orbit around object A.**

How can I do it in code?..

*Sorry for a messy question and bad English. Hope those pictures help to understand what I want. Thanks to you all.*

# Answer
> 1 votes
Solution found. Already answered question.

In my case I had to change the code kinda this way:

```
objB.transform.RotateAround(objA.transform.position, objB.transform.up, 1);

```

---
Tags: unity, rotation
---


# Question
Title: How to delete the splash screen I accidentally added?
GameMaker allows you to display an splash screen different from the default.

For a moment I thought of using the ready method that you just click the button in the global settings of the game.

In the second following I added the splash screen, I changed my mind and decided to do it by the "manual" method: create a room, set the time and everything.

That way I could only make one splash screen for all platforms. Also, for windows, using the method ready, I can not set the time, in addition to what was said, that I have to add to other platforms.

I know that if I unchecked the option to display the splash screen, it will not display by itself, but if it has not disappeared, so the game opening default screen appears, it will be in the game assets ... That is, a useless file of almost half a megabyte.

I have rebooted the GameMaker, delete the directory splash screen, but nothing happened.

Tell me how to delete it so that the default splash screen appears in the game settings (on the windows tab).

# Answer
> 0 votes
I had already accepted the fact that my game contained a useless splash screen in the assets when I compiled it and received three warnings (not to mention here) but that had nothing to do with the problem.

So I was taken to a certain directory where there she was, my useless splash screen.

To find such a directory, just go to the.gmx folder of your game, then Configs, Default, windows.

**yourGame.gmx/Configs/Default/windows**.

Knowing that after deleting, the following splash screen will appear in the GameMaker settings:

---
Tags: game-maker, splash-screen
---


# Question
Title: 360 degree Shooting using Pythagoras problem Unity 2D C#
I have used pythagoras to give the bullet a velocity in the bullet class. Velocity is applied when `Instantiated();`

```
 private Rigidbody2D rB;
 private Vector2 velocity;
 private float bulletSpeed = 15f;

 rB.velocity = new Vector2(bulletSpeed * (Mathf.Cos(transform.rotation.z)), bulletSpeed * (Mathf.Sin(transform.rotation.z)));

```

I call the instantiation from the `Gun` class.

```
if (Input.GetButtonDown("Fire1"))
        {
            bullet = Instantiate(bullet, bulletObjectPos.transform.position, transform.rotation);
        }

```

Its giving me funny velocities for the angle i shoot from when the placeholder Gameobject class is rotated, shown below:

Do i need to do more to the velocity? like conversions to radians or something? Or is doing the Pythagoras thing all wrong. I've been scouring the internet all day.Thanks for any help.

The 'Bullets' travel from the muzzle to their location on the images

# Answer
`transform.rotation` is a `Quaternion`, not a collection of angles. Accessing individual components of a quaternion is almost never what you want to do.

Instead, you can do something like....

```
 // Implicit conversion to Vector2 strips out the z component.
 Vector2 firingDirection = transform.right;
 firingDirection = firingDirection.normalized;

 Vector2 velocity = speed * firingDirection;

```
> 1 votes

---
Tags: c#, 2d, unityscript, angles, euler-angles
---


# Question
Title: How do I get a relative rotation between two positions?
For example, I have two objects: a & b.

a's position is 12, 16, -2 and b's position is 14, 16, -3

I need to know how to find a relative rotation between them.

By relative rotation I mean this: a's pitch and yaw so a is looking at b.

I have no helping methods like lookingAt() etc. I only know a's x,y,z,yaw,pitch and b's x,y,z.

Any help?

# Answer
> 1 votes
Assuming that:

1. **+Z** is **up** in your world.
2. Your objects look in the direction of **+X**.
3. No roll.

And vector *delta* is posB - posA...

Then object *a* **first** needs to yaw (around Z) with angle `atan2f( delta.y, delta.x )`.

And then object *a* needs to tilt with angle `-asin( delta.normalized().z )`.

As DMGregory mentioned, this all changes if you have different conventions in your world (Which axis is up, what is rotation sequence, left-handed coordinate systems or right-handed ones.)

Aside from this, note that it is often beneficial not to use euler angles, and just set *a*'s transformation matrix by choosing x-axis as normalized view dir, y-axis is cross between (0,0,1) and this x-axis, normalized. And then z-axis as cross between x and y. After setting the translation component to the position, the resulting matrix can be used for object *a*.

---
Tags: rotation
---


# Question
Title: How do I move the paddle with the arrow keys?
I am making a pong game using gdi+ and c#. I want to move the paddle using the arrow keys by using the move variable, but it does not work; the paddle does move when I use the int move=0; global variable.

I am thinking about nesting my methods.

Is it possible to nest the Form1\_Paint into the Form1\_Keypress method?

```
    int move = 0;

    public void Form1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)56)//key 8
        {
            move--;
        }

        if (e.KeyChar == (char)50)//key 2
        {
            move++;
        }
    }

    public void Form1_Paint(object sender, PaintEventArgs e)
    {
        Graphics g = e.Graphics;
        SolidBrush blueBrush = new SolidBrush(Color.Blue);
        SolidBrush redBrush = new SolidBrush(Color.Red);
        SolidBrush whiteBrush = new SolidBrush(Color.White);
        Rectangle rect1 = new Rectangle(0, 250, 35, 100); //blue paddle
        Rectangle rect2 = new Rectangle(750, 250 + move, 35, 100); //red paddle
        Rectangle rect3 = new Rectangle(390, 290, 10, 10); //white ball
        g.FillRectangle(blueBrush, rect1);
        g.FillRectangle(redBrush, rect2);
        g.FillRectangle(whiteBrush, rect3);
        g.Dispose();
    }

```

# Answer
This is likely because there is nothing that triggers the paint event.

So in your code the paddle variable is updated by the keypesses, but since there is no ‘gameloop’ the redraw is not triggered and thus the movement is not shown.

There are two ways around this:

1. Trigger the repaint event by ‘invalidating’ the form or calling the `InvalidateRgn(hWnd, NULL, TRUE);` This way the normal eventing of the form handles the drawing updates.
2. Set up a renderthread- a more complex way but better in general. This gives you best control over the drawing aspect of your game. There are some samples out there to explain in more detail like this.

So- if you go for option one, you could do a redraw with each keypress, or... You would need to set a timer anyway for other parts of the game (ball, AI) and handle the repaint trigger there.
> 3 votes

# Answer
You have no logic to actually change the position of the paddles. You just create them, give them a colour and paint them to the screen.
> 0 votes

# Answer
You could try using arrow keys: http://net-informations.com/q/faq/arrowkeys.html

```
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    //capture up arrow key
    if (keyData == Keys.Up )
    {
        move--;
        MessageBox.Show("You pressed Up arrow key");
        return true;
    }
    //capture down arrow key
    if (keyData == Keys.Down )
    {
        move++;
        MessageBox.Show("You pressed Down arrow key");
        return true;
    }
    return base.ProcessCmdKey(ref msg, keyData);
}

```
> 0 votes

# Answer
well here is my code to use the arrow keys

```
        int move = 0;

    public void Form1_KeysDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Up)//key up
        {
            move--;
            MessageBox.Show("Key Press");
        }

        if (e.KeyCode == Keys.Down)//key down
        {
            move++;
            MessageBox.Show("Key Press");
        }
    }

```
> 0 votes

---
Tags: c#, windows-forms, pong
---


# Question
Title: Can I speed up "potential fields" pathfinding when it's working on a large grid?
I'm looking to implement a pathfinding algorithm that will allow me to throw hundreds of spiders at the players in my grid-based game. I can implement this with A\*, but I'm worried that that algorithm has too high of a "per spider" performance cost.

The "potential fields" approach looks really good to me, but my map is quite large and rebuilding the entire potential field sounds expensive (even on a background thread).

Unfortunately, there's no logical divisions on my map where I could separate the grid into smaller grids. And the map is quite dynamic (walls/bridges can be destroyed, which could have huge impacts on pathing).

Are there any options other than reducing the size of the map?

# Answer
If you can't subdivide the grid then combine the spiders. Make each navigable spider represent a group of N spiders, then calculate one path and during your movement flow the N spiders out during placement and rendering.

I assume that you're not keeping individual stats on these hundreds, like Spider named "Leggy Bob" has 3 HP remaining while his neighbor "Mandible Sheila" has 4 HP. That would be silly.
> 2 votes

# Answer
You can amortize the cost of building the grid and computing the flow.

In a 60 FPS game, there is no need to compute it every frame. Once every 20 frames is more than fast enough.

So maybe just process 5% of the cells, each frame.

That said, with fields like this, you typically need to redo all the work for every group of NPCs that have a different goal.

You can also do SIMD processing of your grid. I personally did this with AVX Intrinsics in my steam game Imhotep, Pyramid Builder. I used 10 grids, one per goal, of size 128x128 cells. It pays if you can process 8 cells in a single instruction.

But the nice thing of these fields is, that once computed, you can have as many NPCs using it, as you want. As long as they share their goal. This allows for 1000s of agents doing pathfinding. Pathfinding this way is independent of the crowd size (cost is near-constant in crowd size, linear in number of different goals.)
> 2 votes

# Answer
This is way too much information to explain in a single answer, but some good keywords for multi-unit pathfinding are "swarm pathfinding", "boids", "flocking behaviors", and "collision avoidance pathfinding".

Also for highly dynamic maps, if approximate paths are ok, check out HPA\* (Hierarchical Pathfinding A\*) - you don't need "logical divisions" to be able to separate your grid into smaller grids.
> 0 votes

---
Tags: ai, path-finding
---


# Question
Title: How should I store world data in a 2D grid sandbox game?
I'm just a beginner game developer and working on my own first project (beyond copying other games for learning skills).

Because I really like sandbox games (like Minecraft, Rimworld, Terraria etc..), I am trying to make a 2D grid-based sandbox game.

For now I am building a plan for my game's base architecture, and I'm having an issue managing world data (for more specifically, handling Block/Tile Data).

In a sandbox game, you can easily place or remove some blocks (or tiles) as you like. So you need to store it in some kind of storage and sort it so that you can access these blocks easily.

So I thought I should make an Array that holds pointers to Tile Class instances, and the index in the array corresponds to the grid's index. I started writing code based on this idea.

But here is the problem: since not every tile's size is 1x1, some may take 2x3 blocks. If i just put this object's pointer in the array, there are 6 identical pointers stored in single array.

I think that may not the best way to handle tile data.

I thought there might be some way to handle tile data better than to just put a pointer in array.

So how should my game handle multi-grid-cell sized block (or tile) data?

# Answer
> 3 votes
> But here is the problem, since not every tile's size is 1x1, some may take 2x3 block size. and if i just put in Array this object's pointer, there is 6 same pointer will store in single array.

Don't treat the 2x3 block as one tile. Treat it as 6 different kinds of tiles with the specific behavior that when you add or remove one of them, you also add/remove the other 5 of the group. That will really cut down on the corner-cases you need to handle.

I also agree with Damon: Do not represent each block with a full-blown pointer to an object. That's going to cause an overhead which is non-negligible in this case.

Tiles which do not need an unique state (like a dumb piece of rock) do not need an own object. All rock-tiles can share the same object. You can represent them with an integer representing the type-ID. Use the shortest type of integer which still fits as many tile-types as you have (1 byte if you stay under 255 tile types, 2 byte if you stay under 65535). So for example, if you need the texture of the tile at coordinates `x:y` of the current chunk you would do

```
texture = tileTypes[chunk.tiles[x,y]].texture;

```

This will also make your serialization and deserialization a lot easier. Writing and reading a 2d array to/from files is rather simple. But if you need to come up with a scheme so serialize your tile class, it gets a lot more complicated. A fast and solid serialization system is important for infinite world games like Minecraft, because they suspend those parts of the world which are outside of the sight range to hard drive and load them when the player returns.

For those kind of tiles which do have unique state (like chests, signs or smelters in Minecraft), each of these tiles will require an own object to hold its state and handle its interaction logic. The tiles should still be represented as integers in the map chunk array. But their tile-specifc data should be stored in separate data-structures which serves as a lookup table to link tile-coordinates to tile-specific state objects.

Which data-structure would be appropriate for this purpose depends on how many of them you have. When you expect to have about as many functional as non-functional objects, then it might make sense to store their states in another 2d array with the same dimensions as the map chunk (with the entries which map to non-functional tiles holding `null` values). When you want to be able to handle a few hundred functional tiles per chunk, then you might want to use a binary tree or hashtable to map coordinates to states. When you are only expecting a single-digit number per chunk, you can just store them in a list in which you perform a linear search when you need to.

# Answer
> 1 votes
There are two major things to keep in mind with that kind of game: Memory and cache. While that sounds simple, you could write a bookshelf full of books about this.

Memory is O(N²) or O(N³) respectively in that kind of game, so you are being kinda desperate from the start because you're fighting giants.

If you can get away using one byte of storage per cell (requiring a table lookup or similar) instead of 8 bytes for a pointer, you will want to do that. This not only cuts down memory requirements, but it also increases how many cells will fit into cache.

Next, objects are not cells (even though they may *look* alike). Up to a maximum number of objects is stored *outside the grid* (object with properties and position). Terraria, which you named as an example, stores around 400 objects maximum (drop more, and the oldest one disappears). This is not perfect, but it is rarely a problem and it "works".

Similarly, enemies (or NPCs) are heavily pruned away. What isn't visible doesn't exist (reverts to a minimum or even a default state) and is not simulated.

Also, you will want to prune away as large as possible unused areas as soon and efficiently as you can. Lastly, you will also want to make sure that what belongs together is together.

Which leads to... spatial subdivision algorithms, of which there exist a couple different ones. Minecraft uses, if I am not mistaken (not 100% sure) a sparse octree. Hierarchical grids may be another option. Different algorithms have different pros and cons, you may even want to combine several.

In 2D you might still get away with storing the whole world in an array (though that's very sub-optimal cache-wise, you spend *a lot* of game logic in looking at nearby cells so what's close should be stored close together). In 3D, you have pretty much no choice but to rigorously prune away huge regions of unused space, as for example with a sparse tree. Otherwise there's simply no way you can store a world of any serious size in memory.

---
Tags: tiles, data-structure, grid
---


# Question
Title: Unity animation plays in preview but not in playing mode
I create a simple animation and an override controller for it with code.

```
//AnimationScript.cs
public Vector3 direction;
public float distance;

void Start()
{
    direction = direction.normalized;
    Vector3 posA = transform.position;
    Vector3 posB = posA + (direction * distance);

    AnimationClip clip = new AnimationClip();
    AnimationCurve curve = AnimationCurve.Linear(0.0f, posA.y, 1.0f, posB.y);
    clip.SetCurve("", typeof(Transform), "localPosition.y", curve);

    Animator anim = GetComponent<Animator>();
    AnimatorOverrideController animatorOverrideController = new AnimatorOverrideController(anim.runtimeAnimatorController);
    // "loop" is the name of clip not name of state
    animatorOverrideController["loop"] = clip;
    anim.runtimeAnimatorController = animatorOverrideController;
}

```

When I preview animation it works perfect, but when I export and play it, it does not start but camera motion works. What is the reason for that and how do I correct it?

Here are my object settings and controller:

# Answer
> 1 votes
The SetCurve API Documentation has this to say:

> `SetCurve` will only work at runtime for legacy animation clips. For non-legacy AnimationClips it is an editor-only function.

I’m guessing that this is the problem, since you are working with an Animator.

---
Tags: unity, animation, animation-controller, animator
---


# Question
Title: Unity - how to check if object is fully covered by another objects (2d)
I am creating an educational game for kids , and in one of the levels player must to paint animals , like in color book, so I created scene where 2 object , already colorful lion and white lion (white is above) and script, which is instantiating circle sprite masks in players touch position , how can I check if white lion is fully covered by masks and not visiable .

P. S. If you have better idea for painting (like painting with brush) and checking , please say.

# Answer
One possible solution is to cover your lion with invisible GameObjects that start off with a `bool isTouched = false`.

Then, you keep a count of how many of these GameObjects are on the lion and how many have been touched so far. Each time one is touched and `!isTouched`, you set `isTouched = true;`, increment the count by 1, and then check if the touched count equals the total number of points. If they are equal, then you know every point has been touched at least once.

Pros:

* You can adjust the granularity of how much of the lion needs to be touched manually: fewer GameObjects = more forgiving of gaps in the coloring; more GameObjects = higher fidelity
* You can use the number of touched objects vs the total number to cheaply measure progress & add effects accordingly
* Time efficient - things are only called on frames where something is touched.

Cons:

* Requires manual placement of the GameObjects (there may be a good way around this)
* Depending on GameObject placement and how large their colliders are, there can be false positives or false negatives on detecting complete coloring
> 1 votes

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


# Question
Title: Rendering PhysX Primitive Geometry in DirectX 12
I created a scene with two primitive geometries (Sphere and Box). Now I want to recreate what I see in the scene (PhysX Visual Debugger) in my game engine window, but I can't find any functions that could help me create a vertex buffer.

How do I render PhysX items using DirectX 12? How can I get vertices from geometries in PhysX?

Code used to create a sphere using PhysX:

```
auto geometry = physx::PxSphereGeometry(1);
auto transform = physx::PxTransform(physx::PxVec3(0, 0, 0));
physx::PxRigidDynamic* dynamic = physx::PxCreateDynamic(*mPhysics, transform, geometry, *mMaterial, 10.0f);
mScene->addActor(*dynamic);

```

# Answer
> 0 votes
In most games, the geometry used for collision is distinct from the geometry used for rendering.

* Rendering geometric complexity is driven by the art style and needs, along with performance considerations
* Collision geometry is usually much simpler because collision performance scales with vertex count, and the collision geometry needs to meet mathematical correctness requirements that don't apply to art. In fact, many collision shapes are actually implicit surfaces which can be very difficult to render directly (unless you are doing raytracing).

In short, you should use the normal methods for rendering a box and sphere with DirectX and stick to using PhyX only to create the collision geometry. You make sure they are both in the same position and reference frame, and it will all work out to appear they are the same in many cases.

> For code for creating boxes and sphere vertex/index buffer for rendering, see *DirectX Tool Kit*'s `GeometricPrimitive` class for DX11 / DX12.

---
Tags: directx12, physx
---


# Question
Title: Unity Hit Collider GameObject is Null when Collider is Child (Line-of-Sight Detection Problem)
I'm creating line-of-sight code in Unity. It allows a radar to check whether it can see an object, or whether the object is behind an obstacle (a collider).

Similarly to Unity's suggestion, I check to see whether a Linecast going from radar to target strikes a collider that belongs to the target's game object.

In my implementation, a `Target` is a type that buildings and vehicles inherit from. `Radar` is a script attached to any game object, tracking from the transform of that game object towards any `Target` within the radar's scope.

The method giving me trouble is below. It is called every time a radar checks whether or not a `collider` stands between it and the `Target` (targets behind a wall or mountain can't be tracked).

```
/// <summary>
/// Check whether two objects can see each other. This does not verify any maximum distance.
/// </summary>
/// <param name="seeker">The object seeing</param>
/// <param name="target">The object being seen</param>
/// <returns>True if within line of sight, false if another collider is in the way</returns>
protected bool InLOS(Transform seeker, Transform target)
{
   RaycastHit hit;
   Physics.Linecast(seeker.position, target.position, out hit);
   if(hit.collider.gameObject == target.gameObject) // Null error? Make sure the sensor is not within a collider/rigidbody, or that trigger is on
      return true;
   else
      return false;
}

```

This method works to a degree. The image below shows its result. Green lines represent unobstructed radar tracking. (There are two radars in the scene: one on the airplane, and one on the dish).

Note that the airplane cannot see the radar dish, nor can the dish see the airplane (although they are both targets). Accordingly, there are two null errors at every frame: `NullReferenceException: Object reference not set to an instance of an object.`

The error points me to the following line: `if(hit.collider.gameObject == target.gameObject)`. That's because, unlike the other, simpler targets, the airplane does not have its collider on the parent, but has many different colliders in its children.

I've tried finding the parent game object from the collider, but that didn't work either:

```
// Raycast
// ...

try
{
   if(hit.collider.gameObject == target.gameObject) // Null error? Make sure the sensor is not within a collider/rigidbody, or that trigger is on
      return true;
   else
      return false;
}
catch
{
   if(hit.collider.GetComponentInParent<Target>().transform.gameObject == target.gameObject)
      return true;
   else
      return false;
}

```

Same null error on `hit.collider.GetComponentInParent<Target>().transform.gameObject == target.gameObject`.

Well then, let's check for nulls:

```
// Raycast
// …

GameObject raycastHit = hit.collider.gameObject;
GameObject desiredHit = target.gameObject;

if(raycastHit == null)
{
   // Collider must be child raycast target hit, then
   raycastHit = hit.collider.GetComponentInParent<Target>().transform.gameObject;
}

if(desiredHit == null)
{
   // Collider must be child...
   desiredHit = target.transform.GetComponentInParent<Target>().transform.gameObject;
}

// Check hit equivalency
if(raycastHit == desiredHit)
   return true;
else
   return false;

```

Nope, same old null reference. Man are those `GetComponent<>` methods always a pain.

So let's go simple:

```
if(Physics.Linecast(seeker.position, target.position))
   return true;
else
   return false;

```

In this case, obstacles are not detected anymore. Hmm.

Question: how can I write `GetComponentInParent<>` correctly to find the `Target` game object's transform, knowing that sometimes `Target` will be a component of the same game object as its collider, while at others, `Target` will be the parent, and various colliders will be children?

# Answer
This method tests positions against each other. If a game object does not have a collider at its pivot point, no collider will be found, causing a null exception.

To fix the null errors, it was only necessary to add a collider to cover the radar building's pivot point, which was exposed in my setup.

The code needed for line-of-sight detection is this:

```
protected bool InLOS(Transform seeker, Transform target)
{
   RaycastHit hit;
   Physics.Linecast(seeker.position, target.position, out hit);

   // Test whether the raycast hit the same game object as the wanted target (no obstacle)
   if(hit.collider.gameObject == target.gameObject)
      return true;
   else
      return false;
}

```

Because of Unity compound colliders, all child colliders can be referred to by using `hit.collider`, making `GetComponentInParent<>` calls unnecessary.
> 1 votes

---
Tags: unity, c#, collider, line-of-sight
---


# Question
Title: Is there a way to force a resolution on Android when using Monogame?
I think I looked everywhere but I couldn't find a way. My phone has a native resolution of 1920x1080 and I would like to run my game at 1280x720.

I tried by changing PreferredBackBufferWidth and PreferredBackBufferHeight but it doesn't seem to have any effect.

Is this possible?

# Answer
> 1 votes
Make sure you are calling ApplyChanges() in the GraphicsDevice object after you set the width & height.

Also, try setting the PrefferedBackBufferWidth & Height in the Initialize().

I've ran into issues when trying to set it within the constructor of the Game class.

# Answer
> 1 votes
It is likely that the mobile device ***cannot*** run in anything other than the native resolution.

Fear not, you can use resolution independance for this. The `spriteBatch.Begin()` method has a transformation matrix parameter. You can use it to scale everything- so you can work in the resolution you like. The resolution you want the game to be is the *virtual resolution*.

```
Matrix scaleMatrix=Matrix.CreateScale(
                        nativewidth/virtualwidth,
                        nativeheight/virtualheight,
                        1f);

```

Now pass that value to the `spritebatch.Begin()`:

```
spriteBatch.Begin(transformMatrix: scaleMatrix);

```

Your sprites will now be transformed to match the native resolution- but it will look like you had the virtual resolution.

Note that for 3D your projection matrix would be calculated for the intended viewport anyway.

---
Tags: c#, xna, android, monogame, xamarin
---