# Question
Title: How to check whether the user completed their missions?
I am working on a coding/gaming application. I am currently stuck in the **daily missions** part.

So, the user receives some missions each day, such as solving a problem, following another user, or completing a quiz that, they have to complete.

The problem is, I didn't know how to listen for mission completion? How will I know **whether the user completed their missions or not**?

Here's a solution I thought of, however, I highly doubt that it is good:

Every time the user completes a certain task, I check whether they had that task as a daily mission. If positive, I'll mark that mission as complete.

Something like:

```
onProblemSolve(){
   const missions = this.currentUser.getMissions();
   if(missions.contains('problemSolving')) {
       this.markMissionAsComplete();
   }
}

```

# Answer
> 0 votes
Instead of checking if a puzzle is part of a daily quest, you could fire an event once the puzzle is done. Your daily quests can listen to this event and if there is a quest that involves solving a puzzle, you mark it done. This has a few benefits. You can have an achievement system next to your daily quests and do not need to do much more code changes. If you have the logic on the puzzles side (as your snippet), you would have the same code again to mark an achievement. But if your achievement system just listens on puzzle done, nothing needs to change on the puzzle part. Why would your puzzle even care, if it is needed for a daily quest or achievement?

As a fallback, you should not only count on the event but involve your database as well. That does not mean that every event should write itself to it. Things like puzzle done would probably not only write "Level xy done" but when exactly with some extra stats like how many tries, time, hints, points and whatever your game offers. When you start your game, you can do a query for things like "has x puzzle done today". You do not want to call your database with this the whole time for performance reasons, but once at startup could be fine (or when loading your quest menu).

As DMGregory pointed out, the Observer Pattern is your friend. There is always more than one way how you can do something but for most things, someone did it already and there is a pattern for it.

---
Tags: javascript, events, node.js, achievements
---


# Question
Title: How can I stop the Unity Video Player on WebGL from starting each video with a frame of all black?
# Description

I'm working on a system to seamlessly reconstruct and play numerous segments of a continuous video stream by playing one segment on the active Video Player while loading the next on the hidden, waiting Video Player—and swapping between them when the active segment is done playing.

Although it's not necessary to see the code for this, I included it below just in case:

```
public class VideoController : MonoBehaviour
{
    [SerializeField] private VideoPlayer activePlayer;
    [SerializeField] private VideoPlayer waitingPlayer;
    // The waiting player starts off invisible.

    private Queue<string> _segmentUrls;
    private bool _videoIsPlaying;

    private bool NextSegmentExists => _segmentUrls.Count >= 1;

    private void Awake()
    {
        // Initialize fields.
        _segmentUrls = new Queue<string>();

        // Subscribe to events.
        // VideoPlayer.Prepare() doesn't seem to work in WebGL. The workaround is to call
        // Play() instead and set the players to pause once the track is finished preparing.
        activePlayer.prepareCompleted += source =>
        {
            source.Pause();
        };
        waitingPlayer.prepareCompleted += source =>
        {
            source.Pause();
        };

        activePlayer.loopPointReached += SwitchVideoPlayer;
        waitingPlayer.loopPointReached += SwitchVideoPlayer;
    }

    public void EnqueueSegment(string segmentUrl)
    {
        _segmentUrls.Enqueue(segmentUrl);

        if (!_videoIsPlaying)
            StartCoroutine(StartPlayback());
        else if (!waitingPlayer.isPrepared)
            PrepareNextSegmentOnWaitingPlayer();
    }

    private IEnumerator StartPlayback()
    {
        PrepareNextSegmentOnWaitingPlayer();

        // Give the Video Player a second to finish preparing the segment for playback.
        yield return new WaitForSeconds(1f);

        SwitchVideoPlayer(lastPlayer: activePlayer);
        _videoIsPlaying = true;
    }

    private void PrepareNextSegmentOnWaitingPlayer()
    {
        var segmentUrl = _segmentUrls.Dequeue();
        waitingPlayer.url = segmentUrl;
        waitingPlayer.Play();
    }

    private void SwitchVideoPlayer(VideoPlayer lastPlayer)
    {
        activePlayer = waitingPlayer;
        TransparencyController.ShowGameObject(activePlayer.gameObject);

        waitingPlayer = lastPlayer;
        TransparencyController.HideGameObject(waitingPlayer.gameObject);
        waitingPlayer.Stop();

        if (activePlayer.isPrepared)
            activePlayer.Play();
        else
        {
            activePlayer.Stop();
            _videoIsPlaying = false;
            return;
        }

        if (NextSegmentExists)
            PrepareNextSegmentOnWaitingPlayer();
    }
}

```

# Problem

When a Video Player begins playing, the first frame or two is just a black screen. As a result, when a segment finishes playing and it's time to swap the active and waiting players, there's a momentary black "blink" on the screen.

## Demonstration

Below is a GIF of the issue:

Each blink corresponds to swapping Video Players.

(Not to be confused, the video player is showing a recording of a Unity project.)

# Attempted Fix #1

When a Video Player is done preparing the new segment for playback, I have it advance two frames, so it picks off right where the old segment ended and transitions perfectly smoothly.

This is done by changing the callback for `VideoPlayer.prepareCompleted` as follows:

```
activePlayer.prepareCompleted += source =>
{
    source.StepForward();
    source.StepForward();
    source.Pause();
};
waitingPlayer.prepareCompleted += source =>
{
    source.StepForward();
    source.StepForward();
    source.Pause();
};
// Experimentation found that two calls to StepForward() are necessary.

```

## Why It Doesn't Work

It works on Windows, but testing it on the WebGL build—my primary build target—throws an exception telling me `VideoPlayer.StepForward()` is not supported on WebGL.

# Attempted Fix #2

I tried the equivalent of calling `StepForward()` by setting the current time of the Video Player to a value equal to `2 / framerate`, where the "2" stands for two frames.

## Why It Doesn't Work

It works on Windows, and it seems adjusting the time value works on WebGL, too—at least for values equal to or less than 0.5 seconds. However, on WebGL, the black blink persists despite the time-skip.

# Attempted Fix #3

I tried the same approach as in #2, but by directly adjusting the current frame of the Video Player when preparing the segment for the waiting player.

## Why It Doesn't Work

For the same exact reason as in #2.

# Question

Why does the Video Player start off with black frames on WebGL no matter what, and how can I avoid that?

# Answer
> 1 votes
I settled on the following solution: **start playback on the waiting player a few frames before the active player finishes its segment.**

Since I still don't understand what's causing the black screen on Video Players, I gave up trying to fix it and decided to work around it. Every frame, I check to see if the active player is near the end, and if so, start the waiting player—while it's still hidden.

```
private void Update()
{
    // The below code starts the playback of the waiting player early; when the active player is almost finished with its segment.
    // This gives the waiting player time to "play out" the first few "black" frames it starts out with and get to the actual video.
    // The waiting player will become visible (and active) when the current, active player completely finishes playing.
    if (activePlayer.isPlaying && waitingPlayer.isPrepared)
    {
        var frameCount = 2;

        #if UNITY_EDITOR
        frameCount = 3;
        #endif

        var framesInSeconds = frameCount / activePlayer.frameRate;
        var currentSegmentIsEnding = activePlayer.time >= activePlayer.length - framesInSeconds;

        if (currentSegmentIsEnding)
            waitingPlayer.Play();
    }
}

```

It's still not perfect. I can't precisely determine how many (video) frames the black screen will last, and therefore, there's a slight freeze/stutter when the Video Players switch. As you can see from the code, I start the waiting player 3 frames before the active's end in the Unity Editor, where I use 60 FPS clips, and 2 frames in my WebGL build, where it's 24 FPS. I'm not even sure I should calculate the advance time by (video) frames—it seems to vary each swap.

Until then, I'm eyeballing it. I'm going to test this on several devices to narrow down a satisfactory number, but if anyone knows a better way—or the cause for the black frames—please, chime in.

---

The full, unedited code can be viewed here:

```
public class VideoController : MonoBehaviour
{
    [SerializeField] private VideoPlayer activePlayer;
    [SerializeField] private VideoPlayer waitingPlayer;

    private Queue<string> _segmentUrls;
    private bool _videoIsPlaying, _waitingPlayerIsCurrentlyPreparing;

    private bool NextSegmentExists => _segmentUrls.Count >= 1;

    private void Awake()
    {
        // Initialize fields.
        _segmentUrls = new Queue<string>();

        // Hard-configure required settings.
        activePlayer.source = VideoSource.Url;
        waitingPlayer.source = VideoSource.Url;
        activePlayer.isLooping = false;
        waitingPlayer.isLooping = false;

        // Subscribe to events.
        activePlayer.prepareCompleted += source => source.Pause();
        waitingPlayer.prepareCompleted += source => source.Pause();
        activePlayer.loopPointReached += source => StartCoroutine(OnSegmentEnd());
        waitingPlayer.loopPointReached += source => StartCoroutine(OnSegmentEnd());
    }

    private void Start()
    {
        #if UNITY_EDITOR
        StartCoroutine(EnqueueSegmentsForTesting(3));
        #endif
    }

    private void Update()
    {
        // The below code starts the playback of the waiting player early; when the active player is almost finished with its segment.
        // This gives the waiting player time to "play out" the first few "black" frames it starts out with and get to the actual video.
        // The waiting player will become visible (and active) when the current, active player completely finishes playing.
        if (activePlayer.isPlaying && waitingPlayer.isPrepared)
        {
            var frameCount = 2;

            #if UNITY_EDITOR
            frameCount = 3;
            #endif

            var framesInSeconds = frameCount / activePlayer.frameRate;
            var currentSegmentIsEnding = activePlayer.time >= activePlayer.length - framesInSeconds;

            if (currentSegmentIsEnding)
                waitingPlayer.Play();
        }
    }

    private IEnumerator EnqueueSegmentsForTesting(int segmentCount)
    {
        for (int i = 0; i < segmentCount; i++)
        {
            EnqueueSegment($"file://D:/Projects/ffmpeg-wasm-test/Assets/Videos/{i}.mp4");
            yield return new WaitForSeconds(2.5f);
        }
    }

    public void EnqueueSegment(string segmentUrl)
    {
        _segmentUrls.Enqueue(segmentUrl);

        if (!_videoIsPlaying)
            StartCoroutine(StartPlayback());
        else if (!waitingPlayer.isPrepared && !_waitingPlayerIsCurrentlyPreparing)
            StartCoroutine(PrepareWaitingPlayer());
    }

    private IEnumerator StartPlayback()
    {
        // Check the _videoIsPlaying flag at the very beginning to prevent StartPlayback() from being
        // started multiple times when EnqueueSegment() is called in rapid succession.
        _videoIsPlaying = true;
        PrepareNextSegmentOnVideoPlayer(activePlayer);

        while (!activePlayer.isPrepared)
            yield return null;

        activePlayer.Play();
    }

    private IEnumerator PrepareWaitingPlayer()
    {
        _waitingPlayerIsCurrentlyPreparing = true;
        PrepareNextSegmentOnVideoPlayer(waitingPlayer);

        while (!waitingPlayer.isPrepared)
            yield return null;

        _waitingPlayerIsCurrentlyPreparing = false;
    }

    private void PrepareNextSegmentOnVideoPlayer(VideoPlayer videoPlayer)
    {
        var nextSegmentUrl = _segmentUrls.Dequeue();
        videoPlayer.url = nextSegmentUrl;

        // VideoPlayer.Prepare() doesn't seem to work in WebGL. The workaround is to call
        // Play() instead and set the players to pause once the track is finished preparing.
        // (The pausing happens in a callback to the VideoPlayer.prepareCompleted event.)
        videoPlayer.Play();
    }

    private IEnumerator OnSegmentEnd()
    {
        activePlayer.Stop();

        // If the waiting player isn't already loaded with the next segment...
        if (!waitingPlayer.isPrepared && !_waitingPlayerIsCurrentlyPreparing)
        {
            // ...then the end of the segment buffer has been reached.
            waitingPlayer.Stop();
            _videoIsPlaying = false;
            yield break;
        }

        // The exception is when it's currently preparing.
        if (_waitingPlayerIsCurrentlyPreparing)
        {
            // In that case, wait for it to finish, play it, and continue as normal.
            while (!waitingPlayer.isPrepared)
                yield return null;

            waitingPlayer.Play();
        }

        // Otherwise, assume the waiting player has already begun playback.
        SwapVideoPlayers();

        if (NextSegmentExists)
            PrepareNextSegmentOnVideoPlayer(waitingPlayer);
    }

    private void SwapVideoPlayers()
    {
        var lastPlayer = activePlayer;
        activePlayer = waitingPlayer;
        waitingPlayer = lastPlayer;

        TransparencyController.ShowGameObject(activePlayer.gameObject);
        TransparencyController.HideGameObject(waitingPlayer.gameObject);
    }
}

```

---
Tags: unity, webgl, video, unity-webgl
---


# Question
Title: Objects lose their individual positions and rotations when imported from FBX using Assimp
I am a newbie trying to learn DX11.

I successfully put my obj model into the program by using assimp.

Unfortunately, I cannot load the same model in fbx format correctly (both of them were exported from my 3DS Max 2014).

OBJ:

FBX:

It seems like that all the meshes in the file have been moved to (0, 0, 0) instead of their correct offset positions, and the rotations of these objects are also incorrect.

Here is the code I use:

```
bool Model::LoadModel(const std::string& filePath)
{
    Assimp::Importer importer;

    const aiScene* pScene = importer.ReadFile(filePath, aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_ConvertToLeftHanded);
    //aiProcess_CalcTangentSpace | aiProcess_JoinIdenticalVertices |iProcess_SortByPType | aiProcess_Triangulate | aiProcess_ConvertToLeftHanded);
    if (pScene == nullptr)
        return false;

    ProcessNode(pScene->mRootNode, pScene);
    return true;
}

void Model::ProcessNode(aiNode* node, const aiScene* scene)
{
    for (UINT i = 0; i < node->mNumMeshes; i++) {
        aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
        meshes.push_back(this->ProcessMesh(mesh, scene));
    }
    for (UINT i = 0; i < node->mNumChildren; i++) {
        ProcessNode(node->mChildren[i], scene);
    }
}

Mesh Model::ProcessMesh(aiMesh* mesh, const aiScene* scene)
{
    //Data to fill
    std::vector<Vertex>vertices;
    std::vector<DWORD>indices;

    for (UINT i = 0; i < mesh->mNumVertices; i++) {
        Vertex vertex;
        vertex.pos.x = mesh->mVertices[i].x;
        vertex.pos.y = mesh->mVertices[i].y;
        vertex.pos.z = mesh->mVertices[i].z;

        if (mesh->mTextureCoords[0]) {
            vertex.texCoord.x = (float)mesh->mTextureCoords[0][i].x;
            vertex.texCoord.y = (float)mesh->mTextureCoords[0][i].y;
        }
        vertices.push_back(vertex);
    }

    for (UINT i = 0; i < mesh->mNumFaces; i++) {
        aiFace face = mesh->mFaces[i];

        for (UINT j = 0; j < face.mNumIndices; j++)
            indices.push_back(face.mIndices[j]);
    }

    return Mesh(device, deviceContext, vertices, indices);
}

```

# Answer
Thank DMGregory for the magic of aiProcess\_PreTransformVertices!!!!!!!

```
bool Model::LoadModel(const std::string& filePath)
{
    Assimp::Importer importer;

    const aiScene* pScene = importer.ReadFile(filePath, aiProcess_Triangulate | aiProcess_JoinIdenticalVertices |
        aiProcess_ConvertToLeftHanded | aiProcess_PreTransformVertices);

    if (pScene == nullptr)
        return false;

    ProcessNode(pScene->mRootNode, pScene);
    return true;
}

void Model::ProcessNode(aiNode* node, const aiScene* scene)
{
    for (UINT i = 0; i < node->mNumMeshes; i++) {
        aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
        meshes.push_back(this->ProcessMesh(mesh, scene));
    }
    for (UINT i = 0; i < node->mNumChildren; i++) {
        ProcessNode(node->mChildren[i], scene);
    }
}

Mesh Model::ProcessMesh(aiMesh* mesh, const aiScene* scene)
{
    //Data to fill
    std::vector<Vertex>vertices;
    std::vector<DWORD>indices;

    for (UINT i = 0; i < mesh->mNumVertices; i++) {
        Vertex vertex;
        vertex.pos.x = mesh->mVertices[i].x / 2;
        vertex.pos.y = mesh->mVertices[i].y / 2;
        vertex.pos.z = mesh->mVertices[i].z / 2;//  ÷2 to make model smaller

        if (mesh->mTextureCoords[0]) {
            vertex.texCoord.x = (float)mesh->mTextureCoords[0][i].x;
            vertex.texCoord.y = (float)mesh->mTextureCoords[0][i].y;
        }
        vertices.push_back(vertex);
    }

    for (UINT i = 0; i < mesh->mNumFaces; i++) {
        aiFace face = mesh->mFaces[i];

        for (UINT j = 0; j < face.mNumIndices; j++)
            indices.push_back(face.mIndices[j]);
    }

    return Mesh(device, deviceContext, vertices, indices);

}

```
> 1 votes

---
Tags: c++, fbx, assimp, asset-workflow
---


title: Unity equivalent of GKAgent

text:
# Question
Title: Unity equivalent of GKAgent
Does Unity have an equivalent to GKAgent in Apples GamePlayKit to define agents, goals and behaviours out of the box?

Would this be the unity AI system? Or more likely a 3rd party aaset?

Thanks

# Answer
> 0 votes
Unity doesn't have a built-in goal-oriented AI agent. You need to write your own or get a third-party library.

**Edit:** I looked it up a little bit more and it seems GKAgent is not about GOAP, but it is about steering behaviours. The answer still holds though, Unity does not have built-in support for steering behaviours. However, there are many drop-in libraries that you can use for this purpose. A quick search with the keywords "Unity steering behaviours" should give you plenty of resources. Here is one that I found: https://github.com/ricardojmendez/UnitySteer

---
Tags: unity
---


# Question
Title: Two players using touch control simultaneously
I am working on a game like soccer star and I made a controller using YouTube and stuff. I added two players in the same scene and put this script on them. But when I play with player 1, then player 2 does the same as they are controlled by the same touch. How can I make them work simultaneously?

The Upper half belongs to player 1 and the lower half belongs to player 2 and they are touching the same screen.

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

public class Ball : MonoBehaviour
{
    public float Power = 10f;
    public float maxDrag = 5f;
    Rigidbody2D rb;
    LineRenderer lr;

    Vector3 dragStartPos;
    Touch touch2;

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        lr = GetComponent<LineRenderer>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.touchCount > 0)
        {
            touch2 = Input.GetTouch(0);

            if (touch2.phase == TouchPhase.Began)
            {
                dragStart();
            }
            if (touch2.phase == TouchPhase.Moved)
            {
                dragging();
            }
            if (touch2.phase == TouchPhase.Ended)
            {
                dragRelease();
            }
        }
    }

    void dragStart()
    {
        dragStartPos = Camera.main.ScreenToWorldPoint(touch2.position);
        dragStartPos.z = 0f;

        lr.positionCount = 1;
        lr.SetPosition(0, transform.position);
    }

    void dragging()
    {
        Vector3 draggingPos = Camera.main.ScreenToWorldPoint(touch2.position);
        draggingPos.z = 0f;
        lr.positionCount = 2;
        lr.SetPosition(0, draggingPos);
    }

    void dragRelease()
    {
        lr.positionCount = 0;
        Vector3 dragReleasePos = Camera.main.ScreenToWorldPoint(touch2.position);
        dragReleasePos.z = 0f;
        Vector3 force = dragStartPos - dragReleasePos;
        Vector3 clampedForce = Vector3.ClampMagnitude(force, maxDrag) * Power;
        rb.AddForce(clampedForce, ForceMode2D.Impulse);
    }
}

```

# Answer
The fix is reasonably straightforward. Instead of responding to absolutely any touch on the screen, you need to introduce a variable to track which touch is "my currently active touch".

You can then be choosy about which touches meet the criteria to be claimed this way, and then respond only to movement / release of your claimed touch - the one that matches the variable.

```
// Set this to true for your top-half player, and false for the bottom-half player.
public bool topHalfIsMine;

public float Power = 10f;
public float maxDrag = 5f;

Rigidbody2D rb;
LineRenderer lr;
Vector2 dragStartPos;

int activeTouchId = -1;

void Start() {
    rb = GetComponent<Rigidbody2D>();
    lr = GetComponent<LineRenderer>();
}

void Update() {
    if (activeTouchId < 0) {
        TryStartTouch();
    } else {
        TrackTouch();
    }
}

void TryStartTouch() {
    for (int i = 0; i < Input.touchCount; i++) {
         var touch = Input.GetTouch(i);

         // Skip touches that are not new.
         if (touch.phase != TouchPhase.Began) continue;

         // Check which half of the screen the touch started on.
         bool onBottomHalf = touch.position.y < (Screen.height / 2);

         // Can I claim this touch as being in my half of the screen?
         bool mine = onBottomHalf ^ topHalfIsMine;

         // If not, skip it.
         if (!mine) continue;

         // Otherwise, this is my touch. Record its information.
         activeTouchId = touch.fingerId;
         dragStartPos = Camera.main.ScreenToWorldPoint(touch.position);

         // And configure the line.
         lr.positionCount = 1;
         lr.SetPosition(0, transform.position);

         break;
    }
}

void TrackTouch() {
    for (int i = 0; i < Input.touchCount; i++) {
        // Iterate through the touches till we find the one we claimed.
        var touch = Input.GetTouch(i);
        if (touch.fingerId != activeTouchId) continue;

        // Process the touch depending on its phase.
        switch (touch.phase) {
            case TouchPhase.Moved:

                // Update our line when it moves.
                Vector2 draggingPos = Camera.main.ScreenToWorldPoint(touch.position);

                lr.positionCount = 2;
                // Are you sure you don't want to be setting position 1 here?
                lr.SetPosition(0, draggingPos);

                break;

            case TouchPhase.Ended:
            case TouchPhase.Canceled:

                // Clear our active touch when it ends.
                activeTouchId = -1;

                lr.positionCount = 0;
                Vector2 dragReleasePos = Camera.main.ScreenToWorldPoint(touch.position);

                Vector2 force = dragStartPos - dragReleasePos;
                Vector2 clampedForce = Vector2.ClampMagnitude(force, maxDrag) * Power;
                rb.AddForce(clampedForce, ForceMode2D.Impulse);

                break;
        }
        return;
    }
}

```
> 0 votes

---
Tags: unity, 2d, multitouch
---


# Question
Title: How can I make the objToRotate speed to rotate depending on the target moving speed?
The player has these components: Animator, Rigidbody, Capsule Collider, Third Person Character (Script), Third Person User Control (Script), and the MyLookAT script.

The problem is if I drag the cube target too fast in the editor changing its position it will take some time for the objToRotate to rotate facing the target again. I want somehow to make that the objToRotate will know to set his own speed and to rotate fast/slow enough to face the target when moving the target.

I want the objToRotate to face the target in real-time when the target is moving not with delay.

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

public class RotatingTest : MonoBehaviour
{
    public Transform target;
    public Transform objToRotate;
    public float speed = 1.0f;

    void LateUpdate()
    {
        Vector3 targetDirection = target.position - objToRotate.position;
        float singleStep = speed * Time.deltaTime;

        Vector3 newDirection = Vector3.RotateTowards(objToRotate.forward, targetDirection, singleStep, 0.0f);

        Debug.DrawRay(objToRotate.position, newDirection, Color.red);

        objToRotate.rotation = Quaternion.LookRotation(newDirection);
    }
}

```

# Answer
> -1 votes
```
using UnityEngine;
using System;
using System.Collections;

[RequireComponent(typeof(Animator))]
public class MyLookAt : MonoBehaviour
{
    public Transform target;
    public Transform objToRotate;

    void LateUpdate()
    {
        Vector3 relativePos = target.position - objToRotate.position;
        Quaternion rotation = Quaternion.LookRotation(relativePos, Vector3.up);
        objToRotate.rotation = rotation;
    }
}

```

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


# Question
Title: How do I make animation positions relative?
I have a "reload gun animation".

Currently, this animation makes the character move from its current position to position (0, 0, 0). This doesn't make sense.

What you could I check to make sure that the positions are relative instead of absolute?

# Answer
> 1 votes
The animations (unless blended or so) are ALWAYS absolute!

The problem that I was confronted with was the fact that the animation contained position (and rotation) for the root node (=game object itself):

Once I removed them, it behaved as expected.

---
Tags: unity, animation
---


# Question
Title: How to desaturate and blur the game world when paused in Unreal Engine 4
I am creating the pause menu for my game. I want the screen to turn black and white and blurry when it is paused, much like Left4Dead. But the only special effect I can find is background blur. How can I do this?

I'm using Blueprints in Unreal Engine 4.26

# Answer
> 1 votes
The simplest way would be to apply post process settings to the camera and lower the saturation.  To enable the saturation pin, click on the make node and enable it in the details panel.

Alternatively, instead of applying it to the camera, you could add a post-process component and apply the effects there.

---
Tags: unreal-4, unreal, graphic-effects, blueprints, post-processing
---


title: How do I bitmask these tiles?

text:
# Question
Title: How do I bitmask these tiles?
Using Godot. I can't figure out how to bitmask these tiles in order to autotile them. I've examined the templates shown in the Godot Docs Tilemaps tutorial, but none seem appropriate. My own attempts to solve this through trial and error have left me confused and frustrated. The tiles are 32x32 pixels, and I'm fairly sure I need a 3x3 minimal masking layout.
My most recent attempt is almost workable:

# Answer
Your tileset is not ideal to use for autotiling, as many common pieces are missing, for example the L shape. I modified the tileset and used 160x160 wide tiles, this is the result:

The blue checkerboard means that the cell is ignored, so it could be either filled or empty.
> 5 votes

---
Tags: tilemap, godot, tile-bitmasking
---


title: Can't open UE5 project on Windows

text:
# Question
Title: Can't open UE5 project on Windows
I created a UE5 project on macOS and I'm now trying to open it on a Windows 10 machine.

I made sure not to copy the Saved, Binaries, DerivedDataCache and Intermediate folders, but when I try to open it I get the following errors at build time:

```
Log file open, 07/12/21 08:01:13
LogWindows: Failed to load 'aqProf.dll' (GetLastError=126)
LogWindows: File 'aqProf.dll' does not exist
LogProfilingDebugging: Loading WinPixEventRuntime.dll for PIX profiling (from ../../../Engine/Binaries/ThirdParty/Windows/WinPixEventRuntime/x64).
LogWindows: Failed to load 'VtuneApi.dll' (GetLastError=126)
LogWindows: File 'VtuneApi.dll' does not exist
LogWindows: Failed to load 'VtuneApi32e.dll' (GetLastError=126)
LogWindows: File 'VtuneApi32e.dll' does not exist
LogConsoleResponse: Display: Failed to find resolution value strings in scalability ini. Falling back to default.
LogConsoleResponse: Display: Failed to find resolution value strings in scalability ini. Falling back to default.
LogInit: Display: Running engine for game: MyProject2
LogPlatformFile: Not using cached read wrapper
LogStats: Stats thread started at 12.742427
LogD3D11RHI: Loaded GFSDK_Aftermath_Lib.x64.dll
LogICUInternationalization: ICU TimeZone Detection - Raw Offset: +1:00, Platform Override: ''
LogConfig: Display: Loading platform ini files took 0.29 seconds
LogPluginManager: Mounting plugin MeshPainting
LogPluginManager: Mounting plugin XGEController
LogPluginManager: Mounting plugin Bridge
LogPluginManager: Mounting plugin AISupport
LogPluginManager: Mounting plugin EnvironmentQueryEditor
LogPluginManager: Mounting plugin CameraShakePreviewer
LogPluginManager: Mounting plugin Paper2D
LogPluginManager: Mounting plugin GameplayCameras
LogPluginManager: Mounting plugin LuminPlatformFeatures
LogPluginManager: Mounting plugin MagicLeapMedia
LogPluginManager: Mounting plugin MagicLeapLightEstimation
LogPluginManager: Mounting plugin MLSDK
LogPluginManager: Mounting plugin AnimationSharing
LogPluginManager: Mounting plugin MagicLeap
LogPluginManager: Mounting plugin MagicLeapPassableWorld
LogPluginManager: Mounting plugin CLionSourceCodeAccess
LogPluginManager: Mounting plugin CodeLiteSourceCodeAccess
LogPluginManager: Mounting plugin KDevelopSourceCodeAccess
LogPluginManager: Mounting plugin GitSourceControl
LogPluginManager: Mounting plugin NullSourceCodeAccess
LogPluginManager: Mounting plugin PlasticSourceControl
LogPluginManager: Mounting plugin PerforceSourceControl
LogPluginManager: Mounting plugin PluginUtils
LogPluginManager: Mounting plugin PropertyAccessNode
LogPluginManager: Mounting plugin RiderSourceCodeAccess
LogPluginManager: Mounting plugin SubversionSourceControl
LogPluginManager: Mounting plugin VisualStudioSourceCodeAccess
LogPluginManager: Mounting plugin UObjectPlugin
LogPluginManager: Mounting plugin TcpMessaging
LogPluginManager: Mounting plugin UdpMessaging
LogPluginManager: Mounting plugin VisualStudioCodeSourceCodeAccess
LogPluginManager: Mounting plugin XCodeSourceCodeAccess
LogPluginManager: Mounting plugin AvfMedia
LogPluginManager: Mounting plugin AndroidMedia
LogPluginManager: Mounting plugin Niagara
LogPluginManager: Mounting plugin ImgMedia
LogPluginManager: Mounting plugin MediaCompositing
LogPluginManager: Mounting plugin WmfMedia
LogPluginManager: Mounting plugin MediaPlayerEditor
LogPluginManager: Mounting plugin WebMMedia
LogPluginManager: Mounting plugin DatasmithContent
LogPluginManager: Mounting plugin AssetManagerEditor
LogPluginManager: Mounting plugin VariantManagerContent
LogPluginManager: Mounting plugin CryptoKeys
LogPluginManager: Mounting plugin CurveEditorTools
LogPluginManager: Mounting plugin DataValidation
LogPluginManager: Mounting plugin EditorDebugTools
LogPluginManager: Mounting plugin FacialAnimation
LogPluginManager: Mounting plugin GameplayTagsEditor
LogPluginManager: Mounting plugin GeometryMode
LogPluginManager: Mounting plugin InterchangeEditor
LogPluginManager: Mounting plugin MacGraphicsSwitching
LogPluginManager: Mounting plugin MaterialAnalyzer
LogPluginManager: Mounting plugin MobileLauncherProfileWizard
LogPluginManager: Mounting plugin LauncherChunkInstaller
LogPluginManager: Mounting plugin SpeedTreeImporter
LogPluginManager: Mounting plugin EditorScriptingUtilities
LogPluginManager: Mounting plugin AutomationUtils
LogPluginManager: Mounting plugin BackChannel
LogPluginManager: Mounting plugin PluginBrowser
LogPluginManager: Mounting plugin AlembicImporter
LogPluginManager: Mounting plugin ChaosCloth
LogPluginManager: Mounting plugin ChaosClothEditor
LogPluginManager: Mounting plugin ChaosEditor
LogPluginManager: Mounting plugin ChaosSolverPlugin
LogPluginManager: Mounting plugin CharacterAI
LogPluginManager: Mounting plugin GeometryCache
LogPluginManager: Mounting plugin GeometryCollectionPlugin
LogPluginManager: Mounting plugin GeometryProcessing
LogPluginManager: Mounting plugin MeshModelingToolset
LogPluginManager: Mounting plugin ProxyLODPlugin
LogPluginManager: Mounting plugin PlanarCut
LogPluginManager: Mounting plugin PlatformCrypto
LogPluginManager: Mounting plugin SkeletalReduction
LogPluginManager: Mounting plugin ChaosNiagara
LogPluginManager: Mounting plugin OnlineSubsystem
LogPluginManager: Mounting plugin OnlineSubsystemNull
LogPluginManager: Mounting plugin ActorSequence
LogPluginManager: Mounting plugin LevelSequenceEditor
LogPluginManager: Mounting plugin MatineeToLevelSequence
LogPluginManager: Mounting plugin TemplateSequence
LogPluginManager: Mounting plugin MotoSynth
LogPluginManager: Mounting plugin ActorLayerUtilities
LogPluginManager: Mounting plugin AndroidDeviceProfileSelector
LogPluginManager: Mounting plugin AndroidMoviePlayer
LogPluginManager: Mounting plugin AndroidPermission
LogPluginManager: Mounting plugin ArchVisCharacter
LogPluginManager: Mounting plugin AssetTags
LogPluginManager: Mounting plugin AudioCapture
LogPluginManager: Mounting plugin AppleImageUtils
LogPluginManager: Mounting plugin AppleMoviePlayer
LogPluginManager: Mounting plugin AudioSynesthesia
LogPluginManager: Mounting plugin CableComponent
LogPluginManager: Mounting plugin ChunkDownloader
LogPluginManager: Mounting plugin ExampleDeviceProfileSelector
LogPluginManager: Mounting plugin CustomMeshComponent
LogPluginManager: Mounting plugin GoogleCloudMessaging
LogPluginManager: Mounting plugin GooglePAD
LogPluginManager: Mounting plugin OnlineSubsystemUtils
LogPluginManager: Mounting plugin ScreenshotTools
LogPluginManager: Mounting plugin MultiUserTakes
LogPluginManager: Mounting plugin Interchange
LogPluginManager: Mounting plugin Takes
LogPluginManager: Mounting plugin IOSDeviceProfileSelector
LogPluginManager: Mounting plugin LinuxDeviceProfileSelector
LogPluginManager: Mounting plugin LocationServicesBPLibrary
LogPluginManager: Mounting plugin MobilePatchingUtils
LogPluginManager: Mounting plugin ProceduralMeshComponent
LogPluginManager: Mounting plugin PropertyAccessEditor
LogPluginManager: Mounting plugin RuntimePhysXCooking
LogPluginManager: Mounting plugin SoundFields
LogPluginManager: Mounting plugin SignificanceManager
LogPluginManager: Mounting plugin WebMMoviePlayer
LogPluginManager: Mounting plugin WindowsMoviePlayer
LogPluginManager: Mounting plugin Synthesis
LogPluginManager: Mounting plugin HairStrands
LogPluginManager: Mounting plugin ConcertMain
LogPluginManager: Mounting plugin MultiUserClient
LogPluginManager: Mounting plugin ContentBrowserAssetDataSource
LogPluginManager: Mounting plugin ContentBrowserClassDataSource
LogPluginManager: Mounting plugin OnlineSubsystemGooglePlay
LogPluginManager: Mounting plugin OnlineSubsystemIOS
LogPluginManager: Mounting plugin SQLiteCore
LogPluginManager: Mounting plugin OculusVR
LogPluginManager: Mounting plugin SteamVR
LogPluginManager: Mounting plugin ConcertSyncClient
LogPluginManager: Mounting plugin ConcertSyncCore
LogInit: Warning: Incompatible or missing module: MyProject2
Running F:/Programmi/UE_5.0EA/Engine/Binaries/DotNET/UnrealBuildTool/UnrealBuildTool.exe Development Win64 -Project="F:/unnamed-zombie-game/MyProject2.uproject" -TargetType=Editor -Progress -NoEngineChanges -NoHotReloadFromIDE
ERROR: Could not find NetFxSDK install dir; this will prevent SwarmInterface from installing.  Install a version of .NET Framework SDK at 4.6.0 or higher.
LogInit: Warning: Still incompatible or missing module: MyProject2
LogCore: Engine exit requested (reason: EngineExit() was called)
LogExit: Preparing to exit.
LogModuleManager: Shutting down and abandoning module DesktopPlatform (48)
LogModuleManager: Shutting down and abandoning module PlatformCryptoOpenSSL (46)
LogModuleManager: Shutting down and abandoning module PlatformCryptoTypes (44)
LogModuleManager: Shutting down and abandoning module PlatformCrypto (42)
LogModuleManager: Shutting down and abandoning module XGEController (40)
LogXGEController: Cannot use XGE Controller as Incredibuild is not installed on this machine.
LogXGEController: Cleaning working directory: C:/Users/Ale/AppData/Local/Temp/UnrealXGEWorkingDir/
LogModuleManager: Shutting down and abandoning module AnimationModifiers (38)
LogModuleManager: Shutting down and abandoning module AudioEditor (36)
LogModuleManager: Shutting down and abandoning module PropertyEditor (35)
LogModuleManager: Shutting down and abandoning module TextureCompressor (32)
LogModuleManager: Shutting down and abandoning module RenderCore (30)
LogModuleManager: Shutting down and abandoning module Landscape (28)
LogModuleManager: Shutting down and abandoning module SlateRHIRenderer (26)
LogModuleManager: Shutting down and abandoning module OpenGLDrv (24)
LogModuleManager: Shutting down and abandoning module D3D11RHI (22)
LogModuleManager: Shutting down and abandoning module AnimGraphRuntime (20)
LogModuleManager: Shutting down and abandoning module Renderer (18)
LogModuleManager: Shutting down and abandoning module Engine (16)
LogModuleManager: Shutting down and abandoning module CoreUObject (14)
LogModuleManager: Shutting down and abandoning module NetworkFile (12)
LogModuleManager: Shutting down and abandoning module CookedIterativeFile (10)
LogModuleManager: Shutting down and abandoning module StreamingFile (8)
LogModuleManager: Shutting down and abandoning module SandboxFile (6)
LogModuleManager: Shutting down and abandoning module PakFile (4)
LogModuleManager: Shutting down and abandoning module RSA (3)
LogExit: Exiting.
Log file closed, 07/12/21 08:04:47

```

In addition to Epic Games Launcher and UE5 I also installed Visual Studio 2019 and dotnet-sdk-5.0.301-win-x64.

The very same project compiles just fine on my macOS machine if I delete the above folders so I'd exclude a problem with the project itself.

May someone help me figure out what's missing?

# Answer
> 1 votes
Make sure you have .NET Core 3.1 installed.

You might need a version of 4 as well. Easiest way is to install through the Visual Studio installer.

You can do that through Visual Studio installer or get it from here

---
Tags: unreal
---


# Question
Title: Not understanding how indices and texturePositions are mapped to vertices in LWJGL
I've been following this tutorial on OpenGL and LWJGL and at some point three different lists are introduced without really explaining how they interact with each other. Can someone explain how it works?

```
float[] positions = new float[] {
    -0.5f,  0.5f,  0.5f, // V0
    -0.5f, -0.5f,  0.5f, // V1
     0.5f, -0.5f,  0.5f, // V2
     0.5f,  0.5f,  0.5f, // V3
    -0.5f,  0.5f, -0.5f, // V4
     0.5f,  0.5f, -0.5f, // V5
    -0.5f, -0.5f, -0.5f, // V6
     0.5f, -0.5f, -0.5f, // V7

    // For text coords in top face
    -0.5f, 0.5f, -0.5f, // V8: V4 repeated
     0.5f, 0.5f, -0.5f, // V9: V5 repeated
    -0.5f, 0.5f,  0.5f, // V10: V0 repeated
     0.5f, 0.5f,  0.5f, // V11: V3 repeated

    // For text coords in right face
    0.5f,  0.5f, 0.5f, // V12: V3 repeated
    0.5f, -0.5f, 0.5f, // V13: V2 repeated

    // For text coords in left face
    -0.5f,  0.5f, 0.5f, // V14: V0 repeated
    -0.5f, -0.5f, 0.5f, // V15: V1 repeated

    // For text coords in bottom face
    -0.5f, -0.5f, -0.5f, // V16: V6 repeated
     0.5f, -0.5f, -0.5f, // V17: V7 repeated
    -0.5f, -0.5f,  0.5f, // V18: V1 repeated
     0.5f, -0.5f,  0.5f, // V19: V2 repeated
};

float[] texturePos = new float[]{
    // Front Face
    0.0f, 0.0f,
    0.0f, 0.5f,
    0.5f, 0.5f,
    0.5f, 0.0f,

    // Behind Face
    0.0f, 0.0f,
    0.5f, 0.0f,
    0.0f, 0.5f,
    0.5f, 0.5f,

    // Top Face
    0.0f, 0.5f,
    0.5f, 0.5f,
    0.0f, 1.0f,
    0.5f, 1.0f,

    // Right Face
    0.0f, 0.0f,
    0.0f, 0.5f,

    // Left Face
    0.5f, 0.0f,
    0.5f, 0.5f,

    // Bottom Face
    0.5f, 0.0f,
    1.0f, 0.0f,
    0.5f, 0.5f,
    1.0f, 0.5f,
};

int[] indexes = new int[]{
    0,  1,  3,  3,  1,  2,  // Front face
    8,  10, 11, 9,  8,  11, // Top Face
    12, 13, 7,  5,  12, 7,  // Right face
    14, 15, 6,  4,  14, 6,  // Left face
    16, 18, 19, 17, 16, 19, // Bottom face
    4,  6,  7,  5,  4,  7   // Back face
};

```

For example, why are there only 2 vertices in the Right and Left face of the texture coords? Also, I've noticed that the texture I'm drawing on a cube is insideout on those faces. Could that be the reason?

Thanks in advance.

# Answer
> 0 votes
In the graphics pipeline, we need a vertex for each distinct combination of attributes, like position, texture coordinate, normal vectors, etc.

So if you have two faces meeting at a corner, and on one face that corner should show the bottom-right part of the texture, but on the other face that corner should show the bottom-left part of the texture, then you actually need two vertices there. Both with the same position, but with different texture coordinates, one for each face to use. This is how we make what we call a texturing or UV mapping seams, where different parts of the texture get mapped to adjacent parts of the geometry.

That's why, even though a cube only has 8 corners, we have a list of 20 vertices here: 20 positions, and 20 texture coordinates matching them. Some of the positions and texture coordinates need to be repeated in different combinations to get the texture wrapping around the cube as desired.

Note that this is still less than the full 24 (6 x 4) we'd get if we wanted 4 unique vertices for every face, so we're still sharing some of the vertices. It looks like the author of this data decided that the mirrored texture was "good enough" for their needs, so they let two of the faces stay back-to-front to save 4 vertices.

When we draw this geometry, we start with the index buffer. We read out three consecutive indices, and that tells us which three vertices, in which order, make up one triangle.

So the first triangle uses vertices 0, 1, and 3 - that's the first, second, and fourth items in the `positions` and `texturePos` lists. Then the next triangle uses vertex 3 and 1 again (the shared diagonal across the middle of the face), and vertex 2 (the opposite corner).

The order of the vertices is important in that it tells the GPU which way the triangle should face: 0, 1, 3 faces out, while inverting any two indices like 0, 3, 1 would make the triangle face inward. This order is called the "winding", for the way our iteration winds around the triangle's perimeter.

You can see in these lines:

```
12, 13, 7,  5,  12, 7,  // Right face
14, 15, 6,  4,  14, 6,  // Left face

```

that the left and right faces still have 6 indices = 2 triangles each, and they touch 4 distinct vertices, not just two.

But two corners of each of those faces, 5 and 7 for the right face, and 4 and 6 for the left face, are shared with the back face:

```
4,  6,  7,  5,  4,  7   // Back face

```

So that's why there's only two unique vertices' worth of position and texture coordinate information set aside for them in the lists above. They re-use two of the back face's vertices each.

---
Tags: opengl, textures, rendering, lwjgl
---


# Question
Title: Looking to build a game that uses names of Premier League teams - what are the steps required to stay compliant
I am looking to build a game that users would play weekly. In order for the game to make sense, I would have to display the names of the 20 Premier League teams playing on a weekly basis. I will **not be using the names of players** themselves. The game would require people to pay to contend for their share of a weekly pot of winnings.

The game would be similar to: https://fantasy.espn.com/games/english-premier-league-pickem-2020/make-picks

# Answer
> 1 votes
If you want to use someone's intellectual property, you need to contact them regarding licensing.

The description of your game essentially sounds like gambling. As such you would also need to check to see if you are compliant with any laws you might be subject to as well as any terms of service with respect to whatever platform you plan to release on.

---
Tags: legal
---


# Question
Title: Scratching with mouse to reveal a symbol
How can I make the minigame where you move a mouse around a rectangular grid and the symbol gets more or less "apparent" as shown below? (I can do mouse things, don't know how to approach making the symbol scatter to bits)

# Answer
> 2 votes
One way to accomplish this would be to have 4 textures:

* a pre-scratched texture
* a post-scratched texture
* an alpha mask which determines which of the latter textures are visible
* a "brush" or scratch texture(s) which will be used to paint onto the alpha mask.

When the user clicks you would stencil the brush texture onto the alpha mask at the mouse position. Depending on the particularities of your environment and implementation, you might have to do some converting between mouse-space and texture-space. This "painting" operation which would reveal the scratched texture could happen on the cpu or gpu, depending on how much you care about performance and how comfortable you are with shaders.

---
Tags: textures
---


# Question
Title: Shade a box different colors for two ends with one material in Three.js
First, I knew the following basic knowledges,

Then, I can use shader to render 2D graphics on the Shadertoy or GLSL Sandbox Gallery cross-browser online editor through WebGL or with the cross-platform SHADERed IDE. It's easy to use `GLSL` to draw 2D objects because 2D coordinates correspond to `gl_Position`. But I failed to use ShaderMaterial with the `GLSL` code to render a BoxGeometry I created in `three.js`. See the following code for my case.

```
/** @type {HTMLElement} */ var container;
var camera, scene, renderer;
/** @type {THREE.Mesh} */ var mesh;
var uniforms;
/** @type {THREE.TrackballControls} */ var controls;
/** @type {THREE.LineSegments} */ var wireframe;

var clock = new THREE.Clock();

try {
    init();
    animate();
} catch (err) {
    alert(err);
}
function init() {
    container = document.getElementById('container');

    camera = new THREE.PerspectiveCamera(40, window.innerWidth / window.innerHeight, 1, 3000);
    camera.position.z = 2.0;
    camera.position.y = 1.0;
    camera.rotation.x = -0.45;

    scene = new THREE.Scene();

    //var boxGeometry = new THREE.PlaneGeometry(0.75, 0.75, 1);
    var boxGeometry = new THREE.BoxGeometry(0.5, 0.5, 0.5);

    uniforms = { u_time: { type: "f", value: 0.0 } };

    var material = new THREE.ShaderMaterial({
        uniforms: uniforms,
        side: THREE.DoubleSide,
        transparent: true,
        vertexShader: document.getElementById('vertexShader').textContent,
        fragmentShader: document.getElementById('fragmentShader').textContent
    });

    mesh = new THREE.Mesh(boxGeometry, material);

    var geo, lineMaterial = new THREE.LineBasicMaterial({ color: 0xffffff, transparent: true, opacity: 0.5 });
    // lineMaterial.depthTest = false;
    // lineMaterial.polygonOffset = true;
    // lineMaterial.depthTest = true;
    // lineMaterial.polygonOffsetFactor = -2;
    // lineMaterial.polygonOffsetUnits = 0.1;
    if (0) {
        geo = new THREE.EdgesGeometry(mesh.geometry);
    } else {
        geo = new THREE.WireframeGeometry(boxGeometry);
    }
    wireframe = new THREE.LineSegments(geo, lineMaterial);
    mesh.add(wireframe); // wireframe.material === lineMaterial

    scene.add(mesh);

    var axesHelper = new THREE.AxesHelper();
    mesh.add(axesHelper);

    renderer = new THREE.WebGLRenderer();
    renderer.setClearColor(0xffffff, 1);
    container.appendChild(renderer.domElement);

    onWindowResize();

    window.addEventListener('resize', onWindowResize, false);

    initControls();
    initDatGui();
}

function onWindowResize(event) {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
}

function animate() {
    // requestAnimationFrame(animate);
    try {
        render();
    } catch (err) {
        if (confirm("An error occured:\n" + err.message)) {
            return;
        }
    }
    requestAnimationFrame(animate);
}

function render() {
    if (controls) controls.update();
    var delta = clock.getDelta();
    uniforms.u_time.value += delta;
    mesh.rotation.y += delta * 0.5;
    renderer.render(scene, camera);
}

function initControls() {
    if (!THREE.TrackballControls) return

    controls = new THREE.TrackballControls(camera, renderer.domElement);

    // controls.enabled = true; // default is true
    // controls.target = new THREE.Vector3(); // default is new Vector3()

    // controls.rotateSpeed = 3.0; // default is 1.0
    // controls.zoomSpeed = 1.2; // default is 1.2
    // controls.panSpeed = 0.3; // default is 0.3

    // controls.noRotate = false; // default is false
    // controls.noZoom = false; // default is false
    // controls.noPan = false; // default is false

    // controls.staticMoving = false; // default is false
    // controls.dynamicDampingFactor = 0.2; // default is 0.2

    // controls.minDistance = 0;
    // controls.maxDistance = Infinity;
}

function initDatGui() {
    if ('object' !== typeof dat && !dat.GUI) return;
    var datGui = new dat.GUI({ closed: true }); // panel is collapsed
    if (controls) {
        datGui.add(controls, "enabled").name("Enable").onChange(change);
        datGui.add(controls, "rotateSpeed", 1.0, 10.0).onChange(change);
        datGui.add(controls, "zoomSpeed", 1.0, 5).onChange(change);
        datGui.add(controls, "panSpeed", 0.1, 1.0).onChange(change);
        datGui.add(controls, "noRotate").name("Rotate").onChange(change);
        datGui.add(controls, "noZoom").name("Zoom").onChange(change);
        datGui.add(controls, "noPan").name("Pan").onChange(change);
        datGui.add(controls, "staticMoving").name("Static Moving").onChange(change);
        datGui.add(controls, "dynamicDampingFactor", 0.1, 1.0).name("Dynamic Damping Factor").onChange(change);
        datGui.add(controls, "minDistance", 0, 5).name("MinDistance").onChange(change);
        datGui.add(controls, "maxDistance", 5, 10).name("MaxDistance").onChange(change);
        datGui.add(controls, "reset").name("Reset").onChange(function resetTrackballControls() {
            this.object.reset();
        });
    }

    // var gui = { widthSegments: 1 }
    datGui.add(mesh.geometry.parameters, "widthSegments", 1, 66, 1).name("Width Segments").onChange(function updateGeometrySegments(newValue) {
        wireframe.geometry = mesh.geometry = new THREE.BoxGeometry(0.5, 0.5, 0.5, newValue);
    });
    datGui.add(wireframe, "visible").name("Show Wireframe");

    function change(newValue) {
        this.object[this.property] = newValue;
    }
}
```

```
<!DOCTYPE html>
<html>

<head>
<meta charset='utf-8'>
<meta name="description" content="WebGL Shader in Three.js">
<title>Shader</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<style>
a { color: #08f; }
b { color: lightgreen; }
html, body, .bespread { margin:0; padding:0; width:100%; height:100%; }
canvas { border: 1px dotted salmon; }
#info { position:absolute; bottom:0; }
</style>
</head>

<body>
<script>
window.onerror = function (msg, url, line, col, error) {
    // Note that col & error are new to the HTML 5 spec and may not be
    // supported in every browser.  It worked for me in Chrome.
    var extra = !col ? '' : '\ncolumn: ' + col;
    extra += !error ? '' : '\nerror: ' + error;

    // You can view the information in an alert to see things working like this:
    alert("Error: " + msg + "\nurl: " + url + "\nline: " + line + extra);

    // TODO: Report this error via ajax so you can keep track of what pages have JS issues

    var suppressErrorAlert = true;
    // If you return true, then error alerts (like in older versions of
    // Internet Explorer) will be suppressed.
    return suppressErrorAlert;
};
</script>

<script id="fragmentShader" type="x-shader/x-fragment">
varying vec3 v_color;

void main( void ) {
    gl_FragColor = vec4(v_color, 1.);
}
</script>
<script id="vertexShader" type="x-shader/x-vertex">
varying vec3 v_color;

void main()
{
    v_color = vec3(position.x < 0., 0, position.x >= 0.);
    vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
    gl_Position = projectionMatrix * mvPosition;
}
</script>

    <div id="container"></div>
    <div id="info">
        <a href="https://threejs.org/examples/#webgl_postprocessing_outline">WebGL Postprocessing Outline</a>
        <br>
        <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a>- Outline Pass by
        <a href="http://eduperiment.com" target="_blank" rel="noopener">Prashant Sharma</a>
        and <a href="https://clara.io" target="_blank" rel="noopener">Ben Houston</a>
    </div>
</body>
<!-- <script src="https://threejs.org/build/three.min.js"></script> -->
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r121/three.min.js"></script> -->
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/three@0.130.1/build/three.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/three@0.130.1/examples/js/controls/TrackballControls.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/dat.gui@0.7.7/build/dat.gui.min.js"></script>
<!-- <script type="module" src="index.js"></script> -->
</html>
```

I guessed that it was because it could distinguish between vertexes in the same middle position of the `+x` sides and `-x` sides for `v_color = vec3(position.x < 0.25, 0, position.x >= 0.25);`.

Finally, I also knew that I can Split the geometry into groups with different materials, but I just want to use one `ShaderMaterial` to do this.

```

var geo = new THREE.BoxGeometry(48, 48, 48, 2);
var magnetMaterial = ['red', 'blue', 'green', 'purple', 'cyan', 'white', 'black', 'pink', 'orange', 'gray'].map(it =>
    new THREE.MeshPhongMaterial({
        color: it, side: THREE.DoubleSide,
        polygonOffset: true, polygonOffsetFactor: 1
    }));

//Initializes the magnetic orientation to +x, red on the left side and blue on the right side.
//faces[].materialIndex: -x,-x, +x,+x, +z,+z,+z,+z, -y,-y,-y,-y, -z,-z,-z,-z, +y,+y,+y,+y
// var faceColors = [1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0];
// console.log('faceColors', geo.faces.map((it, idx) => it.materialIndex = faceColors[idx])); // for Three.js 1.20

// let's regroup materialIndex of five faces of the two ends of the Cuboid (x+,x-,y+,y-,z+,z-)
console.log(geo.getIndex().count, geo.groups.slice(0));
geo.clearGroups();
[0, 1, 1, 0, 1, 0, 1, 0, 0, 1].forEach((val, idx) => geo.addGroup(6 * idx, 6, val));

```

Anyone could help me to explain and solve this problem because the gradient is not what I want?

# Answer
> 0 votes
Last week, I moved the code about determining color from the vertex fragment to the fragment shader, it worked. That is to say,

Fragment Shader

```
varying vec3 v_pos;

void main( void ) {
    gl_FragColor = vec4(vec3(step(v_pos.x, 0.), 0., step(0., v_pos.x)), 1.);
}

```

Vertex Shader

```
varying vec3 v_pos;

void main()
{
    v_pos = position;
    vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
    gl_Position = projectionMatrix * mvPosition;
}

```

I guessed I had a fixed mind-set or could not understand thoroughly how the fragment/pixel shader works with a custom 3D mesh defined by vertices, because I always played with 2D `gl_FragCoord.xy` in an online live editor for fragment shaders in early learning.

1. Vertex Shader

> A vertex shader can manipulate the attributes of vertices. which are the corner points of your polygons.

Despite the fact `varying` was deprecated in GLSL 1.30 (OpenGL 3.0) and removed in GLSL 1.40 (Removed qualifiers).

2. Fragment Shader (Pixel Shader)

> The fragment shader on the other hand takes care of how the pixels between the vertices look. They are interpolated between the defined vertices following specific rules.

3. varying

See ShaderMaterial - Vertex shaders and fragment shaders

> **Varyings** are variables that are passed from the vertex shader to the fragment shader. For each fragment, the value of each varying will be smoothly interpolated from the values of adjacent vertices.

---

The output of a vertex shader will be interpolated as the input of a fragment shader. As a result, as for the example in the question, WebGL interpolates between these colors on each face (triangle) using a `varying` variable (v\_color).

If we want our faces to be completely red/blue, we should define all pixels red/blue. So we can do that in the fragment shader rather than in the vertex shader because the internal pixels cannot be controlled by a vertex shader except for the pixels specified by those corner vertices.

To manipulate the color for each position, we should use a fragment shader, or there is a gradient between the vertices if `gl_FragColor` is directly determined in a vertex shader.

---
Tags: 3d, glsl, fragment-shader, three.js, vertex-shader
---


# Question
Title: Pygame 2D : rotation around center not working properly
here is the code I use to rotate an image around its center:

```
class Square:
    def __init__(self) :
        self.x, self.y, self.angle = 50, 200, 0
        self.image = load('redrect.png')
        self.image360 = pygame.transform.rotate(self.image, self.angle)
        ...

    def blit(self):
        self.image360 = pygame.transform.rotate(self.image, self.angle)
        # I made a center() function to calculate the center of an image/rect
        self.center360 = center(self.x, self.y, self.image360)
        MyScreen.blit(self.image360, self.center360)

mysquare = Square()

while 1:
    for e in events:
        if e.type == KEYDOWN:
            if e.key == K_r:
                mysquare.angle += 45

```

When I run the code and attempt to rotate the square, I notice that the rotation isn't smooth and isn't really around its center though I'm blitting the `image360` attribute of the square in its center coordinates.

Btw if I just flip the image by 90°, it will seem to be perfectly rotating around its center.

Here is how I created my center() function :

```
def center(x, y, rect) :
    try:
        return (x + rect.get_width() / 2, y + rect.get_height() / 2)
    except AttributeError:
        return (x + rect.width / 2, y + rect.height / 2)

```

## UPDATE :

Here is an example of what happens when I try to rotate the image (square case) :

rectangular image case : (I modified the GIF as I realized I had made a wrong one before)

# Answer
Finally I solved the issue and it was related to wrong image positioning as @Tyyppi\_77 has mentionned in the comments.

The `blit` method of `pygame.Surface` turns out to blit a surface in the topleft corner if coordinates are passed to the 2nd parameter.

However, if we pass a `Rect` object, we would be able to position the image as we want.

Here is what the documentation says :

> The dest argument can either be a pair of coordinates representing the position of **the upper left corner of the blit** or a Rect, where the upper left corner of the rectangle will be used as the position for the blit.

And fortunately, pygame.Surface objects have a `get_rect()` method using which we can obtain a `Rect` object that can be centered at a given position.

So what I did to solve the issue is getting and updating the rotated image's rect object while positioning it to the center not to the top left corner like this :

```
class Square:
    def __init__(self):
        self.x, self.y, self.angle = 50, 200, 0
        self.image = load('square.png')

    @property
    def center360(self):
        return center(self.x, self.y, self.image)

    @property
    def image360(self):
        return pygame.transform.rotate(self.image, self.angle)

    @property
    def rect360(self):
        return self.image360.get_rect(center=self.center360)

    def blit(self):
        MyScreen.blit(self.image360, self.rect360)

```
> 1 votes

---
Tags: rotation, transformation, pygame
---


title: Unity Grass in VR

text:
# Question
Title: Unity Grass in VR
I'm working on a VR game in Unity and I just discovered that trees and grass added to a terrain bend in funky ways when you move your VR headset which is really nauseating and weird.

This is a known issue with VR and trees / grass in the terrain editor - https://forum.unity3d.com/threads/unity-tree-billboard-bug-with-oculus-unity-what-is-going-on.406006/

I opted to add trees manually as GameObjects which fixed my tree issue, but I have no idea how to add the grass since it's just a 2D image (I'm using this - https://www.assetstore.unity3d.com/en/#!/content/52977)

If anyone can point me in the right direction, I'd really appreciate it! I've been reading posts about this for an hour and feeling pretty lost!

Thanks!

# Answer
The solution is to use 3D grass, which will be expensive in terms of system resources. There's no way around it, even if the billboard problem is fixed, using 2D grass will look strange in VR, because 2D does not have depth and you can see depth in VR. It will essentially look like how a 2D game looks in the editor when you're in 3D mode.

If you have money to risk I suggest taking a look at VolumeGrass or InfiniGRASS.

Disclaimer: I have NOT tested these and do NOT know whether they work as 3D grass or not. Use at your own risk.

If not, try making a cone shape, color it green and just scatter it around. You'll see the difference.
> 1 votes

# Answer
I know this is an old question but I'd thought I'd throw in my two cents.

The reason for this is because Unity terrains use billboards rotation as the same as the camera rotation. Now you don't usuallly notice this on a normal screen, but in VR it looks really strange. The billboards are simply using `camera.transform.rotation` and really should use something like `grass.RotateTowards(camera.transform);` but that would be too expensive

The solution is to not use billboard grass and simply have static grass, or as John mentioned, use grash meshes, but they might also be too expensive depending on what VR platform you're using and how many details you have
> 1 votes

---
Tags: unity, virtual-reality, oculus
---


# Question
Title: Black screen after unity updated to 2019.4.17and later on Android
I upgraded my app from Unity 2019.4.9 to 2019.4.21. it seems to work fine in the editor, but on my Android build I just get a blank screen. No splash screen, no app main window. I've been able to isolate it to the update from 2019.4.16 to .17 that breaks it. I can toggle back and forth, build .16 it works, .17 and higher are all black screen. I tried (.17,.18 and .21)

only thing relevant in the logs seems to be:

```
03-13 10:49:09.689  1458  7484 I WindowManager: WIN DEATH: Window{378e77 u0 com.mycompany.myapp/com.unity3d.player.UnityPlayerActivity}
03-13 10:49:09.689  1458  7484 W InputDispatcher: Attempted to unregister already unregistered input channel
03-13 10:49:09.689  1458  2335 I ActivityManager: Process com.mycompany.myapp (pid 8851) has died: fore TOP (366,458)

```

i'm building for Mono, .NET 4.x and Targeting ARMv7

anyone else run into this? any info on what I should look at next to continue to debug? anyone know what changed in .17 that might be causing this?

# Answer
> 1 votes
in case anyone is interested. I didn't find a real fix so I created a new project in 2019.4.28 and manually imported all my code and assets. After this it works as expected.

---
Tags: unity, android
---


# Question
Title: Stride: Gamepad (DS4) Input Not Working in CSharpBeginner Example
I have only Microsoft build tools and Visual Studio Code installed (not Visual Studio). The CSharpBeginner example from the Stride Game Studio seems to generate, build and run fine using the Game Studio and the project also seems to open, build, and run okay from Visual Studio Code.

It looks like the only thing that doesn't work is controller input in the Virtual Buttons scene. The Visual Studio Code build shows a warning about SDL in the terminal:

```
EXEC : warning 2.150s: [YamlAssemblyRegistry] Assembly [SDL2-CS, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null] has not been processed by assembly processor with --serialization flags. [DataContract]
aliases won't be available. [D:\dev\StrideProjects\CSharpBeginner\CSharpBeginner.Windows\CSharpBeginner.Windows.csproj]

```

Anyone have any ideas on how to deal with this? Thanks.

Edit - the project is:

https://github.com/stride3d/stride/tree/master/samples/Tutorials/CSharpBeginner

I just created it from the list of examples given when launching the Game Studio. The only thing I changed was the path to `CSharpBeginner.Windows.dll` in `.vscode/launch.json`. I'm not sure if these files were generated by Stride or Visual Studio Code but wherever it came from it seems to have gotten it wrong. Actually I think it worked before that change in Game Studio but not Code.

# Answer
> 2 votes
Partial answer from what I figured out yesterday...

I was initially testing with a DS4 (official PS4 controller) and it was not working. The unaltered example did work when I switched to an "Afterglow" XBox controller though.

I had wrongly assumed SDL was used for input in the example. I edited the example to switch to SDL by changing `CSharpBeginner.Game\Code\VirtualButtonsDemo.cs` as follows:

```
using Stride.Engine;
using Stride.Games;

namespace CSharpBasics
{
    class CSharpBeginnerApp
    {
        static void Main(string[] args)
        {
            using (var game = new Game())
            {
                // game.Run();
                game.Run(new GameContextSDL(new GameFormSDL(), 1280, 720, false));
            }
        }
    }
}

```

With SDL, both controllers' input is available from scripts via the `Input.GameControllers` list. Stride only shows `IGameControllerDevice` instances and no `IGamePadDevice` instances.

---
Tags: input, sdl, stride
---


# Question
Title: Is the CC BY-SA 4.0 licence what I want?
I'm looking for a licence for my game-assets (everything like artwork, music, stories, characters... **except the code**) who respects those points :

Assets are free to use, share, remix, adapt, transform, redistribute for any purpose, even commercially, as long as :

1. You give the appropriate credit.
2. Any new Asset that is associated in the collective imagination or represented nears the original Asset need to have the same licence as the original asset.

It look like the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) licence is what I want, it has Attribution and ShareAlike, however I'm not fully sure with:

* The second point above.
* Is any other free to use asset (like public domain) can also be considered under this licence (CC BY-SA 4.0)
* Is is okay if the code have a different licence in contradiction with this one ? (After all code is somethings abstract that isn't represented, visible, perceptible in for the consumer

To be clear, I don't want the following situation to happen:

> Let's say that `Mateo Universe` assets are under the licence I described. A brand named `GreedyCompanie` like this universe and decide to use it next to their copyrighted `Dylan Universe` assets. The `Dylan Universe`, *even if it may cool*, is of course not free in any way, and only `GreedyCompanie` have the right on it.

Last more doubtful question, consider this one as a bonus:

What about non-profit fan games ? If someone make a `Dylan Universe` X `Mateo Universe` game even if the person don't have the right on `Dylan Universe`, will it infringe the licence ? (I think it will infringe the licence, but I would appreciate if it will not be the case or if I can keep a blur on it)

Hope it was clear, and sorry I can be a bit paranoia when it come to licencing assets, that why I'm here to get some confirmations about my doubts.

# Answer
> Is the CC BY-SA 4.0 licence what I want?

No.

CC BY-SA 4.0 will cover the point *You give the appropriate credit.* but it does not cover the second point *Any new Asset that is associated in the collective imagination*, so GreedyCompany can use your `hero_Mateo_image.png` (that is CC BY-SA 4.0) in their next game; as long as they comply with the *Attribution* clause, they're not forced to release their own assets with the same license.

> Is any other free to use asset (like public domain) can also be considered under this licence (CC BY-SA 4.0)

It depends on the original license. Quoting user1937198 from the comments:

> > If you receive free-to-use asserts under a license that allows unlimited sub-licensing like MIT that is a superset of CC-BY-SA, you can make it so anyone who gets the license from you has to use the CC-BY-SA license, but you can't stop them from getting the MIT license from wherever you got it from.

So although you *could* change the license and re-distribute the asset, there is not really a point in doing so.

> Is is okay if the code have a different licence in contradiction with this one ?

Yes, it is okay; you'll need to be explicit about what is covered under which license. (But I suggest you don't release your game code.)

> \[...\] if the person don't have the right on Dylan Universe, will it infringe the licence ?

Yes, if the Dylan Universe copyright owner did not license the assets to be used (e.g. using a CC BY-SA license) it will infringe the copyright because you'll be using their work without explicit permission. If you decide to come up with your own drawings of the characters (e.g. you decide to draw Pikachu yourself), you'll infringe their IP.

---

It looks like you have two concerns:

> I want my assets to be used in a way "as open" as I make them available.

That's okay. You have an uncommon licensing scheme, so I suggest you consult with a lawyer to help you write this license. That'll help you in the case you need to defend a copyright: imagine you write your license text with a lot of legal flaws, you'll have trouble finding a lawyer that will want to take your case when you need to sue GreedyCompany.

> Can I use someone else's copyrighted and unlicensed work?

You can't legally do it. Without explicitly/legally being stated as such, some copyright owners will let folks use their assets and IPs in the context of fan games/fictions/mods, and some others won't. And even if you see people get away with this, the copyright owner still has the power to come after you and have you stop using their assets/IPs.

---

On a final note:

* I suggest you consider what you have to gain/lose by allowing such license and distributing your code. Maybe you'll end up considering what you have to lose outweighs what you have to gain.
* You can release your game without a license, then decide to make the assets available under a CC BY-SA 4.0 at a later point in time.
* I suggest your make only the assets as freely usable, *not* the characters nor your universe. That's your IP, your bread and butter. That's what you can use to make a sequel, or sell to a bigger company.
* Whatever you do, if GreedyCompany steals your assets or use it in a way that does not comply with the license, and thinks it has more money than you do to defend itself in court, you're kind of stuck and unable to defend your copyright.

In any case, I suggest you consult with a lawyer before you get close to release, just to make sure you back yourself enough to have peace of mind, or to know what kind of hell hole you've dug yourself into ;P
> 5 votes

---
Tags: licensing
---


title: Mac unity not working (error message)

text:
# Question
Title: Mac unity not working (error message)
Upon opening a new project or template the unity launcher dies and shows the error message:

```
Could not find Unity Package Manager local server application at
[/Applications/Unity/Hub/Editor/2020.3.15f1/Unity.app/Contents/Resources/PackageManager/Server/UnityPackageManager].
Missing files could be the result of an antivirus action or a corrupt Unity installation.

```

If I diagnose it says

```
❓ UPM health check (UNKNOWN)
Start the UPM process and call its health endpoint
>> Could not find UPM executable at path '/Applications/Unity/Hub/Editor/2020.3.15f1/Unity.app/Contents/Resources/PackageManager/Server/UnityPackageManager'

```

Anyone that cane help it would be greatly appreciated

# Answer
I had that problem yesterday, and I solved it by uninstalling Unity and reinstalling it.
> 1 votes

---
Tags: unity, macos
---


# Question
Title: Scenes do not stop showing "(is loading)"
I want to rebuild the RE4 game behaviour.

In RE4, the inventory screen is a scene of its own.

In Unity, the scenes which are loaded additively inherit the skybox / lights from the first scene loaded.

That is why I start my game with an empty scene without any lights. Else, if I would load the inventory level when it's actually needed, it would inherit the lights from the currently loaded scene.

To avoid this, I have established the following game logic:

The first scene a black scene with just a single, empty gameobject. This gameobject has a script on it that loads the other scenes:

```
using UnityEngine;
using UnityEngine.SceneManagement;

public class StartupScript : MonoBehaviour
{
    AsyncOperation _InventoryScene;
    AsyncOperation _FirstLevel;

    void Start()
    {
        //load the inventory scene so that we can quickly show it when the user presses the "Inventory" key.
        _InventoryScene = SceneManager.LoadSceneAsync("InventoryScene", LoadSceneMode.Additive);
        _InventoryScene.allowSceneActivation = false; //we make it so that it is not shown

        //Instead, we load the first level
        _FirstLevel = SceneManager.LoadSceneAsync("Level1Scene", LoadSceneMode.Additive);
        _FirstLevel.allowSceneActivation = true;//start the game by showing Level 1 scene
    }
}

```

For some reason however, Unity does not show the level. Instead, both scenes stay at "(is loading)".

What am I missing?

Thank you!

Edit: When I do not load the InventoryScene first, the Level scene loads without any problems.

Edit2: When I load the InventoryScene at last, the InventoryScene stays at "(is loading)".

# Answer
> 2 votes
The documentation for `allowSceneActivation` reads:

> When allowSceneActivation is set to false, Unity stops progress at 0.9, and maintains isDone at false. When AsyncOperation.allowSceneActivation is set to true, isDone can complete. While isDone is false, the AsyncOperation queue is stalled.

So Unity **intentionally** doesn't let the load operation finish if `allowSceneActivation` is false. And when the queue stalls, the other load operations don't even start:

> Unity does not call the second operation until the first AsyncOperation.allowSceneActivation is set to true.

An alternative solution for your scenario is to have a root GameObject in all of your scenes, and treat that root GameObject as the scene itself. That is: enable/disable the root GameObject of a scene to control whether that scene is currently active.

You can get the root GameObjects in a Scene with `Scene.GetRootGameObjects`.

---
Tags: unity, scenemanager
---


# Question
Title: What are some good examples of the practical usages of cross product in game development?
I know how to calculate cross product, and know that the cross product of 2 vectors is a third vector that is perpendicular to a plane created by the first 2 vectors.

However, I have not seen any good explanations about the practical usages of cross product in game development.

What are practical examples of the usages of cross product in game development ?

# Answer
**Generating Normals**

As Maximus Minimus notes in the comments, when we have a mesh without normal vectors (say just raw vertex positions from a procedural generator or 3D scanned point cloud), we can determine a normal vector for each triangle of the mesh using the cross product of two of the triangle's edges, ensuring the vector is perpendicular to the triangle surface.

The magnitude of such a vector will be equal to twice the area of the triangle, which we can exploit when averaging the normals around each vertex to make vertex normals. The area weighting means that dividing a big triangle into many small skinny triangles won't unfairly skew the resulting normal.

These vertex normals can then be used to apply lighting and shading when rendering the surface, or match an object's orientation to its underlying surface, or compute a ricochet off the surface, etc.

**Checking Winding**

We can use a simplified version of this cross product between a triangle's edges to check whether it's a front face or a back face during rendering.

After transforming the vertices to normalized device coordinates, we can compute just the z component of the cross product and check its sign to determine whether the triangle is facing toward the camera, or away. In many shaders this will be used to cull triangles from the back sides of objects, roughly halving the fragment shading/blending costs for them.

**Generating a Coordinate Basis**

Often in games we want an object to face in a particular direction — like pointing a camera at a target or aiming a character's head/eyes/weapon with IK, or spawning a projectile oriented along its flight direction.

But one direction vector along isn't quite enough information to fully specify an orientation — it uses up two degrees of rotational freedom, but we still have one degree of freedom left: spinning the object around that direction vector.

So to get an unambiguous orientation, we need to extend this direction into a basis. One common way to do this uses the cross product. In a left-handed coordinate system, that might look like:

```
desiredRight = normalize(cross(worldUp, desiredForward))
desiredUp = cross(desiredForward, desiredRight)

```

(This has a singularity when you want to look exactly up or down, so those edge cases need to be handled separately — usually still with a cross product)

You can use the trio of right/up/forward vectors formed this way as the columns of a rotation matrix, or convert them to a quaternion.

**Applying a Torque**

When a force is applied to a physics object at an offset from its center of mass, it should impart some angular momentum to the object, making it rotate.

We can calculate the amount and direction of spin using torque:

```
torque = cross(offsetFromCenter, force)

```

This acts as the angular equivalent of force, and can be integrated into angular momentum/angular velocity by the physics engine similar to how regular linear force gets integrated into linear momentum/linear velocity.

**Matrix Determinants and Inverses**

A handy shortcut to computing the determinant of a 3x3 matrix is the scalar triple product. If vectors `a`, `b`, and `c` are the rows of your matrix, then:

```
determinant = dot(cross(a, b), c)

```

You can find a fuller mathematical treatment of this elsewhere, but suffice it to say that this can be handy when computing matrix inverses, like if we want to undo the transformation of an object to convert a point from world coordinates into the object's local coordinates — such as to position a bullet decal on an object at the position of a projectile collision.

**Grassmann Algebra**

This one is a bit more esoteric, but as Eric Lengyel explains in a number of GDC talks, the cross product can be thought of as being a special case of a more general "wedge product". Wedges (and their complementary anti-wedges) turn out to be powerful tools for working with constructs of different dimensions, like finding intersections between lines and planes etc., in a really elegant way.
> 16 votes

# Answer
Many.. many things:

1. calculating normals for light/physics calculation
2. using for calc distances (point/plane)
3. checking orientation of (2D)-Polys (are they left or right wound?)
4. calculating 2D-area of general polygons (ok, it is using a "shrinked" 2d-cross product)
> 3 votes

---
Tags: game-design, movement, vector, linear-algebra, normals
---


# Question
Title: Slots - Reel with a predefined symbol positions or make each symbol change independently on the others
I'm making a slot machine game and I need some advice on how to implement the spinning reels or how it's usually done. Right now, I'm thinking about two different approaches that would make sense - if you know any other way to implement this, please do share - and I don't know which one is better or the more common (if either of those is even right).

**Approach No.1** \- Predefined Reels

In this approach, the symbols on the reels are predefined and fixed in place (akin to how it's done on the old-school mechanical slots) and the reels rotate like this.

**Approach No.2** \- Random Symbols

Here all the symbols are randomly chosen on the go, just before the symbol appears in the view.

Which one of these approaches is the right way to go, if either. Are there any alternative solutions that are used normally?

# Answer
I think it will depend on a couple of factors, and none of them are governed by technical ease of implementation.

You'll probably want to go with a predefined set of images

* if you want to advertise your game as "close to the real thing". Images are attached to reels and so the users should be able to figure the amount of images on a reel and the sequence.
* if you want to let the users try to stop the reel over precise images.

Whether you want to have the reel go in "reverse" after it has been going "forward" is irrelevant here, as you would simply store the generated pictograms and reuse them in the sequence it is stored.

Another thing to consider before deciding this is how you'll use your random number generation and how you'll decide how often you want your players to win.

Going with the "real" thing, you'll decide upfront the probability of each symbol to get picked, and it's going to be "relatively" easy to tune how often the player wins. However, if you decide to go ahead with "randomly selected" symbols, you'll have to come up with an algorithm that will let you tune what symbols are randomly selected.

So I suggest you figure out how you'll decide how the player wins, and how you want to market your game; that'll help you decide what approach you should use.
> 0 votes

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


# Question
Title: Grouping Around a Point and Moving Together With Steering Behaviors
I have a group of enemies that move together. I have them grouped around a point by setting their target to be a point at the center of the group. I have combined the "Seek" and "Separate" steering behaviors to achieve this. My issue stems from the fact that they all want to move to that point, effectively fighting for the center. (The separate steering behavior just has them doing this at a distance, and when trying to use the arrive steering behavior the same issue happens it's just slightly less pronounced, but has other side effects I don't want.) Is there any way I could group them like this without having them fight for the center? I don't want to have set positions as that would be unnatural looking and ill-fitting for my game. I also think a flow field would have the same issues (I'm not sure about that).

Note: The point moves, as this is for group movement.

# Answer
> 1 votes
# Falloff with distance

Implement falloff with distance in your steering behaviours to make them do less when less relevant.

I assume your Seek and Separate behaviours each output a desired direction and weight that your enemies use to determine how to move. If you scale the weight by distance, then you can let the two behaviours balance each other out.

*Seek* scales **inversely** with distance to destination.

*Separate* scales **proportionally** with distance to other enemies.

```
function clamp(min, max, num)
    return num <= min and min or (num >= max and max or num)
end

function inverse_lerp(a, b, t)
    return (t - a)/(b - a)
end

function scale(min, max, val)
    val = clamp(min, max, val)
    local t = inverse_lerp(min, max, val)
    -- See easings.net for alternatives to this cubic curve.
    return t * t * t
end

```

Will give a curve like:

Use `1 - scale(min, max, distance)` to scale inversely.

That way your *Seek* will have no influence when the enemies are close to their target, only small influence when "close enough", and lots of influence when far away.

# Influence threshold before action

**Additionally,** if your enemies look good stationary (ground units, units with standing idles, etc), you could set a threshold of influence before they move. This threshold could vary so it becomes higher when they're stationary to avoid jittering and lower when moving quickly to be more responsive.

---

When figuring this stuff out, I'd always recommend visualizing your data with graphs. Here's the love2d program that I used to generate that graph:

```
function love.draw()
    local pts = {}
    local size = 10000
    local min = 100
    local max = 200
    for x=0,size,1 do
      table.insert(pts, x + 50)
      table.insert(pts, 200 - 100 * scale(min, max, x))
    end
    love.graphics.points(pts)
    love.graphics.line(10, 200, 10, 100)
    love.graphics.line(10, 200, 20, 200)
    love.graphics.line(10, 100, 20, 100)
    love.graphics.print("0", 25, 190)
    love.graphics.print("1", 25, 100)
end

```

# Answer
> 0 votes
The answer to your question lies with the strategies employed in this short video by Game Endeavor...

**https://www.youtube.com/watch?v=6BrZryMz-ac**

*Quote from Game Endeavor:*

> NOTE: I'm not using this as a replacement for path finding. The purpose of this is to control how the AI behaves in its local environment. ie avoid clumping together, strafe the player, flee from the player but don't get stuck on walls. NOT get from point a to point b.
>
> The fact that it can avoid simple obstacles is just an added bonus that came about naturally from this system, but not the primary way of avoiding them. Without proper path finding, the ai will get stuck if there is a wall between it and its target. However, you can combine this with a pathfinder, if you have it seek along the path instead of directly at its target. :)

---
Tags: steering-behaviors
---


title: Tab between input fields

text:
# Question
Title: Tab between input fields
I am new to working with Unity3d, I need to navigate between several `inputField`, for this I have looked at the solution that is in: tab-between-input-fields, but always the `FindSelectableOnUp()` or `FindSelectableOnDown()` returns null, so my next is always null and always ends in: `next = Selectable.allSelectables[0];`

# Answer
> 2 votes
I did a small improvement to @virtouso answer. I start always with the first inputfield in my list and after the last inputfield I am reseting my counter to start again from beginning.

```
public  List<InputField> fields;
int _fieldIndexer;

private void Update()
{
    if (Input.GetKeyDown(KeyCode.Tab)) {
        if (fields.Count <= _fieldIndexer)
        {
            _fieldIndexer = 0;
        }
        fields[_fieldIndexer].Select();
        _fieldIndexer++;
    }
}

void Start () {
    fields = new List<InputField>{PreNameInput, FamilyInput, BirthdateInputField};
}

```

# Answer
> 1 votes
It seems you want to change **focus** between input fields by TAB button. I'm not sure there is a built-in function for this but you can simply write some code for this solution. For this, you have to make a list of your input fields. Then, on Press Tab Button, change the index and call the **Select** function. This is my example but you have to handle other things too:

```
public  List<InputField> fields;
int fieldIndexer;

private void Update() {
    if (Input.GetKeyDown(KeyCode.Tab)) {
        fieldIndexer++;
        fields[fieldIndexer].Select();
    }
}

```

# Answer
> 1 votes
A possible cause for the FindSelectableOnUp and FindSelectableOnDown returning null could be the value set under Navigation. Each Selectable (InputField is a Selectable) has in its inspector a section called Navigation.

This influences what FindSelectableOnDown and FindSelectableOnUp return. If vertical is not checked for any of the 2 InputFields you want to link for instance, they won't be able to navigate to each other. (Also note, the visualize button should show arrows in the scene view if Navigation is enabled for both elements)

For more info about how Navigation works, see this section in the manual

# Answer
> 0 votes
All you're wanting to do here is:

1. check if the user has just pushed the tab key
2. find what they're selecting (and its index in the list)
3. select the next thing in the list, or wrap around to the beginning

So:

```
public Selectable[] UISelectables;
private EventSystem eventSystem;

private void Start() {
    eventSystem = FindObjectOfType<EventSystem>();
}

private void Update() {
    if (Input.GetKeyDown(KeyCode.Tab)) {
        for (int i = 0; i < UISelectables.Length; i++) {
            if(UISelectables[i].gameObject == eventSystem.currentSelectedGameObject) {
                UISelectables[(i+1) % UISelectables.Length].Select();
                break;
            }
        }
    }
}

```

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


# Question
Title: Improve cube rendering performance in lwjgl
I've been coding a minecraft-like game in lwjgl using cubes. I've reached a point where I can render 6 chunks of blocks before it starts lagging. I've searched online for optimizations and one of the most common ones was to remove the faces of the cube that cannot be seen by the player. I've tried implementing this but even after only leaving one face of each cube enabled, the performance is still the same. This is my current (and probably terrible) implementation:

**Block.java**

```
package com.yellow.engine.prefabs.base;

import com.yellow.engine.enums.Face;
import com.yellow.engine.handlers.TextureHandler;
import com.yellow.engine.rendering.Mesh;
import com.yellow.engine.rendering.Texture;
import com.yellow.engine.world.GameObject;

public class Block extends GameObject{

float[] vertices = new float[] {
    // Front Face
    -0.5f,  0.5f,  0.5f, // V0
    -0.5f, -0.5f,  0.5f, // V1
     0.5f, -0.5f,  0.5f, // V2
     0.5f,  0.5f,  0.5f, // V3

    // Top Face
    -0.5f, 0.5f, -0.5f, // V4
     0.5f, 0.5f, -0.5f, // V5
    -0.5f, 0.5f,  0.5f, // V6
     0.5f, 0.5f,  0.5f, // V7

    // Right Face
     0.5f,  0.5f,  0.5f, // V8
     0.5f, -0.5f,  0.5f, // V9
     0.5f, -0.5f, -0.5f, // V10
     0.5f,  0.5f, -0.5f, // V11

    // Left Face
    -0.5f,  0.5f,  0.5f, // V12
    -0.5f,  0.5f, -0.5f, // V13
    -0.5f, -0.5f, -0.5f, // V14
    -0.5f, -0.5f,  0.5f, // V15

    // Bottom Face
    -0.5f, -0.5f, -0.5f, // V16
    -0.5f, -0.5f,  0.5f, // V17
     0.5f, -0.5f, -0.5f, // V18
     0.5f, -0.5f,  0.5f, // V19

    // Back Face
    -0.5f,  0.5f, -0.5f, // V20
     0.5f,  0.5f, -0.5f, // V21
    -0.5f, -0.5f, -0.5f, // V22
     0.5f, -0.5f, -0.5f, // V23
};

float[] texturePos = new float[]{
    // Front Face
    0.0f, 0.0f,
    0.0f, 0.5f,
    0.5f, 0.5f,
    0.5f, 0.0f,

    // Top Face
    0.0f, 0.5f,
    0.5f, 0.5f,
    0.0f, 1.0f,
    0.5f, 1.0f,

    // Right Face
    0.0f, 0.0f,
    0.0f, 0.5f,
    0.5f, 0.5f,
    0.5f, 0.0f,

    // Left Face
    0.5f, 0.0f,
    0.0f, 0.0f,
    0.0f, 0.5f,
    0.5f, 0.5f,

    // Bottom Face
    0.5f, 0.5f,
    0.5f, 0.0f,
    1.0f, 0.5f,
    1.0f, 0.0f,

    // Back Face
    0.5f, 0.0f,
    0.0f, 0.0f,
    0.5f, 0.5f,
    0.0f, 0.5f,
};

int[] indices = new int[]{
    0,  1,  3,  3,  1,  2,  // Front Face
    7,  5,  6,  6,  5,  4,  // Top Face
    8,  9,  11, 11, 9,  10, // Right Face
    12, 13, 15, 15, 13, 14, // Left Face
    19, 17, 18, 18, 17, 16, // Bottom Face
    20, 21, 22, 22, 21, 23  // Back Face
};

// Lo mettiamo uguale ad indices così anche se non togliamo una faccia ha i valori di base
int[] activeIndices = indices;
float[] activeVertices = vertices;
float[] activeTexturePos = texturePos;

private Texture texture;

public Block() {
    super();

    Face[] faces = new Face[]{ Face.Top, Face.Bottom, Face.Right, Face.Left };
    this.removeFaces(faces);

    this.texture = TextureHandler.getTexture("grassblock.png");
    //this.mesh = new Mesh(vertices, indices, texturePos, texture);
    this.mesh = new Mesh(activeVertices, activeIndices, activeTexturePos, texture);
    this.mesh.generateBuffers();
}

// TODO: Finisci di implementare questo.
// I vertici e le coordinat edella texture non devono essere passate se le loro facce sono disabilitate.
protected void removeFace(Face face) {
    int faceIndex = Face.valueOf(face.toString()).ordinal();

    for(int i = 0; i < indices.length; i++) {
        // 6 è il numero di indici per faccia
        if((faceIndex * 6) <= i && i < (faceIndex * 6 + 6)) {
            // TODO: Implementa un check per questo -1 nel renderer: se vede -1, lo ignora direttamente
            // forse c'è un modo migliore di implementarlo.
            activeIndices[i] = -1;
            continue;
        }

        activeIndices[i] = indices[i];
    }

    for(int i = 0; i < vertices.length; i++) {
        if((faceIndex * 12) <= i & i < (faceIndex * 12 + 12)) {
            activeVertices[i] = -1;
            continue;
        }
    }

    for(int i = 0; i < texturePos.length; i++) {
        if((faceIndex * 8) <= i & i < (faceIndex * 8 + 8)) {
            activeTexturePos[i] = -1;
            continue;
        }
    }
}

protected void removeFaces(Face[] faces) {
    for(Face face : faces) {
        this.removeFace(face);
    }
}

```

}

**Mesh.java**

```
package com.yellow.engine.rendering;

import org.lwjgl.system.MemoryStack;

import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.List;

import static org.lwjgl.opengl.GL33.*;
import static org.lwjgl.system.MemoryStack.stackPush;

public class Mesh {

private int VAO;
private int vertxVbo, idVbo, textVbo;
protected List<Integer> VBOs;

private int vertexCount;

private float[] vertices, texturePos;
private int[] indices;

private Texture texture;

// TODO: Rinomina texturePos che è brutto
public Mesh(float[] vertices, int[] indices, float[] texturePos, Texture texture){
    this.vertices = vertices;
    this.texturePos = texturePos;
    this.indices = indices;

    this.texture = texture;
}

// Questo metodo è fondamentale per le draw call
// Però deve essere chiamato dopo Renderer#init altrimenti le shader non sono linkate
public void generateBuffers() {
    vertexCount = indices.length;
    VBOs = new ArrayList<>();

    try(MemoryStack stack = stackPush()){
        FloatBuffer verticesBuffer = stack.callocFloat(vertices.length);
        verticesBuffer.put(vertices).flip();

        FloatBuffer textureBuffer = stack.callocFloat(texturePos.length);
        textureBuffer.put(texturePos).flip();

        IntBuffer indicesBuffer = stack.callocInt(indices.length);
        indicesBuffer.put(indices).flip();

        // Crea il VAO e bindalo
        VAO = glGenVertexArrays();
        glBindVertexArray(VAO);

        // Crea il VBO (posizioni) e bindalo
        vertxVbo = glGenBuffers();
        VBOs.add(vertxVbo);
        glBindBuffer(GL_ARRAY_BUFFER, vertxVbo);
        glBufferData(GL_ARRAY_BUFFER, verticesBuffer, GL_STATIC_DRAW);
        glEnableVertexAttribArray(0);
        glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0);

        // Crea il VBO (colori) e bindalo
        textVbo = glGenBuffers();
        VBOs.add(textVbo);
        glBindBuffer(GL_ARRAY_BUFFER, textVbo);
        glBufferData(GL_ARRAY_BUFFER, textureBuffer, GL_STATIC_DRAW);
        glEnableVertexAttribArray(1);
        glVertexAttribPointer(1, 2, GL_FLOAT, false, 0, 0);

        // Crea il VBO (indici) e bindalo
        idVbo = glGenBuffers();
        VBOs.add(idVbo);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, idVbo);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, indicesBuffer, GL_STATIC_DRAW);

        // Unbinda VBO e VAO
        glBindBuffer(GL_ARRAY_BUFFER, 0);
        glBindVertexArray(0);
    } catch(Exception e) {
        // Questo catch serve per Texture#loadImage, altrimenti ogni volta che
        // chiamiamo generateBuffers bisogna aggiungere un throws Exception ai prefab, per esempio.
        e.printStackTrace();
    }
}

public void draw() {
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE0, texture.getTextureId());

    glBindVertexArray(this.getVAO());

    glDrawElements(GL_TRIANGLES, this.getVertexCount(), GL_UNSIGNED_INT, 0);

    glBindVertexArray(0);
}

// Questo metodo di norma va chiamato con GameObject#dispose() direttamente se assegnato ad un gameobject
// così si elimina anche dalla lista dei gameobject.
public void dispose(){
    // Disattiva gli attributi del VAO
    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);

    // Elimina VBOs
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    for(int vboId : VBOs) {
        glDeleteBuffers(vboId);
    }

    // Elimina la texture
    texture.dispose();

    // Elimina VAO
    glBindVertexArray(0);
    glDeleteVertexArrays(VAO);
}

public int getVAO(){
    return VAO;
}

public int getVertexCount(){
    return vertexCount;
}

```

}

I think the problem is the way I'm telling OpenGL not to draw a quad of a cube, which is by setting the indices of that face to -1. That doesn't point to any vertex so it's not rendered but it's still sent to the GPU (?).

Thanks in advance.

# Answer
> 0 votes
It appears you are manually removing faces, rather than using:

> glEnable(GL\_CULL\_FACE)

Although you are using Java, perhaps having a look at this?

---
Tags: opengl, rendering, lwjgl, optimization, mesh
---