# Question
Title: Why isn't my BoxCollider2D doing anything?
I'm trying to make a speech bubble appear when you approach the tutorial board.

The bubble is there and it has its animation states "Appear" and "Disappear"

> Appear is called OnTriggerEnter2D
>
> Disappear is called OnTriggerExit2D

The collider is on the parent, tutorial board

The animator and script are on the bubble itself.

**This is the script I have attached to the bubble, the conditions script.**

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

 public class Conditions : MonoBehaviour
 {

     private Animator bubblecondition;
     private BoxCollider2D boxCollider;

     // Start is called before the first frame update
     private void Awake()
     {
         bubblecondition = this.GetComponent<Animator>();
         bubblecondition.Play("Disappear", 0, 1f);
     }
     void Start()
     {
         //bubblecondition.SetBool("Here", false);
         boxCollider = this.GetComponentInParent<BoxCollider2D>();
     }

     // Update is called once per frame
     void Update()
     {

     }

     public void OnTriggerEnter2D(Collider2D other)
     {
         if (other.tag == "Player")
         {
             bubblecondition.Play("Appear", 0, 0f);
         }
         else
         {
             return;
         }
     }

     public void OnTriggerExit2D(Collider2D other)
     {
         if (other.tag == "Player")
         {
             bubblecondition.Play("Disappear", 0, 0f);
         }
         else
         {
             return;
         }
     }
 }

```

What am I doing wrong? I spent an hour trying to know why.

> I even tried to have the console write a message on collision but it's just dead. Not only that, but I also tried to make it public and referenced it, still nothing.

Help me see my mistake :)

# Answer
> 0 votes
## **SOLVED**

I simply put the conditions script on the board itself and referenced the collider as private BoxCollider2D directly. This fixed it oddly. Don't know exactly why that was happening.

---
Tags: unity, c#, 2d, collision-detection
---


# Question
Title: Generating noise heightmap in C# Console
I want to generate a heightmap for a 2D world (top-down, not a side-scroller), I've followed a guide that worked fine in Unity but in my current project which is a C# console application it doesn't work cause there the method Mathf.PerlinNoise doesn't exist. Is there a way I can translate this method into something that works using normal math or is there another relatively simple solution to generating a noise map that doesn't take advantage of that method?

# Answer
FastNoise had a simple implementation that seems to do the trick!
> 0 votes

---
Tags: c#, perlin-noise, heightmap, noise, simplex-noise
---


title: Implementing moving animation

text:
# Question
Title: Implementing moving animation
I faced the problem of attaching animation to the enemy. In the Animator window I added a "moveSpeed" (float) condition, so moving animation should turn on when moveSpeed is greater than 0.001. But after prescribing a reference to an Animator in the code, whatever I write further, a message pops up about the presence of compiler errors. Here's my script:

```
public int health;
public GameObject explosion;

public float playerRange;

public Rigidbody2D theRB;
public float moveSpeed;

public Animator anim;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

    if(Vector3.Distance(transform.position, PlayerController.instance.transform.position) < playerRange)
    {
        Vector3 playerDirection = PlayerController.instance.transform.position - transform.position;

        theRB.velocity = playerDirection.normalized * moveSpeed;

    }
    anim.SetFloat("moveSpeed") = theRB.velocity;
}

public void TakeDamage()
{
    health--;
    if(health <= 0)
    {
        Destroy(gameObject);
        Instantiate(explosion, transform.position, transform.rotation);
    }
}

```

What exactly do I need to write for the condition to work and the animation to play? Thanks for any help!

# Answer
> error CS1501: No overload for method 'SetFloat' takes '1' argument"

This tells you you're using the `SetFloat()` method incorrectly, so you should consult the documentation for how to use it correctly.

Here you'll see that the value to set needs to be passed as the second argument to the function, not as an assignment after the function call (you cannot assign something to a function call's result in C#)

So instead of writing invalid code like this:

```
anim.SetFloat("moveSpeed") = theRB.velocity

```

You would write:

```
anim.SetFloat("moveSpeed", theRB.velocity.magnitude);

```

Here I've used the `.magnitude` getter to transform the `Vector3` velocity into its scalar length, a speed.
> 1 votes

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


# Question
Title: How could I prevent a player from cheating by taking a picture with their phone?
I'm making a game with a primary mechanic of a very limited amount of time that you can see a maze, and must navigate it blindly as much as possible to conserve your torch fuel. It's possible you could snap a photo with your phone and then beat every level.

My initial thought is, "so what?" if someone wants to cheat, they are just taking the fun out for themselves. But I'd like to add a leaderboard to the game, which would make cheating even more enticing to some players who value bragging rights over having fun.

The obvious answer is that there is NO way to prevent this.... but is there? I am trying to find an out-of-the-box idea that renders cheating nearly impossible or pointless. Any ideas? Curious if anyone has any thoughts first without altering your perspective by playing my game first. Let me know if you want the link and I'll give it to you. Thanks!

# Answer
> 37 votes
Obvious answer, there's no way to prevent this. If they can see it with their eyes, they can see it with their phone. However, here's two strategies mitigating this:

1. Don't show the entire maze at once. Scroll the maze, show it only in segments, etc. This will prevent a single picture from capturing the entire maze, however, it won't prevent video and does make it more difficult to solve.
2. Utilize other strategies to convey the maze information. For example, "reveal" the solution to the maze in the form of verbal instructions "Right, second left, straight, etc.". Again, this can make things more difficult, but would prevent an image (but again, not video).

Essentially, don't give them everything at once and give it to them in different ways. This will help make cheating harder, but it won't be impossible.

# Answer
> 28 votes
## Embrace cheating and modify your mechanics

**Cheaters gonna cheat** \- you can't avoid that, and lots of other answers here cover that in enough detail. But, you can certainly edit the mechanics of your game to make the obvious cheating routes like taking a screenshot simply pointless. You don't want your cheat routes to be so easy that a majority of players do it.

Similarly, you don't want to do things that prevent screen recording or screenshots because then streamers and influencers can't play your game.

In this case, rather than flashing the complete overview of the maze on screen, you'd instead have the character enter the maze with a torn or damaged map which can be viewed at any point. There's no indication of where you are currently, so the memory challenge simply shifts from remembering *what you saw* to remembering *where you are*.

Difficulty can also be indroduced by having a sliding scale of the amount of damage to the map, as people would have to remember damaged sections of the map only via travelling through them. Maybe the player can draw on the map to fill in the blanks (but only the blanks, if you wouldn't want them keeping track of where they are via drawing a path on it).

Alternatively maybe map sections can be collected within the maze, introducing some strategic gameplay options - is it worth just trying to go through the maze and get lucky, or invest some time in repairing the map first by finding pieces/ completing mini side-quests to unlock them etc.

# Answer
> 11 votes
# Option 1: Occupy their hands

This might be a bit left-field, but what if you forced the user to keep their hands on the keyboard the entire time?

For example, you could give them a task like typing the letters that appear on the screen, or using `W``A``S``D` and `I``J``K``L` to keep their character balanced.

Anything that keeps their hands busy will make it more difficult to take a photo with their phone.

Cheating would still be possible with enough technology, or the help of a friend, but at least it would be harder.

# Option 2: Make them play the game on their phone

They can't take a picture of their phone with their phone! (Unless they set up some mirrors.)

# Option 3: Make them submit a video if they want to appear on the scoreboard

A bit like competitive gaming or speedrunning, require the player to submit a video of them playing the game. Of course this will require a second device. You might not be able to completely control the environment, but you might be able to weed out some of the cheaters this way.

# Answer
> 6 votes
This is just me brainstorming, but what if:

you split the map in stripes, and only show the first stripe a very short amount of time. Then you blank that stripe out and show the next one, blank the next one and so on. If you switch stripes fast enough, you will see the whole map when you look at it, but if you take a still picture, you will only see a part of it.

Or maybe you can do it with an overlay with a slit in it, that scans across the map fast enough. I'm thinking along the lines of a cathode ray tube monitor that only projects one line at a time but does it so fast that you see the whole picture.

The speed and width of the part of the map you are showing must be optimized so that a regular camera can't capture the whole picture in one shot, but still allows the player to view it. Of course, this wouldn't prevent anyone from filming the map either.

# Answer
> 5 votes
# Take advantage of dynamic range.

Human senses are much better than cameras at paying attention to small variations to light intensity in the presence of large variations nearby. With a camera, any large variations in the shot squash the detail in regions where variations are small.

For best results, you should pepper the image with white or black spots, as it makes sure they end up in the shot.

Compare the original image:

And the photo I took with my phone:

Much of it has disappeared!

This isn't too reliable, it depends on the camera and on lighting (and the user may find the original image difficult to see on certain screen displays) but it could be one component of a broader strategy...

# Answer
> 4 votes
Maybe base the leaderboard score on actual real life time spent rather than In-Game time spent. Taking a picture and then viewing the picture would slow you down considerably, hurting your score.

Alternatively, any kind of pause could disqualify you from leaderboards but still record local high scores.

# Answer
> 3 votes
You can do something similar to LED Multiplexing. Here's a snippet from the Wikipedia article:

> **Multiplexed** displays are electronic display devices where the entire display is not driven at one time.
>
> Instead, sub-units of the display (typically, rows or columns for a dot matrix display or individual characters for a character oriented display, occasionally individual display elements) are multiplexed, that is, driven one at a time, but the electronics and the persistence of vision combine to make the viewer believe the entire display is continuously active."

If the user is presented with a picture of a maze, you could show only one portion at a time - but do so rapidly so that our "persistence of vision" can see the maze as a whole. Cameras do not have this persistence of vision, and so a snapshot would only see the portion of the maze visible at the time. Sort of like being in a room with a strobe light. Even video would look extremely buggy, and you could probably sneak in some incorrect portions that would be invisible to the naked eye.

# Answer
> 2 votes
Give points based on how long the user looks at the maze AND how long it takes them to solve it without a picture.

If people want to cheat, they will. Make sure it's worth your time to actually fix the problem. Don't solve problems that are not out there.

# Answer
> 2 votes
For the player to see the maze picture, make them hold down two keys on the opposite side of the keyboard at the same time. That way, they will need to use both hands and may not be able to easily take a picture.

# Answer
> 2 votes
## Allow them to replay the levels to get better speeds

If they can replay the levels to get a better speed, then what is the difference between memorizing the level by playing it over and over and taking a photo? Don't punish them for number of tries. Eventually, the best times will simply be based on what path they take rather than their ability to memorize. In that case, their "cheating" will not have gained them anything as far as leaderboards are concerned.

# Answer
> 1 votes
You could just determine when a user captures a screenshot. When they do, invalidate that maze and give them another.

https://www.hackingwithswift.com/example-code/uikit/how-to-detect-when-the-user-takes-a-screenshot

# Answer
> 1 votes
There are a lot of good ideas on how the gameplay can be changed in such a way that it will lessen the advantage a cheater has, but at the end of the day it's more or less impossible to prevent cheating completely, so the question becomes how to handle that given the wish for a global leaderboard.

# Personal leaderboard or a leaderboard for friends only

First of all I just have to mention that maybe the best idea is to ditch the idea of a global leaderboard. As much fun as those can be with a healthy community, they end up with a lot of issue. Even in something as innocent as a bridge building game you end up with people using bugs in the physics engine to take the top spots thus ruining the fun for normal players.

An easy way to 'fix' this is to only put friends on the leaderboard, because that way at least the large large majority of players won't encounter cheaters and the leaderboard will still be a meaningful goal.

# Normal and tool assisted leaderboard

Only applies if cheating **is fun**

Players are surprisingly honest *typically*. I have once seen a game which literally asked 'Did you cheat? Just be honest, we wont punish you.' at the end and if you said 'Yes' it put you on a different leaderboard. In that case the 'cheating' was playing with two players which the rules prohibited explicitly, but I could totally see a situation where people who 'cheat' will be competing on a tool assisted leaderboard and people who don't cheat will compete on the normal leaderboard.

# Time constrained leaderboard

Only applies if cheating **is not fun**

Lastly it's useful to note that typically repeated cheating is not fun, as it often makes it trivial to win. This thus means that repeatedly wiping the the leaderboard (e.g. by having a daily leaderboard only) makes both the reward for and damage from cheating minimal.

# Answer
> 1 votes
Optical Illusion? So what people see in 1 second isn't what they see when they've got 20 seconds to study it? The factually incorrect map will be remembered in the correct way. This would work especially well if it's a grid pattern.

# Answer
> 1 votes
Show the leaderboard as a histogram, and show the player's position in it as a percentile rather than absolute ranking. There will likely be two very distinct curves, and players can be satisfied that they are on the better end of the non-cheater curve. You may still get players who cheat but intentionally slow themselves to the upper end of the non-cheater range, but this will likely be infrequent.

# Answer
> 0 votes
If you generate the levels dynamically, so that each player gets a new maze, sharing pictures and video will be pointless.

Then again, this will mean no two runs are similar and the position depends on luck to a certain extent.

# Answer
> 0 votes
As previously pointed out you can not 100% prevent it. One option I would like to bring up is playing with the contrast of your maze's preview.

Generally taking a picture of a monitor results in a not so high quality picture. the phone's camera won't be able to cope with low contrast and dark areas as well as the human eyes can. So making your preview happen in a low contrast/dark environment will at least hinder the photo-takers in some way as it will be hard to make out the contours of your alleyways.

This won't however stop the user from taking a screenshot, but depending on what you're making this game in screenshots can be disabled (although such disabling can be circumvented as well).

Another downside would be that lowering contrast may also keep people with visual impairments from playing your game.

As pointed out by others not showing the maze in one go would stop pictures, but not videos. One way to make it harder on the video takers would be to randomize the order in which you show the maze's segments. However randomizing that order would also make it much harder for your casual players!

# Answer
> 0 votes
Disable screenshots. This will cover most cases.

Disable screenshots in Android.

Disable screenshots in iOS (sorta).

This does not sound like an easy solution, so I would recommend taking the ¯\\\_(ツ)\_/¯ approach as suggested by others. But it is an option.

---
Tags: puzzle, anti-cheat
---


# Question
Title: Unity: Game objects in scene load incrementally and not at the same time
I am using Unity in my Android app. When the app opens, I show the user data in the Unity scene. User data contains texts and images.

In order to load this data in the scene, I make a lot of `UnityPlayer.UnitySendMessage(GameObject,Function,Params)` calls to many `C#` scripts in Unity from Android. Each of these calls performs a specific task like loading an image, creating a text, applying the text font etc.

Problem is that the loading of this data right now looks incremental (if that's the right word). So the text is visible first and after a fraction of a second the image shows. Some text effects show later. This looks ugly.

How can I make all the UI elements load at the same time even if it takes some time? Is there a way to freeze the scene before each game object is ready to be drawn?

# Answer
> 1 votes
You can use this to wait until something happens:

https://docs.unity3d.com/ScriptReference/WaitUntil.html

Or you can set up a load scene, where you load up and store stuff, than show it in the next scene when is is ready, or when the player presses a button:

https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.LoadSceneAsync.html

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


# Question
Title: How do you repeat 2D tiles in Java code when you go out of range?
I am looking up tutorials on how to make 2D games, and I can just copy and paste their code but I would rather know what it means and how to do it.

Suppose you have a 2D game window that has a map width of 64, how do you actually repeat the tiles when you go out of range when scrolling?

In this render method what line of code is actually allowing the game to repeat the tiles when you go out of range?

From the below code this line stands out to me:

```
int tileIndex = (xTile &(MAP_WIDTH_MASK)) + (yTile &(MAP_WIDTH_MASK))* MAP_WIDTH;

```

As this line gives you the X and Y coordinates of which tile you are on, it seems like the bitwise & operator is repeating the tiles, please correct me if I am wrong and also explain to me what the & operator is doing?

Code Example:

<pre><code> public static final int MAP_WIDTH= 64;
 public static final int MAP_WIDTH_MASK= MAP_WIDTH - 1;
 public static final int PIXEL_SIZE= 8;
 public static final int PIXEL_SIZE_MASK= MAP_WIDTH - 1;
 public int[] tiles = new int[MAP_WIDTH*MAP_WIDTH];
 public int[] colours = new int[MAP_WIDTH*MAP_WIDTH*4];
 public int xOffset = 0;
 public int yOffset = 0;

 public void render(int[] pixels, int offset, int row) {
        for(int yTile = (0 + yOffset) >> 3; yTile<=(height + yOffset) >> 3; yTile++) {
            int yMin = (yTile * PIXEL_SIZE) - yOffset;
            int yMax = yMin + PIXEL_SIZE;
            if (yMin<0) yMin=0;
            if (yMax>height) yMax = height;
            for(int xTile = (0 + xOffset) >> 3; xTile<=(width + xOffset) >> 3; xTile++) {
                int xMin = (xTile * PIXEL_SIZE) - xOffset;
                int xMax = xMin + PIXEL_SIZE;
                if(xMin<0) xMin=0;
                if (xMax>width) xMax = width;
                int tileIndex = (xTile &(MAP_WIDTH_MASK)) + (yTile &(MAP_WIDTH_MASK))* MAP_WIDTH;
                for (int y = yMin; y < yMax; y++){
                    int sheetPixel = ((y + yOffset) & PIXEL_SIZE_MASK)*sheet.width + ((xMin + xOffset)& PIXEL_SIZE_MASK);
                    int tilePixel = offset + xMin + y * row;
                    for(int x = xMin; x< xMax; x++) {
                        int colour = tileIndex * 4 + sheet.pixels[sheetPixel++];
                        pixels[tilePixel++] = colours[colour];
                    }
                }
            }
        }
```
</code></pre>

# Answer
If you have a grid that is `xSize` x `ySize` in size and it is stored in a one-dimensional array, then a way of finding the index in that array for a given (`x`, `y`) coordinate is:

```
int index = x + y * xSize;

```

Each increment to the `y`-axis advances the index by the entire width of the grid, and each increment to the `x-axis` increments along that row.

In your example this is basically what happens if we remove the `& (MAP_WIDTH_MASK)` :

```
int tileIndex = (xTile) + (yTile)* MAP_WIDTH;

```

The reason your example is applying the bit-wise and-operator, `&`, is to wrap around the coordinates.

Since a `x`-coordinate greater than the width of the grid has no meaning, your code uses the `&` to clamp the `x`-coordinate to the range \[`x`\- `MAP_WIDTH`\] since it effectively removes the part of the number that is greater than `MAP_WIDTH`

With the `MAP_WIDTH` set to *64* the `MAP_WIDTH_MASK` is *63*, or in binary

```
0000 0000 0011 1111

```

By applying a bit-wise and between that mask and any number, you're zeroing all the bits of the number that isn't matched by a one in the mask.

So the answer is the `&` operator is used to wrap the coordinates, and it does this by removing/zeroing the part of the number that is greater than the width.
> 1 votes

---
Tags: java, 2d, tilemap
---


title: Debug in OpenGL & GLFW (version >= 4.3)

text:
# Question
Title: Debug in OpenGL & GLFW (version >= 4.3)
I try enable debug system in OpenGL with helps debug output in OpenGL version \>= 4.3. My code:

```
void GLAPIENTRY glDebugOutput(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam)
{

}

int main()
{
    glfwInit();
    GLFWwindow* window = glfwCreateWindow(800, 600, "TestGL", nullptr, nullptr);
    glfwMakeContextCurrent(window);
    glfwSetKeyCallback(window, key_callback);
    glewExperimental = GL_TRUE;
    glewInit();
    int width, height;
    glfwGetFramebufferSize(window, &width, &height);
    glViewport(0, 0, width, height);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 4);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    std::cout << glGetString(GL_VERSION) << std::endl;
#if defined(DEBUG) | defined(_DEBUG)
    glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
    GLint flags;
    glGetIntegerv(GL_CONTEXT_FLAGS, &flags);
    if (flags & GL_CONTEXT_FLAG_DEBUG_BIT)
    {
        glEnable(GL_DEBUG_OUTPUT);
        glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
        glDebugMessageCallback(glDebugOutput, nullptr);
        glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE);
    }
    else
        std::cout << "Debug for OpenGL not supported by your system!" << std::endl;
#endif

   ...... // etc
}

```

My output from console:

```
4.5.0 - Build 24.20.100.6286
Debug for OpenGL not supported by your system!

```

I don’t understand why the debugging tools do not work, because the OpenGL version matches the necessary one. Thanks.

# Answer
You create a window with default hints and context. See glfw documentation.

Solution: first give the hints, then create the window.

```
 glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 4);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
GLFWwindow* window = glfwCreateWindow(800, 600, "TestGL", NULL, NULL);
glfwMakeContextCurrent(window);
// init glew
GLint flags;
glGetIntegerv(GL_CONTEXT_FLAGS, &flags);
if (flags & GL_CONTEXT_FLAG_DEBUG_BIT)
{
    glEnable(GL_DEBUG_OUTPUT);
    glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
    glDebugMessageCallback(glDebugOutput, NULL);
    glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE);
    puts( "Debug" );
}
else
    puts( "Debug for OpenGL not supported by your system!" );

```
> 2 votes

---
Tags: opengl, c++, glfw
---


# Question
Title: samplerCube for point light shadow map has dark corners relative to screen aspect ratio / size?
I almost have point light shadows working but the corner of the samplerCube that I use for the shadow map has corners that get darker depending on the main camera. Is this something to do with a transform into a different space somewhere? I followed learn-opengls tutorial on this and they don't seem to have this issue or it just didn't come up in their simple example.

Here a YouTube video of the problem because it is kinda hard to explain... https://youtu.be/FXpwgyJh1ZA

That shows the depth map sampler not the shadows by the way.

This also happens when the radius is almost 0 and the cube map is completely white.

```
float PointLightShadow(
    vec3 NegL, // FragWorldPos - pointLights[i].Position
    float R)   // radius of light
{
    if (mat_hasShadowMap2 == 0) {
        return 1.0f;
    }

    float closestDepth = texture(mat_shadowMap2, NegL).r;
    float currentDepth = length(NegL);

    float bias = 0.05;
    float shadow = R * closestDepth > currentDepth - bias ? 1.0 : 0.0;

    return closestDepth; // for this example
}

```

Sending light position to shader

```
...
m_lightData.PointLights[i].Position = lights[i]->Position(); // setting in world space
...

```

and for the FragWorldPos

```
...
out vec3 FragWorldPos;
...
vec4 worldPos = model * vec4(vert, 1);
FragWorldPos  = worldPos.xyz;
...

```

and then the fragment shader has a matching in variable.

I think like 99% of this is working, I just don't understand why the cube map seems to have these dark corners. They change aspect by changing the screen also suggesting that they are in some type of camera space, but I don't see where that would happen. Let me know if you need more context for the code snippets, these are the only important parts I think though.

# Answer
> 1 votes
For anyone with this problem in future: I never thought to check the mipmaps which were generated as fully black originally. Fix was to regenerate them after the light was updated.

---
Tags: opengl, shadow-mapping, cubemap
---


title: Arc length between two angles

text:
# Question
Title: Arc length between two angles
As I calculate the length of the arc (green) between two angles;

I need a method like:

arc\_lenght (xpos, ypos, radius, ang1, ang2) { return arc\_lenght }

# Answer
> 1 votes
The arc-length, `l`, of a circle is equal to the angle of the arc, `θ`, in radians times the radius.

If we assume that `ang1` is in the range `[0 - ang2]` and `ang2` is in the range `[ang1 - 360]` (so `ang1` is always the smaller of the two and neither is bigger than `360`) then:

```
float angle = ang1 - ang2;
float rad = angle * PI / 180.0;
float radOutside = (2 * PI) - rad;

float arc_length = radOutside * radius;

```

I am not sure what `xpos` and `ypos` represents, but I don't think they're relevant for getting the arc length.

---
Tags: linear-algebra, trigonometry
---


# Question
Title: How can I design a battle algorithm for my MMORTS?
So I am actually developing a MMORTS myself, and this is getting me stuck a bit. So lets say you have two opposing armies who just started their battle. How should the code determine who is the winner? Obviously you have to take into consideration such things as...

* How many troops does the army have?
* What level are the troops? (tier 1, tier 2, etc)
* What buffs and bonuses do they have? (increased attack and defense through research perhaps)

There are more I could list but you get the idea. There is a bit of math involved of course. Calculating all the stats and incorporating any buffs. But how should the actual fighting work? I have tried finding out via research on google, but most games keep their battle algorithms close to the table. You have all of this input from the armies, and then you put them into these mysterious algorithms and the code spits out a result. I must be missing something. I have had small glimpses of ideas.

It is weird because you are not actually controlling some character with hitboxes and a weapon. You are commanding armies of NPC units that are physically controlled by AI. Which side should attack first? Should they attack each other at the same time? How do you incorporate troops with different damage amounts and health and defense? And what about support units?

How can I make this such a battle algorithm for my game?

# Answer
As game designer, that is up to you.

*The End.*

---

Alright, alright... Ask yourself how do you want the game to be played. Ask yourself how should the player react with the results of combat. Then, for each aspect of your combat mechanic consider how it supports those play styles and whatever or not it justifies reactions you do not want.

---

It can be helpful to reduce the mechanic to its minimum. In this case, it would be whoever attacks wins. Is that good for your game? Maybe, but probably not. You seem to want troops, you probably want the players to make them... however, if they don't affect the result of combat, this design does not support any play style that involve making troops.

So, we want a design that encourages to make troops. That means that the more troops the better. Then the simplest design is that whoever has more troops wins. So the player will want to send more troops than the enemy. That is viable.

How about types of troops? You could have some troops have more weight than others. You could have some troops be better when attacking than defending.

Do you want players to pick the best troop possible and then just do a bunch of that one? If not, then you need to give incentive to create different kinds of troops. Perhaps some troops have synergies and count as more when they are together. Or perhaps some troops have diminishing returns, so at some point it does not make sense to add more of the same kind.

Now, we are getting somewhere. You need a function that takes the army and gives it a score for attack, and a score for defense. And you can put there whatever. Yes, the number of troops of each kind, but also buffs, terrain, time of the day, etc.

Oh, I forgot, a common trope is to have some kinds troops have advantage over other kinds of troops. In a rock-paper-scissors fashion. Which can be the foundation of rotating meta. If you want to do that, then the score needs to consider the both armies... so, yeah.

---

I do not know what buffs exist in your game, or what terrains, or even if there is a day cycle... you know, so you have to make up this function. You, as game designer, tweak it for your needs. It is art and engineering, not science.

Ah, something else you need to decide: are the result just win or lose, or can you have results like they loss x amount of troops, or even they earned experience. Do troops have levels? In some games yes, in some games no.

Here is an idea: you could have hero units, they could be the only ones with experience, and gain levels. They could even have equipment. Now it is an strategy game and an RPG.

---

And one more thing: are the results deterministic? You can, for example, use the score of the army as a mean metric for a bell curve, with some (hand tweaked by you, the designer) standard deviation, so that the army sometimes performs a little better, some times a little worse. And why should it be a bell curve? It can be whatever.

Should a single unit be able to defeat a large army just by chance? Ern... probably not. Unless that is what you are going for, players are likely to want to feel in control.

What I describe above is output randomness (the player set all the thing the best they can, and then RNGesus comes and messes with the result).

You can convert that into input randomness. That is, the game tells the player that if they attack they will have x random buff. Now, the random happens before the player decides.

You can go further. Perhaps the player has a deck of card, and each attack one is pulled at random. Now it is an strategy game and a deck building game.

---

OK, so you come up with some model, how do you know if it is right? YOU TEST!

If it does not work, if player react in ways you don't want (be that as evident as rage quit or in more subtle ways), or if the play styles you want are not viable or do not make sense with the given mechanic... well, you go back and tweak it.

Which reminds me. You do not need to have final art to test the mechanic. Heck, you do not need to put the mechanic into the game to test it, you can do an isolated prototype. In fact, some mechanics can be tested with pen and paper, which could make sense in early stages when you yet don't know if it worth the trouble to program the mechanic.

---

There is another aspect of this, and that is conveying the mechanic to the player. In general, the player does not need to know the details of how these mechanics work in a particular game. However, the game should teach how to play it. And that means that the game got to convey how it works to some degree. The game does not have to tell the player that the army attack score is such and such function of the troops. Yet, convey that more troops means better.

It could be useful for you to play those games with the intent of analyzing them from the point of view of game design. In particular see what are they doing to convey their mechanics. Not only to have a hint of how they work, which is directly applicable to your problem. But also to see what play styles are they encouraging.

---

All in all, remember that I do not know what is in your game. Furthermore, I cannot tell you what should be in your game. I cannot design the game for you. *If you just wanted games designed by other people, you would not be doing this, right?* Perhaps, what your game needs is precisely to not do it like everyone else.

As game designer, that is up to you.

*The End.*
> 5 votes

---
Tags: game-design, algorithm, game-mechanics, mmorts
---


title: Recalculating Stats After Any Change?

text:
# Question
Title: Recalculating Stats After Any Change?
I have four sources of a character's stats changing (in order of calculation):

1. Due to leveling up (base stats)
2. Equipment changing (calculated after base stats)
3. A passive skill being toggled on or off (calculated after equipment stats)
4. Being afflicted by a buff/debuff (calculated after passive skill stats)

My question is, if any of these sources causes a change, should I recalculate everything from base stats, or store "sets" of the stats after each change (i.e. save a copy of the stats after passive skill changes, so if the player is hit by a "defense down" status effect, I only have to recalculate from skill stats). Unless there's a better way to deal with this problem, I don't know which of these two options is better.

# Answer
What happens more often:

* Changing something which causes a derived stat to require recalculation
* Reading the value of a derived stat

We don't know anything about the architecture of your game, so we can only guess.

If changes are more frequent than reads, then it can make sense to make each derived stat a property which get recalculated on the fly. (A property looks like a variable from the outside, but internally includes logic when you set and/or get its value).

Something like this:

```
public float Attack {
     get => ( strength * level ) + weapon.damage;
}

```

From a code readability and maintainability standpoint I find this a quite clean solution. You can immediately see that Attack is a derived attribute and how it's calculated. If performance is not a concern, I would recommend you to keep doing it that way.

However, in most games, character attributes are read far more frequently than they are changed. That means the attack value will get recalculated again and again even though the variables it is based on didn't change. Often this won't be a concern. As long as you only have a small number of objects fighting in the scene, you won't even notice the performance overhead. But if you want to create huge battle simulations with thousands of objects, then it could become noticeable.

In that case it might make more sense to turn the base attributes into properties instead and trigger the recalculation in their setters. The frequently called derived attributes become read-only properties which return the cached values:

```
private float _attack;
public float Attack {
    get => _attack
}

private float _strength;
public float Strength {
    get => _strength;
    set {
         _strength = value;
         recalculateAttack();
    }
}

private void recalculateAttack() {
        _attack = ( _strength * level ) + weapon.damage;
}

```

But while this code is more optimized for frequent reads, it also has a lot more boilerplate. There is also some room for bugs. It's not unlikely that some developer will at some point during development add some obscure way to change a variable which contributes to `_attack` without triggering the `recalculateAttack()` method. You might not even notice when you test it, because in your test setup there is something else which happens immediately afterwards which triggers a recalculation. But that might not be guaranteed to happen in *every* situation.

Do you want to get exploits in your game? Because that's how you get exploits.
> 1 votes

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


title: How does lookAt matrix math work?

text:
# Question
Title: How does lookAt matrix math work?
Can someone provide me an explanation of how the lookAt matrix works?

```
+----+----+----+----+
| Xx | Xy | Xz |  0 |  <- x axis
+----+----+----+----+
| Yx | Yy | Yz |  0 |  <- y axis
+----+----+----+----+
| Zx | Zy | Zz |  0 |  <- z axis
+----+----+----+----+
| Tx | Ty | Tz |  1 |  <- camera position
+----+----+----+----+

```

From my current understanding using the diagram above from this tutorial, the zAxis is created by subtracting camera position from the target position. Then you create two more perpendicular vectors calculated by: xAxis = zAxis **x** up, yAxis = xAxis **x** zAxis.

However, I don't understand how these exact operations result in the camera facing towards something? Like why are these exact calculations needed? Why could it not have been zAxis = camPosition - targetPosition? Or yAxis = zAxis **x** down instead of zAxis **x** up? Or have xAxis = targetPosition - camPosition instead of the zAxis?

# Answer
The **positive** zAxis actually points **away** from the target. Thus what I wrote previously was incorrect, it should instead be: `zAxis = norm(camPosition - targetPosition)`. This will cause the positive zAxis to point out of the screen from the camera's perspective, and thus the **negative** zAxis to go into the screen towards the target. This means then means the target can be rendered as it is located on the negative zAxis of the camera (remember that the camera **only renders vertices on negative zAxis**).

Because of the above, that is why `zAxis = norm(camPosition - targetPosition)` is needed.
> 1 votes

# Answer
You are creating an orthogonal coordinate system with the operations described that moves objects from world space into view space.

The vector of target - pos gives you the Z axis. It is from the eye towards the direction you are looking. The next cross product of Z x Up creates the X vector, which points left or right depending on the handedness of the coordinate system. Finally, the Y vector is created by X x Z, giving you your orthogonal basis vectors. These are then offset by the camera's position.

The reason why we typically do the math in that order: By convention, Z typically points into the screen in a left handed system and out of the screen in a right handed system. This causes X to match the horizontal of the screen and Y to match the vertical of the screen, leaving Z to represent depth.
> 0 votes

---
Tags: 3d, mathematics, graphics, webgl
---


# Question
Title: Unity3D, voxel chunk mesh modification: Further performance improvements
I've flattened my 3D chunk array(Got nice 20ms speed up), modified my VertexData struct (that I use in Dictionary as a key) to have custom hashcode(another 20ms and -2.7mb GC.alloc data speedup). But I'm not sure what to do next, since 40ms still feels long for such a small chunk(In fact, its twice smaller the size of Minecrafts 16x256x16 and still managing to be slower.).

My biggest bottleneck still seems to be the dictionary.

This is current performance profile:

The code:

```
public void MakeChunk()
    {

        vertexCount = 0;
        //these are all Lists except verticesDictionary
        vertices.Clear();
        normals.Clear();
        verticesDict.Clear();
        uvs.Clear();
        triangles.Clear();

        int len = 32 * 32 * 32;

        for (int i = 0; i < len; i++)
        {
            int cubeType = data.raw[i];
            if (cubeType != 0)
            {
                int x = i % 32;
                int y = (i / 32) % 32;
                int z = i / (32 * 32);
                MakeCube(x, y, z, cubeType);
                blocksGenerated++;
            }
        }
    }
    void MakeCube(int x, int y, int z, int cubeType)
    {
        for (int i = 0; i < 6; i++)
        {
            Direction dir = (Direction)i;
            if (data.GetNeighbor(x, y, z, dir) == 0)
            {
                MakeFace(dir, x, y, z, cubeType);
            }
        }
    }
    void MakeFace(Direction dir, int x, int y, int z, int cubeType)
    {
        VertexSignature signature;
        signature.normal = dir;

        Vector3[] faceVertices = CubeMeshData.faceVertices((int)dir, x, y, z);
        int[] triangleIndices = new int[4];
        signature.cubeType = cubeType;

        for (int i = 0; i < 4; i++)
        {
            signature.position = faceVertices[i];
            Vector3 uv = CubeMeshData.ProjectPositionToUV(signature.position, dir);
            uv.z = signature.cubeType;

            int vertex = GetVertexIndex(signature);
            triangleIndices[i] = vertex;
        }

        triangles.AddRange(new int[6] {
            triangleIndices[0],
            triangleIndices[1],
            triangleIndices[2],
            triangleIndices[0],
            triangleIndices[2],
            triangleIndices[3]
            }
        );

    }
    void PrepareMeshData()
    {
        foreach (var pair in verticesDict)
        {
            int index = pair.Value;
            vertices.Add(pair.Key.position);
            CubeMeshData.DataCoordinate coord = CubeMeshData.offsets[(int)pair.Key.normal];
            normals.Add(new Vector3(coord.x, coord.y, coord.z));

            Vector3 uv = CubeMeshData.ProjectPositionToUV(pair.Key.position, pair.Key.normal);
            uv.z = pair.Key.cubeType;
            uvs.Add(uv);
        }
    }

```

Hashing:

```
 struct VertexSignature
    {
        public Vector3 position;
        public Direction normal;
        public int cubeType;

        public override int GetHashCode()
        {
            uint h = 0x811c9dc5;
            h = (h ^ (uint)position.x) * 0x01000193;
            h = (h ^ (uint)position.y) * 0x01000193;
            h = (h ^ (uint)position.z) * 0x01000193;
            h = (h ^ (uint)normal) * 0x01000193;
            h = (h ^ (uint)cubeType) * 0x01000193;

            return (int)h;
        }
    };

```

Then I do this:

```
    Vector3[] vertexArr = vertices.ToArray();
    int[] triArr = triangles.ToArray();
    Vector3[] normalsArr = normals.ToArray();

```

I've really run out of ideas on how to improve performance further.

Any help is welcome.

# Answer
**Nested method calls**

Method calls in loops should be inlined (not sure C# /CLI's internal rules for this), as every such causes a `JMP` in the generated assembly (same for `MakeCube` calling `MakeDir`):

`for (int i = 0; i < len; i++)
 {
 int cubeType = data.raw[i];
 if (cubeType != 0)
 {
 ...
 MakeCube(x, y, z, cubeType);
 ...
 }
 }` In C we would just macro this, but you are stuck with C# which may mean copy-pasting blocks of code, or using a code generator of some sort to do that for you.

Even worse is that you call `MakeDir` inside `MakeCube` inside a loop.

**"Fiddly branchless logic"**

FBL - a coin termed on a question I once asked on the OpenGL forums for shader code - is the best thing you can do, where possible, to avoid conditionals, especially inside loops.

For example, you are saying `if (cubeType != 0) { /*do some stuff*/ }` What if you eliminated that and did that stuff anyway, but made it invisible for null voxels? For example, creating blocks that exist but have zero dimensions and thus are not visible? This can be done by for example, doing the following:

```
1. factor = 1 if any bit is set in cube.type (without using a conditional), else 0 (if no bits are set, i.e. = positive zero)
2. multiply your x, y, z dimensions of cube generated by this factor

```

I know that C# has some restrictions in this regard (getting `factor` without triggering a full conditional)... You'll need to do some more (re)search on this. And this may also increase the number of vertices sent to the GPU... but if you are doing custom shaders, that "full set" is then also easier to index into without search (for example if you want to generate your voxels using a geometry shader). But at the end of the day, it all depends on what you want to speed up.

This is not trivial, but FBL is a valuable tool indeed for data-intensive applications like this.

**Hashing inefficiency**

Also, your hash function is very heavy on ops count. I would try to reduce that. We can talk about this further if you wish.
> 1 votes

---
Tags: unity, c#, optimization, voxels
---


# Question
Title: line to point collision without doing three square roots
Is it possible to test a point to line collision without doing three square roots? Here's how I'm currently doing it:

I have point P that I want to check is on the line, and point A and B for the two ends of the line. I use the Pythagorean equation to get length PA, PB, and AB. Now I check to see if PA + PB = AB. if PA + PB is larger than AB, the point cannot be on the line.

```
private boolean PTLCollisionCheck(float px, float py, float ax, float ay, float bx, float by) {
    float PA = (float) Math.sqrt(((px - ax) * (px - ax)) + ((py - ay) * (py - ay)));
    float PB = (float) Math.sqrt(((px - bx) * (px - bx)) + ((py - by) * (py - by)));
    float lineLength = (float) Math.sqrt(((ax - bx) * (ax - bx)) + ((ay - by) * (ay - by)));
    return (PA + PB) <= (lineLength + 1);
}

```

# Answer
In 2D, we can use a trick that if we exchange the x & y of a vector and negate one of them, we get a vector perpendicular to the one we started with very cheaply.

```
Vector2 span = pointB - pointA;

Vector2 perpendicular = new Vector2(-span.y, span.x);

Vector2 offset = pointP - pointA;

float perpendicularDot = Vector2.Dot(offset, perpendicular);

```

This dot product (`offset.x*perpendicular.x + offset.y*perpendicular.y`) is proportional to how far our point strays off the line - positive for the half plane "above" the line, negative for the half plane "below", and zero when our point sits exactly on the line. Specifically, it's our distance off the line times the length of the line segment itself.

Due to precision limits, our point will almost never fall exactly on the line, so you'll often want to check when this value changes signs (meaning it crossed the line somewhere between the last check and this one), rather than waiting for it to hit zero perfectly.

You can also use an epsilon to say "values in this range are close enough to zero to count", similar to the `+1` fudge factor in your current algorithm - but you'll want to adjust for the length of the line segment if using lengths over different orders of magnitude. Or you can store a unit normal for each segment to get a true perpendicular distance cheaply.

Once we know our point is somewhere on the (infinite) line, we need to check whether it's between the endpoints of our segment. We can do that with another dot product:

```
float spanDot = Vector2.Dot(span, offset);

// If negative, we're behind the start point.
if (spawDot < 0f)
   return false;

// If greater than the squared magnitude of span, we're past the end point.
if (spanDot > Vector2.Dot(span, span))
   return false;

return true;

```
> 1 votes

# Answer
I'm sure there are many solutions, but this is the first one I thought of. It's fairly simple and only involves basic algebra (which based on the method you proposed I assume you understand), but I'm going to go through it fully to try and ensure it makes sense:

First, ensure that px is between the values of ax and bx, and that py is between ay and by. If either is false, then it is impossible for the point to be on the line segment. The way I did this in the code example below was to check if either **ax \<= px \<= bx** or **bx \<= px \<= ax** were true (because it is unknown whether or not ax or bx is greater, doing it this way ensures that the check is *true* in either case). The check for py is done the same way. If either px or py were not between, *false* is automatically returned because the point cannot be on the line segment AB. For readability, another function called *IsBetween* was made for this check.

Now begins the algebra.

All lines can be modeled using a linear equation. In this case, I'd use the form

**f(x) = y = m(x - x1) + y1**,

where m is the slope of the line and x1, y1 represent any coordinate pair on the line

The slope can be calculated fairly easily using the slope formula ((by - ay) / (bx - ax)), and the point (x1, y1) can be either the start or end point (since both are, of course, on the line)

If point (px, py) is on line AB, then this equation *must* be true when (px, py) is plugged into it.

If **f(px) = py**, then the point (px, py) is on the line AB. Otherwise, it is not. Because we already checked to ensure that px was between ax and bx and that py was between ay and by, if this is true, then (px, py) is on the line segment AB, meaning we can have *PTLCollisionCheck* return *true*.

Here is a code example I made (because you did not specify a specific language I wrote it in C#, although it is a simple enough function that only minor changes should need to be made for it to work in other languages):

```
private bool PTLCollisionCheck(float px, float py, float ax, float ay, float bx, float by)
{
     if (!(IsBetween(px, ax, bx) && IsBetween(py, ay, by)))
     {
          return false;
     }

     float slope = (by - ay) / (bx - ax);

     return (slope * (px - ax) + ay == py);
}

private bool IsBetween(float testNum, float a, float b)
{
     return (a <= testNum <= b) || (b <= testNum <= a);
}

```
> 0 votes

---
Tags: collision-detection
---


# Question
Title: Reducing disk space needed to use TextMeshPro in AssetBundles
My game uses `AssetBundles`, and quite often each of those bundles use `TextMeshPro`. The project is at a stage where it would be unwise to change to `Addressables`.

Anyway, I noticed that when a bundle has `TextMeshPro` involved, it easily adds roughly 2mb to the bundle - I assume it's a copy of all the dependencies to make it work.

Ideally all bundles should simply point to one copy which is guaranteed to always be present in the game, which I think `Addressables` sort of does, but as mentioned we cannot use it for this project for various reasons.

One way is to create/add the `TextMeshPro` components at runtime (e.g. have some kind of "placeholder/dummy" component that, upon `Awake()` will add `TextMeshPro` with various preset attributes).

That would work fine, and I'm willing to do that - but perhaps there are less tedious alternatives (other than `Addressables`) that I haven't thought of.

The goal is to be able to reduce the disk space required for each bundle just because it is using `TextMeshPro` components.

# Answer
> 2 votes
Step one is to determine what is being included in multiple asset bundles that can be included in just one.

https://docs.unity3d.com/Manual/AssetBundles-Browser.html

This tool lets you look at what is included in asset bundles, whether directly assigned or as a dependency of something else. It also indicates with a warning flag anything that is being included in multiple bundles.

Step two is then to just move all of those things into a separate asset bundle, which you can do from right inside that tool. Just select everything that has a warning flag, and drag it over to the section where it lists all asset bundles. It will ask if you want to make one bundle for each asset or one bundle for everything selected. Go with the single bundle option. Then, all of the other asset bundles should now rely on that single dependency asset bundles.

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


title: Zoom into character upon collision

text:
# Question
Title: Zoom into character upon collision
When a character collides with an object in my game, there is a slow motion effect. That's coool, but how would I zoom into a sprite when it collides with another object?

Here is my code currently...

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

public class GameManager : MonoBehaviour
{
    public float slowness = 2f;

    public int index;

    private AudioSource hitSource;

    public Vector3[] Target;
    public Camera Cam;
    public float Speed = 0.012f;

    public void Start()
    {
        Cam = Camera.main;

    }

    public void EndGame()
    {
        Application.targetFrameRate = 300;

        StartCoroutine(RestartLevel());

        hitSource = GetComponent<AudioSource>();

    }

    IEnumerator RestartLevel()
    {
        Cam.orthographicSize = Mathf.Lerp(Cam.orthographicSize, 3, Speed);
        Cam.transform.position = Vector3.Lerp(Cam.transform.position, Target[1], Speed);

        Time.timeScale = 1f / slowness;

        Time.fixedDeltaTime = Time.fixedDeltaTime / slowness;

           yield return new WaitForSeconds(1.5f/slowness);

        Time.timeScale = 1f;
        Time.fixedDeltaTime = Time.fixedDeltaTime * slowness;

        SceneManager.LoadScene(2);

    }

    private void OnCollisionEnter(Collision collision)
    {

    }
}

```

# Answer
You need to 'interpolate' (commonly shortened to 'interp') your 'camera position' towards the object.

**Edit**

You have correctly identified a collision response event.

However, the name of your class seems to suggest that you are attempting to deal with this collision outside of either the player or the sprite that you have collided with.

1. Step 1 is to put your collision response inside your player object. Your player should be responsible for handling its own collision - your game manager should **not** be responsible for handling something else's collision, make sense?
2. You need to interp your camera position towards the sprite if it has been collided with

To do this:

1. Calculate the *vector* from your camera to the collided sprite -
`Vector = CollidedSprite.WorldLocation - Camera.WorldLocation`
2. Each *frame* (tick), adjust the camera's position *a fraction* of this *vector* e.g. `Camera.WorldLocation += Vector / 10`
3. It stands to reason that after 10 frames in this example, the camera will have travelled 10 1/10ths of the way towards the sprite's location. You likely don't want it to travel all of the way, so you'll probably want to move the camera by 50-75% of the calculated vector. Make sure that when you have travelled the required amount, you halt whatever repeated process is causing this camera position change.
> 0 votes

---
Tags: unity, c#, collision-detection
---


# Question
Title: Using a object as origin for a Raycast using mouse position as direction
Is there any way to cast a ray from an object using the mouse position as the direction for the ray? I´ve been looking for a while but I can´t find something like that anywhere, so if anyone could help with this it would be great.

I´m using kind of a top view, you can see how here:

And what I want to do is set a empty game object on top of the character to act as the origin for the ray, then when I press a key the mouse is unlocked and an area appears, here´s how that looks:

And I want to use the position where the mouse clicks to be the direction of the ray.

# Answer
> 0 votes
First you want to convert the position of the mouse on screen to a position in 3D world space. That involves a raycast from the camera's perspective to find what's under your mouse cursor. So first we'll form that ray:

```
var camera = Camera.main;

var screenRay = camera.ScreenPointToRay(Input.MousePosition);

```

Now depending on your needs, you might want to...

* Cast this ray into your physics scene, stopping at the closest solid collider \[in selected layers\]

```
if(Physics.Raycast(screenRay, out RaycastHit hit, float.positiveInfinity, selectionLayers)) {
    selectedPoint = hit.point;
    // ...

```
* Cast this ray against a specific collider representing your selection region

```
if(selectionZoneCollider.Raycast(screenRay, out RaycastHit hit, float.positiveInfinity)) {
    selectedPoint = hit.point;
    // ...

```
* Cast this ray against an infinite plane representing your ground/aiming level

```
if(selectionPlane.Raycast(screenRay, out float distance)) {
    selectedPoint = screenRay.GetPoint(distance);
    // ...

```

Whichever way you go, now you have a position in world space to aim toward. You might still want to shift that point (eg. if it's a point on your ground plane, you might want to lift it up on the y-axis to a position at eye/gun level).

Then you can form a ray toward that point from your origin transform by simply writing:

```
var originToSelectionRay = new Ray(originTransform.position, selectedPoint - originTransform.position);

```

---
Tags: unity, raycasting
---


# Question
Title: How to mute the background music when an ad begins to play when a scene is loaded?
I am a bit of a novice here but I have created a game and I am showing ads when a scene is loaded but the background music keeps playing in the background. Is there a way in which the background music can be paused when the ad begins but resumes playing once the ad has finished?

I have an ad controller for the ad placements and an coroutine to play the ads once a specific scene has been loaded.

The background music is currently working using the inspector on a random background gameobject.

This is my code for the ad manager for the scene:

```
public static Ads instance;
private string playStoreID = "XXXXXXXX";

private string vidad = "XXXXXX";
private string rewardedVideoAD = "YYYYYYY";
private string BannerAD = "ZZZZZZ";

   private void Awake()
{
    if (instance != null)
    {

        Destroy(gameObject);
    }

    else
    {
        instance = this;
        DontDestroyOnLoad(gameObject);
    }
}

void Start()
{
    Monetization.Initialize(playStoreID, true);
}

public void ShowInterstitialAD()
{

   if (Monetization.IsReady(vidad))
    {
        ShowAdPlacementContent ad = null;
        ad = Monetization.GetPlacementContent(vidad) as ShowAdPlacementContent;

        if (ad != null)
        {
            ToggleMute();

            ad.Show(ToggleMute);
        }
    }

}

void ToggleMute(ShowResult finishState = default(ShowResult))
{
    audioToMute.mute = !audioToMute.mute;
}

public void ShowRewardVideoAD2()
{

    if (Monetization.IsReady(rewardedVideoAD))
    {
        ShowAdPlacementContent ad = null;
        ad = Monetization.GetPlacementContent(rewardedVideoAD) as ShowAdPlacementContent;

        if (ad != null)
        {
            ToggleMute();

            ad.Show(ToggleMute);
        }
    }

}

public void ShowRewardVideoAD()
{

    if (Monetization.IsReady(rewardedVideoAD))
    {
        ShowAdPlacementContent ad = null;
        ad = Monetization.GetPlacementContent(rewardedVideoAD) as ShowAdPlacementContent;

        if (ad != null)
        {

            ToggleMute();

            ad.Show(ToggleMute);
        }
    }

}

}

```

Here is a picture of the inspector...

# Answer
Inside your ad script, add a field to point to the audio source that you want to mute:

```
public AudioSource audioToMute;

```

Be sure to wire this up in the Inspector so it references your background music source.

Then we prepare a method to mute/unmute this audio source each time we call it. In the Monetization API that looks like this `ShowAdFinishCallback`:

```
void ToggleMute(ShowResult finishState = default(ShowResult)) {
    audioToMute.mute = !audioToMute.mute;
}

```

Then in your show method:

```
if (Monetization.IsReady(rewardedVideoAD))
{
    ShowAdPlacementContent ad = null;
    ad = Monetization.GetPlacementContent(rewardedVideoAD) as ShowAdPlacementContent;

    if (ad != null)
    {
        // Mute our audio while the ad is shown.
        ToggleMute();

        // Show our ad and call back to our mute function once it finishes.
        ad.Show(ToggleMute);
    }
}

```

---

In the Advertisement API we can work very similarly, we just set up our callback as a listener, registered up-front, rather than part of the `Show` call:

```
// Declare our manager as implementing the IUnityAdsListener interface.
public class AdManager : MonoBehaviour, IUnityAdsListener {

    // All your existing member variables go here. I'll skip repeating that.

    // Handle the various messages this interface exposes:
    // (We don't need anything special with three of these, so we can ignore them)
    public void OnUnityAdsReady (string placementId) {}
    public void OnUnityAdsDidError (string message) {}
    public void OnUnityAdsDidStart (string placementId) {}

    // This is where we want to unmute our audio, after the ad is gone.
    public void OnUnityAdsDidFinish (string placementId, ShowResult showResult) {
        // Call the same ToggleMute method we defined in the first example.
        ToggleMute();
    }

    // When you initialize your ads in Start, also register this listener.
    void Start()
    {
        Advertisement.Initialize(playStoreID, true);
        Advertisement.AddListener(this);
}

IEnumerator ShowBannerWhenReady () {
    while (!Advertisement.IsReady (placementId)) {
        yield return new WaitForSeconds (0.5f);
    }

    // Mute our audio before showing the ad.
    ToggleMute();
    Advertisement.Banner.Show (placementId);
    // After the ad finishes, it will call the listener method we defined above.
}

```
> 0 votes

---
Tags: unity, music, advertisements, unity-ads
---


# Question
Title: Fishbowl effect correction in raycasting engine suggestions (pseudo 3d projection)
I'm writing a simple raycaster in golang and I have some problems understanding perspective correction. The code is simple, the main rendering loop is this:

```
    curVector := playerVector.NewRotated(-curFov / 2)
    rotateStep := curFov / float64(screen.Width()) // Angles per screen row
    // Traverse each row of our screen, cast a ray and render it to screen buffer
    for i := 0; i <= screen.Width(); i++ {
        curVector.Rotate(rotateStep)

        hit, distance, tile, tileP := rayCast(curX, curY, curVector, viewDistance)

        if hit {
            // distToHeight is basically linear (screen.Height()/distance)
            drawTexturedWallColumn(screen, tile, i, distToHeight(distance, screen.Height()), tileP) // Project walls on screen
        }
        // drawSpritesColumn(screen, i, curVector, distance) // Project sprites on screen
    }

```

So I just cast rays with even angle intervals and get this fishbowl effect:

So, I understand that the problem is with angle intervals and sphere projected rays with the same length. I found this question How can I correct an unwanted fisheye effect when drawing a scene with raycasting? and tried to implement the same logic:

```
leftVector := playerVector.NewRotated(90)
    // Traverse each row of our screen, cast a ray and render it to screen buffer
    for i := 0; i <= screen.Width(); i++ {
        progress := float64(i)/float64(screen.Width()) - 0.5 // -0.5 to 0.5
        stepX := (playerVector.X + progress*(leftVector.X*2)) // *2 to make 90 FOV
        stepY := (playerVector.Y + progress*(leftVector.Y*2))
        curVector := Vector{X: stepX, Y: stepY}

        hit, distance, tile, tileP := rayCast(curX, curY, curVector, viewDistance)

        if hit {
            // distToHeight is basically linear (screen.Height()/distance)
            drawTexturedWallColumn(screen, tile, i, distToHeight(distance, screen.Height()), tileP) // Project walls on screen
        }
        // drawSpritesColumn(screen, i, curVector, distance) // Project sprites on screen
    }

```

But the result is almost the same (FOV variable is not used here but it's around 90, it's not important at the moment). The difference is that this one has a more "linear" fishbowl effect because of evenly spaced intervals (progress variable):

So, I don't know how to fix this, I also tried to use perpendicular distance (distance\*cos).

# Answer
> 2 votes
Here's a solution I got for now (using the second one with vectors above). Before, i calculated the distance using vector's angle, i corrected it to increase starting ray position using direction vector like this:

```
func rayCast(x0, y0 float64, dir Vector, distance float64) (hit bool, dist float64, tile int, tileP float64) {
    length := 0.0 // Length of hit check
    step := 0.01  // Interval of collision checking
    for length <= distance {
        if hit, tile, tileP := IntersectsWithMap(x0, y0); hit {
            return true, length, tile, tileP
        }
        x0 += dir.X * step
        y0 += dir.Y * step
        length += step
    }
    return false, distance, 0.0, 0.0
}

```

Results so far:

---

The previous rayCast is a bit messy but I'll include it for historic purposes:

```
func rayCast(x0, y0 float64, dir Vector, distance float64) (hit bool, dist float64, tile int, tileP float64) {
    length := 0.0 // Length of hit check
    step := 0.01  // Interval of collision checking
    sX, sY := x0-dir.X, y0-dir.Y
    for length <= distance {
        if hit, tile, tileP := IntersectsWithMap(increaseVector(sX, sY, x0, y0, length)); hit {
            return true, length, tile, tileP
        }
        length += step
    }
    return false, distance, 0.0, 0.0
}

// Gets next point for vector by length
func increaseVector(x0, y0, x1, y1, length float64) (x, y float64) {
    dX, dY := x1-x0, y1-y0
    mg := math.Sqrt(dX*dX + dY*dY)
    uX, uY := dX/mg, dY/mg

    return x1 + uX*length, y1 + uY*length
}

```

---
Tags: raycasting
---


# Question
Title: Animator get number of animations (Unity)
In C#, how would I get the number of animations in an Animator Controller?

So I want to find out how many animations there are in an Animator Controller, and have this number in script.

Thanks in advance!

# Answer
`[SerializeField] Animator animator;
int NumberOfNonEmptyStates = animator.runtimeAnimatorController.animationClips.Length;`

This returns the number of non-empty states in the specified animator. (I'm using Unity version 2018.3.4)
> 1 votes

# Answer
If you are using Version 5 and up, you can get all states in the Animation Controller. You will need to drill down to layer, state-machine and then finally state.

Follow these to get started:

http://docs.unity3d.com/ScriptReference/Animations.AnimatorController.html http://docs.unity3d.com/ScriptReference/Animations.AnimatorController-layers.html http://docs.unity3d.com/ScriptReference/Animations.AnimatorControllerLayer-stateMachine.html http://docs.unity3d.com/ScriptReference/Animations.AnimatorStateMachine.html
> -2 votes

---
Tags: unity, c#, animation, controllers, mecanim
---


# Question
Title: How often should I check for collisions in a Minecraft-like game?
I'm trying to build a game from scratch in Dart, similar to Minecraft.

As far as I understood, there are two main functions in a general game loop:

* tick: a function that gets executed a fixed amount of times per second independently of the frame-rate. And I think in Minecraft those are called TPS (Tick per second).
* render: a function that draws everything on the screen called every frame, the frequency of which depends on the device's capabilities. (FPS)

(I am referencing Minecraft, as It's a well-known game and It's quite simple)

What I'm trying to understand, is at which time should collisions be checked for? Are they checked each time the screen draws (render), or every time the tick function runs?

# Answer
> 2 votes
Collisions are part of the physics update, which is typically handled in the fixed timestep loop (what you call "tick" here).

By handling collision detection and resolution at a fixed game time interval, you help ensure that the physics play out consistently even on very different hardware.

If you do physics on a variable timestep (like in the render loop), then folks running at a low framerate can get glitchier physics — objects have to move farther in each physics step to keep up the right apparent movement rates, so they're prone to tunneling through collisions that would have been caught and handled correctly if using smaller steps.

In the Unity game engine as an example, this fixed timestep defaults to 0.02 seconds, or 50 Hz. Other games use different values, so you can tune it to get the right balance between performance and physics precision for your game.

---
Tags: collision-detection, game-loop, fixed-timestep
---


# Question
Title: Text Rendering using FreeType library not working correctly
I am currently implementing font rendering into my 3D game engine using the `FreeType` library. I have followed this tutorial: https://learnopengl.com/In-Practice/Text-Rendering, which lead into this next tutorial: https://learnopengl.com/In-Practice/2D-Game/Render-text.

I will quickly describe my implementation and end by showing my output. When I create my `TextRenderer` object the following code is called:

```
TextRenderer::TextRenderer() :
    TextShader("text")//This creates text.glsl (shown later)
{
    glGenVertexArrays(1, &this->VAO);//.h file has GLuint members VAO and VBO
    glGenBuffers(1, &this->VBO);
    glBindVertexArray(this->VAO);
    glBindBuffer(GL_ARRAY_BUFFER, this->VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 6 * 4, NULL, GL_DYNAMIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), 0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindVertexArray(0);
}

```

The `text.glsl` shader file created in the above constructor is as follows:

```
#include "common.glh"

varying vec2 texCoord0;

#if defined(VS_BUILD)
attribute vec4 vertex;

uniform mat4 T_MVP;

void main()
{
    gl_Position = T_MVP * vec4(vertex.xy, 0.0, 1.0);
    texCoord0 = vertex.zw;
}

#elif defined(FS_BUILD)

uniform sampler2D H_text;
uniform vec3 H_textColor;

DeclareFragOutput(0, vec4);
void main()
{
    vec4 sampled = vec4(1.0, 1.0, 1.0, texture(H_text, texCoord0).r);
    vec4 color = vec4(H_textColor, 1.0) * sampled;
    SetFragOutput(0, color);
}
#endif

```

Following the creation of the `TextRenderer` object its `Load` function is called, the `Load` function uses a `struct` defined in the `.h` file which can be seen here along with the `Load` function:

```
/// Holds all state information relevant to a character as loaded using FreeType
struct Character {
    GLuint TextureID;   // ID handle of the glyph texture
    glm::ivec2 Size;    // Size of glyph
    glm::ivec2 Bearing; // Offset from baseline to left/top of glyph
    GLuint Advance;     // Horizontal offset to advance to next glyph
};

```

```
void TextRenderer::Load(std::string font, GLuint fontSize)
{
    // First clear the previously loaded Characters
    this->Characters.clear();
    // Then initialize and load the FreeType library
    FT_Library ft;
    if (FT_Init_FreeType(&ft)) // All functions return a value different than 0 whenever an error occurred
        printf("ERROR::FREETYPE: Could not init FreeType Library");
    // Load font as face
    FT_Face face;
    if (FT_New_Face(ft, "arial.ttf", 0, &face))
        printf("ERROR::FREETYPE: Failed to load font");
    // Set size to load glyphs as
    FT_Set_Pixel_Sizes(face, 0, fontSize);

    if (FT_Load_Char(face, 'X', FT_LOAD_RENDER))
        std::cout << "ERROR::FREETYTPE: Failed to load Glyph" << std::endl;
    // Disable byte-alignment restriction
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    // Then for the first 128 ASCII characters, pre-load/compile their characters and store them
    for (GLubyte c = 0; c < 128; c++)
    {
        // Load character glyph
        if (FT_Load_Char(face, c, FT_LOAD_RENDER))
        {
            printf("ERROR::FREETYTPE: Failed to load Glyph");
            continue;
        }
        // Generate texture
        GLuint texture;
        glGenTextures(1, &texture);
        glBindTexture(GL_TEXTURE_2D, texture);
        glTexImage2D(
            GL_TEXTURE_2D,
            0,
            GL_RED,
            face->glyph->bitmap.width,
            face->glyph->bitmap.rows,
            0,
            GL_RED,
            GL_UNSIGNED_BYTE,
            face->glyph->bitmap.buffer
        );
        // Set texture options
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

        // Now store character for later use
        Character character = {
            texture,
            glm::ivec2(face->glyph->bitmap.width, face->glyph->bitmap.rows),
            glm::ivec2(face->glyph->bitmap_left, face->glyph->bitmap_top),
            face->glyph->advance.x
        };
        Characters.insert(std::pair<GLchar, Character>(c, character));
    }
    glBindTexture(GL_TEXTURE_2D, 0);
    // Destroy FreeType once we're finished
    FT_Done_Face(face);
    FT_Done_FreeType(ft);
}

```

Follwoing this the `TextRenderer` object has its `RenderTextRenderer` function called every frame, this is as follows:

```
void TextRenderer::RenderTextRenderer(const RenderingEngine& renderingEngine) {
    //glEnable(GL_BLEND); //Commented for now
    //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //Commented for now
    glDisable(GL_DEPTH_TEST);
    this->TextShader.Bind();
    this->TextShader.UpdateUniformsTextRenderer(renderingEngine);
    RenderText("TEST testpqli", 20, 20, 1);//HAS THE DRAW CALL
    glEnable(GL_DEPTH_TEST);
    //glDisable(GL_BLEND); //Commented for now
}

```

The `UpdateUniformsTextRenderer` function and the `RenderText` function are both shown bellow respectively:

```
void Shader::UpdateUniformsTextRenderer(const RenderingEngine& renderingEngine)
{
    for (unsigned int i = 0; i < m_shaderData->GetUniformNames().size(); i++)
    {
        std::string uniformName = m_shaderData->GetUniformNames()[i];
        std::string uniformType = m_shaderData->GetUniformTypes()[i];

         if (uniformName.substr(0, 2) == "T_")
        {
             if (uniformName == "T_MVP")
                 SetUniformMatrix4f(uniformName, Matrix4f().InitOrthographic(0.0f, 800.0f, 0.0f, 600.0f, 0, 10.0f));//left, right, top, bottom, near, far
            else
                throw "Invalid Transform Uniform: " + uniformName;
        }
        else if (uniformName.substr(0, 2) == "H_") {
            if (uniformName == "H_text") {
                int samplerSlot = renderingEngine.GetSamplerSlot(uniformName);//set earlier using SetSamplerSlot("H_text", 4);
                SetUniformi(uniformName, samplerSlot);
            }
            else if (uniformName == "H_textColor")
                SetUniformVector3f(uniformName, Vector3f(0, 1, 0));//Green
            else
                throw "Invalid Transform Uniform: " + uniformName;
        }
    }
}

```

```
void TextRenderer::RenderText(std::string text, GLfloat x, GLfloat y, GLfloat scale)
{
    // Activate corresponding render state
    this->TextShader.Bind();
    glActiveTexture(GL_TEXTURE0);
    glBindVertexArray(this->VAO);

    // Iterate through all characters
    std::string::const_iterator c;
    for (c = text.begin(); c != text.end(); c++)
    {
        Character ch = Characters[*c];

        GLfloat xpos = x + ch.Bearing.x * scale;
        GLfloat ypos = y - (ch.Size.y - ch.Bearing.y) * scale;

        GLfloat w = ch.Size.x * scale;
        GLfloat h = ch.Size.y * scale;
        // Update VBO for each character
        GLfloat vertices[6][4] = {
            { xpos,     ypos + h,   0.0, 1.0 },
            { xpos + w, ypos,       1.0, 0.0 },
            { xpos,     ypos,       0.0, 0.0 },

            { xpos,     ypos + h,   0.0, 1.0 },
            { xpos + w, ypos + h,   1.0, 1.0 },
            { xpos + w, ypos,       1.0, 0.0 }
        };
        // Render glyph texture over quad
        glBindTexture(GL_TEXTURE_2D, ch.TextureID);
        // Update content of VBO memory
        glBindBuffer(GL_ARRAY_BUFFER, this->VBO);
        glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices); // Be sure to use glBufferSubData and not glBufferData

        glBindBuffer(GL_ARRAY_BUFFER, 0);
        // Render quad
        glDrawArrays(GL_TRIANGLES, 0, 6);
        // Now advance cursors for next glyph
        x += (ch.Advance >> 6) * scale; // Bitshift by 6 to get value in pixels (1/64th times 2^6 = 64)
    }
    glBindVertexArray(0);
    glBindTexture(GL_TEXTURE_2D, 0);
}

```

All of this gives the following output (`note I am rendering the string "TEST testpqli"`):

Normally, my output seen in the above picture would be the result of something the linked too tutorial describes as "we can disable blending to see what the actual rendered quads look like", and as my blending code is commented out this all seems right on track, but If I un-comment my blending code in my `RenderTextRenderer` function shown earlier (just the `glEnable(GL_BLEND);` and `glDisable(GL_BLEND);` lines) then the output is the exact same, except the "text" becomes slightly more transparent when looking around the scene with things in the background like trees now been shown through the "text", and if I look at the sky the "text" loses its green color and become white as seen in the bellow image:

But if I then next un-comment specifically the line of code `glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);` the "text" completely disappears instead of solving the issue, as seen in the following image:

Therefore I have suspicions the issue lies with the `glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);` call or something to do with blending in general. Can anyone see where I have gone wrong? any advice is much appreciated.

# Answer
> 1 votes
In your `text` shader, you've forgot to set the `sampler2D` uniform's index. Each sampler in a shader need to be set to a specific index value, either at the creation of the shader (at the startup of the application) or each frame (not necessary, but possible). Whenever a sampler should be used in a shader, OpenGL needs to know what sampler to use, depending on which texture unit that has been set as the active (by calling `glActiveTexture()`).

Below I've added a working `RenderTextRenderer` function, with an added function call that sets the index of the texture sampler. It is set every frame but, like I wrote, it isn't necessary to do that. I do it only for demonstration purpose.

```
void TextRenderer::RenderTextRenderer(const Shader& shader, const RenderingEngine& renderingEngine, const Camera& camera)
{
    // Enable blending and set the blend function so that the text is rendered instead of the quads
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    // Disable the depth test since the text is being rendered in 2D
    glDisable(GL_DEPTH_TEST);

    this->TextShader.Bind();
    this->TextShader.UpdateUniformsTextRenderer(renderingEngine);

    /**
    * NEW CODE
    * Set the sampler named "H_text" to have index 0
    * When glActiveTexture(GL_TEXTURE0) is called, and a texture is later bound,
    * OpenGL is being told that the sampler named "H_text" should use that specific bound texture
    */
    glUniform1i(glGetUniformLocation(TextShader.GetShaderData()->GetProgram(), "H_text"), 0);

    RenderText("TEST testpqli", 20, 20, 1);

    // Enable the depth test again so that the 3D rendering will be correctly rendered in the next frame
    glEnable(GL_DEPTH_TEST);

    /**
    * Optionally disable the blending
    * Can be removed since the 3D world might have some parts that needs to be rendered (semi-)transparent
    */
    glDisable(GL_BLEND);
}

```

**Result**:

As you can see, the text is being rendered upside-down. To get the text to render correctly, you just need to edit the UV coordinates a bit, in the `Rendertext` function, at the point where the vbo is to be updated.

```
// Current UV setup
GLfloat vertices[6][4] =
{
    { xpos,     ypos + h,   0.0, 1.0 },
    { xpos + w, ypos,       1.0, 0.0 },
    { xpos,     ypos,       0.0, 0.0 },

    { xpos,     ypos + h,   0.0, 1.0 },
    { xpos + w, ypos + h,   1.0, 1.0 },
    { xpos + w, ypos,       1.0, 0.0 }
};

// Fixed UV setup, notice that the Y-element of the UV coordinates are flipped
GLfloat vertices[6][4] =
{
    { xpos,     ypos + h,   0.0, 0.0 },
    { xpos + w, ypos,       1.0, 1.0 },
    { xpos,     ypos,       0.0, 1.0 },

    { xpos,     ypos + h,   0.0, 0.0 },
    { xpos + w, ypos + h,   1.0, 0.0 },
    { xpos + w, ypos,       1.0, 1.0 }
};

```

---
Tags: c++
---


title: How to stream a game inside an app

text:
# Question
Title: How to stream a game inside an app
I would like to build an app like the onw downloadable from here https://playhatch.com/. How is it possible, technically speaking, to achive such result? Need I to implement some instant app feature? Need I to instantiate a kind of android runtime like a "mini docker image"? What's the technical concept which allows to implement such a feature?

Many thanks

# Answer
> 1 votes
One way I can think of, is using javascript. Assuming multiple games made with javascript, you can make a "docker" app, that includes all thoses, possible as files in the hard drive, and you can play any of them on-demand using javascript. You can also use the same method to download games from a website, although this may affect the age rating of your game, and if not handled well, may not be allowed in some Stores. This of course means that whenever you want to try a new game, you'd have to wait some time for it to download, similarly to how android handles the Play Store.

I haven't used the app that you mentioned, but if by "streaming" it means you are playing the game while it downloads, then you have to make the game in such a way that its playable with some of the assets, and while the user is playing it, it keeps downloading new ones. You'd have to separate the game in chunks like "basic" and "extra" or something similar.

You could probably do it with native code as well, but it would behave very similarly to the Play Store (for android), and it may not be allowed in some stores.

# Answer
> 1 votes
The way this particular app works is as a "thin client"

The software running on your local device is just a relay. It accepts your inputs and sends them to a remote server.

The game running "inside" the app is actually running on that server. It accepts the relayed input and uses it to update the game state, and streams the resulting rendered video to your device for display.

This is similar to how the old game streaming service OnLive worked, a model which is now most famously used by Google Stadia.

With this model the game can run on hardware vastly more powerful than the device the player is holding, but at the cost of lots of bandwidth to transmit the rendered view, and latency from the back-and-forth communication (and compression/decompression) involved.

As for how to implement your own steaming platform in this vein, my advice would be: do not do this.

Doing this well, managing the sheer bandwidth demands and optimizing latency, takes an immense investment in engineering and infrastructure — a Google-scale project. If you have to ask how to do it on StackExchange, then it is very likely you do not have the resources to pull it off successfully.

A better bet may be to evaluate existing, battle-tested streaming platforms, to see if any of them would meet your needs, then release your game on that platform. Let the experts in streaming handle that part, so you can focus on your game.

---
Tags: appstore, streaming
---


# Question
Title: SDL window crashes when mouse goes below a certain point
I added code to check the rgb values of my surface, and whenever i call the function it seems to work fine! the only problem is that whenever the mouse goes under y = 400 the entire window crashes... Right now the program outputs the rgb color of the pixel on the screen, and when it goes below 400 one or all of the pixel values are 0, and then the program crashes. I have no ideas why this is happening. Any help is appreciated! Heres the github repo! https://github.com/jcsq6/SDLGame not much has been done except a couple classes to make my life easier in SDL :)

```
int* texture::getPixel(int x, int y){
    static int Color[4];
    SDL_PixelFormat *fmt;
    Uint32 temp, pixel;
    Uint32 *pixels = (Uint32 *)Surface->pixels;
    Uint8 red, green, blue, alpha;

    fmt = Surface->format;
    SDL_LockSurface(Surface);
    pixel = pixels[(y * Surface->w) + x];
    SDL_UnlockSurface(Surface);

    temp = pixel & fmt->Rmask;
    temp = temp >> fmt->Rshift;
    temp = temp << fmt->Rloss;
    red = (Uint8)temp;

    temp = pixel & fmt->Gmask;
    temp = temp >> fmt->Gshift;
    temp = temp << fmt->Gloss;
    green = (Uint8)temp;

    temp = pixel & fmt->Bmask;
    temp = temp >> fmt->Bshift;
    temp = temp << fmt->Bloss;
    blue = (Uint8)temp;

    temp = pixel & fmt->Amask;
    temp = temp >> fmt->Ashift;
    temp = temp << fmt->Aloss;
    alpha = (Uint8)temp;

    Color[0] = red;
    Color[1] = green;
    Color[2] = blue;
    Color[3] = alpha;

    return Color;

```

}

it's worth noting that when I call this function, the input y and x values are the mouse's position.

# Answer
According to the SDL Documentation, your casting of

```
Uint32 *pixels = (Uint32 *)Surface->pixels;

```

only works if your `surface->format->BytesPerPixel == 4`. Your `BytesPerPixel` appears to be 3. Another clue as to it being only 3 bytes is that your `aMask == 0`.

Your pixel array is only `3*N` bytes wide, where `N` is the number of pixels. Since you're casting to a `Uint32*`, any accesses into the array assume that each pixel is 4 bytes wide, and you'll access elements between `[pixels, pixels + 4*N)`. Your actual array only takes up space between `[pixels, pixels + 3*N)`.

According to the SDL Doc linked above, your bytes should therefore be accessed as 3-tuples of `Uint8`. Change your code like this:

```
int* texture::getPixel(int x, int y){
    static int Color[4];
    Uint8 *pixels = (Uint8 *)Surface->pixels;
    Uint8 red, green, blue;

    SDL_LockSurface(Surface);
    red   = pixels[(y * Surface->w) + x    ];
    green = pixels[(y * Surface->w) + x + 1];
    blue  = pixels[(y * Surface->w) + x + 2];
    SDL_UnlockSurface(Surface);

    // since each R, G, B value takes up a full Uint8, I'm not
    // sure if you need to mask, downshift, then upshift the values
    // at all.

    // setting opacity to 0xff, for full-opacity

    Color[0] = red;
    Color[1] = green;
    Color[2] = blue;
    Color[3] = 0xff;

    return Color;
}

```

Let me know how this works. I don't have any experience with SDL, so this may need adjustment.

Your use of a `static` array to return the colors is suspect, but I kept that to mimic your code. It's also strange to stick color values: `Uint8`s, into an array of `int`s, but I kept that as well to match your code. I didn't know what you were using this array for, and wanted to change as little as possible.
> 0 votes

---
Tags: c++, graphics-programming, sdl2
---


title: Cannot select desired Unity version

text:
# Question
Title: Cannot select desired Unity version
I'm coming back to Unity after around a 4 month break and finding that opening my past Unity projects/ creating a new project will not create it in the Unity version I select(v2018.4), and instead always creates it in v2018.1, despite having both installed.

In this image, the file I'm speaking about is RPGprojr.

I have tried reinstalling the 2018.4 version and deleting the 2018.1 version altogether, to no avail.

# Answer
Try opening Unity itself (not Unity Hub) in the desired version (2018.4), and then open your project.

If you haven't changed the default location during installation, Unity can be found in "C:\Program Files\Unity\Hub\Editor\\Editor\Unity.exe".
> 1 votes

---
Tags: unity
---


title: Viewport Navigation controls

text:
# Question
Title: Viewport Navigation controls
I'm encountering an issue: I cannot move into my view with `W`, `A`, `D`, `S`. However `UP`, `LEFT`, `RIGHT`, `DOWN` arrows work. What's wrong?

Here's my viewport navigation configuration:

Viewport navigation key binding

# Answer
When in doubt, always consult the documentation:

> ## Game-style
>
> The WASD controls will feel natural to those who are used to playing shooter games on the PC. They are enabled by default and can be used **whenever you are holding RMB**. This means you will still use RMB to turn the camera while navigating in this way.
>
> These controls are mirrored on the arrow keys and num pad to provide alternate access to them.
>
> All of these controls are only valid in a Perspective viewport, and by default **you must hold RMB** to use the WASD game-style controls.

Here, "RMB" means the right mouse button (or secondary button, if you're using a different mouse configuration).
> 1 votes

---
Tags: unreal-4
---


title: Topdown Game Collision Detection

text:
# Question
Title: Topdown Game Collision Detection
I am working on a simple game with topdown movement, but I am unable to get the collisions to work properly. I know the collision detection itself works, but the constraining of the player is where I fail. It gets close to working, but on the corners it still clips into the squares. Also, if I add more squares for the player to collide with, it fails completely. I am programming this game in Processing, which uses Java. Here is my code:

```
void Collide(float WallX,float WallY,float WallWidth,float WallHeight) {

  this.WallX = WallX;
  this.WallY = WallY;

  this.WallWidth = WallWidth;
  this.WallHeight = WallHeight;

  float TestX = PosX;
  float TestY = PosY;

  if(PosX <= WallX) {
    TestX = WallX;
    CollideLeft();
  }

  if(PosX >= WallX+WallWidth) {
    TestX = WallX+WallWidth;
    CollideRight();
  }

  if(PosY <= WallY) {
    TestY = WallY;
    CollideUp();
  }

  if(PosY >= WallY+WallHeight) {
    TestY = WallY+WallHeight;
    CollideDown();
  }

  fill(255,0,0,150);
  ellipse(TestX,TestY,16,16);

  Dis = sqrt(sq(TestX-PosX) + sq(TestY-PosY));

  println("Dis= ",Dis,", TestX= ",TestX,", PosX= ",PosX,", TestY= ",TestY,", PosY= ",PosY);

}

boolean CollideLeft() {

  if(Dis <= Radius+5) {
    //PosX = WallX-Radius;
    return CollideLeft = true;
  }
  else {
    return CollideLeft = false;
  }

}

boolean CollideRight() {

  if(Dis <= Radius+5) {
    //PosX = WallX+WallWidth+Radius;
    return CollideRight = true;
  }
  else {
    return CollideRight = false;
  }

}

boolean CollideUp() {

  if(Dis <= Radius+5) {
    //PosY = WallY-Radius;
    return CollideUp = true;
  }
  else {
    return CollideUp = false;
  }

}

boolean CollideDown() {

  if(Dis <= Radius+5) {
    //PosY = WallY+WallHeight+Radius;
    return CollideDown = true;
  }
  else {
    return CollideDown = false;
  }

}

void Move() {

  if(MoveRight && !CollideLeft) {
    MoveX(1);
  }
  if(MoveLeft && !CollideRight) {
    MoveX(-1);
  }
  if(MoveDown && !CollideUp) {
    MoveY(1);
  }
  if(MoveUp && !CollideDown) {
    MoveY(-1);
  }

}

```

# Answer
> 2 votes
It's hard to tell, but it looks like you are only ever testing for one collision. You need to maintain a list or collection of walls in order to test each one for the collision. That may be why it fails upon adding more walls. Once you have a collection of the walls you would test the player against each one before moving.

One way to solve the overlapping issue is inside of the collision code, calculate an overlap amount. The overlap amount could be calculated for the x by taking the distance between the specific wall currently being tested and the player and then subtracting the wall's width added with the player's width divided by 2. You would take the absolute values of the distance and the entire equation.

$$overlapX=| |distance\_{player\rightarrow wall}| - \frac{player\_{width}}{2} + \frac{wall\_{width}}{2}|$$

In order to use this, you would first move the player in the x, test for collision with each wall, and then for each tested collision add/subtract this overlap. Whether you add or subtract can be determine by whether the player is to the left or right of the wall. To the left, subtract the overlap to push the player out to the left. To the right, add the overlap to push the player out to the right.

For an example, consider if you had a wall at 32,32 with a width and height of 4. The player is at 26,32 with a width and height of 2. The player then moves with a x velocity of 4, placing him at 30,32. Then collisions with walls are tested. The collision with the wall described occurs, and the overlap is calculated to be ||(32 - 30)| - (2 + 1)| = 1. Since the player is to the left of the wall, this overlap is subtracted from the player's position.

This method is not good with dealing with high velocities, as in the above example if the velocity was 7, then the player would end up past the center of the wall, and pushed out the right, thus tunneling through the wall. If you do end up having higher velocities than the half width's/height's of your walls, then you may want to consider breaking the velocity down into "steps" which are of a known safe velocity for all objects in your game, and attempting to move the player in these smaller steps in the same movement function call.

Here's some resources I found helpful:

https://developer.mozilla.org/en-US/docs/Games/Techniques/2D\_collision\_detection

Similar to what I outlined above.

https://www.gamedev.net/articles/programming/general-and-gameplay-programming/swept-aabb-collision-detection-and-response-r3084/

Another way to deal with high speed objects or small walls that is slightly more involved.

---
Tags: java, 2d, collision-detection, collision-resolution, processing
---