# Question
Title: Why do I get this error: "error: video system not initialized"?
The error occurs when I call

```
keys_pressed = pygame.key.get_pressed()

```

Here is the full code:

```
import pygame

pygame.font.init()

pygame.init()

WIDTH, HEIGHT = 900,500

WIN = pygame.display.set_mode((WIDTH, HEIGHT))

pygame.display.set_caption('BattleGrounds!!!')

WHITE = (255,255,255)

BLACK=(0,0,0)

BLUE=(0,0,255)

WINNER_FONT=pygame.font.SysFont('comicsans',100)

RED=(255,0,0)

YELLOW=(255,255,0)

GREEN=(0,255,0)

FPS=60
YELLOW_HIT=pygame.USEREVENT+1

RED_HIT=pygame.USEREVENT+2

VEL=5

MAX_BULLETs = 3

RDM=(100,60,20)

BULLET_VEL=10

HEALTH_FONT = pygame.font.SysFont('comicsans',20)

BORDER=pygame.Rect(WIDTH//2-5,0,10,HEIGHT)

GUN_WIDTH,GUN_HEIGHT= 50,40

YELLOW_GUN_IMAGE=pygame.image.load('gun1.png')

YELLOW_GUN =pygame.transform.rotate(pygame.transform.scale(YELLOW_GUN_IMAGE,(100,60)),0)

RED_GUN_IMAGE=pygame.image.load('gun.png')

RED_GUN=pygame.transform.rotate(pygame.transform.scale(RED_GUN_IMAGE,(100,60)),0)

BG = pygame.image.load('download.jpg')

BG1=pygame.transform.scale(BG,(WIDTH,HEIGHT))

def draw_window(red,yellow,red_bullets,yellow_bullets,red_health,yellow_health):
    WIN.fill(WHITE)
    WIN.blit(BG1, (0,0))

    red_health_text=HEALTH_FONT.render('Health:'+str(red_health),1,RED)
    yellow_health_text = HEALTH_FONT.render('Health:' + str(yellow_health), 1, YELLOW)
    WIN.blit(red_health_text,(725,0))
    WIN.blit(yellow_health_text,(0,0))
    WIN.blit(YELLOW_GUN,(yellow.x,yellow.y))
    WIN.blit(RED_GUN,(red.x,red.y))
    for bullet in red_bullets:
        pygame.draw.rect(WIN,RED,bullet)
    for bullet in yellow_bullets:
        pygame.draw.rect(WIN,GREEN,bullet)
    pygame.display.update()

def draw_winner(text):
    draw_text=WINNER_FONT.render(text,1,BLUE)
    WIN.blit(draw_text,(WIDTH//2-draw_text.get_width()//2,HEIGHT//2-draw_text.get_height()//2))
    pygame.display.update()
    pygame.time.delay(5000)
def yellow_movement(keys_pressed,yellow):
    if keys_pressed[pygame.K_a] and yellow.x - VEL > 0:
        yellow.x -= VEL
    if keys_pressed[pygame.K_d] and yellow.x + VEL < BORDER.x-95:
        yellow.x += VEL
    if keys_pressed[pygame.K_w] and yellow.y - VEL > 0:
        yellow.y -= VEL
    if keys_pressed[pygame.K_s] and yellow.y + VEL < HEIGHT-45:
        yellow.y += VEL

def red_movement(keys_pressed,red):
    if keys_pressed[pygame.K_LEFT] and red.x -VEL > 450:
        red.x -= VEL
    if keys_pressed[pygame.K_RIGHT] and red.x + VEL <800:
        red.x += VEL
    if keys_pressed[pygame.K_UP] and red.y - VEL > 0:
        red.y -= VEL
    if keys_pressed[pygame.K_DOWN] and red.y - VEL < HEIGHT-58:
        red.y += VEL

def handle_bullets(yellow_bullets,red_bullets,yellow, red):
    for bullet in yellow_bullets:
        bullet.x+=BULLET_VEL
        if red.colliderect(bullet):
            pygame.event.post(pygame.event.Event(RED_HIT))
            yellow_bullets.remove(bullet)
        elif bullet.x > WIDTH:
            yellow_bullets.remove(bullet)
    for bullet in red_bullets:
        bullet.x-=BULLET_VEL
        if yellow.colliderect(bullet):
            pygame.event.post(pygame.event.Event(YELLOW_HIT))
            red_bullets.remove(bullet)
        elif bullet.x<0:
            red_bullets.remove(bullet)

red = pygame.Rect(700, 300,GUN_WIDTH,GUN_HEIGHT)
yellow = pygame.Rect(100, 300, GUN_WIDTH, GUN_HEIGHT)
red_bullets = []
yellow_bullets=[]
red_health=5
yellow_health=5
clock=pygame.time.Clock()
run=True
while run:
    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            run=False
            pygame.quit()
            if event.type==pygame.KEYDOWN:
                if event.key==pygame.K_LCTRL and len(yellow_bullets)<MAX_BULLETs:
                    bullet=pygame.Rect(yellow.x+yellow.width,yellow.y+yellow.height//2-2,10,5)
                    yellow_bullets.append(bullet)

                if event.key==pygame.K_RCTRL and len(red_bullets)< MAX_BULLETs:
                    bullet=pygame.Rect(red.x,red.y+red.height//2-2,10,5)
                    red_bullets.append(bullet)
            if event.type==RED_HIT:
                red_health-=1

            if event.type==YELLOW_HIT:
                yellow_health-=1
        winner_text=""
        if red_health<=0:
            winner_text='YELLOW WINS'

        if yellow_health<=0:
            winner_text='RED WINS'

        if winner_text!="":
            draw_winner(winner_text)
            break

        keys_pressed = pygame.key.get_pressed()
        yellow_movement(keys_pressed,yellow)
        red_movement(keys_pressed,red)
        handle_bullets(yellow_bullets,red_bullets,yellow , red)
        draw_window(red,yellow,red_bullets,yellow_bullets,red_health,yellow_health)

```

# Answer
Let me first point out that the block introduced by `if event.type==pygame.KEYDOWN:` here:

```
            pygame.quit()
            if event.type==pygame.KEYDOWN:

```

will never be processed because it is directly under `if event.type==pygame.QUIT:`, and an event can't be `pygame.QUIT` and `pygame.KEYDOWN` at the same time.

---

You're shy on details: you don't say *when* the error occurs. I suppose it's when you quit the game.

When you call `pygame.quit()`, the engine will uninitialize all of the modules. Then, further down, you try to access one of those deleted modules (`pygame.key.get_pressed()`). Hence, the first call to `pygame.*` crashes your game.

Here is something that should help you get a bit further:

1. When you detect that you need to quit, then make sure that no code is executed before the end of the loop.
2. Make sure the indentation is correct: an event can't be two things at the same time.
3. Don't draw your game at every event, draw it once per frame.

Here is a new version of your game loop:

```
while run:
    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            run=False
            break
        if event.type==pygame.KEYDOWN:
            if event.key==pygame.K_LCTRL and len(yellow_bullets)<MAX_BULLETs:
                bullet=pygame.Rect(yellow.x+yellow.width,yellow.y+yellow.height//2-2,10,5)
                yellow_bullets.append(bullet)

            if event.key==pygame.K_RCTRL and len(red_bullets)< MAX_BULLETs:
                bullet=pygame.Rect(red.x,red.y+red.height//2-2,10,5)
                red_bullets.append(bullet)
        if event.type==RED_HIT:
            red_health-=1

        if event.type==YELLOW_HIT:
            yellow_health-=1

        winner_text=""

        if red_health<=0:
            winner_text='YELLOW WINS'

        if yellow_health<=0:
            winner_text='RED WINS'

        if winner_text!="":
            draw_winner(winner_text)
            break

    keys_pressed = pygame.key.get_pressed()
    yellow_movement(keys_pressed,yellow)
    red_movement(keys_pressed,red)
    handle_bullets(yellow_bullets,red_bullets,yellow , red)
    draw_window(red,yellow,red_bullets,yellow_bullets,red_health,yellow_health)

pygame.quit()

```
> 2 votes

---
Tags: pygame
---


# Question
Title: How to make a cubemap image with perlin noise?
Recently I just finished a program which makes a plane image using perlin noise. Now I want to make that image a cubemap image.

This because I want to apply it to a planet (which was made from a cube). I have been trying to generate this cubemap, but there are a lot of discontinuities on the image. Do you know any way to generate this cubemap without these "gaps"? Thank you in advance.

I am using the Javascript library P5.js

# Answer
DMGregory's comment is correct in that the proper and canonical solution is to use 3D noise. If you get the coordinates of each cube face in 3D space, you can iterate over them and sample the noise in such a way that the the cube faces connect naturally. Be sure to transform the cube coordinates to what they would be on the actual sphere you're mapping to, e.g. by normalizing the vector from the center.

Additionally, please note:

* There are many noise algorithms out there. Perlin is only one such, and it's an older one with significant square alignment problems. We would do best to move past counting unmitigated Perlin noise as default, and to also do our due-diligence to address this when answering queries framed around unmitigated Perlin.
* P5.js noise isn't even Perlin -- it's the further artifact-prone "Value noise" algorithm with fractal summation built in. My first step when using noise in P5 would always be to import an external library.

I recommend the JS port of FastNoiseLite, with one of the Simplex-type options. Disclosure: I contributed substantially to this library's development.
> 2 votes

---
Tags: javascript, perlin-noise
---


# Question
Title: Why is my character controller deacceleration not working?
I want my player to deaccelerate when he stop not just stop in place. Here is my code:

```
public override Vector3 Move(MovementManager manager, Vector2 input, bool jump, bool isCrouching)
{
    float speed = isCrouching ? CrouchSpeed : MoveSpeed;
    Vector3 velocity = manager.Velocity;

    float currentVelocity = new Vector3(velocity.x, 0, velocity.z).magnitude;
    Vector3 moveDirection = Vector3.zero;

    if (Mathf.Abs(input.x) > 0 || Mathf.Abs(input.y) > 0)
    {
        moveDirection = new Vector3(input.x, 0, input.y);
        moveDirection = manager.transform.TransformDirection(moveDirection);

        if(input.y > 0)
        moveDirection *= input.y;

        LastMoveDirection = moveDirection;

        if (IsWalkSpeed) currentVelocity += (Acceleration * .4f) * Time.fixedDeltaTime;
        else currentVelocity += Acceleration * Time.fixedDeltaTime;

        //if (currentVelocity > MaxSpeed) currentVelocity = MaxSpeed;
        if (currentVelocity > speed) currentVelocity = speed;
        return moveDirection.normalized * currentVelocity * Time.fixedDeltaTime;
    }
    else
    {
        currentVelocity -= Deacceleration * Time.fixedDeltaTime;
        currentVelocity = Mathf.Max(currentVelocity, 0);

        return LastMoveDirection.normalized * currentVelocity * Time.fixedDeltaTime;
    }
}

```

# Answer
> 0 votes
Here is the solution:

```
 public override Vector3 Move(MovementManager manager, Vector2 input, bool jump, bool isCrouching)
{
    float speed = isCrouching ? CrouchSpeed : MoveSpeed;
    Input = input;

    if (Mathf.Abs(input.x) > 0 || Mathf.Abs(input.y) > 0)
    {
        moveDirection = new Vector3(input.x, 0, input.y);
        moveDirection = manager.transform.TransformDirection(moveDirection);

        if (input.y > 0)
            moveDirection *= input.y;

        LastMoveDirection = moveDirection;

        if (IsWalkSpeed) currentVelocity += (Acceleration * .4f) * Time.fixedDeltaTime;
        else currentVelocity += Acceleration * Time.fixedDeltaTime;

        //if (currentVelocity > MaxSpeed) currentVelocity = MaxSpeed;
        if (currentVelocity > speed) currentVelocity = speed;

    }
    else if(input.x <= 0 && input.y <= 0)
    {
        currentVelocity -= Deacceleration * Time.fixedDeltaTime;
        currentVelocity = Mathf.Max(currentVelocity, 0);
    }

    return LastMoveDirection.normalized * currentVelocity * Time.fixedDeltaTime;

}

```

There was the problem with moveDirection and manager.velocity these 2 vectors were zero at a specific point so the player just stop in place. Deacceleration was working but it was multiply by the zero vector so it did nothing.

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


title: Large Text in Unity Inspector

text:
# Question
Title: Large Text in Unity Inspector
I'am building a game using the webcam where I have to step back from the screen for testing. Thus I would like to display a single value in the inspector using a larger font.

Is there a possibility to change the text size in the inspector of a single entry?

I'm currently using `[Title ("$currentState")]` which creates bold text, but does not increase text size.

# Answer
Using the PropertyDrawer as proposed by @DMGregory finally works:

```
using UnityEditor;
using UnityEngine;

[CustomPropertyDrawer (typeof (LargeTextInGUI))]
public class LargeTextInGUIDrawer : PropertyDrawer
{
    public override void OnGUI (Rect position, SerializedProperty property, GUIContent label)
    {
        var style = new GUIStyle ();
        style.fontSize = 40;
        EditorGUI.LabelField (position, label.text, property.intValue.ToString(), style);
    }

    public override float GetPropertyHeight (SerializedProperty property, GUIContent label)
    {
        return 45;
    }
}

```

```
using UnityEngine;

public class LargeTextInGUI : PropertyAttribute
{
}

```

```
public class MyClass: ScriptableObject{
    [LargeTextInGUI]
    public int currentState;
}

```
> 1 votes

---
Tags: unity
---


title: Sometimes player moves too much

text:
# Question
Title: Sometimes player moves too much
I'm working on a simple platform game. I have the player - a dynamic body, which moves by `ApplyLinearImpulse`. Generally it works very well, but sometimes the player moves to much.

For example - I'm making short clicks on the keyboard, every click the player moves for example 50 pixels, but once in a few clicks it will move 200-300 pixels.

The code of the movement:

```
void GameObject::move_phisical_body_horizontally(const float x)
{
    float velChange = x - m_phisical_body->GetLinearVelocity().x;
    float h_impulse = m_phisical_body->GetMass() * velChange;
    m_phisical_body->ApplyLinearImpulse(b2Vec2(h_impulse, 0), m_phisical_body->GetWorldCenter(), true);
}

```

the code of the ground object: (the ground is a collection of ground tiles)

```
auto& texture = Resources::instance().getTexture(GroundTexture);
auto width = texture.getSize().x;
auto hieght = texture.getSize().y;
auto position = this->convert_position(position_vec, { width, hieght });

b2BodyDef bodyDef;
bodyDef.type = b2_staticBody;
bodyDef.userData.pointer = reinterpret_cast<uintptr_t>(this);
b2Body* body = world->CreateBody(&bodyDef);

b2Vec2 v0((position.x - width) / SCALE, position.y / SCALE);
b2Vec2 v1(position.x / SCALE, position.y / SCALE);
b2Vec2 v2((position.x + width) / SCALE, position.y / SCALE);
b2Vec2 v3((position.x + width * 2) / SCALE, position.y / SCALE);

b2EdgeShape edge1;
b2EdgeShape edge2;

edge1.SetOneSided(v0, v1, v2, v3);
edge2.SetTwoSided(v1, v2);

b2FixtureDef FixtureDef1;
b2FixtureDef FixtureDef2;
FixtureDef1.density = 0.f;
FixtureDef1.shape = &edge1;
FixtureDef2.friction = 1;
FixtureDef2.shape = &edge2;
body->CreateFixture(&FixtureDef1);
body->CreateFixture(&FixtureDef2);

m_phisical_body = body;

```

The code of the player:

```
auto width = 32u;
auto hieght = 32u;
sf::Sprite sprite(Resources::instance().getTexture(PlayerTexture));
sprite.setPosition(position_vec.x * width, position_vec.y * hieght);
sprite.setTextureRect(sf::IntRect({ 0, 0, (int)width, (int)hieght }));
sprite.setOrigin(16.f, 16.f);

auto player_obj = std::make_unique<Player>(sprite, std::vector<int>{ 11, 12, 1, 1, 1 }, "player");
player = *player_obj.get();

auto position = player_obj->convert_position(position_vec, { width, hieght });

b2BodyDef BodyDef;
BodyDef.position = b2Vec2(position.x / SCALE, position.y / SCALE);
BodyDef.type = b2_dynamicBody;
BodyDef.userData.pointer = reinterpret_cast<uintptr_t>(&player);
b2Body* body = world->CreateBody(&BodyDef);
body->SetFixedRotation(true);

b2PolygonShape Shape;
Shape.SetAsBox((width / 2.f - 1) / SCALE, (hieght / 2.f - 1) / SCALE);
b2FixtureDef FixtureDef;
FixtureDef.density = 1.f;
FixtureDef.friction = 1.f;
FixtureDef.shape = &Shape;
body->CreateFixture(&FixtureDef);
player.set_phisical_body(body);

```

# Answer
> 1 votes
I fixed it by setting the player's friction to zero and just handled the deceleration by myself instead of letting the box2d handling this.

```
void GameObject::update_deceleration(const float  friction_decrease)
{
    auto velocity = m_phisical_body->GetLinearVelocity();

    if (velocity.x)
    {
        velocity.x *= friction_decrease;
        if (abs(velocity.x) < 0.3f)
            velocity.x = 0;
    }
    m_phisical_body->SetLinearVelocity({ velocity.x, velocity.y });
}

```

---
Tags: c++, movement, box2d
---


title: 24bit float to RGB

text:
# Question
Title: 24bit float to RGB
There's solutions to convert float to RGBA but I would like to encode a float depth value in RGB format and save the three components in three separated unused alpha channels and recompose when needed. I prefer 24bit float because the decoded value is to be compared to regular 24+8 bit depthstencil buffer.

there's this code for float to RGBA (https://gamedev.net/forums/topic/684158-rgba-to-float-percision/5321338/)

```
vec4 pack(float depth)
{
   const vec4 bitSh = vec4(256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0);
   const vec4 bitMsk = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);
   vec4 comp = fract(depth * bitSh);
   comp -= comp.xxyz * bitMsk;
   return comp;
 }

float unpack(vec2 pos)
{
   vec4 packedZValue = texture2D(shadow_map, pos);
   const vec4 bitShifts = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1);
   float shadow = dot(packedZValue , bitShifts);
   return shadow;
}

```

I tried to change to vec3 by removing the first component as below but get weird results (see picture below).

Note: left panels are showing the alpha chanel were the depth is stored as 3 component (1rt = x, 3rd = y and 4th = z, second is something else) by default the alpha channel is 1 (so it appears white) as it is for depth buffer and I perform a alpha OP\_MIN test to write new value as if it was comparison\_less. So we can see something in panel 1/3 but in 4 it is still white suggesting that the z value is 1 or more.

```
vec3 pack(float depth)
{
   const vec3 bitSh = vec3(256.0 * 256.0, 256.0, 1.0);
   const vec3 bitMsk = vec3(0, 1.0 / 256.0, 1.0 / 256.0);
   vec3 comp = fract(depth * bitSh);
   comp -= comp.xyz * bitMsk;
   return comp;
 }

float unpack()
{
   vec3 packedZValue = float3(textureA.a, textureB.a, textureC.a);
   const vec3 bitShifts = vec4(1.0 / (256.0 * 256.0), 1.0 / 256.0, 1);
   float shadow = dot(packedZValue , bitShifts);
   return shadow;
}

```

# Answer
> 1 votes
Finally I change from RGB to RG encoding of depth with the code found here that is fine (https://blog.katastros.com/a?ID=00300-1312986b-8ead-4a41-8d1e-1845010de79a). Importantly I made a final test to have correct value for depth = 1 as the method seems not able to give full 1.0f. The code is recalled below with added the special depth =1 test in the depth decode part as well as a picture of the result.

encode :

```
 float2 FloatToRG(float v)
 {
    float2 kEncodeMul = float2(1.0f, 255.0f);
    float kEncodeBit = 1.0f/255.0f;
    float2 color = kEncodeMul*v;
    color = frac(color);
    color.x -= color.y * kEncodeBit;
    return color;
 }

```

decode

```
 //TexS is an int3
 float2 DRG = float2(textureA.Load(TexS).a, textureB.Load(TexS).a);
 float D = dot(DRG, float2(1.0f, 1.0f/255.0f));
 if ( D > 0.9999f ) D = 1;// needed to have correct value depth = 1

```

maybe there is a limit to this final test but it gives me what I need.

---
Tags: hlsl, floating-point
---


# Question
Title: Testing if instantiated prefab is colliding with environment
I'm trying to generate a number of prefabs in a scene where that scene will have procedurally-generated terrain objects. I have tagged each of the terrain objects with `Environment` to try and make trigger detection a bit easier.

The issue I'm facing is that the prefabs I'm attempting to spawn don't have their trigger detection run until after my script runs, and I'm wondering if there is a better way to do this. Basically, what is happening is that my prefabs are spawning inside of environmental objects and I want to either move them or regenerate them.

Here's what I'm trying so far:

1. Instantiate scene (tagging environmental objects with `Environment` \- right now this is manual to prove out the prefab placement but will later become fully automated).

This is what the scene currently looks like - it is basically going to be an extension of the Unity ROS example:

Eventually the objects placed in the scene (tagged `Environment`) will be procedurally generated.

2. Prefab controller script will attempt to randomly place 100 objects within the bounds of the scene. Currently I'm trying to have the prefab script handle its own destruction and have the main controller check to see if the prefab was destroyed - however that information isn't available until later. What I tried before was to add an `OnTriggerEnter` function within the prefab to set a flag that was publicly-accessible, but had the same issue with timing.

```
public class WaypointGenerator : MonoBehaviour
{
    public List<GameObject> locations;

    void Start()
    {
        for (int i = 0; i < 100; i++)
        {
            GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>("Assets/Prefabs/BaseWaypoint.prefab");

            // instantiate prefab
            var prefabInstance = Object.Instantiate(prefab, GenerateLocation(), Quaternion.identity);
            var prefabScriptInstance = prefabInstance.GetComponent<WaypointController>();

            locations.Add(prefabInstance);

            // previous attempt - check if collision flag is true
            // if (prefabScriptInstance.IsColliding())
            // {
            //   Destroy(prefabInstance);
            //   print("spawned inside object");
            // }
        }

        for (int i = 0; i < locations.Count; i++)
        {
          // here i was thinking to check which prefabs were missing and regenerate
          if (locations[i].name.Contains("Missing Prefab"))
            print("oops");
        }
    }

```

This is what my prefab script looks like. Right now the prefab itself is an empty `gameObject` with a `BoxCollider` with `trigger` checked.

```
public class WaypointController : MonoBehaviour
{
    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "Environment") {
            print("Spawned inside environment - destroying.");
            Destroy(transform.root.gameObject);
        }
    }
}

```

# Answer
The answer here for me was pretty simple, so this might not fit for everyone. I just generate a new position from the child (`WaypointController`) script if `OnTriggerEnter` is called appropriately. Then the object takes care of itself rather than the main controller.
> 0 votes

---
Tags: unity, procedural-generation, prefabs
---


# Question
Title: Inconsistent movement / line-of-sight around obstacles on a hexagonal grid
In a roguelike game I've been working on, one of my core design goals has been to allow the player to "Play the game, not the grid."

In essence, I want the player's positioning to be tactical because of elements in the game world, not simply because some grid tiles are more advantageous than others in relation to enemies. I am fine with world geometry not being realistic, but it needs to be consistent.

In this process, I have run into most of the common problems (Square tiles? Diagonal movement, LOS, corner cases, etc.) and have moved to a hexagonal tile grid. For the most part this has been great, and I've not had too many inconsistencies.

Recently, however, I have been stumped by the following:

Points **A** and **B** are both distance 4 from the player (red lines). Lines-of-sight to both are blocked by walls (black tiles). However, due to the hexagonal grid, **A** can be reached in 4 moves, whereas **B** requires 5 moves (blue lines).

On a hex grid, "shortest path" seems divorced from "direct path"; there may be multiple shortest paths to any point, but there is only one direct path (or two in some situations). This is fine; geometry doesn't need to be realistic.

However, this also seems inconsistent: Similar obstacles are more effective in some positions than in others. A player running away from an enemy should be able to run in any direction, increasing the distance between the two actors. However, when placing obstacles or traps between themselves and enemies, the player is best served by running in one of the six directions that don't have multiple shortest paths.

Is there a way to rationalise this? Am I missing something that makes this behaviour consistent? Or is there a way to make this behaviour consistent? I am most certainly over-thinking this, but as it is one of my goals, I should do it due diligence.

# Answer
> 9 votes
As long as your movement space isn't Euclidean and things can block an entire grid space, you'll have this problem.

If you want people to not "play the grid" you're probably going to have to not use a grid.

# Answer
> 7 votes
(I don't have enough reputation to comment) The answer here is that the distances are wrong. A is closer than B. To convince yourself, compare A and the reflection of B w.r.t. the player, so I don't think there is an issue here.

Hex grids are tricky in a lot of ways.

# Answer
> 2 votes
The mistake in this post was treating any red line that crosses a hex as being equal. Those red lines are not all the same length in the Euclidean space of the player's screen (ignoring the grid).

If we take the edge length of a hexagon to be our unit, 1, then a line connecting two opposite corners has Euclidean length 2, and a line connecting the centers of two opposite edges has Euclidean length \\$\sqrt 3\\$.

That makes the straight-line distance to A:

* center to corner = 1
* hex edge = 1
* corner-to-corner = 2
* hex edge = 1
* corner to center = 1

...for a grand total of 6 hex edges' distance from the center of the start tile to the center of A.

Compare to the straight-line distance to B, which is:

* center to edge = \\$\frac {\sqrt 3} 2\\$
* 3 x edge-to-edge = \\$3 \sqrt 3\\$
* edge to center = \\$\frac {\sqrt 3} 2\\$

...for a grand total of \\$4 \sqrt 3 \approx 6.928\\$ from the center of the start tile to the center of B - almost one full hex edge farther away.

Two ways to see this:

1. Duplicate the map and rotate one copy around the starting point, so that A and B are in the same line. Notice how the copy of B is farther down the line than the original A.
2. As suggested by Alexis Andre, mirror B across the starting point (shown in green). Now we can see that to reach either A or the mirrored B we need to move the same distance down the screen. But to reach the mirrored B we *also* need to move some distance left. So B's distance from the starting point must be strictly greater than A's.

---
Tags: movement, roguelikes, hexagonal-grid, line-of-sight
---


title: Box2D bodies order inside the world

text:
# Question
Title: Box2D bodies order inside the world
I'm working on a small platform game using box2d. When I create the game's objects I store them inside a vector. One for dynamic bodies and one for static bodies.

```
auto static_obj = Factory<StaticObject>::create(name, position, world);
auto dynamic_obj = Factory<DynamicObject>::create(name, position, world);

if (static_obj)
    static_objects.push_back(std::move(static_obj));
else if (dynamic_obj)
    dynamic_objects.push_back(std::move(dynamic_obj));

```

Afterwards when the game starts I have to pull the dynamic bodies from the world and update the visual part of the objects.

```
for (b2Body* BodyIterator = m_world->GetBodyList(); BodyIterator != 0; BodyIterator = BodyIterator->GetNext())
{

    if (BodyIterator->GetType() == b2_dynamicBody || BodyIterator->GetType() == b2_kinematicBody)
    {
        auto data = (GameObject*)BodyIterator->GetUserData().pointer;

        if (data)
        {
            if (data->get_name() == "moving_platform")
            {

                m_dynamic_objects[counter]->update_position(SCALE * BodyIterator->GetPosition().x - 16, SCALE * BodyIterator->GetPosition().y - 25);
                m_dynamic_objects[counter]->update_rotation(BodyIterator->GetAngle() * 180 / b2_pi);

                counter++;
            }
            else if (data->get_name() == "player")
            {
                m_dynamic_objects[counter]->update_position(SCALE * BodyIterator->GetPosition().x, SCALE * BodyIterator->GetPosition().y);
                m_dynamic_objects[counter]->update_rotation(BodyIterator->GetAngle() * 180 / b2_pi);
                counter++;
            }
        }
}

```

But the problem is that there is no synchronization between the order of the objects in the world and their order in the vector.

Is there any order of objects within the world or is it just random? And if so, how can my problem be addressed?

# Answer
I founded very simple solution. For each object I'm holding the body, so there is no need to go through the body list of the world, but just let every object to update his own position by taking the position from the body.

```
this->update_position(SCALE * m_phisical_body->GetPosition().x, SCALE * m_phisical_body->GetPosition().y);

```
> 0 votes

---
Tags: c++, box2d
---


title: Draw a graph as a world map in UI?

text:
# Question
Title: Draw a graph as a world map in UI?
What's a good way to take a graph of nodes and draw it in your UI as a map?

I already have a graph and I'm happy with how it's generated. However, it doesn't have any positional data for the nodes -- just their connections. How can I use it to draw a map along the lines of Slay The Spire:

I've seen examples (Procedural Dungeon Generation #3, stsmapgen) that populate a space with nodes and connect those nodes, but I want to have more control over how often I branch so I would prefer if my generation wasn't based derived from random node positions.

So far most answers I've found were to use graphviz, but obviously that's not feasible at runtime.

My graph starts at an entrance node, terminates at an exit node, all transitions are unidirectional, and each node can have at most four connections (one in and three out). Paths through the tree can branch off and merge back in to a later path.

My naïve approach of giving an offset for each of the three out transitions, doing a breadth-first walk of the tree, and assigning node positions based on the source node and the offset produced overlapping nodes. It seems like I'd need to push nodes away that are overlapping, but I'm hoping there's a simpler solution and one that doesn't require physics.

# Answer
I ended up storing some information at map generation time that guides map layout in UI.

I generate the map nodes into a grid (to help bound the total size of the map) and lay them out as follows:

* world map flows from left to right (unlike the above image)
* rooms are generated breadth first
* each room is assigned an index based on generation order
* each additional depth is in a new column
* each new room is put in the first available row in the column

This allows me to draw my UI as a transformation of this grid: vertically align each column and add some noise to offset them (I store this noise along with the generated map so presentation doesn't vary when the map's displayed).

## In More Detail

I count the number of connected rooms in each column to determine a bucket count. This determines the starting height of the first node and the vertical offset for each subsequent node (`max_height / bucket_count`).

I horizontally space based on the bucket count too so that nodes with few connections can be placed closer together but nodes with many connections have more space to show their connections.

I have a circular list of random offsets. I select one based on the room index, scale it by column width, and added each node's position. This hides the regular grid and makes the map look more organic.
> 1 votes

---
Tags: 2d, gui, software-engineering, maps
---


# Question
Title: How to make the transform rotate backwards but in FixedUpdate instead in coroutine?
First time I tried this method:

```
public IEnumerator DoRotation(float time)
{
    var newRotation = Quaternion.AngleAxis(180, Vector3.up) * transform.rotation;
    var progress = 0f;

    while (progress < 1)
    {
        progress += Time.deltaTime / time;
        transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, progress);
        yield return new WaitForEndOfFrame();
    }
}

```

Then I used a flag helper inside `Update()` to start the coroutine only once but when the transform rotates backwards it also start moving and when moving the transform it shakes/stutters.

I had the same problem with another rotation part and when moving it to `FixedUpdate()` it solved the shaking problem.

I'm not sure why it's shaking like that.

I tried this in the `FixedUpdate`:

```
var newRotation = Quaternion.AngleAxis(180, Vector3.up) * transform.rotation;
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, Time.deltaTime * rotationSpeed);

```

But it keeps rotating the transform 180 degrees the opposite direction nonstop.

How to make the transform rotate backwards in `FixedUpdate` instead of in coroutine?

# Answer
How about using WaitForFixedUpdate instead of WaitForEndOfFrame? You should put the yield **before** your code to ensure your code is called in FixedUpdate.

Also, I find tracking the elapsed time easier to reason about. And you probably want to lerp from the start rotation to the end to ensure you're linearly rotation from one to the other:

```
var startRotation = transform.rotation;
var newRotation = Quaternion.AngleAxis(180, Vector3.up) * transform.rotation;

var elapsed = 0f;
while (elapsed < time)
{
    yield return new WaitForFixedUpdate();

    elapsed += Time.deltaTime;
    var progress = elapsed / time;
    transform.rotation = Quaternion.Slerp(startRotation, newRotation, progress);
}

```

The advantage of lerping from start to end is that you can pass the progress value to an easing function to adjust how it interpolates.

Note that this doesn't guarantee that it reaches the end point because we stop looping before elapsed == time. To solve that, you could change the loop condition and clamp progress between 0 and 1.
> 0 votes

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


title: Sphere rolling shader like ice cream

text:
# Question
Title: Sphere rolling shader like ice cream
now I can make cylinder shape with shader. But what I want to do is like picking up ice cream with an ice cream scoop. How can I do this?

# Answer
> 0 votes
Here's a sketch of how I'd approach an effect like that:

1. When the scoop contacts the surface of the ice cream, spawn a decal at that position that overwrites the ice cream's normals to look like it's bulging (like a classic ground pound effect). As the scoop presses deeper, expand/increase the intensity of this decal.
2. As the scoop passes a threshold depth, spawn/reveal an ice cream textured sphere just under the surface of the ice cream. Scale this sphere so it's a narrow spindle at first, lying perpendicular to the scoop direction.
3. As the scoop moves, gradually grow the sphere back to uniform scale and slide it into position in the center of the bowl. While doing this, pan the ice cream texture along the sphere so it looks like the ice cream is rolling. Adjust the texture tiling so that the details remain the same size as the sphere gets bigger.
4. Behind the scoop, extend the distortion decal into a ribbon, similar to drawing skid marks behind a car tire. You can use a parallax displacement effect in the decal shader to make it look like a concave hollow.

If you need to take multiple overlapping scoops out of the same ice cream surface (not specified in your question), then the decal fakery won't hold up, and you may want to draw the ice cream surface using a heightmap instead, like terrain. Where the scoop travels, lower the heights in the heightmap to leave a trough shape.

---
Tags: unity, shaders, mesh
---


# Question
Title: How do I make a blueprint run keyboard key commands?
I created a project based on the **Top Down Example**.

In the project comes a character that I can move by clicking on the terrain that already comes by default.

**Image of gameplay:**

In the character's blueprint, I added a function on the **N KEY**. Simply to print a sentence (*key N*).

**Character's blueprint:**

**I created an NPC based on creating a Blueprint Class \> Character:**

In the NPC blueprint I added a function, only now in the **M KEY**, but with the same principle. Print a sentence (*key M*).

**NPC's Blueprint:**

**It turns out that only the command made in the blueprint of the character works:**

*I alternately clicked the **N and M keys** to take the screenshot.*

I scanned the character's blueprint to see if something was missing, something I needed to add in order for the NPC blueprint to recognize the keyboard command. But I only found things like that related to the mouse.

**Scan:**

I'd like to know what I need to do to make the NPC blueprint recognize the **M KEY**.

# Answer
> 1 votes
In the Pawn section of your AI Character, you will find the option "AI Controller Class"

You need to create this controller class in Blueprint. It's not one of the standard options, you'll need to search for it or use the drop down arrows.

When you've got this and set up your required options in the Pawn section of your AI Character, you can set the relevant code inside this AI Controller Blueprint.

# Answer
> 1 votes
To receive input, you should use a PlayerController. You'd want to check "Auto Possess Player" in your pawn and set your GameMode to use your PlayerController as the default.

However, I'd suspect your new Character receives input and the existing one does not because the new one either has "Auto Possess Player" or is otherwise being possessed by the player and the existing one is not.

In Unreal, a Controller "possesses" a Pawn so it's the thing that can tell it how to behave. So a PlayerController can possess a Pawn and send it commands based on player inputs or an AIController can possess a Pawn and send it commands based on your AI scripting. You can probably use input commands from the Pawn if it's possessed by the PlayerController.

---
Tags: unreal-4, keyboard, blueprints
---


# Question
Title: How can I move and rotate an object along with another using vector math?
How can I move and rotate an object along with another using vector math?

This is using Godot 3.1 using a `KinematicBody2D` as a ship with a `StaticBody2D` as a planet.

# Answer
> 2 votes
The engine is geared towards making this easy by parenting. Though it may not be conceptually correct in your case, it's the most godot friendly way of doing it. Just add the ship as a child node of the planet when it lands, and detach it from the planet when it leaves.

As long as the parent-child relation is a chain of spatial nodes (if 3D) or Node2d (if 2D) they will share and propagate transforms.

If for a reason you want a node to be a child of a Spatial or Node2d without inheriting their movement, you just have to make sure that the "independent" node is child of a bare "Node" (the gray/white ones in the UI, instead of the blue/red). This would interrupt the transform propagation

# Answer
> 1 votes
*Disclaimer*: *This solution assumes knowledge of linear algebra. Additionally, I'm new to these problems myself and my solution might be erroneous or incomplete. Any comments or edits are **more than welcome**.*

Any *transformation* of objects in 2(3)D space is done via what is called an **affine transformation** matrix. This matrix is usually a 3x3 (or 4x4 in 3D) matrix that contains/combines the following transformations:

1. Scaling
2. Rotating
3. Translating (moving)

All of the transformations are applied to *each* of the points that make up the object(s) in space. **Affine transformations** have a specific property where whichever *set* of points they transform, their *relative* positions remain unchanged.

In order to perform a transformation on an object you must first generate the corresponding matrix that will do this (in your picture example this would be a matrix containing only a rotation around the Z axis located in the middle of the orange square). With the matrix at hand, you can now *apply* it to each point that represents your objects in space (both the orange and the blue squares). In order to apply a transformation matrix you multiply it with the *vector* that represents the *position of the point* (in 3D the vector has 3 components namely x,y and z), \\$M\*V\\$ where \\$M\\$ is a 4x4 transformation matrix and \\$V=\[x,y,z\]^T\\$ (the \\$T\\$ exponent denotes the transpose of the matrix). Applying this transformation to all the points in space will rotate them but their *relative positions* will remain unchanged (as per the affine transformation property) which means that the blue square position relative to the orange square will **not** change.

# Answer
> 0 votes
Oxy is correct that parenting is the easy way. *And, yes, I'm aware I'm answering years later.* Yet, if that is not convinient, we can still do this.

The `KinematicBody2D` (which I'll call `ship`) and the `StaticBody2D` (which I'll call `planet`) has their own transforms:

```
var ship_transform := ship.global_transform
var planet_transform := planet.global_transform

```

We are looking for a `relative_transform`, such that:

```
planet_transform * relative_transform = ship_transform

```

In other words:

```
var relative_transform := planet_transform.affine_inverse() * ship_transform

```

---

Once you have that, you can rotate the `planet`… Consider using a `KinematicBody2D` for the planet… Anyway, for example:

```
planet.rotation_degrees += somavelue

```

Which would change the transform of the `planet`. In fact, if you prefer, you could work with the transform directly:

```
planet_transform = planet_transform * Transform2D.IDENTITY.rotated(rad2deg(somevalue))
planet.global_transform = planet_transform

```

*This also gives you the option to not set `planet.global_transform`, so we would be doing this as if it rotated. You would probably want to keep track of the rotation elsewhere in that case.*

And then we can computed the updated transform for the `ship`:

```
ship_transform = planet_transform * relative_transform
ship.global_transform = ship_transform

```

Notice that if the `planet_transform` didn't change, `shipl_transform` would not change either. Because the `planet_transform` and `planet_transform.affine_inverse()` (part of `relative_transform`) cancel each other out.

---
Tags: physics, rotation, godot
---


title: SQL Database structure for ECS

text:
# Question
Title: SQL Database structure for ECS
I am making turn-based browser game (mostly server-sided), and every turn all game-state is saved into database (SQLite). Using ECS pattern. Never done this before (I am webdev).

There will be a lot of components, mostly simple but a lot of it.

I am thinking about DB structure right now, probably the most important thing for all development, and I have two versions:

1. One table, entities are rows, components are columns.

```
+ only one table, easier to code and to think about
- most of this table will be empty, null, 99%
- there can be a lot of small components, like some small tags for very few specific entities, table can become *very* wide (and very empty)
- can't do one-to-many (several same components for entity)

```
2. Every component is separate table with entity id per row

```
+ no nulls, everything is tight and beautiful
+ one-to-many
+ performance
- harder to code
- can have a lot of small tables, like several rows total for some specific entities
- only 1 (tag) or 2 (value) columns for every table, seems like denormalization or vertical partition

```

What is the generally best option? Or maybe something else.

All info I can find is about in-memory storage (arrays), but nothing about dbs.

# Answer
> 2 votes
I would lean towards option 2.

A *system* in ECS uses a database query using joins across tables. For example, you might have a system that needs all entities that have a health component and a potion component. When you represent components as tables, this system would be a database *join* of the health table and the potion table.

However, you're right that option 1 is *easier* in many ways. I think a lot of games using ECS may be better off with something more like option 1 (e.g. structs with option\<\> fields instead of separate arrays for each component).

I think you have to decide *why* are you using the ECS pattern. Once you know the reason you've chosen to use it, you'll be able to evaluate option 1 and 2 relative to your goals.

---
Tags: databases, entity-component-system
---


# Question
Title: Help swapping out one player character for another
recently I’ve been working on a system that would allow the player to swap out one character for another with a touch of a button.

So far I’ve just been trying to focus on switching to one character in particular before expanding into being able to switch to all the other characters.

***Player Controller blueprint - Character swapping setup:***

***Character blueprint:***

I’ve managed to set up the blueprint so that when the character being controlled by the player pushes the right analog stick to the left, the previous actor is destroyed and the new character is spawned in their place. I’ve also managed to accomplish switching my custom camera from following the old character to the new one as well.

However, the one thing I haven’t been able to accomplish is that the newly spawned character won’t respond to any controller input. Not only is the character unable to move but they can’t access the pause menu as well, which would appear to indicate that the Player Controller blueprint isn’t taking control of the new character when they spawn into the level.

I’m not sure why is happening, which is why I need help in figuring out why it isn’t working properly.

I was also wondering if anyone also knows how I can spawn the new character in the exact same location as the old one.

With my current setup, the newly spawned character appears at the start of the level instead of the exact same location as the previously spawned character.

As always, any help whatsoever with either of these issues would be greatly appreciated!

UPDATE: I’ve managed to get the new character to spawn in the same spot as the previous one, as well as getting them to face in the same direction upon spawning.

Unfortunately though, I'm still unable to get the Player Controller blueprint to possess the newly spawned character when I switch characters.

# Answer
Nevermind, I managed to solve the problem myself. It turns out the solution was to remove the Set Actor Tick Enabled node, as once it was removed my character swapping setup started to work properly.
> 0 votes

---
Tags: unreal-4, blueprints
---


# Question
Title: Unity ScrollRect: Pass scrolling through to parent ScrollRect when reaching limits
I have a nested ScrollRect, or more specifically a scrollable list inside one of the items in another scrollable list. Think of it as a scrollable menu with one of the items including a scrollable list. All the following will just refer to vertical scrolling, since I do not require any horizontal scrolling.

I would have expected that once reaching the limits of the child ScrollRect, the scrolling would pass through to the parent ScrollRect and continue scrolling the parent list, as is common in all such instances that I'm aware of. However, this simply does not happen. The child ScrollRect captures the scrolling, sees that it is at its limit, does not continue scrolling and nothing further happens.

Looking for answers online, I only find answers to having a horizontal scrolling ScrollRect inside a vertical one, but no problems matching mine. If I'm just missing something very obvious, I'm happy to be pointed in the right direction, but if not, any assistance with this problem would be appreciated. For now I'm going to play around with subclassing to see if I can solve the problem in that way.

See below the child and the parent ScrollRects

# Answer
I ended up copying the ScrollRect script as is to my own script. I called it ScrollRectChild and removed it from the namespace. I tried to subclass from ScrollRect, but too many of the functions and variables are private and I didn't want to change the base script.

Note: This modification will only work for a clamped ScrollRect, and I haven't tested it for horizontal movement, though it should work for that as well.

Modifications to the script: Added a bool called passScrolling, which indicates that "overrunning" the scrolling should be passed on to parent ScrollRects.

In the OnScroll function, modify the last if statement to:

```
if (m_MovementType == MovementType.Clamped)
{
    Vector2 offset = CalculateOffset(position - m_Content.anchoredPosition);
    position += offset;
    data.scrollDelta = offset / m_ScrollSensitivity;
    if (passScrolling)
    {
        passToParent(data);
    }
}

```

The passToParent function:

```
private void passToParent(PointerEventData data)
{
    Transform parent = transform.parent;
    while (parent != null)
    {
        if (parent.GetComponent<ScrollRect>() != null)
        {
            parent.GetComponent<ScrollRect>().OnScroll(data);
            break;
        }
        if (parent.GetComponent<ScrollRectChild>() != null)
        {
            parent.GetComponent<ScrollRectChild>().OnScroll(data);
            break;
        }
        parent = parent.parent;
    }
}

```

This code works perfectly for horizontal scrolling (slight modification might be required for horizontal, to be tested). However if there is a better solution, please post it as another answer. This is more of a work-around and I'm still very surprised this functionality isn't standard.
> 1 votes

---
Tags: unity, unity-ui
---


title: Custom Recipes in Minecraft Modpack

text:
# Question
Title: Custom Recipes in Minecraft Modpack
I want to have a new Recipe with crafttweaker, which using machines from the create mod, for Netherrack like this

At the moment I tryed this code in \scripts\MyRecipes.zs:

```
import crafttweaker.api.item.IItemStack;
import crafttweaker.api.ingredient.IIngredient;
import crafttweaker.api.recipe.FurnaceRecipeManager;

import mods.create.IProcessingRecipeManager;
import mods.create.MechanicalCrafterManager;
import mods.create.CrushingManager;
import mods.create.SplashingManager;
import mods.create.CompactingManager;
import mods.create.FillingManager;
import mods.create.MixingManager;
import mods.create.PressingManager;

<recipetype:create:compacting>.addRecipe("compact_netherrack", <constant:create:heat_condition:none>, [<item:minecraft:netherrack> * 8], [<item:minecraft:cobblestone> * 8, <item:minecraft:nether_wart>], [<fluid:minecraft:lava> * 10], 100);

```

but when I go into the world I get this errors:

```
[Error] Parser Exception @ MyRecipes.zs:16:63 : Invalid bracket expression: no prefix constant
[Error] Scripts are invalid!
[Error] Parser Exception @ MyRecipes.zs:16:63 : Invalid bracket expression: no prefix constant
[Error] Scripts are invalid!

```

can somebody help me?

# Answer
From the error text, I'm guessing that the problem is this part `<constant:create:heat_condition:none>` as it says "Invalid bracket expression: no prefix constant", I figured that `<constant:...>` is not a thing, or at least not valid here.

Thus, I decided to search the line up to that point, to see an example of how it should be. And I found it here: Create Compacting. Based on that I believe you should write `"none"` instead of `<constant:create:heat_condition:none>`. As far as I can tell that is all the fixing required.
> 0 votes

---
Tags: minecraft-modding
---


title: Empty room list on region change

text:
# Question
Title: Empty room list on region change
I am using PUN2 for my game and I am using the `OnRoomListUpdate()` function to sync my UI with the rooms that are available to players when they are in the lobby. The room lists come back from Photon just fine until I switch regions. If I switch regions and rejoin the lobby, I get the `OnRoomListUpdate()` event but no rooms are handed back for that region when I know I have rooms open. Below is the code I have for switching regions:

```
public void ConnectToRegion(string region)
{
    PhotonNetwork.Disconnect();
    PhotonNetwork.PhotonServerSettings.AppSettings.FixedRegion = region;

    if (!PhotonNetwork.ConnectUsingSettings())
    {
        Debug.LogError("Unable to connect.");
    }
    else
    {
        PhotonNetwork.JoinLobby();
        currentRegionText.text = $"Current region: {region}";
    }
}

```

# Answer
I haven't tested myself, but what's sticking out to me is that you're attempting to join lobby right away after calling ConnectUsingSettings, which has some asynchronous work to do. In my project I call JoinLobby after receiving the OnConnectedToMaster callback. So perhaps you're just trying to join the lobby too soon?

EDIT: The disconnect is asynchronous as well. I just needed to put something together myself so here is something you can do (I used the connection callbacks in mine but coroutines should work too, as below). I also used "ConnectToRegion" so that I don't mess with server settings. This works for me, I'm seeing rooms from the selected region.

```

   public void SwitchToRegion(string region)
   {
      StartCoroutine(SwitchToRegionCoroutine(region));
   }

   IEnumerator SwitchToRegionCoroutine(string region)
   {
      PhotonNetwork.Disconnect();
      yield return new WaitWhile(() => { return PhotonNetwork.IsConnected; });
      PhotonNetwork.ConnectToRegion(region);
      yield return new WaitUntil(() => { return PhotonNetwork.IsConnected; });
      PhotonNetwork.JoinLobby();
   }

```
> 1 votes

---
Tags: unity, photon
---


# Question
Title: Argument out of Range Exception on click of button that calls a function that doesn't use an index
Currently writing a script that builds a HUD for testing some functions in a project. It automatically builds buttons, one of which works, while the other gives the error indicated in the title and error message below.

The function the button is calling works when called by a button manually placed in the scene, indicating that the issue isn't with the function itself but the way the button is being built.

The script compiles successful and are rendered correctly in the edtior. Clicking the radio button (which builds the button that is giving the error) works correctly, building the button and running the debug logs.

The error occurs when clicking on the "next song" button, which is generated by clicking on the radio button.

**Here is the error:**

```
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
System.Collections.Generic.List`1[T].get_Item (System.Int32 index) (at <6073cf49ed704e958b8a66d540dea948>:0)
TestHUD+<>c__DisplayClass12_0.<BuildActions>b__0 () (at Assets/Scripts/TestHUD.cs:86)
UnityEngine.Events.InvokableCall.Invoke () (at <f1212ad1dec44ce7b7147976b91869c3>:0)
UnityEngine.Events.UnityEvent.Invoke () (at <f1212ad1dec44ce7b7147976b91869c3>:0)
UnityEngine.UI.Button.Press () (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Button.cs:70)
UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Button.cs:114)
UnityEngine.EventSystems.ExecuteEvents.Execute (UnityEngine.EventSystems.IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/ExecuteEvents.cs:57)
UnityEngine.EventSystems.ExecuteEvents.Execute[T] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.ExecuteEvents+EventFunction`1[T1] functor) (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/ExecuteEvents.cs:272)
UnityEngine.EventSystems.EventSystem:Update() (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/EventSystem.cs:501)

```

**Here are the Debug Logs**

> Length of buttonActions is 1.

> Function button created

**Here is the script as it currently exists:**

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

public class TestHUD : MonoBehaviour
{
    GameObject testHUD;

    public List<TestHUDPanel> testHUDPanels = new();

    public GameObject sectionPanel;
    public GameObject functionPanel;

    public GameObject sectionPrefab;
    public GameObject functionPrefab;

    //Color32 activeColor = new Color32(255, 201, 191, 255);
    //Color32 inactiveColor = new Color32(191, 255, 241, 255);

    SoundManager soundManager;

    public class TestHUDPanel
    {
        public string name;
        public GameObject linkedObject;
        public GameObject panelObject;
        public List<Action> buttonActions = new();
        public List<string> buttonLabels = new();

        public TestHUDPanel(string panelName)
        {
            name = panelName;
        }

        public void AddButton(string buttonName, Action buttonFunc)
        {
            buttonActions.Add(buttonFunc);
            buttonLabels.Add(buttonName);
        }
    }

    private void Awake()
    {
        testHUD = gameObject;
        soundManager = GameObject.Find("SoundManager").GetComponent<SoundManager>();
    }

    private void Start()
    {
        BuildPanelList();
        BuildPanels();
    }

    public void BuildPanelList()
    {
        testHUDPanels.Add(new TestHUDPanel("Radio"));
        testHUDPanels[0].AddButton("Next Song", soundManager.PlayNextSong);
        testHUDPanels.Add(new TestHUDPanel("Typing"));
        testHUDPanels.Add(new TestHUDPanel("Audio"));
    }

    public void BuildPanels()
    {
        foreach (TestHUDPanel panel in testHUDPanels)
        {
            GameObject panelObject = Instantiate(sectionPrefab);
            panelObject.transform.SetParent(sectionPanel.transform);
            Button button = panelObject.GetComponent<Button>();
            panelObject.GetComponentInChildren<TextMeshProUGUI>().text = panel.name;
            button.onClick.AddListener(() => BuildActions(panel));
        }
    }

    public void BuildActions(TestHUDPanel panel)
    {
        for (int i = 0; i < panel.buttonActions.Count; i++)
        {
            GameObject panelObject = Instantiate(functionPrefab);
            panelObject.transform.SetParent(functionPanel.transform);
            Button button = panelObject.GetComponent<Button>();
            panelObject.GetComponentInChildren<TextMeshProUGUI>().text = panel.buttonLabels[i];
            Debug.Log(string.Format("Length of buttonActions is {0}, ", panel.buttonActions.Count));
            >>> THIS IS LINE 86 <<< : button.onClick.AddListener(() => panel.buttonActions[i]());
            Debug.Log("Function button created");
        }
    }
}

```

# Answer
This is a common coding pitfall: you are using a loop increment in a callback function inside a loop construct. The callback function records the reference of the local variable `i` and reads it when it is called, but at this time i has already increased to the exit threshold.

Try this:

```
    for (int i = 0; i < panel.buttonActions.Count; i++)
    {
        var temp = i;
        ...
        button.onClick.AddListener(() => panel.buttonActions[temp]());
    }

```

Deeper explanation:

When a local variable is referenced in the delegate, it becomes a captured variable. this is a good explanation.

The for loop is actually a syntactic sugar, the scope of i is outside the for structure:

```
    for (int i = 0; i < 10; i++)
    {
        //your code
    }

```

is actually equivalent to:

```
    int i = 0;
    for (;;)
    {
        if(i < 10) break;
        //your code
        i++;
    }

```

that is to say, the `i` used in each round of the loop points to the same local variable. The captured variable is also the same one. If a new variable(copied of `i`) scoped to the loop structure is used in each round of the loop, then the captured variable is different.
> 2 votes

---
Tags: unity, user-interface
---


# Question
Title: Custom Recipes in Minecraft Modpack (other Error)
I want to have a new Recipe with crafttweaker, which using machines from the create mod, for Netherrack like this  Im playing Mc 1.16.5

At the moment I tryed this code in \scripts\MyRecipes.zs:

```
import crafttweaker.api.registries.IRecipeManager;

<recipetype:create:compacting>.addRecipe("compact_netherrack", "none", [<item:minecraft:netherrack> * 8], [<item:minecraft:cobblestone> * 8, <item:minecraft:nether_wart>], [<fluid:minecraft:lava> * 10], 100);

```

but when I go into the world I get this errors:

```
[Error] Parser Exception @ MyRecipes.zs:3:0 : No such member: addRecipe
[Error] Scripts are invalid!

```

can somebody help me?

# Answer
> 1 votes
The error text is telling you that it does not have the method `addRecipe`, or at least the system is unable to find it.

The Create Compacting article says:

> The Compacting mechanic is a type of IRecipeManager and implements all the methods that are available to IRecipeManager's, such as removeRecipe() and removeAll().

We can confirm that `IRecipeManager` does not have an `addRecipe` method.

So we want some type that extends `IRecipeManager`, adding some things, presumably adding the missing `addRecipe`. Sadly the article quoted above does not say the name of the class we need. It only refers to it as "The Compacting mechanic".

Searching for `<recipetype:create:compacting>` I found `CompactingManager`, which lists among its methods `addRecipe`.

So, I believe you need to import `CompactingManager`:

```
import mods.create.CompactingManager;

```

---
Tags: minecraft-modding
---


# Question
Title: In Unity 2021.3, is there a way to search my project files for all prefabs that have a specific component attached to them?
If many of my prefabs have an `ExampleComponent.cs` attached to them, how can I use Unity's built-in search to find them?

If such a search isn't possible, what are some tips for organizing one's assets so that things are more searchable as my project grows in complexity?

# Answer
Unity Editor allows you to find usages of an asset in scene only. You can implement resource search through some third-party scripts like this.

Put the code in the editor directory, right-click a script (resource) and a new search button will appear.

It basicly uses EditorUtility.CollectDependencies:

> Calculates and returns a list of all assets the assets listed in roots depend on.

Recursively traverse all resources with the specified suffix in the Assets directory, access the resources they depend on. so that you can find out which resources the specified resource is referenced by.
> 2 votes

---
Tags: unity
---


# Question
Title: Unity, hold down right mouse button to turn the camera
How would I use my right mouse button to turn a player character in Unity, while only turning in the direction and speed of the drag?

The game is 3D and you should hold down right click and drag to turn the camera.

Here is the code:

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

public class Control : MonoBehaviour {

public int speed;
public Transform tf;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if (Input.GetMouseButton(1))
    {
        tf.eulerAngles = new Vector3 (0, Input.GetAxis("Mouse X") * speed, 0);
    }
}
}

```

The code above works, but after moving the mouse in the specified direction the character jumps back to its original position and kind of does this glitchy turn while moving the mouse (keeps jumping back to original position).

# Answer
An even better solution IMO would be to use transform.Rotate:

```
tf.Rotate(0f,  Input.GetAxis("Mouse X") * speed, 0f);

```
> 1 votes

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

public class Control : MonoBehaviour {

public int speed;
public Transform tf;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if (Input.GetMouseButton(1))
    {
        tf.eulerAngles = tf.eulerAngles + new Vector3 (0, Input.GetAxis("Mouse X") *
speed, 0);
    }
}
}

```

^ I solved it, thanks @Gabriele Vierti.

Also, I can't accept my own answer for two days, someone please re answer this with the code so that I can set as the answer.
> 0 votes

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


title: Drawing a filled ellipse in Unity

text:
# Question
Title: Drawing a filled ellipse in Unity
For my Unity puzzle game, I am looking to draw elliptical "shadows" under certain letters in a Text Mesh Pro text field.

These shadows will have varying widths depending on the width of the letters, and the number of letters covered by the shadow. The following picture shows three possible examples of one-letter, two-letter and three-letter shadows.

I have calculated the width of each letter, and between that and the kerning... I know what the semi-major axis of the ellipse should be. (The height/semi-minor axis will always be the same.)

I understand that it's possible to draw an ellipse using a Line Renderer. Is there a similarly simple way to draw a filled ellipse? There would ideally be 4 inputs:

* Width (semi-major axis)
* Height (semi-minor axis)
* Color of the fill
* Color of the border

(If the color of the fill and the color of the border has to be the same, that is totally acceptable.)

Any suggestions on how to draw such a filled ellipse in Unity? Thank you!

# Answer
> 1 votes
The easiesy way to get just a pseudo shadow working is to use an image and stretch it. You can use 9 Splice or 2 images (for border and inside). As long as your basis image is not too small, it will look decent enough.

---
Tags: unity, graphics-programming
---


# Question
Title: How to get data from a Scriptable Object into a Prefab template
I made a Unity Prefab where about 5 things vary. I then made an invisible GameObject where I use Visual Scripting to hardwire the 5 differing items, in order to create the various GameObjects I need.

It is hardwired, but the Prefab is working really well for my purposes. Here's a sample part of that script, where I'm setting the color of some text and also the sprite.

I'd like to make the whole thing less hardwired, and to keep track of these 5 things in a database of sorts. So I defined a Scriptable Object with the 5 variables in it:

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

[CreateAssetMenu(fileName = "New NeemData", menuName = "Neem Data", order = 51)]

public class NeemData : ScriptableObject
{
    [SerializeField]
    private string neemName;

    [SerializeField]
    private Vector3 neemPosition;

    [SerializeField]
    private Sprite singleNeemSprite;

    [SerializeField]
    private string feemText;

    [SerializeField]
    private Color feemColor;

}

```

I've been able to easily create Scriptable Objects with data in it, like this one:

I'd like to be able to populate my Prefab with the data from that Scriptable Object, and create GameObjects with that workflow. But I'm not sure the best way to get data out of a Scriptable Object, and combined with a Prefab template to make GameObjects. Any advice?

# Answer
> 1 votes
I changed the Scriptable Object variables to be public, and everything worked perfectly.

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

[CreateAssetMenu(fileName = "New NeemData", menuName = "Neem Data", order = 51)]
public class NeemData : ScriptableObject
{
    [SerializeField]
    public string neemName;

    [SerializeField]
    public Vector3 neemPosition;

    [SerializeField]
    public Sprite singleNeemSprite;

    [SerializeField]
    public string feemText;

    [SerializeField]
    public Color feemColor;
}

```

---
Tags: unity, prefabs, scriptable-object
---


# Question
Title: Network racing game position interpolation jitters a lot
I'm making multiplayer racing game and I have problem with interpolating position..

Here's the sequence.

1. Server simulate the world and send vehicle transform packet through UDP socket every 33ms to all clients.
2. Client receive packets and update next transform.
3. Client interpolate transform between previous state and next state every frame.

```
void InterpolateWorldTransform(float elapsed, float updateRate)
{
    // updateRate is about 0.033f.
    // if updateRate is zero, don't interpolate..
    if (updateRate <= 0.0f) return;

    // I used mutex to prevent data-race.
    mProgressMut.lock();
    // if progress is more than 1.0f than make it 1.0f.
    float progress = std::min(1.0f, mProgress / updateRate);
    mProgress += elapsed;
    mProgressMut.unlock();

    const XMFLOAT3& prevOrigin = mPrevOrigin.GetXMFloat3();
    const XMFLOAT4& prevQuat = mPrevQuat.GetXMFloat4();

    const XMFLOAT3& correctOrigin = mCorrectionOrigin.GetXMFloat3();
    const XMFLOAT4& correctQuat = mCorrectionQuat.GetXMFloat4();

    // use Lerp for position and Slerp for rotation, both works well.
    mPosition = Vector3::Lerp(prevOrigin, correctOrigin, progress);
    mQuaternion = Vector4::Slerp(prevQuat, correctQuat, progress);
}

// This called in different thread.
void SetCorrectionTransform(SC::packet_player_transform* pck, float latency)
{
    mProgressMut.lock();
    mProgress = 0.0f;
    mProgressMut.unlock();

    mPrevOrigin = mCorrectionOrigin;
    mPrevQuat = mCorrectionQuat;

    mCorrectionOrigin.SetValue(pck->position);
    mCorrectionQuat.SetValue(pck->quaternion);
}

```

I used mutex for `mProgress` because this variable is accessed in different threads.

The result is not good. It jitters a lot even in local host.

I tested in remote too, and jittering even gets worse.

I also tried snapshot interpolation but my lack of knowledge and low experience, it didn't go well..

EDIT: Here is my snapshot interpolation code.(It works but still jitter)

#include "stdafx.h"
#include <queue>

class Interpolator
{
public:
    struct Entry
    {
        bool empty;
        Clock::time_point timeStamp;

        XMFLOAT3 position;
        XMFLOAT4 rotation;

        Entry()
            : empty{ true }
        {
        }

        Entry(const XMFLOAT3& pos, const XMFLOAT4& rot)
            : empty{ false }
        {
            timeStamp = Clock::now();
            position = pos;
            rotation = rot;
        }
    };

public:
    Interpolator()
        : mProgress{ 0.0f }
    {
    }

    void Enqueue(const XMFLOAT3& pos, const XMFLOAT4& rot)
    {
        mEntryQueueMut.lock();
        mEntryQueue.push(Entry(pos, rot));
        mEntryQueueMut.unlock();
    }

    void Interpolate(float dt, XMFLOAT3& targetPos, XMFLOAT4& targetRot)
    {
        mEntryQueueMut.lock();
        if (mEntryQueue.empty())
        {
            mEntryQueueMut.unlock();
            return;
        }

        Entry next = mEntryQueue.front();
        if (mPrevEntry.empty)
        {
            mEntryQueue.pop();
            mEntryQueueMut.unlock();

            mPrevEntry = next;
            targetPos = next.position;
            targetRot = next.rotation;
            return;
        }

        mEntryQueueMut.unlock();

        mProgress += dt;
        float timeBetween = GetDurationSec(next.timeStamp, mPrevEntry.timeStamp);
        float progress = std::min(1.0f, mProgress / timeBetween);

        targetPos = Vector3::Lerp(mPrevEntry.position, next.position, progress);
        targetRot = Vector4::Slerp(mPrevEntry.rotation, next.rotation, progress);

        if (progress >= 1.0f)
        {
            mEntryQueueMut.lock();
            mEntryQueue.pop();
            mEntryQueueMut.unlock();

            mPrevEntry = next;
            mProgress -= timeBetween;
        }
    }

private:
    static float GetDurationSec(Clock::time_point& a, Clock::time_point& b)
    {
        auto msec = std::chrono::duration_cast<std::chrono::milliseconds>
            (a - b).count();
        return (float)msec / 1000.0f;
    }

private:
    std::queue<Entry> mEntryQueue;
    std::mutex mEntryQueueMut;

    Entry mPrevEntry;
    float mProgress;
};
```

# Answer
> 1 votes
You don't need to interpolate the movement during every frame. What you need to do is correct the movement of the client when it goes too far away from the position on the server.

If you do it this way, your vehicle won't be jittering as often. Instead, it will rubberband when it hits the movement threshold.

You can go really deep and find a much more complex way of solving your jittering issues, but what I just described would be the easiest way to go about it.

---
Tags: c++, networking, interpolation, racing
---


# Question
Title: How to reference an object that was not destroyed from a previous scene in the inspector
In a game I'm working on, I have a button on the pause menu that allows me to mute and unmute the background music. The toggle button, in the inspector, references the audio manager object and calls the function to update the sound when the button is pressed. This worked well until recently when I made my audio manager persist across all scenes to avoid the music restarting between levels. As a result, when the next scene loads, the audio manager cannot be found by the toggle button (which I would ordinarily have to drag into the toggle button's "On Value Changed" field from the inspector.

Is there a way around this, or am I going to have to make my pause menu persist across all scenes, too? If I do this, then how should I handle scenes like the main menu or game over menu when they don't have pause menu objects?

# Answer
Use a relay:

```
public class MenuFunctions() {

    // If your AudioManager is already a singleton with an AudioManager.Instance getter,
    // you can use that instead of finding & caching your own reference.
    AudioManager _audio;

    public Toggle _muteButton;

    void Start() {
        // On load, cache a reference to the dependencies persisted from the old scene.
        _audio = FindObjectOfType<AudioManager>();

        // Do any setup needed to ensure the displayed menu state matches any
        // persistent state inherited from the previous scene.
        _muteButton.SetValueWithoutNotify(_audio.isMuted);
    }

    // Your mute button in this scene calls this method.
    public void ToggleMute() {
        // ...which then forwards the message along to the real recipient.
        _audio.ToggleMute();
    }
}

```

Put this script on your pause menu, and wire it up so your mute button (and any other buttons with dependencies on stuff not in the scene) sends its interactions through this script instance.

At runtime, it will get the correct reference to route those interactions along to the correct recipient that did not exist at edit time.
> 1 votes

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


# Question
Title: Anchored Pull Function Breaks at Low Framerate
To start, I'm not working with an engine and am looking for some help fixing the math behind the function I created.

Say we have `anchor`, `obj`, `speed`, `dt`, and `terminationDist` ; function `anchorPull` will theoretically pull `obj` towards `anchor` at a rate of `speed` pixels per second until the distance from `anchor` to `obj` is less than `terminationDist`. My implementation is as follows:

```
def anchorPull(anchor, obj, speed, dt, termDist = 10):

    if dist(anchor, obj) > termDist:
        deltaX1 = obj.x - anchor.x
        deltaY1 = obj.y - anchor.y

        theta = degrees(atan(deltaX1/deltaY1))

        deltaX2 = sin(theta) * speed * dt
        deltaY2 = cos(theta) * speed * dt

        obj.x += deltaX2
        obj.y += deltaY2

```

Visual Representation:

The problem is, at low framerates (a high `dt`) `obj` wont go all the way to `anchor`:

`obj` will also stochastically move around when `anchor` isn't stationary.

Any help would be great, thanks!

# Answer
> 0 votes
It looks like you're trying to implement a MoveTowards function. Try something more like this:

```
def moveTowards(mover, target, maxStep):

    deltaX = target.x - mover.x
    deltaY = target.y - mover.y

    mag = deltaX * deltaX + deltaY * deltaY

    if mag < maxStep * maxStep:
        mover.x = target.x
        mover.y = target.y
    else:
        scale = maxStep / sqrt(mag)

        mover.x += deltaX * scale
        mover.y += deltaY * scale

```

Or, to stop at a fixed distance away from the object, modify like so:

```
def moveTowardsOrbit(mover, target, maxStep, stopDistance):

    deltaX = target.x - mover.x
    deltaY = target.y - mover.y

    distance = sqrt(deltaX * deltaX + deltaY * deltaY)

    unitScale = 1 / distance

    deltaX *= unitScale
    deltaY *= unitScale

    onCircleX = target.x - deltaX * stopDistance
    onCircleY = target.y - deltaY * stopDistance

    fromStop = distance - stopDistance

    if abs(fromStop) <= maxStep:
        mover.x = onCircle.x
        mover.y = onCircle.y
    else:
        if fromStop < 0:
            deltaX *= -1
            deltaY *= -1

        mover.x += deltaX * maxStep
        mover.y += deltaY * maxStep

```

Call this with `moveTowards(obj, anchor, speed * dt, 10)`.

This version...

* Picks a point on the circle `stopDistance` away from the `anchor` and moves toward that - whether that takes it inward or outward along the line joining `obj` and `anchor`.
* Moves the object at most a distance of `maxStep` per invocation.
* When the destination is closer than `maxStep`, it snaps the object directly to the `stopDistance` circle, with no under- or over-shooting.
* Uses no trigonometric functions. It also handles all angles correctly, unlike the sample code (hint: you probably want `atan2` when trying to find an angle from two coordinates).

You should also consider using a fixed timestep for your game simulation, so it's not subject to variation depending on the rendering framerate.

---
Tags: mathematics, movement
---


title: Game Maker Studio 2 - Pixel Distortion

text:
# Question
Title: Game Maker Studio 2 - Pixel Distortion
I am new to game development and am trying to learn how to use Game Maker to create pixel art games.

I've created a demo game with 16x16 pixels art style, the room size is 1024 x 768 and the viewpoint has 384x216 size.

When I've imported my own pixel demos (like a dog and ground tiles) everything looked ok, but when I've imported a tile set from Stardew Valley (also with 16x16 pixels) just to practice the proportions these new tiles started to distort every time the game is run. When I just preview it in a room editor - everything looks crisp and 16x16, but when the game is running my designs stay 16x16 and Startdew Valley designs switch to 8x8.

I would appreciate any help.

Here are the screenshots.

# Answer
> 0 votes
The reason your tileset appears low-res is it was resized because it didn't fit its assigned texture page size.

Texture pages are used to store sprites tightly and are actually the GameMaker-version of sprite atlases. In particular, texture *pages* are packed into texture *groups*, which are the actual atlases. Besides, you can define different groups for different target platforms.

Some platforms are only compatible with limited texture page sizes, usually a power of 2. The standard size is 2048x2048 and it works on most devices and OS.

Your Stardew Valley tileset is 400x1264, so it needs to be stored in a texture page of a minimum of 2048x2048 (unfortunately, 1264 is greater than 1024, so the next power of 2 is 1024\*2=2048).

However, if a sprite (or tileset, or background) is too big for the current texture page size, it needs to be "adapted" in order to be used by the engine. The standard behaviour is scaling.

**Texture groups** define what **sprites** are to be stored in **texture pages** for the current platform. Groups also define additional options for packing sprites, such as scaling, crop, and mipmapping. In the Texture Groups window, you can set these as you wish. Here, *Allow Scaling* is applied on a per-sprite basis whenever such a sprite is too big for the current texture page size. If you disable it, the sprite will be moved to a different page, but I'm not sure how it behaves for small-size page sizes.

Anyway, you can prevent resources from being downscaled by increasing the texture page size from the Graphics Tab in *Game Options \> Platform Settings \> \[Your platform\]*. If you want some resources to NOT be scaled under any circumstances, you can also untick the *Allow Scaling* option for those resources.

---
Tags: game-maker, pixel, pixel-art, game-maker-studio-2
---


# Question
Title: Why rotating backwards is too fast, even if I set the time to 3 seconds?
The rotation is very fast. It takes less than a second and for sure not 3 seconds.

Maybe it's better to do it without using a coroutine? Or something in the `IEnumerator` is wrong with the time and progress calculation?

```
public IEnumerator DoRotate(float time)
{
    var newRotation = Quaternion.AngleAxis(180, Vector3.up) * transform.rotation;

    var progress = 0f;

    while (progress < 1)
    {
        progress += Time.deltaTime / time;

        transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, progress);

        yield return new WaitForEndOfFrame();
    }
}

```

Usage :

```
private void FixedUpdate()
{
    if (rotateBackwards)
    {
        StartCoroutine(DoRotate(3f));
        rotateBackwards = false;
    }
}

```

# Answer
> 1 votes
You forgot to cache your starting rotation, and rotate each frame relative to that starting point, rather than where you already advanced to:

```
public IEnumerator DoRotate(float time)
{
    var startRotation = transform.rotation;

    var newRotation = Quaternion.AngleAxis(180, Vector3.up) * transform.rotation;

    var progress = 0f;

    while (progress < 1)
    {
        progress += Time.deltaTime / time;

        transform.rotation = Quaternion.Slerp(startRotation, newRotation, progress);

        yield return null;
    }

    transform.rotation = newRotation;
}

```

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


# Question
Title: Multiplayer game - Player position updates transmission pattern
I'm building a very basic 3D multiplayer game using Three.js and Socket.io where all the player does is move in an environment.

Considering there will be ~ 100 players in a single room and all data that is required to be transmitted is their positions. Which of the following two patterns should be used :

1. Immediately echoing the player's position to other players in the room when a socket event is received :

Server side :

```
        socket.on("move", (singlePlayerPos) => {
           socket.to(socket.room).emit("player update", singlePlayerPos);
        });

```

Client side: receiving the event and updating the players position stored in an array/map. Note : client currently emits the position update event on every frame.

2. Storing the positions on server side and transmitting them on a 'tick rate' basis say every 16 ms

```
        setInterval(function () {
            io.to(socket.room).emit("positions", allPlayersPositions);
        }, 16);

```

I'm currently using approach #1 and have concerns whether it'll lead to too many messages for client to handle as the position event is emitted during every requestAnimationFrames() cycle.

The issue I have with approach #2 is that my servers are horizontally scaled and using L4 load balancing (there's no sticky session). The sockets are scaled using Redis adapter (pub/sub) so I can't really store player's positions in memory (RAM) as player belonging to a single room can join different servers. If I'll have to store all positions they'll have to be stored in Redis which i'm concerned would impact performance (latency). Additionally the client is pretty light weight on the "game logic" part but have many other traditional web elements (such as modals, buttons etc.) on the business logic part ... so don't really intend to introduce complexity such as interpolations and predictions (its okay if some players lag/skip at full load).

I'm a beginner when it comes to game development and would appreciate any suggestions and/or criticism.

# Answer
> 0 votes
You probably already do this but, in case you don't, one modification that I suggest for both cases is to place a threshold on the position changes so that you are not constantly streaming them (every frame).

---
Tags: javascript, multiplayer, three.js
---


title: LWJGL With Modern OpenGL

text:
# Question
Title: LWJGL With Modern OpenGL
I have a question. I am following ThinMatrix's tutorial on YouTube which is about making a 3d game with lwjgl. He uses OpenGL v3.0 and higher. However, my built-in graphic card supports only OpenGL version 2.1.

Here is the question: why can I use `GL30.glGenVertexArrays()` but can not use `GL30.glGenerateMipmap()`?

When I use Mesa, print `GL11.glGetString(GL11.GL_VERSION)` it still shows 2.1 but I don't get any errors when I try to use `GL30.glGenerateMipmap`.

# Answer
Your graphics card driver implements the GL\_ARB\_vertex\_array\_object extension.

Couple of things to note.

First, there is no -ARB suffix on new entry points or tokens with this extension. The reason why is explained at issue #6 of the extension spec, linked above.

Second, this extension exists for the explicit purpose of providing a subset of OpenGL 3.0 functionality on hardware and drivers that can't implement the full OpenGL 3.0 specification. It shouldn't be surprising to find an OpenGL 2.1 implementation that supports it (it's probably more surprising to find OpenGL 2.1 hardware still in use and still working).

In a C/C++ program, attempting to use a GL call that doesn't exist in your driver will crash your program, due to it attempting to access a NULL pointer. I don't know LWJGL so I can't explain why trying to use glGenerateMipmap doesn't throw some kind of error; most likely it does but you're not looking in the right place.
> 0 votes

# Answer
Posting an objective answer to this is probably impossible. Most likely your GL driver might have some forward-compatibility, meaning that even though it's on version 2.1 it supports a few select things from later versions to speed up rendering. Most likely stuff that doesn't really add functionality, but that simplifies existing implementations, so for example (the following are not real functions) if previously you had to use `glSetVertexArrayIndex(int index, float data)` like so

```
glSetVertexArrayIndex(0, data_index0);
glSetVertexArrayIndex(1, data_index1);

```

but in new GL versions (let's pretend 3.0) they added a function `glSetVertexArrayIndexes(int[] indexes, float[] data)` that you could now use like so:

```
glSetVertexArrayIndexes([0, 1], [data_index0, data_index1]);

```

That means your GL driver might secretly implement support for the new `glSetVertexArrayIndexes(int[], float[])` behind the scenes, since if it recognizes multiple calls of the old `glSetVertexArrayIndex` in a row it can just translate it to a single call of `glSetVertexArrayIndexes` and save some processing time.

But like I said, this is just a pure guess.
> 1 votes

---
Tags: opengl, lwjgl
---


title: Why does the player rotate nonstop?

text:
# Question
Title: Why does the player rotate nonstop?
```
private void Update()
{
  targetAngles = transform.eulerAngles + 180f * Vector3.up;
  transform.eulerAngles = Vector3.Lerp(transform.eulerAngles, targetAngles, 3f * Time.deltaTime);
}

```

I guess because it's rotating by 180 degrees all the time.

How can I make the player rotate by 180 degrees only once, without using a coroutine?

Before that, I used in the Update with a coroutine and a flag to start the coroutine only once and it did rotate fine, but with stuttering. I guess the coroutine didn't sync good enough with the player movement.

While the player is rotating I also make the player start moving.

This is the coroutine I used before but then when the player starts moving and rotating he was stuttering.

```
public IEnumerator DoRotate(float time)
    {
        var startRotation = transform.rotation;
        var newRotation = Quaternion.AngleAxis(180, Vector3.up) * transform.rotation;
        var progress = 0f;

        while (progress < 1)
        {
            progress += Time.deltaTime / time;
            transform.rotation = Quaternion.Slerp(startRotation, newRotation, progress);

            yield return null;
        }

        transform.rotation = newRotation;
    }

```

This is the full script the rotating part is at lines 56-57.

At the bottom is the coroutine I used to make the rotation, but because of the stuttering I want to try to do it without coroutine to see if it will fix the stuttering problem.

```
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using UnityStandardAssets.Characters.ThirdPerson;
using Cinemachine;

public class DistanceCheck : MonoBehaviour
{
    public Transform objectToRotatetowards;
    public float slowDownLerpDuration;
    public float speedUpLerpDuration;
    public float rotationSpeed;
    public GameObject descriptionTextImage;
    public TextMeshProUGUI text;
    public ThirdPersonUserControl thirdPersonUserControl;

    private Animator anim;
    private float timeElapsed = 0;
    private float startValue = 1;
    private float endValue = 0;
    private float valueToLerp = 0;
    private bool startRotating = false;
    private bool slowOnBack = true;
    private bool exited = false;
    private Vector3 exitPosition;
    private float distance;
    private bool rotateTowards = false;
    private bool rotateBackwards = false;
    private bool rotateTowardsObject = false;
    private Vector3 targetAngles;

    void Start()
    {
        anim = transform.GetComponent<Animator>();
    }

    private void FixedUpdate()
    {
        if (startRotating)
        {
            if (rotateTowards)
            {
                if (rotateTowardsObject)
                {
                    Vector3 targetDirection = objectToRotatetowards.position - transform.position;
                    float singleStep = 3f * Time.deltaTime;
                    Vector3 newDirection = Vector3.RotateTowards(transform.forward, targetDirection, singleStep, 0.0f);
                    transform.rotation = Quaternion.LookRotation(newDirection);
                }

                if (rotateBackwards)
                {
                    targetAngles = transform.eulerAngles + 180f * Vector3.up;
                    transform.eulerAngles = Vector3.Lerp(transform.eulerAngles, targetAngles, 3f * Time.deltaTime);
                    //StartCoroutine(DoRotate(2f));
                    //rotateBackwards = false;
                }
            }
        }

        if (exitPosition != new Vector3(0, 0, 0) && slowOnBack)
        {
            distance = Vector3.Distance(transform.position, exitPosition);
        }

        if (distance > 5 && slowOnBack)
        {
            slowOnBack = false;
            StartCoroutine(SlowDown());
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.tag == "NoExit")
        {
            rotateTowardsObject = true;
            rotateBackwards = false;
            descriptionTextImage.SetActive(true);
            if (other.TryGetComponent(out ColliderInfo info))
            {
                text.text = info.onExitText;
                rotateTowards = info.rotateTowards;
            }
            RepositionPlayer();
        }
        else if (other.tag == "NoEntry")
        {
            OnPlayerRepositioned();
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.tag == "NoExit")
        {
            OnPlayerRepositioned();
        }
        else if (other.tag == "NoEntry")
        {
            rotateTowardsObject = false;
            rotateBackwards = true;
            descriptionTextImage.SetActive(true);
            if (other.TryGetComponent(out ColliderInfo info))
            {
                text.text = info.onEnterText;
                rotateTowards = info.rotateTowards;
            }
            RepositionPlayer();
        }
    }

    private void RepositionPlayer()
    {
        exited = true;
        slowOnBack = true;
        exitPosition = transform.position;
        thirdPersonUserControl.enabled = false;
        StartCoroutine(SlowDown());
    }

    private void OnPlayerRepositioned()
    {
        exited = false;
        startRotating = false;
        text.text = "";
        descriptionTextImage.SetActive(false);
    }

    IEnumerator SlowDown()
    {
        timeElapsed = 0;

        while (timeElapsed < slowDownLerpDuration)
        {
            valueToLerp = Mathf.Lerp(startValue, endValue, timeElapsed / slowDownLerpDuration);
            anim.SetFloat("Forward", valueToLerp);
            timeElapsed += Time.deltaTime;

            yield return null;
        }

        if (exited)
        {
            yield return new WaitForSeconds(1.5f);

            startRotating = true;
            StartCoroutine(SpeedUp());
        }

        if (slowOnBack == false)
        {
            thirdPersonUserControl.enabled = true;
        }
    }

    IEnumerator SpeedUp()
    {
        timeElapsed = 0;

        while (timeElapsed < speedUpLerpDuration)
        {
            valueToLerp = Mathf.Lerp(endValue, startValue, timeElapsed / speedUpLerpDuration);
            anim.SetFloat("Forward", valueToLerp);
            timeElapsed += Time.deltaTime;

            yield return null;
        }
    }

    public IEnumerator DoRotate(float time)
    {
        var startRotation = transform.rotation;
        var newRotation = Quaternion.AngleAxis(180, Vector3.up) * transform.rotation;
        var progress = 0f;

        while (progress < 1)
        {
            progress += Time.deltaTime / time;
            transform.rotation = Quaternion.Slerp(startRotation, newRotation, progress);

            yield return null;
        }

        transform.rotation = newRotation;
    }
}

```

# Answer
My usual solution to this problem is:

1. Introduce a new variable `Quaternion desiredRotation` which represents the direction where the object *should* look but might or might not be looking right now because it's still in the progress of turning around.
2. When I give the object the command to turn, I set the `desiredRotation` to where it is supposed to look, not its actual rotation. (You seem to have a variable `targetAngle` which seems to do the same thing, but you are setting its value in `Update`. So you are changing the value again and again, which is probably not what you want. I would usually do that once in response to `Input.GetKeyDown` or whatever other situation triggers the rotation).
3. In `FixedUpdate` I use `Quaternion.RotateTowards`. This methods returns a quaternion which represents a rotation from `from` into the direction of `to`, but limited to an angular change of `maxDegreeDelta`. So you can use it for things like this:

```
transform.rotation = Quaternion.RotateTowards(transform.rotation, desiredRotation, turnSpeed * Time.deltaTime);

```
> 1 votes

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


# Question
Title: Set SpriteRenderer tile to extend from a different side
I have a SpriteRenderer that should represent a never-ending tile floor. The idea is that we have a factory floor in an idle game that can grow forever.

I got two components:

1. Top part consisting of a wall, and a floor part that remains fixed and should connect to the endless floor.
2. An endless floor that should tile from the bottom and only downwards.

Roughly where the brighter floor patch begins, this is where the endless floor starts, the problem is that when I set the Sprite to "Tiled" & "Continuos" the tiling actually extends at the top instead of at the bottom and causes this visual annoyance where some of the tiles look cut-off:

I set the Sprite's pivot to be Top-Center, when it was the default center it was even worse as the tiling would go both ways.

Any idea how to resolve this so the top part of the endless floor remains fixed and only the bottom part is being extended & tiled?

Thanks!

# Answer
> 2 votes
In an image editor, mirror your tiling texture vertically.

In your scene, select your tiling floor sprite and negate its y scale.

These two flips together cancel out, so the displayed pattern is the same as you had before. But now the "top" of the sprite according to Unity is the bottom, and vice versa, so the direction in which the tiling extends has been reversed as desired.

---
Tags: unity
---