# Question
Title: text rendering artifact when rendering in 3D opengl GLfW
Main.cpp

```
//Variables
const unsigned int width = 896, height = 504;

//Initiating GLFW Window
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

//Creating a GLFW window
window = glfwCreateWindow(width, height, "Jaguar", NULL, NULL);

//Checking if Window was initiated
if (window == NULL) {
    std::cout << "GLFW FAILED TO INITIATE WINDOW!\n";
    glfwTerminate();
}

glfwMakeContextCurrent(window);

//Centering Window
int windowWidth, windowHeight;
glfwGetWindowSize(window, &windowWidth, &windowHeight);
const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
glfwSetWindowPos(window, mode->width / 2 - windowWidth / 2, mode->height / 2 - windowHeight / 2);

//Setting-Up window's icon
GLFWimage icon[1];
icon[0].pixels = stbi_load("resources/images/gui/icon/icon.png", &icon[0].width, &icon[0].height, 0, 4);
glfwSetWindowIcon(window, 1, icon);
stbi_image_free(icon[0].pixels);

//Checking if Glad was initiated
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
    std::cout << "GLAD FAILED TO BE INITIATED\n";
}

glEnable(GL_CULL_FACE);
glEnable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

stbi_set_flip_vertically_on_load(true);

//Setting-Up Viewport
glViewport(0, 0, width, height);

//Intitiating MainMenu
states.push(new MainMenuState(*window, &states));

```

font.cpp

```
FT_Library ft;

if (FT_Init_FreeType(&ft)) {
    std::cout << "FREETYPE::Failed to initialize library\n";
}
FT_Face face;
if (FT_New_Face(ft, filePath, 0, &face)) {
    std::cout << "FREETYPE::Failed to load to font: " << filePath << "\n";
}

// set size to load glyphs as
FT_Set_Pixel_Sizes(face, 0, px);

glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

for (unsigned char c = 0; c < 128; c++) {

    if (FT_Load_Char(face, c, FT_LOAD_RENDER)) {
        std::cout << "FREETYPE::Failed to load glpyh\n";
    }
    unsigned int texture;
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, face->glyph->bitmap.width,
        face->glyph->bitmap.rows, 0, GL_RED, GL_UNSIGNED_BYTE,
        face->glyph->bitmap.buffer);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    Character character = {
    texture,
    glm::ivec2(face->glyph->bitmap.width, face->glyph->bitmap.rows),
    glm::ivec2(face->glyph->bitmap_left, face->glyph->bitmap_top)
    ,face->glyph->advance.x };

    Characters.insert(std::pair<char, Character>(c, character));
}
FT_Done_Face(face);
FT_Done_FreeType(ft);

```

text.cpp

```
// activate corresponding render state
shader.use();
glUniform3f(glGetUniformLocation(shader.id, "textColor"), color.x, color.y,
color.z);
glActiveTexture(GL_TEXTURE0);
glBindVertexArray(VAO);

// iterate through all characters
std::string::const_iterator c;
for (c = string.begin(); c != string.end(); c++)
{

    Character ch = font.Characters[*c];

    float xpos = position.x + ch.bearing.x * scale;
    float ypos = position.y - (ch.size.y - ch.bearing.y) * scale;

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

        { xpos,     ypos + h,   0.0f, 0.0f },
        { xpos + w, ypos,       1.0f, 1.0f },
        { xpos + w, ypos + h,   1.0f, 0.0f }
    };
    // render glyph texture over quad
    glBindTexture(GL_TEXTURE_2D, ch.textureId);
    // update content of VBO memory
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    // render quad
    glDrawArrays(GL_TRIANGLES, 0, 6);
    // now advance cursors for next glyph (note that advance is number of
1/64 pixels)
    position.x += (ch.advance >> 6) * scale; // bitshift by 6 to get value in
pixels (2^6 = 64)
}
glBindVertexArray(0);
glBindTexture(GL_TEXTURE_2D, 0);

```

# Answer
> 0 votes
To remove box around text(ASSUMING YOU HAVE GL\_DEPTH\_TEST ENABLED): Disable GL\_DEPTH\_TEST before drawing your text Enable GL\_DEPTH\_TEST after rendering text

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


# Question
Title: How would I add keyframes to my animation clip from another object in Unity?
I am creating an FPS game which will have many weapons that have their own animations. I will need to access keyframes of the character's position, rotation, and scale, how will I do that? I can only add keyframes from the object I'm animating, or, I can only add keyframes from a child object.

# Answer
> 0 votes
Nevermind, I just animated the character itself and made the gun a child lol.

---
Tags: unity, animation, animator
---


# Question
Title: Extend distance for rendering grass and tree objects on terrain
I am trying to make an adventure game with a big landscape (made the terrain with terrain tools) with 3D models of grass (that I placed using terrain tools) but it only shows the grass/trees that are within a small area. Here is a pic of what I am talking about:

I would not want to totally remove this because otherwise the framerate will go too low. I just want to make the circle bigger.

thanks (:

# Answer
> 0 votes
Never mind I just couldn't find the tree distance (: There are so many little things that don't tell you that it even exists or how to find it.

---
Tags: unity, 3d, terrain-rendering
---


title: UE 4.25 - Can't create EQS assets

text:
# Question
Title: UE 4.25 - Can't create EQS assets
Like the title says I am unable to create EQS assets. I am running 4.25 and there is no option in the BT details panel, nor under "Add assets -\> AI". AND there is no option to activate it. Neither under settings or under plugin. Nothing.

What am I doing wrong? See screenshots and thanks in advance

# Answer
It's in `Editor Settings / Experimental`, as per documentation (EQS Quick Start):

Here is my own screenshot from `4.25.4`:
> 0 votes

---
Tags: unreal-4
---


# Question
Title: How can I improve the seemingly capped framerate of my flash game?
I used to be sure that all Flash games are capped to 30fps as Edmund McMillen's The Binding of Isaac runs at that frame rate.  `v2.0` (Flash Player 11) runs at 60fps.

Why do games developed in Flash seem to have capped frame rate?
What are the limits on the fps when developing in Flash?

# Answer
According to AS3 documentation:

> frameRate:
>
> Gets and sets the frame rate of the stage. The frame rate is defined as frames per second. By default the rate is set to the frame rate of the first SWF file loaded. Valid range for the frame rate is from 0.01 to 1000 frames per second.
>
> Note: An application might not be able to follow high frame rate settings, either because the target platform is not fast enough or the player is synchronized to the vertical blank timing of the display device (usually 60 Hz on LCD devices). In some cases, a target platform might also choose to lower the maximum frame rate if it anticipates high CPU usage.

flash.display.Stage.frameRate
> 2 votes

# Answer
Flash Player has frame rate capped to 60, ignoring `Stage.frameRate` = 1000 property since FP10. In `Flash Player 9.0c`, both frame rate and timer resolution can be set to 1000 (millisecond-accurate).
> 2 votes

# Answer
Meanwhile, the max. framerate has been extended to **120 fps**
> 0 votes

---
Tags: flash, frame-rate
---


# Question
Title: How can I prevent players from reading a puzzle solution out of the game's code?
I'm sure you know of the part in Five Nights at Freddy's 3 where you input the reverse of the hex code for purple into a wall and something happens (I forget what).

I want to implement something similar in a game I'm making, but I'm worried about people looking at the code for the game or hacking into it to figure out what to do.

I wonder whether fnaf somehow prevented people from just decompiling the code and seeing what code to enter. How could I do something similar?

# Answer
> 2 votes
The first step is managing expectations.

Remember that "the client is in the hands of the enemy" — if you're making an offline game, then you're giving your attacker both the lock and the key. If the game is able to verify the solution to the puzzle, then a skilled attacker can use that verification routine to determine the solution to the puzzle.

You can make it somewhat more challenging, but for the sizes of solutions that are comfortable for a player to deduce and enter through play, it's still likely to be computationally tractable to brute-force.

The only way to make it properly impossible to work around is to take the key out of the client entirely, putting any secret information on a server you control, and restricting access to it (say, no more guesses per hour than a player could execute by hand)

That said, there are things you can do to make finding the secret less trivial — hopefully to the point where playing the game seems like a more fruitful and enjoyable way to solve the puzzle than hacking at the code. I wouldn't invest a lot of effort here, since as pointed out above a determined adversary *will* win, but we can raise the bar to block "mildly curious" adversaries cheaply enough, if they're all you expect to face.

One simple route is using a cryptographic hash function.

You take your puzzle solution, add some extra characters to it (a "salt"), then hash the combined text. What you get out is some blob of random-looking bytes that isn't your solution anymore, and should (for a well-designed hash function — use a well-studied one, DO NOT invent your own) resist decoding it to reveal the original input.

You put this hash value and its salt into your game data. When your game wants to check if the player entered the right solution to the puzzle, it takes the text the player entered, adds the salt to it, and hashes the result. Because you're using the same salt and same hash function, the output will exactly match your saved hash value if the player entered the right solution.

So now your game can check the solution to the puzzle even without the literal solution being present in the code or data.

(This is how websites and other software verify your login credentials without storing your password where a bad actor could easily find it)

This can still be defeated, of course. An attacker can build a program that exhaustively runs each possible answer through this salting and hashing process until they find a match, but at least they can't just glance at your binaries and read the answer in plain text, or look it up in a rainbow table.

(What they might do instead is just replace your check function with `bool IsAnswerCorrect(string answer) { return true; }` and skip the puzzle entirely to just find out what's on the other side — but again, you can't stop this unless you hide all that stuff on a server out of their reach)

So while it's not ironclad, this hashing approach is reasonably quick and cheap to do with standard components, so at least you're not going down a rabbit hole fighting a war you won't win. You can hack this up in half an hour or less, feel a bit better that your puzzle isn't completely trivial to cheat, and move on to other features that have a bigger impact on player experience.

# Answer
> -1 votes
1)Scan for dll injections.

2)Scan for memory hooks.

3)Check compiled source code memory pages checksum sometimes.

Its 3 most popular ways to hack.

---
Tags: security
---


# Question
Title: Extending a ScriptableObject to have a get property instead of a field, without losing serialized data
I have a ScriptableObject that's already used extensively in my project:

```
public class SFXClip : ScriptableObject
{
    public AudioClip clip;

    // other properties
}

```

I want to extend it to a derived version something like this:

```
public class SFXRandom : SFXClip
{
    [SerializeField] List<AudioClip> audioClips;

    override public AudioClip clip
    {
        get
        {
            return audioClips[Random.Range(0, audioClips.Count)];
        }
    }
}

```

But of course, I can't do that without making the `clip` field on the original object into a `virtual` property. If I do that, I'll lose all the `AudioClip` references in existing `SFXClip` instances in my project's Assets.

Is there a way I can implement this change without losing that data?

# Answer
> 1 votes
Here's a cool trick you can use:

```
using UnityEngine.Serialization;

public class SFXClip : ScriptableObject
{
    [SerializeField, FormerlySerializedAs("clip")]
    private AudioClip _clip;

    public virtual AudioClip clip {
        get { return _clip; }
        set { _clip = value; }
    }

    // other properties
}

```

The `FormerlySerializedAs` attribute from the `UnityEngine.Serializaton` namespace allows you to migrate saved parameters from an old name to a new one.

When the serializer doesn't find a member named `_clip` in the saved asset, it will look for one with its old name, `clip`. If it finds one, it will use that value for the new field.

When you next open and save your asset, it will be saved under the new name. So this way, you can migrate this field to be a property you can override, with no data loss.

To migrate the data from a field into a list, we need a method to do the data fix-up after the object has been deserialized:

```
public class SFXClip : ScriptableObject {
    [SerializeField] List<AudioClip> audioClips;

    [SerializeField, HideInInspector, FormerlySerializedAs("clip")]
    AudioClip _legacyClip;

    void OnValidate()
    {
        if (_legacyClip == null) return;

        if (!audioClips.Contains(_legacyClip))
            audioClips.Add(_legacyClip);

        _legacyClip = null;
    }
}

```

This gets called on assets included in a build during the build process, or referenced in an open scene or selected object in the inspector. Once the old data has been successfully updated and saved, you can delete this code - although it's not called in a built executable anyway (only in editor), so it doesn't add significant overhead.

---
Tags: unity, c#, oop, serialization, scriptable-object
---


# Question
Title: What exactly is different between a string and an FString in Unreal C++?
Sorry, maybe a noob question, I did a quick google search and couldn't find what I was looking for. I have two related questions about FString.

1. Does regular C++ Have this, or is this an Unreal term. (I know python has a variable called FString).
2. What makes FString different from the String variable?

thnx. It's not very necessary for development, but I'm just curious why Unreal uses FString instead of String.

# Answer
`FString` (and all types that are prefixed with `U`,`F`,`T` etc.) are custom Unreal Types.
They have special behaviour and work hand-in-hand with Unreal's Typesystem and Garbage Collection.

Use `string` and other raw types if you want to program plain C++ Code. Use the Unreal Types if you want to interface with your Game.
> 5 votes

---
Tags: architecture, unreal-4
---


title: Mesh seams visible in Unity

text:
# Question
Title: Mesh seams visible in Unity
I'm currently working on a procedurally generated sphere but I can't get rid of those seams between the meshes. My first step is to generate a cube and normalize all vertices. I've already search the internet for solution but I never achieved a full removal only just made less visible the seams.

Correct me if I'm wrong but the root cause is this: Unity uses per vertex normals for creating smooth shading instead of flat shading and at the mesh edge the normals are not correctly calculated by the built-in RecalculateNormals method.

So the solution what I found: during vertex generation of a mesh also create border vertices and Unity will calculate correct normals and after that I remove border vertices and triangles from the mesh.

Here you can see seams without any fix:

I tried to generate border for every side of the cube, call RecalculateNormals on the Mesh object and reassign vertices, indices and normals without the border. The result is better but not perfect (Solution A):

I was thinking about this border. If I generate one strip border and I normalize also the border vertices then these border triangles won't be there where adjacent mesh's edge triangles are located:

So I tried to move the border vertices to overlap the adjacent mesh's most outer triangles (most outer strip):

And the result is almost perfect but the borders are visible (Solution B):

Is it possible to remove seams fully? I want to use that solution where I just create border on the plane of the current mesh and not move to adjacent mesh. It's easier to create meshes with one unit wider.

**EDIT1**

This code is used for generation. I collect mesh/border vertices and indices in separate lists in the MeshData object.

```
private MeshData CalculateMeshData()
{
    MeshData meshData = new MeshData();
    meshData.ChunkSize = CHUNK_SIZE;
    meshData.BorderSize = BORDER_SIZE;

    int borderedResolution = meshData.BorderedResolution;
    int vertexIndex = -1;
    float faceWidth = _radius * 2 / CHUNK_SIZE;
    float currentYPosition = -_radius - faceWidth * BORDER_SIZE;

    for (int y = 0; y < borderedResolution; y++)
    {
        float currentXPosition = -_radius - faceWidth * BORDER_SIZE;
        for (int x = 0; x < borderedResolution; x++)
        {
            bool isMeshVertex = !IsBorderVertex(x, y, borderedResolution);
            Vector3 axisAOffset = _axisA * currentXPosition;
            Vector3 axisbOffset = _axisB * currentYPosition;
            Vector3 pointOnUnitCube = _center + axisAOffset + axisbOffset;
            Vector3 vertex = pointOnUnitCube.normalized;

            vertexIndex++;
            meshData.AddVertex(vertex, isMeshVertex);

            // Prevents to create more two triangles next to the edge of the mesh.
            if (x != borderedResolution - 1 && y != borderedResolution - 1)
            {
                bool isMeshTriangle = IsMeshTriangle(x, y, borderedResolution);
                meshData.AddTriangle(vertexIndex,
                                         vertexIndex + borderedResolution + 1,
                                         vertexIndex + borderedResolution,
                                         isMeshTriangle);

                meshData.AddTriangle(vertexIndex,
                                     vertexIndex + 1,
                                     vertexIndex + borderedResolution + 1,
                                     isMeshTriangle);
            }

            currentXPosition += faceWidth;
        }

        currentYPosition += faceWidth;
    }

    return meshData;
}

```

And here is the mesh creation:

```
private void GenerateMesh()
{
    // Creates object and its components.
    _meshObject = new GameObject("mesh");
    _meshFilter = _meshObject.AddComponent<MeshFilter>();
    _meshRenderer = _meshObject.AddComponent<MeshRenderer>();
    _meshRenderer.material = Shape.Material;
    _mesh = new Mesh();
    _meshFilter.sharedMesh = _mesh;

    // Creates the mesh and calculates normals with the border faces.
    MeshData meshData = CalculateMeshData();
    _mesh.vertices = meshData.GetVertices(true);
    _mesh.triangles = meshData.GetIndices(true);
    _mesh.RecalculateNormals();

    // Recreates mesh without the border.
    Vector3[] normals = _mesh.normals;
    _mesh.Clear();
    _mesh.vertices = meshData.GetVertices(false);
    _mesh.triangles = meshData.GetIndices(false);
    _mesh.normals = meshData.GetMeshNormals(normals);
}

```

The GetVertices and GetIndices method has a switch which controls whether mesh data returned including border or not.

The GetMeshNormals method returns normals for the mesh without the border.

# Answer
> 2 votes
The problem is that `RecalculateNormals` doesn't know about the adjacent meshes.

It works similar to the code I show in this answer: for each face in your mesh, it calculates a face normal. Then for each vertex, it averages-together the normals from each face it touches, proportionate to the area of those faces.

Let's take a vertex in the middle of your mesh. It's surrounded by faces...

* to its right, with a normal leaning slightly to the right (+x)
* to its left, with a normal leaning slightly to the left (-x)
* in front of it, with a normal leaning slightly forward (+z)
* behind it, with a normal leaning slightly backward (-z)

All these slight leans cancel out when we average the normals, and you're left with a normal that points straight out along the line joining the vertex to the sphere's center.

Now let's take a vertex on the edge of your mesh. It's missing faces on one side to counter-balance the leaning of the normals from faces on the other side. So it gets a normal appropriate to those faces that are present in the mesh, without considering the absent faces beyond the edge. The result is a slight bias inward toward the center of your mesh.

The simplest solution here is to just calculate your own normals. If your mesh is a sphere, you can take the vector from the sphere's center to your vertex and normalize that. Now it's exactly the vertex normal you want, no matter whether it's on the edge of your mesh or somewhere in the middle. And the calculation is consistent, so the next mesh chunk you generate will exactly agree with this normal at the place where they meet. This may even be more efficient than `RecalculateNormals` since you're saving it the work of computing and summing the face normals.

If you're displacing your sphere (eg. with noise functions), then this gets a bit more complicated, but computing exact normals analytically is often possible, and where it's not, we can find ways to compute normals in a consistent way using eg. partial differences. But we'll need a new question with details of your deformation/displacement method to be able to advise on the specifics here.

---
Tags: unity, procedural-generation, seams
---


# Question
Title: Why do I get a jitter/stutter when moving and following a target?
I am using the script below to move a transform to quickly follow a target (the player), and come to a stop close to the player.

When I move the player around, the transform is following the player, keeping the 1.5 distance.

To ensure the transform can keep up with the player, I set the `moveSpeed` to 5, But when I do that, the transform jitters/stutters when moving.

If I set the `moveSpeed` to 1 for example, the transform will move smoothly but will not keep up with the player - the player has to stop moving and wait for it to catch up. But increasing the speed makes the stutter return.

Why is this stutter happening, and how can I make the movement smooth?

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

public class Follow : MonoBehaviour
{
    public Transform targetToFollow;
    public Text text;
    public Text text1;
    public float lookAtRotationSpeed;
    public float moveSpeed;

    private float minMoveSpeed = 0f;
    private Vector3 originPos;

    // Start is called before the first frame update
    void Start()
    {
        originPos = targetToFollow.position;
    }

    // Update is called once per frame
    void Update()
    {
        Vector3 lTargetDir = targetToFollow.position - transform.position;
        lTargetDir.y = 0.0f;
        transform.rotation = Quaternion.RotateTowards(transform.rotation,
            Quaternion.LookRotation(lTargetDir), Time.time * lookAtRotationSpeed);

        var distance = Vector3.Distance(transform.position, targetToFollow.position);

        text.text = "Transform Distance From Target " + distance.ToString();

        float ms = moveSpeed;

        if (distance > 5f)
        {
            ms = moveSpeed + 0.5f;
        }
        else if (distance < 1.5f)
        {
            ms = Mathf.Max(minMoveSpeed, ms - 0.3f);
        }
        else
        {
            //transform.position = Vector3.MoveTowards(transform.position, targetToFollow.position, Time.deltaTime * ms);
        }

        if (distance < 0.5f && originPos == targetToFollow.position)
        {
            ms = 0f;
        }

        if (distance > 1.5f)
            transform.position = Vector3.MoveTowards(transform.position, targetToFollow.position, Time.deltaTime * ms);

        originPos = targetToFollow.position;
    }
}

```

# Answer
You have two hard cutoffs in your code:

```
if (distance > 5f)
{
    ms = moveSpeed + 0.5f;
}

```

This switches to a higher seed if the object is more than 5 units away.

```
if (distance > 1.5f)
    transform.position = Vector3.MoveTowards(transform.position, targetToFollow.position, Time.deltaTime * ms);

```

This moves the object only if the object is more than 1.5 units away.

Consider what happens when your distance is *close* to one of these thresholds.

* On frame 1, I'm 1.51 units away.

That's more than 1.5, so **I take a step** of .16 units, now I'm 1.34 units away
* On frame 2, my target has moved .1 units further away, so now I'm 1.44 units from it.

That's less than 1.5, so **I don't move**.
* On frame 3, my target has moved .1 units again, so now I'm 1.54 units from it.

That's more than 1.5, so **I take a step** of .16 units, now I'm 1.38 units away.
* On frame 5, my target has moved .1 units again, so now I'm 1.48 units from it.

That's less than 1.5, so **I don't move**.

You can see, instead of approaching at a slow rate to keep pace with the object I'm following, I stop and start. On alternating frames I find myself too far (so I move and overshoot) or too close (so I stop), creating a jerky, stuttering movement.

The same thing can happen more subtly at the 5 unit cutoff, where I alternate between taking big steps (because I'm just past 5 units) and small steps (because I'm just under 5 units).

You can solve the hard movement cutoff by aiming for the place where you would want to stop. That way you take a smaller move when you're very close, rather than overshooting.

```
float followRadius = 1.5f;

// Compute a position no further than followRadius away from our target.
Vector3 fromTarget = Vector3.ClampMagnitude(-lTargetDir.normalized, followRadius);
Vector3 stopPoint = targetToFollow.position + fromTarget;

// Move as far as we can at our speed ms to reach the stopPoint, without overshooting.
transform.position = Vector3.MoveTowards(transform.position, stopPoint, Time.deltaTime * ms);

```

To solve the sharp speed change you get at the 5 unit mark, you can blend the speed gradually over a longer distance, something like...

```
float fastRadius = 5f;
float speedBoost = 0.5f;

float speedBlend= Mathf.Clamp01((distance - followRadius)/(fastRadius-followRadius));

ms = moveSpeed + speedBlend * speedBoost;

```

This has you moving at your normal move speed when close to the `followRadius`, and at your faster speed when at/beyond your `fastRadius`, with a smooth acceleration/deceleration in between.
> 0 votes

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


# Question
Title: Visual Studio not adding the header file to the Solution explorer
I'm having trouble with my Unreal Visual Studio 2019 project. I created a new header file, and saved it in the same folder my other ones are in. (I didn't add these, they were in the starter project of the video course I'm following.) For some reason, the file is not showing in the solution explorer, and IntelliSense isn't working in the particular file. How do i fix this? sorry if it's obvious, I'm not an expert at Visual Studio.

# Answer
> 0 votes
Solved it, I needed to add it to the project.

---
Tags: unreal-4, visual-studio
---


# Question
Title: Ini files only work on my computer. How to create ini files in a directory on another computer?
I am creating a game that requires the use of ini files.

The game works perfectly on my computer.

When I create and executable, the executable even uses the ini files when I am programming/testing the game on the engine.

**Directory where the ini files are located:**

```
D:\Users\BonecoSinforoso\AppData\Local\Brasmotor_1

```

The problem occurs when a person from another computer tries to play. The game does not create any ini files.

Even placing the ini files in the zipped file that I put the game on, it gives an error. Because the ini files don't go to a directory that the game can read.

I would like to know how to make my executable create or move the ini files to a directory where the files can be read.

---

**EDIT 1**

**How do I create the ini files:**

```
ini_open("config.ini");
    arkivoIdioma=ini_read_string("jogoIdioma","arkivoIdioma","");
    dadosNum=ini_read_real("dadosNum","dadosNum",1);
    paradaModo=ini_read_string("paradaModo","modo","automatico");
    paradaPorcAutomatico=ini_read_real("paradaPorcAutomatico","porcentagem",10);
    paradaPorcAviso=ini_read_real("paradaPorcAviso","porcentagem",10);
ini_close();

```

**Searching about, I found something explanatory about the directory:**

> The ini files get created. Probably you are not looking in the right place for it. The ini file get created in %AppData%/Local/"YourGameNameHere" folder, that's where you'll find all the files you save.

BY JM DG.

**LINK:**

https://www.reddit.com/r/gamemaker/comments/5d6pf0/how\_do\_i\_create\_a\_new\_ini\_file/

**Error obtained by a user:**

A little earlier, I made a change to the line of this script. I will wait for this user to test again to see if the error has been resolved.

# Answer
> 0 votes
**To solve the problem. Just add the ini files to the game's zipped file:**

**And adapt the opening code of the zip file:**

`ini_open("config.ini");` -\> `ini_open(working_directory+"config.ini");`

---
Tags: game-maker
---


# Question
Title: How do you detect which side of a cube is facing up/down/left/right?
Please imagine a scene that shows a cube. Both the camera and the cube can be randomly positioned and rotated. How can you tell which side of the cube is facing up/down or left/right?

Or in other words: What's the math to find a cube's orientation in relation of the camera?

Your advise is very much appreciated. Thank you.

**Edit:** Here's a screenshot:

The camera is "locked" onto the cube. I.e. one of it's sides is facing directly into the camera. Both cube and camera are rotated in 90 degree steps, so that each face of the cube is always in parallel to the camera's axis's. How can you tell which face (or color in the screenshot above) is pointing left/right/up/down?

Thank you!

# Answer
> 1 votes
First let's label each cube face.

I'll do this in a specific order, with the negative axes first, then the positives. ±z are on the outside edges of the list, and ±x are on the inside. I'll leave a default/unassigned value in the middle of the range.

```
public enum CubeFace: sbyte {
    Back   = -3,  // -z
    Bottom = -2,  // -y
    Left   = -1,  // -x
    None   =  0,
    Right  =  1,  // +x
    Top    =  2,  // +y
    Front  =  3   // +z
}

```

Now, since you've locked your camera/cube to 90-degree rotations, once we transform the camera's direction into the cube's orientation, we know it has to be (±1, 0, 0) or (0, ±1, 0) or (0, 0, ±1), (or within a small rounding error of these six values). By multiplying x, y, and z by 1, 2, and 3 respectively, we get the corresponding enum value.

```
public CubeFace FaceInDirection(transform cube, Vector3 worldDirection) {
    var local = cube.InverseTransformDirection(worldDirection);

    int code = Mathf.RoundToInt(local.x + 2 * local.y + 3 * local.z);

    return (CubeFace)code;
}

```

Now you can get the face in a particular camera direction like so...

```
var rightFace  = FaceInDirection(cubeTransform,  cameraTransform.right);

var topFace    = FaceInDirection(cubeTransform,  cameraTransform.up);

var facingFace = FaceInDirection(cubeTransform, -cameraTransform.forward);

```

etc.

---
Tags: unity, 3d, mathematics
---


# Question
Title: Is it okay to update the graphical handlers in the same function where you render them?
I have a class called 'GraphicalHandler' that all my graphical handlers inherit from the main game loop. The class manages a static vector of pointers to all instances of itself. I can then call the member fucntion GraphicalHandler::drawAllInstances() to draw everything to the screen.

But since my graphical handlers need to update their graphical objects, as well as rendering them, I figured I would change the function to updateAndDrawAllInstances(). I know that game logic and rendering should be as separated as possible, but since updating the graphical handlers doesn't seem like game logic I figured it would be valid.

So my question is if this is 'accepted' in game development, i.e. to update and render the graphical objects in the same function.

# Answer
I'd advise not worrying about what's "accepted" or "OK". These things do not matter.

Very successful games have shipped with absolute nightmares lurking in their code. Nobody decompiles the game and docks your Metacritic score or claws back your sales because you didn't follow the "best practice" (whatever that might be interpreted to mean).

Instead, if you know common advice often points against a particular practice, examine **what are the *consequences* of that practice** that lead folks to advise against it. Could those consequences be a problem for your game, now or in the future? *That* would be the reason to avoid the practice: concrete impacts it has on your game and development, *not* because it's "unaccepted".

So, let's look at some consequences that come from bundling together your update and rendering into one call:

* **This locks your simulation time step to your rendering frame rate.**

+ If you render with a variable frame rate, then this variability in your update timing can make your game behave inconsistently, depending on the hardware it's running on or the load on the system. This can change your game feel or even impact the game's fairness.
    + If you lock your framerate, then you've forced even players with super-powerful gaming rigs to play at the same framerate as your minimum recommended hardware. And if ever under load you miss the next frame deadline, you'll get a very visible stall/hitch in the gameplay.

For reasons like these, games often prefer to decouple simulation from rendering, stepping the simulation at a fixed time step while the rendering is free to run as fast as the hardware allows. I go into more detail about these reasons, and benefits we get from this strategy, in this answer.

Even if you're not planning on using this strategy at present, you might want to switch over to it in future. The more tightly bound-together your update and rendering are in your base version, the more refactoring work you'll need to put in down the line if you ever want to change that.
* **This mixes-together very dissimilar work, which may impact performance due to memory access patterns.**

+ Each time you call a function or touch data you haven't touched in a while, the processor needs to pull the memory containing those instructions or data into its cache, and that's very slow.

    If you're doing something consistent, like always fetching the next sprite from an array to add to a draw batch, the processor can often predict the next chunk of memory you'll need and pre-fetch it to minimize this wait time.

    But if you mix together lots of different operations - like running an AI script (that needs to read memory about its patrol path or targets), updating object positions (that needs to store transformations to memory), processing collisions (using memory about colliders), updating health, spawning particles, etc... *then* drawing the next sprites, ...then this memory access looks super random, and the processor will have a hard time guessing what you'll need next.

    And this compounds: by the time you get to updating the positions of the *next* batch of objects, you might have done so many other things in between that the instructions for how to update object positions got kicked out of the cache, so you need to wait to haul them back in again.
    + Compare this versus doing all your random-accessing gameplay logic first, then doing all your drawing at the end. A lot of the drawing routines will be working with similar code - calling the same graphics API methods to submit draw calls and such. So they'll often find the instructions they need are still warm in the cache from the previous drawing action, and be able to proceed that much faster.
* **This clusters multiple different responsibilities in one place.**

This doesn't have as immediate an impact on your game, but it can affect the experience of development as you try to grow and evolve it.

+ Let's say one member of your team is working on optimizing the updates of game objects, to skip over static/dormant objects that don't need an update this frame and save some processor cycles.
    + Another team member is working on changing the sorting of draw calls for rendering, so you get less overdraw and better performance on low-end graphics cards.
    + They go to submit their changes, but they have a merge conflict, because they're both modifying the same files in mutually-contradictory ways. The grouping of multiple responsibilities in one code path creates extra friction your team needs to work around to accomplish their goals.
    + You also get a bug, because the first coder changed the update logic of the first 3 `GraphicHandler` classes, but missed updating the fourth `GraphicHandler` to match. Because the update logic is duplicated or called from multiple different classes not obviously related to game update order, it's easy to make a change in one place and miss the corresponding changes needed in the other place.
    + Together, these aspects increase the cognitive load of working with the system, or learning about it when ramping up a new team member. If the update and drawing sections were completely separate, then you could ramp up a new graphics programmer by showing them just the drawing code, and you can better isolate where a bug affecting one particular system might be coming from.

Because of scenarios like the above, we have principles like "Don't Repeat Yourself (DRY)" and "The Single Responsibility Principle (SRY)" to remind us that while this code might *work*, *now*, it's often setting us up for extra complexity and avoidable problems down the line.

So, these types of effects are the *consequences* that lead game devs to recommend separating game simulation updates from rendering.

You might find, after examining the issue in detail, that these consequences are not a concern for your game, and choose to proceed as you initially proposed. That's fine. The trick is to always make your decisions based on the real *effects* of a choice, not on whether or not some strangers on the Internet would "accept" or "approve" of it.
> 1 votes

---
Tags: rendering, software-engineering, game-loop
---


# Question
Title: How to make the transform to slow down when he come from a far distance and getting close to the target?
```
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;

public class Follow : MonoBehaviour
{
    public Transform targetToFollow;
    public Transform missionTarget;
    public Text text;
    public Text text1;
    public float lookAtRotationSpeed;
    public float moveSpeed;
    public float followRadius = 1.5f;
    public float fastRadius = 5f;
    public float speedBoost = 0.5f;

    void Start()
    {

    }

    // Update is called once per frame
    void FixedUpdate()
    {
        Vector3 lTargetDir = targetToFollow.position - transform.position;
        lTargetDir.y = 0.0f;
        transform.rotation = Quaternion.RotateTowards(transform.rotation,
            Quaternion.LookRotation(lTargetDir), Time.time * lookAtRotationSpeed);

        float ms = moveSpeed;
        var distance = Vector3.Distance(transform.position, targetToFollow.position);
        text.text = "Transform Distance From Target " + distance.ToString();

        // Compute a position no further than followRadius away from our target.
        Vector3 fromTarget = Vector3.ClampMagnitude(-lTargetDir.normalized, followRadius);
        Vector3 stopPoint = targetToFollow.position + fromTarget;

        // Move as far as we can at our speed ms to reach the stopPoint, without overshooting.
        transform.position = Vector3.MoveTowards(transform.position, stopPoint, Time.deltaTime * ms);

        float speedBlend = Mathf.Clamp01((distance - followRadius) / (fastRadius - followRadius));

        moveSpeed += speedBlend * speedBoost;

        text1.text = "Transform Speed " + ms.ToString();
    }
}

```

I didn't understand how to work with the bottom part :

```
float speedBlend = Mathf.Clamp01((distance - followRadius) / (fastRadius - followRadius));
moveSpeed += speedBlend * speedBoost;

```

I tried to set here instead += to -= and then set it back to += and change the speedBoost here to be negative added the minus before it or in the inspector made it minus but then the transform is moving away from the target.

What I want to do is that if the transform when the game is starting is far from the target more then 5 for example the distance is 10 or 30 when the transform is getting close to the followRadius he just stop at once and instead I want it to slow down and stop at the follow Radius depending if the target is moving or not. If not moving slow down and stop at the follow radius if the target is moving slow down and move in the follow radius.

The main goal is to create a slow down effect when the transform is reaching the target from far.

This is what I tried according to the solution :

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

public class Follow : MonoBehaviour
{
    public Transform targetToFollow;
    public Text text;
    public Text text1;
    public float lookAtRotationSpeed;
    public float moveSpeed;
    public float followRadius = 1.5f;
    public float fastRadius = 5f;
    public float speedBoost = 0.5f;

    void Start()
    {

    }

    // Update is called once per frame
    void FixedUpdate()
    {
        Vector3 lTargetDir = targetToFollow.position - transform.position;
        lTargetDir.y = 0.0f;
        transform.rotation = Quaternion.RotateTowards(transform.rotation,
            Quaternion.LookRotation(lTargetDir), Time.time * lookAtRotationSpeed);

        float ms = moveSpeed;
        var distance = Vector3.Distance(transform.position, targetToFollow.position);
        text.text = "Transform Distance From Target " + distance.ToString();
        // Compute a position no further than followRadius away from our target.
        Vector3 fromTarget = Vector3.ClampMagnitude(-lTargetDir.normalized, followRadius);
        Vector3 stopPoint = targetToFollow.position + fromTarget;

        // Compute a speed that's faster when far away and slower when close.
        float speedBlend = Mathf.Clamp01((distance - followRadius) / (fastRadius - followRadius));

        ms = moveSpeed + speedBlend * speedBoost;

        // Move as far as we can at our speed ms to reach the stopPoint, without overshooting.
        transform.position = Vector3.MoveTowards(transform.position, stopPoint, Time.deltaTime * ms);
    }
}

```

And the values in the inspector :

The main problem is that it's stuttering again. The code is in FixedUpdate.

If I'm settings the moseSpeed to 0 and the Speed Boost to 3 the transform is not moving at all. Only with this settings and I'm not sure if they are fine the transform is a bit slowing down when getting close to the target. I had to set the Fast Radius to 1.5 to make it slow down.

# Answer
You copied the code I gave you incorrectly.

`moveSpeed += speedBlend * speedBoost;` is wrong.

You want what I wrote in my answer: `ms = moveSpeed + speedBlend * speedBoost;`.

This line should come *before* you try to move with that speed with `MoveTowards`:

```
    // Compute a position no further than followRadius away from our target.
    Vector3 fromTarget = Vector3.ClampMagnitude(-lTargetDir.normalized, followRadius);
    Vector3 stopPoint = targetToFollow.position + fromTarget;

    // Compute a speed that's faster when far away and slower when close.
    float speedBlend = Mathf.Clamp01((distance - followRadius) / (fastRadius - followRadius));

    ms = moveSpeed + speedBlend * speedBoost;

    // Move as far as we can at our speed ms to reach the stopPoint, without overshooting.
    transform.position = Vector3.MoveTowards(transform.position, stopPoint, Time.deltaTime * ms);

```

Once you write the code correctly, you can just set your `moveSpeed` parameter to a small value (maybe as low as zero) and your `speedBoost` parameter to a large value to get fast movement when far and slow movement when close.

Or you can reframe this as a lerp:

```
float slowestSpeed = 0;
float fastestSpeed = 5;

ms = Mathf.Lerp(slowestSpeed, fastestSpeed, speedBlend);

```
> 0 votes

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


# Question
Title: Is it legal to add a cameo appearance of a known video game character in my game?
If I am not going to name the character and I use my own original art that very closely resembles a well-known video game character that appears in my game for a very brief moment, is it legal to add a cameo appearance of the character in my game? In an indie game and meant as a tribute to the original game, but I doubt that makes any difference.

Example 1: A scrolling 2D platformer with Super Mario in one level performing a single action and dissapearing afterwards. Not naming the character at all.

Example 2: A video game poster inside the game with Sonic The Hedgehog with or without naming the character, with or without Sega logo.

---

* Fair use doesn't apply here, as I won't be using the art verbatim.
* The game might make some money
* I don't need to use names, since it is not really necessary, but there is no problem attributing the character trademark holder
* **I am not going to hold anyone responsible for their answers, you don't need to say "I am not a lawyer"** I know a lawyer will probably give me the best answer, but so will probably do indie game developers who used something similar in their game. This is what I am looking for.
* The examples given are not real. Just analogy.

# Answer
> 4 votes
### Legal issues

It depends, there are elements that are copyrighted and there are elements that are not.

In case they are - it's illegal. Well, not illegal, but you may run into legal issues.

Then, there is this parody law. I'm not a US resident, nor I know about it here - hence no link.
For one of my projects, I had a discussion with related people, and they said that if you use something for / in parody, you will not run into legal issues. (*Yeah, yeah, he said, she said, they said, they heard, we heard, you heard*).
Probably someone with law background will be able to provide more information about this.

### Easter eggs (eeggs)

In video games, these parodies may fall under specific feats, named Easter Eggs.

One of the best examples is World of Warcraft. The game is full of eeggs, some cameo appearances (though, official - Mr. T, Ozzy Osbourne) and such.

Speaking of WoW's eeggs, the one that has left the best memories in my mind is this guy with a little quest chain. He's called Harrison Jones \- Harrison Ford \+ Indiana Jones.

Here is a list of some of the eeggs found in WoW. And, here is a list of pop-culture and other jokes found throughout the game.

### Blizzard

Actually, Blizzard puts a load of eeggs in their titles. Not always they are parodies, but they have some from time to time.

There are probably other companies out there that put such eeggs in games. I just don't know about them, am more of a competitive gamer, sticking to one game, not playing everything.

### Why did I brought eeggs up?

Well, for your Mario example, go on, copy the sprites over, maybe change the scene, like, making the Mario eat a banana in the background. Also, change his name to Wario.

The idea is that people do not need the real Mario in your game - he has his own ones, -and they are the best.
What the eegs serve for, is the reference. People will always get it if they know about it, and will have much greater laugh about it than if you had actual Mario in there.

As for the sonic... Name him the other way around - "Cinos", make him roll backwards, make him pink. Instead of jumping, make him dig beneath the ground. Instead of rings, make him eat tendrils that form a shape of a ring.

Use your imagination, and let the people find out what have you referred to there. They will still see it as a tribute. I doubt you'd bother that much for a Sonic if you didn't like it.

# Answer
> 1 votes
To answer the wording of the question: You will never go to prison or have to pay a fine for including a video character from another universe in your game. In that sense, it's not illegal.

You might however be liable to claims of the copyright owner for licenses or damages. What's worse, **the copyright owner can file charges against you even if there's no legal footing for their claim**, simply to make things expensive for you. Some rights holders are very protective and will ask you for money even if the legal framework doesn't require you to pay them, and they will at least threaten to take you to court if you don't pay up.

Consider asking the rights holder for permission first. If you don't want to risk them saying no, consider asking another developer who used a character belonging to the same rights holder how it turned out for them.

# Answer
> 0 votes
Note: I'm not a lawyer, which is really who you should be talking to about this.

U.S. law provides certain protections for parodies and the like. Ultimately, though, whether or not you get in trouble depends on just how close your art and usage are to the original and what your intent is for including it.

From your explanation, it sounds to me *(remember, not a lawyer, here)* like you should be okay. It doesn't sound like something that the original rights holder would bother with.

# Answer
> -2 votes
To answer your question straight out.... YES, it's illegal, because your placing a copyrighted character in your own game for profit. But, if you where using a copyrighted character for your own personal use to mod a game or create personal artwork to show off to friends etc. without profit or to give away for free then it's not illegal.
The same goes for copyrighted ideas unless you get legal permission from the copyrighted owners.

---
Tags: legal
---


# Question
Title: How do I get a reference to a component on a sibling object in C# Script?
I'm working on a game, where the player dumps trash from Trash cans into a Trash Truck. These Trash cans have a random chance of having a Racoon on top of them.

I have a script set up to detect when the player enters a Collider Trigger attached to the Racoon, which will cause it to play an animation and start attacking the player.

To do that, it needs to work with a racoon navigation component on a neighbouring object:

I'm trying to access the `RacoonNAVAI` component on the `Racoon_Mover` game object with this line:

```
racNav = transform.parent.parent.Find("Racoon Mover").gameObject.GetComponent<RacoonNAVAI>();

```

But it's throwing a null reference exception. How can I correctly get a reference to this component?

# Answer
In the line below you are looking for `Racoon Mover` instead of `Racoon_Mover`, note the `_` (underscore symbol).

```
racNav = transform.parent.parent.Find("Racoon Mover").gameObject.GetComponent<RacoonNAVAI>();

```

Also, it is not a good idea to use find in runtime code like this. Instead, you can assign it as a serialized component if they are part of the same prefab or at least cache the reference so that you won't need to look it up each time. Good luck!
> 0 votes

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


# Question
Title: Change Text - Inside A button, inside a Canvas, inside a GameObject: Access all the texts inside of hierchy?
```
//....
Gameobject tile;
int count = 1f;
float posX = 0;
float posY = 0;
....//

GameObject blueTile = (GameObject)Instantiate(Resources.Load("block_blue"));
tile = (GameObject)Instantiate(blueTile, transform);

for loop {
   ...
   ...
   tile.GetComponent().GetComponentInChildren().text = count.ToString();
   tile.transform.position = new Vector2((float)posX, (float)posY);
   count++;
}

```

As you can see by the image. My line of thinking goes like this; I used to create Flash/AS3 Applications and Games. I have used a number of API's and they usually have a lot in common. Unity, however, is very different and I may have not grasped the key concepts.

I want to access my PreFab, named in Assets/Resources (the root path)
"block\_blue"

All I wan to do is set up a row and columns of a box with a number inside of it.

Before you go and ask, why the complicated mix of Objects? Well, Adobe had MovieClip and use of layers and also use of a timeline. Unity doesn't seem to have this in setting up a Scene (the Stage in Flash).

So, I set up a block that looks like this (right of main image 66): It's a Canvas, to hold a Button, the button has a text. To move the Canvas, I put the Canvas inside a GameObject. This, to me, is like a MovieClip in Flash API.

\**GameObject \> ButtonLight, Button \> TextBlack, Text\**

I need to access TextBlack and also Text. Pretty easy right? I've been at this for 4 days, many many hours.

EDIT: It seems that it is working, somewhat.
Looking at the reference photo and the Hierarchy reference, it looks like the blackText behind the blueText is changing as expected. But I cannot access the top BlueText. The Blue Text is also a child of type Text, but it's a second (layer?) copy of the text inside of the Button. So, it's getting the first Child Text, but how to access the second Text?

# Answer
As you can see by the images, I had to change the "Hierarchy". In the attempt to utilize this as we do in Adobe Flash (AS3) in using-layers, this is how I accomplished this. To give it a "MovieClip" Feel from the Adobe Flash API approach.
I replaced **ButtonLight** in the hierarchy, with **Image**.
I removed **TextBlack** from Button and **Added a Shadow component** to the Text inside the Button Component. The new hierarchy is in the image.
Here are the 3 syntax I used, with this Hierarchy, to accomplish the goal:

> Hierarchy
>
> * GameObject
> * Image - \> Color
> * Button - \> Image - \> Color
> > Text - \> Color & Shadow Component instead of a second Text

***Button Color***

* public void changeButtonColor(GameObject gameObject, Color color)
* gameObject.GetComponentInChildren().GetComponent().color = color;

***Font Color***

* public void changeFontColor(GameObject gameObject, Color color)
* gameObject.GetComponentInChildren().color = color;

***Image Color***

* public void changeTileColor(GameObject gameObject, Color color)
* gameObject.GetComponentInChildren().color = color;

I was able to create 3 functions/methods to change the attributes within the Hierarchy Layers of the GameObject Prefab, "block". Where, the "block" is a GameObject with the given hierarchy above. A layers approach.
> 0 votes

# Answer
`GetComponentInChildren` traverses the whole object tree below an object using a depth-first search until it finds the first component of the requested type and returns it. I would not advise to use that method unless you are in a situation where you are certain that there is only one child with that component and there will never be a reason to add a second one.

If you want to get **all** the text components in **all** the descendants of an object, use `GetComponentsInChildren`. Note the extra `s` behind `Component`. It doesn't just return the first Component it finds. It traverses the whole tree collecting all the components of that type and then returns them as an array of 0 or more Components. So when you want to change the color of all the texts of a given object, do

```
foreach(UI.Text text in theGameObject.GetComponentsInChildren<UI.Text>()) {
     text.color = Color.blue;
}

```

Caveat: When you have very large object hierarchies, then this method can become slow. With object hierarchies of 5, I don't think you are at that point yet. But it might become a problem with 100s of nested objects.

So when you want to change the color of a large number of text nodes in a deeply nested hierarchy very frequently, then I would look if it's possible to assign the same Material to all the texts and control the color by changing that shared material.

---

By the way: You can find a lot more useful methods for navigating the scene graph in the documentation of the GameObject class.
> 1 votes

---
Tags: unity, c#, gameobject, text
---


# Question
Title: Multiplayer game with differently screen size
I am making a classic ping pong 2D multiplayer and its run on full screen, but i have a problem that the ball touch the limits of screen to one player and other no. Any idea how to solve this ?

# Answer
Don't use screen pixels as a unit of length for your game.
You could use an abstract scene in arbitrary units, compute the ball position in this scene (independently of the players' screen resolution) and then transform the scene coordinates into screen coordinates depending on the screen resolution.
> 0 votes

---
Tags: c++, sdl2
---


title: How do I get the local player?

text:
# Question
Title: How do I get the local player?
I'm using Mirror as UNet is deprecated. How can I get the local player GameObject in my code?

# Answer
> 6 votes
Currently, the best method is using NetworkClient from Mirror:

```
using Mirror;
GameObject localPlayer = NetworkClient.localPlayer.gameObject;

```

---

*Note that the following is deprecated and shouldn't be used.*
The ClientScene class has a static property called localPlayer of type NetworkIdentity. All Components in Unity have `gameObject` as property which refers to the GameObject they're attached to. So in order to get the localPlayer object you would do:

```
using Mirror;
GameObject localPlayer = ClientScene.localPlayer.gameObject;

```

---
Tags: unity, mirror-networking
---


# Question
Title: SNES development: why bitplanes get scrambled?
I am following this tutorial https://georgjz.github.io/snesaa04/. I am stuck on trying to draw a sprite.

Where the end result should be this:

My end result is this:

As I have not been able to find samples of tile and palette files, I am not sure if I have done everything right.

Sprites.vra:

```
0b 2e 2a 3f 1e 1f 0f 3f 2e 3f 1c 1f 0c ff f3 fe
2f 00 3f 00 1f 00 3c 00 38 00 10 00 00 00 00 00

```

SpriteColors.pal:

```
fe 3f 3e 77 f8 5d 0f 49 ff 7f f8 6f 8a 6b 49 62
64 39 e0 2c 60 18 98 04 9f 0e 3e 09 2c 00 00 00

```

As the tutorial proposes, I use cc65 as a compiler. The files are included like this:

```
.segment "SPRITEDATA"
SpriteData: .incbin "Sprites.vra"
ColorData:  .incbin "SpriteColors.pal"

```

As I could not get bsnes working, I am using Snes9X.

As this failed, I tried to draw a plane with just one color as well to figure out the logic. I did not manage, as the colors were always scrambled.

**Questions:**

How should the tile/bitplane and palette files look like? What is the checksum error my emulator throws?

As a last note: please be patient if this is basic stuff. I am ex web dev and a retro game hobbyist, and assembly code is completely foreign world to me.

# Answer
When coding in assembly, it can be easy to mix up your data format. In this particular case, the assembly code is expecting the `.pal` and `.vra` files to be in hex / binary. For instance, here's the `.pal` data from the tutorial:

The far left columns indicate the memory offset, the middle column is the data in hexadecimal form & the far right column is the data in ASCII.

So, if properly encoded, if you open the `.pal` file in something like Notepad, you should see the data as presented on the right, starting with  `?>w ] I o kIbd`.

If, instead you see `fe3f3e77f8` and so forth in a text editor, then the data has been encoded as text / ASCII and will not represent what you want or what the assembly program is expecting.

My first clue that this was a data representation problem was the combination that the data came directly from the tutorial & the error returned was complaining about a bad checksum. Unless the tutorial itself was flawed, this suggested that somewhere, bad / unexpected data was getting processed. I've made similar errors myself when dealing with assembly & hex data.

Using a good hex editing tool will help, but it's still possible to make mistakes, so if you are experiencing data problems, it's a good idea to double check your data format & encoding.
> 2 votes

---
Tags: sprites, nintendo, assembly
---


# Question
Title: Creating Complex Collision Shapes in GMS2
I'm pretty new to Game Maker Studio 2 and I've hit a wall in programming with their built-in physics engine. I created a irregularly shaped object and I want to modify the collision shape so that it fits the shape of the sprite. In the built in collision shape editor it only allows you to create a convex shape with a max of 8 points. Is there another way to do this without having to plot out points individually in code?

Thanks!

# Answer
> 1 votes
Go to the sprite you want to make the precise collision, go inside the collision mask dropbox and change the type from rectangle to "precise per frame". Keep in mind that this will be a bit slower than other types of collision (not sure how much tho).

---
Tags: collision-detection, game-maker, physics-engine
---


# Question
Title: Image of the room appearing incorrectly for no apparent reason
**In the game, when I call the room (room\_Corrida) from the room of the selection menu, it was for that to appear:**

**It turns out this is how the room appears:**

The effect is as if it had a white rectangle the same size as the room, with less than 100% opacity.

When I start the room immediately (I put it first), it appears normally. The room also appears normally when I have the room called directly after the start menu. It only appears wrongly when I call it after the game selection menu.

**Code that makes the room appear wrong (from the selection menu):**

```
if(mouse_x>=1601 && mouse_x<=1917 && mouse_y>=762 && mouse_y<=1077){
    room_goto(room_Corrida);
}

```

**Code that makes the room appear correctly (from the home menu):**

```
if(mouse_x>=room_width/7*1 && mouse_x<=room_width/7*2-1 && mouse_y>=room_height/10*1 && mouse_y<=room_height/10*2-1){
    room_goto(room_Corrida);
}

```

# Answer
> 2 votes
Are you using draw? if yes, try using `draw_set_colour(c_white)` before drawing this whole text. I think the problem could be that you are changing the draw colour somewhere in the code but not changing back to white before drawing the whole ranking on the room.

---
Tags: game-maker
---


# Question
Title: How can I create a pressure pad in order to open a door?
I'm making a 2D platformer with Unity. I want to create a pressure pad in order to open a door and I want the door to open when the player is on the pressure pad and close in few seconds after the player leaves the pressure pad. I've tried different ways but none of them worked. In this case, the door should be open upwards and close downwards. Also, I already created some animations (idle, open and close) for the door but don't know how to make a connection between these two objects then play the animations at the proper time. Thank you in advance.

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

public class PressurePad: MonoBehaviour
{
    public UnityEvent OnActivate;
    public UnityEvent OnDeactivate;

    int objectsInContact;

    IEnumerator Timer()
    {
        yield return new WaitForSeconds(6);
        OnDeactivate.Invoke();
    }
    void OnTriggerEnter2D(Collider2D other)
    {
        objectsInContact++;
        if (objectsInContact == 1 && OnActivate != null) OnActivate.Invoke();
    }

    void OnTriggerExit2D(Collider2D other)
    {
        objectsInContact--;
        if (objectsInContact == 0 && OnDeactivate != null) OnDeactivate.Invoke();
        StartCoroutine(Timer());

    }

}

```

# Answer
You're very close, but you're firing your deactivate event twice: once the instant the pad is empty, and then again after a delay.

Delete the first one, and also make sure you stop the timer if the player returns to the pad before the time is up:

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

public class PressurePad: MonoBehaviour {

    public UnityEvent OnActivate;
    public UnityEvent OnDeactivate;

    public float deactivationDelay = 6f;

    int objectsInContact;
    Coroutine waitingToDeactivate;

    IEnumerator Timer() {
        yield return new WaitForSeconds(deactivationDelay);

        // Tell our listeners we're switched OFF.
        if (OnDeactivate != null)
            OnDeactivate.Invoke();

        // Return to ready-to-activate state:
        waitingToDeactivate = null;
    }

    void OnTriggerEnter2D(Collider2D other) {
        objectsInContact++;

        // Pressure pad pressed.
        if (objectsInContact == 1) {

            if (waitingToDeactivate != null) {
                // Cancel deactivation timer.
                StopCoroutine(waitingToDeactivate);
                waitingToDeactivate = null;

            } else if (OnActivate != null) {
                // Tell our listeners we're switched ON.
                OnActivate.Invoke();
            }
        }
    }

    void OnTriggerExit2D(Collider2D other) {
        objectsInContact--;

        // Pressure pad released.
        if (objectsInContact == 0) {
            // Start a delay before telling anyone.
            waitingToDeactivate = StartCoroutine(Timer());
        }
    }
}

```
> 0 votes

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


# Question
Title: Can I use 3d models I have created in Hexagon made by Daz 3d in commercial games?
I have been modelling in Hexagon for a while. I want to know if I can use 3d models I have created in hexagon in a commercial game as I have been planning to do one myself.

I don't want to get in trouble for using Hexagon 3d models I have created in my commercial game. I searched Google but could not find the answers I was looking for. I went to the DAZ studio website but I could not find anything answering my question

# Answer
> 0 votes
The information I could find about the Daz3d Standard License Agreement states:

> Whenever you purchase 3D Content from Daz, it comes with certain rights that allow you to use that content. Some of those rights include the ability to:
>
> * Render Images
> * Render Videos
> * Render HDRIs\> and/or Virtual Reality (VR) scenes
>
> Any of these that you produce and render out are completely owned by you, so you can use them commercially, modify them, sell them, or promote them, as protected by the End User License Agreement (EULA). This is because the end product is a render (your individual artwork) of the 3D Model, as opposed to the actual 3D Content.
>
> **When you should get an Interactive License:**
>
> Certain applications of models from Daz 3D require an Interactive License if you want to use that product in a particular way. Any app, game, or video game where the model changes depending on what a user does requires an Interactive License (example: if the 3D Model moves, bends, or walks based on an action the user of that app or game makes).

In general terms, it sounds like if you generated your meshes completely on your own, you should be in the clear to use them commercially. That said, this is not legal advice & you should consult a qualified legal professional.

Also, the information above doesn't include anything about textures / materials. I suspect the situation is similar - if you're using things you developed yourself, you're probably fine. If you're using materials from their marketplace, you'll need to check those rights seperately.

---
Tags: copyright
---


# Question
Title: How should I change the script so I will be able to change the transform height while the game is running and the transform is following?
```
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;

public class Follow : MonoBehaviour
{
    public Transform targetToFollow;
    public Transform missionTarget;
    public Text textDistance;
    public Text textSpeed;
    public float lookAtRotationSpeed;
    public float moveSpeed;
    public float followRadius = 1.5f;
    public float fastRadius = 5f;
    public float speedBoost = 0.5f;

    void Start()
    {

    }

    // Update is called once per frame
    void FixedUpdate()
    {
        Vector3 lTargetDir = targetToFollow.position - transform.position;
        lTargetDir.y = 0.0f;
        transform.rotation = Quaternion.RotateTowards(transform.rotation,
            Quaternion.LookRotation(lTargetDir), Time.time * lookAtRotationSpeed);

        float ms = moveSpeed;
        var distance = Vector3.Distance(transform.position, targetToFollow.position);
        // Compute a position no further than followRadius away from our target.
        Vector3 fromTarget = Vector3.ClampMagnitude(-lTargetDir.normalized, followRadius);
        Vector3 stopPoint = targetToFollow.position + fromTarget;

        // Compute a speed that's faster when far away and slower when close.
        float speedBlend = Mathf.Clamp01((distance - followRadius) / (fastRadius - followRadius));

        ms = moveSpeed + speedBlend * speedBoost;

        // Move as far as we can at our speed ms to reach the stopPoint, without overshooting.
        transform.position = Vector3.MoveTowards(transform.position, stopPoint, Time.deltaTime * ms);
    }

    private void Mission()
    {

    }
}

```

I mean the transform of the gameObject the script is on. I want to keep the y position up all the way or at least make it finish moving on the ground or above the ground depending on my settings.

Now the transform the script is attached to the name is NAVI. NAVI is by default position Y set to 5.94 :

Then the game start NAVI is moving to the target the kid\_from\_space in this case. Kid\_from\_space position is at 0,0,0 when the NAVI getting close to the target NAVI position Y is 0 and the result is :

Therefore the NAVI is not on the ground and I also can't change it's Y position up or down. The NAVI is stuck at the Y 0 position. I want to be able to change the Y position up/down, for example if before the game is running I'm setting the Y position of NAVI to 5.94 or 6 or 21 I want the NAVI to stay at this position on the Y and not move down to 0.

# Answer
The culprit appears to be this line:

```
lTargetDir.y = 0.0f;

```

This makes this object head for the direction of the floor at the position of the object its following. When you want this object to retain its y-coordinate, then it should be sufficient to add back the transform.position.y of this object which you just subtracted on the line above:

```
lTargetDir.y += transform.position.y;

```
> 0 votes

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


title: OnMouseOver not registering collisions

text:
# Question
Title: OnMouseOver not registering collisions
I'm working on a UI-heavy game and I'd like to add sound effects for when the player mouses over a UI button (using TMP, if that matters). I've tried OnMouseOver and its siblings OnMouseEnter and OnMouseStay, I've tried with and without 2D Box Colliders, but so far nothing I've tried seems to register that the mouse is over the button: i.e. nothing happens. If a collision or Raycast hit were registered, all that I'm asking right now is for it to run the line Debug.Log("Collision detected");

I know that Unity is able to register hits on the UI element I'm testing on, because mousing over it engages the Sprite Swap function that's part of the Button component, which it would not do if it were not accepting Raycast hits.

I'm sure there's some very simple solution to this, like a check-box I haven't ticked, but I could really use some help here.

Many thanks!

# Answer
Maybe try `void OnPointerEnter(PointerEventData eventData){}`? It comes with

```
using UnityEngine.EventSystems;
using UnityEngine.UI;

```
> 1 votes

# Answer
That did it. Thanks Dead Lord! Here's the code that worked.

```
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine;

public class Test : MonoBehaviour, IPointerEnterHandler
{
    public void OnPointerEnter(PointerEventData eventData)
    {
    Debug.Log("Mouse detected");
    }
}

```
> 1 votes

# Answer
This may also happen if you forget to disable the 'raycast target' checkbox on images & text that can block the mouse over raycast.

Since you are using TMP: the option is found in the inspector and located via the extra settings dropdown
> 0 votes

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


title: Another try. List don't remove properly

text:
# Question
Title: Another try. List don't remove properly
I hve that script:

```
public void ActivateCard(Card card)
        {
            Debug.Log("Activating card: " + card.CardsData);
            if (card.CardsData.creatureName != string.Empty)
                Summon(card);
            else
                CastSpell(card);

            if (_hand.Cards.Contains(card))
            {
                _hand.Cards.Remove(card);
                Debug.Log("Card " + card.CardsData.cardName + " deleted");
                Debug.Log("now we have(cards): " + _hand.Cards.Count);
            }

            _hand.TakingCards(0);
        }

```

And I expect that card will be removed from the list. But it allways remove only FIRST element in there. Here's what I have(card can't be the same in one list):

ADDICTION:

It's not a full code, but it's all we need I think. Here's how this method calls: -I-

```
public class InputClass
{
  void Update
  {
    if (targetSet)
     {
         if (Input.touches[0].phase == TouchPhase.Ended)
                    Cancel(true);
     }
  }

  void Cancel(bool isDone){ _actCard.Cancel(isDone); }
}

```

-II-

```
class ActCard
{
  public void Cancel(bool isDone)
  {
    if (isDone)
     {
        _activator.ActivateCard(_card);
     }
  }
}

```

-III-

```
class CardActivator
{
  public void ActivateCard(Card card)
        {
            Debug.Log("Activating card: " + card.CardsData);
            if (card.CardsData.creatureName != string.Empty)
                Summon(card);
            else
                CastSpell(card);

            if (_hand.Cards.Contains(card))
            {
                _hand.Cards.Remove(card);
                Debug.Log("Card " + card.CardsData.cardName + " deleted");
                Debug.Log("now we have(cards): " + _hand.Cards.Count);
            }
        }
}

```

-IV-

public class Hand
{
  List<Card> _hand = new List<Card>();

  public List<Card> Cards
        {
            get { return _hand; }
            set { _hand = value; }
        }
}
```

# Answer
> 1 votes
Basically contains does not know how to identify the correct card in your list since you didn't implement those. You can take a look at this stackoverflow.com/questions/2629124/… Your equals should return something that is unique for all your cards, like an id, name or a combination.

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


# Question
Title: Unity - How to don't ignore a layer when Raycasting?
For example: `Physics.Raycast(ray, out hit, range, layerMask)`, let's say `layerMask = groundMask`. What I want to do is only return true if it didn't hit a ground mask. Like what I mean is like "Ignore raycast except `groundMask`". Is there anyway to do this?

Some example:

```
origin ------------ (groundmask) -------- (other mask) --- // return false;
because there is a ground mask in a range
origin ---------------------------------- (other mask) --- // return true;
because there is no ground mask in a range

```

# Answer
> 0 votes
If you cast against a layer you should only return true if your cast hits the layer specified.

You can setup the QueryTriggerInteraction to also register objects that have colliders set to trigger.

You can use this to cast against whichever layers you would like to check and it will only return true to the ones you touched.

example: "groundmask"

```
public bool GroundCheck()
{
    return isGrounded = Physics.Raycast(transform.position, Vector3.down, out hit, range, groundMask,QueryTriggerInteraction.Collide);
}

```

In your case to see if you are not grounded you can use if !GroundCheck() or if !isGrounded to see if you are no longer touching ground.

Be sure to also set the layer to the object you use for ground or it will not get a return for the ground layer check.

---
Tags: unity, raycasting
---


# Question
Title: How do I support animation with frames of different sizes?
I'm trying to create a simple top-view 2D rpg, in the style of Zelda and Secret of Mana, using PyGame. I've managed to make the beginnings of a game, with an animated character walking around. However, when I start animating attacks, I'm running into problems because the sprite with the sword slash is bigger than the walking sprite. This makes the character appear to be jumping around when attacking.

I managed to handle the problem by defining a center of gravity, so to speak, for each image, and apply a suitable offset at each frame in the animation to make the center of the character stay at the same place throughout the animation. I defined a dictionary of lists of images (instances of pygame.Surface), where I pick out the correct list by the state of the character, so for example there is one list for walking left, and then I loop over the list to get the animation. To handle the offset, I similarly created a dictionary of lists of offsets, looping over those in the same way.

However, I'm not entirely pleased with this implementation, so I'm looking for a more elegant solution.

I tried to add an attribute called offset to each instance of the pygame.Surface class, to hold the offset for each image, but the Surface class doesn't allow new attributes to be set. I then thought about subclassing pygame.Surface, which would allow me to set any attribute I wanted, but then I couldn't load my images with pygame.image.load without a lot of extra code.

I imagine everyone who makes a game with animations where the size of the sprite changes between frames would have to deal with this problem, so if anyone could suggest an elegant implementation, that would be great. If example code with PyGame is available, that would be even greater.

# Answer
> 2 votes
Imagine the worst case scenario, a fighting game where each moves' frames are different in size. Some kicks have an exceptionally far reach and some even further (think Dhalsim)

The bounding box may be very different in each frame and so are the frame's size and the relative position point. There is no mystic way to do it. Normally to handle complex sprites' animations, one of the teams' members uses a tool to define a bounding rectangle around each frame and place a relative positioning dot in each frame. This data is saved to an xml file often but is created with a specialized tool.

# Answer
> 1 votes
I'm kinda late, but I was having the same problem, so yesterday I made a tool that tries to handle the case of the accepted answer (it identifies each rectangle in each animation line, then sorts then by line, so you can use the output to create a list of rectangles for each frame of each animation in each sprite sheet, instead of marking the rectangles manually), it still needs some work tough, seems to break with large files, and it doesn't handle non black background yet...

https://gitlab.com/pedroga/way-of-the-fist/-/blob/master/tools/frame-identifier/identify.cpp

I'll be improving it as need arises, but feel free to modify it to suit your needs.

Example output:

Line 0: {.x = 19, .y = 22, .w = 62, .h = 100} {.x = 90, .y = 22, .w = 63, .h = 100} {.x = 162, .y = 19, .w = 67, .h = 103} {.x = 237, .y = 18, .w = 70, .h = 103} {.x = 316, .y = 22, .w = 64, .h = 100} {.x = 389, .y = 22, .w = 61, .h = 100} {.x = 459, .y = 22, .w = 61, .h = 100} {.x = 529, .y = 22, .w = 61, .h = 100} {.x = 599, .y = 22, .w = 61, .h = 100} {.x = 664, .y = 28, .w = 68, .h = 94}

Line 1: {.x = 15, .y = 141, .w = 63, .h = 89} {.x = 80, .y = 136, .w = 70, .h = 93} {.x = 154, .y = 135, .w = 68, .h = 95} {.x = 232, .y = 134, .w = 59, .h = 95} {.x = 306, .y = 135, .w = 54, .h = 94} {.x = 374, .y = 136, .w = 56, .h = 93} {.x = 438, .y = 141, .w = 63, .h = 89} {.x = 507, .y = 136, .w = 61, .h = 93} {.x = 575, .y = 135, .w = 54, .h = 94} {.x = 643, .y = 134, .w = 54, .h = 95}

Line 2: ...

---
Tags: animation, sprites, pygame
---


# Question
Title: What does a perspective projection matrix look like in OpenGL?
I've been trying to construct a perspective projection matrix myself and finding it extremely difficult.

I realize that a perspective projection matrix is by default a frustum in OpenGL 3.3+ that is transformed into a unit cube and I need to divide x , y and z by -z too project x y z into -z then I need to divide by w after I've done some equations on I believe these values top , bottom , left , right , zFar and ZNear however I don't exactly know what those equations are and I'm not exactly savy in all the maths required to do this persay also I've read that this is not the full perspective projection matrix and I need some kind of clipping planes?

```
GLfloat x = 1.0-z;
GLfloat y = 1.0-z;
GLfloat z = 1.0-z;

GLfloat projm[16] = {0};

//crazy equations that I don't know with values
//that I don't know where to place exactly:
//top , bottom , left , right , zFar and ZNear

x / w;
y / w;
z / w;

projm[] ={x, 0.0 , 0.0, 1.0,
          0.0, y , 0.0, 1.0,
          0.0, 0.0, z,  1.0};

```

I'm very aware of GLM , I'd prefer too do it myself for learning , curosity and potential benefits please be gentle.

# Answer
> 14 votes
OpenGL already handles the division by W part, you don't need to do anything about that.

So, this is what a perspective projection matrix should look like:

FOV is the vertical angle of the frustum.

Near and far are the distance from the camera to the cutting planes. Nothing gets rendered beyond those. Make sure fo set the near plane to a small value, but not too small, or you will lose precision because of how the depth buffer works.

Aspect is the aspect ration of the window (windowWidth/windowHeight)

The best explanation about how all this works I found was on this website (yes it's about webgl, but it can be read without knowledge of it)http://webglfundamentals.org/webgl/lessons/webgl-3d-perspective.html

# Answer
> 1 votes
http://www.songho.ca/opengl/gl\_projectionmatrix.html

Note the perspective projection matrix is a transform like any other. The difference compared to orthogonal matrix is that the xy-displacement is dependent on the z coordinate. If you figure out what a perspective is and have a good idea about what shearing transforms do perspective projection matrices are no magic at all. Good luck!

# Answer
> 0 votes
I eventually, figured out a way to do this here's what I've written about this subject on my youtube channel:

Basically the idea with perspective projection

your clipping and or attaching the znear and or zfar plane on the x (width), y (height) and z (depth) axis with the clipping (perspective boundary) and perspective volume (perspective shape which is kinda like a 3D weird cube with a pyramid at the top) which is helped by the distance between zfar and znear planes but the equations are weird and confusing.

* translation = positioning
* transforms = various kinds of visual transformations (rotation,size,etc)

First lets understand the matrix :

```
var matrix = [
xx, xy, xz, xw,
yx, yy, yz, yw,
zx , zy, zz, zw,
wx, wy, wz, ww
];

```
* x(anything) is for width and any other transform including projection.
* y(anything) is for height and any other transform including projection.
* z(anything) is for depth (not perspective) and any other
transform including projection.
* w is for perspective (growing and shrinking geometry) and any other transforms including projection

any combination of xyzw are just obvious xy will work on width of height or yz will work on the depth of height, I think, etc.

Now depending on if it's in row or column order. will determine which w's are used for translation in this case for WebGL row is

```
var matrix = [
xx, xy, xz, xw,
yx, yy, yz, yw,
zx , zy, zz, zw,
(wx, wy, wz, ww)
];

```

if it was column then it would be

```
var matrix = [
xx, xy, xz, (xw,
yx, yy, yz, yw,
zx , zy, zz, zw,
wx, wy, wz, ww)
];

```

To create the actual plane you use variables

```
float top = 1.0,
bottom = -1.0
left = -1.0
right = 1.0

```

These are all the variable declarations:

```
        var top = 1.0; // top of cube
        var bottom = -1.0; // bottom of cube
        var zfar = -2.0; // distance of furthest boundary of perspective shape
        var znear = 4.0; // distance of closest boundary of perspective shape
        var width = 1.0; // width of cube
        var height = 1.0; // height of cube
        var left = -1.0; // left side of cube
        var right = 1.0; // right side of cube
        var zoomfactor = 2.0; // amount zoomed in and out

```

The cube formation is a consequence of creating a plane with these equations (I think) and the pyramid part and perspective projection is all in these equations also zfar and znear equations are here too:

```
var PersMat = [
    //ROW 1
    znear / width / 4.0 * zoomfactor, 0.0, left+right/width/2, 0.0,
    //ROW 2
    0.0, znear / height / 4.0 * zoomfactor  , top+bottom/height/2, 0.0,
    //ROW 3
    0.0, 0.0, - (zfar + znear) / (zfar - znear), 2*zfar*znear / zfar - znear,
    // ROW 4
    0.0, 0.0, -1.0, 0.0
  ];

```

Hope that helps.

---
Tags: opengl
---


title: XNA configuration on legacy code

text:
# Question
Title: XNA configuration on legacy code
**Background:** Our biomechanics and Advanced Surgical Technologies Lab wrote a surgery navigation system desktop application in C# around ten years ago. One of its major functions uses XNA Game Studio 4.0 to aid in the interactive interface for rendering in 2D and 3D cloud data originating from CT (medical scan data in DICOM format), and then segmenting that data and reconstructing it to generate surface models (stl format).

**Summary of problem:** The whole application worked fine and still does on the old hardware, but, while compilation succeeds, execution fails in one aspect related to XNA processes destined for the GPU processor rather than the main PC CPU.

The import of data from DICOM and various filtering and scaling all works, and basic rendering also works on previously compiled source code and executable code on Windows 7 machine (details later below). Also, compilation and execution work fully on an old Win PC with the Visual Studio 2013 environment.

Our attempts to compile the same source code and execute on newer hardware and environment with Win 10 and Visual Studio 2019 have partly failed. The compilation works, and most of the execution works, except for some rendering of XNA processes destined for the GPU processor.

**More details:** The user interface successfully renders bitmaps through the Texture2D class (Microsoft.Xna.Framework.Graphics) initialized with the grayscale data from previous number crunching operations in our code.
In another part of the interface, where we think and say above may rely on the (onboard GPU) processing, using the same Texture2D object, but when the code involves setting parameters of Effect (Microsoft.Xna.Framework.Graphics.Effect) using Texture2D, drawings which use the spriteBatch.draw function is not rendering on the modern PC platform we set up.
We guess the relevant code which fails to do the job is the following. Pls note that it simply fails to render parts of the image which require image processing (filters, thresholding, boundary detection, etc.), AND without any errors/exceptions reported.

```
            GraphicsDevice device = SosGraphicsDeviceService.Instance;
            SpriteBatch spriteBatch = SosGraphicsDeviceService.ServiceInstance.SpriteBatch;

            string technique = SosRenderModeName.GetTechniqueName(renderMode_, false);

            BlendState blend = device.BlendState;
            DepthStencilState depth = device.DepthStencilState;
            RasterizerState raster = device.RasterizerState;

            Effect.CurrentTechnique = Effect.Techniques[technique];

            Effect.Parameters[“useModelBuilderTextureInclude”].SetValue(includeTexture != null);
            Effect.Parameters[“modelBuilderTextureInclude”].SetValue(includeTexture);
            Effect.Parameters[“modelBuilderTextureExclude”].SetValue(excludeTexture);
            Effect.Parameters[“modelBuilderTextureCorrection”].SetValue(correctionTexture);

            Effect.Parameters[“minThreshold”].SetValue(minThreshold);
            Effect.Parameters[“maxThreshold”].SetValue(maxThreshold);

            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Additive, SamplerState.PointWrap,DepthStencilState.Default, RasterizerState.CullNone, effect_);

            foreach (EffectPass pass in Effect.CurrentTechnique.Passes)
            {
                pass.Apply();

                spriteBatch.Draw(texture, new Rectangle(0, 0, 512, 512), Color.White);
            }

            spriteBatch.End();

```

The following are some of the functions we use in our effect file if that helps to identify the Shader Model Version.

```
•   float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{

       return float4(1, 0, 0, 1);
}
•   technique Technique1
{
       pass Pass1
       {
        VertexShader = compile vs_2_0 VertexShaderFunction();
        PixelShader  = compile ps_2_0 PixelShaderFunction();
       }
}

```

To try to see which settings or aspects of the environment are causing the problem, we tried to recompile the same code in a variety of configurations and execute on both the old and new machines which having different hardware, drivers, libraries, and different installation configurations.

For example, we tried: • Changed Compatibility mode to match Win7 • Reduced color mode to 8bit • Changed Screen Resolution • Ran in administrator mode • Changed Game profile to Reach

The modern PC platform just would not render with the interface that utilizes Effect.

To recap, below is a summary comparison of the two setups, the one that works on the left, and the one that does not on the right, in terms of hardware, system, and environment setup. We tabulate here the hardware and system environment of each case. If needed, I can upload the whole System information file.

|  | Desktop\_Old (Works) | Desktop\_New (does not work) |
| --- | --- | --- |
| System OS | Microsoft Windows 7 Enterprise | Microsoft Windows 7 Professional |
| OS version | 6.1.7601 Service Pack 1 Build 7601 | 6.1.7601 Service Pack 1 Build 7601 |
| System Type | X64-based PC | X64-based PC |
| Total Physical Memory | 7.88GB | 15.9GB |
| Display | NVIDIA Quadro 1000M | Intel HD graphics 4600 |
| Resolution | 1920 X 1200 X 59 hertz | 1280 X 1024 X 60 hertz |
| I/O port | Just one | three |
| Driver | nvlddmkm.sys | Igdkmd64.sys |
| Installed DirectX | DirectX11 | DirectX11 |
| IDE | Visual Studio 2013 | Visual Studio 2019 |
| Game Profile | HiDef | HiDef |
| Unsafe Code | Allowed | Allowed |

Also, this is the previous post for the same problem and thanks for responding.

# Answer
> 1 votes
While I have spent years working with XNA across Xbox 360, Windows Phone 7 and PC, this kind of a problem is typical and requires lots of tedious configuration of the target system. While I was once successful in past, it took more effort than to simply update graphics API (say, DX8 to DX11).

Every new version of VS links against different libraries. Given how long ago was XNA abandoned, you have no business in attempting to compile it there.

For my personal projects in XNA, I still use VS2010 even though I have three other newer versions of VS on PC (different languages and APIs). It's just not worth the effort.

I would, however, very strongly recommend mirroring the Dev HW as you are one unexpected catastrophe away from being unable to deploy critical bug fixes to the production HW.

Oh, and I didn't see anything about trying the Quadro inside the Intel HD box. Seems like a very simple and quick exercise (just to rule out the Intel drivers).

---
Tags: xna, directx, graphic-effects, rendertexture, settings
---


# Question
Title: Unity - Mathf.Lerp() didn't work as expected?
I want to rotate an object 360 degrees so this is what I did: `xRotation = Mathf.Lerp(0, 360, Time.fixedDeltaTime * lerpTime)`

and then I used Quaternion.Lerp() to rotate the Object so:

```
targetRotation = Quaternion.Euler(initialRotation.x + xRotation, initialRotation.y, initialRotation.z);
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, Time.fixedDeltaTime * lerpTime);

```

But it didn't work as expected, the xRotation didn't go from 0 to 360, it just changed from 0 to 9 (instantly), and that's it, it never changed.

This is my full code:

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

public class QuaternionExpirement : MonoBehaviour
{

    [SerializeField] [Range(5, 10)] float lerpTime;
    Vector3 initialRotation;
    bool mousePress, readyToRotate;
    float xRotation;

    private void Awake()
    {
        initialRotation = Vector3.zero;
        mousePress = false;
        readyToRotate = false;
        xRotation = 0;
    }

    private void Update()
    {
        mousePress = Input.GetMouseButtonDown(0);
    }

    private void FixedUpdate()
    {
        if (mousePress)
        {
            initialRotation = transform.eulerAngles;
            readyToRotate = true;
        }

        if (readyToRotate)
        {
            xRotation = Mathf.Lerp(0, 360, Time.fixedDeltaTime * lerpTime);
            Quaternion targetRotation = Quaternion.Euler(initialRotation.x + xRotation, initialRotation.y, initialRotation.z);
            transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, Time.fixedDeltaTime * lerpTime);

            if (xRotation >= 360)
            {
                readyToRotate = false;
            }
        }
    }

}

```

# Answer
> 1 votes
It seems you have not really understood what the functions you use actually do. The `Time.fixedDeltaTime`, as per the documentation, returns the time between each physics update in seconds. This is a **fixed** value (e.g. for 50 physics updates per second this will be 0.02). Now, `lerpTime` is **also** a fixed value in your case from my understanding. This means that in **every** `FixedUpdate()` call, the `Mathf.Lerp` function will return **the same** value (`360 * 0.02 * lerpTime`), in your case 9, which means that `Time.fixedDeltaTime * lerpTime = 0.025`.

In order to fix the problem the `Time.fixedDeltaTime * lerpTime` must not be a constant value but must be updated each frame in order to start from 0.025 and eventually reach 1 after 40 frames.

```
float previousInterpolation = 0f; // member variable
FixedUpdate() {
  previousInterpolation = Time.fixedDeltaTime * lerpTime + previousInterpolation;
  xRotation = Mathf.Lerp(0, 360, previousInterpolation);
}

```

---
Tags: unity, rotation, lerp
---