# Question
Title: How can i rotate object for some seconds when other object get close to it?
The first script draw numbers above some gameobjects:

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

 public class generatenumbers : MonoBehaviour
 {
     public GameObject[] objectsToNumber;
     public GameObject text;
     public float yPadding;              /// Padding on the Y-Axis.
     public bool rotateNumbers = false;
     public float rotationSpeed = 10f;

     private MeshRenderer[] renderer;
     private Vector3 newPos;
     private List<GameObject> newTexts = new List<GameObject>();

     private void Start()
     {
         renderer = new MeshRenderer[objectsToNumber.Length];

         for (int i = 0; i < objectsToNumber.Length; i++)
         {
             GameObject newText = Instantiate(text);

             renderer[i] = newText.GetComponent<MeshRenderer>();

             newPos = new Vector3
             (
              objectsToNumber[i].transform.position.x,
              ((objectsToNumber[i].transform.position.y + renderer[i].bounds.extents.y) + yPadding),
                objectsToNumber[i].transform.position.z
              );

             newText.transform.position = newPos;
             newText.transform.parent = transform;
             newText.name = i.ToString();
             newText.tag = "Number";
             newTexts.Add(newText);
             var textmesh = newText.GetComponent<TextMesh>();
             textmesh.text = i.ToString();
         }
     }

     private void Update()
     {
         if (rotateNumbers == true)
         {
             for (int i = 0; i < newTexts.Count; i++)
             {

                 newTexts[i].transform.Rotate(Vector3.up, 10 * rotationSpeed * Time.deltaTime);
             }
         }
     }
 }

```

The result is:

The second script make the character/player to move between the waypoints:

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

 public class waypoints : MonoBehaviour
 {
     public GameObject[] Waypoints;
     public Transform nextWaypoint;
     public float moveSpeed = 10f;
     public float slowDownSpeed = 3f;
     public float rotationSpeed = 1f;
     public bool random = false;
     public bool reverse = false;

     private int targetsIndex;
     private Vector3 originalPosition;
     private int index;
     private GameObject[] numbers;

     // Use this for initialization
     void Start()
     {
         targetsIndex = 0;
         originalPosition = transform.position;
         index = Random.Range(0, Waypoints.Length);

         numbers = GameObject.FindGameObjectsWithTag("Number");
     }

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

     private void WayPointsAI()
     {
         if (targetsIndex == Waypoints.Length)
             targetsIndex = 0;

         if (random == true)
         {
             nextWaypoint = Waypoints[index].transform;
         }
         else
         {
             nextWaypoint = Waypoints[targetsIndex].transform;
         }
         float distance = Vector3.Distance(transform.position, nextWaypoint.transform.position);
         transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(nextWaypoint.position - transform.position), rotationSpeed * Time.deltaTime);

         if (distance < 3)
         {
             transform.position += transform.forward * slowDownSpeed * Time.deltaTime;
         }
         else
         {
             transform.position += transform.forward * moveSpeed * Time.deltaTime;
         }
         if (distance < nextWaypoint.transform.localScale.magnitude)
         {
             if (random == false)
             {
                 StartCoroutine(tempRotate());
                 targetsIndex++;
             }
             else
             {
                 StartCoroutine(tempRotate());
                 index = Random.Range(0, Waypoints.Length);
             }
         }
     }

     IEnumerator tempRotate()
     {
         while (true)
         {
             if (random == false)
             {
                 numbers[targetsIndex].transform.Rotate(Vector3.up, 10 * 10 * Time.deltaTime);
             }
             else
             {
                 numbers[index].transform.Rotate(Vector3.up, 10 * 10 * Time.deltaTime);
             }

             yield return new WaitForSeconds(3.0f);
         }
     }
 }

```

I want that each time the character reach a waypoint to rotate for 3 seconds the number object above the waypoint. So i'm trying to use StartCoroutine

```
StartCoroutine(tempRotate());

```

Then using while(true) i also tried without the while(true) but nothing make it rotating.

```
IEnumerator tempRotate()
         {
             while (true)
             {
                 if (random == false)
                 {
                     numbers[targetsIndex].transform.Rotate(Vector3.up, 10 * 10 * Time.deltaTime);
                 }
                 else
                 {
                     numbers[index].transform.Rotate(Vector3.up, 10 * 10 * Time.deltaTime);
                 }

                 yield return new WaitForSeconds(3.0f);
             }
         }

```

It's like when in game you touch a coin for example and the con rotate a bit for 2-3 seconds then stop. Same idea i want to do with the numbers. When it's reaching to the next waypoint rotate for 3 seconds the number object above this waypoint.

# Answer
> 2 votes
From what I see in your tempRotate() coroutine, you are rotating the object once and then waiting 3 seconds so clearly you woulnd't be able to see it rotate. What you should do instead is store a float that increments with Time:

```
float timeElapsed;

void Update(){
    timeElapsed += Time.deltaTime;
}

```

Now when you call your coroutine, you can set that float to 0 so that u can track how much time has passed, like this :

```
IEnumerator tempRotate()
    {
        timeElapsed = 0;

        while(timeElapsed <= 3) // this checks if 3 seconds is up
        {
            transform.Rotate(Vector3.up, 10);
            yield return new WaitForEndOfFrame();
        }
    }

```

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


# Question
Title: unity editor support 3.5 .net or lower, plugin targeting 4 .net is not supported by unity editor?
I am trying to import some libraries in my unity project but keep getting the above error. Kindly help. Also, if anyone has some some image processing within unity,please point some useful libraries.

When I changed the framework to .net 4 and added the assembly reference to my project, I could compile my unity script but still there were errors like **unloading broken assembly, this assembly can cause crashes in runtime.** and the library I am trying to add is ConvNetSharp.

# Answer
supports the 4, but it is experimental, libraries that you can use there are many and each one is adjusted to your needs, you only need to be compatible with the framework 3.5 or 4
> 1 votes

---
Tags: unity, dll
---


# Question
Title: Can GPU draw from one VB and upload to another VB at the same time? (OpenGL)
We have a working implementation of vertex double buffering, rendering from one buffer and uploading vertex data to next frame buffer at the same time.

However I am concerned that CPU spends quite a lot of time uploading vertex data. Is the upload blocked by video driver because it's busy with drawing?

Or is it caused by driver's pipeline using the frame N+1 buffers for internal rendering of the frame N-1 frame while the drawing thread is issuing commands for frame N and I should consider switching to triple buffering (however I seriously doubt that it can improve FPS)?

Or should I rather queue the frame N+1 vertex uploads and do them after frame N commands have been issued so that there are no blocks in driver?

It's just that the thread that uploads vertex data also does much other work and is now a bottleneck and I want to offload it as much as possible and definitely don't want to see it blocked by driver.

# Answer
What you need is buffer orphaning. Before uploading new data, you first orphan the old buffer by passing NULL to a `glBufferData()` call.

This will avoid the synchronization, and the GPU can keep working with the old buffer, if it has to. GL will allocate a new block for the new data, and will take care of the deallocation for you once the GPU is done with it.

Right after the `glBufferData` with NULL, you call it again with the actual new data.

Doing it this way, both the GPU and CPU can keep doing their thing without having to sync up.
> 3 votes

---
Tags: opengl, vertex-buffer, double-buffering
---


# Question
Title: Calculating unique ID number from a set of bitmasked tiles
I'm writing a match3-style game where you as player need to match tiles with three or more of the same type.

I'm thinking what is the best method to recognize the shapes without writing a monstrosity of switch/if-else statements. Because in my game the player should be able to match many different shapes that consist of at least 3 or more vertical and/or horizontal shapes, for example ...

```
###

#
#
#

#
#
###

###
 #
 #

 #
###
 #

##
##
##

```

And any variation of these (the last one is a block). I'm currently using a floodfill algorithm that not only find all the connected tiles but also assigns a bitmask depending on if and what connections the tile has to its surrounding tiles (it's based on the bitmasking explained here.

Here is the relevant code part for this (Unity, C#):

```
    internal const int BITMASK_NONE = 0;
    internal const int BITMASK_TOP = 1;
    internal const int BITMASK_RIGHT = 2;
    internal const int BITMASK_BOTTOM = 4;
    internal const int BITMASK_LEFT = 8;

    internal const int BITMASK_CORNER_TOP_RIGHT = 3;
    internal const int BITMASK_CORNER_BOTTOM_RIGHT = 6;
    internal const int BITMASK_CORNER_TOP_LEFT = 9;
    internal const int BITMASK_CORNER_BOTTOM_LEFT = 12;

    internal const int BITMASK_THREEWAY_TOP = 11;
    internal const int BITMASK_THREEWAY_RIGHT = 7;
    internal const int BITMASK_THREEWAY_BOTTOM = 14;
    internal const int BITMASK_THREEWAY_LEFT = 13;

    internal const int BITMASK_VERTICAL_LINE = 5;
    internal const int BITMASK_HORIZONTAL_LINE = 10;

    internal const int BITMASK_CROSS = 15;

    private Dictionary<int, GridCell> FindConnectedCells(GridCell cell)
    {
        var connectedCells = new Dictionary<int, GridCell>(size);

        cell.isFlagged = true;

        _cellStack.Clear();
        _cellStack.Push(cell);

        while (_cellStack.Count > 0)
        {
            cell = _cellStack.Pop();

            /* Assign bitmask to cell. */
            if (cell.Equals(cell.top)) cell.bitmask |= BITMASK_TOP;
            if (cell.Equals(cell.bottom)) cell.bitmask |= BITMASK_BOTTOM;
            if (cell.Equals(cell.right)) cell.bitmask |= BITMASK_RIGHT;
            if (cell.Equals(cell.left)) cell.bitmask |= BITMASK_LEFT;

            connectedCells.Add(cell.id, cell);

            if (FlagMatchingCell(cell, cell.top)) _cellStack.Push(cell.top);
            if (FlagMatchingCell(cell, cell.bottom)) _cellStack.Push(cell.bottom);
            if (FlagMatchingCell(cell, cell.right)) _cellStack.Push(cell.right);
            if (FlagMatchingCell(cell, cell.left)) _cellStack.Push(cell.left);
        }

        return connectedCells;
    }

```

This uses a stack-based flood-fill. In any case every tile (or cell) ends of with a specific bitmask value between 1 and 15 and I want to calculate a unique number from these and a couple of other numbers (e.g. how many tiles are in the shape, how many horizontal/vertical tiles it has, etc.) but so far I haven't managed to calculate it to produce really unique numbers. Every now and then it comes up with different shapes that have the same calculated number.

Another problem with this approach is that it can't detect whether all tiles of the shape are valid or not. Consider this shape:

```
 #
****

```

It should be recognized only as a shape of four horizontal tiles but it would also include that additional tile on top.

So my question is: What is another good approach for recognizing all these different shapes? Basically the idea of calculating a unique number for every shape doesn't seem so bad because it seems very elegant but there is then still the problem with the odd shapes like above.

**UPDATE:**

Possible solution to calculate unique number ID for each possible variation (Code in Swift because written in Playground for faster testing):

```
import Cocoa
import Foundation

var d:[Int:Int] = [:]

func calc(n:Int)
{
    var s = ""
    for i in 1 ... 15
    {
        let result = i * (i + (i * n * n))
        s += "\(result)  "
        if let _ = d[result] { print("\t\t\tAlready exists: \(result)") }
        else { d[result] = result   }
    }
    print("(\(n)) \(s)");
}

for tileCount in 3 ... 30
{
    calc(tileCount)
}

```

Output:

```
(3) 10  40  90  160  250  360  490  640  810  1000  1210  1440  1690  1960  2250
(4) 17  68  153  272  425  612  833  1088  1377  1700  2057  2448  2873  3332  3825
(5) 26  104  234  416  650  936  1274  1664  2106  2600  3146  3744  4394  5096  5850
(6) 37  148  333  592  925  1332  1813  2368  2997  3700  4477  5328  6253  7252  8325
(7) 50  200  450  800  1250  1800  2450  3200  4050  5000  6050  7200  8450  9800  11250
(8) 65  260  585  1040  1625  2340  3185  4160  5265  6500  7865  9360  10985  12740  14625
(9) 82  328  738  1312  2050  2952  4018  5248  6642  8200  9922  11808  13858  16072  18450
(10) 101  404  909  1616  2525  3636  4949  6464  8181  10100  12221  14544  17069  19796  22725
(11) 122  488  1098  1952  3050  4392  5978  7808  9882  12200  14762  17568  20618  23912  27450
(12) 145  580  1305  2320  3625  5220  7105  9280  11745  14500  17545  20880  24505  28420  32625
(13) 170  680  1530  2720  4250  6120  8330  10880  13770  17000  20570  24480  28730  33320  38250
(14) 197  788  1773  3152  4925  7092  9653  12608  15957  19700  23837  28368  33293  38612  44325
(15) 226  904  2034  3616  5650  8136  11074  14464  18306  22600  27346  32544  38194  44296  50850
(16) 257  1028  2313  4112  6425  9252  12593  16448  20817  25700  31097  37008  43433  50372  57825
(17) 290  1160  2610  4640  7250  10440  14210  18560  23490  29000  35090  41760  49010  56840  65250
(18) 325  1300  2925  5200  8125  11700  15925  20800  26325  32500  39325  46800  54925  63700  73125
(19) 362  1448  3258  5792  9050  13032  17738  23168  29322  36200  43802  52128  61178  70952  81450
(20) 401  1604  3609  6416  10025  14436  19649  25664  32481  40100  48521  57744  67769  78596  90225
(21) 442  1768  3978  7072  11050  15912  21658  28288  35802  44200  53482  63648  74698  86632  99450
(22) 485  1940  4365  7760  12125  17460  23765  31040  39285  48500  58685  69840  81965  95060  109125
(23) 530  2120  4770  8480  13250  19080  25970  33920  42930  53000  64130  76320  89570  103880  119250
(24) 577  2308  5193  9232  14425  20772  28273  36928  46737  57700  69817  83088  97513  113092  129825
(25) 626  2504  5634  10016  15650  22536  30674  40064  50706  62600  75746  90144  105794  122696  140850
(26) 677  2708  6093  10832  16925  24372  33173  43328  54837  67700  81917  97488  114413  132692  152325
(27) 730  2920  6570  11680  18250  26280  35770  46720  59130  73000  88330  105120  123370  143080  164250
(28) 785  3140  7065  12560  19625  28260  38465  50240  63585  78500  94985  113040  132665  153860  176625
(29) 842  3368  7578  13472  21050  30312  41258  53888  68202  84200  101882  121248  142298  165032  189450
(30) 901  3604  8109  14416  22525  32436  44149  57664  72981  90100  109021  129744  152269  176596  202725

```

# Answer
> 1 votes
Up to about an 8x8 grid, it makes sense to index your shapes as a simple bitboard:

1. Find your whole connected shape via flood fill, as you do now. Record the leftmost column and topmost row encountered
2. Initialize your ID to a 64-bit unsigned integer value of 0
3. For each cell in your shape, use an OR operator to set one bit in your ID, like so:

```
bit = (cellColumn - leftmostColumn) + (cellRow - topmostRow) * 8
ID |= (1 << bit)

```

At the end you'll have an integer that's unique to this shape, and insensitive to translation. (It's still sensitive to rotations & flips though. To merge those, you can choose the orientation with the minimal / maximal integer value as "canonical")

This can get impractical if your shapes get bigger though. If we wanted to store a line of 16 cells in a row or column or any other arrangement using a square bitboard like this, we'd need 256 bits, using 16 bits per cell!

---

If your shapes can get large like this, but are generally sparse (lines and Ls, not big blocks usually), you can take a different approach that doesn't assume a fixed-size bounding box for your shapes:

1. Initialize your ID to 0 / an empty bit stream.
2. Start at the leftmost cell of the top row of your shape, facing right
3. Begin a depth-first search from this cell, visiting each other cell in the shape. Make sure your search checks its neighbours in a deterministic order (the order is arbitrary, as are the bit codes below, just be consistent)
4. Each time the depth first search steps forward into a new cell, or backtracks to a previous cell, append some bits to your ID:

* When you go forward (progressing in same direction as the last movement), write the bits 11
    * When your search takes a right turn, write the bits 10
    * When your search takes a left turn, write the bits 01
    * When you backtrack, write the bits 00

Concatenating all of these bits together, you now have a bit string that's unique to the particular polyomino shape traversed (given your particular search sequence). You can reconstruct the shape from its ID just by playing back the "dance steps" encoded in the bit string.

The trouble with this method is that it can produce bit strings which are quite long. Run length encoding can help significantly, but you may pay between 2-8 bits per cell in the shape (a + junction can be entered & backtracked to 3 times). Still better than very sparse use of a large bitboard, but not competitive for smaller/denser shapes.

# Answer
> 0 votes
One way you could do this is to set a specific tag for each type of tile within the Inspector View of each tile in Unity3D. Then you could write code for it, a simple example being:

```
void OnTriggerEnter()
{
   if (tag == "redTileGroup")
  {
     // do something
  }
}

```

---
Tags: unity, c#, algorithm, tile-bitmasking
---


title: Is "reverse season pass" a thing?

text:
# Question
Title: Is "reverse season pass" a thing?
"Reverse Season Pass" is a name I just made up and I want to know if something like this already exists with a better name.

We all know regular season passes: you buy a pass for a game you already paid for, which gives you access to future dlc, which doesn't exist yet, and may or may not be worth the money. AAA publishers love those things and they're pretty BS for the customer, because they are expected to pay for something that doesn't exist yet, or may never exist, or may not even be worth the money. You just have to trust them with your money, and there's no guarantee the base game hasn't been already sliced up into future dlc prior release.

Now lets say you have a story-driven game you want to release in episodes, like I want to do. The game itself is already completely done, all episodes are ready, you just want to pace the content over a few weeks like a show on tv to create discussion and excitement in the fandom for each new episode. The episodes would be added to the base game, meaning the episodes aren't sold separatly, you want to sell the whole experience.

However, if you're like me and you're still a nobody in the gaming industry, charging full price for a game, that's *supposedly done* (you can't know for sure, right?), which is going to be released in pieces *supposedly*, seems... very shady. I wouldn't blame anyone if they found that suspicious.

Lets say your game as a whole is worth 30$ and you have five episodes, so 6$ per episode. What I thought of doing, which I think is pretty fair, is to adjust the price depending on how many episodes are already released. When the first episode is released, the game costs 6$. When the second episode is released, the game costs 12$, then 18$ with three episodes, 24$ with four episodes, and at last, 30$ for the full game with all five episodes.

On top of that, when people buy the game early, when only one or two episodes are available for example, they already essentially bought a season pass on top of the game and will receive all other episodes *for free*. That way, people pay for the game *only* what it's *currently* worth and early adopters are rewarded for their early purchase and show of trust.

Has anyone ever done something similair? Is there a name for it?

# Answer
This sounds pretty much like the Early Access business model. You start selling your game in a very early development stage. While the game is still mostly incomplete, you offer the game for a very low price. The further you progress, the more you raise the price until you've reached your planned price at release day.

The main difference to your business model is that Early Access games are usually not almost finished when they start going into early access. It usually takes years between early access release and actual release. The purpose is usually to fund the development while simultaneously market-testing the game and building hype.

But in your case, where you already financed the development, there is really no reason to follow that business model. You could just offer the base game for little money (or even for free) and release the individual episodes as paid DLC (just make sure that the total cost of the game is transparent). There is also very little business reason to artificially delay the release of the individual episodes. When they are finished, you can just put them onto the market and let players experience them at their own pace. If you release them with delays, there is a high risk that players will get distracted by a different game and forget about yours.
> 2 votes

# Answer
Hitman (2016) did something similar.

Square-Enix sold the base game, what they called the "Intro Pack", for something like $30usd. This included the basic content and a small set of missions (I believe something like 10). Then they released monthly "Episodes" which included new locations and missions, each episode was sold separately and was independent from each other so you didn't had to purchase the first 3 to purchase the 4rd, for instance. They costed around $7usd each. In the end they released a total of 5 Episodes and thus completing season 1.

* Season 1
    + Sapienza
    + Marrakesh
    + Bangkok
    + Colorado
    + Hokkaido

After the season is complete they release both the Season1 pack (all episode but no base game) for around $24usd, and the GOY Edition that includes all previously released content including the base game sold at full retail price; $59.99usd.

I think this model works pretty well, however, it was badly received in the beginning as people are used to purchasing "complete" games, so there were several complaints that the game felt unfinished and unpolished. Usually pricing models that are not traditional or not completely straight forward are perceived in a bad light by gamers, so be aware of that.

Im not sure there is a name for that, but looks like you are trying to do is in fact a "reverse season pass", "**anti-season pass**"?
> 1 votes

# Answer
Arcen Games tried to do something like this with their game In Case of Emergency: Release Raptor figuring they could charge a few bucks for it "as it" and then as it sold, they could use those funds to develop further, incrementally increasing the price to match what the game was at the time.

It didn't go well.

Arcen's press release can speak better than I can, but press didn't like the concept and prospective players (incorrectly) assumed it was YouTube bait (what Goat Simulator is).

So be aware that while that kind of pricing scheme *can* work, there are problems to be aware of.
> 1 votes

# Answer
For over fifteen years, I've been following the games, the game industry and the business models in the industry. I have to say, I've never seen a business model like you're suggesting and I think it might work if you do it well.

The biggest problem you'll have is people not believing that a new developer actually has all the episodes done, but just wants to implement fancy business model.

I think you should have two versions of the game. One where you can present episodes as you want them to be available, and one that has all the episodes readily available. I see two options for this method to work.

The first one is easy, you just release both versions and let people choose whether they want to buy the whole thing now, or buy the episodic version which is cheaper now, but will be the same price as the full version. This can mean that the episodes you haven't released yet for the episodic version will have videos out there and you can't really control this.

Your second option is to only release the episodic version but to give the complete edition to the streamers or Youtube personalities and just ask for them to not release their relevant episodes (in case of Youtube) or play the unreleased episodes (in case of streamers) before you release them. You can do this pretty easily with an NDA (non-disclosure agreement) before sending them the game.

This does mean extra work on your side, but you'll at least have some people that can attest that your game is indeed complete.
> 0 votes

---
Tags: monetization
---


# Question
Title: Instantiating Unity prefabs in a for loop - please help me understand how this works
What this for loop means in context of unity 3d

```
for (int i = 0; i < numberOfObjects; i++) {
        Transform o = (Transform)Instantiate(prefab);
        o.localPosition = nextPosition;
        nextPosition.x += o.localScale.x;

```

i m following this Tutorial

# Answer
> 2 votes
"The next step is spawning the initial row of cubes. We'll use a simple loop for that, instantiating new objects, setting their position, and advancing nextPosition by the width of the object so they form an unbroken line. " This for loop is used to spaw the cubes in your level.

```
for (int i = 0; i < numberOfObjects; i++)

```
* this means : run the code in the brackets based on the number of objects.

First of all you create a Transform object called o; this is the instantiated prefab. Since our goal is to spawn cubes in an unbroken line, also considering that we are using unit cubes(which means width=height=depth) we have to write:

```
o.localPosition = nextPosition;
nextPosition.x += o.localScale.x;

```

We set the position of o to nextPosition and then we increase the x component of nextPosition by o.localScale.x(which in our case is the width of the unit cube)

# Answer
> 1 votes
Loop over desirable number of objects

```
for (int i = 0; i < numberOfObjects; i++) {

```

Create an instance of object, cast to "Transform" type and save to variable "o"

```
        Transform o = (Transform)Instantiate(prefab);

```

Set position of object "o" to position from "nextPosition"

```
        o.localPosition = nextPosition;

```

Update x parameter of "nextPosition" of instantiated object.

```
        nextPosition.x += o.localScale.x;

```

If 1st object is created at nextPosition.x = 10, and width of on object is o.localScale.x = 2, then the 2nd object will be created at 12, 3rd at 14 and etc. To sum it up, bunch of objects are created in line.

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


# Question
Title: LibGDX - i need an event like mouseMoved but it shouldn't care about which buttons are pressed
Using ClickListener I have events like enter(), exit(), and mouseMoved(). But when I have any mouse buttons pressed, moveMoved() won't fire because that's how it works. There is touchDragged() but this will only fire if touchDown happened on Actor (or Actor's tap square). I'd like an event that would fire even if any mouse buttons was pressed outside Actor and his tap square, and keep firing each time mouse is moved over the Actor. How to do it?

# Answer
Sounds like you should implement your own InputProcessor. Here is article on libgdx wiki: https://github.com/libgdx/libgdx/wiki/Event-handling
> 2 votes

---
Tags: java, libgdx, input
---


# Question
Title: How to ignore collisions of triggers after first collision of trigger until OnTriggerExit of first collision of trigger?
There is are white and red two teams of tank which are auto spawning in certain time interval. both red and white type of tanks have triggers so when red and white tank come close enough, OntriggerEnter() is activated and both types of tank stop moving and start to fire each other. their movement is controlled by navemesh and both type of tanks are navmeshagent. Now What i want is when these two start firing each other both tank's trigger need to ignore collision of trigger with third tank until one of those two tanks die. Below is my code any help is appreciated thanks.

```
      public float RBdist;
      public GameObject Rbullet;
      public Transform targetofred;
      public float attackspeedofRtank;
 private void Start()
{
   // rwalktohit = GetComponent<Animator>();
     red = GetComponent<NavMeshAgent>();
    //cube2.velocity = 2f * (cube2.velocity.normalized);
    red.destination = targetofred.position;
//targetofred is the position of house of white tank or base of white tank.

    Rcollider = GetComponent<Collider>();
}
      private void OnTriggerEnter(Collider whitettank)
      {

          if (whitettank.gameObject.tag == "whitetank")//tag of white
// tanks is "whitetank".

        {
          red.isStopped = true;
          twhitetank = whitettank.transform;
          transform.LookAt(twhitetank.position);
          InvokeRepeating("Rfire", 1f, attackspeedofRtank);
         }

      }

private void Rfire()
{

     GameObject Rbulletclone = Instantiate(Rbullet, transform.position ,
    transform.rotation);
     Rbulletclone.transform.position =
   Vector3.MoveTowards(transform.position , twhitetank.position, RBdist);
}

private void OnTriggerExit(Collider whitettank)
{
    if (whitettank.gameObject.tag == "whitetank")
    {
        CancelInvoke("Rfire");
        red.isStopped = false;
    }

}

```

# Answer
> 2 votes
I think it should be as easy as:

```
if (whitettank.gameObject.tag == "whitetank" && !red.isStopped)
{
    // do stuff
}

```

This way the script will skip over your shooting-code after the first time. When you want to re-enable it just set `red.isStopped` to `false` again.

---
Tags: unity, c#, ai, collider
---


title: Precision timing in Unity3d

text:
# Question
Title: Precision timing in Unity3d
I am trying to implement a method which should be called each 10ms with a precision not less than 0.1ms (better 0.05ms). This method is very complex and it is generating sound samples which are placed to float\[\] buffer to be played with OnAudioFilterRead function.

I have tried both Coroutines and InvokeRepeating - both are bad, because they can call the method with period from 7ms to 13ms which is not acceptable.

The only idea I have is another Task with while() cycle checking the Time.realtimeSinceStartup permanently. But I feel like this is a bad idea.

Can you help me? Thanks.

# Answer
> 1 votes
Yes, You can use multi-threading which is not recommended in many cases but it can be used if threads are managed correctly and made sure that Unity API is being called from main thread only.

Read more about pros and cons of using multi-threading:

Why Should I Use Threads Instead Of Coroutines?

Hope this helps :)

---
Tags: unity, c#, audio, sound, timer
---


title: Having the same camera in all scenes

text:
# Question
Title: Having the same camera in all scenes
I have 100 scenes, each scene has a camera, but I want only the camera from scene 1 to exist in each scene that I appear in.

I use the function DontDestroyOnLoad() to make the camera exist in each scene but I always find my self with another camera that I don't want.

Any ideas? thank you in advance.

# Answer
> 2 votes
You need to make sure you remove the camera in every scene except the first one. Assuming you HAVE to keep the first camera for some reason, you probably then need to re position the camera somewhere in your subsequent scenes.

# Answer
> 2 votes
Another option is to have one "master scene" with the camera (and anything else you want to have in every level, like UI elements for example) and then load the individual levels additively with `SceneManager.LoadSceneAsync(scene, LoadSceneMode.Additive)`. You will then have two scenes at once loaded in your game. If you want to switch levels, you can unload the current level-scene with `SceneManager.UnloadSceneAsync(scene)`.

Remember to wait until `UnloadSceneAsync` has finished before calling `LoadSceneAsync`. Otherwise you might occasionally see objects from the new scene interact with objects from the old which were not deleted yet. You can do that by examining the `AsyncOperation` object returned by `LoadSceneAsync` or by assigning a callback method to `SceneManager.sceneUnloaded`.

# Answer
> 1 votes
You can use singleton pattern or add some simple functionality destroying newly created camera if it's already present in scene.

# Answer
> 1 votes
It depends on what you want to achieve:

***You want to preserve the camera through all the levels in you scene***

Then what you want to use is a script with Object.dontDestroyOnLoad()

***You want to use a camera in all your levels, but don't want to preserve the object throughout all the scenes***

This is a work for prefabs. You make a prefab of you camera and apply components, scripts and so on to it. You have to remember to have a "camera" prefab object in every scene. If you want to make changes to it, you just have to modify the prefab, not all the "camera" objects in the scenes

---
Tags: unity
---


title: Image import in Haxe / Openfl

text:
# Question
Title: Image import in Haxe / Openfl
I want to import an image using Haxe, my image is big but it is 8 bits and it weighs 89kb. The problem occurs when I import it, because the size of the memory grows by 35mb. I suppose it is reserving memory for a 32bit image. Any idea how to import an image of 8bits, without consuming so much memory?

# Answer
> 1 votes
Joshua answer the question: https://stackoverflow.com/questions/47478690/image-import-in-haxe-openfl/47479897#47479897

> OpenFL currently uses 32-bit memory for images at runtime, regardless of the original compression format. I believe there is an enhancement task open right now to allow for 24-bit, 16-bit and other color formats.

---
Tags: haxe
---


title: Camera Linecast Bumper Stuttery

text:
# Question
Title: Camera Linecast Bumper Stuttery
I copied a script off the internet and changed it a bit:

```
void LateUpdate()
{
    if (target)
    {
        x += Input.GetAxis("Mouse X") * xSpeed * distance * 0.02f;
        y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;

        y = ClampAngle(y, yMinLimit, yMaxLimit);

        Quaternion rotation = Quaternion.Euler(y, x, 0);

        RaycastHit hit;
        //Over here is probably where the problem occurs
        if (Physics.Linecast(target.position, transform.position, out hit))
        {
            if (!hit.collider.CompareTag("Player"))
            {
                distance = hit.distance;
            }
        }
        else
        {
            distance = 10f;
        }
        Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
        Vector3 position = rotation * negDistance + target.position;

        transform.rotation = rotation;
        transform.position = position;
    }
}

```

I made it so that if the `RaycastHit`'s `collider` is `null`, that the distance would be reset at 10. Whenever the `RaycastHit` is hit, it will move the camera distance closer to the player as to get in front of the object blocking the view. All nice and dandy, but when I run the game, when I get in front of and object, it works as planned but it is very stuttery, I have a hunch it has something to do with the if statement for the linecast but I have no idea how to fix it, I tried changing `LateUpdate` to `FixedUpdate` and to `Update` but it still occurs. I'm still new to unity and c# so forgive me if this was a simple mistake.

Here is a video showing it happening: https://www.youtube.com/watch?v=n6ffVmq1UWs

# Answer
> 3 votes
I am not sure at all about the following.

Instead of Linecasting between the **current** position of the camera and the target, I would linecast between the **desired** position and the target.

```
void LateUpdate()
{
    if (target)
    {
        // Reset to the desired distance
        distance = 10 ;
        // OR the following line if you want smoother reset
        // distance = Mathf.Lerp(distance, 10, Time.deltaTime * 5);

        // Rotate according to mouse position
        x += Input.GetAxis("Mouse X") * xSpeed * distance * 0.02f;
        y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;

        y = ClampAngle(y, yMinLimit, yMaxLimit);

        Quaternion rotation = Quaternion.Euler(y, x, 0);

        // Compute the desired position
        Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
        Vector3 position = rotation * negDistance + target.position;

        RaycastHit hit;

        // Check if there is an obstacle between the desired position
        // and the target
        if (Physics.Linecast(target.position, position, out hit) && !hit.collider.CompareTag("Player"))
        {
            // Obstacle detected !
            // Computing the new position so that
            // the object is on the other side of the obstacle
            distance = hit.distance;
            negDistance = new Vector3(0.0f, 0.0f, -hit.distance);
            position = rotation * negDistance + target.position;
        }

        // Placing the object
        transform.rotation = rotation;
        transform.position = position;
    }
}

```

---
Tags: unity, c#, camera, scripting
---


title: Save game on server side

text:
# Question
Title: Save game on server side
I'm working on a small management game. The player manage his hospital where he can collect items and new characters. Each player can visit others players hospital and gives collected entities.

I would like to save game state on the server side to allow this "multiplayer" part and check data to avoid cheating players.

I'm a little bit curious about the server side. Should I send all the game save file to the server then parse it to check his integrity?

My game will call specific routes to update the amount of data each 30 seconds/1 minutes.

I have made few games by the past but without the network part.

# Answer
> 3 votes
I assume you know how you're going to send the file to the server and how your going to store it...

To check integrity of the file you can do a few things:

**Check the the values in the file are possible**. let's say you save the score/currency in steps of 2 so every time you increase it the smallest amount is 2 and you never add an odd number. If you get a save file which ends in an odd number you have a cheater. You have characters with statistics, let's say that you're saving those stats in the save file because of experience gain or something. If there is a maximum value for each of those stats, check for it. If it's greater than the max for that character you have a cheater.

**Compare the previous save file to the new one** You already have the previous save file in the server, so you can look at the differences in them to try and figure out if the player is suddenly gaining a spike in resources. So it the player had 500 money last save game and 60 seconds have passed and they now have 300,000 money they might be cheating. This will depend on your game but if you can figure out what the maximum change in values are over a given amount of time you can catch people out that way. Just make sure that you keep in mind all possible ways of making money, if microtransactions give people 1,000,000 instantly it is probably going to be faster than the maximum amount you can earn in 30 seconds. you don't want to mark them as cheaters for it. You can apply the same strategy to your character statistics, work out the maximum stat difference and compare save files.

**Include a save game counter**, so every time you update the save game you increase the counter by one. This will essentially mean that every valid save file will be greater than the last and that there shouldn't be any collisions in save file numbers. If the number is the same or lower as the last one, there is a high chance that it is a cheater. Since they will have had to grab or write the save file change it and upload it. If the number is greater than the last time by more than the iteration amount. it could be a cheater but there is also a chance that the save file wasn't uploaded properly the last time they tried. This really depends on how you handle fail cases, if there is a server error do you keep iterating the number or do you skip iteration until the next successful upload.

The above will somewhat try to prevent people who have apps that look at other apps variables in memory and modify them. So when they do you can send a message to the game telling it to reload the last cloud save, putting them in the last known good state.

There are also people who will look at the data that your app is sending and will piece together the full save file from captured packets. For those you should **encrypt your save files**. Put the public key in the app and the private in the server then decrypt all of the save file and check them for integrity. If you couple this with the save game counter you can get good at throwing away bad save files since it will be hard to modify them in the app itself and the server can keep track of good save files.

Before you encrypt your save file you could also generate a hash of the save file. If you **include that hash in the save file** before you upload it you can compare the hashes you get server side after decrypting the save (keep in mind you don't want to include the hash in the server hash otherwise they will never match). If the hashes don't match throw the save away.

If you want to get really fancy you can use the possible value checks to move players from the general population to the cheating population. So that the general population play with people who are probably not cheating.

With all this said keeping cheating at bay is a cat and mouse game, they will figure out how your detecting them and try to work around it. It's inevitable, best you can do is make it as hard as possible for them.

---
Tags: performance, client-server, databases, anti-cheat
---


# Question
Title: Approximating Subdivision Surfaces with Gregory Patches for Hardware Tessellation
I'm trying to implement the approach (http://research.microsoft.com/en-us/um/people/cloop/sga09.pdf). Unfortunately I'm not quite clear regarding the formulas in chapter 3, I am hoping to get some answers.

I am unclear on the following points, did you figure them out?

* what kind of value do I get, when I calculate T(u,v,w) (a point?) and what do I do with the result?
* do I recieve the values u,v,w from the domain shader SV\_DomainLocation or are they calculated?
* are the corner points in chapter 3.2 barycentric too?
* does v get replaced by p0 in figure 5?
* In chapter 3.3 Edge Points there is a formula for e0+, but none for e0-? For which edge is e0+ in figure 5? and how can I calculate e0+ for the other edges? It seems for me (figure 5) there are 5 edges, but just one e0+ is calculated, shouldn't there be 5 e0+?
* Do you maybe have a diagram of the controlpoints in relation to the control mesh? I am having problems seeing the big picture...
* In chapter 3.4: face points, you mention different transversal vectors r, r0+ and r0- but there is only one formula for r0+. Are r = r0+ = r0-? If not, how do I calculate r and r0-?

I am hoping someone could point me in the right direction, thank you in advance!

# Answer
By evaluating T(u,v,w) you will indeed get a point. The patches are designed and optimized for the tessellation stage in modern graphics hardware. In this stage of the pipeline you are supplied with parametric values \[u,v,w\] and these can be used to evaluate a patch. You do not need to calculate these values yourself.

I'm not quite sure what you mean about the corner points being barycentric. In general the corner points **v** are not replaced by **p**. The original mesh is used as a control mesh for which the control points of the parametric patch can be derived.

Indeed, there is only one formula for e0+ but the other e0- can be found by starting at a different edge mid-point and then going around the vertex's outgoing edges. You can look at the answer of this question for more information.

The transversal vector r0- is in the opposite direction from r0+. So, r0+ = -r0-. Thus the face point f0- can be calculated using the same formula but instead using a different sign for r0+.
> 1 votes

---
Tags: shaders, directx11, tessellation
---


# Question
Title: Circular Dependencies in an Entity Component System
I'm developing a top-down shooter in C++ using an entity-component system, and have run into a problem when attempting to refactor powerups. Currently I have a `PowerupSystem` that is essentially a load of `if...else` statements that directly modifies player entity attributes (for example speed).

I'd like to move towards using different powerup classes that inherit from a base `PowerupComponent` class that encapsulate powerup behaviour. An example of this would be `SpeedPowerup`. These derived classes would have a constructor that changes a value in the player entity, and a destructor that sets it back to its original value.

The problem I'm having is that the powerup constructors and destructors need access to the player entity data to make these changes (stored in my `World` class), giving me a circular dependency issue.

The dependency is:

world -\> powerup system -\> powerup -\> world

Any ideas on how I could overcome this issue are appreciated.

Thanks in advance, Rich.

# Answer
> 1 votes
The way I would design this would be based on physics collisions.

I would register the `PowerUpSystem` with the `PhysicsSystem` so that it can be notified about times when game objects collide so that it can handle those collisions.

```
void PowerUpSystem::OnCollisionEvent(const CollisionEvent& event)
{
  Entity* sender = event->GetSender();
  Entity* receiver = event->GetReceiver();

  //! do something here with the two entities.
}

```

I would expect the power-up entity to have some component type that your `PowerUpSystem` would look for and might verify that the player entity is actually the player and not some other entity. You wouldn't want some wandering NPC to be able to greedily acquire a power-up.

At this point, you have a component that knows what attribute to modify in what way and your entity instance. You could simply use delegation here like this:

```
void SpeedUpComponent::ApplyToEntity(Entity* entity)
{
   //! Apply the speed modification to the provided entity.
}

```

What I would do is separate the concept of a power-up and an aura/buff that has been applied so that you can easily track them separately and react accordingly.

So `SpeedUpComponent` applies a `SpeedAuraComponent` that could either then be tracked by the `PowerUpSystem` or by a separate aura/buff system.

---
Tags: c++, entity-system, entity-component
---


title: Calculating NDC Co-ordinates

text:
# Question
Title: Calculating NDC Co-ordinates
How does performing the Perspective divide cause the vertex co-ordinates to be NDC (-1 to 1)?

# Answer
> 2 votes
Perspective division ensures nothing.

Between the Vertex Shader's output and the perspective divide is the clipping step. This removes any triangle that's entirely outside of the clip-space region \[-W, W\], and it actually clips off any parts of a triangle that is outside of that region.

Therefore, after clipping, all triangle vertices lie in the \[-W, W\] region. So when you divide by W, all vertices will lie in the \[-1, 1\] region.

# Answer
> 0 votes
The output of the vertex stage is clips space and the visible geometry must be inside \[-w, w\] after division by w it ends up in \[-1, 1\].

Any geometry outside the NDC box that will no be draw on screen.

It's the job of the view and perspective matrices to make sure the geometry that you want on screen ends up in that clips space.

---
Tags: opengl, graphics
---


title: Same dimension feel no matter what FOV

text:
# Question
Title: Same dimension feel no matter what FOV
Does anyone know a formula, way, ... to make a FPS player feel like an object has the same size on different FOVs (given that it's at the same distance of the player, of course)? I know that this can't be done perfectly, because of the distortion various FOVs cause and the position of the object (near the edges of the FOV = more distortion). Let's ignore these distortions, and aim for a same size feel for objects that are directly in front of the player (so in the exact center of the FOV).

To clarify things a bit further: I want 1 object in my game to have the same scale feel on different FOVs, not my entire game world.

I've tried giving it a percentage of the frustrum height, but that doesn't seem to give me consistent results.

Note: I'm using vertical field of view in my game.

# Answer
If the suggested dolly zoom is not what you are after, you could try this - not sure how well it'll work, though, this is pretty much of the top of my head. Store the initial view frustum height (`h0`) in a variable, and then when it changes (`h1`) compute the scaling factor `s = h1/h0`, and then uniformly scale your target object by `s`.

Now, if the FOV change is extreme, the distortion you mentioned may become a bit too pronounced; you could then experiment with dynamically modifying `s` to compensate - by making `s` larger or smaller; just multiply it with a floating point number that's around 1.0 (slightly higher or lower) and see what works best.

Once you have the values that work (say, `cMin` and `cMax`), you can use linear interpolation for that multiplier. For that, you'll need an interpolation parameter `t` that goes from 0 to 1 (0 will map to `cMin`, and 1 will map to `cMax` \- think of it like a slider of some kind). So, you calculate your compensation factor like this:

```
c = (1-t)*cMin + t*cMax

```

To get `t`, you can use either the FOV angle or the view frustum height. Again, find some minimum value and a maximum value (say, `hMin` and `hMax`), and do:

```
t = (h - hMin) / (hMax - hMin)    // where h is the current value

```

This will produce `0` when `h == hMin` and `1` when `h == hMax`.

Finally, you calculate the scale:

```
sFinal = c * s         // or
sFinal = c * h1/h0

```
> 0 votes

---
Tags: unity, camera, first-person-shooter, frustum
---


# Question
Title: Why do game developers force new players to play a big amount of unranked games before playing ranked?
I have noticed that CS:GO and Overwatch, two very popular competitive games, force you to play a rather big amount of unranked games and gain a certain "level" before you are allowed to play ranked. CS:GO aso limits the amount of ranked games that you can play per day until you have a rank, forcing you to wait even longer. Many other games do the same, but those two are different in the fact that they have a *paywall*, a huge one in case of Overwatch.

This means that for a long time a new player is forced to play in unfair teams (as making the teams fairly balanced is the sole benefit of ranked matches). Not only can one team be just stronger than the other, making the game predetermined and boring not matter which team is our newbie in, but there can also be a couple of very experienced players in each of the otherwise fair teams, and those veterans will really be the ones deciding the outcomes of a battle, making the newbies feel useless (as they will actually be useless in this particular match).

It also means that newbies who want to play seriously are mixed with people who want to play for fun (not to win) and troll.

Unranked matches also have an a bit different balance compared to ranked in CS:GO, which means that our newbie can also learn something that is not applicable in ranked matches.

**What is the benefit of the game if new players are not allowed into ranked matches right away if they want to try them?**

**What is the benefit of making unranked balance even slightly different from ranked?**

# Answer
One benefit of requiring a certain amount of play to get into ranked is that you're certain that anyone playing ranked *already knows the game* to a certain extent.

Heroes of the Storm goes one step further: to play any hero in ranked, you must have advanced that hero to level 5. That means playing roughly 10 games with them. That's not a lot, but it's enough to get the basics of how to play them.

I know that when I hit LoL ranked (which required roughly 350 games at the time), I wasn't fielding questions about "what's a turret" and "what's botlane".
> 4 votes

# Answer
I think this is actually a two-fold approach from what I've gathered.

One reason is to ensure that there is some level of experience and knowledge in the ranked queues. It would be pretty annoying if brand new players were mixed into the ranked queue having little to no idea about how the game is played (both from a mechanics perspective and a meta perspective.

Games like League of Legends also have a nice ramping aspect to the path to the ranked queues. All characters start out in a more 'neutral' play style. The game is a little more forgiving because there are no runes to polarize and amplify hero characteristics. Once you get to rank 30 and have full rune pages, the DPS characters hit much harder and die much quicker while the Tank characters can soak up much more damage. By letting the players grow into these roles as the roles are emphasized by the runes / masteries, it builds a much better experience.

The OTHER side of this is likely as a way to combat cheaters/hackers. This is especially problematic in CS:GO. By making a large time burden on getting into ranked, it acts as both a deterrent and a throttle to keep people from using hacks. The problem of people getting banned and making new accounts now has a monetary penalty (Buying a new copy of the game) as well as a time penalty (playing for days before being allowed back into ranked queues). This is even more of a problem for free games like League of Legends or Fortnite.
> 3 votes

---
Tags: ranking
---


# Question
Title: In track and field dash, determine starting speed from a final time with acceleration
I am developing an athletics game, and working on the mechanics of the 100 meter dash. The player controls an athlete, that during the race has acceleration and a max speed. To win the race, the player has to collect boost tokens, which will increase the max speed.

So when the dash starts, the athlete will accelerate to his max speed, then when the athlete picks up a token, the max speed will increase, and he will accelerate again to the new max speed.

The problem is, I want to set the fastest time possible. In a config file, I want to set the fastest possible 100m dash time to 9.4 seconds.

How do I determine my starting max speed, so that when all tokens are collected, the final time will be 9.4 seconds?

This code is not actual code, but to illustrate the problem, and provide an example with numbers.

```
const acceleration = 6; // meters / seconds^2
const numTokens = 10;
const tokenDistribution = 100 / (numTokens + 1); // one token per 9.1 meters (and not on the finish line)
const tokenIncreaseSpeed = 1; // meters / seconds
const bestTime = 9.4; // seconds

const maxSpeed = ?? // meters / seconds - value so with all tokens the final time is 9.4 seconds...
const speed = 0;
// Pseudo loop code
update(delta) {
    speed += acceleration / delta;
    if (speed > maxSpeed) speed = maxSpeed;
    if (player.collides(token)) {
        maxSpeed += tokenIncreaseSpeed;
    }
    player.y += speed / delta;
    if (player.y > finishLineY) endRace();
    render() etc...
}

```

# Answer
### TL;DR

Starting maxSpeed should be about 6.28171069

### Approach

The naive approach isn't terribly difficult, but it's a bit tedious. I'm using "naive" here to mean "ignoring that the actual time spent prior to getting a boost token will vary based on frame rate", and "we assume runner reaches max speed after each boost, prior to the next boost". If you need better than that, you'll need to go beyond what I do here and add per-frame bookkeeping.

Suppose you think of your track as numTokens+1 sections. Each section has a time to traverse based on the player's acceleration and max speed in that section.

Working from formulas for distance-acceleration explanation (I grabbed them from http://www.dummies.com/education/science/physics/how-to-calculate-time-and-distance-from-acceleration-and-velocity/ ) you can work out how long each section has to take to hit the target time of 9.4, and from that, work out the starting maxSpeed you'd need.

Two formula of interest pulled from the above link:

`t = ( v_f - v_i ) / a` (time to reach a given speed from a start speed with a given acceleration)

and

`s = v_i*t + 0.5*a*t^2` (how much distance was traveled during that acceleration)

and I suppose we can include the equation Stephan mentioned:

`speed = distance/time`

### More Variables, Maestro!

Let's define a few variables of interest, using \_j to denote values related to the jth section of track:

* `startSpeed_j` is the speed we had coming into section j
* `maxSpeed_j` is the `maxSpeed` we can reach in section j, a function of our initial `maxSpeed + numTokens * tokenIncreaseSpeed`
* `accelTime_j` is how long it takes to accelerate to maxSpeed for section j
* `accelDist_j` is the distance traveled during acceleration
* `cruiseDist_j` is how much distance remains in a section after `accelDist_j`
* `cruiseTime_j` is how long we spend at maxSpeed before we reach the next boost
* `totalTime_j` is how long the runner spends in the section
* `overallTime_j` is how long it took the runner to get from the race start to the end of section j

### Computing values

So using the above formulas and variables in a per-section way, we get:

```
accelTime_j = (maxSpeed_j - startSpeed_j) / acceleration
accelDist_j = startSpeed_j * accelTime_j + (1/2) * acceleration * accelTime_j * accelTime_j

```

Then with these, we can figure out how much distance remains after acceleration:

```
cruiseDist_j = tokenDistribution - accelDist_j
cruiseTime_j = cruiseDist_j / maxSpeed_j

```

And from these we can calculate how long the section takes to run (though we need a special case for the first section):

```
totalTime_j = accelTime_j + cruiseTime_j
overallTime_j = overallTime_(j-1) + totalTime_j

```

You *could* flip all this around to solve for the starting maxSpeed value, but unless you need that to be adjustable real-time in your game, I'd probably just solve it by trial and error.

I made a google doc spreadsheet that I used to solve this, which you can find and make a copy of here: https://docs.google.com/spreadsheets/d/1RJQWbbc831Rw\_pWBoU3UHh4OKW13dt0yHDSRQ8eO\_9U/edit?usp=sharing

The sheet supports tweaking of the initial parameters (up to 50 numTokens, above that will you'll have to do some copy-pasting), and has the starting maxSpeed value I found: 6.28171069

Hope this helps!
> 1 votes

# Answer
Speed = Distance/Time

You don't need to care about the acceleration here. Even with instant acceleration, your max speed if you complete 100m in 9.4 seconds is

Speed=100m/9.4s

Speed=10.6382978723 m/s

Divide this by however many tokens you intend to let the player collect to get your token boost value.
> 0 votes

---
Tags: mathematics, game-loop
---


title: SDL_TTF Manual Line Ending

text:
# Question
Title: SDL_TTF Manual Line Ending
With SDL TTF I've already gotten automatic line wrapping down using the built in "wrapped" function.

However, now I want to do what I guess you could call manual line wrapping. Basically, at certain points I want to start a new line.

Specifically, every time there is a open square bracket "\[" I want to do a line ending, and continue the text on a new line. (The equivalent of hitting enter)

Any help would be awesome! (/n doesn't work with SDL TTF as far as I know)

# Answer
> 1 votes
The `\n` is supposed to work in the \_Wrapped() function calls. So just replace the `[` character with a `\n` character.

# Answer
> -1 votes
That did the trick! Thanks!

To restate for future users: Using the "\_Wrapped()" function, '/n' does actually work as you'd expect. But not in the other TTF modes.

---
Tags: c++, sdl, sdl2, ttf
---


title: libgdx Player movment dungeon crawler

text:
# Question
Title: libgdx Player movment dungeon crawler
The player go's throe walls and stops when theres no wall. Code:

```
package input;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.math.GridPoint2;
import com.badlogic.gdx.math.Vector2;

import dungeon.Dungeon;
import player.PlayerCharacter;
import player.Player_state;

public class PlayerInputProcessor {
private PlayerCharacter player;
private Dungeon dungeon;

private final int NORTH = 0, SOUTH = 1, WEST = 2, EAST = 3;

public PlayerInputProcessor(PlayerCharacter player, Dungeon dungeon) {
    this.player = player;
    this.dungeon = dungeon;
}

public void HandleInput() {
    Vector2 pos = player.getVectorPos();

    if(Gdx.input.isKeyPressed(Keys.UP)) {
        if(canmovethere(new GridPoint2( (int) player.getVectorPosX() / player.getWidth(), (int) (player.getVectorPosY() - 3) / player.getHight()), NORTH)) {
            player.setVectorPosY(player.getVectorPosY() + 3);
        }
    }
     if(Gdx.input.isKeyPressed(Keys.DOWN)) {
        if(canmovethere(new GridPoint2( (int) player.getVectorPosX() / player.getWidth(), (int) (player.getVectorPosY() - 3) / player.getHight()), SOUTH)) {
            player.setVectorPosY(player.getVectorPosY() - 3);
            player.setState(Player_state.WALKING_FORWORD);
        }
    }
     if(Gdx.input.isKeyPressed(Keys.RIGHT)) {
         if(canmovethere(new GridPoint2( (int) (player.getVectorPosX() + 3) / player.getWidth(), (int) player.getVectorPosY() / player.getHight()), EAST)) {
            player.setVectorPosX(player.getVectorPosX() + 3);
        }
    }
     if(Gdx.input.isKeyPressed(Keys.LEFT)) {
         if(canmovethere(new GridPoint2( (int) (player.getVectorPosX() - 3) / player.getWidth(), (int) player.getVectorPosY() / player.getHight()), WEST)) {
            player.setVectorPosX(player.getVectorPosX() - 3);
        }
    }

    if(Gdx.input.isKeyJustPressed(Keys.E)) {
        if(player.hasSword()) {
            player.sword = false;
        }
        else player.sword = true;
    }

     player.setGridPos(new GridPoint2((int) player.getVectorPosX() / player.getWidth(),(int) player.getVectorPosY() / player.getHight()));

}
private Boolean canmovethere(GridPoint2 newpos, int die) {
    GridPoint2 nextpos = new GridPoint2();
    GridPoint2 nextpos2 = new GridPoint2();

    if(die == NORTH) {
        nextpos.x = newpos.x;
        nextpos.y = newpos.y + 1;
        nextpos2.x = newpos.x;
        nextpos2.y = newpos.y + 1;
        if(dungeon.getTile(nextpos).isPassable()) {
            return true;
        }
    }
    if(die == SOUTH) {
        nextpos.x = newpos.x;
        nextpos.y = newpos.y;
        nextpos2.x = newpos.x + 1;
        nextpos2.y = newpos.y;
        if(dungeon.getTile(nextpos).isPassable()) {
            return true;
        }
    }
    if(die == EAST) {
        nextpos.x = newpos.x + 1;
        nextpos.y = newpos.y;
        nextpos2.x = newpos.x;
        nextpos2.y = newpos.y + 1;
        if(dungeon.getTile(nextpos).isPassable() && dungeon.getTile(nextpos2).isPassable()) {
            return true;
        }
    }
    if(die == WEST) {
        nextpos.x = newpos.x;
        nextpos.y = newpos.y;
        nextpos2.x = newpos.x;
        nextpos2.y = newpos.y - 1;
        if(dungeon.getTile(nextpos).isPassable()) {
            return true;
        }
    }
    player.setState(Player_state.STANDING);
    return false;
 }
}

```

# Answer
> 0 votes
I feel like your player's location should be based on your underlying data structure. The division you are doing to get the next tile location has me a little worried about what cell you are actually looking at for next tile.

If `Dungeon` is all in integer values for tile locations (which makes sense), you are almost certainly having integer math problems when you are trying to find the next tile. It's hard to tell without the implementation of `Dungeon` included in your question.

If I were you, I would consider flipping your data around and having your player position be solid integers, so you always know exactly what tile your player is supposed to be at, and doing math to figure out where the player should render on screen.

But my gut feeling is that this all boils down to integer math rounding -- I'd be able to update this answer if you post your `Dungeon` code so I can get a better idea of how this is all playing together.

**Edit:**

There are a lot of what look to be copy/paste errors in your `canMoveThere` function.

1) You are setting nextpos2 in all 4 cases, but only using it in the `EAST` case. (Are you sure you only want to move east if both `nextpos` and `nextpos2` are passable?)

2) You are incorrectly setting the coordinates on `nextpos` in most of your situations. \- `NORTH` looks ok \- `SOUTH` is only incrementing the `x` on `newpos2` and not touching `nextpos` \- `EAST` is modifying both `x` and `y`, as well as being the only case that checks `isPassable()` for both `nextpos` and `nextpos2` \- `WEST` is only incrementing `y` on `newpos2` and not touching `nextpos`

The problem is certainly in the logic of `canmovethere`. I believe your function should look more like this:

```
private Boolean canmovethere(GridPoint2 newpos, int die) {
    GridPoint2 nextpos = new GridPoint2();

    if(die == NORTH) {
        nextpos.x = newpos.x;
        nextpos.y = newpos.y + 1;
        if(dungeon.getTile(nextpos).isPassable()) {
            return true;
        }
    }
    if(die == SOUTH) {
        nextpos.x = newpos.x;
        nextpos.y = newpos.y - 1;
        if(dungeon.getTile(nextpos).isPassable()) {
            return true;
        }
    }
    if(die == EAST) {
        nextpos.x = newpos.x + 1;
        nextpos.y = newpos.y;
        if(dungeon.getTile(nextpos).isPassable()) {
            return true;
        }
    }
    if(die == WEST) {
        nextpos.x = newpos.x - 1;
        nextpos.y = newpos.y;
        if(dungeon.getTile(nextpos).isPassable()) {
            return true;
        }
    }
    player.setState(Player_state.STANDING);
    return false;
}

```

I removed `nextpos2` as it was only used in the `EAST` case, and seemed unneeded. If you indeed intended for east to behave differently, just add that back in and make sure you are adjusting the correct values.

**Edit 2:**

There is another copy/paste error in your south logic, it looks like you have a minus where you should have a plus. Note the `- 3` in both the `UP` and `DOWN` call to `canmovethere()`:

```
if(Gdx.input.isKeyPressed(Keys.UP)) {
    if(canmovethere(new GridPoint2( (int) player.getVectorPosX() / player.getWidth(), (int) (player.getVectorPosY() - 3) / player.getHight()), NORTH)) {
        player.setVectorPosY(player.getVectorPosY() + 3);
    }
}
 if(Gdx.input.isKeyPressed(Keys.DOWN)) {
    if(canmovethere(new GridPoint2( (int) player.getVectorPosX() / player.getWidth(), (int) (player.getVectorPosY() - 3) / player.getHight()), SOUTH)) {
        player.setVectorPosY(player.getVectorPosY() - 3);
        player.setState(Player_state.WALKING_FORWORD);
    }
}

```

I think one piece that is contributing to the confusion after looking at this more and more: You seem to be accounting for the direction the player is trying to move twice. Once in the call to `canmovethere()`:

```
if(Gdx.input.isKeyPressed(Keys.UP)) {
    if(canmovethere(new GridPoint2( (int) player.getVectorPosX() / player.getWidth(), (int) (player.getVectorPosY() - 3) / player.getHight()), NORTH)) {
        player.setVectorPosY(player.getVectorPosY() + 3);
    }
}

```

(Noting the `(int) (player.getVectorPosY() - 3)` specifically)

and once inside the `canmovethere()` function:

```
if(die == NORTH) {
        nextpos.x = newpos.x;
        nextpos.y = newpos.y + 1;
        nextpos2.x = newpos.x;
        nextpos2.y = newpos.y + 1;
        if(dungeon.getTile(nextpos).isPassable()) {
            return true;
        }
    }

```

(Where you are again adjusting the y position.)

You should certainly simplify this so that you only adjust the position on one side of the call. Since you currently pass a direction into your `canmovethere` function, you might as well do it there. You can probably reduce your code to look something like this:

```
if(Gdx.input.isKeyPressed(Keys.UP)) {
    if(canmovethere(new GridPoint2( (int) player.getVectorPosX() / player.getWidth(), (int) player.getVectorPosY() / player.getHight()), NORTH)) {
        player.setVectorPosY(player.getVectorPosY() + 3);
    }
}
 if(Gdx.input.isKeyPressed(Keys.DOWN)) {
    if(canmovethere(new GridPoint2( (int) player.getVectorPosX() / player.getWidth(), (int) player.getVectorPosY() / player.getHight()), SOUTH)) {
        player.setVectorPosY(player.getVectorPosY() - 3);
        player.setState(Player_state.WALKING_FORWORD);
    }
}
 if(Gdx.input.isKeyPressed(Keys.RIGHT)) {
     if(canmovethere(new GridPoint2( (int) player.getVectorPosX() / player.getWidth(), (int) player.getVectorPosY() / player.getHight()), EAST)) {
        player.setVectorPosX(player.getVectorPosX() + 3);
    }
}
 if(Gdx.input.isKeyPressed(Keys.LEFT)) {
     if(canmovethere(new GridPoint2( (int) (player.getVectorPosX() / player.getWidth()), (int) (player.getVectorPosY() / player.getHight()), WEST)) {
        player.setVectorPosX(player.getVectorPosX() - 3);
    }
}

```

The arguments for `canmovethere()` should be changed to `canmovethere(GridPoint2 currentPos, int direction)`. You pass in your current position and what direction you are wanting to move, and the function returns true or false if you are able to do that.

Also worth noting is that you are only setting the player state to `WALKING_FORWARD` in your `DOWN` case. Not sure if this is intentional or not.

---
Tags: libgdx, movement
---


# Question
Title: How can I `draw` something on a JavaFX WritableImage?
I'm migrating a project from Swing to JavaFX, and I have a problem. Since `java.awt.BufferedImage` provides `getGraphics` and it has lots of convenient methods (like `drawLine`, `drawImage`, etc.), I have some codes that uses these features.

But in JavaFX' `WritableImage`, I can't find any similar methods.
Did I miss something? Or should I use something else instead of `WritableImage`?

# Answer
You can use `getGraphics` in `BufferedImage` and do all the drawing job in the `BufferedImage`, and use `SwingFXUtils.toFXImage` to convert it into a `WritableImage`.

It's slow, and I have an alternative.

Draw everything on a `Canvas`, and use this:

```
override val screenCut get() =
  JvmImage(SwingFXUtils.fromFXImage(canvas.snapshot(
      SnapshotParameters(), null), null))

```

This will probably help.
> 1 votes

---
Tags: java, javafx
---


title: FillRecatangle set Opacity?

text:
# Question
Title: FillRecatangle set Opacity?
I have a game with a HUD which is drawn by `fillrectangle`.

How would I fade these rectangles when the player is on the HUD?

# Answer
You can start a new thread, create a loop inside, and invoke this every few ms:

```
// decalre a golbal int i
i = (i + 1) % 0xFF
Color color = new Color(i, [your color], [your color], [your color]);
g.setColor(myColour); // graphics context object

```

And you'll see your canvas fading.
> 1 votes

---
Tags: java, swing
---


# Question
Title: How do I balance these numbers in a rock-paper-scissors attack system?
I have three arrays of numbers. If you take a random one from x, it will 'win' more times than a random number from z, which will win more times than a number from y, which will win more times than a number from x.

However, the distribution is not equal.

y beats x 51% of the time, being beaten by x 46% of the time

x beats z 46% of the time, being beaten 42% of the time

z beats y 52% of the time, being beaten 46% of the time

How can I change these to make them approximately equal, winning more than 50% of the time?

Each array must have every number from 0 to 21, add up to the same amount (currently 735) and be of equal length. The closer the probabilities are the better, the higher the better, with as few numbers as possible.

x = \[21,21,21,21,21,21,21,21,21,20,19,18,17,16,15,14,13,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,11,10,9,9,9,9,9,9,9,9,9,8,7,6,6,6,6,6,6,6,6,6,5,4,3,3,3,3,3,3,3,3,3,2,1,0\]

y = \[21,20,19,18,18,18,18,18,18,18,18,18,17,16,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\]

z = \[21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,20,19,18,17,16,15,14,13,12,12,12,12,12,12,12,12,12,11,10,9,8,7,6,5,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,1,0\]

# Answer
You might want to look into the concepts behind non-transitive dice.

Briefly, it's a set of dice such that:

```
P(A beats B) > 50%
P(B beats C) > 50%
P(C beats A) > 50%
etc...

```

As an example, consider these 3 dice:

```
A = { 2, 2, 4, 4, 9, 9 }
B = { 1, 1, 6, 6, 8, 8 }
C = { 3, 3, 5, 5, 7, 7 }

```

Then:

```
5/9 = P(A beats B) = P(B beats C) = P(C beats A)

```

Not all non-transitive dice have equal probabilities like this example set does.
> 3 votes

# Answer
What matters is not the total of all the numbers but the ratio of how many numbers in one set win/lose against ALL the numbers in the other set.

To understand this you need to simplify your set to an extreme example:

`A=[96, 1, 1, 1, 1]` vs `B=[22, 21, 20, 19, 18]`

**Both sets add to a total of 100.**

However it's easy to see how in A vs B, **A will win only 1 time out of 5**.

To balance you need to **compare each number on each set to each number in the other set and count the wins vs losses** and adjust to insure an equal number of win/lose.

For example:

`A=[96, 100, 20, 1, 1]` vs `B=[22, 21, 20, 19, 18]`

A has a total of 218, B has a total of 100, however they will have an equal number of wins when randomly matched.

Table of where A wins with the new set:

```
A B:22, 21, 20, 19, 18
96   W   W   W   W   W
100  W   W   W   W   W
20   L   L   E   W   W
1    L   L   L   L   L
1    L   L   L   L   L

W=Win, E=Even, L=Lose

Wins: 12
Lose: 12
Even: 1

```
> 4 votes

---
Tags: mathematics, probability
---


title: Orthographic Projection viewable area

text:
# Question
Title: Orthographic Projection viewable area
I have a simple orthographic projection that is rotated at an arbitrary angle on any combination of the three axes. I am trying to use these matrices to calculate the viewable area of the screen for clipping purposes.

All of the examples I can find are old, use one game engine or another, mostly deal with perspective projection (and seem more complex than they need to be for orthographic projection), just plain don't work, or I am not understanding the calculations enough to plug in my own values and get the answer I am looking for.

I aim not only to get a functional (and relatively fast) way to achieve my goal, but hopefully understand the why and how in the process.

Does anyone here know how to calculate these values given the projection/view/model matrices?

I work with OpenGL, in C++, using glm for matrix calculations.

**Update #1**

I realize my original post might not be clear enough so I will try and clarify a bit.

Imagine I had an ortho projection like: `glm::ortho(0.0f, 2.0f, 0.0f , 1.0f, -10.0f, 10.0f);`

Given no rotation or other translation of any kind, then the information I am looking for would coincide exactly with the values I put into the ortho. Taking the X axis as an example, I want to know that the first visible X coordinate is 0.0 and the last visible X coordinate is 2.0. If I were to translate this by 0.5 on the X axis, then the values would be 0.5 and 2.5 respectively.

Now if I rotated the view by 90 degrees, then the first visible X would be 0.0 and the last visible X would be 1.0 (obviously depending on the rotation origin), because it can now only display what it can fit on the vertical screen area.

Given any arbitrary rotation, scaling or translation (on any axis) how would I get that information (and the same for Y and Z)?

# Answer
Since perspective division is not performed, it seems you could simply multiply `inverse(projection * view)` by `vec4(±1,±1,±1,1)` (each one of the 8 corners of unit cube) to get 8 corners of the cuboid.

You seem to want AABB (axis-aligned bounding box) of that cuboid. If so, you need to compute component-wise min and max of those transformed 8 points. Those will be the opposite corners of the AABB.
> 1 votes

---
Tags: opengl, c++, 3d, glm
---


title: Substance Painter: Face selection Mask

text:
# Question
Title: Substance Painter: Face selection Mask
Is there a possiblilty to select the polygons of the model that the brush will apply to? This is what happens when I paint the insides of a house.

Inside:

Outside:

As if the absence of WASD Camera controls wasn't bad enough, every brush stroke smears up faces around it. Painting indoor environments is a pain in Substance Painter but I don't see any other program that can do the job.

# Answer
Switch to Quick Masking Mode by pressing T on your keyboard. Then Select the area that you want to mask out. Masked areas will be colored black. Invert the selection by pressing I on your keyboard.

Press T again to apply the mask and begin painting. T will toggle between paint mode and mask mode so you can go back and forth as you need.

Once you're finished press Y on your keyboard and the mask will be removed and lost forever.
> 1 votes

---
Tags: masking
---


# Question
Title: How can I completely hide and protect strings from the player in Unity?
I have been using Unity to create a 2D game which will be completely offline (which is the problem), the game-play needs you to enter certain strings at certain levels and Unity compiles to DLLs, which can be easily reverse engineered, so is there a way to protect those strings (the game is offline so I can't retrieve from other source)?

The game relies heavily on those strings, and yes I'm aware of Obfuscation but I want something more robust. And I know that the easy way out would be doing everything online from a data-source but I was wondering if it's possible.

It can be decompiled like this:

# Answer
> 161 votes
Do not store those strings, store the (cryptographic) hash of them.

A (cryptographic) hash function, like encryption, is a way to turn a string into "gibberish" (called hash), but unlike encryption, you cannot get the original string from this hash (unless you can brute-force it or the hash function is broken). Most (if not all) hash functions takes a string of arbitrary length and returns a string of a constant length (depends on the function).

How do you check that a string that the user has entered is the correct one? Since you cannot get the valid string from the hash, the only thing you can do is to hash the user's guess and compare it to the correct hash.

Warning (by Eric Lippert): DO NOT USE the built in function `GetHashCode` as such a function - its result can differ between different .NET versions and platforms, making your code work only on specific .NET framework versions and platform.

# Answer
> 106 votes
What you are trying to do is both futile and pointless.

It is futile because there is no way to properly hide information which is on the user's machine. Anyone dedicated enough will find it. You can make it harder, but you can never prevent it. If you encrypt it, then you need to store the encryption key and algorithm somewhere. No matter how many layers of encryption you add, the outmost layer will always need to be unencrypted in order for your game to run.

It is also pointless, because we are living in the internet age. When your game becomes just remotely popular, then those passcodes will be posted all over the web.

All you can do is trust the player to not ruin their own game experience by looking up information the game isn't supposed to tell them yet. The vast majority of players will not start reverse-engineering your game anyway. And if the few who have the necessary skills do this, then it's their own fault.

# Answer
> 5 votes
If such a thing is really desired, then instead of hashing, you might consider building the strings from a numeric input value at runtime.

The advantage is that as pointed out by @Philipp, it is somewhat pointless to try and hide codes in the executable if you can expect them being posted on the internet anyway. Hashed or not, the same word found on the internet and entered into the game will give the same hash and will work either way.

Except... *except* if someone else's code *doesn't work* for you. Which you can trivially do -- not 100% tamper-proof but reasonably hard to work around for the average user. Anything as simple as the "Online Elven name generator" will do (can be arbitrarily simple, really doesn't need much of a markov text gen engine, pulling 4-5 syllables from a random list is good enough).

Just generate a somewhat user-specific or machine-specific number, it doesn't even have to be perfectly unique or very tamper-resistant. Something that is likely different for most people, and unlikely to change regularly, e.g. the computer's network name, the MAC address, or the GUID of the system disk drive, whatever (the GPU serial number might be a *very bad* idea since users are likely to upgrade GPUs). Add to that the numeric code the unlock code refers to, and feed that into your word generator. But be prepared to answer support queries when players use two computers or change their network card (which is unusual, but not impossible). It might be a good plan to only generate the random ID once, and store it with the game's settings. That way, at least it doesn't break existing installations on the same machine if something changes.

Or, you might just use the game's serial number which is unique and will work if the user changes hardware (ironically, however, this might promote pirating since shared unlock codes work for pirated serials but not for legitimate customers!).

Note that preventing users from cheating is not necessarily a good thing. In an offline (i.e. non-competetive game) it's usually no problem if the user cheats and gets the codes from *somewhere* rather than from playing. He is only cheating himself. Who cares.
On the other hand, getting too much in their way if they really wish to cheat is a great opportunity for *completely pissing off* paying customers.

So... before you do something that way, think very thoroughly whether you really want that, and what you want. Quite possibly, having human readable strings (or trivially made "unreadable" with xor) is just good enough and indeed preferrable.

# Answer
> 3 votes
If you don't need to show the strings, then the hashing idea is probably the way to go. If, on the other hand, you do need to show them to the user, there are some other ways you could avoid them showing up in your DLL directly.

One way to deal with this besides encrypting or otherwise obfuscating the strings is to break them up. Maybe just a have an alphabetically sorted dictionary of all the possible words from all the strings in the game. Then have an array somewhere that allows you to piece together the words into the string you need by indexing into the array of words. This way you don't have the complete strings anywhere in the game. There's no master key needed to decrypt the strings. And the data that tells their order could be all over your source, if, for example, each function that used a string just had an array of indexes local to the function. I'm not sure how practical that is in your specific case, but it's one way of doing it.

You might even have string composed of a few words, but they end up put in different orders. For example, you might need the following 2 strings:

1. A bear walked through my house
2. My house protected me from a bear

Your list of phrases would contain both "a bear" and "my house", but you'd have a large list of other phrases that could be put in between them, so figuring out which one would be just as hard as actually figuring out the puzzle in the game (or whatever). For example, the action phrases could be "walked through", "burnt down", "pushed over", "protected me from", "separated me from", "magically produced", etc.

You could work this into your game by making the indexes be based on something the player has collected or done. So there'd be no master list of indexes anywhere inside the game. They would be generated by the player playing the game.

---
Tags: unity, c#, anti-cheat
---


title: Unity Level Lock/Unlock Problem

text:
# Question
Title: Unity Level Lock/Unlock Problem
I am working on Unity 2D game. I used **PlayerPrefs** to save the level of the scene. As I go from one level to the next, the levels become unlocked and it works fine. But, after unlocking a few levels, when I go back to the lowest level, **all** the levels above become locked. What is the problem in my code?

Here is the `LevelSelector` class:

```
public class LevelSelector : MonoBehaviour {

public void Update ()

  {
    {
        int myLevel = PlayerPrefs.GetInt ("LevelPassed",1);

        for (int level = 0; level < myLevel; level++)
        {
        levelButtons[level].interactable = true;
        }
     }
   }
}

```

Here is the `Score` script:

```
public class Score : MonoBehaviour {

    void Update ()
    {

        UpdateScore ();

    }

    public void UpdateScore ()
    {

        if (sceneOne.isLoaded && meshLevel != null) {

            zLevel = 1;
            meshLevel.text = "Level  " + zLevel;
            PlayerPrefs.SetInt ("LevelPassed", 1);
        }

        else if (sceneTwo.isLoaded && meshLevel != null) {

            zLevel = 2;
            meshLevel.text = "Level  " + zLevel;
            PlayerPrefs.SetInt ("LevelPassed", 2);
        }

        else if (sceneThree.isLoaded && meshLevel != null) {

            zLevel = 3;
            meshLevel.text = "Level  " + zLevel;
            PlayerPrefs.SetInt ("LevelPassed", 3);
        }

        else if (sceneFour.isLoaded && meshLevel != null) {

            zLevel = 4;
            meshLevel.text = "Level  " + zLevel;
            PlayerPrefs.SetInt ("LevelPassed", 4);

        }
    }
}

```

# Answer
> 3 votes
Since this looks like more of a Code Review question, I'll answer it like one. Please note that I'm writing all of this to offer help and constructive criticism.

First of all, you're checking what levels are available inside the `Update()` function, that means that your game is checking whether the levels are available *at every frame*, which is most likely at least 30 times per second.

You could fix this by using the code inside `Start()` or `Awake()`, depending on the situation, instead of `Update()`.

Secondly, you're updating score at every frame too. There should be no need for this. You should only ever call that update score when the score changes. (i.e. you earn points, you call `UpdateScore()` method).

Also, in case of an `if` call, if you're using the same check at every single one, you should really consolidate them into one and anything you do in every single `if` call can also be consolidated into one, like so:

```
public void UpdateScore ()
{

  if(meshLevel != null){

    if (sceneOne.isLoaded) {
        zLevel = 1;
    }
    else if (sceneTwo.isLoaded) {
        zLevel = 2;
    }
    else if (sceneThree.isLoaded) {
        zLevel = 3;
    }
    else if (sceneFour.isLoaded) {
        zLevel = 4;

    }
    meshLevel.text = "Level  " + zLevel;
    PlayerPrefs.SetInt ("LevelPassed", zLevel);
  }
}

```

Now, let's get to the meat of the question.

Inside `UpdateScore()` you're setting the "LevelPassed" integer to whatever the level you are in. That means, if you replay any previous level, the "LevelPassed" integer will be set to that same level instead of the latest passed level.

You could fix that by writing a check to see whether the maximum passed level is lower than the level you're on, like this:

```
public void UpdateScore ()
{

  if(meshLevel != null){

    if (sceneOne.isLoaded) {
        zLevel = 1;
    }
    else if (sceneTwo.isLoaded) {
        zLevel = 2;
    }
    else if (sceneThree.isLoaded) {
        zLevel = 3;
    }
    else if (sceneFour.isLoaded) {
        zLevel = 4;

    }
    meshLevel.text = "Level  " + zLevel;
    int maxLevelPassed = PlayerPrefs.GetInt ("LevelPassed", 1); //leaving 1 here since the minimum level to be passed is 1
    if( maxLevelPassed < zLevel )
    {
        PlayerPrefs.SetInt ("LevelPassed", zLevel);
    }
  }
}

```

This will ensure you are on a level you have not passed before and it should fix your problem. If it doesn't, then you have something else that interferes with the locks but you haven't posted it here.

# Answer
> 0 votes
You need to check if the value stored in LevelPassed is already higher than the current value. As is, you're resetting the value each time, even if LevelPassed is already 4.

---
Tags: unity, 2d, single-player
---


title: Box2D Check If Point Intersects a Body

text:
# Question
Title: Box2D Check If Point Intersects a Body
Is there a way to check if a point is intersecting a body?

For example, lets say there's a body in the world at a position of (100,100).

Is there a way to check if a point at (100,100) intersects that body?

Another example is related to a game called "PHUN". In PHUN you can click and drag bodies around. How would you check if a mouse point is intersecting a body?

# Answer
As with colin's answer, b2World.Query() is a useful function, if you set the aabb to cover only a single point then you can get a list of objects that *may* overlap that point. However, due to speed concerns it only checks the bounding box (AABB) for an overlap which is not always entirely accurate.

To check a fixture (shape, in older versions) accurately, use the b2Fixture.TestPoint() function. As a body can have multiple fixtures, you may need to loop through the entire list to be sure. Combining those 2 functions should allow you to recreate the functionality of Phun, if you like.
> 5 votes

# Answer
If you have a point you *know* is inside the shape then you can intersect the line joining the mouse location to that point with the boundary of the shape. If there are an odd number of intersections then the point is inside. If there are an even number of intersections then the point is outside.

<sub>(source: co.uk)</sub>

The green dots are the mouse locations, the red is the know point inside the shape.

There are edge cases - if the line joining the points coincides with an edge, for example - but this should get you 90% of the way there.
> 2 votes

# Answer
Take a look at `b2QueryCallback` for finding what fixtures contain a point and use `b2MouseJoint` for having objects follow a mouse. I have some sample code, but no time to simplify it for you right now. If you need it, I can provide it later.
> 2 votes

# Answer
I know this question is old but I feel like its missing a simple, code-based answer. So here it is:

```
    /// <summary>
    /// Return if a given position is inside the physical body.
    /// </summary>
    /// <param name="body">Body to test.</param>
    /// <param name="position">Position to check if inside the body.</param>
    /// <returns>If given point is inside the physical body.</returns>
    public bool TestPointCollision(FarseerPhysics.Dynamics.Body body, Vector2 position)
    {
        // get body transformation
        FarseerPhysics.Common.Transform trans;
        body.GetTransform(out trans);

        // iterate fixtures to see if any of them hit the point
        foreach (var fix in body.FixtureList)
        {
            if (fix.Shape.TestPoint(ref trans, ref position))
                return true;
        }

        // if there are no hits, return false
        return false;
    }

```

Note that this is not plain Box2D but Farseer (and in C#), but it should have the exact same API.
> 1 votes

---
Tags: 2d, physics, box2d
---


# Question
Title: How do you calculate a sprite's localScale to resize the sprite to a defined height?
I'd like to uniformly scale a Sprite in Unity, so that its height on the screen matches the height of a button on a canvas. The scene setup looks like:

* Canvas with a `CanvasScaler` and a reference resolution of 800x1280 pixels.
* A button on the canvas with a height of 90 pixels.
* A sprite with a texture size of 250x250 pixels.
* The sprite's pixels per unit setting is set 100.
* An orthographic camera with a size of 5.
* The `transform.scale` values of all involved components are (1,1,1).

Now the question is, how do you calculate the sprite's `localScale` value so that it appears with the same height (90 pixels) as the button? What's the math behind it?

# Answer
Here's a script that performs the matching, with each step of the math called out:

```
using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(SpriteRenderer))]
public class SpriteScaler : MonoBehaviour {

    public CanvasScaler matchCanvas;
    public float pixelHeightOnCanvas = 90f;
    SpriteRenderer _sprite;

    private void Start() {
        _sprite = GetComponent<SpriteRenderer>();
    }

    void Update () {
        // You might not need to call this every Update,
        // just when something changes size/configuration.
        UpdateScale();
    }

    void UpdateScale() {
        // The canvas will try to scale its reference resolution
        // to match the screen's dimensions in either x or y.
        // (Assuming it's in Overlay mode or using a fullscreen camera
        // - if rendering to a smaller rect, use that pixel rect instead)
        Vector2 scaleFactorRange = new Vector2(
            Screen.width / matchCanvas.referenceResolution.x,
            Screen.height / matchCanvas.referenceResolution.y);

        // When the screen's aspect ratio isn't the same as the reference,
        // the canvas picks between two scale factors with matchWidthOrHeight
        float scaleFactor = Mathf.Lerp(
            scaleFactorRange.x,
            scaleFactorRange.y,
            matchCanvas.matchWidthOrHeight);

        // We can now compute how much it will scale our in-canvas
        // dimensions to produce on-screen pixel dimensions.
        float heightInScreenPixels = pixelHeightOnCanvas * scaleFactor;

        // For the next part, we need to know what camera we're
        // being rendered by - consider caching this if it's constant.
        Camera cam = Camera.main;

        // We'll convert the screen height into a fraction of the camera's
        // vertical span (which might be less than the screen's if rendering
        // to a smaller viewport rect).
        float heightAsViewFraction = heightInScreenPixels / cam.pixelRect.height;

        // Now we can convert that to a desired world height by multiplying
        // by the camera's vertical size - note that orthographicSize is
        // only half the height of the camera's view, hence the 2x.
        float heightInWorldUnits = 2f * cam.orthographicSize * heightAsViewFraction;

        // Lastly, we need to know how big "this" sprite is at scale = 1.
        float nativeWorldHeight = _sprite.sprite.rect.height / _sprite.sprite.pixelsPerUnit;

        // And our scale factor is the multiplier that gets us from our
        // native world size to the desired world size.
        transform.localScale = Vector3.one * heightInWorldUnits / nativeWorldHeight;
    }
}

```

Because a "90px" button might actually appear smaller if its texture includes a border, in this example I dropped my `pixelHeightOnCanvas` value to 88.
> 1 votes

# Answer
I do not think you need any calculation.

Select the canvas and in the inspector you should match the pixels per unity unit.

The same in the texture inspector

2 test examples
> 0 votes

---
Tags: unity, sprites
---