title: How can I structure in-game menus?

text:
# Question
Title: How can I structure in-game menus?
I'm working on a multiplayer RPG using only C++ and SDL2. I've already made the main menu and a map editor, and I'm preparing to make the actual game. The main menu and map editor were easy to structure, because they had repetitive visuals and concepts -- map-editing tools can be represented as an enumerated list, just like saved-games and settings -- and so I was able to store them in structured vectors, and then when I went to render everything and check for user actions I could just iterate through the lists and hit every visible menu item. My code for those sections is small and neat; I'm proud of it.

Now, in the game, I'm realizing that my HUD is composed of a rather random assortment of types of things that the player can click on. There's a quick-access area for items, another one for spells, another one for the map, another for NPC-buddy commands, etc, and each of those have totally unique popup menus associated with them. Then there's a menu for crafting, a menu for NPC dialog, and several of the items have their own independent menus for interacting with them.

I'm trying to think of the right way to structure all these lists. Storing them in vectors like I did with the menu and stuff seems like it will land me with an unwieldy and asymmetrical set of nested vectors, and it might be complicated to iterate through it. How do good programmers handle this kind of thing? Should I just make an independent section in code for each in-game menu?

# Answer
> 1 votes
I don't think you are too far off making your code more manageable from what you have described. I write in C# so bare with me here.

I personally set up my UI components in containers, these containers not only hold all the associated UI components in a list (buttons, graphics, text etc), but also allows you to manage common capabilities such as position of the container, alpha values and enabling/disabling the UI container.

Each of these containers uses a common "Execute" function which just interates through each item in the container and executes their core code (any updates such as animations etc). The containers themselves are handled through a factory manager which simply keeps track of what containers have been allocated, and I reference them through a unique string name to retrieve the container, and I use unique names to reference the UI Component in the lists.

For each UI Component, I don't embed the game logic in the containers either, I have either in the past used callbacks or events to trigger the related logic.

My thoughts would be also not to make an independent section for each UI group. If you use something like callbacks or events, this abstraction allows you have high reuse of any actions from the UI. You want to auto trigger a UI action, say for a tutorial, you now have complete control of that, you simply calling for example (in C# i override \[\] operator!)

UIManager.Containers\["Spellbar"\].\["fireball"\].Trigger();

Hopefully it gives you some ideas, yes, moving to create containers around your UI to group the components will help with the code. Creating a common approach to your UI then means you it doesn't leach into your game logic.

---
Tags: c++, architecture, sdl2, menu
---


# Question
Title: Debugging built-in physics components in Unity
I have a particular GameObject with Rigidbody which I'm trying to move over time. If I move the object using its `transform.position`, it works fine. However, if I move the object using `rigidbody.position` or `rigidbody.MovePosition()`, it does not move as expected. It should be moving up and forward (+Y and +Z). Instead, it oscillates up and down but does not move on the X or Z axis.

I do not have any constraints enabled on the Rigidbody, and I can't find anywhere in my code that would freeze or alter its position, besides the line of code that's supposed to move it, and its behavior is the same whether or not gravity or colliders are enabled.

Is there some way to view a list of inputs that are affecting the position and movement of a particular Rigidbody each frame?

# Answer
> 0 votes
It turned out that the GameObject was a child of another GameObject. The parent was rocking back and forth slightly, which created the oscillating movement and apparently overrode and nullified attempts to move the GameObject through `rigidbody.position` or `rigidbody.MovePosition()`. I solved the issue by removing the GameObject from its parent and making it a root object of the scene.

---
Tags: unity
---


# Question
Title: Why does my first person camera attached to a rigid body vibrates?
I'm trying to make a first-person character with a rigid body. I need a rigid body because I want to add areas where the gravity comes from different directions so I also need to rotate the character accordingly. And as far as I know you cant rotate a character controller.

So I wrote a script for movement and camera rotation.

The problem I now face is that the camera vibrates. I recorded this video to show it.

Why do I get this and how do I fix this?

Movement code:

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

public class PlayerMovementRigidBody : MonoBehaviour
{
    public float speed = 10.0f;
    public Rigidbody rb;
    public LayerMask groundLayers;

    public float jumpForce = 7;
    public CapsuleCollider col;

    float transelation;
    float straffe;

    // Start is called before the first frame update
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        rb = this.GetComponent<Rigidbody>();
        col = GetComponent<CapsuleCollider>();
    }

    // Update is called once per frame
    void Update()
    {
        transelation = Input.GetAxis("Vertical") * speed;
        straffe = Input.GetAxis("Horizontal") * speed;
        bool jumping = Input.GetKeyDown(KeyCode.Space);

        transelation *= Time.smoothDeltaTime;
        straffe *= Time.smoothDeltaTime;

        /*if (IsGrounded())
        {
            rb.useGravity = false;
        }
        else
        {
            rb.useGravity = true;
        }*/

        if (IsGrounded() && Input.GetKeyDown(KeyCode.Space))
        {
            rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
        }

        if (Input.GetKeyDown("escape"))
        {
            Cursor.lockState = CursorLockMode.None;
        }

    }

    void FixedUpdate()
    {
        transform.Translate(straffe, 0, transelation);
    }

    private bool IsGrounded()
    {
        return Physics.CheckCapsule(col.bounds.center, new Vector3(col.bounds.center.x, col.bounds.min.y, col.bounds.center.z), col.radius * .9f, groundLayers);
    }
}

```

Mouse look code:

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

public class MouseLookRigidBody : MonoBehaviour
{
    public float mouseSensitivity = 100f;

    public Transform playerBody;

    Rigidbody rig;

    float xRotation = 0f;

    // Start is called before the first frame update
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        rig = this.transform.parent.gameObject.GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    public void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;

        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
        playerBody.Rotate(Vector3.up * mouseX);

    }
}

```

# Answer
Avoid placing the camera on the player GameObject at all, unless it's provisional or you ***really*** know what you are doing.

In most cases most issues are solved if you have an independent camera object (not parented with the player in any shape or form) and use the Update or LateUpdate method to put it into the right position at every frame.

Physical effects occur within FixedUpdate, which does not synchronize with the (Late)Update frames. That can cause flickering and other issues with the camera. The object it is parented to might not flicker (which you can't see because it's first person view), but everything else will.

Handling a camera is a bit mathematically challenging, but you can also use free assets or Unity's Standard Assets pack (a bit outdated, but still works fine).
> 1 votes

# Answer
This is likely caused by the physics engine updating your character out of sync with the rendering framerate, which is normal.

The standard way to avoid this is to turn on interpolation for your player gameobject. Interpolation is perfect if you use a kinematic rigidbody as your player, and a good compromise if you use a dynamic rigidbody.

You can also make your physics framerate faster if you can afford it, 1/75th can help, or set it to a multiple of your ideal framerate, to mitigate the issue.

Other problems may be that you're using the transform to move your rigidbody instead of calls to MovePosition, AddForce or velocity.

If you have a dynamic rigidbody, and you don't like the camera lag caused by standard interpolation, you can use the current velocity and a raycast to guess the position of the rigidbody during the next render frame.
> 0 votes

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


# Question
Title: How to store the configuration of Unity prefab components during map generation?
I managed to have a basic map generation algorhytm, but now it needs some content.

I generate abstract map data, which then will be used to build the map itself.

When I want to generate monsters, chests, entrances, etc, I have a prefab, and I will determine it's placement, then register it in the mapdata.

The problem is that I want to configure them as well, like affixes, stats, or where those entrances lead, etc. But the component is only available after the map is built. At generation I have only the prefab, so I have to transfer the generated configuration to the map builder somehow.

If I could clone the prefab, modify the clone's values and store that prefab.. . that would be great. But I can only instantiate prefabs, and I can't clone them without making a new asset.

# Answer
> 1 votes
You can simply Instantiate the prefab, disable it, modif it, and keep it as a reference.

Once you need it, simply call Instantiate on the disabled gameobject, and use the result.

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


# Question
Title: How can I make the code run only once when I release the key?
Im making a game in `LWJGL 2` and `Slick2d`. Im trying to add an item to my inventory by releasing a key (the inventory system works properly, the part where I have to see if the button was RELEASED is difficult). Right now when I do...

```
if (Keyboard.getEventKey() == Keyboard.KEY_L) {
    if(Keyboard.getEventKeyState() == false){
        Inventory.addItem(1);
    }
}

```

... In my update method, Instead of it only calling the 2nd if statement once, ( because you can only release a key once) It just keeps going because the `getEventKeyState` variable stays false, but if Ive already released it once it should switch back to the opposite. Although I can do it by making it add an item when i hold the key, I cant exactly make it add only the 1 item, it keeps adding items while I hold it.

```
public static void addItem(int id){
    for(InventorySlot s : inventoryslots){
        if(s.getItem() == -1){
            s.setItem(id);
            System.out.println("Added item " + id + "!");
            break;
        }
    }
}

```

Thats the addItem method, and if I would approach this by making it add the item while holding, I would have to make it so that it adds it only once. Any suggestions please? Thank you

# Answer
> 1 votes
The problem here is (likely) really simple. You need to call `Keyboard.next()` in order to pop the "L key was released" item out of the `Keyboard` queue, otherwise it'll just stick around in there.

# Answer
> 0 votes
You can use also container reference, getInput and check if a key is pressed, down, etc..

For example:

```
container.getInput().isKeyPressed(Input.KEY_SPACE)

```

see more details on javadoc

---
Tags: java, lwjgl, input, slick
---


title: Why is my TextMesh always on top?

text:
# Question
Title: Why is my TextMesh always on top?
I have a 2-d game that I am making, using 3-d assets, including TextMeshes for text. I have decided that in some instances, I would like to have the TextMesh appear behind objects in the foreground. The below is one such example.

It seems that the TextMesh is always in front. I have tried a number of things to get the text between the map and object layers, with no success. These include:

* Moving the text between the map and object.
* Changing the SortingLayers and SortingOrder. The map, objects, and labels are on 3 different layers, with the Objects being the highest layer, the map the lowest, and default and label in between.
* Using a perspective camera, not orthographic.

Any ideas as to what else could be going on? Thanks!

How can I make the TextMesh appear that isn't on the top layer? Thanks!

# Answer
The answer is fairly complex, and involves 2 key things. Note that I used this reference to help me.

1. Create a custom text shader. There are two examples given, I chose this one, which is for one sided text, which I believe is more common.

```
Shader "GUI/3D Text Shader - Cull Back" {
    Properties{
        _MainTex("Font Texture", 2D) = "white" {}
    _Color("Text Color", Color) = (1,1,1,1)
    }

    SubShader{
        Tags{ "Queue" = "Transparent" "IgnoreProjector" = "True" "RenderType" = "Transparent" }
        Lighting Off Cull Back ZWrite Off Fog{ Mode Off }

        Blend SrcAlpha OneMinusSrcAlpha
        Pass{
            Color[_Color]
            ColorMaterial AmbientAndDiffuse
            SetTexture[_MainTex]{
                combine primary, texture * primary
            }
        }
    }
}

```
2. This shader should be applied to a material. The texture should be the texture of the font (Must download a font).

This allowed me to do this (Still working on what text to use exactly)
> 0 votes

# Answer
In Text Mesh Pro, you can use overlay shader to render alway on top.

And for normal rendering, you can use Distance Field Shader.

Here is the demo.
> 1 votes

---
Tags: unity, text, sorting
---


# Question
Title: Execute Timer Events of another Blueprint from the C++ UE4
I am having problem and it's about a week now that I still can't figure out how to get it right.

It seems that I can't run any functions from the blueprints that contain timers at all.

I have a Datatable full of details of each functions that will executed according to its key input and the owner of the functions.

The ordinary functions and custom events executed well but will stopped at a timer.

This is the code that I have made so far. I added the matching functions string into the delegate with its Owner which is the obj, and it will executed on key input.

p.s: Ignore the error, Intellisense was messing me up

I saw the error regarding the world not found here,

but I'm not sure if that is the case since other functions without any timer inside can execute well. Any ideas? Thanks.

# Answer
> 0 votes
So I finally solved it. I have to point the UObject to AActor by using

`UGameplayStatics GetActorOfClass(this, ActorClass)` and apparently the `obj` was pointed to the wrong blueprint object in the game, but I read somewhere that it is not good to use GetActorOfClass too many times, but for now I'll just use this before I find another better solutions.

---
Tags: c++, unreal-4, events, timer, delegates
---


# Question
Title: Why do not Easy Mobile Pro scripts know about each other?
I am getting this error when I try to build the project:

```
Assets\EasyMobile\Scripts\Modules\NativeAPIs\NativeUI\Nati
veUI_AlertPopup.cs(68,17): error CS0103: The name 'AndroidNativeAlert' does not exist in the current context

```

I tried adding this to my NativeUI\_AlertPopup.cs:

```
    #if UNITY_ANDROID
        using EasyMobile.Internal.StoreReview.Android;
    #endif

```

Hint says unnecessary using. Googling, searching Unity EMP forum and thread did not bring any results. Unity version 2019.2 .net 4.x EMP 2.5 If I try adding a breakpoint it says:

```
The breakpoint will not currently be hit. Unable to find a corresponding location.

```

AndroidNativeAlert is a static class, have have no clue why it can't been seen from the other one.

# Answer
> 0 votes
Deleting the EMP folder from the assets folder and reinstalling it seems to put it right.

---
Tags: unity, android, build-process
---


# Question
Title: OpenGL Strange mesh when animating Assimp
I'm trying to animate a skeletal mesh. The mesh loads with no problems and everything is set up correctly. My problem is that when I calculate the matrix for a given keyframe the mesh goes nuts.

Here is an image of the problem.

The mesh on the right is using the `bone->transform` as the final matrix. The one on the left is using the matrix calculated from keyframes. I don't know where I'm going wrong with this.

Here is my code:

The `AnimationClip` is where all keyframes are stored:

```
Matrix4 AnimationClip::GetTransform(Bone *bone, float deltaTime)
{
Channel* channel = channels[bone->name];
if (channel == nullptr)
    return bone->transform;
else
    return channel->Update(deltaTime);
}

///////////

Channel::Channel(aiNodeAnim* animNode)
{
name = string(animNode->mNodeName.data);

for (GLuint k = 0; k < animNode->mNumPositionKeys; k++)
{
    aiVectorKey vec = animNode->mPositionKeys[k];
    positions.push_back(
        Keyframe<Vector3>(
        (float)vec.mTime,
            Vector3(vec.mValue.x, vec.mValue.y, vec.mValue.z)));
}

for (GLuint k = 0; k < animNode->mNumScalingKeys; k++)
{
    aiVectorKey vec = animNode->mScalingKeys[k];
    scalings.push_back(
        Keyframe<Vector3>(
        (float)vec.mTime,
            Vector3(vec.mValue.x, vec.mValue.y, vec.mValue.z)));
}

for (GLuint k = 0; k < animNode->mNumRotationKeys; k++)
{
    aiQuatKey vec = animNode->mRotationKeys[k];
    rotations.push_back(
        Keyframe<Quaternion>(
        (float)vec.mTime,
            Quaternion(
                vec.mValue.x,
                vec.mValue.y,
                vec.mValue.z,
                vec.mValue.w)));
}
}

Matrix4 Channel::Update(float animTime)
{
return
    CalculatePosition(animTime) *
    CalculateRotation(animTime) *
    CalculateScaling(animTime);
}

Matrix4 Channel::CalculatePosition(float animationTime)
{
return
    Matrix4::CreateTranslation(
        CalcInterpolatedPosition(animationTime));
}

Vector3 Channel::CalcInterpolatedPosition(float animationTime)
{
if (positions.size() == 1)
    return positions[0].value;

GLuint positionIndex = FindPosition(animationTime);
GLuint nextPositionIndex = (positionIndex + 1);

float deltaTime =
    positions[nextPositionIndex].time - positions[positionIndex].time;
float factor =
    (animationTime - (float)positions[positionIndex].time) / deltaTime;

Vector3 startPos = positions[positionIndex].value;
Vector3 endPos = positions[nextPositionIndex].value;

Vector3 delta = endPos - startPos;

return startPos + delta * factor;//Vector3::Lerp(startPos, endPos, factor);
}

GLuint Channel::FindPosition(float AnimationTime)
{
for (GLuint i = 0; i < positions.size() - 1; i++) {
    if (AnimationTime < (float)positions[i + 1].time)
        return i;
}
return 0;
}

```

And here is my `SkinnedMesh` code where I'm fetching the keyframes:

```
void SkinnedMesh::BoneTransform(
double delta,
vector<Matrix4>& transforms,
AnimationClip *anim)
{
Matrix4 identity_matrix = Matrix4::Identity();

float ticksPerSecond =
    anim->ticksPerSecond == 0 ? 25.0f : anim->ticksPerSecond;

double time_in_ticks = delta * ticksPerSecond;
float animation_time =
    fmod((float)time_in_ticks, anim->duration);

UpdateTransforms(
    animation_time,
    anim,
    rootBone,
    identity_matrix);

transforms.resize(m_num_bones);

for (GLuint i = 0; i < m_num_bones; i++)
    transforms[i] =
        m_bone_matrices[i].final_world_transform;
}

void SkinnedMesh::UpdateTransforms(
float p_animation_time,
AnimationClip *anim,
Bone *parentBone,
Matrix4& parentTransform)
{
Matrix4 boneTransform =// parentBone->transform;
    anim->GetTransform(parentBone, p_animation_time);

Matrix4 global_transform =
    parentTransform * boneTransform;

if (m_bone_mapping.find(parentBone->name) !=
    m_bone_mapping.end()) // true if node_name exist in bone_mapping
{
    GLuint bone_index = m_bone_mapping[parentBone->name];
    m_bone_matrices[bone_index].final_world_transform =
        m_global_inverse_transform *
        global_transform *
        m_bone_matrices[bone_index].offset_matrix;
}

for (vector<Bone*>::iterator it =
    parentBone->children.begin();
    it != parentBone->children.end();
    it++) {
    UpdateTransforms(
        p_animation_time,
        anim,
        (*it),
        global_transform);
}
}

void SkinnedMesh::Render(Shader* shader, AnimationClip *clip)
{
vector<Matrix4> transforms;
BoneTransform(
    (double)SDL_GetTicks() / 1000.0f,
    transforms,
    clip);

for (GLuint i = 0; i < transforms.size(); i++)
{
    GLfloat values[16];
    Matrix4::ValuePointer(transforms[i], values);

    string a = "jointTransforms[";
    a.append(to_string(i));
    a.append("]");

    glProgramUniformMatrix4fv(
        shader->GetID(),
        shader->GetUniformLocation(a.c_str()),
        1,
        GL_FALSE,
        (const GLfloat*)values);
}

for (unsigned int i = 0; i < meshes.size(); i++)
    meshes[i]->Render(shader);
}

```

It seems like the matrices are all wrong and therefore deforming the mesh. Can you help me?

EDIT :

The mesh on the right has this code :

```
Matrix4 AnimationClip::GetTransform(Bone *bone, float deltaTime)
{
Channel* channel = channels[bone->name];
if (channel == nullptr)
return bone->transform;
else
return bone->transform;
}

```

EDIT 2 :

As daniel\_1985 pointed out my matrices might have to be transposed but I'm in doubt…

This is how I'm converting Assimp matrices now

```
Matrix4 Matrix4::ToMatrix4(aiMatrix4x4 mat)
{
Matrix4 result;

result.row0 = Vector4(mat.a1, mat.b1, mat.c1, mat.d1);
result.row1 = Vector4(mat.a2, mat.b2, mat.c2, mat.d2);
result.row2 = Vector4(mat.a3, mat.b3, mat.c3, mat.d3);
result.row3 = Vector4(mat.a4, mat.b4, mat.c4, mat.d4);

return result;
}

```

This is the result if I set my skinned mesh to its `bone->transform`:

So what am I doing wrong? Is the matrix being correctly converted or not? If it is, why does my mesh get deformed like this?

I am building my bone hierarchy like this :

```
void SkinnedMesh::BuildBoneHierarchy(
aiNode* node,
Bone* parentBone)
{
if (parentBone == nullptr)
{
    rootBone = new Bone();
    rootBone->name = string(node->mName.data);
    rootBone->transform =
        Matrix4::ToMatrix4(node->mTransformation);

    for(GLuint i = 0; i < node->mNumChildren; i++)
        BuildBoneHierarchy(
            node->mChildren[i],
            rootBone);
}
else
{
    Bone* bone = new Bone();
    bone->name = string(node->mName.data);
    bone->transform =
        Matrix4::ToMatrix4(node->mTransformation);
    parentBone->children.push_back(bone);

    for (GLuint i = 0; i < node->mNumChildren; i++)
        BuildBoneHierarchy(
            node->mChildren[i],
            bone);
}
}

```

UPDATE :

So I've succesfully fixed my skinned mesh for its pose by calculating manually each bone `inverseTransform` manually like this :

```
void Bone::CalcInverseBindTransform(Matrix4 parentBindTransform)
{
Matrix4 bindTransform = parentBindTransform * transform;
inverseTransform = Matrix4::Invert(bindTransform);

for (vector<Bone*>::iterator iter = children.begin();
    iter != children.end();
    iter++)
    (*iter)->CalcInverseBindTransform(bindTransform);
}

```

In my `UpdateTransforms` I'm setting the mult like this:

```
GLuint bone_index = m_bone_mapping[parentBone->name];
    m_bone_matrices[bone_index].final_world_transform =
        m_global_inverse_transform *
        global_transform *
        parentBone->inverseTransform;

```

But when I animate it, it goes nuts. So what do I need to do now?

# Answer
Like daniel\_1985 pointed out, I was wrongly converting the Assimp matrices. The convention above (`ToMatrix4(aiMatrix4x4 …)`) should fix things.
> 1 votes

---
Tags: opengl, c++, assimp
---


title: Transparency fog performance

text:
# Question
Title: Transparency fog performance
Old games use Distance Fog to limit the draw distance and decrease the number of polygons drawn.

This is usually done by lerping the color to the fog color. But what if this color is full transparency and the resulting color is alphablended with the underlying image?
Is Alpha blending in this case more performance heavy?

I am talking about an effect like this:

# Answer
I think its still distance fog just not so dense. Personally I'd either sample custom distance function or just go with one standard but lower its density.
> -1 votes

---
Tags: alpha-blending
---


# Question
Title: I need an analytic formula for 3 arms inverse kinematics system
I need an *Analytic formula* for 3 arms IK system\_. I'm currently using Fabrik and CCD solutions but I'm facing low-performance and accuracy issues. So now I'm looking for an Analytic formula.

I'm working on a planar system so a 2D solution would work.

Thanks in advance for any help.

# Answer
Let's attack this in parts: we'll find where to place the end of the first bone, then figure out where the other two go. Once we've arranged the first bone, what remains is a two-bone IK problem, which we already know how to solve analytically.

The trick is to understand the constraints on where the end of the first bone can end up. It can't be further away from the target than the remaining bones can reach, ie.

```
Distance(1st bone end, target) <= Length(2nd bone) + Length(3rd bone)

```

And it also can't be closer to the target than the shortest length the remaining bones can fold to, ie.

```
Distance(1st bone end, target) >= Abs(Length(2nd bone) - Length(3rd bone)

```

And lastly, the endpoint of the first bone can't be closer or further from the start point than the bone's own length:

```
Distance(1st bone end, origin) = Length(1st bone)

```

Taking these three constraints together, we have an interesection between a circle (the sweep of the first bone) and an annulus (the allowable places the remaining bones can start and still reach the target)

Points where your 1st bone circle (red) intersects the outer rim of the annulus (teal) correspond to solutions where the 2nd and 3rd bone are pulled into a straight line to reach their maximum extent.

Points where it intersects the inner rim correspond to solutions where the remaining two bones are forced to fold 180 degrees to collapse as tightly as possible.

Any intermediate point along the arc(s) of overlap between the circle and annulus (fine solid red curves) are solutions where the second elbow bends some intermediate amount - tighter further in, looser further out.

You can pick any point you like along those curves of overlap - each of the infinite choices corresponds to a feasible solution (barring obstacles / joint angle limits). But some options along these arcs might be better than others, based on considerations like...

* Proximity to the arm's previous pose
* Continuity with the arm's previous motion
* Balancing the amount of bending between the joints
* Prioritizing more bending at freer joints and less at stiffer/more expensive joints

...etc. What heuristics/algorithms you apply here will depend on your context and how you want the arm to behave.
> 1 votes

---
Tags: mathematics, rigidbody, inverse-kinematics
---


# Question
Title: What's the difference between UClass and UObject?
I know that UCLASS() macro creates a seperate UClass for every UObject class ,but what is the need for this seperate class , how both of these classes relate to each other and what is the basic difference between both of them??

# Answer
> 9 votes
In Unreal Engine the base class used for every reference counted or garbage collected object is UObject. UObject is the base for classes like UActorComponent, AActor, APawn, AGameMode, etc. almost every single class in the entire engine.

UClass is also a UObject based class. UClass is a class that is used for meta/reflection.

Meta/reflection allows you to ask questions at runtime about the types in your project. What do I mean by types? I mean classes. A simple question might be. "What properties does this class have?" or "What methods does this class have?" A very helpful part of reflection is the ability to build very generic editors because all of the properties can be broken down into string entries, numeric fields, checkboxes, asset selectors, etc...

There are many classes used in Unreal's reflection system. UStruct, UField, UProperty, UEnum, UFunction, etc... Each one of these types maps to a different queryable attribute that a UObject based class can contain. As an aside you can also query meta/reflection on structs as well but only properties.

Meta/reflection is a common part of larger game engines but is not built into C++ natively. Some programming languages build that meta-data and reflection capabilities in, C# and Java both come to mind.

Because it isn't built into C++ natively game engines need to find a way of reflecting that data and making sure users know which data is reflected in an easy way. The unreal devs decided that marking your class with a syntax like UCLASS() and your methods with UFUNCTION() and properties with UPROPERTY() was a great way of explicitely defining which data/methods is going to be reflected.

Then during the compilation process they pre-process your header file and generate a new header file "yourfilename.generated.h" which includes all of the necessary reflection data that you marked up. They then run the rest of the compilation process and once your binaries/dlls are built they include reflection information, neat!

Here's a link to Unreal's article on reflection info. Unreal Property System (Reflection)

# Answer
> 0 votes
UCLASS(), UFUNCTION() and UPROPERTY() are macros that work with Unreal's reflection system to expose elements of the code to blueprints:

According to the doc:

> Calling Functions across the C++ and Blueprint Boundary So far, we have shown how to expose properties to Blueprints, but there is one last introductory topic that we should cover before you dive deeper into the engine. Whilee creating gameplay systems, designers will need to be able to call functions created by a C++ programmer. The programmer will also need to be able to call functions implemented in Blueprints from C++ code. Let us start by first making the CalculateValues() function callable from Blueprints. Exposing a function to Blueprints is just as simple as exposing a property. It takes only one macro placed before the function declaration! The code snippet below shows what is needed for this.
>
> ```
> UFUNCTION(BlueprintCallable, Category="Damage")
> void CalculateValues();
>
> ```
>
> The UFUNCTION() macro handles exposing the C++ function to the reflection system. The BlueprintCallable option exposes it to the Blueprint virtual machine. Every Blueprint exposed function requires a category associated with it, so that the right click context menu works properly. The image below shows how the category affects the context menu:

---
Tags: c++, unreal-4, terminology
---


# Question
Title: What is the proper way to handle data between scenes?
I am developing my first 2D game in Unity and I have come across what seems an important question.

How do I handle data between scenes?

There seems to be different answers to this:

* Someone mention using PlayerPrefs, while other people told me this should be used to store other things like screen brightness and so on.
* Someone told me that the best way was to make sure to write everything into a savegame everytime that I changed scenes, and to make sure that when the new scene loads, get the info from the savegame again. This seemed to me wasteful in performance. Was I wrong?
* The other solution, which is the one I have implemented so far is to have a **global game object** that isn't destroyed between scenes, handling all the data between scenes. So when the game starts, I load a **Start Scene** where this object is loaded. After this ends, it loads the first real game scene, usually a main menu.

This is my implementation:

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

public class GameController : MonoBehaviour {

    // Make global
    public static GameController Instance {
        get;
        set;
    }

    void Awake () {
        DontDestroyOnLoad (transform.gameObject);
        Instance = this;
    }

    void Start() {
        //Load first game scene (probably main menu)
        Application.LoadLevel(2);
    }

    // Data persisted between scenes
    public int exp = 0;
    public int armor = 0;
    public int weapon = 0;
    //...
}

```

This object can be handled on my other classes like this:

```
private GameController gameController = GameController.Instance;

```

While this has worked so far, it presents me with one big problem: If I want to load directly a scene, let's say for instance the final level of the game, I can't load it directly, since that scene does not contain this **global game object**.

Am I handling this problem the wrong way? Are there better practices for this kind of challenge? I would love to hear your opinions, thoughts and suggestions on this issue.

Thanks

# Answer
Listed in this answer are the fundamental ways of handling this situation. However, most of these methods do not scale well to large projects. If you want something more scalable and are not afraid of getting your hands dirty, check out the answer by Lea Hayes about **Dependency Injection** frameworks.

---

# 1. A static class for holding data only

You can create a static class to hold data only. Since it is static, you don't need to assign it to a GameObject (i.e. you don't need to create an instance of it). You can simply access your data such as `ClassName.Variable = data;` etc.

### Pros:

* No instance or singleton is required.
* You can access data from everywhere in your project.
* No extra code to pass values between scenes.
* All variables and data in a single database-like class make it easy to manage them.

### Cons:

* You cannot use a Coroutine inside a static class.
* You will probably end up with a huge class if you don't organize well.
* Since static classes cannot be assigned to GameObjects, you can't assign fields/variables inside the editor.

### An Example:

```
public static class PlayerStats
{
    public static int Kills { get; set; }
    public static int Deaths { get; set; }
    public static int Assists { get; set; }
    public static float Points { get; set; }
}

```

---

# 2. DontDestroyOnLoad

If you need your script to be assigned to a GameObject or derive from MonoBehavior, then you can add `DontDestroyOnLoad(gameObject);` line to your class where it can be executed once *(Placing it in `Awake()` is usually the way to go for this)*.

### Pros:

* All MonoBehaviour jobs (for example Coroutines) can be done safely.
* You can assign fields inside the editor.

### Cons:

* You will probably need to adjust your scene depending on the script.
* You will probably need to check which scene is loaded to determine what to do in Update() or other general functions/methods. For example, if you are doing something with UI in Update(), then you need to check if the correct scene is loaded to do the job. This may cause you to write lots of long if-else or switch-case statements.

---

# 3. PlayerPrefs

You can implement this if you also want your data to be stored even if the game gets closed.

### Pros:

* Easy to manage since Unity handles all background logic.
* You can pass data not only between scenes but also between instances (game sessions).

### Cons:

* Uses file system.
* Data can easily be changed from the prefs file.

---

# 4. Saving to a file

This is a bit overkill for storing values between scenes. If you don't need encryption, I discourage you from this method.

### Pros:

* You are in control of data saved as opposed to PlayerPrefs.
* You can pass data not only between scenes but also between instances (game sessions).
* You can transfer the file (user-generated content concept relies on this).

### Cons:

* Slow.
* Uses file system.
* Possibility of reading/loading conflicts caused by stream interruption while saving.
* Data can easily be changed from the file unless you implement encryption, which will make the code even slower.

---

# 5. Singleton pattern

Singleton pattern is a really controversial topic in object-oriented programming. Some suggest it, and some don't. Research it yourself and make the appropriate call depending on your project's needs and scale.

### Pros:

* Easy to both setup and use.
* You can access data from everywhere in your project.
* All variables and data in a single database-like class make it easy to manage them.

### Cons:

* Lots of boilerplate code whose only job is to maintain and secure the singleton instance.
* There are strong arguments against the use of singleton pattern. Be cautious and make your research beforehand.
* Possibility of data clash due to poor implementation.
* Unity may have a difficulty handling singleton patterns<sup>**1**</sup>.

---

**1**: In the summary of `OnDestroy` method of Singleton Script provided in Unify Wiki, you can see the author describing *ghost objects* which bleed into the editor from runtime:

> When Unity quits, it destroys objects in random order. In principle, a Singleton is only destroyed when the application quits. If any script calls Instance after it has been destroyed, it will create a buggy ghost object that will stay on the Editor scene even after stopping playing the Application. Really bad! So, this was made to be sure we're not creating that buggy ghost object.
> 112 votes

# Answer
A slightly more advanced option is to perform dependency injection with a framework like Zenject.

This leaves you free to structure your application however you want; for instance,

```
public class PlayerProfile
{
    public string Nick { get; set; }
    public int WinCount { get; set; }
}

```

You can then bind the type to the IoC (inversion of control) container. With Zenject this action is performed inside a `MonoInstaller` or a `ScriptableInstaller`:

```
public class GameInstaller : MonoInstaller
{
    public override void InstallBindings()
    {
        this.Container.Bind<PlayerProfile>()
            .ToSelf()
            .AsSingle();
    }
}

```

The singleton instance of `PlayerProfile` is then injected into other classes that are instantiated via Zenject. Ideally through constructor injection but property and field injection is also possible by annotating them with Zenject's `Inject` attribute.

The latter attribute technique is used to automatically inject the game objects of your scene since Unity instantiates these objects for you:

```
public class WinDetector : MonoBehaviour
{
    [Inject]
    private PlayerProfile playerProfile = null;

    private void OnCollisionEnter(Collision collision)
    {
        this.playerProfile.WinCount += 1;
        // other stuff...
    }
}

```

For whatever reason you might also want to bind an implementation by interface rather than by the implementation type. (Disclaimer, the following isn't supposed to be an amazing example; I doubt you'd want Save/Load methods in this particular location... but this just shows an example of how implementations could vary in behaviour).

```
public interface IPlayerProfile
{
    string Nick { get; set; }
    int WinCount { get; set; }

    void Save();
    void Load();
}

[JsonObject]
public class PlayerProfile_Json : IPlayerProfile
{
    [JsonProperty]
    public string Nick { get; set; }
    [JsonProperty]
    public int WinCount { get; set; }

    public void Save()
    {
        ...
    }

    public void Load()
    {
        ...
    }
}

[ProtoContract]
public class PlayerProfile_Protobuf : IPlayerProfile
{
    [ProtoMember(1)]
    public string Nick { get; set; }
    [ProtoMember(2)]
    public int WinCount { get; set; }

    public void Save()
    {
        ...
    }

    public void Load()
    {
        ...
    }
}

```

Which can then be bound to the IoC container in a similar way as before:

```
public class GameInstaller : MonoInstaller
{
    // The following field can be adjusted using the inspector of the
    // installer component (in this case) or asset (in the case of using
    // a ScriptableInstaller).
    [SerializeField]
    private PlayerProfileFormat playerProfileFormat = PlayerProfileFormat.Json;

    public override void InstallBindings()
    {
        switch (playerProfileFormat) {
            case PlayerProfileFormat.Json:
                this.Container.Bind<IPlayerProfile>()
                    .To<PlayerProfile_Json>()
                    .AsSingle();
                break;

            case PlayerProfileFormat.Protobuf:
                this.Container.Bind<IPlayerProfile>()
                    .To<PlayerProfile_Protobuf>()
                    .AsSingle();
                break;

            default:
                throw new InvalidOperationException("Unexpected player profile format.");
        }
    }

    public enum PlayerProfileFormat
    {
        Json,
        Protobuf,
    }
}

```
> 11 votes

# Answer
An ideal way to store variables between scenes is through a singleton manager class. By creating a class to store persistent data, and setting that class to `DoNotDestroyOnLoad()`, you can ensure it is immediately accessible and persists between scenes.

Another option you have is to use the `PlayerPrefs` class. `PlayerPrefs` is designed to allow you to save data *between play sessions*, but it will still serve as a means to save data *between scenes*.

## Using a singleton class and `DoNotDestroyOnLoad()`

The following script creates a persistent singleton class. A singleton class is a class that is designed to only run a single instance at the same time. By providing such functionality, we can safely create a static self-reference, to access the class from anywhere. This means that you can directly access the class with `DataManager.instance`, including any public variables inside the class.

```
using UnityEngine;

/// <summary>Manages data for persistance between levels.</summary>
public class DataManager : MonoBehaviour
{
    /// <summary>Static reference to the instance of our DataManager</summary>
    public static DataManager instance;

    /// <summary>The player's current score.</summary>
    public int score;
    /// <summary>The player's remaining health.</summary>
    public int health;
    /// <summary>The player's remaining lives.</summary>
    public int lives;

    /// <summary>Awake is called when the script instance is being loaded.</summary>
    void Awake()
    {
        // If the instance reference has not been set, yet,
        if (instance == null)
        {
            // Set this instance as the instance reference.
            instance = this;
        }
        else if(instance != this)
        {
            // If the instance reference has already been set, and this is not the
            // the instance reference, destroy this game object.
            Destroy(gameObject);
        }

        // Do not destroy this object, when we load a new scene.
        DontDestroyOnLoad(gameObject);
    }
}

```

---

You can see the singleton in action, below. Note that as soon as I run the initial scene, the DataManager object moves from the scene-specific heading to the "DontDestroyOnLoad" heading, on the hierarchy view.

## Using the `PlayerPrefs` class

Unity has a built in class to manage basic persistent data called `PlayerPrefs`. Any data committed to the `PlayerPrefs` file will persist across *game sessions*, so naturally, it is capable of persisting data across scenes.

The `PlayerPrefs` file can store variables of types `string`, `int` and `float`. When we insert values into the `PlayerPrefs` file, we provide an additional `string` as the key. We use the same key to later retrieve our values from the `PlayerPref` file.

```
using UnityEngine;

/// <summary>Manages data for persistance between play sessions.</summary>
public class SaveManager : MonoBehaviour
{
    /// <summary>The player's name.</summary>
    public string playerName = "";
    /// <summary>The player's score.</summary>
    public int playerScore = 0;
    /// <summary>The player's health value.</summary>
    public float playerHealth = 0f;

    /// <summary>Static record of the key for saving and loading playerName.</summary>
    private static string playerNameKey = "PLAYER_NAME";
    /// <summary>Static record of the key for saving and loading playerScore.</summary>
    private static string playerScoreKey = "PLAYER_SCORE";
    /// <summary>Static record of the key for saving and loading playerHealth.</summary>
    private static string playerHealthKey = "PLAYER_HEALTH";

    /// <summary>Saves playerName, playerScore and
    /// playerHealth to the PlayerPrefs file.</summary>
    public void Save()
    {
        // Set the values to the PlayerPrefs file using their corresponding keys.
        PlayerPrefs.SetString(playerNameKey, playerName);
        PlayerPrefs.SetInt(playerScoreKey, playerScore);
        PlayerPrefs.SetFloat(playerHealthKey, playerHealth);

        // Manually save the PlayerPrefs file to disk, in case we experience a crash
        PlayerPrefs.Save();
    }

    /// <summary>Saves playerName, playerScore and playerHealth
    // from the PlayerPrefs file.</summary>
    public void Load()
    {
        // If the PlayerPrefs file currently has a value registered to the playerNameKey,
        if (PlayerPrefs.HasKey(playerNameKey))
        {
            // load playerName from the PlayerPrefs file.
            playerName = PlayerPrefs.GetString(playerNameKey);
        }

        // If the PlayerPrefs file currently has a value registered to the playerScoreKey,
        if (PlayerPrefs.HasKey(playerScoreKey))
        {
            // load playerScore from the PlayerPrefs file.
            playerScore = PlayerPrefs.GetInt(playerScoreKey);
        }

        // If the PlayerPrefs file currently has a value registered to the playerHealthKey,
        if (PlayerPrefs.HasKey(playerHealthKey))
        {
            // load playerHealth from the PlayerPrefs file.
            playerHealth = PlayerPrefs.GetFloat(playerHealthKey);
        }
    }

    /// <summary>Deletes all values from the PlayerPrefs file.</summary>
    public void Delete()
    {
        // Delete all values from the PlayerPrefs file.
        PlayerPrefs.DeleteAll();
    }
}

```

Note that I take additional precautions, when handling the `PlayerPrefs` file:

* I have saved each key as a `private static string`. This allows me to guarantee I am always using the right key, and it means that if I have to change the key for any reason, I do not need to ensure I change all references to it.
* I save the `PlayerPrefs` file to the disk after writing to it. This probably won't make a difference, if you do not implement data persistence across play sessions. `PlayerPrefs` *will* save to the disk during a normal application close, but it may not naturally call if your game crashes.
* I actually *check* that each key *exists* in the `PlayerPrefs`, before I attempt to retrieve a value associated with it. This might seem like pointless double-checking, but it is a good practice to have.
* I have a `Delete` method that immediately wipes the `PlayerPrefs` file. If you do not intend to include data persistence across play sessions, you might consider calling this method on `Awake`. By clearing the `PlayerPrefs` file at the start of each game, you ensure that any data that *did* persist from the previous session is not mistakenly handled as data from the *current* session.

---

You can see `PlayerPrefs` in action, below. Note that when I click "Save Data", I am directly calling the `Save` method, and when I click "Load Data", I am directly calling the `Load` method. Your own implementation will likely vary, but it demonstrates the basics.

---

As a final note, I should point out that you can expand upon the basic `PlayerPrefs`, to store more useful types. JPTheK9 provides a good answer to a similar question, in which they provide a script for serialising arrays into string form, to be stored in a `PlayerPrefs` file. They also point us to the Unify Community Wiki, where a user has uploaded a more expansive `PlayerPrefsX` script to allow support for a greater variety of types, such as vectors and arrays.
> 4 votes

# Answer
You're doing things in a good way. It's the way I do it, and clearly the way many people do it because this autoloader script (you can set a scene to automatically load first whenever you hit Play) exists: http://wiki.unity3d.com/index.php/SceneAutoLoader

Both of the first two options are also things your game may need for saving the game between sessions, but those are wrong tools for this problem.
> 3 votes

# Answer
Many good answers but for **a more clear picture**, here is the picture cause picture tells a thousand words:

At your local system, you can effectively utilize `PlayerPrefs`, `DontDestoryOnLoad`, Static `variable`(Data) script, `System.IO` File handling, or SQLite database (The pros and cons already mentioned in above answer). While you can also use the server-side (which a bit slow but share across many many application instances). It can contain your custom code (your own server-side language and logics) or a third party(firebase, back4app, etc).
> 3 votes

# Answer
I use a functional approach I call Stateless Scenes. I don't like the God class, Singleton, DontDestroyOnLoad or static variables as they all have their quirks.

```
using UnityEngine;
public class MySceneBehaviour: MonoBehaviour {
    private static MySceneParams loadSceneRegister = null;

    public MySceneParams sceneParams;

    public static void loadMyScene(MySceneParams sceneParams, System.Action<MySceneOutcome> callback) {
        MySceneBehaviour.loadSceneRegister = sceneParams;
        sceneParams.callback = callback;
        UnityEngine.SceneManagement.SceneManager.LoadScene("MyScene");
    }

    public void Awake() {
        if (loadSceneRegister != null) sceneParams = loadSceneRegister;
        loadSceneRegister = null; // the register has served its purpose, clear the state
    }

    public void endScene (MySceneOutcome outcome) {
        if (sceneParams.callback != null) sceneParams.callback(outcome);
        sceneParams.callback = null; // Protect against double calling;
    }
}

[System.Serializable]
public class MySceneParams {
    public System.Action<MySceneOutcome> callback;
    // + inputs of the scene
}

public class MySceneOutcome {
    // + outputs of the scene
}

```

You can keep global state in the *caller*'s scope, so scene inputs and outputs states can be minimized (makes testing easy). To use it you can use anonymous functions:-

```
MyBigGameServices services ...
MyBigGameState bigState ...

Splash.loadScene(bigState.player.name, () => {
   FirstLevel.loadScene(bigState.player, (firstLevelResult) => {
       // do something else
       services.savePlayer(firstLevelResult);
   })
)}

```

More info at https://corepox.net/devlog/unity-pattern:-stateless-scenes
> 1 votes

---
Tags: unity
---


# Question
Title: How can I check if my object just stopped rotating this frame?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RotateRandom : MonoBehaviour
{
    private void Update()
    {
        if(Whilefun.FPEKit.FPEInteractionManagerScript.naviRotate == true)
        {
            transform.Rotate(0,0,100);
        }
        else
        {
            transform.eulerAngles = new Vector3(0, 0, 0);
        }
    }
}

```

I set the flag to true and false in another script. And here I want that each time the transform stops spinning, it should revert to looking forward once.

But since I wrote `transform.eulerAngles = new Vector3(0, 0, 0);` in the Update method, it will try to go back to facing forward every frame. I want it to do it only once each time it stops spinning.

# Answer
When the other script contains the information whether the object is currently rotating or not, then it can also contain the information whether it just stopped rotating. You are not saying how that other script works exactly, but I would assume it determines the state in its update method. In that case you could modify the update method like this:

```
void Update() {
       justStoppedRotating = false;
       if (naviRotate && /* condition occured which stops rotating */) {
             naviRotate = false;
             justStoppedRotating = true;
       }
}

```

The variable `justStoppedRotating` will only be true on those updates where the script changes from `naviRotate == true` to `naviRotate == false`.

You can then rewrite the Update-method of RotateRandom like this:

```
private void Update()
{
    if(Whilefun.FPEKit.FPEInteractionManagerScript.naviRotate)
    {
        transform.Rotate(0f, 0f, 10000f * Time.deltaTime);
    }

    if(Whilefun.FPEKit.FPEInteractionManagerScript.justStoppedRotating)
    {
        transform.eulerAngles = new Vector3(0, 0, 0);
    }
}

```

---

Alternative solution: If you can't or don't want to change the `FPEInteractionManagerScript`, then you could have the `RotateRandom` script remember the previous state in its own private variable:

```
public class RotateRandom : MonoBehaviour
{
    private bool previousNaviRotate;

    private void Update()
    {
        if(Whilefun.FPEKit.FPEInteractionManagerScript.naviRotate == true)
        {
            transform.Rotate(0f, 0f, 10000f * Time.deltaTime);
        }
        else if (previousNaviRotate == true)
        {
            transform.eulerAngles = new Vector3(0, 0, 0);
        }

        previousNaviRotate = Whilefun.FPEKit.FPEInteractionManagerScript.naviRotate;
    }
}

```

---

By the way: I took the liberty to apply the `Time.deltaTime` factor to the rotation speed. You don't want your objects to rotate with different speeds depending on the speed of the user's machine.
> 2 votes

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


# Question
Title: UE4 Multiplayer how to replicate Player name in lobby
I've been working on a little 1V1 snipper project to try and get a better grip on the replication and the game framework of unreal engine.

So after the core gameplay, I'm trying to make a lobby system. I've been able to make the player join together without any issues, but I struggle a little bit with the replication. I'm trying to show the player's name over their pawn in the lobby, and I can't get it to work. In the client, both their name doesn't get replicated, and in the server, only the server name appear:

And I get this error from the server logs

```
[2020.01.21-00.45.03:318][906]PIE: Error: Only Local Player Controllers can be assigned to widgets. BP_PlayerLobbyController_C_1 is not a Local Player Controller.
[2020.01.21-00.45.03:321][906]LogScript: Warning: Accessed None trying to read property CallFunc_Create_ReturnValue
        BP_PlayerLobbyController_C /Game/Maps/Lobby.Lobby:PersistentLevel.BP_PlayerLobbyController_C_1
        Function /Game/Player/Controller/BP_PlayerLobbyController.BP_PlayerLobbyController_C:ExecuteUbergraph_BP_PlayerLobbyController:0049
[2020.01.21-00.45.03:323][906]LogScript: Warning: Script call stack:
        Function /Game/Player/Controller/BP_PlayerLobbyController.BP_PlayerLobbyController_C:ReceiveBeginPlay
        Function /Game/Player/Controller/BP_PlayerLobbyController.BP_PlayerLobbyController_C:ExecuteUbergraph_BP_PlayerLobbyController

[2020.01.21-00.45.03:325][906]LogOnlineSession: Warning: OSS: No game present to join for session (GameSession)
[2020.01.21-00.45.03:326][906]LogTemp: POST LOGIN FOR
[2020.01.21-00.45.03:331][906]LogScript: Warning: Accessed None trying to read property CallFunc_GetController_ReturnValue
        BP_Character_Lobby_C /Game/Maps/Lobby.Lobby:PersistentLevel.BP_Character_Lobby_C_1
        Function /Game/Player/Character/BP_Character_Lobby.BP_Character_Lobby_C:Display Player Name:00CC
[2020.01.21-00.45.03:333][906]LogScript: Warning: Script call stack:
        Function /Game/Player/Character/BP_Character_Lobby.BP_Character_Lobby_C:ReceiveBeginPlay
        Function /Game/Player/Character/BP_Character_Lobby.BP_Character_Lobby_C:ExecuteUbergraph_BP_Character_Lobby
        Function /Game/Player/Character/BP_Character_Lobby.BP_Character_Lobby_C:Display Player Name

[2020.01.21-00.45.03:335][906]LogScript: Warning: Accessed None
        BP_Character_Lobby_C /Game/Maps/Lobby.Lobby:PersistentLevel.BP_Character_Lobby_C_1
        Function /Game/Player/Character/BP_Character_Lobby.BP_Character_Lobby_C:Display Player Name:00E1
[2020.01.21-00.45.03:337][906]LogScript: Warning: Script call stack:
        Function /Game/Player/Character/BP_Character_Lobby.BP_Character_Lobby_C:ReceiveBeginPlay
        Function /Game/Player/Character/BP_Character_Lobby.BP_Character_Lobby_C:ExecuteUbergraph_BP_Character_Lobby
        Function /Game/Player/Character/BP_Character_Lobby.BP_Character_Lobby_C:Display Player Name

```

So I get that something is wrong with accessing the 2nd player controller from bluprint like this

But I don't know how to make it work other wise. I've set the PlayerName widget to replicated, but it doesn't seem to work.

Any idea on how I could get this to work?

# Answer
> 3 votes
The PlayerControllers for all players exist only on the server. Each client only has its own PlayerController, but none of the others.

Calling GetController on a pawn will only work if you're on the server or if the pawn is locally controlled. Instead, get the PlayerState from the pawn directly.

Widgets exist *only* on each client, they can not and should not be replicated.

---
Tags: c++, multiplayer, unreal-4, unreal, blueprints
---


# Question
Title: How to properly build unity mesh from 3dsmax Triobj extracted data
I'm trying to make a importer for my mesh file exported from 3ds max sdk using triobj I already changed YZ vectors and extracted data is just like a obj file.

In unity I have no idea how to build it , it goes wrong:

Here's my code , I included mesh data :

```
using UnityEngine;

public class autodesk_3dsmax_mesh_import : MonoBehaviour
{
    public Material DefaultMaterial;
    private float scalefactor = 10.0f;

    class MeshFace
    {
        public int _vid { get; set; }
        public int _uid { get; set; }
        public int _nid { get; set; }

        public MeshFace(int vid,int uid,int nid) {
            _vid = vid; _uid = uid; _nid = nid;
        }
    }

    //// Exported data from 3DsMax using Trimesh API [YZ flip is applied]
    //// It's in *.obj data-type format
    private Vector3[] _3dsmax_vertexdata = {
      new Vector3(-5.000000f,-5.000000f,5.000000f),
      new Vector3(5.000000f,-5.000000f,5.000000f),
      new Vector3(-5.000000f,-5.000000f,-5.000000f),
      new Vector3(5.000000f,-5.000000f,-5.000000f),
      new Vector3(-5.000000f,5.000000f,5.000000f),
      new Vector3(5.000000f,5.000000f,5.000000f),
      new Vector3(-5.000000f,5.000000f,-5.000000f),
      new Vector3(5.000000f,5.000000f,-5.000000f)
    };
    private Vector3[] _3dsmax_normaldata = {
      new Vector3(0.000000f,-1.000000f,0.000000f),
      new Vector3(0.000000f,-1.000000f,0.000000f),
      new Vector3(0.000000f,-1.000000f,0.000000f),
      new Vector3(0.000000f,-1.000000f,0.000000f),
      new Vector3(0.000000f,1.000000f,0.000000f),
      new Vector3(0.000000f,1.000000f,0.000000f),
      new Vector3(0.000000f,1.000000f,0.000000f),
      new Vector3(0.000000f,1.000000f,0.000000f),
      new Vector3(0.000000f,0.000000f,1.000000f),
      new Vector3(0.000000f,0.000000f,1.000000f),
      new Vector3(0.000000f,0.000000f,1.000000f),
      new Vector3(0.000000f,0.000000f,1.000000f),
      new Vector3(1.000000f,0.000000f,0.000000f),
      new Vector3(1.000000f,0.000000f,0.000000f),
      new Vector3(1.000000f,0.000000f,0.000000f),
      new Vector3(1.000000f,0.000000f,0.000000f),
      new Vector3(0.000000f,0.000000f,-1.000000f),
      new Vector3(0.000000f,0.000000f,-1.000000f),
      new Vector3(0.000000f,0.000000f,-1.000000f),
      new Vector3(0.000000f,0.000000f,-1.000000f),
      new Vector3(-1.000000f,0.000000f,0.000000f),
      new Vector3(-1.000000f,0.000000f,0.000000f),
      new Vector3(-1.000000f,0.000000f,0.000000f),
      new Vector3(-1.000000f,0.000000f,0.000000f)
    };
    private Vector2[] _3dsmax_uvdata = {
      new Vector2(0.000000f,0.000000f),
      new Vector2(1.000000f,0.000000f),
      new Vector2(0.000000f,1.000000f),
      new Vector2(1.000000f,1.000000f),
      new Vector2(0.000000f,0.000000f),
      new Vector2(1.000000f,0.000000f),
      new Vector2(0.000000f,1.000000f),
      new Vector2(1.000000f,1.000000f),
      new Vector2(0.000000f,0.000000f),
      new Vector2(1.000000f,0.000000f),
      new Vector2(0.000000f,1.000000f),
      new Vector2(1.000000f,1.000000f)
        };
    private MeshFace[] _3dsmax_facedata = {
      new MeshFace(4,11,1),
      new MeshFace(2,9,2),
      new MeshFace(1,10,3),
      new MeshFace(1,10,3),
      new MeshFace(3,12,4),
      new MeshFace(4,11,1),
      new MeshFace(8,12,5),
      new MeshFace(7,11,6),
      new MeshFace(5,9,7),
      new MeshFace(5,9,7),
      new MeshFace(6,10,8),
      new MeshFace(8,12,5),
      new MeshFace(6,8,9),
      new MeshFace(5,7,10),
      new MeshFace(1,5,11),
      new MeshFace(1,5,11),
      new MeshFace(2,6,12),
      new MeshFace(6,8,9),
      new MeshFace(8,4,13),
      new MeshFace(6,3,14),
      new MeshFace(2,1,15),
      new MeshFace(2,1,15),
      new MeshFace(4,2,16),
      new MeshFace(8,4,13),
      new MeshFace(7,8,17),
      new MeshFace(8,7,18),
      new MeshFace(4,5,19),
      new MeshFace(4,5,19),
      new MeshFace(3,6,20),
      new MeshFace(7,8,17),
      new MeshFace(5,4,21),
      new MeshFace(7,3,22),
      new MeshFace(3,1,23),
      new MeshFace(3,1,23),
      new MeshFace(1,2,24),
      new MeshFace(5,4,21),
    };

    void Start()
    {
        uint v_count = 8; uint n_count = 24;
        uint t_count = 12; uint f_count = 36;

        //// Extracted From 3DsMax
        string obj_name = "Box_001";
        Vector3 object_pos = new Vector3(0, 0.5f, 0);
        Quaternion object_rot = new Quaternion(0,0,0,0);
        Vector3 object_scale = new Vector3(1f,1f,1f);

        GameObject simple_mesh = new GameObject(obj_name);
        simple_mesh.transform.position = object_pos;
        simple_mesh.transform.rotation = object_rot;

        simple_mesh.AddComponent<MeshFilter>();
        simple_mesh.AddComponent<MeshRenderer>();

        Mesh mesh = simple_mesh.GetComponent<MeshFilter>().mesh;
        mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;

        Vector3[] vertex_data   =   new Vector3[f_count];
        Vector3[] normal_data   =   new Vector3[f_count];
        Vector2[] texcoord_data =   new Vector2[f_count];
        int[] triangles         =   new int[f_count];

        for (int i = 0; i < f_count; i++)
        {
            int vertex_id = _3dsmax_facedata[i]._vid - 1;
            int texcoord_id = _3dsmax_facedata[i]._uid - 1;
            int normal_id = _3dsmax_facedata[i]._nid - 1;

            float vtx_x = _3dsmax_vertexdata[vertex_id].x;
            float vtx_y = _3dsmax_vertexdata[vertex_id].y;
            float vtx_z = _3dsmax_vertexdata[vertex_id].z;

            vertex_data[i] = new Vector3(vtx_x / scalefactor, vtx_y / scalefactor, vtx_z / scalefactor);

            float nrm_x = _3dsmax_normaldata[normal_id].x;
            float nrm_y = _3dsmax_normaldata[normal_id].y;
            float nrm_z = _3dsmax_normaldata[normal_id].z;

            normal_data[i] = new Vector3(nrm_x , nrm_y , nrm_z );

            float uv_x = _3dsmax_uvdata[texcoord_id].x;
            float uv_y = _3dsmax_uvdata[texcoord_id].y;

            texcoord_data[i] = new Vector2(uv_x, uv_y);

            triangles[i] = vertex_id;
        }

        mesh.Clear();
        mesh.vertices =vertex_data;
        mesh.normals = normal_data;
        mesh.uv = texcoord_data;
        mesh.triangles = triangles;
        mesh.RecalculateNormals();
        simple_mesh.GetComponent<MeshRenderer>().material = DefaultMaterial;

    }
}

```

Data is a simple 3ds max box.

What am I doing wrong? How can I make it work?

# Answer
Your `for` loop is doing too much work. Here's a version that should do what you want; I'm not convinced it's the right way to do it:

```
        Vector3[] vertex_data   =   new Vector3[f_count];
        Vector3[] normal_data   =   new Vector3[f_count];
        Vector2[] texcoord_data =   new Vector2[f_count];
        int[] triangles         =   new int[f_count];

        for (int i = 0; i < f_count; i++)
        {
            triangles[i] = i;
            var face = _3dsmax_facedata[i];
            vertex_data[i] = _3dsmax_vertexdata[face._vid-1];
            normal_data[i] = _3dsmax_normaldata[face._nid-1];
            texcoord_data[i] = _3dsmax_uvdata[face._uid-1];
        }

        mesh.Clear();
        mesh.vertices = vertex_data;
        mesh.normals = normal_data;
        mesh.uv = texcoord_data;
        mesh.triangles = triangles;

```

The key here is to understand that `triangles` contains an array of indexes into the entire set of (vertex, normal, uv) data. The underlying code will use that in batches of 3 to create triangles. Each index needs to have all the relevant pieces at the same index in all three datasets. This is wasteful, but I don't know Unity's mesh system well enough to offer an alternative.
> 0 votes

---
Tags: unity, 3dsmax
---


# Question
Title: How can I calculate normals using a vertex and index buffer?
Is it possible to calculate normals using the positions in a vertex buffer and index buffer? Would someone show pseudocode for the algorithm?

# Answer
> 5 votes
Yes it is, here is how you can do:

Every vertex in the vertex buffer is represented by one index which may occur several times in the index buffer. What you first need to do is to make a function that for a index returns the corresponding vertex. Should be fairly trivial.

I am going to assume that the mesh is rendered as GL\_TRIANGLES

```
for every 3 indexeses in index buffer
  edge1 = index1 - index2
  edge2 = index1 - index3

  var normal = edge1 cross edge2

```

Simple as that! This normal can either be sent once for every 3 vertices making up a face, or one time for every 3 vertices

This normal though, will be a face normal, meaning that you will get a flat looking shading, so what you might want to do is calculate the interpolated per vertex normals. What you do then is that you for every vertex keep a map that tells which face this vertex belongs to. Then for all vertexes you take all faces that this vertex belongs to, take their normals, add them together and then normalize the resulting vector. Maybe you should even weight the face normals according to size of the face

# Answer
> 3 votes
Another user was struggling to implement this with the existing answer, so I thought I'd show a slightly deeper code example for folks in a similar situation.

I'll use Unity C# syntax since it's what I use most often, but the same steps can be applied to any language/framework.

```
CalculateVertexNormals(Vector3[] vertexPositions, int[] triangleIndices, Vector3[] vertexNormals)
{

    // Zero-out our normal buffer to start from a clean slate.
    for(int vertex = 0; vertex < vertexPositions.Length; vertex++)
        vertexNormals[vertex] = Vector3.zero;

    // For each face, compute the face normal, and accumulate it into each vertex.
    for(int index = 0; index < triangleIndices.Length; index += 3) {
        int vertexA = triangleIndices[index];
        int vertexB = triangleIndices[index + 1];
        int vertexC = triangleIndices[index + 2];

        var edgeAB = vertexPositions[vertexB] - vertexPositions[vertexA];
        var edgeAC = vertexPositions[vertexC] - vertexPositions[vertexA];

        // The cross product is perpendicular to both input vectors (normal to the plane).
        // Flip the argument order if you need the opposite winding.
        var areaWeightedNormal = Vector3.Cross(edgeAB, edgeAC);

        // Don't normalize this vector just yet. Its magnitude is proportional to the
        // area of the triangle (times 2), so this helps ensure tiny/skinny triangles
        // don't have an outsized impact on the final normal per vertex.

        // Accumulate this cross product into each vertex normal slot.
        vertexNormals[vertexA] += areaWeightedNormal;
        vertexNormals[vertexB] += areaWeightedNormal;
        vertexNormals[vertexC] += areaWeightedNormal;
    }

    // Finally, normalize all the sums to get a unit-length, area-weighted average.
    for(int vertex = 0; vertex < vertexPositions.Length; vertex++)
        vertexNormals[vertex] = Vector3.Normalize(normal);
}

```

---
Tags: mathematics
---


# Question
Title: Why is the origin in computer graphics coordinates at the top left?
From what I've seen almost all things use coordinates where (0, 0) is at the top left and the positive Y-axis goes in the downwards direction of your screen.

Why is it like this? Why not the conventional positive Y-axis going upwards like shown in graphs in simple math classes?

# Answer
This is caused in the history. Early computers had Cathode Ray Tubes (CRTs) which "draw" the image with a cathode ray from the upper left corner to the lower right.

To ease the interface between the graphics card memory and the CRT the memory was read from the beginning and the image was drawn from the top left (with the lowest memory address) to the lower right (with the highest memory address).

**Extension (based on the comments)**

The CRTs are based on analog TV sets that were available at that time.

The TV sets create the image line by line first from left to right and then from top to bottom. The reason for this can only be assumed to be based on the writing style in western contries.
> 56 votes

# Answer
This is a great question that I've thought of many times. The simple answer to "why" is because TV formats also drew their lines from left-to-right then top-to-bottom. Original computer monitors were CRT screens (small TVs), so the format naturally stayed the same. When monitors became flat screens (and TVs became flat screens too), it was equally natural to keep the same format for easy compatibility.

Of course you can then ask: why do TVs draw this way? They were invented in the early 20th century so you can imagine how much thought or lack thereof went into the design, if it was even questioned. **Note:** not meant to be disrespectful as it is incredibly more challenging to get equations for magnetically deflecting rays to the proper lines on a screen, as opposed to a simple matrix of tiny "light bulbs". (This kinda brings up the question of how on Earth did they invent CRTs before the simple matrix of dots, way back in the early 20th century?)

Nevertheless, my guess is that probably it was never questioned (a bad thing) since the Western languages write words left-to-right and top-to-bottom. Probably no one conceived of the possibility of doing it differently.

Personally, I dislike this format. I gained this attitude as I programmed games and other simulations involving elliptical orbits. **Whenever you look up drawing equations involving sin, cos, or tan, you have to carefully invert the signs that deal with the y-axis parameters...or you will get the wrong thing drawn.** An example would be the parametric equations for an ellipse drawn at any 2D angle. It can be a real nightmare dissecting the sin*sin, sin*cos, and similar things.

Succinctly speaking in mathematical terms, **the screen is in Quadrant 4 instead of Quadrant 1.** This is unnecessarily complicated.

BTW when you get to 3 dimensions, the z axis is considered to go "upwards" in the positive direction. Kinda ironic. \[EDIT\]: Maybe not, see my comment below.

**2 more things I realized/came across:**

Sundials in the northern hemisphere (that have north-facing pointers and disks parallel to the ground) always rotate **clockwise**. So if we put the zero hour at the top of the "clock face", then the shadow pointer starts moving to the right. This could be the origin of left-to-right direction in western languages, propagating down to Cartesian coordinates and TV/computer screens.

Old computers did not draw graphical objects so much. **They drew text in a command prompt.** So it is natural to put line 0 at y=0. If we had a bottom-left origin, the math of drawing textlines would be a bit more involved, and it could've been a big deal to those old slow computers (who even made a shortcut for incrementing by 1, for goodness sakes, called "++"). Plus you need to know the resolution of the screen, whereas if you just do line 0 at y=0, you don't need to know the resolution.
> 7 votes

# Answer
Addendum: Early graphics were done on vector monitors, just one step up from the oscilloscopes seen in the lab where (0,0) would be in the exact middle of the screen, subject to some knob turning to set X/Y scale, X/Y offset, and possibly X/Y inversion.

The dedicated hardware of Atari "Asteroids" (1979) for example used a vector screen; it would be interesting to know what it thought its program coordinate system was.

Ivan Sutherland's "Sketchpad" system (1963) was based on a TX-2 vector display, and in "Sketchpad: A Man-Machine Graphical Communication System" (PhD thesis, January 1963), he writes on page 70ff:

> The coordinate system of the TX-2 display system has origin at the center of the scope and requires ten bits of deflection information located at the left of 18 bit computer subwords for each axis.
>
> ...
>
> For convenience in representing many component variables and for more than 18 bit precision, Sketchpad uses an internal coordinate system for drawing representation divorced from the representation required by the display system. This internal system is called the "page" coordinate system. In thinking of the drawings in Sketchpad, the page coordinates are considered as fixed. A page to scope transformation gives the ability to view on the scope any portion of the page desired, at any degree of magnification, as if through a magnifying glass (...) A scale factor for the display controls the size of the square which will appear on the scope. The actual number saved is the half-length of the side of the square, called SCSZ for SCope SiZe) as shown in Figure 5.2. Also saved are the page coordinates of the center of the scope square. By changing these numbers the portion of the page shown on the scope may be changed in size and moved, but not rotated.

Diagram 5.2 on page 73 shows that the "page coordinate system" uses the mathematical convention of the X/Y cartesian coordinate system. (One might ask why that convention is the way it is...)
> 5 votes

# Answer
Not everything is top-left.

OpenGL, for example, specifies that the origin is at *bottom*-left, and this is pervasive throughout the API: texture coordinates, viewports, texel rectangles, the standard ortho projection: it's bottom-left all the way.

There is a difference in thinking here.

On computer screens, as with books, when people read (and I'm assuming a language like English here) they read from left-to-right and top-to-bottom. You did it yourself when you wrote this question and you're doing it when you're reading answers to it.

In mathematics and design when you plot a graph, you have an X and a Y axis with positive X going left and positive Y going up.

If you're building something like a 2D GUI in a game it can be easier and more intuitive to many people to lay it out in a "top-left is the origin" manner.

If you're building something to mimic a design or layout on graph paper it can be easier and more intuitive to many people to lay it out in a "bottom-left is the origin" manner.

In fact both of these are quite informal conventions, and if you're setting up an ortho projection you can actually choose to have your origin at any arbitrary point on (or off) the screen, with positive X going either left or right and positive Y going either up or down. It's just a matter of adjusting your projection matrix accordingly.

The only important thing is therefore to choose which convention you're going to use and use it consistently.
> 3 votes

# Answer
**An argument FOR:** (By Example)

```
var R uint32 = 0xFF0000FF; //:Red pixel
var W uint32 = 0xFFFFFFFF; //:White Pixel.
var Pixels []uint32 = {
W,W,W,R,R,W,W,W,
W,W,R,R,R,R,W,W,
W,R,R,R,R,R,R,W,
W,W,W,R,R,W,W,W,   //:8x8 pixel image of " ↑ "
W,W,W,R,R,W,W,W,
W,W,W,R,R,W,W,W,
W,W,W,R,R,W,W,W,
W,W,W,R,R,W,W,W, }

```

**Code matches results on screen**:

Red arrow would be **upside-down** if you did NOT use top-left origin.

I can't say if this is "why". Just that, it's a good reason for top-left origin.
> 0 votes

# Answer
None of the above answers reflect the reality of early image rendering on an teletype. The 'bottom' of a vector drawn was printed first - i.e at the (final) bottom of the page. Removing the page after printout showed the image correctly displayed. Later slavish inversion of Y (in most applications) is nothing more than an annoyance, as today we have image, rather than teletype rendering. I'm constantly annoyed at having to invert Y when using modern applications - why don't folks just wise up?
> 0 votes

# Answer
Because screens start rendering the image from top left corner. It would be easier to co-relate the rendering or drawing of co-ordinate axis when (0,0,0) is at the top left corner with + Y-axis going into the screen.
> -1 votes

---
Tags: coordinates, graph
---


# Question
Title: Updating object's property on Start is visible for a second when game loads
I have a world selection scene in which I have `GameObject`s representing worlds. The `GameObject`s have default properties when the scene is loaded. For example: the world name text is red and each world has a "locked" status. This initial state can be seen in the following screenshot:

On the `Start()` method I'm dynamically updating the properties on each `GameObject` based on values I'm reading from a save file. If a world is unlocked the name text is set to white. If a world is currently selected the name text is set to green. Here's what that looks like at run time:

The problem is that when the scene is loaded from another scene(e.g. by clicking a navigation button) the initial state of the `GameObject`s can be seen for a second and then they change to the proper values as dictated by the save file. How can I prevent this from happening? I was under the impression that anything that happens in the `Start()` method takes place before `GameObject`s are rendered.

Here's some slimmed down code of what my code looks like:

```
    var worldIcons = FindObjectsOfType<WorldIcon>().OrderBy(x => x.WorldNumber).ToList();
    var saveFile = GameSaveManager.GetSaveFile();

    if (saveFile == null)
    {
        Debug.LogError("Could not find save file while loading worlds");
        return;
    }

    foreach (var worldIcon in worldIcons)
    {
        var savedWorld = saveFile.Worlds.SingleOrDefault(x => x.Number == worldIcon.WorldNumber);

        if (savedWorld == null)
        {
            //add world to save file
            GameSaveManager.CreateWorld(worldIcon.Controller);

            //unlock first world by default
            if (saveFile.Worlds.Count == 0 && worldIcon.WorldNumber == 1)
                worldIcon.Unlocked = LevelMapController.LockedStatus.Unlocked.ToString();
        }
        else
        {
            worldIcon.DisplayName = savedWorld.Name;
            worldIcon.WorldNumber = savedWorld.Number;

            var button = worldIcon.GetComponent<Button>();

            if (savedWorld.Unlocked)
            {
                button.interactable = true;
                button.targetGraphic.color = Color.white;
                worldIcon.Unlocked = LevelMapController.LockedStatus.Unlocked.ToString();
            }
            else
                worldIcon.Unlocked = LevelMapController.LockedStatus.Locked.ToString();
        }
    }

```

# Answer
I finally figured out what was going on. It turns out that it only *looked* like the World `GameObject`s weren't initialized before the scene was rendered. Each world `GameObject` has a button whose `Target Graphic` property is set to a child `Text` object called `DisplayName`. This child object displays the world's name(World1, etc.) The button's `Fade Duration` property is set to 0.1 by default. The problem was fixed by changing this property to 0.
> 1 votes

# Answer
> I was under the impression that anything that happens in the Start() method takes place before GameObjects are rendered.

No, here is a link that breakdowns the unity events execution order

And also, loading files and loops might take time, a workaround will be to put your buttons under a CanvasGroup component with an alpha of 0 til everything is loaded.
> -2 votes

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


title: How to reset snake in javafx game?

text:
# Question
Title: How to reset snake in javafx game?
I am making snake in javafx, I have completed my game, and I am trying to add a reset button in my game. When I click the reset key (ENTER), the game should reset, but the arraylist that stores the rectangles that make up the snake does not reset. For the life of me, I cannot figure out how to make it work. Any help is appreciated, thanks!

Code: https://pastebin.com/yiQi8DSU

Code:

```
package finalproject;

public class FinalProject extends Application {

Random rand = new Random();

Pane canvas;
Scene scene;
double points1[] = {100, 100, 1200, 100, 1200, 900, 100, 900,};
Polygon poly1;
Text Score, HighScore, GameOver, Reset, Time;
Font font1, font2;
Rectangle SnakeBody, Food, EndScreen, SpeedBoost, ScoreMultiplier;
ArrayList<Rectangle> Snakes;
int RIGHT = 0, UP = 1, LEFT = 2, DOWN = 3;
int facing = 0;
int rightSpeed = 0, upSpeed = 0, leftSpeed = 0, downSpeed = 0;
int SnakeSpeed = 4;
int score = 0;
int Multiplier = 0;
int Booster = 0;
int Score2 = 0;
//int timeCount = 2000;
// long second = 1000000000;

public void Objects() {

    facing = RIGHT;

    Food = new Rectangle(600, 600, 20, 20);
    Food.setStroke(Color.RED);
    Food.setFill(Color.RED);

    SpeedBoost = new Rectangle(4000, 4000, 20, 20);
    SpeedBoost.setStroke(Color.WHITE);
    SpeedBoost.setFill(Color.PURPLE);

    ScoreMultiplier = new Rectangle(4000, 4000, 15, 15);
    ScoreMultiplier.setStroke(Color.WHITE);
    ScoreMultiplier.setFill(Color.CHARTREUSE);

}

public void reset() {

    SnakeBody.setX(150);
    SnakeBody.setY(150);

    Food.setX(600);
    Food.setY(600);

    rightSpeed = 0;
    upSpeed = 0;
    leftSpeed = 0;
    downSpeed = 0;
    SnakeSpeed = 4;

    if (canvas.getChildren().contains(SpeedBoost)) {
        canvas.getChildren().remove(SpeedBoost);
    }

    if (canvas.getChildren().contains(ScoreMultiplier)) {
        canvas.getChildren().remove(ScoreMultiplier);
    }

    score = 0;
    Score.setText("Score: " + score);

    Snakes.clear();

    Objects();
    ;

}

private class Timer extends AnimationTimer {

    @Override

    public void handle(long l) {

        // Timer timer2 = new Timer();
        Shape overlap2 = Shape.intersect(SnakeBody, SpeedBoost);

        if (overlap2.getBoundsInLocal().getWidth() > 0 || overlap2.getBoundsInLocal().getHeight() > 0) {

            SpeedBoost.setX(4000); //Moves the object outside of the canvas.
            SpeedBoost.setY(4000);

            Booster = 10;
        }

        Shape overlap3 = Shape.intersect(SnakeBody, ScoreMultiplier);

        if (overlap3.getBoundsInLocal().getWidth() > 0 || overlap3.getBoundsInLocal().getHeight() > 0) {

            ScoreMultiplier.setX(4000); //Moves the object outside of the canvas.
            ScoreMultiplier.setY(4000);

            Multiplier = 10;

        }

        //Snake moving lines
        if (rightSpeed > 0 && facing != RIGHT) {

            facing = RIGHT;

        } else {

            for (int i = Snakes.size() - 1; i > 0; i--) {

                Snakes.get(i).setX(Snakes.get(i - 1).getX());
                Snakes.get(i).setY(Snakes.get(i - 1).getY());

            }

        }

        SnakeBody.setX(SnakeBody.getX() + rightSpeed - leftSpeed);
        SnakeBody.setY(SnakeBody.getY() + downSpeed - upSpeed);

        //Boundaries for the snake
        if (SnakeBody.getX() <= 100 || SnakeBody.getY() <= 100) {

            if (!canvas.getChildren().contains(EndScreen)) {
                canvas.getChildren().addAll(EndScreen, GameOver);

            }

        }

        if (SnakeBody.getX() >= 1170 || SnakeBody.getY() >= 870) {

            if (!canvas.getChildren().contains(EndScreen)) {
                canvas.getChildren().addAll(EndScreen, GameOver);

            }
        }

        Shape overlap = Shape.intersect(SnakeBody, Food);

        if (overlap.getBoundsInLocal().getWidth() > 0 || overlap.getBoundsInLocal().getHeight() > 0) {

            Food.setX(rand.nextInt(1200));
            Food.setY(rand.nextInt(900));

            if (Multiplier == 5) {

                Score2 = Score2 + 1;
                Score.setText("Score: " + Score2);

            } else {

                score = score + 1;
                Score.setText("Score: " + score);

            }

            if (score > 5) {

                if (!canvas.getChildren().contains(SpeedBoost)) {

                    SpeedBoost.setX(350);
                    SpeedBoost.setY(350);

                    canvas.getChildren().add(SpeedBoost);

                }
            }

            if (score >= 4) {

                if (!canvas.getChildren().contains(ScoreMultiplier)) {

                    ScoreMultiplier.setX(100);
                    ScoreMultiplier.setY(100);

                    canvas.getChildren().add(ScoreMultiplier);
                }
            }

            if (leftSpeed > 0) {

                for (int i = 0; i < 5; i++) { //Adds 5x the rectangles, preventing the slow growing.

                    Rectangle r = new Rectangle(Snakes.get(Snakes.size() - 1).getX(), Snakes.get(Snakes.size() - 1).getY(), 30, 30);
                    Snakes.add(r);
                    r.setFill(Color.GOLD);
                    r.setStroke(Color.WHITE);
                    canvas.getChildren().addAll(r);

                }
            }

            if (rightSpeed > 0) {

                for (int i = 0; i < 5; i++) {

                    Rectangle r = new Rectangle(Snakes.get(Snakes.size() - 1).getX(), Snakes.get(Snakes.size() - 1).getY(), 30, 30);
                    Snakes.add(r);
                    r.setFill(Color.GOLD);
                    r.setStroke(Color.WHITE);

                    canvas.getChildren().addAll(r);
                }

            }

            if (upSpeed > 0) {

                for (int i = 0; i < 5; i++) {
                    Rectangle r = new Rectangle(Snakes.get(Snakes.size() - 1).getX(), Snakes.get(Snakes.size() - 1).getY(), 30, 30);

                    Snakes.add(r);
                    r.setFill(Color.GOLD);
                    r.setStroke(Color.WHITE);
                    canvas.getChildren().addAll(r);
                }

            }

            if (downSpeed > 0) {

                for (int i = 0; i < 5; i++) {
                    Rectangle r = new Rectangle(Snakes.get(Snakes.size() - 1).getX(), Snakes.get(Snakes.size() - 1).getY(), 30, 30);

                    Snakes.add(r);

                    r.setFill(Color.GOLD);
                    r.setStroke(Color.WHITE);
                    canvas.getChildren().addAll(r);
                }
            }

        }

        if (Food.getX() <= 100) {
            Food.setX(rand.nextInt(1200));

        }

        if (Food.getY() <= 100) {
            Food.setY(rand.nextInt(900));

        }

        if (Food.getX() >= 1170) {
            Food.setX(rand.nextInt(1200));

        }

        if (Food.getY() >= 870) {
            Food.setY(rand.nextInt(900));

        }

    }

}

public void start(Stage primaryStage) {

    canvas = new Pane();
    scene = new Scene(canvas, 1300, 1300, Color.BLACK);
    Objects();

    /*Shape overlap5 = Shape.intersect(SnakeBody, Food);

    if (overlap5.getBoundsInLocal().getWidth() > 0 || overlap5.getBoundsInLocal().getHeight() > 0) {

        timeCount = timeCount - 1;
        Time = new Text(700, 60, "Time Survived: " + timeCount);
        Time.setFont(font1);
        Time.setFill(Color.YELLOW);

    }*/
    EndScreen = new Rectangle(1300, 1300);
    EndScreen.setFill(Color.BLACK);

    poly1 = new Polygon(points1);
    poly1.setFill(Color.DARKBLUE);
    poly1.setStroke(Color.GREY);
    poly1.setStrokeWidth(3);

    font1 = Font.font("Arial", 24);
    font2 = Font.font("Arial", 48);

    GameOver = new Text(500, 500, "Game Over");
    GameOver.setFont(font2);
    GameOver.setFill(Color.RED);

    //Reset = new Text(650, 650, "You survived for: " + timeCount);
    Score = new Text(250, 60, "Score: " + score);
    Score.setFont(font1);
    Score.setFill(Color.YELLOW);

    HighScore = new Text(700, 60, "High Score: ");
    HighScore.setFont(font1);
    HighScore.setFill(Color.YELLOW);

    canvas.getChildren().addAll(poly1, Score, Food);
    Snakes = makeSnakeBodies();
    canvas.getChildren().addAll(Snakes);

    scene.setOnKeyPressed(new EventHandler<KeyEvent>() {

        public void handle(KeyEvent evt) {

            if (Multiplier == 10) {

                Score2 = score * 2; //Multiplies score

                Multiplier = 5; //Any value other than 10

            }

            if (Booster == 10) {

                if (evt.getCode().equals(KeyCode.Q)) {

                    SnakeSpeed = 15;

                }

                if (evt.getCode().equals(KeyCode.A)) {

                    SnakeSpeed = 4;

                }
            }

            if (evt.getCode().equals(KeyCode.ENTER)) {

                reset();

                //AnimationTimer class1 = new Timer(); // Code resets the Objects() method but not the animation timer class
            }

            if (evt.getCode().equals(KeyCode.RIGHT) && leftSpeed == 0) {

                rightSpeed = SnakeSpeed;
                upSpeed = 0;
                leftSpeed = 0;
                downSpeed = 0;

            } else if (evt.getCode().equals(KeyCode.UP) && downSpeed == 0) {

                upSpeed = SnakeSpeed;
                rightSpeed = 0;
                leftSpeed = 0;
                downSpeed = 0;

            } else if (evt.getCode().equals(KeyCode.DOWN) && upSpeed == 0) {

                downSpeed = SnakeSpeed;
                rightSpeed = 0;
                leftSpeed = 0;
                upSpeed = 0;

            } else if (evt.getCode().equals(KeyCode.LEFT) && rightSpeed == 0) {

                leftSpeed = SnakeSpeed;
                rightSpeed = 0;
                upSpeed = 0;
                downSpeed = 0;

            }

        }

    });

    primaryStage.setTitle("Snake");
    primaryStage.setScene(scene);
    primaryStage.show();
    Timer timer = new Timer();
    timer.start();

}

public ArrayList<Rectangle> makeSnakeBodies() {

    ArrayList<Rectangle> joints = new ArrayList<>();

    int x = 150;
    int y = 150;

    SnakeBody = new Rectangle(x, y, 30, 30);
    SnakeBody.setFill(Color.GOLD);
    SnakeBody.setStroke(Color.WHITE);
    joints.add(SnakeBody);

    return joints;

}

}

```

---

If you need specific sections of code, I can post them separately. Thanks again!

# Answer
> 2 votes
You are adding the Snake body to your canvas but you never remove it. That's why `reset()` won't clear your Snake.

You're adding the Snake body within your `start()` method:

```
Snakes = makeSnakeBodies();
canvas.getChildren().addAll(Snakes); //HERE you add the Snakes

```

now the `Snakes` are added to your `Canvas` (well: `Pane`) but they are never removed.

## Solution:

you should remove the `Snakes` later in your `reset()` method as well:

```
public void reset() {
    SnakeBody.setX(150);
    SnakeBody.setY(150);
    ...
    if (canvas.getChildren().contains(SpeedBoost)) {
        canvas.getChildren().remove(SpeedBoost);
    }
    ...
    canvas.getChildren().removeAll(Snakes); //HERE you remove the Snakes
    ...
}

```

---
Tags: java, javafx, snake
---


title: Can I develop indie games for GameCube?

text:
# Question
Title: Can I develop indie games for GameCube?
I am a game developer who has always loved the GameCube system. I've been developing games since 2017 and have been self-teaching and learning various coding languages. I know it's officially unsupported now but is there any way I can make games for the platform still? Google has not been of much help to me so far. Do I need a development SDK or a specific game engine for this task?

I'd also like any and all help and resources related to GameCube optical media security bypassing you can find. I am okay with building my game engine from scratch but my biggest problem is that I have no idea how I'm going to get past the disc verification system. I know that Datel has done it with Action Replay and SD Loader but they haven't made it publicly available what process they used. I know it's possible but the furthest I've gotten research-wise is this article I found that shows how Nintendo scrambled the data.

For clarification, I want to make signed games that can be played on an unmodified system. I also want to released boxed games so it is more like a real game release rather than some hobbyist project.

# Answer
Just like when you make games for Windows you use the Windows SDK (DirectX, etc.), or other similar SDKs that work for Windows, if you want to make games for the GameCube, you will need to use the GameCube SDK.

Generally speaking, there are two approaches to making a game for the GameCube (or any platform in general).

**The official approach** is to use the official GameCube SDK that Nintendo made. Unfortunately, this SDK is not public, so to do this, you need to register with Nintendo, become an official developer, sign an NDA, most likely you will have to buy a development kit (a special version of the console that is designed for development), and reach an agreement for publishing your game once it's finished.

Since there are many newer Nintendo consoles, it is very likely that Nintendo is no longer accepting applications to become an official GameCube developer. You may want to contact Nintendo and see if this is the case. Only they can tell you the exact requirements.

**The homebrew approach** is to use an unofficial GameCube SDK that people around the world have created, most likely through the process of reverse engineering. To find them, Google can be your friend (I suggest searching for "GameCube homebrew").

These unofficial SDKs are most likely unsupported, may not be complete or stable, and using them may not even be legal in your jurisdiction. In other words, you use them at your own risk.
> 4 votes

# Answer
In terms of how to run homebrew games on a retail GameCube, you'd need to work around GameCube's proprietary disc authentication. It isn't digital signatures, it is creating specific errors in specific places on the disc that line up with an encoded value in the BCA. Datel figured out how to manufacture discs that could be read by a retail GameCube, without going through Nintendo. So it may be possible to construct a burnable image that a retail GameCube could read, but I'm not aware of anyone that has actually done that (Datel discs weren't burned, they were pressed at a factory).

So making a boxed disc game at this point will be tricky. If you don't care about the game being on disc, there's lots of solutions out there for running homebrew off of memory cards.
> 1 votes

---
Tags: console, nintendo
---


# Question
Title: How do i writing timing function for lightning flash in C++?
I need to write a horror scene with lightning flash. Unfortunately I am new to both C++ and OpenGL and I am looking for efficient way to mimic lightning timing in C++/OpenGL?

I don't need graphical implementation, just algorithmic implementation.

as such, the function should return a float representing lighting intensity and the delay of lightning flash should be random (5 seconds followed by 10 seconds then 3 seconds.. etc)

I hope I made everything clear!

# Answer
You'll need some persistent state and a frame counter passed in:

```
float lightning(lightningState* state, uint64 frame){
    if(!state->enabled) return 0.0f;
    if(frame - state->lastStart < state->flashDuration)
         // during flash
         return 1.0f; //can also have a decreasing function here based on the difference
    if(frame - state->lastStart >= state->nextFlashDelay){
        //start of next flash
        state->lastStart = frame;
        state->nextFlashDelay = rollTimeOut(5, 20, *state->rngSeed);
        return 1.0f;
    }
    //no flash
    return 0.0f;
}

```
> 1 votes

---
Tags: opengl, c++, physics
---


# Question
Title: Ways to track login/loading progress dynamic?
Lets say we want to add a dynamic "loading bar" to our server-client game... the player presses on "login", a bar appears and shows the percentage of loaded assets and configurations from the server.

The only way i found... is very laborious and hardcoded :

```
// We received our environment
barPercentage += 10f; // Increasing the bar.
updateBar();

// We received our player settings
barPercentage += 5f; // Increasing the bar again
updateBar();

```

As you can see this progress tracking from received server data is very bad and needs to be adjusted everytime you change some important part of the game structure itself.

What are good ways to implement such a percentage tracker client side ? How do we actually track the loading progress (client & server related) without hardcoding it like i did in the code sample ? Are there any good patterns or data structures ?

# Answer
> 1 votes
One possibility would be for the server to enumerate the content it needs to send at the time the download is initiated, and start by sending the player an estimate of the total download size.

Ie. "User A is logging in, in game state B. That means I need to send them map X and assets Y and Z. Altogether that makes ## MB of data, so I'll tell them to expect that much"

Now on your client side, you can tabulate how many bytes of data you've finished receiving so far, divided by the total the server told you to expect, to figure out your progress through the total load, without knowing at compile time what files / roles might be included in that set.

If you have additional stuff that might add time — like unpacking/parsing/initializing assets after they've been received, or allowance for extra dependencies that are only identified later in your load process, you can add an extra fudge factor to your initial estimate, and then gradually decrease that fudge factor as these extra uncertainties are resolved.

---
Tags: unity, c++, java, software-engineering, design-patterns
---