# Question
Title: Forward declaring in SFML C++ . How to know whether to #include in .h or .cpp?
Hello I am trying to teach myself about the how's and why's of OOP in C++. So I am trying to seperate most of my code into specific classes and methods that do specific things.

I've also been reading/watching lots about best practice for OOP, and I can see how it gives a great advantage for making changes to things later, or re-using classes/components in other projects or other game objects.

From what I understand it is NOT good practice to put **#include**'s to all the needed header files , inside my header files. Rather I should 'forward-declare' them in .h and then fully define them in the .cpp files. This will avoid cycles of header pastes, which gives compiler errors.

However there are MANY threads on SFML help forums directly contradicting this advice. https://en.sfml-dev.org/forums/index.php?topic=21705.0 , https://en.sfml-dev.org/forums/index.php?topic=2043.0 (and more). Thing is, I ran into compiler errors doing it their way. And had to use #pragma once everywhere (even in very small project).

I found a way to properly forward declare (https://stackoverflow.com/questions/13848451/how-to-forward-declare-a-c-template-class/13848492), and it works in the most part. Here's where it gets wierd for me....

My Guy class, it works . I have successfull forward declared a RenderWindow, Texture, Sprite and Vector2 all in sf namespace:

Guy.h:

```
namespace sf
{
class RenderWindow;
class Texture;
class Sprite;
template <typename> class Vector2;
}

class Guy
{
public:
Guy();
void Start();
void Update();
void Draw(sf::RenderWindow& Window);
const sf::Vector2<float> GetPosition();
void SetPosition(float x, float y);

private:
sf::Texture Texture;
sf::Sprite Sprite;
};

```

Guy.cpp:

```
#include "SFML/Graphics.hpp"
#include "SFML/System.hpp"
#include "Guy.h"
#include "Constants.h"

Guy::Guy()
{
Texture.loadFromFile("Textures/guy.png");
Sprite.setTexture(Texture, true);
Sprite.setOrigin(Sprite.getTextureRect().width * 0.5f, Sprite.getTextureRect().height * 0.5f);
SetPosition(15 * Constants::PPU, 18 * Constants::PPU);
}

void Guy::Start()
{
}

void Guy::Update()
{
}

void Guy::Draw(sf::RenderWindow& Window)
{
Window.draw(Sprite);
}

const sf::Vector2<float> Guy::GetPosition()
{
return Sprite.getPosition();

}

void Guy::SetPosition(float x, float y)
{
Sprite.setPosition(x, y);
}

```

That all worked for me, but then I tried to move the #includes on my 'LevelManager' class (this time I had to forward declare stuff from sf and std namespace, maybe this is why?)...

LevelManager.h:

```
namespace sf
{
class RenderWindow;
class View;
class Texture;
}

namespace std
{
class string;
template <typename, typename> class vector;
}

class Guy;
class Tile;

class LevelManager
{
public:
void Start();
void Update();
void Draw(sf::RenderWindow& Window);
sf::View& GetGameView();

private:
sf::View GameView;
Guy Guy;

std::string Level1;
sf::Texture TileTexture_Sky;
sf::Texture TileTexture_Ground;
std::vector<Tile> LevelTiles;
};

```

LevelManager.cpp:

```
#include <string>
#include "SFML/Graphics.hpp"
#include "Guy.h"
#include "Tile.h"
#include "Constants.h"
#include <iostream>
#include "ViewTools.h"
#include "LevelManager.h"

void LevelManager::Start()
{
Level1 = "";
GameView.setSize(Constants::VIEW_WIDTH, Constants::VIEW_HEIGHT);
GameView.setCenter(GameView.getSize().x / 2, GameView.getSize().y / 2);
GameView = ViewTools::GetLetterBoxView(GameView, Constants::WINDOW_WIDTH, Constants::WINDOW_HEIGHT);

Guy.Start();
GameView.setCenter(Guy.GetPosition());

TileTexture_Sky.loadFromFile("Textures/tile_sky.png");
TileTexture_Ground.loadFromFile("Textures/tile_ground.png");

// .......Rest of class...
// ......
// ......

```

And this gives me hundred+ errors. It got very hard for me to debug, because it seems on Guy.cpp if I re-order the #includes , this can break them. They needed to have SFML/Graphics.hpp first I think (?I'm confused?). I tried many orders in LevelManager but couldnt get rid of errors. I also tried many variations of the wordings for forward declaration without success.

If I #include SFML/Graphics.hpp (and Guy.h & Tile.h) in LevelManager.h , then the problem is gone... but one day I will have to include it in two headers unless I realise why it is like this.

The SFML forums where not super-helpful. They seem to tell you just do it in .h and use #pragma once.

**My Question:** Should I find a way to #include "SFML/Graphics.hpp" and the other two headers in the LevelManager.**cpp**, or move them back to the LevelManager.h? I do also have other queries about why sometimes the forward declarations work fine, and other times they don't (but I cannot get the question written concisely, i will have to form a new question for this and post all the code i think).

At any rate, thank you for all and any help

# Answer
> 1 votes
My suggestion is to

1. Use include guards on your `.h` files
2. Move necessary `#include` directives to these `.h` files

A `.h` file is an interface to describe some other compiled binary file. If I want to include `Guy.h` in `LevelManager.cpp`, I shouldn't have to comb through `Guy.h` to see which *other* `#include`s I need to add to `LevelManager.cpp` to get `Guy.h` to not need forward declarations.

`Guy.h` should be set up so that any other includes it needs are, well, included in `Guy.h`. That means at a minimum you should move `#include "SFML/System.hpp"` and `#include "SFML/Graphics.hpp"` to `Guy.h`. `#include "Constants.h"` isn't necessary in `Guy.h` since it's unused.

But what about circular dependencies?

To avoid circular dependencies, you simply tell the compiler to only include that file once. If you use a compiler that enables `#pragma once`, you can use that, but more universal is the use of include guards.

If you look at `SFML/System.hpp` you can see an example of these at the top (and very bottom) of the file:

```
#ifndef SFML_SYSTEM_HPP
#define SFML_SYSTEM_HPP
...
#endif // SFML_SYSTEM_HPP

```

My suggestion is to move the minimum number of `#include` statements to `Guy.h` and `LevelManager.h` so that you don't need to use forward declarations, and to sandwich the entire files in include guards. Naming standard is `#ifndef ALL_CAPS_ENDING_IN_AN_H`

`Guy.h` becomes:

```
#ifndef GUY_H
#define GUY_H
...
#endif // GUY_H

```

`LevelManager.h` becomes:

```
#ifndef LEVEL_MANAGER_H
#define LEVEL_MANAGER_H
...
#endif // LEVEL_MANAGER_H

```

# Answer
> 1 votes
I'll not cover what has already been said it the other answer as it's good advice (`#pragma once` should be the first thing seen in each of your own `.h` files; in headers, include what the header actually uses, forward declare what it only tell it uses (e.g. only used as pointers) and include in the cpp \[note that there is some debate about it, and I think Google's coding standard says to *not* forward declare and always include...\]).

---

> Forward declaring in SFML C++ . How to know whether to #include in .h or .cpp?

A solution is to not include them anywhere. Or everywhere.

You can look into precompiled headers. This is a feature that will let you group all of the most used headers in your project, will pre-compile them when you compile your project the first time and use them "automatically" anywhere you need them, without you needing to type the `#include <sfml/bla.h>`.

The main advantages of the precompiled headers include:

1. Include the header *once*.
2. Access the included content anywhere in your project.
3. In the long run, faster compilation for your project.

The drawbacks in using precompiled headers:

1. You need to set them up in your project configuration
2. You need to include it in *each* of your `.cpp` file in your project, and this include has to be the first thing to include. (At least in Visual Studio.)

A typical use of the precompiled headers is to include in it all the *library* headers (because those change, like, well, never) including `std`, `windows`, and in your case, `sfml`. So, basically, if you're to include something with the angle brackets (`<` and `>`), you should include it in the precompiled headers (and only there, no need to repeat yourself). And you include your own files the typical way.

For instance, your `LevelManager.h` file could look like this:

```
#pragma once

#include "Guy.h"
#include "Tile.h"

class LevelManager
{
public:
  void Start();
  void Update();
  void Draw(sf::RenderWindow& Window);
  sf::View& GetGameView();

private:
  sf::View GameView;
  Guy Guy;

  std::string Level1;
  sf::Texture TileTexture_Sky;
  sf::Texture TileTexture_Ground;
  std::vector<Tile> LevelTiles;
};

```

While the `.cpp` would look like that:

```
#include "precomp.h" // <- Configured in your project, contains all the headers you want precompiled.

#include "LevelManager.h"
#include "Constants.h"
#include "ViewTools.h"

void LevelManager::Start()
{
  Level1 = "";
  GameView.setSize(Constants::VIEW_WIDTH, Constants::VIEW_HEIGHT);
  GameView.setCenter(GameView.getSize().x / 2, GameView.getSize().y / 2);
  GameView = ViewTools::GetLetterBoxView(GameView, Constants::WINDOW_WIDTH, Constants::WINDOW_HEIGHT);

  Guy.Start();
  GameView.setCenter(Guy.GetPosition());

  TileTexture_Sky.loadFromFile("Textures/tile_sky.png");
  TileTexture_Ground.loadFromFile("Textures/tile_ground.png");

  // .......Rest of class...
  // ......
  // ......

```

<sup>* I changed a bit the order here, and it's a preference, lots of debate around the Internet. </sup>

---
Tags: c++, sfml
---


# Question
Title: How to saving and loading animation curves
Is there any way to save an animation curve by playerprefs ? The animation curves in the inspector reset each time the script is changed (public variables added) I want record my animation In runtime as animation curve then I load It next time(same playerprefs I want save/load it)

```
using UnityEngine;
using System.Collections;

public class curvRecord : MonoBehaviour {
    public AnimationCurve xPositionCurve;
    public float timer = 0;
    public float recorder = 0;
    public bool play;
    public bool Reset;
    public bool record;

    void Update () {
        if (Reset && !play && ! record) {
            xPositionCurve.RemoveKey (5);
            play = false;
            recorder = 0;
            timer = 0;
        }
        if(play && timer<=recorder){
            record = false;  Reset = false;
            Vector3 localPosition = transform.position;
            localPosition.x = xPositionCurve.Evaluate (timer);
            transform.localPosition = localPosition;

            // Increase the timer by the time since last frame
            timer += Time.deltaTime;

        } else if(!play && record) {
            Reset = false;
            recorder += Time.deltaTime;
            xPositionCurve.AddKey (recorder, gameObject.transform.position.x);
        }
    }
}

```

I can record and play my curve animation but when I go exit from game reset curve animation.when I start game again I want load last curve animation

You can see my problem in this video: videoLink

I have to use playerprefsX but when I use It in runtime I have lag In my game please tell me what Is easiest way?!?!?! for saving animation curves using UnityEngine; using System.Collections;

```
public class curvRecord : MonoBehaviour {
    [SerializeField]
    public AnimationCurve xPositionCurve;
    public AnimationCurve yPositionCurve;
    public AnimationCurve zPositionCurve;
    public float timer = 0;
    public float recorder = 0;
    public bool record;
    public bool play;
    public bool Reset;
    public float[] CurveFrameValue;
    public bool OnceRunSaving;
    public bool OnceRunLoading;
    Keyframe[] ks = new Keyframe[500];

    void Start () {

    }

    void Saver(){
        for (int m = 0; m < CurveFrameValue.Length; m++) {
            CurveFrameValue [m] = xPositionCurve [m].value;
            PlayerPrefsX.SetFloatArray ("xpos", CurveFrameValue);
            print (m);
            }
    }

    // Update is called once per frame
    void Update () {
        if(OnceRunLoading){
            for (int n = 0; n < CurveFrameValue.Length; n++) {
                CurveFrameValue = PlayerPrefsX.GetFloatArray ("xpos");
                ks[n] = new Keyframe(n, CurveFrameValue[n]);
                xPositionCurve = new AnimationCurve(ks);
            }
            transform.position = new Vector3(Time.time, xPositionCurve.Evaluate(Time.time), 0);
            OnceRunLoading = false;
        }
        if (Reset && !play && !record) {
            xPositionCurve.RemoveKey (50);
            yPositionCurve.RemoveKey (50);
            zPositionCurve.RemoveKey (50);
            play = false;
            recorder = 0;
            timer = 0;
        }
        if(play && timer<=recorder){
            record = false;  Reset = false;
            Vector3 localPosition = transform.position;
            localPosition.x = xPositionCurve.Evaluate (timer);
            localPosition.y = yPositionCurve.Evaluate (timer);
            localPosition.z = zPositionCurve.Evaluate (timer);
            transform.localPosition = localPosition;

            // Increase the timer by the time since last frame
            timer += Time.deltaTime;
        } else if(!play && record) {
            timer = 0;
            Reset = false;
            recorder += Time.deltaTime;
            xPositionCurve.AddKey (recorder, gameObject.transform.position.x);
            yPositionCurve.AddKey (recorder, gameObject.transform.position.y);
            zPositionCurve.AddKey (recorder, gameObject.transform.position.z);
            if(!OnceRunSaving){
                Saver ();
                OnceRunSaving = true;
            }
        }else if(play && timer>=recorder){

            // Increase the timer by the time since last frame
            timer = 0;
        }
        else if(play && record) {
            Reset = true;
        }
        else if(Reset) {
            Reset = true;
        }
    }
}

```

# Answer
> 1 votes
I have done this! Didn't try the ScriptableObject solution since I read that it might not work in production mode. Instead I created a SerializableAnimationCurve and SerializableKeyframe:

```
using System;
using UnityEngine;

[Serializable]
public class SerializableCurve
{
    SerializableKeyframe[] keys;
    string postWrapMode;
    string preWrapMode;

    [Serializable]
    public class SerializableKeyframe
    {
        public Single inTangent;
        public Single outTangent;
        public Int32 tangentMode;
        public Single time;
        public Single value;

        public SerializableKeyframe(Keyframe original) {
            inTangent = original.inTangent;
            outTangent = original.outTangent;
            tangentMode = original.tangentMode;
            time = original.time;
            value = original.value;
        }
    }

    public SerializableCurve(AnimationCurve original) {
        postWrapMode = getWrapModeAsString(original.postWrapMode);
        preWrapMode = getWrapModeAsString(original.preWrapMode);
        keys = new SerializableKeyframe[original.length];
        for (int i = 0; i < original.keys.Length; i++) {
            keys[i] = new SerializableKeyframe(original.keys[i]);
        }
    }

    public AnimationCurve toCurve() {
        AnimationCurve res = new AnimationCurve();
        res.postWrapMode = getWrapMode(postWrapMode);
        res.preWrapMode = getWrapMode(preWrapMode);
        Keyframe [] newKeys = new Keyframe[keys.Length];
        for (int i = 0; i < keys.Length; i++) {
            SerializableKeyframe aux = keys[i];
            Keyframe newK = new Keyframe();
            newK.inTangent = aux.inTangent;
            newK.outTangent = aux.outTangent;
            newK.tangentMode = aux.tangentMode;
            newK.time = aux.time;
            newK.value = aux.value;
            newKeys[i] = newK;
        }
        res.keys = newKeys;
        return res;
    }

    private WrapMode getWrapMode(String mode) {
        if (mode.Equals("Clamp")) {
            return WrapMode.Clamp;
        }
        if (mode.Equals("ClampForever")) {
            return WrapMode.ClampForever;
        }
        if (mode.Equals("Default")) {
            return WrapMode.Default;
        }
        if (mode.Equals("Loop")) {
            return WrapMode.Loop;
        }
        if (mode.Equals("Once")) {
            return WrapMode.Once;
        }
        if (mode.Equals("PingPong")) {
            return WrapMode.PingPong;
        }
        Debug.LogError("Wat is this wrap mode???");
        return WrapMode.Default;
    }

    private string getWrapModeAsString(WrapMode mode) {
        if (mode.Equals(WrapMode.Clamp)) {
            return "Clamp";
        }
        if (mode.Equals(WrapMode.ClampForever)) {
            return "ClampForever";
        }
        if (mode.Equals(WrapMode.Default)) {
            return "Default";
        }
        if (mode.Equals(WrapMode.Loop)) {
            return "Loop";
        }
        if (mode.Equals(WrapMode.Once)) {
            return "Once";
        }
        if (mode.Equals(WrapMode.PingPong)) {
            return "PingPong";
        }
        Debug.LogError("Wat is this wrap mode???");
        return "f you";
    }
}

```

In order to use it, create this Serializer class. Be aware that with this you can serialize any unity component, you just gotta tweak it a little

```
using System;
using System.IO;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;

public class Serializer
{
    public static T Load<T>(string filename) where T : class {
        if (File.Exists(filename)) {
            try {
                using (Stream stream = File.OpenRead(filename)) {
                    BinaryFormatter formatter = new BinaryFormatter();
                    return formatter.Deserialize(stream) as T;
                }
            }
            catch (Exception e) {
                Debug.Log(e.Message);
            }
        }
        return default(T);
    }

    public static void Save<T>(string filename, T data) where T : class {
        using (Stream stream = File.OpenWrite(filename)) {
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, data);
        }
    }
}

```

# Answer
> 2 votes
If you go to the definition of `AnimationCurve` (F12 in VS), you'll see that it is not marked `[System.Serializable]` and no amount of coaxing will change that.

When you change your code and go back to the editor, everything that *was* there is `Unity.Serialized()` (don't look for it; not a real thing) to native, the new managed code is loaded, and then the old values are `Unity.Deserialized()` back into the new data structure blindly. If you rename something, for example, the editor won't know to put the old data in the new place so, instead, it just throws away the old-data and creates new, new-data.

Your only recourse is to provide the methods needed to `System.De/Serialize` the non-serializable curves. You can do so by iterating each `KeyFrame` in the curve and manually exporting the data *somewhere*, *some* way. You'll also need to provide the method that converts that raw data back into an `AnimationCurve` that *appears to be* the same one as before.

`ScriptableObject` is not meant for persistent storage of run-time-generated data. They allow you to create design-time "assets" out of chunks of data that scripts can reference, rather than contain/copy. You are free to create new `ScriptableObjects` at run-time and you are able to permanently store them in the asset database. However (big but), this depends on the `Editor` namespace which doesn't exist in builds. If you use them just to help design the game, you're still required to provide the implementation to make them `System.Serializable` (they are also only `Unity.Serializable`). In case you consider doing so, you cannot simply add `[System.Serializable]` to a `ScriptableObject` because the base class (`UnityEngine.Object`) still won't be `[System.Serializable]`.

Instead, the object that contains the curves can implement the ISerializationCallbackReceiver interface and use the corresponding methods to extract the `KeyFrames` into a serializable form. You can make a new `SerializableKeyFrame` class that contains the same names and types as the real `KeyFrame` class except they'll be stored as members, not as properties. The `SerializableKeyFrame` class will need to be marked `[System.Serializable]` to be eligible for serialization. As well, the for-serialization-only member within the curve-containing object (presumably a `List<SerializableKeyFrame>` will need to be public or marked `[SerializeField]`. You can leave it public and hide it with `[HideInInspector]`. You are free to use a `struct` instead of a `class` but are subject to the normal drawbacks (no default values for members) which may not really affect you.

**Overview:**

You:

1. Save code; go back to editor

Then, Unity:

2. Unity-serializes everything to native
    * (The callback) Deconstruct the `AnimationCurve` into the for-serialization-only member (composed only of `System.Serializable` types)
3. Load the new Managed assemblies
4. Unity-deserialize from native into new Managed
    * (The callback) Reconstruct the `AnimationCurve`'s data using the data in the for-serialization-only member

# Answer
> 1 votes
You cant save complex types in PlayerPrefs. You can only save floats,ints and strings. I suggest you search online for a way to serialize the AnimationCurve object. Maybe you can use a binnary formatter like here. In one of my projects i used ProtoBuff to serialize my own classes and it works great on both android and iOS. Here is a nifty tutorial

# Answer
> 1 votes
You can do this by storing the AnimationCurve variable in a ScriptableObject. Unlike MonoBehaviours that are attached to GameObjects, ScriptableObjects are created as scene independent assets, so they're not reset when exiting playmode.

# Answer
> 1 votes
## Creating Animation Data Scriptable Object

```
    using UnityEngine;

    [CreateAssetMenu(fileName = "new AnimationData",menuName = "Data/AnimationData")]
    public class AnimationData : ScriptableObject
    {
        public AnimationCurve animationCurve;

        public void AddKey(Keyframe keyframe)
        {
            animationCurve.AddKey(keyframe);
        }

        public float GetKeyAt(float time)
        {
            return animationCurve.Evaluate(time);
        }
    }

```

## Recording Animation

```
using UnityEngine;

public class RecordAnimation : MonoBehaviour
{
    [SerializeField] private Transform target;
    [SerializeField] private bool isRecording;
    [SerializeField] private AnimationData[] animationData;

    private void Update()
    {
        if (isRecording)
        {
            RecordPosition();
        }
        else
        {
            LoadPosition();
        }
    }

    private void RecordPosition()
    {
        var position = target.position;
        animationData[0].AddKey(new Keyframe(Time.time, position.x));
        animationData[1].AddKey(new Keyframe(Time.time, position.y));
        animationData[2].AddKey(new Keyframe(Time.time, position.z));
    }

    private void LoadPosition()
    {
        target.position = new Vector3(
            animationData[0].GetKeyAt(Time.time),
            animationData[1].GetKeyAt(Time.time),
            animationData[2].GetKeyAt(Time.time)
        );
    }
}

```

## Source is Available on my Github

# Answer
> 0 votes
If you check "Runtime Curve Editor" on Unity Asset Store, not just that you can load/save an animation curve, but you can even edit it at runtime.

# Answer
> 0 votes
The simple way:

Enter Play Mode -\> record the desired curve -\> click the cogwheel on your script -\> "copy component". Exit Play Mode -\> "paste component values".

---
Tags: animation, unity, curves
---


# Question
Title: How to load a separate map from a text file?
I have a text file that I am using for my map for the tiles to be allocated. This works fine, but I am running into issues figuring out how I would go about loading in a different part of the map.

For example, say I wanted the character to go into a cave or building, what would be a good way to go about loading this new area?

Right now I have my handler class setting the world in my game state class, and I have tried messing around in the game state class to try and accomplish what I want but have not had much success. In that game state class I have a tick and render method, and in the constructor I have it being set.

The methods that I have tried have resulted in a new map to be loaded in, but the other map is still loaded in under this, and I know this because the character has collisions set up. This also goes along with this issue, but what would be a good way to trigger this loading of the new section of the map?

Below is the code in my GameState class. (`changeWorld` is based off of the X coordinate when in game, and once you reach a certain point it switches maps; this was just done for testing because it is not an accurate way of doing it).

```
// Constructor...
    World1 = new Worlds(handler,"resources/Worlds/world1.txt");

    SpawnWorld = new Worlds(handler,"resources/Worlds/world2");

    if(Worlds.changeWorld() == false)
        handler.setWorld(World1);
    }
    else if(Worlds.changeWorld() == true) {
        World1=SpawnWorld;
        handler.setWorld(World1);
        entityManager.setPlayer(new Player (handler, 0,0));
    }
}//end contructor

public void tick() {
    if(Worlds.changeWorld() == false)  {
        World1.tick();
    }
    else if(Worlds.changeWorld() == true){
        World1=SpawnWorld;
        handler.setWorld(World1);
        SpawnWorld.tick();
    }
}//end tick

public void render(Graphics g) {
    if(Worlds.changeWorld() == false) {
        World1.render(g);
    }//end if
    else if(Worlds.changeWorld() == true) {
            World1=SpawnWorld;
            handler.setWorld(World1);
            World1.render(g);
    }
}//end graphics

```

# Answer
some of your ideas are good, some are terrible...

## Data Model

first you have to create a proper *design* \- that means you have to think about what data you have and how they interact - this part is missing yet (as far as i can see from that question)

## Architecture

as you are a beginner i suggest you try to achieve something like a M-VC (Model-View-Control) to separate your game logic from your drawing tasks.

on the other hand it seems to be a good idea to update your game (your model) frequently using a `tick()` method - but keep in mind that you update **only model values** within the model (not controller or not on view) - maybe you trigger the `GuiListener` but that would be all.

## UML-Diagramm (Draft)

## reaction on changes

i'm not sure how you do implement input handling so i come up with this idea: Input Handling is done in the controller and delegated into the model. This is done by creating first a GUI and add `ActionListener` on the widget, maybe a keyListener for input on Keyboards or an actionListener on a button. These Inputs are delegated to the model and the model reacts to these changes

## Data flow

**finally** comes some code - haha

**User Input**
the User presses a key (or a Button) on the GUI and this event is catched by the correlated `Listener`. this Listener is located inside the `Controller`:

```
public class Controller implements GuiListener{

    private final Game game;

    public Controller (Game game){
        this.game = game;
    }

    public void onButtonPresse(ActionEvent e){
        //Let's assume that was the Button to move player NORTH
        game.movePlayer(Direction.NORTH);

        //TODO validate input before:
        //if(game.canMove(Direction.North)){game.movePlayer(Direction.NORTH)}
        //else{notifyInvalidMovement();}
    }

    @Override
    public void guiChanged(Point center){
        //maybe somehting like this
        canvas.render(game.getViewport(center));
    }
}

```

that was all what happens on controller side - the input is simply delegated to the model!

**Game reaction** (finally he talks about how to load seperate maps!!!)
now the Input Event has come into the Model (aka the Game). The model updates it's values according to the input

```
public class Game{

    private final Map map;
    private final Player player;
    private final GuiListener guiListener;

    public void movePlayer(Direction dir){
        Point from = player.getLocation();
        Point to = Direction.getDestiny(from, dir);
        map.movePlayer(from, to);

        if(map.isLocationTeleporter(to)){
           MapId mapId = map.getTeleportId();
           Point teleportDestiny = map.getTeleportDestiny();
           map = MapLoader.loadMap(mapId);
           map.setPlayer(teleportDestiny);
        }

        //whatever happened now you might notify the UI to render these changes
        guiListener.guiChanged(player.getLocation());
    }
}

```

the changes from the controller are now properly handled and the map has been updated as soon as the player enters the teleport location (*stairs to the basement*). Even more, the player is set to the proper location on the new map.

## Implementation hints

instead of using x/y-coordinates it seems very helpful to create a Data Object that encapsules these valuse: a `Point`!

```
class Point {
    private int x;
    private int y;

    //default constructor
    public Point(){
        this(0,0); //calls internally my two-parameter constructor
    }

    public Point(int x, int y){
        this.x = x;
        this.y = y;
    }

    public int getX(){
        return x;
    }

    public int getY(){
        return y;
    }

    @Override
    public String toString(){
        return "x/y:"+x+"/"+y;
    }

    public void translate(int dx, int dy){
        x = x + dx;
        y = y + dy;
    }

    public void translate(Point d){
        translate(d.getX(), d.getY());
    }
}

```

**UML-Diagramm of `Point`**
its much smaller than all this code and can be changed easier: good for playing with design/architecture/data models
> 1 votes

---
Tags: java, 2d, tilemap
---


# Question
Title: Update variable before building the unity build
Before building the standalone build I want to update one of the variables in the script using this.

```
class MyCustomBuildProcessor : IPreprocessBuild
 {
      public int callbackOrder { get { return 0; } }
      public void OnPreprocessBuild(BuildTarget target, string path) {
        // Do the preprocessing here
        CopyRightCls.buildDateTime = System.DateTime.Now;
        Debug.Log("+++++++++++++++++++++++++++++++++++BuildDateTime" + CopyRightCls.buildDateTime);
      }
 }

```

But the problem is my date variable is not updating its showing 1 january 0001.

# Answer
If you have a static variable like this:

```
public class CopyRightCls {

    public static System.DateTime buildDateTime;

    //...
}

```

That translates into code in your built game that says "At startup, initialize `buildDateTime` to `default`" (since we didn't specify an initializer, C# structs are default-initialized)

When you set `CopyRightCls.buildDateTime = System.DateTime.Now;`, what you're setting is the *current value in memory within your editor*. Nothing serializes that value to disc, or modifies the code above to add an initializer you didn't write. So at startup, you still get the same default-initializing behavior as the runtime executes your code.

To actually save the value (without dynamically modifying your source code), you need to write it down in a serialized data structure - something that will get exported into your game as an asset, and loaded from disc when your game runs.

For example:

```
[CreateAssetMenu(fileName = "buildInfo.Asset", menuName = "Metadata/Build Info")]
public class BuildInfo : ScriptableObject {
    public System.DateTime buildDateTime;
}

```

This will let you create a new "Build Info" asset in your project hierarchy. You can assign a reference to this asset in any script that needs to consult the build metadata.

Your build processor can then load this object from the asset database and write the new value into it. Be sure to flag the object with `Undo.RecordObject` in that method, so the serializer knows you changed some values it needs to commit to the serialized version.

```
string infoPath = "Assets/Build/buildInfo.asset"; // Or wherever you keep it.
BuildInfo info = (BuildInfo)AssetDatabase.LoadAssetAtPath(infoPath, typeof(BuildInfo));
Undo.RecordObject(info, "Update Build Timestamp");
info.buildDateTime = System.DateTime.Now;

```
> 1 votes

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


# Question
Title: Godot - Get button node in click event not working
How we can get the button reference on the event function that is connected? My connect signals never works

```
extends PanelContainer

onready var hbox_container = $ScrollContainer/HBoxContainer
var btn

func _ready():
    createbutton()

func createbutton():
    btn = Button.new()
    btn.set_name("button 1")
    btn.text = "button 1"
    hbox_container.add_child(btn)
    btn.connect("toggled", self, "button_toggled", [btn])

func button_toggled(toggled, target):
    print("which button = ", target.get_name())
    if toggled == true:
        print("Button ist pressed")
    else:
        print("Button is released")

```

# Answer
You need to set the toggle\_mode

```
extends PanelContainer

var btn:Button

func _ready():
    createbutton()

func createbutton():
    btn = Button.new()
    btn.set_name("button 1")
    btn.text = "button 1"

    btn.toggle_mode = true

    add_child(btn)
    btn.connect("toggled", self, "button_toggled", [btn])

func button_toggled(toggled, target):
    print("which button = ", target.get_name())
    if toggled == true:
        print("Button ist pressed")
    else:
        print("Button is released")

```

I removed `onready var hbox_container = $ScrollContainer/HBoxContainer` for brevity

It is best to type variable to get autocomplete to work like `var btn:Button` done above.
> 1 votes

---
Tags: godot, gdscript
---


# Question
Title: Implications of variable run speeds in 2D
I'm getting my feet wet trying to design and implement a 2D action platforming game. Combat will be a big focus, so I want to have tight ground and air control so players can be precise and express mastery. For now, I don't think I want high acceleration and deceleration times, as I think they detract from a 'tight' feeling control scheme, but feel free to correct me if there's data or examples saying otherwise.

I'm taking a lot of combat inspiration from, and want it to feel like, a fighting game. From a surface level analysis, in many fighting games, most notably smash brothers, there are usually two (or more) speeds of horizontal movement - a walk and a run, a run and a sprint, and so on. Naively, I thought 'well fighting games have it so if I want this to feel like a fighting game I need to have it as well' but thinking about it some more, I'm not sure if its worth implementing. Primarily because I don't understand the implications of having a sprint mechanic or not.

One thing I'm rapidly discovering is that any design question can boil down to 'it depends,' especially on the game itself and what I want to accomplish. If you need more context, my initial idea is to more closely marry the feelings you get when you pull off a new combo or link or discover new ways to use a system mechanic in a fighting game with that feeling of discovery from cracking open a game world in a Metroidvania. So a 2D metroidvania with action/fighting game level combat. My initial thought is sprinting would open up opportunity for dash attacks, maybe some cancels, and make moving around the world easier. It also means more implementation work, because I'm mostly out of buttons, so I'd have to do some sort of double tap or smash-attack-like analog input to work it in.

My main example of two run speeds in a non-fighting game is in some Kirby games, where you can start a dash by double tapping a direction. In the context of Kirby, what does having the dash do for the game as a whole? Would it be better to have a faster base walk speed and no dash? What opportunities would open up if I had a sprint, and what would become closed off from me?

Perhaps a better example, though not in 2D, is Raiden's Ninja Run from Metal Gear Solid Rising Revengeance. It helped him get from encounter to encounter faster, and served as a way to close gaps while under fire.

Initial reaction says that my players will just use sprint to run from encounter to encounter and will miss stuff I put in they might not if they're taking their time. I'd have to put in stuff that encourages the player to slow down, and be intelligent about it so as to not feel like I'm mangling whatever pacing the player is at. I think 'go as fast as I'm allowed to' is the default mode for most players, and that having a variable run speed doesn't actually add much of a choice. I think going fast, especially going fast-er by comparison, is fun, but is it a worthwhile tradeoff? I could offset this with a stamina system just for sprinting or some other artificial limiter, but I think that opens up a whole new set of implications I even further don't fully grasp.

TL;DR

What are the benefits and downsides of having a sprint?

# Answer
When there is no downside to not sprinting, then there is no reason for the player to ever take the finger off of the sprint button. You just made the regular speed mode obsolete.

Adding a stamina bar just to limit the sprint duration just adds a limitation for limitation sake. It doesn't make the game any more interesting to play, just more annoying. The player doesn't want to walk. They want to constantly sprint. But because of that damn stamina bar, they are constantly forced in and out of walk mode for no good reason.

If you want to make the two speed modes interesting, then you need to make sure that the player has a reason why they would **want** to switch between the two modes. You need to add upsides and downsides to both. The upside of sprint mode is obvious: faster traversal. So how could we make the walk mode more interesting?

If you plan to have a very complex combat moveset, then you could have some attacks which work in sprint mode and some which work in walk mode. The walk mode attacks should be very different, but generally a bit more effective to compensate for the loss in traversal speed. You might also want to add a little delay between releasing the sprint button and being able to perform walk moves. Otherwise a skilled player will release the sprint-button for a single frame, perform the attack, and press it again.

You could also look into ways to use the two speed modes for platforming sections. How about sprint mode allowing the player to jump further, but walk mode allowing them to jump higher and/or with more air-control?

I am looking forward to playing your game.
> 1 votes

---
Tags: 2d, game-design, movement
---


# Question
Title: Is the position of a control relative to its anchor in Godot engine?
I'm trying to place a button on the bottom right corner of the screen, so I tried to put all the Anchor parameters in the inspector to the value "End" but the position still needs to be specified relative to the top-left corner. If I try changing the margins in the inspector it kind of works but then I have to change all four margins taking into account the size.

# Answer
> 0 votes
Having a Node2D with a Button in it you need this code.

```
extends Node2D

func _ready():
    var v:Vector2 = get_viewport().size
    $Button.rect_position = v - $Button.rect_size

```

This does not look clean as the button is squeezed into the bottom right not looking great. It's better to put it in ie a MarginContainer and then move that bottom right. It's *Custom constants* margins can be set manually.

```
extends Node2D

func _ready():
    var v:Vector2 = get_viewport().size
    var m:MarginContainer = $MarginContainer

    m.rect_position = v - m.rect_size

```

Hope this was useful :-)

---
Tags: godot
---


# Question
Title: How to automatically scroll vertical text?
I've a GUI, and a panel with a Text control.

I simply want to do an automatic vertical scroll effect (circular).

Problems I've to solve: \- How to identify if text on my textbox is "too much" and overflow vertical

* How to move Text and not textbox transform Y

Can you help me find the correct solution ?

Thanks

# Answer
> 1 votes
I solved:

1. I put my text control inside a Panel
2. I add a Rect Mask 2d to my panel
3. I wrote this simple script to attach to Text control:

```
[SerializeField] float              SecondsAfterStartAutoscroll;
[SerializeField] float              ScrollSpeed;

bool isScrolling = false;
RectTransform rectTransf;

void Start()
{

    rectTransf = GetComponent<RectTransform>();
    Invoke("EnableScroll", SecondsAfterStartAutoscroll);
}

void EnableScroll()
{
    isScrolling = true;
}

void Update()
{
    if(isScrolling)
    {
        rectTransf.Translate(new Vector3(0, 1, 0) * Time.deltaTime * ScrollSpeed);
    }
}

```

What I haven't solved yet: loop circular scroll... text didn't restart after last 'sentences' finish ..

---
Tags: unity, gui
---


# Question
Title: UE4 - Want my landscape to be unlit BUT catch shadows from objects
Here is my problem, I have a landscape that was created through photogrametry. I already has strong shadows on it's diffuse texture so I don't want it to be affected by my virtual sun. What I do want though is for objects added in my scene to receive shadows from the landscape, and for the objects to cast shadows onto the landscape. To do that I matched my virtual sun as close as I could with the shadows on the diffuse texture of the landscape.

How do I keep my landscape unlit yet able to receive and cast shadows from and to other objects?

# Answer
> 1 votes
AFAIK you can't do that.
But what you can do is to use decals as a shadow which will be pretty hard (and annoying) to do...

OR you can just take the diffuse texture into Photoshop(or whatever you use) and remove the shadow/highlight in 2-4 clicks.

---
Tags: unreal-4
---


# Question
Title: Do I need Microsoft authorization to support Xbox 360 controllers for a pc game?
Do I need to pay Microsoft, or do I need some kind of license so I can support the xbox controller on a pc game? Or I just implement it and let people use their Xbox 360 controllers?

# Answer
No, you do not need authorization from Microsoft to support Xbox 360 controllers.

You can use the XInput API for free.
> 7 votes

---
Tags: xbox360, controllers
---


# Question
Title: XBOX ONE controller inputs vanish in project settings
I'm putting in the inputs for the XBOX ONE controller in Project settings, but when I try to put in the values for the triggers and click on the next window, that value vanishes. I'm putting the value in **Positive Button**. I then tried it in the Negative with the same result.

I checked the spelling, axis and everything looks fine, so I'm unsure why it's suddenly vanishing and not letting me input a value.

Here is the input for the right trigger:

Now when I put in the axis for the right trigger, like this:

And I press enter, or click away, it clears the field like this:

After setting it up as an axis, it's still not working:

And setting the type to axis:

Any idea on why it's doing this?

# Answer
"Right Trigger" is not one of the button names Unity knows how to check. Neither is the number 10.

These special names that Unity looks for are listed in the docs here:

> * Normal keys: “a”, “b”, “c” …
> * Number keys: “1”, “2”, “3”, … Arrow keys: “up”, “down”, “left”, “right”
> * Keypad keys: “\[1\]”, “\[2\]”, “”, “\[+\]”, “\[equals\]”
> * Modifier keys: “right shift”, “left shift”, “right ctrl”, “left ctrl”, “right alt”, “left alt”, “right cmd”, “left cmd”
> * Mouse Buttons: “mouse 0”, “mouse 1”, “mouse 2”, …
> * Joystick Buttons (from any joystick): “joystick button 0”, “joystick button 1”, “joystick button 2”, …
> * Joystick Buttons (from a specific joystick): “joystick 1 button 0”, “joystick 1 button 1”, “joystick 2 button 0”, …
> * Special keys: “backspace”, “tab”, “return”, “escape”, “space”, “delete”, “enter”, “insert”, “home”, “end”, “page up”, “page down”
> * Function keys: “f1”, “f2”, “f3”, …

**The left/right triggers are not buttons at all**, but axes. Axis 9 & 10 specifically, on Windows. You can find the mapping between buttons/axes and their joystick-indexed slots here.

To configure an axis like the analog sticks or triggers, **you do not type anything at all into the "Positive Button" field**. Because, again, they are not buttons. Instead, set the input type to Joystick Axis and select the axis number from the "Axis" dropdown near the bottom of the inspector for this input, as shown in this screenshot of a right trigger mapped control:

Note that the "Positive Button" field is deliberately left blank, and the axis is specified in the drop-down at the bottom. Axes typically also use lower gravity and sensitivity than buttons, with a larger dead range, but this is something you can tune for feel.
> 0 votes

# Answer
Save yourself the trouble without reimplementing the wheel – use a proven, established controller plugin like InControl or Rewired.
> 0 votes

---
Tags: unity, input, controllers
---


title: Move player in a circular manner

text:
# Question
Title: Move player in a circular manner
i'm creating a pong game for learning purpose and decided to have the Paddle moving freely but with a slight change in its control.

When pressing LEFT OR RIGHT it should move in polar coordinates facing the ball. And UP OR DOWN moves the paddle towards or backwards the ball.

I've spent the whole day trying out a few solutions but didn't make it.

```
             var ball = Vector3.zero; // target
             var d = ball - translation.Value.ToVector3();
             var radius = d.magnitude;

             var dir = d.normalized * data.speed * deltaTime;
             var angle = Vector3.Angle(ball, translation.Value);

             var nextPos = translation.Value;

             if (data.input.x > 0)
             {
                 nextPos.x += dir.x + 15 * math.sin(angle) * data.speed * deltaTime;
                 nextPos.z += dir.z + 15 * math.cos(angle) * data.speed * deltaTime;
             }

             if (data.input.x < 0)
             {
                 nextPos.x -= dir.x + 15 * math.sin(angle) * data.speed * deltaTime;
                 nextPos.z -= dir.z + 15 * math.cos(angle) * data.speed * deltaTime;
             }

             translation.Value = nextPos;

```

# Answer
> 0 votes
Sorry for my initial shallow answer. After doing research, I could not find where I had found the initial Mathf.PI solution. But after fiddling around in Unity, I came up with my own solution to this problem. Here is the code below

```
{

public Transform ball;
public float speed = 1.0f;
private float leftToRightMovement;

/*
private Vector3 paddlePosition;
private float distanceFromBall;
private float offsetMultiplier;
*/

void Update()
{
    //This is my attempt to control the speed of the paddle relative to the distance to the ball, but the speed kept multiplying into infinity.
    /*
    Vector3 offset = ball.position + transform.position;
    float sqrLen = offset.sqrMagnitude;
    Debug.Log("distance from ball is " + sqrLen);
    offsetMultiplier = sqrLen;
    speed = speed + offsetMultiplier;
    */

    float forwardBackward = Input.GetAxis("Vertical") * speed * Time.deltaTime;
    float leftToRight = Input.GetAxis("Horizontal") * speed * Time.deltaTime;

    transform.Translate(0.0f, 0.0f, forwardBackward);

    transform.Translate(leftToRight, 0.0f, 0.0f);

    transform.LookAt(ball);

}

```

The main idea here is to assign the ball as a game object and using "LookAt" to rotate your paddle toward the ball. From there, you can use the z position of the paddle to move closer and further away, and the x position to move side to side. Since the z position is always looking at the ball, the x movement will always be in a circle around the ball.

The one problem I had was when the paddle got very far away, the speed was relatively much slower than close up. I couldn't come up with a solution to that problem, but also not sure if you need that. My attempt is commented in the code snippet.

Goodluck and cheers!

---
Tags: unity, movement
---


# Question
Title: Raycast against a mesh without using a mesh collider?
I have a complicated mesh that doesn't need to have anything to do with physics. However, I need to be able to detect said mesh with a raycast from a point. I have several hundred of these objects that regularly get moved around and rescaled, so a mesh collider is way too computationally expensive - especially since I don't need any form of collision detection other than this raycast. However, the mesh is human-shaped, and is thus irregular enough that I can't just use lots of primitives, nor can I just check if the mouse point is within a specified area (since the area is far too complex to manually specify). Turning the mesh collider off when it's not relevant works a little, but the act of turning the collider on and off is ALSO computationally expensive enough to cause noticeable frame drops. What component or settings can I use in order to raycast a mesh without all the slowdown of a mesh collider?

# Answer
A similar question was asked before so I'll just re-post the answer 'Kay' provided.

* Use compound colliders especially box and sphere s Rigidbody manual
* Always attach rigidbodies to moving items
* If you need more than one raycast consider using Physics.RaycastAll
* If the physics engine is to blame for significant frame rate Drops, check whether you can use layers to optimise calculations
* Use the profiler
> 1 votes

---
Tags: unity, raycasting, mesh
---


# Question
Title: Project 3D points to a plane, then project their bounding box back to 3D
I have a table in 3D space, represented by a plane.

I want to project arbitary points representing an object (cup, toy, etc) onto that table, run 2D principal components analysis to get an oriented bounding box (https://www.sciencedirect.com/topics/computer-science/oriented-bounding-box)

This gives me 2D oriented bounding boxes (defined by 8 corner points) that lie along the table plane. Now, I want to project these points back to 3D somehow so I can get 3D bounding boxes that are aligned with the plane.

The projection from 3D to 2D plane is not invertible.. so how do I do this?

# Answer
As you go through your points, before you project them to the plane, look at their height off the plane. Note down the greatest and least height off plane that you encounter for each object.

Once you have the four corners of your planar bounding box, you can duplicate them to four at your minimum height, and four at your maximum height, to get all 8 corners of a 3D bounding box.

This box is guaranteed to contain your object. If a point were outside it horizontally, you would have chosen a larger planar bounding box to encompass it. If a point were outside it vertically, you would have recorded a higher max height or a smaller min height.
> 1 votes

---
Tags: graphics, linear-algebra, bounding-boxes
---


title: Set background color in Phaser

text:
# Question
Title: Set background color in Phaser
I want to set a background color for my game.

I found this solution:

```
function create() {
  this.cameras.main.setBackgroundColor("#d5d5d5");
}

```

but I want to be sure that there is not a more standard way to do this, because editing the camera's property means that the background would be different for another camera.

Thank you for your help.

# Answer
You can set the `backgroundColor` property of the `GameConfig` when you create a new `Phaser.Game`.

```
const config = {
   // ...
   backgroundColor: '#d5d5d'
}

const game = new Phaser.Game(config)

```

Phaser docs for more info: https://photonstorm.github.io/phaser3-docs/Phaser.Types.Core.html#.GameConfig
> 1 votes

---
Tags: color, phaser
---


title: How to connect a 3D head to a body?

text:
# Question
Title: How to connect a 3D head to a body?
I am new to Unity, game-making, etc.

I have downloaded the trial version of Avatar Maker and a similar Unity plugin called Didimo Editor, with the hope of using their features to make game characters that look like real people, using photographs. They both do more or less what I want.

However, both tools output only heads, and do not connect them to 3D bodies. Avatar Maker has another plugin that allows for this, but it is only for male bodies and most of its features are not to my liking.

So my question is: how can I put these heads on working 3D bodies?

The trailer for Didimo Editor seems to confirm that it can, at least, and Avatar Maker is able to export its heads to OBJ, FBX and Prefab, so I'm assuming maybe there is a way to do that too.

# Answer
have you tried unpaking the character that you what to use delete the head and atach the one you have on its place then just make them a pre fab again , i do the same but with robots or randomizing game characters, sorry or my bad english best i can think of , and as far i remember those softwares of this photo to 3d software end up being used in blender then from there you can make them good for youre unity if that its youre problem
> -1 votes

---
Tags: unity, 3d-modeling
---


# Question
Title: Empty Array of IMotionControllers for Unreal using Oculus Quest
The typical way of setting up a MotionController in Unreal Engine is through Blueprints, but I'm trying to identify different types of motion controllers for various VR setups and from there apply the orientation and position data. I have no problems getting Oculus Rift and Vive controllers and trackers using C++, but on Oculus Quest the array that's populated with IMotionControllers is empty when debugging over ADB. Why might this be?

The following code will print a length of 0 on Oculus Quest only.

```
const FName feature = FName(TEXT("MotionController"));
TArray<IMotionController*> controllers = IModularFeatures::Get().GetModularFeatureImplementations<IMotionController>(feature);
UE_LOG(LogGloveController, Warning, TEXT("Number of Controllers: %d"), controllers.Num());

```

# Answer
> 1 votes
I checked the array in the `TickComponent` update and the array was populated. There's just a delay sometimes for a controller to become available (even with Rift/Vive), but it always happens on Quest.

---
Tags: unreal-4, oculus
---


# Question
Title: How to troubleshoot Godot HTTPRequest latency?
I'm running a Django server on localhost, and Godot 3.2 is my client using HTTPRequest. If I make an HTTP request with HTTPie (or cUrl), I get a response in under 3 seconds. The same request is taking 2 or 3 times longer when initiated in Godot in code basically mirroring the example. I have enabled threads.

What could make Godot take so much longer?

I'm not sure where to begin troubleshooting this. I know it's a vague question, and I'm happy to post updates as necessary. I'm logging the time immediately after calling http\_request.request() and at the start of the request\_completed signal handler.

UPDATE 1: I used strace like this and discovered that I'm getting a lot of read errors with Godot. The size of the response body is about 1 MB.

```
% time     seconds  usecs/call     calls    errors syscall
------ ----------- ----------- --------- --------- ----------------
 85.64    9.208080           7   1290272   1235447 recvfrom
 13.07    1.405888         213      6596      5575 recvmsg
  1.29    0.138535        1539        90           sendto
  0.00    0.000060          10         6         3 connect
  0.00    0.000028           9         3           socket
------ ----------- ----------- --------- --------- ----------------
100.00   10.752591               1296967   1241025 total

```

With HTTPie, I don't get these errors. Note that this is a single HTTP request, whereas the above statistics for Godot includes 3 concurrent requests.

```
% time     seconds  usecs/call     calls    errors syscall
------ ----------- ----------- --------- --------- ----------------
 99.72    0.015470           7      2147           recvfrom
  0.09    0.000014           5         3         3 connect
  0.06    0.000009           9         1           getsockname
  0.05    0.000007           2         4           socket
  0.04    0.000006           6         1           getpeername
  0.02    0.000003           3         1           sendto
  0.01    0.000002           2         1           bind
  0.01    0.000001           1         1           setsockopt
  0.01    0.000001           1         1           getsockopt
------ ----------- ----------- --------- --------- ----------------
100.00    0.015513                  2160         3 total

```

UPDATE 2: The problem only occurs in Godot when I have multiple requests running simultaneously. The queries are all expensive and read-only. When I make multiple requests with HTTPie, I see similar delays. By comparing a single HTTPie request to simultaneous Godot requests, I was comparing apples to oranges.

Now I'm confused because I expect read-only queries to execute concurrently with Postgres. I expect three 3-seconds queries to take around 3-4 seconds rather than 9-12 seconds.

I'm also confused because all three concurrent requests, when made in Godot, finish around the 11s mark. If they were operating sequentially due to a lock, I would expect them to finish in a cascading manner (i.e. t+3, t+6, t+9). What am I missing?

# Answer
The problem is that I was using Django's built-in development server (runserver), which doesn't really handle multiple requests well. The problem goes away using Gunicorn. It doesn't matter if the database backend is Sqlite or Postgres, and it has nothing to do with Godot.
> 1 votes

# Answer
I timed the Godot example (see below) and got the timings below both for curl and godot.

Using the debug profiler I did not found any long running thread(s).

You could use a process trace tool like dtrace (MacOS) or strace (linux) to find the culprit.

### curl

```
time curl https://httpbin.org/get
{
  "args": {},
  "headers": {
    "Accept": "*/*",
    "Host": "httpbin.org",
    "User-Agent": "curl/7.54.0",
    "X-Amzn-Trace-Id": "Root=1-5e3d49e8-de33afe0a06876d0f21849b8"
  },
  "origin": "94.214.195.199",
  "url": "https://httpbin.org/get"
}

real    0m0.460s
user    0m0.015s
sys 0m0.008s

```

### Timing

```
    1.847uS : _ready
       55uS : Created request object
       11uS : Add child
        8uS : Requested
1.390.761uS : Got results
{
  "args": {},
  "headers": {
    "Accept": "*/*",
    "Host": "httpbin.org",
    "User-Agent": "GodotEngine/3.2.stable.official (OSX)",
    "X-Amzn-Trace-Id": "Root=1-5e3d4931-8a60c3024b0f21ce7325f18c"
  },
  "origin": "94.214.195.199",
  "url": "https://httpbin.org/get"
}

GodotEngine/3.2.stable.official (OSX)

```

### Code

extends Node2D

var timing = OS.get_ticks_usec()

func time(text):
    var next_tick = OS.get_ticks_usec()
    print (next_tick - timing, "uS : ", text)
    timing = next_tick

func _ready():
    time("_ready")

    # Create an HTTP request node and connect its completion signal.
    var http_request = HTTPRequest.new()
    time("Created request object")

    add_child(http_request)
    time("Add child")

    http_request.connect("request_completed", self, "_http_request_completed")
    time("Requested")

    # Perform the HTTP request. The URL below returns some JSON as of writing.
    var error = http_request.request("https://httpbin.org/get")
    if error != OK:
        push_error("An error occurred in the HTTP request.")

# Called when the HTTP request is completed.
func _http_request_completed(result, response_code, headers, body):
    time("Got results")
    var response = parse_json(body.get_string_from_utf8())

    print(body.get_string_from_utf8())

    # Will print the user agent string used by the HTTPRequest node (as recognized by httpbin.org).
    print(response.headers["User-Agent"])
```

> 1 votes

---
Tags: latency, godot-3
---


# Question
Title: Time complexity of solving constraints in physics engine
Erin Catto mentioned in a talk that solving constraints precisely requires cubic time and quadratic space. What algorithm is he talking about when he mentions cubic time?

pdf of slides with following quote:

> We can model and program our constraints perfectly. Good enough to drive a robot arm on an assembly line or launch a satellite into space. Unfortunately for games, we do not have enough cycles to solve constraints accurately. Solving constraints precisely requires cubic time and quadratic space. For games we make due with linear time and space, so we are constantly wrestling with our solvers. The better you understand constraint solvers, the better chance you’ll have of creating robust simulations in your game.

# Answer
**He tells you later in the slides**

> However, computing the global solution requires building and factoring a matrix. If there are a hundreds constraint, you will have to build and factor a 100x100 matrix. This will likely be too slow for most games.

From page 18. The method he is talking about is solving the matrix he gives a toy example of on the same page, except for a much larger number of constraints. He doesn't specify the exact algorithm used to solve the matrix, but matrix solving algorithms are relatively easy to find and have similar properties. This method requires quadratic space because for N constraints you must construct an N x N matrix but if you look into matrix solving methods you will rapidly discover that many algorithms exist with performance better than O(N^3) - the best has O (N^2.375) - however these algorithms only reach these levels of efficiency for excessively large N so for the purpose of physics models in game O(N^3) is probably a realistic estimate.
> 0 votes

---
Tags: physics, physics-engine
---


# Question
Title: Why UI isn't instantiate when I create a new object that has Canvas as a child component?
I have this object called Treant and I instantiated him from another Object called spawn. The spawn only instantiates a new Treant every second or not.

My problem is that the Treant has a Health bar but that same health bar isn't instantiated in the other Treant that I clone. The health bar will only appear in the next Treant the is created after I destroy the one that has the Health bar.

How can I made all Treants have the Health Bar on top of them?

This is my Spawn class:

```
 // Start is called before the first frame update
public Component Enemies;
public Component Target;
private float lastSpawn = 5;
private float waited = 0f;
private int spawnPerWave = 1;
private int spawned = 0;
private List<int> fibonacci = new List<int>
{
    1, 1
};

// Update is called once per frame
void Update()
{
    CreateNewWave();
    Spawn();
}

private void Spawn()
{
    waited += Time.deltaTime;

    if (lastSpawn < waited && spawned < spawnPerWave)
    {
        Debug.Log("Spawned");
        waited = 0;
        spawned += 1;
        var enemy = Instantiate(Enemies);
        enemy.GetComponent<EnemyAI>().target = Target;
    }
}

private void CreateNewWave()
{
    if(spawned == spawnPerWave && fibonacci.Count < 4)
    {
        spawned = 0;
        spawnPerWave = fibonacci[fibonacci.Count - 1] + fibonacci[fibonacci.Count - 2];
        fibonacci.Add(spawnPerWave);
    }
}

```

The Canvas config:

The Slider config:

The code from FollowTransform:

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

public class FollowTransform : MonoBehaviour
{
    public Transform m_objectToFollow;
    private RectTransform m_rect;

    void Start()
    {
        m_rect = GetComponent<RectTransform>();
    }

    void Update()
    {
        this.m_rect.anchoredPosition = CanvasManager.Instance.WorldToCanvasPoint(m_objectToFollow.position);
    }
}

```

Canvas Manager Script:

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

public class CanvasManager : MonoBehaviour
{
    private Rect m_canvasRect;
    // Start is called before the first frame update
    private static CanvasManager canvasManager;
    public static CanvasManager Instance
    {
        get
        {
            return canvasManager;
        }
    }

    void Start()
    {
        if(canvasManager != null && canvasManager != this)
        {
            Destroy(this.gameObject);
        }
        else
        {
            canvasManager = this;
        }

        m_canvasRect = GetComponentInParent<Canvas>().GetComponent<RectTransform>().rect;
    }

    public Vector2 WorldToCanvasPoint(Vector3 a_position)
    {

        Vector2 viewport = Camera.main.WorldToViewportPoint(a_position);
        return Vector2.right * (viewport.x - 0.5f) * m_canvasRect.width + Vector2.up * (viewport.y - 0.5f) * m_canvasRect.height;
    }
}

```

# Answer
> 1 votes
The problem was with the Canvas Manager Script. It has a Singleton to the canvas, so the canvas isn't been instantiated every time that a Treant is created.

To solve this, just remove the singleton. I got some help from Sid Makes Game

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

public class CanvasManager : MonoBehaviour
{
    private Rect m_canvasRect;
    public static CanvasManager Instance { get; private set; }

    void Start()
    {
        Instance = this;
        m_canvasRect = GetComponentInParent<Canvas>().GetComponent<RectTransform>().rect;
    }

    public Vector2 WorldToCanvasPoint(Vector3 a_position)
    {

        Vector2 viewport = Camera.main.WorldToViewportPoint(a_position);
        return Vector2.right * (viewport.x - 0.5f) * m_canvasRect.width + Vector2.up * (viewport.y - 0.5f) * m_canvasRect.height;
    }
}

```

# Answer
> 1 votes
Check that the Treant prefab has the canvas on it and that the values on it are correct.

If it's not the prefab then maybe Canvas has a singleton script on it that destroys any new instances of itself.

You can then do a sanity check. Get and print all the components on the Treant before instantiating (in Start()) and then after. You can do it like this

```
foreach(var component in Enemies.GetComponents<Component>())
{
    Debug.Log(component.name)
}

```

---

Also maybe instead of

```
 public Component Enemies;

```

use

```
public GameObject Enemies;

```

That's not the problem, but when given a GameObject `Component` references the first component it finds on it i.e. Transform. So when you're doing `enemy.GetComponent<EnemyAI>()` it translates to `enemy.gameObject.GetComponent<EnemyAI>()` so it's pointless to use `Component` instead of `GameObject`

---
Tags: unity
---


# Question
Title: Combining cylindrical Billboarding and aligning with velocity (unity)
I'm trying to make a custom GPU particle solution on Unity to fullfill some needs on my project, using compute shaders and custom shader + Graphics.DrawProceduralNow() to draw them.

While I managed to make the system, I'm struggling making the particles cylindrical billboards and align them to their velocity axis as I'm not really used to work with matrices.

I achieved to make both effect working individually (using usefull ressources on the forum) but I can't manage to combine the two rotations without obtaining wrong results

```
v2f vert(uint id : SV_VertexID, uint inst : SV_InstanceID)
{
    v2f o;

    //Vertex position
    float3 q = quad[id];

    float3 newPos = q * particles[inst].size * _SizeMul;

    //PARTICLE DIRECTION

    float3 particleDirection = normalize(particles[inst].velocity);

    float3x3 rotMatrix;

    float3 xaxis = cross(float3(0,0,1), particleDirection);
    xaxis = normalize(xaxis);

    float3 zaxis = cross(xaxis, particleDirection);
    zaxis = normalize(zaxis);

    //Matrix for particle direction
    rotMatrix[0].xyz = float3(xaxis.x, particleDirection.x, zaxis.x);
    rotMatrix[1].xyz = float3(xaxis.y, particleDirection.y, zaxis.y);
    rotMatrix[2].xyz = float3(xaxis.z, particleDirection.z, zaxis.z);

    newPos = mul(rotMatrix, newPos);

    //CYLINDRICAL BILLBOARDING

    // Distance between the camera and the center
    float3 dist = _WorldSpaceCameraPos - particles[inst].position;

    // With atan the tree inverts when the camera has the same z position
    float angle = atan2(dist.x, dist.z);

    float cosinus = cos(angle);
    float sinus = sin(angle);

    // Matrix for billboarding
    rotMatrix[0].xyz = float3(cosinus, 0, sinus);
    rotMatrix[1].xyz = float3(0, 1, 0);
    rotMatrix[2].xyz = float3(- sinus, 0, cosinus);

    newPos = mul(rotMatrix, newPos);

    newPos += particles[inst].position;

    o.pos = mul(UNITY_MATRIX_VP, float4(newPos.xyz,1));

    o.uv = q + 0.5f;

    o.col = particles[inst].alive * particles[inst].color;

    return o;

}

```

Another way to say it is i would like Y to point toward the velocity direction and then rotate the quad around it's new Y axis to make the billboard point at best toward camera.

Any help would be much appreciated and any other approach for cylindrical billboarding that would work once quad is aligned to velocity vector would be welcomed too. Have a good day!

# Answer
> 1 votes
Finally got it right ! Got it by trying to learn more about those matrices. I needed to use the direction vector between particle position and camera as a forward vector

Here's the code for those who need it.

```
float3 q = quad[id];

float3 newPos = q * particles[inst].size * _SizeMul;

float3 particleDirection = normalize(particles[inst].velocity);

float3 cameraDir = normalize(particles[inst].position - _WorldSpaceCameraPos);

float3x3 rotMatrix;

float3 xaxis = cross(cameraDir, particleDirection);
xaxis = normalize(xaxis);

float3 zaxis = cross(xaxis, particleDirection);
zaxis = normalize(zaxis);

rotMatrix[0].xyz = float3(xaxis.x, particleDirection.x, zaxis.x);
rotMatrix[1].xyz = float3(xaxis.y, particleDirection.y, zaxis.y);
rotMatrix[2].xyz = float3(xaxis.z, particleDirection.z, zaxis.z);

newPos = mul(rotMatrix, newPos);

newPos += particles[inst].position;

o.pos = mul(UNITY_MATRIX_VP, float4(newPos.xyz,1));

o.uv = q + 0.5f;

o.col = particles[inst].alive * particles[inst].color;

return o;

```

---
Tags: unity, shaders, hlsl, particles, projection-matrix
---


title: Instantiation of a custom class

text:
# Question
Title: Instantiation of a custom class
I have a custom class named Stars:

```
class Star
{
    public int primaryID;
    public string properName;
    public string HIPID;
    public string HDID;
    public string HRID;
    public string GLID;
    public string BFID;
    public decimal rightAscension;
    public decimal declination;
    public string magnitude;
    public string colourIndex;
    public int scale;
    public int red;
    public int green;
    public int blue;
    public bool isSimulated;
    public double x;
    public double y;
    public double z;

    public void setDetails(int primaryID, string properName, string HIPID, string HDID, string HRID, string GLID, string BFID, decimal rightAscension, decimal declination, string magnitude, string colourIndex)
    {
        this.primaryID = primaryID;
        this.properName = properName;
        this.HIPID = HIPID;
        this.HDID = HDID;
        this.HRID = HRID;
        this.GLID = GLID;
        this.BFID = BFID;
        this.rightAscension = rightAscension;
        this.declination = declination;
        this.magnitude = magnitude;
        this.colourIndex = colourIndex;
        decimal deg2rad = 0.01745329251994329576923690768489m;

        this.isSimulated = true;

        // Decimal datatype is used to make sure that values are very accurate and precise
        decimal degrees_ra;
        decimal degrees_dec;
        decimal radians_ra;
        decimal radians_dec;

        degrees_ra = Decimal.Multiply(rightAscension, 15);
        degrees_dec = declination;

        radians_ra = Decimal.Multiply(degrees_ra, deg2rad);
        radians_dec = Decimal.Multiply(degrees_dec, deg2rad);

        // Converted from decimal to double because the Math library cannot work with decimals
        float distanceStars = 19113;

        this.x = (distanceStars * Math.Cos(decimal.ToDouble(radians_dec)) * Math.Cos(decimal.ToDouble(radians_ra)));
        this.y = (distanceStars * Math.Cos(decimal.ToDouble(radians_dec)) * Math.Sin(decimal.ToDouble(radians_ra)));
        this.z = (distanceStars * Math.Sin(decimal.ToDouble(radians_dec)));
    }

    public Vector3 getVector()
    {
        return new Vector3((float)z, (float)y, (float)x);
    }
}

```

There are many of these stars and I want to instantiate them at run-time:

```
void plotStars()
{
    int i = 0;
    while (i < (StarDataBank.Instance.NumOfStars))
    {
        string name = StarDataBank.Instance.StarName[i];
        string HIP = StarDataBank.Instance.StarIDHIP[i];
        string HD = StarDataBank.Instance.StarIDHD[i];
        string HR = StarDataBank.Instance.StarIDHR[i];
        string GL = StarDataBank.Instance.StarIDGL[i];
        string BF = StarDataBank.Instance.StarIDBF[i];
        decimal RA = Convert.ToDecimal(StarDataBank.Instance.StarRA[i]);
        decimal Dec = Convert.ToDecimal(StarDataBank.Instance.StarDec[i]);
        string Mag = StarDataBank.Instance.StarMag[i];
        string ColI = StarDataBank.Instance.StarCI[i];

        var star = new Star();
        star = Instantiate(ObjectStar, transform.position + star.getVector(), Quaternion.identity);

        star.transform.parent = StarObject.transform;
        star.transform.localScale = new Vector3(star.scale, star.scale, star.scale);
        i++;
    }
}

```

But I am experiencing a lot of errors.

1. Unity isn't instantiating the Stars because it can't convert UnityEngine.Transform to Star
2. Star doesn't contain definition of Transform

Is there a way to assign a class as a gameobject?

# Answer
It looks like you're using the variable named `star` to do double-duty:

`var star = new Star();`

This says "make a new data structure to hold information about this star"

`star = Instantiate(ObjectStar, ...);`

This says "make a new copy of the `ObjectStar` game object to represent this star in the game scene, and give me its `Transform` (since the `ObjectStar` variable is of type `Transform`"

These two uses are contradictory. This variable cannot simultaneously hold a `Star` and a `Transform`. Pick one or the other.

So, use separate variables for these two uses:

```
Star star = new Star();
Transform sceneObject = Instantiate(ObjectStar, ...);`

```

If you want to associate information from this star data structure with your scene object, you have a few options:

* You can use a `Dictionary` to store a mapping from star data to scene objects, or vice versa
* You can make your `Star` class a `MonoBehaviour` component that can be attached to a game object, just like other components in Unity, using `AddComponent` in script, or the button at the bottom of the Inspector.
* You can make a new `MonoBehaviour` component to attach to your scene object, that holds a reference to a `Star` data structure. This lets you get the advantages of bolting the component directly to the object it relates to, while keeping your `Star` class uncluttered with `MonoBehaviour` stuff — in case your `Star` class needs to be serialized or inter-operate with non-Unity code elsewhere in your project.

Here's an example of that last style:

```
public class StarRepresentation : MonoBehaviour {
    public Star starData;
}

```

You can set up your `ObjectStar` object to have one of these `StarRepresentation` components attached, by using the "Add Component" button in the Inspector.

Then you can change your declaration of the object to...

```
public StarRepresentation starPrefab;

```

Making it use the `StarRepresentation` type means that when you `Instantiate` it, you'll get the component you want directly, without needing a `GetComponent` call.

Now when you want to instantiate & populate your new star object with star data, you can do it like this:

```
StarRepresentation representation = Instantiate(starPrefab, ...);
representation.starData = new Star ();

```

Then you can fill in the details of this `starData` as you like.
> 1 votes

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


title: Moving object with turn in UE4

text:
# Question
Title: Moving object with turn in UE4
I have been struggling with this problem for a while. In my project (RTS in space) I have a ship moving on a 2D plane. I want to make the right movement in space so that when I click somewhere in space:

1. The ship began the movement by constantly turning its nose towards the destination point. It will turn out some kind of curve;
2. or turned around its axis while standing still and then moved to the point if this happens faster than in the first version.

For the first version i came with this pseudocode (assume that Z component always 0, and assume that moveTo is called every tick)

```
int moveTo(vector3 &position, float deltaTime)
{
    float forwardSpeed = 10;
    float forwardTurningSpeed = forwardSpeed * 0.5;

    // Find direction to destination point
    vector3 direction = position - GetActorLocation();
    direction.normalize();

    // Find on which angle to rotate the actor
    float angleBetweenDirectionAndWorldRightVector = getAngleBetweenVectors(direction, GetRightVector());
    float angleBetweenActorForwardVectorAndWorldRightVector = getAngleBetweenVectors(GetActorForwardVector(), GetRightVector());
    // This subtracion is the root of all problems
    float angle = angleBetweenDirectionAndWorldRightVector - angleBetweenActorForwardVectorAndWorldRightVector;
    // When finding angle between direction vector and actor`s forward vector the value is from 0 to 180
    // and there is no difference when direction is to the left by say 10 degrees or to the right
    // I thought that by subtracting angle between actor`s forward vector and world`s right
    // vector i could decide whether direction is to the left or to the right from actor`s forward vector
    // but its not working in this way

    if(angle < 10 || angle > -10)
    {
        // If actor looking at target position nearly straight then move forward
        vector3 newPosition = GetActorLocation() + GetActorForwardVector() * forwardSpeed * deltaTime;
        SetActorLocation(newPosition);
    }
    else
    {
        // Rotate actor while moving around Z axis (on a plane XY)
        if (angle < 180)
        {
            // Rotate counter-clockwise
            SetActorRotation(0,0,GetActorRotation().Yaw() + angle * deltaTime);
        }
        else
        {
            // Rotate clockwise
            SetActorRotation(0,0,GetActorRotation().Yaw() + angle*(-1) * deltaTime);
        }
        // Move forward after rotation
        vector3 newPosition = GetActorLocation() + GetActorForwardVector() * forwardTurningSpeed * deltaTime;
        SetActorLocation(newPosition);
    }
    // Stop if reached destination
    if((position - GetActorLocation()).LenghtSquared() < 100) return 1;
}

float getAngleBetweenVectors(vector3 &first, vector3 &second)
{
    // Find angle using dot product
    float dotProduct = dotProduct(first, second);
    float cosinus = dotProduct / (first.length() * second.length());
    return acosd(cosinus); // returns angle in degree
}

```

This is what I\`ve got.  The second variant is quite simple by using standard MoveComponentTo unreal function twice. First apply to rotate around Z axis while standing still and second apply to move straight to destination.

I don\`t know how to prebuilt path to avoid obstacles so this is next step.

# Answer
> 0 votes
So the answer I got was very simple. I had to use cross product instead of dot product. The answer code listing is connected to my question

```
int moveTo(vector3 &position, float deltaTime)
{
    ...
    // This way the angle between direction and forward vector can be obtained (0-180 degrees)
    float angle = getAngleBetweenVectors(direction, GetForwardVector());
    // This will obtain the cross product value (standard UE4 function)
    float crossProduct = CrossProduct(direction, GetForwardVector());

    if (crossProduct < 0)
    {
        // turn right by angle value
    }
    else if (crossProduct > 0)
    {
        // turn Left by angle value
    }
    else if (crossProduct == 0)
    {
        // move forward
    }
}

```

---
Tags: movement, unreal-4
---


# Question
Title: How to make a vision cone for the enemy in game maker?
I'm making an enemy object where the enemy look for the player when he's going on a patrol

I want the vision cone to changes direction corresponding to the sprite.When the sprite turn right,the cone will faces right,left and the cone will faces left and when he move to any direction the cone will move with him and changes direction accordingly

I also want to give the cone certain ranges.The longest range's where the enemy will be in doubt and get to that position to investigate,medium range he'll start chasing,shortest range he'll attack.

I hope someone can help me.

# Answer
**I will be giving the answer assuming that your sprites were designed this way (with the front side up):**

The origin of sprites is middle center and bottom center, respectively.

**obj\_Enemy - Create Event:**

```
cone=instance_create_depth(x,y,-5,obj_Cone);
cone.owner=self();

```

**obj\_Enemy - Step Event:**

```
direction=point_direction(x,y,mouse_x,mouse_y)-90;
seno=dsin(point_direction(x,y,mouse_x,mouse_y));
cose=dcos(point_direction(x,y,mouse_x,mouse_y));

```
* **-90** is for the values to match. It may vary according to the way your sprites were designed.

**obj\_Cone - Draw Event:**

```
draw_sprite_ext(spr_Cone,0,owner.x+(20*owner.cose),owner.y+(-20*owner.seno),1,1,owner.direction,c_white,1);

```
* **20** was a value that I stipulated as suitable for my tests, it may be the value that you want in your game.

**obj\_Cone - Collision with Player Event:**

```
direction=point_direction(x,y,obj_Player.x,obj_Player.y); //For the enemy to turn to the player
...
rest of your code
...

```

**At range/distance you can use the following code in the enemy's step event:**

```
if(distance_to_object(obj_Player)<=300){

}else{

}

```

**But if you prefer you can do something like this, for different distances:**

See above, that there are 3 different cones, with green being the smallest and red being the largest. That is, there would be 3 cone objects. You would do the same process for everyone.

For the player not to notice this, they just need to be the same color.
> 1 votes

# Answer
enemy line of sight has some standards that works in all engines and languages. i show you the algorithm,you can implement this on your game maker engine:

```
if (target overlapping sphere)// if its near than a value to me
{

    direction = Normalize(target - this);//target is enemy position. this is my position
    dot = Dot(direction, forward);// it means dot product. you can calculate it yourself or find library to do this for you
    if (dot > 0.707)// you can change this for bigger or less eye sight
    {
     //  I see target!
    }
}

```
> 0 votes

---
Tags: game-maker, line-of-sight
---


# Question
Title: GLM conversion from euler angles to quaternion and back does not hold
I am trying to convert the orientation of an OpenVR controller that I have stored as a `glm::vec3` of Euler angles into a `glm::fquat` and back, but I get wildly different results and the in-game behavior is just wrong *(hard to explain, but the orientation of the object behaves normally for a small range of angles, then flips in weird axes)*.

This is my conversion code:

```
// get `orientation` from OpenVR controller sensor data

const glm::vec3 eulerAnglesInDegrees{orientation[PITCH], orientation[YAW], orientation[ROLL]};
debugPrint(eulerAnglesInDegrees);

const glm::fquat quaternion{glm::radians(eulerAnglesInDegrees)};
const glm::vec3 result{glm::degrees(glm::eulerAngles(quaternion))};
debugPrint(result);

// `result` should represent the same orientation as `eulerAnglesInDegrees`

```

I would expect `eulerAnglesInDegrees` and `result` to either be the same or equivalent representations of the same orientation, but that is apparently not the case. These are some example values I get printed out:

```
39.3851 5.17816 3.29104
39.3851 5.17816 3.29104

32.7636 144.849 44.3845
-147.236 35.1512 -135.616

39.3851 5.17816 3.29104
39.3851 5.17816 3.29104

32.0103 137.415 45.1592
-147.99 42.5846 -134.841

```

As you can see above, for some orientation ranges the conversion is correct, but for others it is completely different.

**What am I doing wrong?**

I've looked at existing questions and attempted a few things, including trying out every possible rotation order listed here, conjugating the quaternion, and other random things like flipping pitch/yaw/roll. Nothing gave me the expected result.

**How can I convert euler angles to quaternions and back, representing the original orientation, using `glm`?**

---

Some more examples of discrepancies:

```
original:      4; 175;   26;
computed:   -175;   4; -153;
difference:  179; 171;  179;

original:     -6; 173;   32;
computed:    173;   6; -147;
difference: -179; 167;  179;

original:      9; 268;  -46;
computed:   -170; -88;  133;
difference:  179; 356; -179;

original:    -27; -73;  266;
computed:    -27; -73;  -93;
difference:    0;   0;  359;

original:    -33; 111;  205;
computed:    146;  68;   25;
difference: -179;  43;  180;

```

I tried to find a pattern to fix the final `computed` results, but it doesn't seem like there's one easy to identify.

---

GIF + video of the behavior:

---

Visual representation of my intuition/current understanding:

* The above picture shows a sphere, and I'm in the center. When I aim the gun towards the green half of the sphere, the orientation is correct. When I aim the gun towards the red half of the sphere, it is incorrect - it seems like every axis is inverted, but I am not 100% sure that is the case.

# Answer
> 4 votes
The results are not what you expect, but they are not wrong. It’s just that for a given orientation there are at least two “paths” through Euler angles that lead there.

For instance, the identity quaternion is trivially converted to Euler angles `[0,0,0]`. But doing three 180-degree rotations around each axis leaves you in the same orientation, too. That means that `[180,180,180]` is a valid Euler angle representation of that quaternion, too.

Now since your character appears to be a human, it’s probable that their head can’t roll at 180-degree angles, so here is a simple method that you can use to fix your values:

```
if (std::fabs(result.z) >= 90) {
    result.x += 180.f;
    result.y = 180.f - result.y;
    result.z += 180.f;
}

```

---
Tags: opengl, c++, quaternion, glm, euler-angles
---


title: testPoint not working - libgdx

text:
# Question
Title: testPoint not working - libgdx
I'm making a game like angry birds with LibGDX and box2d in which I want to drag a ball (instead of the bird) back before releasing it.

I deploy with testPoint function: when I touch down the screen, I check if the point is within the body of the ball or not but testPoint function never works exactly. Here's what I'm trying thanks so much:

```
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    for(Fixture fixture:bird.getBody().getFixtureList()) {
        if(fixture.testPoint(screenX/100, (mapHeight-screenY)/100)) { //100 is scaled parameter
             draggedBird = true;
             return true;
         }
    }
    return false;
}

```

# Answer
> 1 votes
The problem I see is you are dividing the `screenX` and `screenY` values by 100 here:

```
if(fixture.testPoint(screenX/100, (mapHeight-screenY)/100)) { //100 is scaled parameter

```

`screenX` and `screenY` are the values indicating the X and Y coordinates of your touch and by sending a modified value to your `testPoint` method you're not testing with the right values.

I suggest you send the original values to your `testPoint` method like so:

```
fixture.testPoint(screenX, mapHeight - screenY)

```

A couple of tips:

* If you need a dragging behaviour check the `onDragged` method instead of the `touchDown` one.
* If you are using an `OrthographicCamera` for your game (which is recommended) you don't have to worry about wrong screen coordinates since you unproject the values to the correct ones and you don't even have to worry about the Y axis being reversed, here's an example:

```
OrthographicCamera camera = new OrthographicCamera(gameWidth, gameHeight); // gameWidth and gameHeight can be any float you want

public boolean touchDown(int screenX, int screenY, int pointer, int button) {
Vector3 unprojected = camera.unproject(new Vector3(screenX, screenY, 0f));
float x = unprojected.x;
float y = unprojected.y;
    for(Fixture fixture:bird.getBody().getFixtureList()) {
        if(fixture.testPoint(x, y) {
             draggedBird = true;
             return true;
         }
    }
    return false;
}

```

---
Tags: libgdx, box2d
---


title: My script doesn't read my prefabs

text:
# Question
Title: My script doesn't read my prefabs
My script is supposed to randomly spawn different slipper projectiles from an array, but when I hit Play Mode, my filled prefabs disappear from the script.

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

public class SpawnSlippers : MonoBehaviour {

public GameObject[] slipperArray;
float randX;
Vector2 spawningArea;
public float spawnRate = 2f;
float nextSpawn = 0.0f;
// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update()
{

    slipperArray = new GameObject[6];

        if (Time.time > nextSpawn)
        {
            nextSpawn = Time.time + spawnRate;
            randX = Random.Range(-12.47f, 10.4f);
            spawningArea = new Vector2(randX, transform.position.y);
            Instantiate(slipperArray[Random.Range(0, slipperArray.Length)], spawningArea, Quaternion.identity);

    }
}

```

}

# Answer
> 1 votes
```
slipperArray = new GameObject[6];

```

This line says "please throw out whatever was previously in the `slipperArray` variable, and replace it with a freshly-allocated empty array"

If that's not the behaviour you want, don't ask for it. Delete that line.

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


title: Alternative path not working

text:
# Question
Title: Alternative path not working
I am using Android studio (libGDX), and I can't figure out why alternative paths doesn't work. I've tried it as it said in the book, but it doesn't do anything, it shows a black window and than the program exterminates. If the .png file would be in the .../android/assets/ folder, it wouldn't work either.

Book: Java Game Development with LibGDX 2nd edition

This is what the book wants me to do it:

```
public Spaceship(float x, float y, Stage s){

    super(x,y,s);
    loadTexture( "assets/spaceship.png" );
    setBoundaryPolygon(8);

    setAcceleration(200);
    setMaxSpeed(100);
    setDeceleration(10);
}

```

This is the shortest form that works for me:

```
public Spaceship(float x, float y, Stage stage) {

    super(x, y, stage);

    loadTexture("core/src/com/dusi/game/ch04/assets/spaceship.png");
    setBoundaryPolygon(8);

    setAcceleration(400);
    setMaxSpeed(200);
    setDeceleration(20);
}

```

This is what my path looks like:

# Answer
**For a Desktop Application**
If you are working on a desktop app it has to do with the Run/Debug Configuration:

The important part is to set the "Working directory" to *YourGameName\android\assets*
> 0 votes

---
Tags: java, libgdx, path
---


# Question
Title: How can I rotate a cylinder so the top points at specific transform?
I have a GameObject (`goA`) with a LineRenderer that has a single line drawn, on which I'd like to place cylinders so the top of the cylinder points to each end of the straight line that the cylinder sits on, (similar to a cylindrical bead on a straight piece of string, or a Candlestick chart).

The cylinder GameObject (`goB`) is a child of the `goA` which the LineRenderer is sat on (`goB.transform.parent == goA.transform`).

`goA` is not rotated itself, and the Line drawn could be any angle relative to the GameObject, and it would be a bit of a hassle to refactor so that the Line is always vertical and instead rotate `goA`, and it seems this should be an easily solvable problem!

I'm attempting to use either LookRotation or LookAt on the cylinder but for whatever reason all permutations I can think of simply are not working.

Thanks for any advice!

# Answer
> 1 votes
First, get the direction from the start of the line to the end:

```
var direction = endTransform.position - startTransform.position;

```

Then form an orientation that rotates the up vector to that direction:

```
var orientation = Quaternion.FromToRotation(Vector3.up, direction);

cylinderTransform.rotation = orientation;

```

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


# Question
Title: How to transition between "rooms" / virtual cameras on a button press?
I'm trying to make a game that navigates like the example here:

I'd like it so that after combat, the player can push the button corresponding with an exit (left, right, up, down) and navigate like in this game.

Also I eventually hope to randomize each run of the game so it would hopefully have some flexibility outside of being hard baked.

I've seen examples of it being done with a player object and a collider, but the player won't actually be moving their character. I like this style of navigation because I think it still provides the joy of exploration for the player, but is more friendly of a navigation system for a novice like me.

How would I implement something like this?

# Answer
> 1 votes
I'd start by making a component to associate with each room. Attach this to an empty game object at the position & orientation you want to view the room from.

This can also store information about which rooms are reachable from this one.

While we're at it, we can load it up with data about how the room should behave - like events to fire when the player reaches the room.

```
public class RoomView : MonoBehaviour {

    public bool visited;

    public RoomView northConnection;
    public RoomView eastConnection;
    public RoomView southConnection;
    public RoomView westConnection;

    public UnityEvent onEnterRoomFirstTime;
    public UnityEvent onEnterRoomSubsequent;

    public void Enter() {
        if(!visited && onEnterRoomFirstTime != null) onEnterRoomFirstTime.Invoke();

        visited = true;

        if(onEnterRoomSubsequent != null) onEnterRoomSubsequent.Invoke()
    }
}

```

For starters, you can wire up these references in the Inspector. Once you create your randomized generator, your generation routine can automatically wire-up adjacent rooms as it places them, or in a post-process scan over the level it's built.

Next we'll need a script on the camera to navigate between these rooms:

```
public class RoomCamera : MonoBehaviour {

    // Populate this in the Inspector to point to the first room.
    public RoomView currentView;

    // How long should a transition take, in seconds.
    public float transitionSeconds = 1f;

    // Where are we going next?
    RoomView _nextView;
    // How far are we through the transition, in the range 0 to 1?
    float _transitionProgress;

    // At the beginning, snap to our first room perspective, and enter that room.
    void OnEnable() {
        transform.position = currentView.transform.position;
        transform.rotation = currentView.transform.rotation;
        currentView.Enter();
    }

    // Each frame, either continue the transition, or accept input if not transitioning.
    void Update() {
        if(_nextView == null) {
            CheckInput();
        } else {
            ContinueTransition();
        }
    }

    void CheckInput() {
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");

        // You can add some extra checks here to ignore diagonals, if desired.
        // Or wire these up to be triggered by on-screen buttons instead of keyboard/gamepad.

        if(horizontal > 0.5f && currentView.eastConnection != null) {
            _nextView = currentView.eastConnection;
        }
        if(horizontal < -0.5f && currentView.westConnection != null) {
            _nextView = currentView.westConnection;
        }

        if(vertical > 0.5f && currentView.northConnection != null) {
            _nextView = currentView.northConnection;
        }
        if(vertical < -0.5f && currentView.southConnection != null) {
            _nextView = currentView.southConnection;
        }
    }

    void ContinueTransition() {
         // Accumulate progress based on time passed, clamping within the range 0...1.
        _transitionProgress = Mathf.Clamp01(
                                _transitionProgress
                                + Time.deltaTime / transitionSeconds);

        // Add some ease-in/out on the transition.
        // You can also use an animation curve to customize the easing.
        float blend = Mathf.SmoothStep(0f, 1f, _transitionProgress);

        transform.position = Vector3.Lerp(
                                currentView.transform.position,
                                _nextView.transform.position,
                                blend);

        transform.rotation = Quaternion.Lerp(
                                currentView.transform.rotation,
                                _nextView.transform.rotation,
                                blend);

        // If we're finished transitioning, clear the transition state.
        if(_transitionProgress == 1f) {
            currentView = _nextView;
            _nextView = null;
            _transitionProgress = 0f;
            currentView.Enter();
        }
    }
}

```

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