# Question
Title: Can I use "Creative Comons BY-NC" licences music in my Freemium game?
According to creativecommons.org, a CC BY-NC license stands for

> a creative commons license that prohibits you to use the material in "Commercial Purposes"

...and for the *Commercial Purposes* they have defined it in this way:

> A commercial use is one **primarily** intended for commercial advantage or monetary compensation.
>
> *(emphasis mine)*

As Freemium games can be played without spending even a penny, and the in-app purchases are only meant to accelerate the process, is this game still intended as a Commercial project with the definition given above, and thus should I ignore using such music?

My interpretation is that my use the song is not intended for a commercial purpose.

# Answer
> 5 votes
As defined by the Creative Commons:

> NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation.

The "intent" here is the developer's intention, not the player's. It does not matter if a particular player - or even the vast majority of your players - intend to play your game for free. What matters is if you intend to use your game to generate revenue.

**I would argue that the Freemium business model does not mean the game is NonCommercial,** and that in most cases the primary intention/direction is still commercial advantage or monetary compensation.

The reason we regard Freemium as a "business model" and not as some kind of charity offer is that we recognize that non-paying players are not incidental to the revenue of a game, but in fact a key part of attracting, converting, and retaining paying players, or getting more views of paid ads.

By allowing the game to be played for free, we lower the bar for acquiring players, benefit from viral marketing by these players, keep our servers/leaderboards active & populated with partners/rivals/audiences for our paying players to interact with, and increase the "social stickiness" that keeps players coming back.

All of these factors help improve our expected revenue from the game, so the free aspect frequently supports, rather than opposes, a profit motive.

By including CC-NC music in your game, it's reasonable to suppose you're hoping to improve the player experience and perceived quality of the game, resulting in more acquisition & retention of players and better conversion rates to paying players. ie. **Even though you're not selling the licensed content itself, you intend that the inclusion of this licensed content in your product will produce monetary compensation**.

That would, by my reading, violate the terms of a CC-NC licence.

**I am not a lawyer and this is not legal advice**. You may well find others who interpret the relationship of NonCommercial use to Freemium apps differently.

But that is itself a problem.

If the interpretation is unclear, the creators of the CC-NC content you've used could interpret that your use of their creations goes outside the scope of the licence they've granted you, and take legal action against you.

**You could then be put in the position of having to defend your interpretation of NonCommercial-vs-Freemium in court**, at substantial cost of time and resources even if your position is correct. Very likely, this is not a possibility you want to face.

So, how can we avoid this?

1. **Contact the creators/licensors** of the content you want to use, and ask for a licence to use the content in your case.

A Creative Commons licence does not bar licensors from *also* offering the content under other licence conditions, so CC-NC might not be your only option.

If the licensors agree that your use is within their intention for sharing the content, then they should have no problem granting you a licence specific to your case without the interpretation risks. (Make sure you get this in writing, so you're protected in case of a misunderstanding or change of heart)

If they don't agree, then you may be able to negotiate other licence terms. As long as you both agree to a common set of terms, there should be no risk of legal fallout.
2. **Consult a lawyer** with expertise in these matters / in the relevant legal jurisdiction. They'll be able to tell you more authoritatively than we Internet randos can whether you're on solid footing or if you might be risking a (losing) battle in court.
3. **When in doubt** \- if you can't get agreement from the licensors nor reassurance from a lawyer - err on the side of caution:

* Use content that explicitly permits commercial use
    * Pay creators to license their works for use in your game
    * Or, do not include a paid/ad-supported aspect to your game at all (making it "Free" as in beer, not "Freemium"/"F2P"), so it cannot be interpreted as commercial

    (If this is not a step you're willing to take, then it's a pretty clear sign that your intention *is* commercial - nothing wrong with that, it's just good to know where you stand so you can choose licensed content accordingly)

---
Tags: music, licensing, free-to-play
---


# Question
Title: split/divide/extract/separate mesh indices&vertex in n
I'm totally lost. I'm trying to split/divide/extract/separate a mesh into sub-meshes via bbox test. But I just realized that I need to properly split indices and vertex and I have no idea how o.o... here is the splitting code that "fails" because my indices/vertex needs a proper re-arranging that I have no idea how to solve o.o.

```
for (auto &box:aabb) { //// list of bboxes
    for (int indi = 0; indi < mIndices.size(); indi += 3) { /// get 3 indices for 1 triangle
        offX = mIndices[indi];
        offY = mIndices[indi + 1];
        offZ = mIndices[indi + 2];
        /// Check if any of the vertex is inside the box
        if (box.contains(mVertex[offX]) || box.contains(mVertex[offY]) || box.contains(mVertex[offZ]))
           {
            /// bellow code is wrong, I'm over-adding vertex even if they
            /// exist, and I'm adding wrong indices because new mVertex/indices arrays are of
            /// different sizes to source one... oh dear... I need to add an only missing vertex,
            /// and indices re-mapped to proper existing/new vertexes.

            box.mVertex.push_back(mVertex[offX]);
            box.mVertex.push_back(mVertex[offY]);
            box.mVertex.push_back(mVertex[offZ]);
            box.mIndices.push_back(offX);
            box.mIndices.push_back(offY);
            box.mIndices.push_back(offZ);
        };
    }
}

```

If any1 could help with this, this would be amazing. I'm not worried if 1 triangle is being duplicated across 2 bounding boxes or even more. As the aaBB can have random positions. I just need each aabb with its own vertex/indices set that can create mesh.

EDIT1.

The only way I could think of doing it is this \> it feels quite..."bad tho...

```
void aabb::addTriangle(QVector3D &x, QVector3D &y, QVector3D &z) {
if (mVertex.contains(x)) {
    mIndices.push_back(mVertex.indexOf(x));
} else {
    mVertex.push_back(x);
    mIndices.push_back(mVertex.size() - 1);
}
if (mVertex.contains(y)) {
    mIndices.push_back(mVertex.indexOf(y));
} else {
    mVertex.push_back(y);
    mIndices.push_back(mVertex.size() - 1);
}
if (mVertex.contains(z)) {
    mIndices.push_back(mVertex.indexOf(z));
} else {
    mVertex.push_back(z);
    mIndices.push_back(mVertex.size() - 1);
}

```

}

EDIT 2. Thanks to ErnieDingo I'm now not copying vertex in to each aabb object, but only adding triangles(3indices) that if either is being contained by bbox. Then I pass pointer to base mesh vertexArray for further tests down the line

# Answer
Looking at your code, i will ask, are you referencing the verts local to your BBOX. I assume you are. Your indices are incorrectly indexing. Don't add the indices you tested with, your index values will be the new index of your vertices you have added.

ALA, if index 6,7 and 8 are added to box1, you would need to make them 0, 1 and 2 in your bounding box when you add the vertices.

```
box.mVertex.push_back(mVertex[offX]);
box.mVertex.push_back(mVertex[offY]);
box.mVertex.push_back(mVertex[offZ]);

box.mIndices.push_back(box.mVertex.size() - 3);
box.mIndices.push_back(box.mVertex.size() - 2);
box.mIndices.push_back(box.mVertex.size() - 1);

```

Edit: I meant, add box.mVertex.size(), not mVertex.size()
> 0 votes

---
Tags: opengl, mesh
---


# Question
Title: How can I find the distance from bezier curve anchor points to control points for a circle approximation and their positions
From the image below, I have represented a circle by a closed bezier curve made of two cubic bezier segments. I am aware that a bezier curve cannot represent a perfect circle. How can I calculate the distance from the anchor points to the control points based on the distance from both anchor points to give a close approximation of a circle?

Also how can I use the calculated distance to find the positions for the control points?

# Answer
> 2 votes
Please don't forget to search for existing information on your problem area before posting new questions - especially when you're asking about something fundamental that's surely been answered before.

That said, I'd like to take a different approach than the answers I linked above.

These past answers seem to choose their control points so that the midpoint of the Bézier curve lies at the midpoint of the circular arc. That means that the half-curve on either side of the midpoint bulge out beyond the circle.

That's not bad, but we can do better, in terms of minimizing the maximum error. If we undershoot a little at the midpoint, we reduce the overshoot on either side, keeping our Bézier curve closer to the circle overall.

To do this, instead of kissing the arc at \\$t = \frac 1 2\\$, we'll cross it at \\$t = \frac 1 3\\$ and \\$t = \frac 2 3\\$. Our curve will weave back-and-forth across the circle we want to follow instead of staying strictly outside it.

I'll spare you the full derivation, but to do that, we want our control handles to have the following length:

$$l = \frac {3\sqrt{\sin^2\theta - 70 \cos \theta + 70} - 17 \sin \theta}{15 - 12 \cos \theta} \cdot r $$

Where \\$\theta\\$ is the angle of the circular arc (180° or \\$\pi\\$ radians if you use just two anchor points at opposite ends of the diameter), and \\$r\\$ is the radius of the circle (half the distance between the anchor points if they're at opposite ends of a diameter)

For the 180° case that translates to \\$l = \frac {2 \sqrt {35}} 9 \cdot r \approx 1.314684396 \cdot r \\$, with a maximum error of about 1.40%

(For comparison, the answers linked above use \\$l = \frac 4 3 \cdot r \approx 1.333333 \cdot r\\$ which suffers an error of about 1.83%)

If you care about fidelity, I'd strongly recommend using more than two segments to represent the circle. Even just 3 segments brings the error down to 0.12%, 4 segments brings it to 0.02%

If your Bézier anchor point is at \\$A\_i = (c\_x + r \cdot \cos {\alpha}, c\_y + r \cdot \sin \alpha)\\$, with \\$(c\_x, c\_y)\\$ the center of the circle, and \\$\alpha\\$ the angle of the point counter-clockwise from the positive x-axis, then its corresponding anchor point is at \\$C\_i = A\_i \pm l \cdot (-\sin \alpha, \cos \alpha)\\$, with the sign of the \\$\pm\\$ being + for the start point, and - for the end.

---

Here's an animation of this method in action:

And here's the code I used:

```
// OnValidate is called by the editor automatically when the user modifies
// the inspector parameters like center, radius, and circleCoverageDegrees.
// Here it's used to update our array of Bézier control points.
private void OnValidate() {
    BezierCircle(center, radius, circleCoverageDegrees, 0, bezierPoints, 0);
    BezierCircle(center, radius, 0, -circleCoverageDegrees, bezierPoints, 3);
}

// This method populates 4 cubic Bézier control points into an array,
// so that the resulting curve approximates a circular arc.
static void BezierCircle(
               Vector2 center, float radius,
               float startAngleDegrees, float endAngleDegrees,
               Vector2[] points, int startIndex
) {
    // First, compute how long our tangents should be to best fit this arc.
    float angle = Mathf.Abs(endAngleDegrees - startAngleDegrees) * Mathf.Deg2Rad;
    float sine = Mathf.Sin(angle);
    float cosine = Mathf.Cos(angle);
    float tangentScale = radius * (3 * Mathf.Sqrt(sine * sine - 70f * cosine + 70) - 17 * sine) / (15 - 12 * cosine);
    tangentScale *= Mathf.Sign(endAngleDegrees - startAngleDegrees);

    // Place the start anchor point and its control point relative to it.
    angle = Mathf.Deg2Rad * startAngleDegrees;
    sine = Mathf.Sin(angle);
    cosine = Mathf.Cos(angle);

    points[startIndex] = center + radius * new Vector2(cosine, sine);
    points[startIndex + 1] = points[startIndex] + tangentScale * new Vector2(-sine, cosine);

    // Place the end anchor point and its control point relative to it.
    angle = Mathf.Deg2Rad * endAngleDegrees;
    sine = Mathf.Sin(angle);
    cosine = Mathf.Cos(angle);

    points[startIndex + 3] = center + radius * new Vector2(cosine, sine);
    points[startIndex + 2] = points[startIndex + 3] - tangentScale * new Vector2(-sine, cosine);
}

```

---
Tags: unity, mathematics, curves
---


# Question
Title: How do I render a cylindrical world space onto a flat, 2D view port in Unity?
The question is just a logical extension of this question.

So, how should I render a cylindrical world space onto a flat, 2D view port in Unity?

Thank you.

# Answer
> 1 votes
The coordinates of any point on a cylinder can be expressed as (`r`, `θ`, `z`), where `r` is the constant radius of the cylinder, `θ` is the angle around the z-axis and `z` is the "height" of the point. You can convert that into 2D coordinates by throwing out `r`, treating `θ` as `x` and `z` as `y`.

Keep in mind that `θ` will be between 0 and 2π (or 0 and 360), so you'll need to scale that the appropriate width to look reasonable when projected onto the `x` coordinate. You'll also need to deal with the wraparound mathematically, probably by using the modulus operator. This blog post may be useful in coming up with ideas for how to deal with such edge cases.

You probably don't have cylindrical assets, but instead have 2D assets. As such, you should just be able to use them like you would any other 2D asset in Unity.

---
Tags: unity, 2d, rendering, camera, viewport
---


# Question
Title: How to render two or more images on a video frame in the same draw call using Metal?
I'm a newbie to graphics programming and I have an existing code base which basically takes frame from video and passes it to a metal shader where effects (like colour changes) happen.

What is currently happening?

I can use the existing method to send an image as a texture and it gets blended with the original frame and a new frame is created.

What do I want to achieve?

I want to place multiple images on the original image in the same drawing call. What would be the best way to achieve this? Should I change the existing render pipeline or can the shader handle it?

# Answer
It would help if you showed us some of your current code. But in general, you can add textures to your shader and then set them up in code by using `-[MTLRenderCommandEncoder setFragmentTexture:atIndex:]`. It may make sense to send them as a texture array, in which case you'd use `-[MTLRenderCommandEncoder setFragmentTextures:withRange:]`.
> 0 votes

---
Tags: metal
---


# Question
Title: Memory Management when changing Game States
I am just wondering what are some of the issues of loading and freeing the memory every time player changes the game state?

Or is it better to load all the resources at once?

# Answer
> 0 votes
The answer is game specific, and vastly depends on what you define as a "state". Does your game "change state" when moving from the main menu to the game itself? Then you should probably unload resources for the main menu and load ones meant for the game.

Does "game state" mean you moved from your game's "attack phase" to "defend phase" which have no new assets? Then probably you don't need to load or unload anything.

Here are some tips and things to remember:

* Machines have plenty of memory, as in, if you want to keep an image loaded for a little longer than needed, its not the end of the world.
* No matter what, do **not** attempt to load/unload assets every frame. It can only lead to disaster. If you need an asset every frame for as long as you are in the main menu, load it when the main menu starts, and unload it when you move to a different menu. If the asset is being used everywhere in the game, load it when the game starts, and unload it when the game ends.
* Depending on the language, unloading assets could be handled by a garbage collector, so even if you think you've unloaded some assets, they could still be in memory, waiting the GC to delete them.
* Loading assets means keeping the CPU busy for some time, do it only when you can afford that (like loading screens)

---
Tags: resource-management, memory
---


# Question
Title: Is it possible to achieve the same performance of CUDA on OpenCL?
I am planning on porting some of my CPU code to GPU. I want my code to run on all GPUs, so openCL seems to be the right choice. Will I be able to achieve the same performance as of CUDA in openCL?. What framework would do better if I want to support all GPUs?

# Answer
It's performance vs. compatibility.

CUDA only works on "CUDA enabled" graphics cards. That means CUDA code can be sure that certain hardware features are present and can get more out of the GPU.

However, it also means it won't work everywhere. For NVIDIA cards, that means it won't work on cards older than the GeForce 8800 (from 2006, so not *that* bad). However, all AMD and Intel cards are right out. If we disregard Intel (because it's mostly cheapo laptop GPUs), that's roundabout half of GPUs out there which it won't work on.

So if you're a scientist, writing code to run on your own PC with a NVIDIA GPU, CUDA would be faster - but for games, you probably want to use OpenCl instead.
> 1 votes

---
Tags: software-engineering, gpu, cuda
---


# Question
Title: Whay can my player only move in one direction?
I am trying out the Phaser 3 framework and I dont know why my player Object moves only left but not right... Here's another weird thing: if I swap code segmentd for move right and move left, then I can move right but not move left.

Why is it so and how can I fix it?

Here is my code:

```
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Making your first Phaser 3 Game - Part 1</title>
    <script src="phaser.js"></script>
    <style type="text/css">
        body {
            margin: 0;
        }
    </style>
</head>
<body>

<script type="text/javascript">

    var config = {
        type: Phaser.AUTO,
        width: 800,
        height: 1051,
        physics: {                              //for physics system
          default: 'arcade',
          arcade: {
            gravity: { y: 300},
            debug: false
          }
        },

        scene: {
            preload: preload,
            create: create,
            update: update
        }
    };

    var player;
    var platform;
    var cursor;

    var game = new Phaser.Game(config);

    function preload()
    {
          this.load.image('background','MyZombiePlatformer/background.jpg');
          this.load.image('platform','MyZombiePlatformer/platform.png');
          this.load.image('ZombieIdle','MyZombiePlatformer/zombie_idle.png');
          this.load.spritesheet('ZombieWalk', 'MyZombiePlatformer/zombie_walk1.png',
          {
            frameWidth: 80, frameHeight: 110
          }
        );

    }
    function create()
    {
          this.add.image(1000,525.2,'background');

          platform = this.physics.add.staticGroup();
          platform.create(1000, 900, 'platform'). setScale(5).refreshBody();

          player = this.physics.add.sprite(10,50,'ZombieIdle');
          player.setCollideWorldBounds(true);

          cursor = this.input.keyboard.createCursorKeys();

          this.anims.create(
            {
              key: 'idle',
              frames: [{key: 'ZombieIdle', frame: 0}],
              frameRate: 1
            }
          );

          this.anims.create(
            {
              key: 'walk',
              frames: this.anims.generateFrameNumbers('ZombieWalk',{start: 0, end: 1}),
              frameRate: 2,
              repeat : -1
            }
          );

          this.physics.add.collider(player,platform);

    }
    function update()
    {
        //this segment doesnt work..be it any left or right walk logic
        if(cursor.right.isDown)
        {
          player.setVelocityX(160);
          player.anims.play('walk',true);

        }

        //this segment always works be it left walk or right walk logic
        if(cursor.left.isDown)
        {
          player.setVelocityX(-160);
          player.anims.play('walk',true);

        }

        else
        {
          player.setVelocityX(0);
          player.anims.play('idle',true);
        }

    }

</script>
</body>
</html>

```

# Answer
> 2 votes
I think your problem is that your understanding of `if` and `else` is slightly wrong.

```
    if(cursor.right.isDown) {
        // move the player
    }

    if(cursor.left.isDown) {
         // move the player
    } else  {
         // stop the player
    }

```

I think you assume that the `else` path is executed when neither of those two conditions is true. But that's incorrect. It only applies to the second condition. What actually happens here is:

1. `cursor.right.isDown` is `true`, so we execute the `if` branch of this condition.
2. We set the velocity to right
3. `cursor.left.isDown` is `false`, so we execute the `else` branch of this conditions
4. We set the velocity we just set to right back to zero.

Try this code instead:

```
    // when the right button is pressed, accelerate to the right
    if(cursor.right.isDown)
    {
      player.setVelocityX(160);
      player.anims.play('walk',true);
    }

    // when the left button is pressed, accelerate to the left
    if(cursor.left.isDown)
    {
      player.setVelocityX(-160);
      player.anims.play('walk',true);
    }

    // when neither the left button nor the right button is pressed, stop!
    if(!cursor.left.isDown && !cursor.right.isDown)
    {
      player.setVelocityX(0);
      player.anims.play('idle',true);
    }

```

---
Tags: phaser
---


# Question
Title: Manage massive items game data in an Android Idle Game
I'm working on an Android Idle game, with many items that user can buy in each level, that each of them has more than 50 levels who can be updated by the user. Each item in each specific level can produce some value of a specific unit every second in the game. Currently, I manage this massive game data (Not user's data) in the Dictionary data structure in code, that each item has an instance of Item class for the value. Item class has many properties like for example multidimensional arrays of levels data. I initialize this dictionary each time user opens the game.

The problem is we want to balance the game, and it needs to change this massive data many times for test. with the current structure, it takes hours to edit data each time.

My question is, is that a better way to manage massive items game data to can be simply replaced for example by data from an excel's sheets in Unity? Thanks.

# Answer
The problem you are running into is a very common one, and the reason why the software design rules around avoiding Magic Numbers and Magic Strings exist. The common solution to the problem is to move the offending value into a single location so it is easier to change. This is usually done through the use of a file for the data (constants file, config file, json file loaded at start, etc). Then, instead of referencing the value directly, your code can be updated to reference the loaded data.

Depending on how deep of a dive into Object Oriented Programming you want to do, you can drive a lot of your code through these kinds of files. A couple years ago I built out a utility for a game I was designing, and because I was still developing technologies, buildings, skills, etc for it, I wanted to make it as generic as possible. I created the basic shell for each object, and populated any important values from a file loaded at startup (for example, my code didn't know that a Barn existed, but it did know that it could have a list of buildings loaded from a file, which happened to contain a Barn object).

The more OOP you go in this way, the easier it is to change values and inputs, but the more complex the code needs to be in terms of error handling. In my example, let's say that a user's data I am loading has reference to the Research Station building, but my buildings file no longer has that building in it. I need to be able to handle that situation, however I decide is appropriate. In your scenario, what happens if you dynamically load an upgrade that has 50 levels, but when your player starts up, their save has 51 levels of upgrades for it?

I'll also add that the vast majority of idle games with upgrades use a multiplier instead of fixed pricing for their upgrades. instead of knowing the cost of each of the million upgrades, it knows that the upgrade cost is some formula like \*1.07^(upgrade level) I'm not certain from your post if you are hard coding them all, or if you are using a multiplier.
> 2 votes

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


title: Cannot assign values to variables (?)

text:
# Question
Title: Cannot assign values to variables (?)
I wouldn't say i'm new to unity or programming in general.. but right now i feel so stupid.

I have a simple enemy script. I instantiate object with another script, calling SettingUpCreep and giving it a list of waypoints. Then happens update object should move from one waypoint to another. But look at information in Console.

What's wrong with waypoints.Count in Update? Why does it increased? And it works only if list and nextPos are public. If i set it to private then other methods can't access it. There's nothing in it.

What's happening and why? I can't understand. Have i've done something wrong or just need more sleep?

```
List<Vector3> waypoints;
Vector3 nextPos;
int currentPoint = 1;

private void Update()
{
    moveToNextWaypoint();
}

void moveToNextWaypoint()
{
    Debug.Log("Update");
    Debug.Log("WP.count " + waypoints.Count + " NP" + nextPos);

    if (transform.position == nextPos)
    {
        if (currentPoint == waypoints.Count)
        {
            gameObject.SetActive(false);
        }
        else
        {
            currentPoint++;
            nextPos = waypoints[currentPoint];
        }
    }
    transform.position = Vector3.MoveTowards(transform.position, nextPos, 5 * Time.deltaTime);
}

public void SettingUpCreep(List<Vector3> list)
{
    Debug.Log("list.Count " + list.Count);
    List<Vector3> waypoints = new List<Vector3>(list.Count);

    for (int i = 0; i < list.Count; i++)
    {
        waypoints.Add(list[i]);
    }
    nextPos = waypoints[1];
    transform.position = waypoints[0];

    Debug.Log("WP.count " + waypoints.Count + " NP" + nextPos);
}

```

# Answer
This is a concept called Variable Shadowing and is a common problem with newer developers. Variables have a scope that represents where they exist and can be manipulated. A class-level variable (such as the three defined at the top of your file) can be used anywhere within the class, regardless of access level. In addition, we can tell the code to allow or disallow access to other parts of code with the public, private, internal, sealed, etc keywords.

However, there's also a scope beneath the class level: Method Level scope. There is not a rule that requires variables defined at the class level and the method level not to share a name (when they get translated into lower level code, that name disappears anyway, so the computer doesn't care). So your line of code that says

```
List<Vector3> waypoints = new List<Vector3>(list.Count);

```

is really defining a method-scoped variable call waypoints. This is not the same variable as your class-level variable also called waypoints. If you wanted to use the class-scp\[ed variable instead, remove the variable definition of List from this line of code. That will tell the compiler to use the class-scoped variable instead. This may not fix all your issues, but it is definitely one problem.

The full stack trace of your error would be helpful to figure out any others.

EDIT: I was thinking about this a little further, and this example shows why having a coding standard for variable naming is valuable.

For example, in my team's coding standard, there is a visible difference between the names of variables.

Properties (aka public, class-scope variables) are capitalized (e.g. Waypoints)

private class-level variables are camel case with an underscore (e.g. \_waypoints)

method-scoped variables are camel case. (e.g. waypoints).

If you followed a standard like this, it would be more obvious which of the variables you were assigning to. Naming things the exact same is still not a good thing to do, but sometimes we aren't paying attention and fail to realize we're doing it.
> 7 votes

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


title: Timed Line Drawing

text:
# Question
Title: Timed Line Drawing
I'm trying to program a remake of the classic Missile Command Atari game from scratch, but I've run into a problem. So I have a function that can draw a line from one point to another. I figured I could use this for the missiles and meteors by having them drawn from their initial position to their current position, and then update their current position each time I render.

This works in the sense that I can see exactly what I want to be graphically rendered, but the issue is that the speeds are either too fast or slow. As the missiles/meteors become closer to falling/rising at a verticle slope, they are drawn almost instantaneously. On the other hand, as they have a slope closer to being y=x, they are drawn slower and slower. Can someone help me out? Here is my code for how I update the position each render: (initX/Y is initial position, x/y are current position, destX/Y is the destination position)

```
float dx = destX - initX;
float dy = destY - initY;
if (initX > destX) x -= speed;
else x += speed;
y = initY + dy * (x - initX) / dx;

```

# Answer
> 1 votes
This is simply combining three formulas Speed = dist/time pythagarus a^2 = B^2 + c^2 and y = mx + c

1. So dist moved each time is speed * time You define a speed for your object, the time is timediff between last update and this one
2. y = mx + c. Ignore C since don't care about where it might cross the x axis So y = mx So m (gradient) is ydiff/xdiff ydiff = starty - endy xdiff = startx - endx
3. Now this is where we combine.

The dist is the hypotinuse of the right angled triangle so Dist^2 = x^2 + y^2,

from above y = mx so dist^2 = x^2 + (mx)^2 Play around with algebra to get dist^2 = x^2 + m^2x^2 so dist^2 = x^2(1 + m^2) x^2 = dist^2/(1+m^2) x = sqrt(dist^2/(1+m^2))

SO get start and endpoint and calc gradient 'm' for time diff since last call calc distance then calc x increment as above calc y increment y=mx latestx+= x inc latesty+= yinc new line is from startx,y to latestposnx,y

# Answer
> -1 votes
Try to use the same mathematical apparatus, but add additional functions in the functions that would average the values vertically and horizontally.

---
Tags: mathematics, algorithm, graphics-programming, linear-algebra, projectile-physics
---


title: Picking targets for homing missles

text:
# Question
Title: Picking targets for homing missles
I'm developing 2.5D space shooter (3D objects, 2D gameplay). I'm searching for a way to pick targets for homing missiles.

There are two types of missiles: active-radar-guided and heatseekers. The first ones are relatively simple to implement: I search for a target once and then store it in the missile's navigation code. If object is destroyed or escapes missile's triangle of view, I seek for another target. Searching for target is costly, because I have to iterate through all game objects and eliminate ones behind the rocket or out of its "radar range". However, that happens rarely - only after launch and when missile loses the target from sight, so I guess it will be acceptable.

Now imagine heatseeker missile. Situation is different here - I have to make decision about flight direction on every frame - gather information about nearby heat sources, create some kind of heatmap, find hottest direction and navigate rocket towards it. This may degrade performance - especially if I have multiple missiles on scene and this is very likely scenario.

I thought of using collider as first-degree sieve to keep track of potential targets. This collider would have to be quite big but it would narrow down count of potential targets to 10-20 and I guess that should be acceptable for processing. However, I'm falling into problem of multiple colliders: I use one for regular collisions and I wouldn't want the other one to interfere. Also, I'm not sure what is the performance penalty for having a couple of big colliders on scene.

How can I solve the problem of picking target for missile every frame such that it won't have big impact on overall performance? Are the colliders correct path to follow? Or should I rely more on coding than on built-in features?

# Answer
> 1 votes
I would approach this by making use of the Layer Based Collisions to reduce the overhead of the target selection.

Add a Physics layer for Heat Source, and one for Radar Reflection.

In your standard seeker missiles, its collider or rays should only be registered with the Radar Reflection physics layer.

The same approach should be used for Heat-seeking missiles, but with the Heat Source layer.

---

I'd have to run some tests, but I think using a box collider trigger to reduce the number of possible targets in the layer and then checking the angle between their position and the position of the missile will probably be the most efficient way to simulate a detection cone, without actually attaching a hidden cone mesh to the front of each missile with a meshcollider.

For a 2.5d game you also have the option to set up multiple rays from the nose of the missile at different angles, and have the missile fly along until one of the rays returns a collision then have the missile turn or accelerate accordingly.

In your missile logic, `OnTriggerStay()`, or the `Physics.Raycast()` logic will automatically screen out any colliders not in that layer, reducing the number of object you have to check for your selection logic. If you only have one object, great! Lock on! If you have more than one, compare the two by whatever criteria you decide is important and choose one.

---

On a subjective note, the beauty of this approach is it allows for decoys and bad targets, but gives you easy control over what those things are.

For heat missiles, having them target the sun, lock onto the trail of other missiles, or IR decoys is relatively easy, as you just have to drop a collider in the Heat Source layer onto the object.

For radar, you get the same flexibility, allowing for behavior like missiles targeting an asteroid or pieces of debris because it got confused and got locked onto it instead.

It also lets you make certain things immune to one targeting method or the other. A stealth ship might not ever be a radar target, but be vulnerable to heat seekers. A ship that's not under thrust might only be vulnerable to radar missiles. A ship firing its laser might generate so much heat that all heat missiles nearby break from their target and re-target it instead.

These types of behaviors can make for more interesting game play.

# Answer
> 0 votes
Choosing between a collider and code would depend on the complexity of the collision shape. If primitive colliders are sufficient to specify the missile's tracking area, adding a collider will cause no more impact than adding any other collider to the scene.

However, if a cone-shaped missile search area is wanted, another approach is to search throughout the scene and populate a list of game objects at game start. From this, at intervals during the game, eliminate game objects that are either too far away or at a too far angle forwards (using `Vector3.Angle()`), and populate the list of targets each missile can see.

For the collider approach: create a list of all targets within the collider at each physics tick using `OnTriggerStay()` (if performance really does cause a problem, create a counter that only updates the list every 15-30 physics ticks).

There is no need for complex heatmap imagery/simulation. If all heat sources are the same intensity, just get the game object with the nearest `Vector3.Distance()`. Comparing all the targets within the missile's tracking list will yield the nearest one.

If heat sources have different intensities, one solution would be to get the heat source distance as a percent of the maximum detection distance, and multiply the heat source's intensity by the inverse of that distance percentage (pseudocode):

```
targetDistance = Vector3.Distance(transform.position, target.transform.position);
maxDistancePercent = Mathf.Clamp01(targetDistance / maxDetectionDistance))
// Compare list items using this result
brightness = (1f - maxDistancePercent) * heatSourceIntensity

```

This will give a heat source's brightness at a distance (assuming a linear rolloff from the maximum detection distance). Other more accurate algorithms might be based on the inverse square law of light, where `brightness = lumens / 4 * Mathf.PI * distance * distance`. In other words:

```
brightness = heatSourceIntensity / 4 * Mathf.PI * targetDistance * targetDistance

```

However, a game implementation may not need to be so complex and may simply go through every light source in the list (generated by the `isTrigger` collider) and find the brightest light source.

Just start from the simplest implementation and keep what takes the least effort for you to make playable. Performance should only be optimized if it becomes a bottleneck.

---
Tags: unity
---


# Question
Title: Recreating Common "Glowing Pillar" Effect in UE4
I've noticed a common "glowing pillar beacon" effect in a few games lately (Overwatch, Fortnite, etc). The effect provides a translucent glowing beam pointing upwards that tapers off towards the top and fades out.

I'm attempting to recreate the effect and was wondering if this is some form of particle emitter and what is involved in the effect?

Thanks!

**Examples:**

# Answer
> 1 votes
They are usually particle effect, however you can accomplish a much simpler(though much cheaper) effect using semi-transparent bill boarded images.

The best approach for small dev times(or just single devolopers) tends to be the billboarded images. Games like fortnite tend to use billboarding, but if you want better looking ones, see how overwatch accomplishes it. The particles around the overwatch checkpoints are like rays of rain.

---
Tags: unreal-4, particles, level-design, materials, glow
---


# Question
Title: In VR Games, i frequently notice that skyboxes look too close. Would this be a method for making them appear more distant, especially for space games?
I was playing Star Trek Bridge Crew, and noticed that the starfield looks oddly close. The same goes for the sky in other games. I realized that this is because when rendering the skybox in a game, VR games render the skybox once for each eye. But because games use a large dome or sphere for the skybox, instead of the appearance of the skybox being located extremely far away (Which happens convincingly in non-vr games), the parallax is quite detectable to our eyes and we see the skybox for what it is, a relatively close wall of stars.

To fix this, I propose that when rendering for the right eye, the right eye camera be temporarily moved to the position of the left eye camera to render the skybox, then moved to the correct position before continuing to render the scene's foreground. Alternately, you could move the skybox model's position by a few pixels (as many as the distance between the cameras) to achieve the same effect.

This should make the appearance of the skybox appear at "infinite" distance since that's how we see stars ourselves, with both eyes seeing the photons arriving at almost parallel vectors.

The effect, in VR, should be convincing. Put simply, stars don't move their apparent position when you close one eye. That should be true in vr games too.

My question is whether, to the game devs of stack exchange, this would be possible using this method. I think the main challenge would be in changing the position of an object in the middle of a render pass.

# Answer
The skybox doesn't exist in world space so it never needs to have a position in world space. It should be rendered with a shader that takes into account its orientation and the camera's orientation and sets its camera space position to 0,0,0, so the camera is always at the center of the skybox. I've never tried it in VR, but if you draw the skybox this way once for each eye/camera, it should produce the proper infinite distance effect.

Also on a side note, there's no need for the skybox to be any particular size or sphere-shaped - it can be a small box, it just needs to be big enough not to clip with the camera's projection plane, and it needs to lose the depth test against other objects. You can set the depth in the fragment shader like this:`gl_FragDepth = 0.9999999f;`
> 1 votes

# Answer
This always bothered me and I've been searching for an answer to this for a few days, but it's a bug in at least Unity (and probably other engines). The VR skybox renders at a fixed distance, and I'm not sure why this hasn't been fixed (Subnautica has this problem where the moon looks closer than the crashed ship).

I found a work around: You setup a 3D skybox { https://www.youtube.com/watch?time\_continue=5&v=9PJ6zJIHbqY OR http://www.mirzabeig.com/tutorials/3d-animated-skybox/ } and setting a parent empty object with 2 child cameras (one for each eye a tiny fraction apart) similar to the method you were mentioning and setting the parent scale to something very small. In theory, you would then skin the inside of a sphere with skybox texture. The added benefit is that you can animate these as gigantic features and even set up parameters to interact with them.
> 0 votes

---
Tags: rendering, virtual-reality, skybox, oculus, htc-vive
---


# Question
Title: Why/how does this code change the button color correctly?
```
void OnMouseDown ()
{
    foreach (Button thisButton in buttonArray)
    {
        thisButton.GetComponent<SpriteRenderer>().color = Color.black;
    }

    GetComponent<SpriteRenderer>().color = Color.white;
}

```

This code results in whichever button I select changing color to white while the rest are black. However, I am not understanding how this works. How does it know to specifically change ONLY the selected button to white while the rest are black. Seems contradictory to me...

# Answer
> 2 votes
On every MouseDown event call, in the foreach loop, the color of all buttons changes to black, then the button which caused the call to the MouseDown event, its color changes to white.

Note that `thisButton.GetComponent<SpriteRenderer>().color` refers to the color of each button, but `GetComponent<SpriteRenderer>().color` refers to clicked button color.

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


# Question
Title: Vulkan - preallocating chunks of memory and resource memory requirements
I would like to allocate a bigger chunk of memory and then suballocate from it but I don't fully understand how memory requirements work, is there a chance that when I allocate a piece of device local memory there might be some buffer/texture that memory requirements of which will not include this heap? Or is it safe to assume that if it's a device local heap it will always be viable for device local resources?

# Answer
> 2 votes
> Or is it safe to assume that if it's a device local heap it will always be viable for device local resources?

If it were safe to assume that, Vulkan wouldn't have APIs that specifically allow you to query which memory types support which resource objects.

Indeed, NVIDIA can get pretty fine-grained in its relations between memory types and resource objects. Many NVIDIA implementations of Vulkan have nearly a dozen separate memory types, some of which can only be used for very specific kinds of resource objects. Notice how that particular implementation has 2 device-local memory types; one of those is (I believe) reserved for render targets (color/depth/stencil attachments).

What you have to do is what the API suggests: build image and buffer objects representing your particular needs, use the `vkGetBuffer/ImageMemoryRequirements` calls to query which types can be used with such buffers/images, and tailor your allocation accordingly. Do however keep section 11.6 handy when coding; the detailed list of which objects will return the same memory type bits is very important for deciding which images/buffers "represent your particular needs".

---
Tags: c++, memory, vulkan
---


# Question
Title: Morphing a 3D model into a sphere or cube using a vertex shader
I want to morph between 3d models.I found a simple OpenGL code to morphing In Graphics Shaders: Theory and Practice(page 456) but I couldn't Implement it correctly in unity.

```
uniform float uBlend;
out vec4 vColor;
out float vLightIntensity;
const float SIDE = 2.;
const vec3 LIGHTPOS = vec3( 5., 10., 10. );
void main( )
{
vec4 vertex0 = aVertex;
vertex0.xyz *= 4./length(vertex0.xyz);
vertex0.xyz = clamp( vertex0.xyz, -SIDE, SIDE );
vec3 tnorm = normalize( uNormalMatrix * aNormal );
vec3 ECposition = vec3( uModelViewMatrix * aVertex );
vLightIntensity = abs( dot(normalize(LIGHTPOS - ECposition),
tnorm));
if( vLightIntensity < 0.2 )
vLightIntensity = 0.2;
vColor = aColor;
gl_Position = uModelViewProjectionMatrix *
mix( aVertex, vertex0, uBlend );
}

```

unity shader:

```
Shader "Unlit/MorphToSphere"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _Blend("Blend",Range(0,1)) = 0
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;
            float SIDE = 2;
            float _Blend;

            v2f vert (appdata v)
            {
                v2f o;
                float3 AnotherShape = 4./length(v.vertex.xyz);
                AnotherShape.xyz = clamp( v.vertex.xyz, -SIDE, SIDE );
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.vertex.xyz = lerp( o.vertex.xyz, AnotherShape.xyz, _Blend );

                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = tex2D(_MainTex, i.uv);
                return col;
            }
            ENDCG
        }
    }
}

```

---

```
uniform float uBlend;
out vec4 vColor;
out float vLightIntensity;
out vec2 vST;
const float TWOPI = 2.*3.14159265;
const vec3 LIGHTPOS = vec3( 5., 10., 10. );
void main( )
{
// original model coords (sphere):
vec4 vertex0 = aVertex;
vec3 norm0 = aNormal;
// circle coords:
vST = aTexCoord0.st;
float s = aTexCoord0.s;
float t = aTexCoord0.t;
float radius = 1.-t;
float theta = TWOPI*s;
vec4 circle = vec4( radius*cos(theta), radius*sin(theta),
0., 1. );
vec3 circlenorm = vec3( 0., 0., 1. );
// blend:
vec4 theVertex = mix( vertex0, circle, uBlend );
vec3 theNormal = normalize( mix( norm0, circlenorm, uBlend ));
// do the lighting:
vec3 tnorm = normalize( vec3( uNormalMatrix *
theNormal ) );
vec3 ECposition = vec3( uModelViewMatrix * theVertex );
vLightIntensity = abs( dot(normalize(LIGHTPOS -
ECposition),tnorm));
if( vLightIntensity < 0.2 )
vLightIntensity = 0.2;
vColor = aColor;
gl_Position = uModelViewProjectionMatrix * theVertex;
}

```

unity shader:

```
Shader "Unlit/MorphToCube"
{
        Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _Blend("Blend",Range(0,1)) = 0
        _Radius("Radius",Float) = 0
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
                float3 normal :NORMAL;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;
            float SIDE = 2;
            float _Blend;
             float TWOPI = 2.*3.14159265;
             float _Radius;

            v2f vert (appdata v)
            {
                v2f o;

                float theta = TWOPI;
                float4 circle = float4( _Radius*cos(theta), _Radius*sin(theta),0., 1. );

                o.vertex = UnityObjectToClipPos(v.vertex);
                o.vertex.xyz = lerp( o.vertex.xyz, circle.xyz, _Blend );

                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = tex2D(_MainTex, i.uv);
                return col;
            }
            ENDCG
        }
    }
}

```

# Answer
The example you're working from is trying to use information encoded in the texture coordinates for some reason (something you didn't replicate in your version), invoking unnecessary trig. I'd just throw that out if all you want is cubes and spheres.

Just remember to do your morphing in object space, *before* you project into clip space, not after.

```
v2f vert (appdata v)
{
    v2f o;

    float3 anotherShape;

    // CUBE
        // We can determine the face of the cube to which we belong
        // by which component is furthest from zero
        // (this divides 3D space into 6 pyramids)
        float3 absolute = abs(v.vertex.xyz);
        float greatest = max(absolute.x, max(absolute.y, absolute.z));

        // Dividing by this greatest value snaps the vertex to one of the planes
        // x = 1, y = 1, z = 1, x = -1, y = -1, or z = -1, ie. the unit cube.
        // Scaling by a _Size parameter makes the cube however big we want it.
        anotherShape = v.vertex.xyz * _Size / greatest;
    /* // SPHERE
        // Spheres are easier - just normalize to get a direction and scale it.
        anotherShape = _Size * normalize(v.vertex.xyz;
    */

    // Perform our blend in object space, before projection.
    float4 blended = float4(lerp(v.vertex.xyz, anotherShape, _Blend), 1.0f);

    // Project our blended result to clip space.
    o.vertex = UnityObjectToClipPos(blended);

    o.uv = TRANSFORM_TEX(v.uv, _MainTex);
    return o;
}

```
> 1 votes

---
Tags: unity, shaders, shaderlab, vertex-shader
---


# Question
Title: Cannot import an .svg into a Unity project
I cannot import an `.svg` into a Unity project.

When I just move the `.svg` file into the Unity project Unity does not work with it and the only option Unity provides is to open the file (in my case it proposes me to open the `.svg` with Inkscape).

After performing a little bit of research I come to a conclusion that I need to have an SVG Package being installed into the Unity in order to import the `.svg` files.

But when I try to install the package I do not find it in the list of packages.

I am using a free Personal Edition of Unity. So, may it be that the option to import `.svg` is for paid version of Unity only?

Thank you.

Yes, it really seems that importing an `.svg` into Unity is only a paid feature. So, does anyone know about a way to import an `.svg` into Unity for free? For instance, are there other packages which help to accomplish this?

I do not see the needed package in the list of packages for preview:

# Answer
> 2 votes
If you want to use the Unity Vector Graphics preview package, make sure you check "Show preview packages" under Window \> Package Manager \> Advanced

With this, you should see the Vector Graphics package appears and can be installed.

# Answer
> 2 votes
I would recommend to open the SVG image with an SVG editor (like the free Inkscape) and export it as a PNG (or other raster-oriented image format).

The drawback of this method is that you will lose the ability to scale the image infinitely without it becomming pixelated or blurry. But the advantage is that it will be a lot faster than solutions which rasterize the SVG in real-time. SVG is a very complex vector image format where many features have very hard to predict performance characteristics. So if you intend to use a lot of complex SVG images, then a runtime rasterizing solution might cause performance problems.

---
Tags: unity, import, ide, importing, svg
---


# Question
Title: Snake AI - Is a Hamiltonian approach valid for all grid sizes?
So, as has been done many times before, I am designing an AI that can play Snake as effectively as possible. It didn't take me long to find this extremely useful thread here: How to find a safe path for an AI snake? where the top answer first and foremost recommends forming a Hamiltonian circuit for the grid and begin by just having the Snake follow this route.

However, after attempting this, I realised it didn't work with my initial grid size (23x23), at least I don't think it does. My understanding may be incorrect, but from what I gather, with m rows and n columns, if mn is odd, then there is no Hamiltonian circuit possible. If this is the case, then should I abandon this method? Or is there any way of implementing it in some case?

# Answer
Yes, you're correct, it's not possible. You can prove this using parity.

Color your grid like a chess-board. The start- and end-tiles of your Hamiltonian circuit must be adjacent, meaning they must have opposite colors. However, with an odd grid size, there are more of one color than the other, meaning to hit every square you must start and end on the same color. Thus no circuit is possible.
> 2 votes

---
Tags: ai, path-finding, graph, snake
---


title: How to achieve a stable hover in Unity

text:
# Question
Title: How to achieve a stable hover in Unity
In the game that I am currently making the play character is supposed to hover off the ground. I had used the code from the Hover Car tutorial on the unity website however this causes a lot of fluctuation in height even when staying still on a flat surface. This is a problem because the game is supposed to be in the first person. Is there a way to make the player character more stable?

```
public float hoverForce = 65f;
public float hoverHeight = 3.5f;
public Rigidbody playerRB;
// Start is called before the first frame update
void Start()
{
    playerRB = GetComponent<Rigidbody>();
}

// Update is called once per frame
void FixedUpdate()
{
    Ray ray = new Ray(transform.position, -transform.up);
    RaycastHit hit;

    if (Physics.Raycast(ray, out hit, hoverHeight))
    {
        float proportionalHeight = (hoverHeight - hit.distance) / hoverHeight;
        Vector3 appliedHoverForce = Vector3.up * proportionalHeight * hoverForce;
        playerRB.AddForce(appliedHoverForce, ForceMode.Acceleration);
    }
}

```

# Answer
> 1 votes
My first instinct would be to fake it. That is, create an invisible cube collider beneath the car that acts as a force field, then attach it to the car with a prismatic joint, which disallows movement between the two in the X and Z axes, and has a spring to try to keep the y-axis distance between the two constant, while allowing the car to sort of bounce up and down a bit.

Of course, if you don’t want to allow bouncing, you could just have the invisible collider be part of the same rigidbody as the car and it will just sit on top of the floor by that amount all the time.

On the other hand, if you want a bit of bounciness, there’s unfortunately no such thing as a prismatic joint in Unity, but as this answer explains, we can create one using a Configurable Joint.

I’m going to steal that answer and adjust it for this situation.

* **Connected Body**: assuming this joint is on the force field, set the connected body to be the car’s main body.
* **Anchor**: this is the position in the invisible collider’s local coordinates that should act as the attachment point. If it’s a 1-unit cube, set it to (0,1,0) to have the top of the force field attach to the car.
* **Axis**: this is the direction of movement, in your object's local coordinate space. Set to (0,1,0) so that it moves along the y-axis
* **Auto-Configure Connected Anchor**: check this. The joint will treat the force fields's placed position as the center of its movement range, allowing it to slide both up & down. If unchecked, we would need to configure the “Connected Anchor” manually
* **X/Y/Z Motion**: Y should be set to "Limited", and the others should be set to "Locked” to allow vertical movement while not letting the force field get out from under the car.
* **Angular X/Y/Z Motion**: We don’t want to allow any. Lock it up.
* **Linear Limit**: Set to 0. We don’t need the force field to freely change the distance between itself and the car.
* **Linear Limit Spring**: Set spring to the value you set in your script’s hoverForce to start with (looks like 65?), and adjust from there. Damping should also be non-zero so that the car doesn’t bounce and down indefinitely.
* **Enable Collision**: unchecked. The force field collider should be able to freely move into the car. However, you may want to use a special layer on the force field so that it doesn’t hit anything other than the floor, using the physics settings’ layer collision matrix.

# Answer
> 0 votes
If I'm not mistaken, increasing the drag should help. Maybe you can fake it only on the y axis, maybe even only when the velocity is going downward/upward. This code should work fine for drag, it's what I use (but increasing the rigidbody's drag might be all that's needed):

```
velocity = velocity * (1 - deltaTime * drag);

```

---
Tags: unity, c#, physics, first-person-shooter
---


# Question
Title: Game running with fewer steps than desired (game created in GameMaker)
I tested my game on 4 different computers and got some results.

**PC 1** =\> AMD A4-6300 APU with Radeon HD Graphics / 2,0 GB RAM / AMD Radeon HD 8370D

In this computer I tested a few stages and I noticed a loss of 1 second in 10, ie ... In the game 10 seconds passed while here in the real world 11 seconds passed.

I calculate the time in the game based on the step event.

I set the speed of the room by default as 30.

Time code:

Step Event: `currentTime+=1;`

Draw Event: `draw_text(x,y,string(currentTime/30));`

On my computer I never had problems. Hence the need to test the game on other computers.

**PC 2** =\> Pentium Dual-core CPU E5700 @ 3.00GHz / 4,0GB RAM / Intel G41 Express Chipset

On this computer, I performed the same tests and I detected a slightly smaller loss. Less than 1 second every 10 seconds, ie ... In the game 10 seconds passed while here in the real world 10.7 / 10.8 seconds passed.

**PC 3** =\> Intel core i3-3217U CPU @ 1.80GHz / 4GB RAM Intel HD Graphics 4000

Worked perfectly! It's a core i3 right? I did not detect any apparent losses.

**PC 4** =\> Intel Core 2 Duo CPU e8200 @ 2,66GHz 2,66GHz / 4GB RAM

Worked perfectly! I did not detect any apparent losses.

Detail that in this computer the game lost enough in resolution (it seems that the monitor is too large for the components of the computer).

Post with the problem =\> Game was resized incorrectly for no apparent reason (GameMaker)

Important!

I put a function on the shift key to accelerate the game (it would be a function for the players who wanted to analyze all the course of the stage, just playing to understand) and I defined that when clicking on the shift key the speed of the room goes to 3000 steps. On my PC the game is super fast, but I doubt it reaches exactly 3000 steps. Even so, a few hours pass in a few minutes here at home.

On PC 1 I tested this same function and accelerated by approximately 20%. In the game it was 11 seconds while 10 seconds passed in the real world.

**Solutions**:

1=\> Stop measuring time through the steps.

I imagine there is some way to do time measurement based on another type of argument, just like unity `timeDeltaTime`.

That way, I imagine that a player with a GTX 1080 the game works correctly and phase 1 finishes in exact 11.23 seconds (real time).

But a player with a humbler computer that same phase finishes with 13 or 14 seconds (real time). It turns out that the same phase that lasted 11.23 seconds on the computer with a GTX 1080, it would take longer to be finalized on that more humble computer. The time was going to be measured correctly (13/14 seconds in the game), but the game was going to be running in different ways (different speeds).

2 =\> Based on the boost (shift key) I tested on PC 1 (the humblest computer I tested) I see that it is possible to force the game to rotate in a number of steps even on that weaker computer.

I think that using solution 2, when I make the online mode available, I may have problems (just like Fallout 76), people with a good computer could change the steps of the game and make the game work in a much larger number of steps.

The ideal would be to join the two solutions, so that time is measured regardless of the number of steps, but that the operation of the game is the same on any computer.

# Answer
`delta_time` is the time that passes between one step and another. In a room with 30 steps per second on a computer that supports such speed, `delta_time` will be equal to 33333.33333333... . Knowing this:

Step Event (clock): `currentTime+=1*(delta_time/33333.333);`

With this equation the time will be calculated regardless of how many steps the game is executing.

Step Event (object car): `speed=carSpeed*(delta_time/33333.333);`

Where `carSpeed` is the variable that defines the speed of the car previously.

Where the `speed` is a property that all instances in the gamemaker have. Which can modify the speed of an instance at any time.

https://docs.yoyogames.com/source/dadiospice/002\_reference/movement%20and%20collisions/movement/speed.html
> 0 votes

---
Tags: game-maker
---


# Question
Title: How can I change view to orthographic using a menu?
I'm writing the custom menu using `MenuItem` and I'm stuck trying to make scene view orthographic when `5` is pressed. What is the object or method I can use to set scene's view to orthographic (I don't mean the main camera, but the main view shown in the window).

This is a C# code of what I was trying to achieve:

```
[MenuItem("View/SetOrtho _5")]
static void SetOrtho() {
    var scene = ... //assign scene
    scene.setOrtho(true); //set orthographic view to the scene
}

```

# Answer
This documentation is for Unity 2019, so it’s not clear whether this applies to 2018 or older, but it’s worth a shot.

The gist is

```
 UnityEditor.SceneView.lastActiveSceneView.orthographic = true;

```
> 1 votes

---
Tags: unity, c#, scene, menu
---


title: nodejs game server timer

text:
# Question
Title: nodejs game server timer
I'm new to game server develop. I'm developing a card game server. How could I make nodejs server wait for few seconds then push data to client after an event fired ? Example : in poker game, one player have about 20 seconds to make a move, after 20 seconds server will auto fold and then push a message to another player. How could I make server wait for 20 seconds and then do next action ?

# Answer
Node has build in timer functionality well documented on their website. Set the delay to 20 * 1000 and have the code in the callback trigger the fold then inform the client.

> ## Timers
>
> ```
> setTimeout(callback, delay, [arg], [...])#
>
> ```
>
> To schedule execution of a one-time callback after delay milliseconds. Returns a timeoutObject for possible use with clearTimeout(). Optionally you can also pass arguments to the callback.
>
> It is important to note that your callback will probably not be called in exactly delay milliseconds - Node.js makes no guarantees about the exact timing of when the callback will fire, nor of the ordering things will fire in. The callback will be called as close as possible to the time specified.
> 2 votes

# Answer
If you talking about "few seconds", you can use setInterval as well as setTimeout.

There is all you need to know about timers in nodejs https://nodejs.org/api/timers.html#timers\_setinterval\_callback\_delay\_args

**setInterval Example**:

```
setInterval(function(){
   //do something each 5 seconds (maybe +/- few milliseconds)
}, 5000);

```

**setTimeout example**:

```
function timeout() {
   setTimeout(function () {
     //do something each 5 seconds (maybe +/- few milliseconds)
     timeout();
   }, 1000);
}
timeout(); // here we start loop

```

Difference:

setInterval CAN skip some timer ticks if callback works longer than timer duration. (some hard loop for 7 seconds for example). You should never meet that you talking about "few seconds". But it may happen if you set intervals to few milliseconds.

setTimeout will not skip ticks, and start new times each time when all tick tasks is complete.
> 0 votes

# Answer
Well, the answer to this is not that easy. If I would be developing this, I would create a loop on server side, where server

1. starts
2. loads all resources
3. Updates game / caches packets to send
4. sends packets to all players, delete all cached messages
5. goto 3

Then, If you want to wait before sending user data, then in UPDATE logic you will keep track of time. If time is up, put the message to be sent to cached queue.

As there will be message to be sent, the server will send it as soon as it can.

Here is a diagram from my website, where is depicted how server operates:

Please, notice mainly the server updates, and then sends all packets to their recipients.

So If you want to wait 20s, you create new class Timer, which will get the current time upon creation, and how long to wait. Then, every single time you call timer.update() it returns you true if time is up.

For additional info, I have publicly available documentation for my own nodeJS project. Documentation describes how I solve certain issues in game dev, such as client-server interactions, how I send data, serialization, and what to be aware of.

That can be found here, in section documentation.

Good luck with your project, if you have any further question, just ask me. I like game dev and will be happy to help

By the way, if you are new to server develop, it is crucial to know how to create the architecture of the code, otherwise you get lost. Trust me, I used to be new to that stuff too. Rewriting code is a pain.
> 0 votes

---
Tags: server, node.js
---


title: NodeJS sharing variables with Client?

text:
# Question
Title: NodeJS sharing variables with Client?
I'm currently developing a HTML5 Canvas Multiplayer Game using NodeJS and Socket.IO. My current setup using a logic loop on the NodeJS Server-end and sending update information to all Clients in this loop 60x a second. For obvious reasons, this isn't feasible, and even with one player, it doesn't work as I'd like it to.

I'm not a networking genius nor am I an experienced Game Dev, but is there any way for Node and my Client(s) to "share" variables so that I'd have no need to send packets like this? Or any way in which I could improve my current situation?

Current workflow:

1. Client sends keypress action to the Server via a packet
2. Server adds it to a queue and in the Logic loop will calculate movement and update the server-side Player Entity accordingly
3. Game loop also sends these updates to all other Players in the same Socket.IO Room at 60x a second
4. Client takes their finger off the movement key(s) and sends this action to the server
5. Logic loop removes the movement from the queue

Thanks in advance, please let me know if there is anymore information you'd need

# Answer
Well, what I did in my project was that I have .ts (or .js) sources that are common for both server and client. Considering typescript, a bit of hack was needed to make it work. If you would be interested, I can provide you full explanation.

Now 60x per second is too much, you should be ok with like 2x per second. Also, you would have to implement client-side interpolation to get rid of ,,laggy movement". If you want, you can add me and I could help you with that (as this forum would not get spammed).

A note: use serialization to send network data. Do not send manually arrays. In past, I did and I had to rewrite project because, with growing complexity, it became unfeasible

have a nice day
> 1 votes

---
Tags: networking, node.js
---


# Question
Title: Visual Studio can't handle my unity scripts
I have created a new project in Unity 2018.3.4f1 with Visual Studio Community 2017. I can't edit scripts properly in Visual Studio because of a bunch of errors related to .net framework. How can I fix these issues?

# Answer
> 3 votes
Seems you don't have the Unity plug-in for VS Community. The project should open as a C# assembly project like the following.

It's in tools and features, go get it.

Good luck.

---
Tags: unity, c#, scripting, visual-studio, .net
---


# Question
Title: Recursively calculate possible pathway on a grid depending on max walk distance
I have a character that is placed on a grid. It has a variable maximum walking distance. Grid fields can be walkable or not walkable. As the character may has to walk around certain not walkable fields to reach his destination his maximum walking distance isn't allways represented by a circle.

See these examples:

Without obstacles, walking distance 7:

With obstacles, walking distance 7:  Note how the obstacles affect the players maximum walking distance

To calculate this i've written this recursive function:

```
static Vector2Int[] GetWalkableFields (Vector2Int position, int steps) {
    List<Vector2Int> walkableFields = new List<Vector2Int>();

    if (steps > 0) {
        foreach (Vector2Int v in GetNearbyFileds(position)) {
            if (m_mc.IsInBounds(v) && m_mc.IsWalkable(v.x, v.y)) {
                walkableFields.Add(v);
                walkableFields.AddRange(GetWalkableFields(v, steps - 1));
            }
        }
        return walkableFields.ToArray();
    } else {
        Vector2Int[] v = { position };

        return v;
    }
}

```

And this function, that returns all four neighbour fields of a field:

```
public static Vector2Int[] GetNearbyFileds(Vector2Int position) {
    Vector2Int[] neighbors = new Vector2Int[4];
    neighbors[0] = new Vector2Int(position.x, position.y - 1);
    neighbors[1] = new Vector2Int(position.x, position.y + 1);
    neighbors[2] = new Vector2Int(position.x - 1, position.y);
    neighbors[3] = new Vector2Int(position.x + 1, position.y);

    return neighbors;
}

```

The function is called with the players position and maximum walking distance (steps) and get's the four neighbour fields and unless the steps are zero calls itselve for every neighbour field with the maximum walking distance decremented.

As you can see in the screenshots, this works absolutely fine. The problem is, as the calculation not only goes away from the player but, in some recursion paths, goes back and fourht between tiles until stepcount zero is reached without even having traveled one field, that this way of calculating the path is really resource heavy. For a walking distance of 7 there are 27646 possible walkways that all are getting calculated. If a player is able to walk 11 fields the calculation takes a few seconds, if he can walk 12 fields Unity crashes while calculating.

Is there a way to calculate this more efficient?

Thank you in advance.

# Answer
You're on the right track, but we can improve on this in three ways:

1. Introduce to notion of a "Closed Set" (a way to mark sites we've visited so we don't need to re-visit them)
2. Iterate in a breadth-first rather than depth-first manner, so we visit cells in order of shortest distance from the start point.

This ensures we don't inadvertently mark a cell visited after finding a long route to it, blocking us from exploring a shorter route through that cell later in the search.
3. Don't allocate new collections (`new List...`) in every iteration of the search - this puts more load on the garbage collector than we need.

Here's an example of how we can do this. Here we pass in & populate a dictionary mapping positions to distances. The caller can then iterate over the keys of that dictionary to find all the reachable sites, and check the values associated with those keys if they need to know the distance to them. You can use this information to reconstruct the shortest path to any reachable site.

```
// Simple record for book-keeping about our search in progress.
struct PathfindingNode {
     public readonly Vector2Int position;
     public readonly int distance;

     public PathfindingNode(Vector2Int position, int distance) {
         this.position = position;
         this.distance = distance;
     }
}

// Stores the nodes at the frontier of our search.
// The Queue type ensures we visit nodes in a breadth-first order.
Queue<PathfindingNode> _openSet = new Queue<PathfindingNode>();

// Populates a dictionary of reachable tiles.
void FindReachableCells(Dictionary<Vector2Int, int> reachable, Vector2Int startPoint, int maxSteps) {

    // Clear the results of any previous pathfinding.
    reachable.Clear();

    // Seed the pathfinding with our start point.
    reachable.Add(startPoint, 0);
    _openSet.Enqueue(new PathfindingNode(startPoint, 0));

    // As long as there are nodes in the frontier...
    while(_openSet.Count > 0) {
        // Pop the oldest one out of the collection.
        PathfindingNode parent = _openSet.Dequeue();

        // Check each neighbouring cell for reachability,
        // and add it to the collection if we can reach it.
        float childDistance = parent.distance + 1;
        CheckChild(parent.position.x - 1, parent.position.y, childDistance, maxSteps, reachable);
        CheckChild(parent.position.x + 1, parent.position.y, childDistance, maxSteps, reachable);
        CheckChild(parent.position.x, parent.position.y - 1, childDistance, maxSteps, reachable);
        CheckChild(parent.position.x, parent.position.y + 1, childDistance, maxSteps, reachable);
    }
}

void CheckChild(int x, int y, int distance, int maxDistance, Dictionary<Vector2Int, int> reachable) {
    var position = new Vector2Int(x, y);

    // Exclude nodes that are out of bounds or not walkable.
    if(map.IsInBounds(position) == false || map.IsWalkable(position) == false)
        return;

    // Exclude nodes we've already visited by some other route.
    if(reachable.ContainsKey(position))
        return;

    // Aha! We found a new walkable node in range. Add it to our reachable set.
    reachable.Add(position, distance);

    // And if we have room to go further, add it to our frontier
    // to later explore its neighbouring nodes.
    if(distance < maxDistance)
        _openSet.Enqueue(new PathfindingNode(position, distance));
}

```
> 4 votes

# Answer
I am not sure what is the code you wrote, but when you are getting all nearby fields, it will return you field that you have already checked for. By recursion, you naturally iterate much more squares than necessary. The solution is: have a hashmap of already visited squares, and if the square is visited, do not look for his neighbors. Well, for this, path searching algorithm can be used (which is something you tried to write ,,come up with"). I would suggest you to look up algorithms like BFS, you can find many examples along with sources online. BFS marks visited squares so it is optimized. Also, the complexity would be N, N being the max amount of squares you can visit.

Alternatively, please note that BFS is not so performant if you have no or small amount of obstacles, for that would be better A\* (if you will later walk towards some point).

Feel free to contact me for more info.

PS: Can you share the game you have so far? I would like to see it (if it is online)
> 0 votes

---
Tags: unity, c#, path-finding, recursion
---


title: Create context menu in Scene view

text:
# Question
Title: Create context menu in Scene view
I created some `MenuItem`functions for navigating, which are currently displayed on the menu toolbar. The C# code:

```
using UnityEditor;
using UnityEngine;

public class Menu : MonoBehaviour {

static void rotateView(Quaternion rotation) {
    SceneView.lastActiveSceneView.LookAt(SceneView.lastActiveSceneView.pivot, rotation);

    SceneView.lastActiveSceneView.Repaint();
}

[MenuItem("View/Front _1")] // FRONT
static void FrontView() {
    rotateView(Quaternion.Euler(0, 180, 0));
}

[MenuItem("View/Back &1")] // BACK
static void BackView() {
    rotateView(Quaternion.Euler(0, 0, 0));
}

// Few more similar functions

}

```

I came from Blender, where there are shortcuts opening a context menu on the cursor position like this one, opened after pressing `U`:

What I want to do is displaying a context menu after pressing `P` which would display a list of implemented `MenuItems`. Is something like this possible in Unity?

# Answer
> 0 votes
You can use `ScreenToWorldPoint` to convert your mouse positions to 3D coordinates.

Also `ScreenToViewportPoint` converts your mouse positions to normalized 2D coordinates on current viewport.

Usage:

`ReferenceCamera.ScreenToWorldPoint(mouseX,mouseY,distanceFromCamera)`

Where

`mouseX = ReferenceCamera.ScreenToViewportPoint(Input.mousePosition).x`

`mouseY = ReferenceCamera.ScreenToViewportPoint(Input.mousePosition).y`

* `ScreenToViewportPoint` gives you a value between 0 and 1 normalized for the screen you are playing in. Very useful for placement of UI elements on HUD. This is probably what you are looking for.
* `ScreenToWorldPoint` is used to get world position. This is useful if you want to create an explosion at x distance from screen for a game with orthographic projection.

Create a HUD. Attach it to camera. Check `ScreenToViewportPoint` and calculate if the menu should spawn to bottom-right/bottom-left/top-left/top-right so it doesnt go out of bounds. You can track selections through same method.

---
Tags: unity, c#, gui, menu
---


# Question
Title: RigidBody.MoveRotation Resetting to (0,0,0);
I'm trying to rotate a character on along the y axis but rather than continuing to rotate, it rotates then the y rotation goes back to 0. I'm not sure what I'm doing wrong. The same thing happens if I change the rotation in the inspector. The line that's causing this is the second one in the Look Function.

```
public void Look()
{
    Quaternion Rotation = transform.rotation;
    Rotation = Quaternion.Euler(transform.rotation.x , transform.rotation.y + Input.GetAxis("Mouse X"), transform.rotation.z);
    rb.rotation = (Rotation);
}

```

# Answer
> 1 votes
Don’t animate using Euler angles. From the Unity docs:

> There are some situations where it is valid to use Euler angles, but you should bear in mind: - You should use the Quaternion Class functions that deal with Euler angles - Retrieving, modifying, and re-applying Euler values from a rotation can cause unintentional side-effects.

You should also avoid assigning rotation directly when animating. Instead, use `Rigidbody.MoveRotation`, which also takes interpolation into account:

```
public void Look() {
  Quaternion rotation = Quaternion.AngleAxis(Input.GetAxis("Mouse X"), Vector3.up)
  rb.MoveRotation(rb.rotation * rotation);
}

```

Here I used `Quaternion.AngleAxis` to create a rotation around the Y-axis (the Vector3.up axis) and then Quaternion multiplication to apply it to the existing rotation.

Note that the problem you saw was due to the fact that you were treating the Quaternion as a vector, expecting the x, y, and z components of the Quaternion to be the same as the Euler angle version you assign it to. This is not the case. You can read more about the difference between quaternions and Euler angles in the first link above to the Unity docs.

# Answer
> 1 votes
As long as you haven't changed the default input settings in the project settings `Input.GetAxis("Mouse X")` will not return the mouse position but the acceleration of the mouse in a certain direction ranging from -1 to 1. This results in your game object rotating at a maximum of one degree depending on the speed you move your mouse.

I'll suggest using `Input.mousePosition.x` as this returns the mouse position on the x-axis on the screen which will be added to the rotation value resulting in a full rotation of your game object every 360 pixels the mouse travels along the x-axis.

Please note, that Ed Marty is completely right! You should never use Euler angles for animation.

---
Tags: rotation, rigidbody
---


# Question
Title: Null Reference Exception error occurs when trying to override AndroidManifest file in unity?
So I Created A manifest file in *Assets/Plugin/Android/*. The File contains:

```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
 <activity android:name="com.unity3d.player.UnityPlayerActivity" android:windowSoftInputMode="stateHidden"></activity>
</manifest>

```

Error Occurs when building:

> NullReferenceException: Object reference not set to an instance of an object
>
> UnityEditor.AndroidManifest.SetApplicationFlag (System.String name, Boolean value)
>
> UnityEditor.AndroidManifest.SetDebuggable (Boolean debuggable)

I followed the docs from here, about **Overriding the Android Manifest**.

The apk builds fine when the manifest is removed.

**Complete Error:**

> NullReferenceException: Object reference not set to an instance of an object UnityEditor.AndroidManifest.SetApplicationFlag (System.String name, Boolean value) UnityEditor.AndroidManifest.SetDebuggable (Boolean debuggable) UnityEditor.Android.PostProcessor.Tasks.GenerateManifest.PatchManifest (UnityEditor.Android.PostProcessor.PostProcessorContext context, System.String manifest) UnityEditor.Android.PostProcessor.Tasks.GenerateManifest.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context) UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context) UnityEditor.Android.PostProcessAndroidPlayer.PostProcess (BuildTarget target, System.String stagingAreaData, System.String stagingArea, System.String playerPackage, System.String installPath, System.String companyName, System.String productName, BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.Build.Reporting.BuildReport report) UnityEditor.Android.AndroidBuildPostprocessor.PostProcess (BuildPostProcessArgs args, UnityEditor.BuildProperties& outProperties) UnityEditor.PostprocessBuildPlayer.Postprocess (BuildTargetGroup targetGroup, BuildTarget target, System.String installPath, System.String companyName, System.String productName, Int32 width, Int32 height, BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.Build.Reporting.BuildReport report) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/PostprocessBuildPlayer.cs:286) UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

*UNITY 2018.3.4f1*

# Answer
While the NullReferenceException is technically a bug that Unity should protect against and present something nicer to the user, your manifest is not complete. The main thing it’s complaining about is that it doesn’t have an \<application\> tag wrapping the activity. You should base your manifest on the one provided by Unity.

To see it, remove your copy, make a build, then check the version it created, which can be found in your project folder at Temp/StagingArea/AndroidManifest.xml. Just copy that file and make modifications to that.
> 2 votes

# Answer
## What's Happening Now

By providing your own Manifest file in Assets/Plugins/Android, you are declaring that *your* Manifest should be considered the main one, and Unity will try to inject any extras into that one.

As the main Manifest, your file would have to provide all the basic requirements and have the correct well-formed structure, according to the standard Android Manifest file documentation.

## What you Want to Happen

That depends on (A) the needs of your project, and (B) how familiar you are with Android development. If you don't need any customization, then the default auto-generated Manifest created by Unity will be fine. Just delete your file as you have done, and build as normal.

However, if you do need additional Android-specific customization, then you can either:

* provide a well-formed main Manifest (including all required tags/structure and your customizations) in Assets/Plugins/Android within your Unity project
* **OR** build as normal, but edit the final Manifest file that Unity auto-generates to your requirements

Generally speaking, Android Manifest files are straightforward configuration files written in XML. If you read & follow the documentation, and understand what your project needs are, then you can write one by hand without much trouble.

That said, from an ongoing maintenance perspective, once you create your own Manifest, you "own" it, and will be required to keep up with any necessary changes as either your project needs change or Android itself evolves. Unless you are interested in Android development particularly, or are otherwise prepared to keep your Manifest up-to-date, your best bet may be to stick with the auto-generated file by Unity.

---

(**For Advanced Users:** As an Android dev, I feel compelled to mention that in modern professional Android development, the Manifest is only one part of the larger build system. If you actually need to get "under the hood" and tweak your Android build in a more than trivial manner, then Gradle build configuration is worth looking into.)
> 1 votes

---
Tags: unity, android, debugging
---


title: Google Play exclude devices

text:
# Question
Title: Google Play exclude devices
I have a game that I'm developing in Unity. The game will be released for Android, so I'm working with the Google Play Console. The thing here is that I don't know how to block (Made not available) some devices with certain properties. For example, I need to made my game NOT available for tablets and for devices that don't have at least 1 GB of RAM. Does anyone know how can I do this?

# Answer
You can use the Android Manifest device compatibility properties to specify required device features like minimum screen size/density, memory/graphics specs, network/touchscreen/accelerator capabilities, etc. Google Play uses those properties to determine whether to show/hide your app for any given device.

However you should consider whether these are hard-and-fast minimum technical requirements, or whether you may need to make your game more adaptable to different devices. The Android device ecosystem is very broad, with manufacturers offering lots of mix-and-match combinations of device specs. If you are too specific in your minimum requirements, you could very easily spec yourself into a very narrow slice of the market.

Android users also tend to expect that any app/game that they've heard of as being "Available on Android" is available for their device, unless they have a *really* old device. So from a PR/Marketing perspective, you can also incur some ill-will by artificially setting minimum specs that are higher than necessary.
> 2 votes

---
Tags: unity, android, google-play
---


# Question
Title: How can I create color fonts to be used in Unity?
I've been searching, downloaded a couple programs that lets you convert images into fonts, but none let you obtain the color. They all switch them to black and white.

While searching the internet, I found a few colored fonts. Yet, almost all games have their own fonts that are colorful.

How do they do it? Did they just opt to program the font with coded position and sizes?

I'd just like to make my own true type or open type font (`ttf` or `otf`) from some images I created. And the images aren't even that colorful, just fill and stroke color.

# Answer
> 1 votes
There is a good reason why these are all black and white. Most game engines allow you to manipulate the RGBA values of the textures in your buffer before being displayed.

For example, in my own OpenGL based engine I use the function glColor:

void glColor4i( GLint red, GLint green, GLint blue, GLint alpha);

As you can see, it takes 4 parameters. The first three, red, blue, green are values from 0 to 1 and combined can display any color on the visible scale. The last parameter, alpha, is a powerful tool to play with the visibility of the texture. That is, you can make the font semi-transparent, make the background transparent around the letter, or blend with the background.

Screenshot of an applied bitmap font with different colours and alpha channels in my project.

In my project I have used one of the tools you were referring to, namely to create an imagine of a font. There is a platherea of software and online tools available if you search for "ttf to bitmap".

Next I've written a class in C++ that allows me to display strings and position these anywhere on the screen. This includes the proper spacing for slimmer characters like"i", "l" and ".", as otherwise the words look stocky and unnatural. I also have a function call to the above OpenGL function and I often play with alpha values to make the font fade in or change the color to add emphasis. Here is an example of my current project, precisely applied a bitmap font and playing with the values.

---
Tags: unity, color, fonts
---


# Question
Title: How to make a 'One Hit and Dead' platformer feel fair
I am currently making a run 'n gun platformer, in which the player dies instantly when they get hit. I'm curious how to make this feel fair. I'm aware of putting checkpoints frequently enough, allowing the player to retry almost instantly, and merciful hitboxes. But I'm curious to know how I should go about level design? Run 'n guns are much different from sanic-speed wall jump platformers like meat boy.

You see, games like Hollow Knight let you learn how to avoid taking hits early in the game by giving easy challenges. If you get hit by something unexpected in Hollow Knight, you can always focus and gain some health, and it wouldn't feel unfair. If that happened in my game, that would feel unfair.

Since I'm designing a Megaman-X like game with a boss at the end of each stage, how am I supposed to go about teaching the player how to dodge fast moving projectiles that you would only know how to dodge after seeing how they act?

And yes, there is going to be a first level before you can go play the other ones in whatever order you like.

# Answer
That's the trade-off to this kind of game play design, the player is *expected to die* many times to learn mechanics and Boss abilities. To make those deaths palatable to the player I have a few ideas:

1) nothing can be random, everything must have a pattern that can be learned. There is nothing more unfair than dying to an attack you've never seen before and will probably never see again.

2) hit boxes should be precise and dependable, don't make them "merciful" because then the player will feel out of control, and the player should always feel in control.

3) reaching a checkpoint should be a Big Deal, make reaching checkpoints exciting and use them to pace the game so the player won't get fatigued playing nonstop. Think of Checkpoints as a pacing mechanic, not a fairness mechanic; the fairness comes from game play and not the rest stops in-between all that playing.

4) alternate easy progress toward a checkpoint with skill+learning challenges to reach the next, let the player feel good about playing better. If the player has immediate feedback like that then new challenges feel fair because they know that it can be learned, just like they did before!

5) bosses should be a Huge Payoff, and you might consider adding a scoring system to encourage players to go back multiple times to achieve special conditions and raise their performance scores. While the player may die a lot it feels fair if they are working towards an extraordinary goal.
> 38 votes

# Answer
In addition to Patrick's answer:

* Time it takes to retry needs to be short, borderline instantaneous. Take Super Meat Boy as an example. Compare with Teslagrad's 4 second death animation.
* Time it takes to regain your progress should also be relatively quick. This goes along with Patrick's comments regarding checkpoints. Taslagrad is pretty good here, as you respawn at the entrance to the room you just entered and most rooms can take only seconds to completely transverse, no more than a minute at the high end.
* No *long term* consequences beyond time lost. Don't penalize the player's exp or in-game currency. Such penalties lead to the player complaining about cheap deaths. For instance, in Teslagrad I found a particularly hard puzzle that kept repaving me facing *towards* the door I entered, and if I tried to start the puzzle without first turning around, I'd kill myself by miss-timing a jump+ability usage. Which cost me am additional 5 seconds as. I waited for the death animation to finish.
* Put limits on the frequency, accuracy, and coordination skills required when building your puzzles or other challenges. The tighter the accuracy or timing the worse off your game will be, as those players that have issues (be they handicapped or just less skilled) will grow frustrated and rage-quit. This is particularly important when it comes to boss fights. "Do the thing 3 times, 3 times" is the biggest complaint I've seen about Teslagrad. Everyone rapidly figures out what they *need* to do, but *actually doing it* often requires incredibly precise timing or movement. The act isn't even that hard, its pulling it off 9 times in a row without getting hit that's the problem.

+ This is also why I hate Super Meat Boy myself. The slippy controls combined with the pixel-perfect jumping, frame-perfect timing is something I just can't do.
> 23 votes

# Answer
The best thing you can do when dealing with situations like these is to study other games that share mechanics and systems with what you intend. Given your description, the two off the top of my head that I think you should most look at are **Metal Slug** and **Contra**. Both involve gun usage as their primary mechanic in a sidescrolling platformer environment, and both involve one hit and dead mechanics like you describe.

Some things that you will notice in games like these is that because getting hit is so costly, there are almost no "surprise" attacks. Nothing moves fast unless there is a huge telegraph to go with it that clearly shows that you should move/jump/whatever so you don't die. **You need to give people opportunities to see how things might kill them** via a combination of telegraphing and make sure that the oncoming death is slow enough that they have a fair amount of time to react before it actually hits them.

Another thing games like this share is **a lives system as opposed to a checkpoint one**. Where death respawns you right where you died a moment or two later, usually with a little mercy invincibility to help you get through whatever just killed you. This allows you to use your number of lives as a kind of limited pool of mistakes available to you without breaking flow entirely. While this might not be strictly necessary, the ubiquity of it is something I would analyze for game feel, especially comparing with other popular "one hit death" games like bullet hells.

Finally, a critical piece is that **how the game responds must be predictable!** Successful play and flow in games like these requires understanding and abusing the mechanics of the game to enable deathless play. Randomness is not entirely out of the question, but things like enemy spawns, enemy AI, and bullet patterns should be very understandable and predictable so that skilled players can use that information to their advantage. Getting through a section because it was easier than usual or getting stymied because RNG hates you both feel bad when the mechanics imply it should be down to your skill.
> 9 votes

# Answer
Rather than one hit dead, short of strong bosses and special enemies, why not use injuries as a way to make things feel real. Injuries tend to slow player movement(jump lower, run slower), impede vision (blurry screen), hearing (gun shots sounds lower or louder depending) or any other the users other senses.

Or if you are definitely focused on keeping the one hit die, take lessons from Contra, frequent armor drops, lots of life drops, starting with lots of lives help. Though you have to create a good enough balance, that allows you to give the user just enough lives without the user feeling as if you are making the game too easy. User testing is a must for that option.

Another Idea from an older game I used to play, was a check point or auto save feature, when you make it to bosses.

Allowing friendly fire between enemy units: This allows the user to use explosions and other enemies fire to make the game a bit more forgiving, if they are talented enough to dodge missiles, shots etc. Which relates to predictability, another answer her discusses this a bit.

This one may be a bit far fetched, but adding vehicles (tanks, plans, cars, horses??) that can take a few shots before exploding at certain parts of the level, that may be littered with enemies.
> 1 votes

---
Tags: level-design, difficulty
---