# Question
Title: Octagonal and dodecagonal tiling: is it possible?
this question rose out of interest of turn-based games, in which there mostly two type of tiling used: square-based and hexagon-based, and both have disadvantages. if you use squares, like in civ3, then moving diagonally always preferable over straight lines, if you use hexagons, like in civ5, then you cant move exactly on left-right axis or up-down. both problem would be solved if we use octagonal or dodecagonal tiling. problem: they doesn't exist in euclidean plane. so, is there any way to do that, like sacrifice straight lines and/or same sizes?

# Answer
There are unfortunately not many options to tile a 2-dimensional plane with regular polygons. If you want to use only one kind of tile, then you can use squares or hexagons. You can use triangles, but then you have up-facing triangles and down-facing triangles. And that's it, because any other tiling schemes require weird combinations of many different tiles with different, shapes, sizes or numbers of edges. Which is going to end in a confusing mess. So unless you want those confusing and unnatural tiling schemes be the main gimmick of your game, I would really recommend against them.

So there are really no good options besides squares or hexagons.

**If you use a square grid**, then you can fix the problem of diagonal moves being cheaper than orthogonal moves by making diagonal moves cost \\$\sqrt2\\$ (1.414) times as much. Which you can approximate pretty well while still keeping the numbers as small integers when you make orthogonal moves cost 2 points and diagonal moves cost 3 points.

And then there is of course also the out-of-the box option: **Do not use tiles at all!** Just let units travel arbitrary floating-point distances up to their maximum movement in any direction they want, and resolve collisions by checking for geometric collider intersection. There are not many turn-based video games which try this. The only one I can think of is the 2004 game *Phantom Brave*. But it is rather popular in tabletop wargames like *Warhammer* (both 40k and Fantasy). Some people also play *Dungeons and Dragons* that way.
> 3 votes

---
Tags: mathematics
---


# Question
Title: Why are sound files always larger in size than an image file?
I am making 2D games. I noticed that PNG files are always much smaller in size than a second-long sound effect file. Why are sound files always larger in size than an image file?

# Answer
Images and audio represent different types of data so it's difficult to compare them directly, it's a bit like comparing apples and orange.

However, the main reason that audio files are *normally* larger than static images is because audio files have an extra dimension, time, and therefore there is more overall data to represent. If you add time as a dimension to an image, you get video, which even without audio is much larger than an audio file.

Audio files aren't always larger than images though. Compression is the key factor, some image files are actually quite large if they're uncompressed and have a large color range (like HDR). An RAW uncompressed 2048\*2048 image with 40-bits of color per pixel *could* take up to 168MB of space. Most songs you'd listen to would take up far less space than that, because MP3/AAC files are compressed.

The reverse case can also be true. If the song file was in WAV format, then a 4 minute song would be around 40MB. And that 2048\*2048 image, using a compressed lossy format like WebP, might only take up 600KB.

But, assuming a reasonable compression with both, a standard large image compressed to 600KB, is going to be smaller than your average compressed song, which even at a lower quality is around 1MB per minute.
> 0 votes

# Answer
Sound is portrayed different than images.

Where an image is a large grid of colored pixels, sound is recorded through soundwaves, which can differ from high-low pitches, loud/soft sound, tone, frequency, and bit depth. And that's a lot of data you hear in one second.

Perhaps this source might explain it in more depth: https://www.omnicalculator.com/other/audio-file-size#what-is-a-digital-audio-file
> -2 votes

---
Tags: file
---


# Question
Title: How to calculate coefficient for how much a object with velocity x is moving towards point a?
I have a object in 3d space that has certain position and velocity. If that object moves perfectly towards point A, the coefficient should be 1. If it moves perfectly away from A it should be -1 or 0. Everything else in between should be respective float. What I have tried for now is googling a lot on the subject, but with no great luck.

# Answer
> 2 votes
Take the position of the two objects, and use that to find a vector that represents the difference of their positions.

```
var pointA = new Vector3(10, 0, 10);
var objectPos = new Vector3(0, 0, 0);

// Subtraction order here matters:
// (pointA - objectPos) gives you a vector pointing toward pointA
// (objectPos - pointA) points from pointA toward objectPos
var objPosTowardPointA = pointA - objectPos;

```

Now you have a vector that points from your object toward pointA, you can use this to compare against your object's velocity. Using a Dot Product you can compare these vectors to determine if they're pointing in a similar direction, or opposite direction, or possibly perpendicular directions. However, when comparing direction, you'll have to make sure that the two vectors are of unit length (normalized).

I'm going to assume you don't have any math libraries handy, but if you already have math functions for `Length()`, `Normalize()`, and `Dot()`, then you skip past where I define those below.

Normalizing a vector is simply making its magnitude (length), a length of 1.

```
// Returns a unit-length version of a Vector3 source
Vector3 Normalize(Vector3 source)
{
    float length = Length();
    float inverseLength = 1.0f / length;

    return new Vector3(
        source.x * inverseLength,
        source.y * inverseLength,
        source.z * inverseLength);
}

```

And to normalize a vector you have to know its length, so here's a method to do that (this is basically the Pythagorean Theorum, if you're familiar with that):

```
float Length(Vector3 source)
{
    return Math.Sqrt(
        source.x * source.x +
        source.y * source.y +
        source.z * source.z);
}

```

Ok, now that we've shown how to normalize a vector, let's put it to use:

```
// Now we have a vector pointing from our object toward point A
// and it's of unit-length, so it can represent a direction
var objToPointANormal = Normalize(objPosTowardPointA);

// We need our velocity to represent a direction without magnitude
// (speed), so we need to normalize it as well
var velocityNormal = Normalize(objectVelocity);

```

And now we have our two directions we care about, both normalized. From here we can perform a dot product operation on them. The method for that is shown below.

```
// Returns dot product of two vectors
Vector3 Dot(Vector3 a, Vector3 b)
{
    return a.x * b.x +
           a.y * b.y +
           a.z * b.z;
}

```

Let's put that dot product to use:

```
var dot = Vector3.Dot(objToPointANormal, velocityNormal);

```

And now you have your answer, in the form you asked for. If `objToPointANormal` and `velocityNormal` are pointing in the same direction, that is, if the object is moving toward point A, then `dot` will be 1. If the object is moving away from point A, then `dot` will be -1. If the object is moving perpendicular to the direction toward point A then `dot` will be 0.

Assuming you have the math functions set up, the code ends up looking like this:

```
var pointA = new Vector3(10, 0, 10);
var objectPos = new Vector3(0, 0, 0);

var objToPointANormal = Normalize(pointA - objectPos);
var velocityNormal = Normalize(objectVelocity);

var dot = Vector3.Dot(objToPointANormal, velocityNormal);

```

# Answer
> 3 votes
There are two vectors: the speed of the object and the direction of the object to the target point. Our goal is to calculate how "consistent" these two vectors are.

You can calculate the angle(θ) between two vectors using Dot\_product:

And,

```
a·b = |a|*|b|*cosθ

```

So that, we get `cosθ`. Then use Inverse\_trigonometric\_functions (arccos) to get θ. It's range should be \[0,180\]. Most math libraries have this feature.

Finally, map \[0,180\] to \[1,0\] or \[1,-1\]:

```
rate = 1 - θ / 180
// or
rate = 1 - θ / 90

```

# Answer
> 0 votes
I ended up with something like this in Unity:

```
Vector3 pos = new Vector3(1, 2, 0);
Vector3 dir = new Vector3(0, -1, 0);
Vector3 targ = new Vector3(1, 0, 0);

Vector3 locTargNorm = (targ - pos).normalized;
Vector3 dirNorm = dir.normalized;

var directCoef = Mathf.Abs(Vector3.Angle(locTargNorm , dirNorm )) / 180.0f;

```

---
Tags: 3d, movement, vector
---


# Question
Title: Efficient way to check collisions for many objects
I am making a Bloons tower defense game and I came across a problem with regards to collisions. The way my code currently works is all the current bullets on the screen(could be potentially thousand) are stored in an array and all the balloons(could be in the hundreds) on the screen are stored in another array and every frame I loop through both arrays and draw each bullet/balloon. Now the problem is that I can't think of an efficient way to see if any bullet is colliding with any balloon every single frame when there are so many objects.

One thing I can thought of is looping through every balloon and then looping through every bullet to check if they are colliding, and it just doesn't seem like a good solution. The other solution I had was to blit all the balloons onto a surface and create a mask from that which I would use to check collisions however the problem that arises then is to determine the exact balloon object that was hit by the bullet in case of a collision and I can't think of any way to find that information from that mask. What would be the best way for me to implement this?

# Answer
Looping through the bullet array and the collider array is brute force way of doing it and will cost (at worst) `Bullet * Collider` amount of checks which can be very slow. Throwing multiple threads at the probably can make it a little better but overall it won't scale.

Here is a little list of things I can think of from my head you can do to speed things up in order of complexity (easiest to hardest):

## Collision shapes

Each collider usually has a shape which determines the amount of math needed to work if two are overlapping in space. Optimising this shape can lead to massive performance improvements (depending on what you are switching from). Circles are the cheapest to calculate, followed by squares, then convex hull (a mesh which doesn't go "in" at all), and actual meshes. It is often cheaper to have multiple circles represent something complex than a convex hull or even a square (if you have very optimised code).

If each bullet is a little circle and each enemy is a big circle all you have to check is if the distance between the centre points is larger than the combined radius of both circles, super fast check, great performance.

## Spatial partitioning

We know where all the enemies are and we know how big our play field is, so using that information we can divide the play field into squares (or rectangles) and then we'll keep a list of what is in each tile. When you then go to resolve a collision rather than looping through everything you do the following:

1. What tile is the centre point of my bullet?
2. Does my bullet collider go over the edge of the tile? (if so add each overlapping tile to the check tiles)
3. Loop though each enemy in the tile(s) and check if they collide, pick the most appropriate collision from there

This has the advantage that you only really care about the enemies in the same area where the collision is going to take place, the worst case is that you have to check 4 tiles but if you divide your play field into 100 tiles (this number will need a little fine tuning to your game) you still have a lot less total calculations.

## Quad Trees

Take what you made with spatial partitioning and nest the tiles, navigating this structure can be cheap depending on how it's layed out in memory (see Morton Codes) because you can reduce the cache misses on the CPU and effectively give easy patterns for the CPU to pick up on and pre-calculate your results before your program even asks for the result.

You can take this concept further with dynamic nesting of tiles so you can subdivide where there are more enemies into fine grain tiles (so you effectively have a limit on the amount of enemies in each tile), though this has some trade offs with either breaking Moron Code compatibility or creating large empty arrays. Depends on the implementation

## GPU compute shaders

Your CPU will have somewhere between 4 and 32 cores while using them all is really good the best you can do is use all of them, meanwhile your most GPUs are able to process thousands of things at the same time. If your target platform and performance requirements allow you to this can be a really good speedup (if your going for mobile this most likely won't be a silver bullet for you).

They differ based on the rendering API your using and have some quirks but if you look around for compute shader tutorials and the theory behind it you can move all the collision checks to the GPU while the CPU goes other things while waiting for the results.

There are other ways and many methods yet to be thought up so this sort of thing is always getting new optimisations and techniques...
> 2 votes

---
Tags: collision-detection, performance, python, pygame, tower-defense
---


# Question
Title: I did changed the text of a graphical text and set its new center origin. Should I reposition it in dead center again?
Should I re-position a graphical text in the dead center again, which I previously do, after editing the text of the graphical text, recalculate its new center origin of the text? I did see that with a new origin, the text automatically applied to whatever the previous x and y were. Does it a wasteful thing to add another duplicate line of code to set it in the dead center?

I saw this sample code from a book. It's confusing for beginners without any explanation for it. Why had the author added that line of code? It's dead center anyway without it.

```
// Draw some text
Text messageText;

// Assign the actual message
messageText.setString("Press Enter to start!");

// Position the text
FloatRect textRect = messageText.getLocalBounds();

messageText.setOrigin(textRect.left +
    textRect.width / 2.0f,
    textRect.top +
    textRect.height / 2.0f);

messageText.setPosition(1920 / 2.0f, 1080 / 2.0f);

// has the player been squished by a branch?
if (branchPositions[5] == playerSide)
{
    // Change the text of the message
    messageText.setString("SQUISHED!!");

    // Center it on the screen
    FloatRect textRect = messageText.getLocalBounds();
    messageText.setOrigin(textRect.left +
        textRect.width / 2.0f,
        textRect.top +
        textRect.height / 2.0f);

    messageText.setPosition(1920 / 2.0f, 1080 / 2.0f);  // Should I add do this line of code?
}

```

# Answer
> 3 votes
You are right; in this short example, the call is not needed.

However, consider this: what if you kept adding code between those two calls? what if you reused the same text object for different contexts? what if instead of reusing the same text object, you would create a new one for this new context?

Your future self would likely be happy to see that call there, just as a reminder that 1) it is actually set and 2) where it is positioning the object.

So although it is not *needed*, it is a good habit to place it there, right after you've set the new size and/or origin. The cost of this call is insignificant.

I suppose some experienced developers (the kind of devs that write books) 1) don't necessarily reflect on all those subtleties that experience brings and 2) don't think about writing it in their books.

---
Tags: sfml, position
---


# Question
Title: Function glBindBuffer access violation while executing
So I have a problem, I am calling some opengl frame buffer functions in my code but for some reason I get the error from the title. I am also calling many other opengl functions without any problems but with this particular one I have troubles. So problematic code:

```
void FrameBuffer::create()
{
    glCreateFramebuffers(1, &m_RendererId);
    glBindFramebuffer(GL_FRAMEBUFFER, m_RendererId);

    glCreateTextures(GL_TEXTURE_2D, 1, &m_ColorAttach);
    glBindTexture(GL_TEXTURE_2D, m_ColorAttach);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, m_buffSpec.Width, m_buffSpec.Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_ColorAttach, 0);

    glCreateTextures(GL_TEXTURE_2D, 1, &m_DepthAttach);
    glBindTexture(GL_TEXTURE_2D, m_DepthAttach);
    //glTexStorage2D(GL_TEXTURE_2D, 1, GL_DEPTH24_STENCIL8, m_buffSpec.Width, m_buffSpec.Height);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, m_buffSpec.Width, m_buffSpec.Height, 0, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, NULL); //(storage ili image??)
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, m_DepthAttach, 0);

    if (!glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE)
        std::cout << "Framebuffer status not OK" << std::endl;

    glBindFramebuffer(GL_FRAMEBUFFER, 0);
}

```

On the second line, calling bind frame buffer, I get this error. In my header file I do have all the needed uint32\_t ids. When I comment out that second line I get the same error but on glCreateTextures. What could be wrong here? This is a method from my frame buffer class. This is the code where the method is called:

```
EditorLayer::EditorLayer()
    : Layer("Example"),
    mVAO(std::make_shared<VertexArrayObject>()),
    mCubeVao(std::make_shared<VertexArrayObject>()),
    m_lib(std::make_shared<ShaderLibrary>()),
    camControl(std::make_shared<CameraController>()),
    textureCube(std::make_shared<CubeTexture>(m_Textures)),
    spec{ 400, 400 },
    m_FB(std::make_shared<FrameBuffer>(spec))
{
    m_FB->create();

    mCubeVao->generateVAO();
    mCubeVao->bindData(verticesCube, texind, 120, 36);
    mCubeVao->dataLayout(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), 0);
    mCubeVao->dataLayout(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), 3 * sizeof(float));
    mCubeVao->unbindVertexArrayObject();
    glEnable(GL_DEPTH_TEST);

    textureCube->loadTexture();

    activeScene.CreateEntity();
    m_lib->Load("shady", "C:/eng/Nube/GameApp/shaders/textureCube.glsl");

}

```

All the other stuff is just fine but this one thing, this frame buffer, is not working. Any ideas?

# Answer
> 0 votes
`glCreateFramebuffers()` is supported by version 4.5 and above:

|  | 2.0 | 2.1 | ... | 4.3 | 4.4 | 4.5 |
| --- | --- | --- | --- | --- | --- | --- |
| glCreateFramebuffers | - | - | ... | - | - |  |

Try changing your OpenGL version. Let me know if it worked.

---
Tags: opengl, c++, frame-buffer
---


# Question
Title: What will happen if I intend to display the hidden surface after clearing the window, draw the game objects, and then display the window again?
What will happen if I intend to display the hidden surface after clearing the window, draw the game objects, and then display the window again? Am I watching the drawing process of the objects? Is this process a graphical glitch? Is it bad only for the aesthetic or bad for the system?

```
window.clear();
window.display();
window.draw(spriteBackground);
window.draw(spritePlayer);
window.display();

```

# Answer
> 1 votes
From the documentation (emphasis mine):

> This **clear/draw/display** cycle is the **only good way** to draw things. **Don't try other strategies**, such as keeping pixels from the previous frame, "erasing" pixels, or drawing once and calling display multiple times. You'll get strange results due to double-buffering.

---
Tags: sfml, draw-order, double-buffering
---


# Question
Title: How can I fix Look rotation viewing vector is zero?
I was following a unity tutorial to make my character face in the position the camera is facing. After I finished the editing the script, I got an error at runtime saying, "Look rotation viewing vector is zero." On the line :

```
  Vector3 viewDir = player.position - new Vector3(transform.position.x, player.position.y, transform.position.z);
    orientation.forward = viewDir.normalized;

```

here is the rest of the code I wrote:

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

public class ThirdPersonCam : MonoBehaviour
{
     [Header("References")]
     public Transform orientation;
     public Transform player;
     public Transform playerObj;
     public Rigidbody rb;

     public float rotationSpeed;

    private void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

     void FixedUpdate()
     {
        Vector3 viewDir = player.position - new Vector3(transform.position.x, player.position.y, transform.position.z);
        orientation.forward = viewDir.normalized;

        // rotate the playerObj
        float horizontalInput = Input.GetAxis("Horizontal");
        float verticalInput = Input.GetAxis("Vertical");
        Vector3 inputDir = orientation.forward * verticalInput - orientation.right * horizontalInput;

        if(inputDir != Vector3.zero)
            playerObj.forward = Vector3.Slerp(playerObj.forward, inputDir.normalized, Time.deltaTime * rotationSpeed);
     }
}

```

# Answer
I added a if statement to check if the vector is zero:

```
if(viewDir != Vector3.zero){}

```

To:

```
Vector3 viewDir = player.position - new Vector3(transform.position.x, player.position.y, transform.position.z);
orientation.forward = viewDir.normalized;

```

And it fixed the error.
> 2 votes

# Answer
The problem is that the camera's position is ending up at the same position as the player's position. So, when you do this:

```
Vector3 viewDir = player.position - new Vector3(transform.position.x, player.position.y, transform.position.z);

```

`viewDir` ends up as a (0, 0, 0), and that cannot be normalized.

If you want the camera to face the same direction as the player, you could do something like this

```
var playerDir = player.transform.forward;
var viewDir = new Vector3(playerDir.x, camera.transform.forward.y, playerDir.z);
orientation.forward = viewDir.normalized;

```
> 0 votes

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


# Question
Title: error parsing expression, missplaced: func
I have been trying to follow Code with Tom's fps tutorial and I encountered this error on line 27. I don't know how to fix it and everything I've tried has not worked.

```
extends KinematicBody

export var speed = 10
export var acceleration = 5
export var gravity = 0.98
export var jump_power = 3
export var mouse_sensitivity = 0.3

onready var head = get_node("head")
onready var camera =get_node("head/camera")

var velocity = vector3()
var camera_x_rotation = 0

func _ready():
    input.set_mouse_mode(input.mouse_mode_captured)

func _input(event):
    if event is inputeventmousemotion:
        head.rotate_y(deg2rad(-event.relative.x * 0.3))

        var x_delta = event.relative.y *mouse_sensitivity
        if camera_x_rotation + x_delta > -90 and camera_x_rotation + x_delta < 90:
            camera.rotate_x(deg2rad(-x_delta))
            camera_x_rotation += x_delta

            func _process(delta)
            if input.is_action_just_pressed("ui_cancel"):
                Input.set_mouse_mode_visible

                func _physics_process(delta)
                var head_basis = head.get_global_transform().basis

                var direction = vector3()
                if input.is_action_pressed("move_forward"):
                    direction -= head_basis.z
                    elif input.is_action_pressed("move_backward")
                    direction += head.basis.z

                    if input.is_action_pressed("move_left")
                    direction -= head_basis.z
                    elif input.is_action_pressed("move_right")
                    direction += head.basis.x

                    direction = direction.normalized()

                    velocity = velocity.linear_interpolation(direction * speed, acceleration *delta)
                    velocity.y -= gravity

                    if input.is_action_just_pressed("jump") and is_on_floor():
                        velocity.y += jump_power

                        velocity = move_and_slide(velocity, vector3.up)

```

Godot marks error on the line that says `func _process(delta)`.

# Answer
> 0 votes
In GDScript, as you would know, nesting is whitespace based. So what you are doing is putting a method inside another. You can just not. Put the method outside (i.e. without indentation).

In fact, given that the method in question is called `_process` I presume you intend to override the virtual method `_process`. So what you have to do is precisely that: have no indentation (no white space before the code, so it is at the start of the line), so it is not inside the other method.

---

**Addendum**: After transcribing the code, I have noticed it has more errors of the same kind (and some capitalization errors too). However, it happens that Godot 3.x first checks for the indentations, and the parser only reports the first error.

Thus, I want to explain the indentation a little better. For example, in this code:

```
if input.is_action_pressed("move_forward"):
    direction -= head_basis.z
    elif input.is_action_pressed("move_backward")
    direction += head.basis.z

    if input.is_action_pressed("move_left")
    direction -= head_basis.z
    elif input.is_action_pressed("move_right")
    direction += head.basis.x

```

You need `:` after the conditions. This indicates to Godot that it is the start of a block:

```
if input.is_action_pressed("move_forward"):
    direction -= head_basis.z
    elif input.is_action_pressed("move_backward"):
    direction += head.basis.z

    if input.is_action_pressed("move_left"):
    direction -= head_basis.z
    elif input.is_action_pressed("move_right"):
    direction += head.basis.x

```

But that is not yet correct. Where does the block end? Currently, Godot would think that everything is inside the first `if`. And would also complain that the other blocks don't have anything inside. That is because you indicate what is inside with white spaces, like this:

```
if input.is_action_pressed("move_forward"):
    direction -= head_basis.z
elif input.is_action_pressed("move_backward"):
    direction += head.basis.z

if input.is_action_pressed("move_left"):
    direction -= head_basis.z
elif input.is_action_pressed("move_right"):
    direction += head.basis.x

```

To reiterate: whitespace is important in GDScript. I hope that makes sense. And yes, the same issue happens with methods and other statements.

*You will see the capitalization errors once you fix the erros of this kind. I suppose you will be able to fix those with help of autocomplete.*

---

If you did actually intend to put a method inside another, know that **Godot 3.x does not support nested methods.** *In that case, you might be interested in Godot 4.0, currently in Alpha at the time of writing, which has method expressions. See GDScript progress report: Feature-complete for 4.0.*

---
Tags: godot, gdscript
---


# Question
Title: What does the 'step' node do in Unreal Engine?
In this youtube tutorial the instructor is using the step node as opposed to the power node to make the contrast of the image higher. I'm looking for documentation on what the 'step' node does to understand it better but couldn't find it on the official unreal docs website. Could someone explain the 'step' node to me and point me in the right direction?

# Answer
Here is what the Unreal documentation has to say:

> The Step Material Expression returns 0 or 1 for every value of X, depending on whether it is greater than or less than the reference value in Y.
>
> Below, a linear gradient (0 to 1) is plugged into the X input. The value in Y (0.25) acts as the reference value. Every value on the gradient below 0.25 on the returns a 0 (black), every value greater than or equal to 0.25 returns a 1 (white).
>
> *Note that the threshold between black and white moves when you increase the value in Y*.
>
> The Step expression is useful when an abrupt on/off effect is needed. For example, you could also use a Step expression to simplify a grayscale texture into a black and white mask.
> 3 votes

---
Tags: unreal
---


title: Scale camera to fit screen size unity

text:
# Question
Title: Scale camera to fit screen size unity
My background and gameobjects are 2d sprites not UI images ,I want to know how to make my background scale with screen size and positions of 2d sprits on it don't change after building game (webGl) like scale canvas with screen size and anchor points in UI elements .

Before building the game

After building

# Answer
> 22 votes
You can adjust the camera's height so it scales with the width of the screen like so:

(Place this script on your Camera object)

```
[ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
public class MatchWidth : MonoBehaviour {

    // Set this to the in-world distance between the left & right edges of your scene.
    public float sceneWidth = 10;

    Camera _camera;
    void Start() {
        _camera = GetComponent<Camera>();
    }

    // Adjust the camera's height so the desired scene width fits in view
    // even if the screen/window size changes dynamically.
    void Update() {
        float unitsPerPixel = sceneWidth / Screen.width;

        float desiredHalfHeight = 0.5f * unitsPerPixel * Screen.height;

        _camera.orthographicSize = desiredHalfHeight;
    }
}

```

If you're using a perspective camera, then instead you'd use...

```
public float horizontalFoV = 90.0f;

// ...

void Update() {
   float halfWidth = Mathf.Tan(0.5f * horizontalFoV * Mathf.Deg2Rad);

   float halfHeight = halfWidth * Screen.height / Screen.width;

   float verticalFoV = 2.0f * Mathf.Atan(halfHeight) * Mathf.Rad2Deg;

   _camera.fieldOfView = verticalFoV;
}

```

If you want to shrink your viewport to add letterboxes instead of showing additional height above/below, you can use the technique described in this answer.

# Answer
> 0 votes
Using 2D, you likely don't want to manipulate the camera. I recommend adjusting the scale of the background object (container or sprite).

```
[SerializeField] private Camera mainCamera;
[SerializeField] private SpriteRenderer spriteRenderer;

private void Start() {
    var spriteBounds = spriteRenderer.bounds; // Sprite to fit viewport
    var worldScale = mainCamera.ViewportToWorldPoint(Vector3.one);
    var localScale = 2 * Math.Max(
        worldScale.x / spriteBounds.size.x * transform.localScale.x,
        worldScale.y / spriteBounds.size.y * transform.localScale.y);

    transform.localScale = new Vector3(localScale, localScale, 1);
}

```

You can apply this script to the background sprite itself or to a container which holds the background sprite.

# Answer
> -1 votes
I think if you decrease the scale size to 1x from above the Game view, it will fit.

---
Tags: unity, 2d, camera, scale
---


# Question
Title: Are there any practical applications for clearing the screen with a specific color?
Why is it common in the 2D game frameworks for the clear function to have the option of clearing the entire screen with a color? Why is this option available to us? Are there any practical applications for clearing the screen with a specific color aside from the default black one?

# Answer
Clearing the color buffer can be optional. For example, if you know that you're going to overwrite every pixel each frame, then you might decide to not clear at all. On the other hand, some drivers might use it as a hint that the previous frame's contents are no longer needed and can be discarded, and optimise around that.

If you're going to clear the color buffer then you need to clear it to some value, and in a 2D game it might make sense to clear it to whatever background color is appropriate for the current scene. For a space scene you might clear to black, for other scenes maybe blue for the sky, or whatever.

Another reason for clearing is if you implement Quake style "noclip" as a development tool or cheat. In that case, when the player moves outside of the world it would give a hall of mirrors effect, so clearing avoids that, and you might pick a color that everything is still visible against.

Yet another reason might be as a debugging tool. If you want to ensure that you draw every pixel each frame, then clearing to something like bright magenta, then checking for bright magenta areas on screen, could be one way of doing it.
> 4 votes

---
Tags: sfml, color, love2d
---


title: Rigging a 2D face on a 3D character

text:
# Question
Title: Rigging a 2D face on a 3D character
I have a question about rigging in Unity -. Is there a way to rig a 2D face on a 3D character in such a way that you are able to get a smooth transition between the different keyed mouth- and eyeshapes in an animation? (Kind of like the cutscenes in the current lego games). So far I've only found tutorials about techniques that are based on alternating between pre-drawn mouthshapes, etc. that are stored on a texture and this way the transitions usually don't look very fluent. I would be very grateful for any kind of tips :) Thank you!

# Answer
My approach to animating a 2d face would be the same as that to animating a 3d face: By doing it in the 3d modeling program. I would break up the face into multiple polygons and then animate their vertices. This would deform the face texture. For example, turn a smiling face into a frowning face or rotate the eyebrows from angry to sad.

Another approach could be to use the 2d animation system and try to render the results to a render texture which is then applied to the 3d model.

By the way: TT Games, the company that made most of the recent Lego titles, developed an own inhouse engine for those games. So they probably have their own specialized tooling for doing those characteristic 2d facial animations on 3d characters.
> 1 votes

---
Tags: unity, 2d, 3d, rigging, face
---


# Question
Title: Use localPosition or position to store character's joints position?
I have a character and I need to save all the joints positions, like Hip - Leftleg - Rightleg.

Should I use `transform.position` or `transform.localPosition`?

# Answer
> 1 votes
You can use `localPosition` because it's the position of the child relative to its parent. The `transform.position` is not, it's relative the world position, if you want to store the joint position.

---
Tags: unity
---


# Question
Title: Unity physics2d object repelling itself from static colliders
Is there a way to have a 2D object repel itself from any colliders within a radius? A PointEffector2D will repel other colliders, but no force is exerted on the object containing the effector.

I also tried to use `OnCollisionEnter2D()` and `OnCollisionStay2D()` on a kinematic rigidbody2D to detect other colliders and emit a force in that direction, but it only seems to register collisions with dynamic rigidbodies and not static colliders.

The use case is as a power up for spaceship to make it bounce off the terrain which is composed of EdgeColliders.

# Answer
In the end emitting raycasts in all directions and adding a force in the opposite direction of the nearest hit worked quite well

    void Radar()
    {
        float range = 2f;
        float force = 15;

        float increment = 10f;
        Vector2 direction = Vector2.up;
        Vector2 closestPoint = Vector2.zero;
        float minDistance = float.PositiveInfinity;
        bool found = false;

        for (int i = 0; i < 360/increment; i++)
        {
            RaycastHit2D hit =  Physics2D.Raycast(transform.position, direction, range);
            if (hit.collider != null)
            {
                found = true;
                float distance = Vector2.Distance(hit.point, transform.position);
                Debug.DrawLine(transform.position, closestPoint);
                if (distance < minDistance)
                    closestPoint = hit.point;
                minDistance = Mathf.Min(distance, minDistance);
            }
            direction = Hutl.rotatePointDegrees(direction, increment);
        }

        if (found)
        {
            Debug.DrawLine(transform.position, closestPoint);
            Vector2 forceDirection = ((Vector2) transform.position - closestPoint).normalized;
            rb.AddForce(forceDirection * force);
        }
```

> 0 votes

---
Tags: unity, physics
---


# Question
Title: Implementing the integration workarounds for AnimationRigging and Animancer
I am working on a project using both Animancer and Animation Rigging. They mostly work nicely together, but, as described here, there is one problem: When you add a new `AnimancerState` to the component, `Animator.Rebind()` gets called, and that resets the weights of all AnimationRigging constraints to their initial value. So, if those weights have been modified at runtime, you lose those modifications.

Now, Kybernetik is kind enough to suggest two workarounds (again, see this link), but, as he points out, neither are very convenient. I already have a slightly-convoluted-but-not-too-awful plan for implementing the second one (caching and reapplying the constraint values when needed), but I was thinking that the first one (creating all the states on startup) is much neater.

The plan for that would be to have a wrapper class around `AnimationClip`, which registers a new state on the `AnimancerComponent` when the game starts. That way, the whole solution is just to find every case where I have a serialized `AnimationClip`, and replace it with this new wrapper.

And so we get to the question. Is there a way I can do this? At first I thought about using `ScriptableObjects`, since they have an `Awake()` method, but of course that means the `ScriptableObject` would need a reference to the scene object that contains the `AnimancerComponent`... and that simply does not work when you can have, for example, many instances of the same prefab that all use the `AnimationClip`, each one with its own `AnimancerComponent`.

My current hunch is that there might be a way to create the wrapper class as a serialized `System.Object` (that way, it can be serialized by value and sit inside the prefab itself, and so find the `AnimancerComponent` in its own hierarchy) that does it. But, of course, the problem then becomes that a `System.Object` does not have a `Start()` or `Awake()` method that can be used to initialize the whole thing automatically. My last bullet here would be to use `System.Reflection` to find all instances of the class on startup and call an `Initialize()` method... but, man, do I not want to do that.

Any ideas for how to solve the problem would be appreciated. However, as I said, I do already have plans that would *work*, so I guess what I'm really looking for is not just a soultion, but a solution that is not confusing and ugly.

# Answer
> 0 votes
Well, I am not known for my patience, so I already implemented my idea for the second workaround (caching and correcting), and it ended up not being that bad. Basically just created a wrapper for the `AnimancerComponent` that handles the caching and reapplying values as necessary. The idea, of course, being that you never interact directly with the `AnimancerComponent`, and instead always do it through this. The following code does not at all cover all things that can be done with `AnimancerComponent`, only those that I happened to need, but it should be easy to extend.

Also, two caveats: currently it only caches weights (but, again, you could cache more stuff by just creating more dictionaries as needed), and most importantly, you need to manually call `registerWeight()` whenever you make a change to a constraint somewhere else in code. But, all in all, it does the job ok.

```
using Animancer;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Animations.Rigging;

[DefaultExecutionOrder(1000)]
public class AnimancerAnimationRigging : MonoBehaviour
{
    Dictionary<IRigConstraint, float> weights;

    AnimancerComponent animancerComponent;
    public Animator Animator => animancerComponent.Animator;
    public AnimancerPlayable.StateDictionary States => animancerComponent.States;
    public AnimancerPlayable.LayerList Layers => animancerComponent.Layers;

    void Awake()
    {
        weights = new Dictionary<IRigConstraint, float>();
        animancerComponent = GetComponent<AnimancerComponent>();
        RigBuilder _RigBuilder = GetComponent<RigBuilder>();
        animancerComponent.Playable.DestroyGraph();
        animancerComponent.InitializePlayable(_RigBuilder.graph);
        animancerComponent.Playable.KeepChildrenConnected = true;
    }

    public AnimancerState GetOrCreate(AnimationClip clip , int layer = 0){
        AnimancerState animancerState;
        if( !animancerComponent.States.TryGet(clip, out animancerState) ){
            animancerState = animancerComponent.Layers[layer].GetOrCreateState(clip);
            restoreConstraints();
        }
        return animancerState;
    }
    public AnimancerState GetOrCreate(object key, AnimationClip clip , int layer = 0){
        AnimancerState animancerState;
        if( !animancerComponent.States.TryGet(key, out animancerState) ){
            animancerState = animancerComponent.Layers[layer].GetOrCreateState(key, clip);
            restoreConstraints();
        }
        return animancerState;
    }

    public AnimancerState GetOrCreate(ITransition transition, int layer=0){
        AnimancerState animancerState;
        if( !animancerComponent.States.TryGet(transition, out animancerState) ){
            animancerState = animancerComponent.Layers[layer].GetOrCreateState(transition);

            restoreConstraints();
        }
        return animancerState;
    }

    public AnimancerState Play(AnimationClip clip, float fadeTime, Animancer.FadeMode fadeMode = Animancer.FadeMode.FixedSpeed, int layer = 0){
        AnimancerState animancerState = GetOrCreate(clip, layer);
        animancerComponent.Layers[layer].Play(animancerState, fadeTime, fadeMode);
        return animancerState;
    }

    public AnimancerState Play(AnimancerState animancerState, float fadeTime, Animancer.FadeMode fadeMode = Animancer.FadeMode.FixedSpeed, int layer = 0){
        animancerComponent.Layers[layer].Play(animancerState, fadeTime, fadeMode);
        return animancerState;
    }

    public AnimancerState Play(ITransition clip, float fadeTime, Animancer.FadeMode fadeMode = Animancer.FadeMode.FixedSpeed, int layer = 0){
        AnimancerState animancerState = GetOrCreate(clip, layer);
        animancerComponent.Layers[layer].Play(clip, fadeTime, fadeMode);
        return animancerState;
    }

    public void registerWeight(IRigConstraint constraint){
        weights[constraint] = constraint.weight;
    }

    void restoreConstraints(){

        animancerComponent.Animator.Rebind();
        foreach(var pair in weights){
            pair.Key.weight = pair.Value;
        }

        //prevent recursive evaluation of the playable graph if --for example-- you get here while executing the callback of an animancer event
        if(AnimancerPlayable.Current!=animancerComponent.Playable)
            animancerComponent.Evaluate();
    }
}

```

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


# Question
Title: Swipe trees in a given direction using events and delegates
I'm sending events out like this in ScreenInputManager.cs, so that trees in my scene will move in the direction of a given swipe:

```
public delegate void SendSwipe(string swipeDirection);
public event SendSwipe moveGameItems;

private void Update()
    {
        if (Touch.activeFingers.Count == 1) {

            // other code here not related to this
            TriggerSwipe(startPos, endPos);
        }
    }

 private void TriggerSwipe(Vector2 start, Vector2 end)
    {
            if (Vector2.Dot(Vector2.left, direction2D) > directionThreshhold)
            {
                moveGameItems("left");
            }

            if (Vector2.Dot(Vector2.right, direction2D) > directionThreshhold)
            {
                moveGameItems("right");
            }
        }
    }

```

Then, in another script, I'm subscribing to those events, like this:

```
private ScreenInputManager inputManager;

    private void OnEnable()
    {
        inputManager.moveGameItems += MoveTree;
    }

    private void OnDisable()
    {
        inputManager.moveGameItems -= MoveTree;
    }

    private void Awake()
    {
        inputManager = ScreenInputManager.Instance;
    }

    private void MoveTree(string direction)
    {

        // code here
    }

```

Problem: However, MoveTree is called continuously - as long as the swipe continues. I think this could because TriggerSwipe() is in Update, but then again, when I Debug.Log in the function itself, it only seems to called it is actually swiped.

What I want:

I want to call MoveTree only when the screen is swiped. I have tried using boolean flags, etc., but the problem is I also want to be able to interrupt MoveTree with a swipe in the other direction if I need to.

So the input from the delegate has to be steadily received, but when it moves in a specific direction, it should move in that direction once until it has to move in another direction.

What I've tried:

I have tried boolean flags, using "yield return" in coroutines, etc., but I don't seem to be able to get it so it can be interrupted to go in the other direction if I need to.

# Answer
> 0 votes
If the thing is that you only want the event to be called when changing directions, you could try storing the direction of the most recent movement, and comparing it to the direction of the current one. If they point in the same direction, ignore it; otherwise, call the event. Something like this comes to mind:

```
public delegate void SendSwipe(string swipeDirection);
public event SendSwipe moveGameItems;

Vector2 directionLastSwipe;
bool alreadyMoving;

private void Update()
{
    if (Touch.activeFingers.Count == 1) {
        // other code here not related to this
        TriggerSwipe(startPos, endPos);
        alreadyMoving = true;
    }
    else
        alreadyMoving = false;
}

private void TriggerSwipe(Vector2 start, Vector2 end)
{
    //I'm guessing direction2D is the current swipe direction
    if(alreadyMoving && Vector2.Dot(directionLastSwipe, direction2D)>0)
        return;

    if (Vector2.Dot(Vector2.left, direction2D) > directionThreshhold)
    {
        moveGameItems("left");
        directionLastSwipe = direction2D;
    }

    if (Vector2.Dot(Vector2.right, direction2D) > directionThreshhold)
    {
        moveGameItems("right");
        directionLastSwipe = direction2D;
    }
}

```

---
Tags: unity
---


# Question
Title: How to handle many event triggers without hard-coding checks for all of them into the game loop?
Let's say I'm developing a horror game. For a jumpscare when entering room #1, the easiest way would be like this example:

```
void gameLoop() {
    if (playerEntersRoom1 && !playerHasBeenInRoom1) {
        playerHasBeenInRoom1 = true;
        jumpscareForRoom1();
    }
}

```

However this doesn't seem like a good solution to me, especially because the code would become quiet large when adding more and more of such events at some point. What's the way to go in a game engine like Unity?

# Answer
I think using trigger objects with their own behaviour scripts, as suggested by @Zibelas, is probably the easiest way to manage this in unity. So, you would have a `GameObject` in your room1 that has a `Collider` marked as trigger (technically, you might be able to do this with a normal collider as well, as long as you are not using physics, but whatever). That object would also contain a script (lets call it `JumpscareScript` for the sake of argument) like this:

```
public class JumpscareScript : MonoBehaviour{
    bool playerHasBeenInRoom1;

    void Start(){
        playerHasBeenInRoom1 = false;
    }

    void OnTriggerEnter() {
        if (!playerHasBeenInRoom1) {
            playerHasBeenInRoom1 = true;
            jumpscareForRoom1();
        }
    }

    void jumpscareForRoom1(){
        // boo!
    }
}

```

That way, the rest of your code does not even need to know that this jumpscare stuff exists, it's all perfectly encapsulated in this one object. Of course, you could make the jumpscare class more generalizable by either having the jumpscare method be virtual, so you could override it in every object that has a jumpscare, or even have it be a delegate so each instace of the class has its own jumpscare without having to create lots of inheriting classes. But I'll leave those details to you, since I don't know your project or how you like to work.

The thing is, Unity is kind of "meant to" be used through this component-based way of organizing your code, where separate scripts are completely autonomous. So, a lot of the time, you wouldn't even have a main loop (of course, one does probably exist on the hidden C++ code of the engine) but you mostly are meant to use the "magical" functions in monobehaviours (`Start`, `Update`, `OnCollisionEnter`, etc) as the way to control the flow of the execution.

That is, of course, not to say it is **wrong** to circunvent all of this and make your own game loop, but it is definitely swimming against the tide.
> 3 votes

# Answer
Here is a short script which is surprisingly simple, yet surprisingly powerful:

```
using UnityEngine;
using UnityEngine.Events;

[RequireComponent(typeof(Collider))]
public class TriggerArea : MonoBehaviour
{
    public GameObject triggeredBy;
    public UnityEvent TriggerEnter;

    private void OnTriggerEnter(Collider other) {
        if (other.gameObject == triggeredBy) {
            TriggerEnter.Invoke();
        }
    }
}

```

What does this script do? When you add it to a game object with a collider **which has "Is Trigger?" enabled** (important!), you will see this in the inspector:

First you have a "Triggered By" field for a GameObject. Assign the object you want to detect, which is probably your Player.

The box below that is a collection of event actions. When you click the plus icon, then you can assign any method\* of any components of any game object in your scene. And you can assign as many as you want. When those methods take parameters, then you can even state what values you want to pass to them.

Then, when the object you assigned enters the trigger-collider, all those methods will be called at once.

This allows you to do... basically anything you can think of. Activate objects, deactivate objects, play animations, play sounds, call your own methods of your own scripts... whatever. And you don't need to write a single additional line of code for that. You can do it all in the inspector. So it's a super designer-friendly script which enables level-designers without programming knowledge to create simple scripted events.

Want the event to trigger only once? Easy, then just assign `GameObject.SetActive(false)` of the trigger area itself, so the trigger area just disables itself when triggering.

Here is an example use-case of this script which plays an audio clip, activates a previously deactivated monster, causes a door to open and then disables itself so it does not trigger again:

Happy jumpscaring!

<sub> * OK, **most** methods. It is limited to methods which take either no parameters or a single parameter that is either an elementary type or some kind of Unity Object. But that covers quite a lot.</sub>
> 2 votes

# Answer
I don't use `unity`, but you wouldn't put that kind of thing directly in your main game loop for the reasons you already cite: the game loop gets too large and too difficult to keep organized. The archetypal game loop example is usually given as:

```
while running == True: #or maybe while state == 'running'
    processInputs();   #process inputs and events
    updateWorld();     #calculate things and update world state
    renderView();      #actually draw things to the display

```

Both your `processInputs()` and `updateWorld()` functions would dispatch out to lengthy lists of things like `processEventQueue()`, `checkPlayerLocation()`, `checkMobs()`, `checkForJumpScares()`, etc.

For a real-time first-person player moving through a live map you would probably want to have a `playerEntersRoom` event, with data indicating which room was being entered (room 1), and which gets added to the event queue when the player crosses an arbitrary point on the map. (By this point you would have created your own map format, probably based on an existing format, and written a map editor to help create and edit your maps.) That event would get processed by `processEventQueue()` to initiate `jumpScareForRoom1()`.

If your game is a turn-based graphical horror instead of real time then your processing gets a lot easier. You may not necessarily have an event queue. `processInputs()` would get you into the room with a simple keypress or mouse click, and `updateWorld()` would take that information and initiate `jumpScareForRoom1()`.

So you're correct that you wouldn't want to put that kind of thing directly in your main game loop. Also, I believe that this question is more one of general game organization than for `unity` specifically.
> -2 votes

---
Tags: unity
---


# Question
Title: Cannot open a package from the Unity Asset Store website
Yesterday I found an asset on the Unity Asset Store website, clicked the button "Open in Unity", and it was opened in Unity.

Today, when I did the same thing, I got the error message below:

I opened the Defaults Apps page in Windows 10 Settings. But what do I do from here?

# Answer
I did not find a solution, but I found a workaround:

* In the Unity website, click "Add to My Assets";
* Go to the Unity editor;
* Open the Asset Store window;
* Click my initials (at the top-right corner; for me they are ES);
* Click "My Assets";
* Find the desired asset, click Download and then click Import.

I still do not understand why clicking "Open in Unity" in the website stopped working, and how to fix it.
> 2 votes

# Answer
I think that for some reason windows doesn't know what application to open the package with. You should open unity and go to `Assets -> Import package -> Custom package` and just open the file.
> 1 votes

# Answer
Generally for questions about Windows configuration, you can ask on Super User.

You can scroll to the bottom of the Default apps window and choose "Choose default apps by file type" then scroll down to UnityPackage and click "Choose a default" - then pick your Unity version of choice.

If you can't get Windows to recognize the Unity package type, then you can also open your Unity project and pull the package in with `Assets > Import Package`
> 0 votes

# Answer
I had a similar issue, but it was due to a missing editor version.

In my case, I run 2020 LTS; I tested 2022, then removed 2022, but Windows regedit still retains the latest installed version:

To fix this, search for a key containing `unity.exe` in regedit, then modify the regkey with you current version, to something like this.

Key:

```
HKEY_CLASSES_ROOT\Unity package file\shell\edit\command

```

Value:

```
"C:\Program Files\Unity\Hub\Editor\2020.3.26f1\Editor\Unity.exe" -openfile "%1"

```
> 0 votes

---
Tags: unity, windows, asset-management
---


# Question
Title: Pygame, jump counter resetting on first button press
Been learning my first platformer game based on this tutorial.

I decided I wanted to go off book and make it so the player could jump a second time before hitting the ground. I used the blit function to show a jump counter under the score as well.

I was using `if player_rect.bottom == 300: player.jump.counter = 2` (where 300 is my ground height) to reset the jump counter. However this seems to mean the first time the player jumps the counter does not reduce, I believe because they still `== 300`. On the second jump (once the player is in the air) the code works as intended and resets when the player lands again. I have tried adding a `player_jumped = False` variable but that hasnt helped and when I tried `time.sleep(0.01)` it slowed the whole code and the frame rate dropped.

So when you run the code the counter is at `2` to start, first space and the counter stays as `2` (this is the issue), second space and it reduces to `1`, third space and it reduces to `0` and any more spaces and nothing happens until the player touches down and the counter resets.

I believe I somehow need to make it so that there is a delay between the player jumping and then the code checking if the player is on the ground and resetting the counter to `2`, I have tried moving the line of code to different positions inside the loop but that hasnt helped.

Please see code below, mainly from the keyboard input heading onwards:

```
import pygame
from sys import exit

pygame.init()
screen = pygame.display.set_mode((800,400))
pygame.display.set_caption("First game")
clock = pygame.time.Clock()
font = pygame.font.Font('Assets/font/Pixeltype.ttf', 50)
pink_colour = pygame.Color(242,172,170)

sky_surface = pygame.image.load("Assets/graphics/Sky.png").convert()

ground_surface = pygame.image.load("Assets/graphics/ground.png").convert()

score_surface = font.render("This is a test", False, 'Black').convert()
score_rect = score_surface.get_rect(center = (400, 50))

snail_surface = pygame.image.load('Assets/graphics/snail/snail1.png').convert_alpha()
snail_rect = snail_surface.get_rect(midbottom = (600,300))

player_surface = pygame.image.load('Assets/graphics/Player/player_walk_1.png').convert_alpha()
player_rect = player_surface.get_rect(midbottom = (80, 300))

player_gravity = 0
player_jump_counter = 2
player_has_jumped = False

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

```

## Keyboard input

```
        if event.type == pygame.KEYDOWN:
            if player_jump_counter > 0:
                if event.key == pygame.K_SPACE:
                    player_jump_counter -= 1
                    player_gravity = -20
                    player_has_jumped = True
                    print(player_jump_counter)

        # Mouse input
        if event.type == pygame.MOUSEBUTTONDOWN:
            if player_rect.collidepoint(event.pos):
                player_gravity = -20

    if player_has_jumped == True:
        if player_rect.bottom == 300:
            player_jump_counter = 2
            player_has_jumped = False

    screen.blit(sky_surface, (0, 0))
    screen.blit(ground_surface, (0,300))
    pygame.draw.rect(screen, pink_colour, score_rect)
    pygame.draw.rect(screen, pink_colour, score_rect, 50)
    jump_surface = font.render(str(player_jump_counter), False, "Black")
    jump_rect = jump_surface.get_rect(midbottom = (400, 110))
    screen.blit(score_surface, score_rect)
    screen.blit(jump_surface, jump_rect)

# snail movement
    snail_rect.x -= 4
    if snail_rect.right <= 0:
        snail_rect.left = 800

    screen.blit(snail_surface, snail_rect)

# player movement
    player_gravity += 1
    player_rect.y += player_gravity
    if player_rect.bottom >= 300:
        player_rect.bottom = 300
    screen.blit(player_surface, player_rect)

    pygame.display.update()
    clock.tick(60)

```

# Answer
The code logic of each frame can be simplified to:

1. Read keyboard input and set gravity.
2. Hit ground check (using position).
3. Player move (using gravity to set position).

See what's wrong? When the jump command is in effect, the character is considered to be on the ground during the hitting ground check (because the character has not yet taken off at this time), and the jump count is reset. Then gravity takes effect and the character jumps. So the jump count is still `2` after the first jump.

You can adjust the order to:

`Read keyboard input and set gravity` -\> `Player move` -\> `Hit ground check`
> 0 votes

---
Tags: game-loop, pygame, jumping
---


# Question
Title: Is there a standard format to store game asset data as a binary archive?
I am building a prototype for a 2D tile based game and I have several sprite sheets in separate image files that in want to use for animation as well as game logic attributes associated each sprite sheet (such as the size of the spite and the start coordinates). The stumbling block I am running up against is how to properly store this data.

Opening several hundred image files as well as one or more files holding the attribute data is impractical even assuming the OS allowed for so many file descriptors for a single process. This lead me to think about designing some container format that contained all of the relevant game assets without superfluous metadata as well as game parameters for the logic. However before I design something on my own I wanted to see if there was a common standard people use. The only thing I could dig up was something like dooms WAD but I didn't find much about the file format itself.

Do games have something close to a standard for an asset container?

# Answer
> 2 votes
**No, there isn't.** Every other game does it differently (some even keep their assets as individual files).

---

> I am building a prototype

I would not bother about assets packaging just yet. It's a low-priority thing. 99 of 100 players will appreciate more fun game over the game that stores the assets "just right". At the prototype stage you are unlikely to bump into any file-management restrictions (unless you do something really stupid, OS will allow you to use like 10k+ files without a word). Sure, the I/O could be a bit slower due to fragmentation (on HDD), but you are going to load everything into RAM anyway, so don't bother yet.

> Opening several hundred image files

Just make sure to open-\>load-\>close. Don't keep files lingering opened for no reason.

# Answer
> 1 votes
No, there isn't. Every game engine has a different solution for this problem.

But when you don't want to invest the time and energy into creating a homebrewed asset pack format, then you can simply get a library for reading a standard archive format like zip or tar and use that. I have also seen and used libraries which are able to combine both regular directories and archive files into a combined "virtual filesystem", so you can access all those files in the same way without having to bother if they are in compressed archives or regular files.

If you don't want end-users to peek at your asset files, then just giving those archive files a different file extension will deter the majority of users.

---
Tags: assets, file-format, asset-management
---


# Question
Title: Why does pulling the camera back in a 2D game not affect ortho size?
I have a 2.5D game. I have multiple layers of objects to simulate parallax, and for maximum flexibility, I am using Unity3D to create it.

I have "Free Aspect" selected. I have an orthographic camera that needs to be pulled back on the Z axis to -10 to see everything on the screen. My orthographic size needs to be set to "6" to make sure everything is seen, otherwise it just is mega zoomed in.

Why is it that when I try to pull my camera back, so it's -40, the orthographic size is unaffected? If orthographic size is the "zoom" on the camera, then surely pulling the whole camera back and zooming in should do the trick, or vice versa?

Putting in a value of 6 feels super arbitrary, so I want to know what can be done to make the orthographic size 1 and still see everything on my screen.

# Answer
Distance to the camera has no effect, because orthographic projection is a form of parallel projection and has no perspective.

Imagine a cube. Now draw a line from each corner towards the camera. In perspective projection, which is modelled after how our eyes see the world, these lines all collapse in a single point, which in reality is the focal point of your eye.

In parallel projection, these lines do not collapse into a single point, but rather all point in the same direction, being parallel with no point of intersection, ever. Now imagine a piece of paper, where all the lines impact. Moving the paper towards the cube or away from it has no effect on the location of the points of impact of the lines, because they are *parallel*. Thus, the size of the projection on the paper stays the same, no matter how far away the paper is from the cube.

In Unity, the distance still matters, because objects that are located behind the camera will not be rendered.
> 6 votes

---
Tags: unity, camera
---


title: Change sprite angle on sloping ground

text:
# Question
Title: Change sprite angle on sloping ground
I have a problem here with GameMaker built-in physics environment.My player is designed to be on a skateboard. I want my player to rotate its sprite, according to the kind of fixture(up or down slopes) he is moving on.I've tried everything i could and everything i could find, but it didn't help me much, because the object is rotating in a very strange way.I enabled some flags to see the mask. Also, I've been studying vector algebra and i know it the angle between vector x speed and vector y speed should be the direction. Please help. Here's what i have so far:

1 object which is the player
Information about object: obj\_Player
Sprite: sprite7
Solid: false
Visible: true
Depth: 0
Persistent: false
Parent: obj\_Static\_Parent
Children:
Mask:
Physics
Start Awake: true
Is Kinematic: false
Is Sensor: false
Density: 0.5
Restitution: 0.1
Group: 0
Linear Damping: 0
Angular Damping: 0
Friction: 0.2
Shape: Polygon
Points:
(76, 52) (76, 60) (0, 56) (0, 52) Create Event: execute code:

```
///Initialize the tires
var half = sprite_width / 2;
var halfy = sprite_height / 2;
var tire = instance_create(x-half+12,y+halfy,obj_Wheel);
physics_joint_revolute_create(id,tire,tire.x,tire.y,0,0,0,0,0,0,false);
var tire = instance_create(x+half+12,y+halfy,obj_Wheel);
physics_joint_revolute_create(id,tire,tire.x,tire.y,0,0,0,0,0,0,false);

```

**Step Event:** execute code:

```
//Code
facing = -point_direction(0, 0, phy_speed_x, phy_speed_y);
phy_fixed_rotation = true;
phy_rotation = facing;

//Move him
if(keyboard_check(vk_space)) {
physics_apply_impulse(x,y,0,-100);
}
if mouse_check_button(mb_left)
{
phy_position_x = mouse_x;
phy_position_y = mouse_y;
}

```

**Information about object: obj\_Wheel** Sprite: spr\_Wheel
Solid: false
Visible: true
Depth: 0
Persistent: false
Parent: obj\_Static\_Parent
Children:
Mask:
Physics
Start Awake: true
Is Kinematic: false
Is Sensor: false
Density: 0.05
Restitution: 0.1
Group: 0
Linear Damping: 0.1
Angular Damping: 0.1
Friction: 30
Shape: Circle
Points: (8, 8) (8, 8) Create Event: execute code:
**Keyboard Event for Key:**
execute code:
physics\_apply\_torque(-100);
**Keyboard Event for Key:**
execute code:
physics\_apply\_torque(100);

And here is the result:
https://i.stack.imgur.com/sn1qh.gif

# Answer
> 0 votes
I'm currently at work so I can't get my example of a game I did with similar physics in GameMaker (Awesome you're using it bte) but I made the object cast a ray down from the center of the player's object, then I set the sprite to rotate based on the rotation of the ray cast to what it was touching *If that made any sense* this can be smooth, but also may not be.

*way2:*

You could always consider using a method that rotates based on the object it touches, for example your game will most likely have pre-made ramps, etc. so have it when the player touches one ramp, they will rotate to a certain degree *Good cheat until you have a quarter pipe*

*way3:*

```
image_angle = <Some sort of formula for your object, maybe object_angle>;

```

The above needs some sort of code that will let it get the angle of an object based on its sprite

*way4:*

Make it quirky as hell and have the player have to move the player, otherwise they will just manual down the ramp using

```
image_angle = point_direction(x, y, mouse_x, mouse_y);

```

This way isn't a fix, but would look funny right?

But yeah, these are a few ways of the top of my head I can think of to make it work. without my projects in front of me it would take more time than its worth for me to remember how I did it. Hope it helps.

# Answer
> 0 votes
Depending on your movement logic, you could approximate the slope angle depending on the relative direction your character is moving towards:

```
var _slope = 0;
if (isGrounded)
{
    _slope = point_direction(xprevious, yprevious, x, y);
}
return _slope;

```

Here, `isGrounded` is an instance variable that detects whenever your character is walking on solid ground rather than, say, jumping.

The above function doesn't account for the sprite scaling (used to implement left/right facing), but you can fix this by either tracking the intended facing side via a dedicated variable, or forcing the character to face their walking direction.

---
Tags: physics, vector, game-maker, angles, direction
---


# Question
Title: Looking for a middle ground between raw random and shuffle bags
I am working on a RPG that I have implemented spells with status effects that can be applied x% of the time. For instance a fire spell has a 25% chance to apply a burning debuff.

Initially I just put it at 0.25 and checked my random roll was less than or equal to the status effect's chance. The problem of course is that it could proc 10 times in a row or go 50 times without.

I decided to swap it over to a shuffle bag to correct the drought issues of it not procing. This gave the opposite problem where now it has become 1 out of 4 with 3 guaranteed failures and at most will hit twice in a row. It was just too predictable.

What I have since come up with is a gate where I leave it fully in the hands of RNG until it surpasses the average number of failures. That's the point I start injecting in extra weight up until a cap where a guaranteed success happens.

```
public class ChanceGate<TValue>
{
    class ChanceContainer
    {
        public TValue Value { get; set; }

        public float Chance { get; set; }

        public int MissCount { get; set; }

        public int IncreaseThreshold => (int)Math.Ceiling(1f / Chance);

        public int MaxFailures => (int)Math.Ceiling(1f / Chance * 1.5);

        public void Reset(float chance)
        {
            Chance = chance;
            MissCount = 0;
        }
    }

    readonly Random _random;
    readonly float _originalChance;
    readonly float _failuresIncreaseBy;
    readonly ChanceContainer _chanceItem;

    public TValue Value => _chanceItem.Value;

    public ChanceGate(Random random, TValue value, float chance, float failuresIncreaseBy)
    {
        _random = random;
        _originalChance = chance;
        _failuresIncreaseBy = failuresIncreaseBy;
        _chanceItem = new ChanceContainer
                      {
                          Chance = chance,
                          Value = value,
                      };
    }

    public bool Roll()
    {
        if (_chanceItem.MissCount >= _chanceItem.MaxFailures)
        {
            _chanceItem.Reset(_originalChance);
            return true;
        }

        if (_random.NextDouble() <= _chanceItem.Chance)
        {
            _chanceItem.Reset(_originalChance);
            return true;
        }

        _chanceItem.MissCount++;
        if (_chanceItem.MissCount >= _chanceItem.IncreaseThreshold)
            _chanceItem.Chance += _failuresIncreaseBy;

        return false;
    }
}

```

There's a lot of fine tuning I need to do to get it to where I want, but this already has felt better than what was before. The chance of success has obviously increased over 1,000,000 iterations, but the droughts are no longer as severe. As much as I hate to force a failure, I might incorporate my characters' luck stat to determine if a streak ends or use that as the basis around how much weight gets added to try and get a success.

I am sure this concept already exists, but I have no idea what it is called in order to research it. Am I going down the right path? Are there other methodologies I should explore?

# Answer
My first attempt would be to enlarge the shufflebag, as Mangata suggested in a comment. So instead of 3 guaranteed failures every 4 rolls, you now have 6 guaranteed failures every 8 rolls.

If you still find that too predictable, then an extension to this approach is to discard and recreate the shufflebag *before* it is empty. For example, let's take a 16 entry shufflebag with 4 wins and 12 losses which gets reshuffled after 4 draws. Getting all 4 wins is not *impossible*, but very, very rare:

* 1st is a win: 4 in 16 or 25%
* 2nd after that is also a win: 3 in 15 or 20%
* 3rd after that is also a win: 2 in 14 or 14%
* 4th after that is also a win: 1 in 13 or 7.7%

Cumulative chance to get a 4 win streak on a single shufflebag: 0,05%. And after the 4th draw, you get a new shufflebag and everything is open again. So even after this unlikely event there will never be absolute certainty what the next event will be.

Now in reality there is of course a higher chance for a 4 win streak if you consider that one bag might end on two wins and the next start with two wins. But that does not give the player much certainty what will happen next.

Especially when the player does not know on which shufflebag they are. Do not overestimate how much the average player really understands your game mechanics. The average player will probably never realize you are even using shufflebags (that's the whole point, after all). And even those who are aware, will probably not keep count. The only people who will intentionally try to exploit your RNG will be the try-hard challenge gamers who intentionally try to break the game. And those are a very small minority.

---

Credits for this idea goes to the Las Vegas casinos which introduced it to counter card counting in Black Jack. Instead of playing Black Jack with one deck, they now play it with multiple decks of cards, and reshuffle the shoe long before all of the cards have been dealt.
> 19 votes

# Answer
Stolen blatantly from D\_M\_Gregory's tweets:

My preferred approach for this kind of selection is to build some Gambler's Fallacy into the generator - adding notion an item can be "overdue" / "used up".

I start with a non-negative weight associated with each item - these don't have to sum to 100% so they're easy to edit. As part of the generator state I track a "dueness" for each item, initialized to that item's weight.

When drawing an item, I form a selection weight for each item as Max(item dueness + item weight * noise, 0) …and select an item with weighted random selection from these weights. After a draw, I increase the dueness of each item (including the selected one) by its original weight, and decrease the dueness of the selected item by the total original weight. If I've overconstrained it so it gets all zero weights, it falls back to the original weights.

The noise parameter lets me control how predictably deck-like (~0) or chaotically dice-like (\>\>0) the generator behaves. So it's not all or nothing, I can dial in the trade-off I want between consistent guarantees and unpredictability.

This gives me much stronger control over the observed frequencies of each item compared to weighted rolls without memory. I can even add a cooldown between rolls of a single item to avoid back-to-back fails/criticals. And you can even change the source weights on the fly!

So that's how I'm tackling this problem currently, letting me guarantee players don't wait too long for a particular event (droughts), or experience too many back-to-back (streaks), with design parameters I can freely tune to any numbers I want and get the frequencies I expect!
> 5 votes

# Answer
One very simple way is to continuously tweak probabilities instead of after some fixed point.

There is base probability `pb` (0.25 in the example). We have another parameter I am calling "stiffness" - `s` that influences how the current probability `p` changes with wins and losses. Our random generator output `r` is in range of 0 to 1 and is compared to the current probability `p`. Current probability `p` changes according to a simple formula (starting with `p=pb`):

```
if r<=p
  p=p-(1-pb)*s //If we win, we make it less likely to win again.
else
  p=p+pb*s //If we lose, we make it more likely to win next time.
end

```

So, let's see what this simple formula gives us. Pluses are for wins (above 0); circles are for losses (below 0).

`s=0` is fully random. Few cases have extremely long win or loss streaks. `s=0.5` is somewhat in-between, showing shorter tail of at most 10 losses or 3 wins in a row. `s=1` is equivalent to a shuffle bag size 4 (the basic shuffle bag size). Then we have `s=2` where we get at most 1 win in a row, but losing streak is also fairly likely to be 3 and is at most 5. Increasing `s` further makes losses even closer to always 3 in a row, in limit `s->inf` we would get 2.5e4 cases of that (note that we get 3 losses in a streak, so end probability of a win is the base 0.25 one)

Tweak the `s` to obtain the curve most suitable for your purposes. `s` can be lower if `pb` is higher - the long losing streaks are problematic, not the long winning ones. I suggest something like `s=1/8pb`. This makes results more random when base probability is high, but more deterministic when base probability is low.

The nice bit about this approach is that it is very simple to understand what is happening and fairly trivial to implement. The possibly problematic aspect is that once people know this is the approach, they might intentionally try getting many misses in a row to "prime" the probability before their big fight. But this can be also desirable - if you want to give a little benefit to the most dedicated players.
> 4 votes

# Answer
A shufflebag that is kept at a constant size and refilled using a predictable series could remedy this.

### The algorithm

I'm using the 25% proc rate as an example.

**Setup**
Create a *refill list* with the correct amount of procs and fails: \[proc, fail, fail, fail\].
Fill the shufflebag by adding items from the refill list in order, cycling back to the first item after the end. Add a proc, fail, fail, fail, proc, fail etc until the bag is full.
**Drawing**
Pull a random result from the bag as normal.
Refill the bag using the next item from the list.

### Interesting aspects of constant refilling shuffle bags

Because results are pulled from a bag randomly there is a random chance for every event. Only in very specific cases (only procs or fails in the bag) the result can be predicted. This is different from a regular shuffle bag, where at least every last draw before refill can be known in advance.

Because the refilling bag is fed from a list where every fourth result procs in the long run this will tend to exactly 25% procs. This is very artificial, but similar to a regular shuffle bag.

The bag size for refilling bags doesn't need to be related to the proc chance like regular shuffle bags. Regular shuffle bags for a 25% chance can have size n\*4, while 31% only works with bag size n\*100. Using a custom filling algorithm where not all bags are the same could fix this but adds another layer of complexity.

### Tweaking this algorithm

* An increase in bag size will cause an increase in randomness. At size 1, exactly every 4th result will proc. Changing the size to 2 will allow a maximum of 2 procs to occur consecutively. Increasing it even further would allow longer chains of procs, even though they become very improbable.
* The proc chance is controlled by the *refill list*. For 25% every fourth item should be a proc, for 20% every fifth. For other percentages it may not be as easy. If you want you can pre-calculate a table for every percentage you'll be using.

### Just like the simulations

Running 1M simulations for various bag sizes and counting proc streak lengths gives the following results. Also shown is the 'naive' implementation where every draw is a simple 25% chance. Note that the count axis is logarithmic.  As expected bigger bags allows longer streaks. For the naive case there is an inverse exponential relationship: the chance of a streak having length *n* is *0.25^n*. Eyeballing it there seems to be an inverse exponential relationship for the refilling bags as well, but it drops off more steeply.

Truncation is visible in bag sizes 2 and 3, this is due to the fill list containing 3 consecutive fails.
> 2 votes

# Answer
Adapted from Steve Rabin article on filtered randomness from AI Programming Wisdom 2.

As you identified in the question, a truly random sequence allows for rare anomalies that are perceived as random. Instead, people expect random results to have an average distribution & avoid certain characteristics. In particular, research by Falk has identified certain things that cause people to perceive things as less random:

* long runs of outcomes
* lack of alternations
* repeated patterns
* symmetric patterns

To counter these problems we can keep a short history of results and apply a series of rules:

* force alternation when needed
* restrict long runs
* eliminate unwanted patterns

My personal take is that tuning unwanted runs is more important that filtering out patterns. But since it's relatively easy to comment out that section of code if desired, so I'm presenting the material in its original form.

Here's a rough C# adaptation from the original C++ companion code along with a basic tester / demo:

```
class Program
{
    const int FR_CHANCE_HISTORY_LENGTH = 20;
    int[] m_hist = new int[FR_CHANCE_HISTORY_LENGTH];
    const float FLOATING_POINT_ROUNDOFF_ERROR = 0.000001f;

    static void Main(string[] args)
    {
        int count = 0;
        float odds = 0.25f;
        for(int a=0; a<1000; a++)
        {
            if (RandChance(odds))
            {
                count++;
            }
        }
        Console.WriteLine("count for " + (int)(odds * 100) + "% out of 1000 trials = " + count + " or " + count/10.0 + "%");
        Console.WriteLine("example output: ");
        for (int a = 0; a < 50; a++)
        {
            int i = RandChance(odds) ? 1 : 0;
            Console.Write(i);
        }
    }

    public static bool RandChance(float a)
    {
        Random rng = new Random();
        return ((((float)rng.Next()) + 0.5) * (1.0 / (float)Int32.MaxValue) <= a);
    }

    // These tables were carefully hand-tuned to ensure that random chances were within 1% of requested chance.
    int[] MaxAlternations = { 2, 4, 4, 4, 4, 4, 4, 4, 4, 6,  //0.01 through 0.10
                              6, 6, 6, 6, 6, 8, 8, 8, 8, 8,  //0.11 through 0.20
                              10,10,10,10,10,12,12,12,12,12,  //0.21 through 0.30
                              12,12,12,12,12,12,12,12,12,12,  //0.31 through 0.40
                              12,12,12,12,12,14,14,14,14,14 };//0.41 through 0.50

    int[] MinAlternations = { 0, 0, 0, 0, 0, 1, 1, 1, 1, 1,  //0.01 through 0.10
                              1, 1, 1, 4, 4, 4, 4, 4, 4, 4,  //0.11 through 0.20
                              4, 4, 4, 6, 6, 6, 6, 6, 6, 6,  //0.21 through 0.30
                              8, 8, 8, 8, 8, 8, 8, 8, 8, 8,  //0.31 through 0.40
                              8, 8,10,10,10,12,12,12,12,12 };//0.41 through 0.50

    int[] MaxTrueRun =      { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  //0.01 through 0.10
                              2, 2, 2, 2, 2, 2, 2, 2, 2, 2,  //0.11 through 0.20
                              2, 2, 2, 2, 2, 2, 2, 2, 2, 2,  //0.21 through 0.30
                              2, 2, 2, 2, 3, 3, 3, 3, 3, 3,  //0.31 through 0.40
                              3, 3, 3, 3, 3, 3, 3, 3, 3, 3 };//0.41 through 0.50

    int[] MaxFalseRun =     {25,25,25,25,25,25,25,15,15,15,  //0.01 through 0.10
                             14,14,14,12,12,12,12,10,10,10,  //0.11 through 0.20
                             10,10,10,10,10,10,10, 7, 7, 7,  //0.21 through 0.30
                              7, 7, 7, 7, 7, 6, 6, 5, 5, 5,  //0.31 through 0.40
                              5, 5, 4, 4, 4, 4, 4, 3, 3, 3 };//0.41 through 0.50

    int[] InitialHistoryChance = { 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0 };

    bool GenRand(float chance)
    {
        int i, alternations = 0;
        float adjchance = chance;
        int adjchance_int = (int)((chance * 100.0f) + 0.5f) - 1;
        bool flip = false;

        for (i = 0; i < FR_CHANCE_HISTORY_LENGTH - 1; i++)
        {   // move history down
            m_hist[i] = m_hist[i + 1];
        }

        if (chance > 0.5f)
        {
            adjchance = 1.0f - chance - FLOATING_POINT_ROUNDOFF_ERROR;
            adjchance_int = (int)(((1.0f - chance) * 100.0f) + 0.5f) - 1;
            flip = true;
        }

        if (adjchance_int < 0)
        {
            adjchance_int = 0;
        }

        // Get random value based on chance
        m_hist[FR_CHANCE_HISTORY_LENGTH - 1] = RandChance(adjchance) ? 1 : 0;

        // force desired alterations
        int max, min;

        for (i = 0; i < FR_CHANCE_HISTORY_LENGTH - 1; i++)
        {   // count alternations
            if (m_hist[i] != m_hist[i + 1])
            {
                alternations++;
            }
        }

        max = MaxAlternations[adjchance_int];
        min = MinAlternations[adjchance_int];

        if (alternations > max)
        {   // if too many alternations, make the new value the same as the last
            m_hist[FR_CHANCE_HISTORY_LENGTH - 1] = m_hist[FR_CHANCE_HISTORY_LENGTH - 2];
        }
        else if (alternations < min)
        {   // if not enough alternations, make the new value the opposite fo the last
            m_hist[FR_CHANCE_HISTORY_LENGTH - 1] = (m_hist[FR_CHANCE_HISTORY_LENGTH - 2]+1)%2;
        }

        // eliminate implausible runs
        int run = 1;   //the first element starts as a run of 1

        for (i = FR_CHANCE_HISTORY_LENGTH - 2; i >= 0; i--)
        {   // count size of the most recent run
            if (m_hist[i] == m_hist[i + 1])
            {
                run++;
            }
            else
            {
                break;
            }
        }

        if (m_hist[FR_CHANCE_HISTORY_LENGTH - 1]==1 && run > MaxTrueRun[adjchance_int])
        {
            m_hist[FR_CHANCE_HISTORY_LENGTH - 1] = 0;
        }
        else if (!(m_hist[FR_CHANCE_HISTORY_LENGTH - 1]==1) && run > MaxFalseRun[adjchance_int])
        {
            m_hist[FR_CHANCE_HISTORY_LENGTH - 1] = 1;
        }

        // eliminate repeating motifs of size 4, like 01110111 where 0111 is the motif
        if (chance >= 0.4f && chance <= 0.6f)
        {   // enforce for around the 50% chance case
            if (m_hist[FR_CHANCE_HISTORY_LENGTH - 1] == m_hist[FR_CHANCE_HISTORY_LENGTH - 5] &&
                m_hist[FR_CHANCE_HISTORY_LENGTH - 2] == m_hist[FR_CHANCE_HISTORY_LENGTH - 6] &&
                m_hist[FR_CHANCE_HISTORY_LENGTH - 3] == m_hist[FR_CHANCE_HISTORY_LENGTH - 7] &&
                m_hist[FR_CHANCE_HISTORY_LENGTH - 4] == m_hist[FR_CHANCE_HISTORY_LENGTH - 8])
            {
                if (m_hist[FR_CHANCE_HISTORY_LENGTH - 1] == 0)
                {
                    m_hist[FR_CHANCE_HISTORY_LENGTH - 1] = 1;
                }
                else
                {
                    m_hist[FR_CHANCE_HISTORY_LENGTH - 1] = 0;
                }
            }
        }

        // eliminate 111000 and 000111 pattern
        if (chance >= 0.4f && chance <= 0.6f)
        {   // enforce for around the 50% chance case
            if ((m_hist[FR_CHANCE_HISTORY_LENGTH - 1] == 0 && m_hist[FR_CHANCE_HISTORY_LENGTH - 4] == 1 &&
                 m_hist[FR_CHANCE_HISTORY_LENGTH - 2] == 0 && m_hist[FR_CHANCE_HISTORY_LENGTH - 5] == 1 &&
                 m_hist[FR_CHANCE_HISTORY_LENGTH - 3] == 0 && m_hist[FR_CHANCE_HISTORY_LENGTH - 6] == 1) ||
                (m_hist[FR_CHANCE_HISTORY_LENGTH - 1] == 1 && m_hist[FR_CHANCE_HISTORY_LENGTH - 4] == 0 &&
                 m_hist[FR_CHANCE_HISTORY_LENGTH - 2] == 1 && m_hist[FR_CHANCE_HISTORY_LENGTH - 5] == 0 &&
                 m_hist[FR_CHANCE_HISTORY_LENGTH - 3] == 1 && m_hist[FR_CHANCE_HISTORY_LENGTH - 6] == 0))
            {
                if (m_hist[FR_CHANCE_HISTORY_LENGTH - 1] == 0)
                {
                    m_hist[FR_CHANCE_HISTORY_LENGTH - 1] = 1;
                }
                else
                {
                    m_hist[FR_CHANCE_HISTORY_LENGTH - 1] = 0;
                }
            }
        }

        if (flip)
        {   // requested percentage (chance) is above 0.50, so flip result
            return (!(m_hist[FR_CHANCE_HISTORY_LENGTH - 1]==1));
        }
        else
        {
            return (m_hist[FR_CHANCE_HISTORY_LENGTH - 1]==1);
        }
    }

}

```

Result:

```
count for 25% out of 1000 trials = 253 or 25.3%
example output:
10000001000000100000001000010011000000001001000010

```

As indicated in the comments, the tables were hand tuned for the corresponding percentages. As such if experiment with other values you should make sure to thoroughly test the result to avoid unpleasant surprises.
> 0 votes

---
Tags: game-design, random
---