# Question
Title: Unity how to save the number of successive wins?
I'm making a trivia game on Unity, everything works fine and now I'm trying to save and retrieve the stats of a game. I have listed most of the stats (score, highscore, points) but now I would like to add the best series of consecutive correct answers, and I don't know how I can exactly set this value.

In theory I know that during the game when a correct answer is given, a counter is triggered to record the number of consecutive correct answers and it stops at the wrong answer. Then at the next triggered series the method checks if the new count is the best. But, as I'm a beginner, I don't know how I can save this kind of streak.

Could you help me please?

In order to understand the context:

```
public class ansButtonScript : MonoBehaviour {

public Text txt;
public Sprite im_basic, im_corr, im_wrong;

#region Pts&Score
    public int points = 1;
    string _allPts = "totalPts";
    static int totalPts;
    static int score = 0;
    string _score = "score";
    static int hiscore = 0;
    string _hiScore = "hiScore";
#endregion

public AudioClip sound_win, sound_loose;
public GameObject correctTxt, wrongTxt;

#region Cache Refs
public GameObject _canvas, _barInt;
private qManager _qManagerCanvas;
private progBarScript _progBarInt;
private countdownScript _barCountdown;
#endregion

public void Start()
{
    totalPts = PlayerPrefs.GetInt(_allPts);

    _qManagerCanvas = _canvas.GetComponent<qManager>();
    _progBarInt = _barInt.GetComponent<progBarScript>();
    _barCountdown = _barInt.GetComponent<countdownScript>();
}

public void updateTxt(string str_text)
{
    txt.text=str_text;
    GetComponent<Image>().sprite = im_basic;
}

public void SelectButton()
{
    if(_qManagerCanvas.canPlay)
    {
        _progBarInt.barTimeStop();
        _qManagerCanvas.canPlay = false;
        string reponse = _qManagerCanvas.reponse;

        if(transform.Find("Text").GetComponent<Text>().text == reponse)
        {
            //good answer
            GetComponent<AudioSource>().PlayOneShot(sound_win);     //SFX Win
            vraiTxt.SetActive(true);                                //animation Correct
            updateTrue();                                           //the answer is shown
            StartCoroutine(addPoints());
            StartCoroutine(next_question());                        //new question
        }
        else
        {
            //wrong answer
            GetComponent<AudioSource>().PlayOneShot(sound_loose);
            fauxTxt.SetActive(true);
            updateFalse();                                      //the answer isn't shown
            StartCoroutine(next_question());                    //new question
            _barCountdown.ResetTimer();
        }
    }
}

IEnumerator addPoints()
{
    yield return new WaitForSeconds(2.2f);
    playerStats.UpMoney += points;
    score++;                                    //set the nb of correct answers
    saveAllPts();                               //save the nb of points
    PlayerPrefs.SetInt(_score, score);          //save the nb of corr answers
    SaveBestScore();                            //save best score
}

IEnumerator next_question()
{
    yield return new WaitForSeconds(3f);
    _qManagerCanvas.tirage();
    _barCountdown.ResetTimer();
    correctTxt.SetActive(false);
    wrongTxt.SetActive(false);
}

public void updateTrue()
{
    GetComponent<Image>().sprite = im_corr;
}
public void updateFalse()
{
    GetComponent<Image>().sprite = im_wrong;
}

public void SaveBestScore()
{
    if (score > PlayerPrefs.GetInt(_hiScore))
    {
        PlayerPrefs.SetInt(_hiScore, score);
    }
}

public void saveAllPts()
{
    totalPts += points;
    PlayerPrefs.SetInt(_allPts, totalPts);
}
}

```

# Answer
> 0 votes
It's hard to answer without seeing your code, but it would be something like this:

```
int consecutiveHits = 0;
int consecutiveHitsRecord = 0;

public void OnAnswerQuestion(int answer)
{
    if(answer == correctAnswer)
    {
        consecutiveHits++; //Increments the count of hits
    }
    else
    {
        // Check if the series is a record
        if(consecutiveHits > consecutiveHitsRecord)
        {
            consecutiveHitsRecord  = consecutiveHits;
        }

        consecutiveHits = 0; // Restarts the counter
    }
}

public void OnEndGame()
{
    if(consecutiveHits > consecutiveHitsRecord)
    {
        consecutiveHitsRecord  = consecutiveHits;
    }
}

```

Of course this is a pseudocode, you have to adapt it with your own! The first part goes where you're checking if the answer is correct and the second where the game ends.

# Answer
> 1 votes
If I am understanding correctly you want to keep a running score that resets on an incorrect answer I would use events. Put the EventManager and ScoreManager on an GameObject somewhere in your scene.

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

public class EventManager : MonoBehaviour
{
    //Create a new delegate
    public delegate void CorrectAnswer();
    //Create the event for the delegate
    public event CorrectAnswer OnCorrectAnswer;

    //here's the function we'll call from otherscripts to tell whatever is subscribed (ScoreManager) in this case
    //to do whatever it needs to do on a correct answer given
    public void TriggerOnCorrectAnswer()
    {
        if (OnCorrectAnswer != null)
        {
            OnCorrectAnswer();
        }
    }

    public delegate void WrongAnswer();
    public event WrongAnswer OnWrongAnswer;

    public void TriggerOnWrongAnswer()
    {
        if (OnWrongAnswer != null)
        {
            OnWrongAnswer();
        }
    }
}

```

I'm only using "Score" here to keep it simple but you can keep track of pretty much any action your player makes, you could track how many questions they got wrong for example.

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

public class ScoreManager : MonoBehaviour
{
    public EventManager eventManager;

    //I'll use this as the current players score
    private Dictionary<string, int> playerValues = new Dictionary<string, int>();
    //this will be the saved High score board to compare the current players score against
    private Dictionary<string, int> highScoreValues = new Dictionary<string, int>();

    // Use this for initialization
    void Start ()
    {
        //set default score or load score from playerprefs
        playerValues.Add("Score", 0);

        //same for the highest scores
        highScoreValues.Add("HighestScore", 5);
    }

    //make sure to subscribe to the events
    private void OnEnable()
    {
        eventManager.OnCorrectAnswer += UpdateScore;
        eventManager.OnWrongAnswer += GetFinalScore;
    }

    //and also doubly make sure to unsubscribe!
    private void OnDisable()
    {
        eventManager.OnCorrectAnswer -= UpdateScore;
        eventManager.OnWrongAnswer -= GetFinalScore;
    }

    void GetFinalScore()
    {
        Debug.Log("Player's final score is " + playerValues["Score"]);

        //if the players current score is higher than the stored Highest score then
        if (playerValues["Score"] > highScoreValues["HighestScore"])
        {
            //we have a new high score
            highScoreValues["HighestScore"] = playerValues["Score"];

            //you could add a OnNewHighScore event and trigger it here then do ui stuff like show notification, effect, etc
            //eventManager.TriggerOnNewHighScore()
            //this is in its simplest form how achievements work in games
            Debug.Log("New High Score! " + highScoreValues["HighestScore"]);
        }

        //reset player values
        playerValues["Score"] = 0;
    }

    void UpdateScore()
    {
        playerValues["Score"]++;
        Debug.Log("Correct Answer new score is " + playerValues["Score"]);
    }
}

```

Then in your Player Script or where ever you handle question answering trigger the relevant events if the question is correct or wrong.

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

public class Player : MonoBehaviour
{
    //you can set a refence to this via the editor or GameObject.Find/FindOfType<>
    public EventManager eventManager;

    // Update is called once per frame
    void Update ()
    {
        //Demo code when I press space it counts as correctly answering a question
        if (Input.GetKeyDown(KeyCode.Space))
        {
            eventManager.TriggerOnCorrectAnswer();
        }

        //same here but for wrong answers
        if (Input.GetKeyDown(KeyCode.F))
        {
            eventManager.TriggerOnWrongAnswer();
        }
    }
}

```

---
Tags: unity, savegame
---


title: How can I "amplify" current motion ?

text:
# Question
Title: How can I "amplify" current motion ?
I've two objects A and B. A impact B causing B movement.

I want programmatically "amplify" B movement mantaining B resulting direction.

I've try adding a script like this

```
void OnCollisionEnter(Collision col) {
    // Controllo se è un tag
    if (_forceAlreadyApplied==false) {

        _rb.AddForce (_forcePower * transform.forward, ForceType);
        _forceAlreadyApplied = true;

    }
}

```

The problem is that transform.forward obviously change B direction.

Maybe this is a wrong approach.

My question is: how to "amplify" current speed ?

Thanks

# Answer
I've solved using (and multiplying) RigidBody.velocity.

Example:

```
void Update() {
    if (_activated && ApplyForTimer  > 0) {
        _rb.velocity = _rb.velocity * _forcePower;
        ApplyForTimer  = ApplyForTimer  - Time.deltaTime;

    }
}

```
> 0 votes

---
Tags: unity
---


# Question
Title: Instantiate two objects at random non-overlapping positions
I'm making an endless runner game.

I have the script that make coins and walls appear at the same time in front of the player.

The problem is that sometimes the coin and wall appear in the same place/position.

How can I ensure that coins and walls do not appear in the same place/position?

```
public class Instantiate : MonoBehaviour
{
public float betweenSpawn = 1.05f;
public float angle;
public Vector3 spawnValues; //Range of appearing
public GameObject coinPrefab;
public GameObject wallPrefab;

public Transform coinInstantiate;
public Transform wallInstantiate;

void Start()
{
    InvokeRepeating("Spawn", 0f, betweenSpawn);
}

void Spawn()
{
    Vector3 coinPosition = new Vector3(Random.Range(-spawnValues.x, spawnValues.x), 1, Random.Range(-spawnValues.z, spawnValues.z));
    Vector3 wallPosition = new Vector3(Random.Range(-spawnValues.x, spawnValues.x), 1, Random.Range(-spawnValues.z, spawnValues.z));

    Instantiate(coinPrefab, coinPosition + coinInstantiate.TransformPoint(0, 0, 0), Quaternion.AngleAxis(angle, Vector3.forward));
    Instantiate(wallPrefab, wallPosition + wallInstantiate.TransformPoint(0, 0, 0), Quaternion.AngleAxis(angle, Vector3.forward));
}

```

}

# Answer
> 1 votes
Two approaches you can try:

**A) Guess and Check** (simple, usually works well enough, but a little wasteful)

```
void Spawn() {
    // First, we place the wall (assuming it's the bigger / more complicated obstacle)
    Vector3 wallPosition = GetRandomSpawnPositionNear(platformPosition);

    Instantiate(wallPrefab, wallPosition, Quaternion.Euler(0, 0, angle);

    // Next, we try to place the coin in some non-intersecting position.
    // We make sure to limit how many tries we take, so we don't stall unduly.
    for(int i = 0; i < maxSpawnAttempts; i++) {
        Vector3 coinPosition = GetRandomSpawnPositionNear(pathPointPosition);

        // Check for overlaps near this position.
        // (Assuming your wall has a 2D collider attached)
        if(Physics2D.OverlapCircle(coinPosition, coinRadius) == null) {
             // We found a non-overlapping spot! Slap it down & call it done. :D
             Instantiate(coinPrefab, coinPosition, Quaternion.Euler(0, 0, angle));
             return;
        }
        // Otherwise, loop and try again with a new random point.
    }
}

// In case you need it, here's the point-randomizing logic - same as you're using now.
Vector3 GetRandomSpawnPositionNear(Vector3 center) {
    Vector3 spawnOffset = spawnRange;

    spawnOffset.x *= Random.Range(-1f, 1f);
    spawnOffset.z *= Random.Range(-1f, 1f);

    return center + spawnOffset;
}

```

This has a chance to fail and give up before it finds a place to put the coin. In practice, it usually succeeds with just a few tries, unless you've put it in an over-constrained situation (colliders too densely packed in the spawning space to hit a non-overlapping spot by chance)

**B) Correct by Construction**

For this strategy we need to exploit some knowledge of the structure of your level, which unfortunately isn't included in your question so I can only guess. So I'll describe the overall approach rather than explicit code.

Let's say, for example, that we always want the coin to spawn to the left, above, or to the right of the wall. Once we've placed the wall, we can choose one of these three zones randomly, then choose a random place within the selected zone.

By offsetting the zones' positions and sizes using our knowledge of the shape & size of the wall, we can ensure that *any* point we choose in these zones will be non-overlapping, without needing to check for overlaps using physics queries.

# Answer
> 0 votes
I don't know what you are trying to do exactly, but it seems that either your Vector3 position and the Random.Range producing too much similiar numbers (maybe not a high enough range in your spawnvalues?) or that the addition of your pathposition is zero or very low.

Here's how i would do it:

Add an empty gameobject to your player, call it spawnPosition. Simply change the position in front of the player.

then:

```
public class Instantiate : MonoBehaviour
{

public GameObject coinPrefab;
public GameObject wallPrefab;

public Transform attachedGameObject;

void Start()
{

}

void Update(){
 Instantiate(coinPrefab, attachedGameObject.postion, Quaternion.Identity);

}

```

You can change the position also by simply adding a Random.Range to the position.

# Answer
> 0 votes
There are literally **infinite** approaches to this problem.

**One of it could be**, for example, Worley noise \+ Voronoi diagram. You could create that diagram then choose 1 area on it, remove that area from possible samples. Then pick another one and you have 2 non-overlapping points. -

This is harder approach than the next one. But it was just to show you an example of how this can be achieved to support theory of multiple(infinite) ways.

**Everything depends on your game**, its needs, how it should work... without enough context, I doubt that there will be a perfect enough solution for your game.

The easiest/**fast-forward** option in my opinion would be to pick point 1 at random. Then pick another one at random. Check the distance/collision between points -

1. No collision - good, it worked.
2. They overlap - move the second point from other point until(by distance) they don't overlap (opposite direction or whatever suits your game).
3. There is no place for the second point in the direction its choosing - move 2 points simultaneously. 1 away from another till they don't overlap. First on both axis, then separately. - it will always work as far as I understand, unless there is really no space for them to fit at all.
4. Nothing worked - choose second point at random again. Max attempts. Usually it won't get here because of (3). So you will just need to increase the spawn area for points.

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


title: LibGDX Json writes only part of class

text:
# Question
Title: LibGDX Json writes only part of class
Hello I've been developing this game for awhile and now trying to implement save data via Json. I've gotten to where when the app is first launched it will write the Json file with the variables I would like the game to save, but it only writes part of the class that I am passing.

Here is my implementation

```
@Override
    public void create()
    {

        batch = new SpriteBatch();
        file = Gdx.files.external("/bin/save.json");
        create.setFirstSpawn(true);
        create.setSpawnX(-7);
        create.setSpawnY(417);
        create.setTime(0);
        create.setMap("cabinMap");

        if(!file.exists()) {
            Json json = new Json();

            json.setOutputType(JsonWriter.OutputType.json);
            file.writeString(json.prettyPrint(create), false);

        }
        if (file.exists()) {
            JsonReader jread = new JsonReader();
            JsonValue base = jread.parse(file);
            SpawnX = base.getFloat("SpawnX", -7);
            SpawnY = base.getFloat("SpawnY", 417);
            map = base.getString("map", "cabinMap");
            time = base.getFloat("time", 0);
firstSpawn = base.getBoolean("firstSpawn", true);
        }
        if(map == "cabinMap") {
            this.setScreen(new cabinMap(this));
        }
        if(map == "tMap") {
            this.setScreen(new tMap(this));
        }
        if(map == "lowerTMap") {
            this.setScreen(new lowerTMap(this));
        }
        if(map == "rightTMap") {
            this.setScreen(new rightTMap(this));
        }
        else {
            this.setScreen(new cabinMap(this));
        }
    }

```

Here is the class that I am passing

```
public class create
{
    boolean firstSpawn;
    float SpawnX;
    float SpawnY;
    float time;
    String map;

    public void setFirstSpawn(boolean firstSpawn)
    {
        this.firstSpawn = firstSpawn;
    }

    public void setTime(float time)
    {
        this.time = time;
    }

    public float getTime()
    {
        return time;
    }

    public void setMap(String map)
    {
        this.map = map;
    }

    public String getMap()
    {
        return map;
    }

    public boolean isFirstSpawn()
    {
        return firstSpawn;
    }

    public void setSpawnX(float spawnX)
    {
        SpawnX = spawnX;
    }

    public float getSpawnX()
    {
        return SpawnX;
    }

    public void setSpawnY(float spawnY)
    {
        SpawnY = spawnY;
    }

    public float getSpawnY()
    {
        return SpawnY;
    }
}

```

And this is my result

```
{
"map": "cabinMap",
"SpawnX": -7,
"SpawnY": 417
}

```

As you can see from the output file I am missing 2 values. float time and boolean firstSpawn are missing from the file. I've worked for hours trying to find out why. I have no clue why it omitted part of the code... If anyone knows why that would be very helpful to me.

# Answer
Well I fixed my issue that I was having. Instead of using libGDX

> Json

to write to file from the class I used

> JSONObject

and used put() and surrounded it with try and catch to write the classes now the file is pretty and complete with the data that I want to pass.

```
if(!file.exists()) {

        JSONObject jobj = new JSONObject();

        try
        {
            jobj.put("SpawnX", -7);
            jobj.put("SpawnY", 417);
            jobj.put("time", 0);
            jobj.put("map", "cabinMap");
            jobj.put("firstSpawn", true);
        }
        catch (JSONException e)
        {}
        Json json = new Json();

        json.setOutputType(JsonWriter.OutputType.json);
        file.writeString(json.prettyPrint(jobj), false);

    }

```

Output

```
{
"nameValuePairs": {
    "SpawnX": {
        "class": "java.lang.Integer",
        "value": -7
    },
    "SpawnY": {
        "class": "java.lang.Integer",
        "value": 417
    },
    "time": {
        "class": "java.lang.Integer",
        "value": 0
    },
    "map": {
        "class": "java.lang.String",
        "value": "cabinMap"
    },
    "firstSpawn": {
        "class": "java.lang.Boolean",
        "value": true
    }
}
}

```

That is so much better. Well I hope that helps someone else in the future that has the same problem. I still would like to know what went wrong.
> 4 votes

---
Tags: libgdx, savegame, json
---


# Question
Title: Why do actors stretch when I add them to a stage in LibGDX?
I have started learning LibGDX and I have been making a few little games to learn how it all works but ever since I started using stages and actors, all of my textures stretch horizontally and I can't seem to fix it at

```
public class GameScreen extends BaseScreen
{
private BaseActor background;
private PhysicsActor spaceship;
private BaseActor rocketfire;

private PhysicsActor baseLaser;
private AnimatedActor baseExplosion;

private ArrayList<PhysicsActor> laserList;
private ArrayList<PhysicsActor> rockList;
private ArrayList<BaseActor> removeList;

public GameScreen(BaseGame g)
{
    super(g);
}

public void create()
{
    spaceship = new PhysicsActor();
    Texture shipTex = new Texture("fire.png");
    shipTex.setFilter(TextureFilter.Linear, TextureFilter.Linear);
    spaceship.storeAnimation("default", shipTex);
    spaceship.setPosition(400, 300);
    spaceship.setOriginCenter();
    spaceship.setMaxSpeed(200);
    spaceship.setDeceleration(20);
    spaceship.setEllipseBoundary();
    mainStage.addActor(spaceship);
}

public void update(float dt)
{

}
}

```

BaseScreen class

```
public abstract class BaseScreen implements Screen, InputProcessor
{
protected BaseGame game;
protected Stage mainStage;
protected Stage uiStage;
public final int viewWidth;
public final int viewHeight;
private boolean paused;

public BaseScreen(BaseGame g)
{
    this(g, 1024, 600);
}

public BaseScreen(BaseGame g, int viewWidth, int viewHeight)
{
    game = g;
    this.viewWidth = viewWidth;
    this.viewHeight = viewHeight;
    mainStage = new Stage(new FitViewport(viewHeight, viewHeight));
    uiStage = new Stage(new FitViewport(viewWidth, viewHeight));
    paused = false;
    InputMultiplexer im = new InputMultiplexer(this, uiStage, mainStage);
    Gdx.input.setInputProcessor(im);
    create();
}

public abstract void create();
public abstract void update(float dt);

public void render(float dt)
{
    uiStage.act(dt);
    if (!isPaused())
    {
        mainStage.act(dt);
        update(dt);
    }

    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    mainStage.draw();
    uiStage.draw();
}

```

I changed the texture to a perfect red square but when renderered on the screen it was more rectangle shaped than square (horizontally) and I have no idea why. I read somewhere that it was something to do with the camera but I have no idea what to do to fix it! Please help :O

# Answer
There is a mistake in your `Viewport` parameters that you use in the `mainStage`. Instead of passing the `viewWidth` argument, you passed the `viewHeight`, ending up with a `FitViewport(viewHeight, viewHeight)`.

Change it to `FitViewport(viewWidth, viewHeight)` and you should be good to go.
> 1 votes

# Answer
try overriding the "resize" method of your "basecreen" class and update the viewport there

```
@Override
public void resize(int width, int height) {
    stage.getViewport().update(width, height);
}

```
> 0 votes

---
Tags: java, libgdx
---


title: Tuning physics for a "worms"-like game

text:
# Question
Title: Tuning physics for a "worms"-like game
I'm using LibGDX and Box2D for my physics but my characters bounce all over the place when moving and if there is a small slope in the terrain they launch off of it. I've tried tweaking settings but it either seems to completely kill the motion or send the player off to space. How can I get movement closer to Worms where there is a little bounce but the players for the most part stick to the floor.

For reference I want it to be like this:

https://www.youtube.com/watch?v=zMDfo2czbu0&t=5s

What kind of things can I tweak to get that kind of motion?

# Answer
I found out the issue was I was constantly applying velocity instead of doing it based on a delta. Now the player does not bounce around violently.
> 0 votes

---
Tags: java, libgdx, box2d
---


title: Can I offset all rendering in SDL2?

text:
# Question
Title: Can I offset all rendering in SDL2?
I know about `SDL_RenderSetScale`, but I need also horizontal/vertical shift of the renderer's origin. At the moment, I manually modify positions of all screen objects with the shift. Is there a way to set this shift/offset globally?

# Answer
No. You might try tinkering around with `SDL_RenderSetViewport`, but that might not even work, and if it did, you wouldn't be using it for what it is supposed to be used.

The best solution here is to add your own wrapper layer, perhaps inside your own custom renderer class. You would proxy all rendering calls trough a specific method, and that method would automatically offset the rendering for you.

So, manually modifying the positions is the best and most reasonably way to go here.
> 3 votes

# Answer
I like to use a `Camera` class, which contains logic to smoothly track the player. When I want to render, I project my `SDL_Rect`s through the camera with some convenience functions like this:

    void Camera::project(SDL_Rect& rect) {
        rect.x += -floorToInt(position.x) + floorToInt(width * 0.5f);
        rect.y += -floorToInt(position.y) + floorToInt(height * 0.5f);
    }```
</code></pre>

<pre><code>SDL_Rect Camera::getProjected(const SDL_Rect& inRect) {
    SDL_Rect rect = inRect;
    rect.x += -floorToInt(position.x) + floorToInt(width * 0.5f);
    rect.y += -floorToInt(position.y) + floorToInt(height * 0.5f);
    return rect;
}```

The offset is the inverse of the camera's position, plus an additional offset to place the camera focal point at the center of the screen.
> 1 votes

---
Tags: sdl2
---


title: Why use gimbals?

text:
# Question
Title: Why use gimbals?
With all the gimbal lock problems, quaternions, and stuff like that - why do we even use gimbals for rotation? Why not use local rotation instead of gimbals?

# Answer
If I understand you correctly, by local rotation you mean something like this:

```
void RotateCamera(float horizontalInput, float verticalInput) {
    // Apply an incremental rotation about our current vertical axis (local yaw)
    camera.Rotate(horizontalInput * horizontalSpeed, camera.up);

    // and an incremental rotation about our current horizontal axis (local pitch)
    camera.Rotate(verticalInput * verticalLookSpeed, camera.left);
}

```

The trouble with doing this on its own for something like a first-person camera is that these rotations compound in somewhat non-intuitive ways. Consider the ring your forward vector traces across the visual sphere as you turn left to right:

* Starting from zero pitch, looking straight outward, spinning with local yaw will keep your forward vector trained on the horizon, tracing out the equator of your visual sphere.
* Starting from a viewpoint that's looking 45 degrees upward, spinning with local yaw traces a ring that's slanted 45 degrees to the horizontal plane. (Since your local up vector pivot is tilted)

So by the time you've turned 180 degrees to look behind you, you're now looking 45 degrees down instead of 45 degrees up. A horizontal input became a vertical output. If you want to turn around while continuing to look up at the same angle, you need to provide more complicated input to compensate.

When we compound a lot of little local rotations like this frame over frame, the player's reference to global up/down/left/right can become confused:

This is because combining local pitch (x) and yaw (y) rotations can turn into roll (z) rotations - something we're not used to controlling manually in most first person controls (but might be perfectly at home in flight sims or space exploration games)

One common way to fix this is to perform the yaw rotation about the global vertical axis, instead of whichever direction the object's vertical axis is currently pointing. This has the effect of acting like a set of gimbals: An outer gimbal pivoting vertically to control yaw, and an inner gimbal pivoting horizontally off the outer to control pitch.

This keeps the horizontal and vertical input roles more strictly separated, and eliminates unwanted roll:

But this isn't the only solution we can use. Another method, common in flight simulators or spaceship games, is to allow local rotation input to twist and roll the view as shown above, and then apply a compensating rotation to "untwist" it, like an autopilot restoring you to level, so the player doesn't have to manually control a third axis of rotation.

So, the choice of which rotation scheme to use boils down to what kinds of inputs you want to accept, and what kinds of outputs you want them to map to. For some applications, a gimbal-style scheme helps us get an intuitive mapping. For others, it's less appropriate.
> 5 votes

---
Tags: rotation, gimbal-lock
---


# Question
Title: How can I change the color of a SpriteRenderer using a hexadecimal string representation?
I tried to give color like below but unity doesn't accept the format `spriteRenderer.color = "#ffffff"`.

How can I give a hex color to a `SpriteRenderer` in Unity?

# Answer
> 2 votes
Try using `ColorUtility.TryParseHtmlString`

```
   //define a color variable
   Color newCol;
   //if we successfully parse html color string
    if (ColorUtility.TryParseHtmlString(htmlValue, out newCol))
    //then set the colour
        property.colorValue = newCol;

```

ColorUtility.TryParseHtmlString

---
Tags: unity
---


# Question
Title: Does texture splatting always sample 4 x N textures per fragment (regardless of the weights)?
Texture splatting - usually - is done by vertex painting, where each channel R-G-B-A is assigned as a different texture weight.

Due to the way shaders are executed, doesn't it mean that the fragment shaders will ALWAYS sample 4+ textures even if the weights are (1,0,0,0) or (0,1,0,0)?

Lets say some parts of the terrain are almost exclusively grass and the other part of the terrain is exclusively dirt, which means the times when more than one texture sample is necessary is very, very rare - on the transitions, but regardless 4 textures are sampled?

Or do GPUs perform some sort of optimization to minimize the impact of this?

# Answer
Yes it does sample all textures all the time.

It boils down to the cost of sampling compared to the cost of the conditional statement in the shader. At how many samples does the condition start the be beneficial might vary, depending on hardware and such.
> 1 votes

---
Tags: shaders, textures, fragment-shader, gpu
---


# Question
Title: UObjectFinder versus UClassFinder; when is one better than the other?
I want to change the default pawn of my game and I decided to do it with c++.

I came up with this solution, which works fine:

```
static ConstructorHelpers::FClassFinder<APawn> MyPawn(TEXT(" address..."));
        DefaultPawnClass=Pawn.Class;

```

However, I searched on the internet and found this approach used more often:

```
static ConstructorHelpers::FObjectFinder<UClass> MyPawn(TEXT(" address..."));
        DefaultPawnClass=(UClass*)Pawn.Object;

```

What advantages does UObjectFinder have over UClassFinder?

Are there certain circumstances where one is preferable to the other?

# Answer
> 3 votes
`FObjectFinder` is used to find *any* `UObject`. `FClassFinder` is used to find any `UClass`. Note that a `UClass` itself is a `UObject`, so the object finder is the more general utility.

Since what you are ultimately trying to find here is a class, `FClassFinder` is the "better" option in the sense that it more clearly communicates your intent, and the result is itself already a `TSubclassOf<T>`.

---
Tags: unreal-4
---


# Question
Title: Scale screen space quads (used in font rendering)
I have quads positioned in \<0, 1\> x \<0, 1\> coordinates. I use this system for font rendering.

In vertex shader I have:

```
gl_Position.xy = 2.0 * POSITION.xy - 1.0;

```

that brings the position to the screen space \<-1, 1\> x \<-1, 1\>.

My quads are created from two triangles ABD, BCD

```
D-C
|\|
A-B

```

Now, I want to scale the quad by a scale factor. Can I achieve this with this data?

I have tried to change geometry and store quad center and half-sizes, then calculate the final position as

```
gl_Position.xy = 2.0 * (CENTER_POSITION.xy + HALF_SIZE.xy) - 1.0;

```

This way, I can translate points to origin, scale them and translate them back. However, this scale single quad correctly, but the two closely neigboring quads are no longer closely neigboring, since the space between them is constant.

So the final question. How can I scale quads used for font rendering, so that the text is still readable without large gaps between glyphs?

# Answer
> 1 votes
It sounds like you've already answered this for yourself:

> this scales a single quad correctly, but the two closely neigboring quads are no longer closely neigboring, since the space between them is constant.

So, to scale the whole string of text, you need to scale the spaces between them too. That means the centers of each quad aren't fixed.

Instead of translating each quad to the origin then back, you'll want to translate a group of quads that are meant to scale together to the origin then back.

Pick a scaling/pivot point somewhere in your block of text (popular choices are the top-left or bottom-left corner of the whole block, the center of the block, or the start of the first line), and subtract that point from all your quads before scaling, then add it back to the result.

---
Tags: rendering, transformation, fonts
---


# Question
Title: Use GKEntity's component(ofType:) with inheritance
I'm writing a SpriteKit game in swift and making use of GameplayKit's entity-component system. There are many components that do different stuff but share the same methods in which they do it, so I thought I'd group them into categories. At first I thought about using protocols, but `component(ofType:)` only accepts classes. So then I thought about making a base class for each category, define methods and variables there and have the actual components classes override them to implement their own functionality (you know like basic OOP). So I had something like:

```
class InputComponent: GKComponent {
    func handleInput() {
        //Whatever
    }
}

class ControllerComponent: InputComponent {
    override func handleInput() {
        //Do something
    }
}

class KeyboardComponent: InputComponent {
    override func handleInput() {
        //Do something different
    }
}

```

Then somewhere in my code I'd call

```
entity.component(ofType: InputComponent)

```

and I thought I'd get both `ControllerComponent` and `KeyboardComponent` type objects. But I am getting none, it seems `component(ofType:)` doesn't return instances of subclasses.

I guess I can make an extension to `GKEntity` and define something like

```
component<P>(conformingTo protocol: P.Type)

```

and implement that behavior myself but I want to know if I can use the built in function to achieve the same.

# Answer
> 1 votes
Well it appears as if no one here seems to know it so I'll just post what I used which is a new method that I added in an extension to `GKEntity` (which I was actually trying to avoid)

```
extension GKEntity {
    func component<P>(conformingTo protocol: P.Type) -> P? {
        for component in components {
            if let p = component as? P {
                return p
            }
        }

        return nil
    }
}

```

Actually you can pass not only protocol types as an argument, you can actually pass any type (like classes) - so actually the results are similar to the native method provided by Apple, though I am not sure how similar these are so I wouldn't use them interchangeably, I use it solely for when I need to get a `GKComponent` that conforms to a protocol instead of a specific type of `GKComponent`.

---
Tags: entity-component, spritekit, swift, inheritance
---


# Question
Title: Why do transformation matrices always have an extra dimension?
In 3D math I always see matrices with one additional dimension. For example, in 3D graphics, matrices are always 4x4 and in 2d they are 3x3 matrices. Can anyone explain why?

# Answer
> 34 votes
This is a facet of the math of affine transformations crammed into a single matrix.

In an affine transformation you have the equation: `x' = Ax + b`, where `x` is the original vector, `A` is the transformation matrix, and `b` is the translation vector.

To combine `A` and `b` into a single matrix requires some extra work. Namely, we must be sure that we can "turn off" the translation when transforming a geometric vector (they have no position in space and hence cannot move) but still apply it when transforming a geometric point (which is nothing *but* a position in space).

The trick is to put the translation into a fourth column on the transformation matrix as well as adding an additional component to the vectors themselves. This additional component is 1 for geometric points and 0 for geometric vectors. The math of the matrix multiply then works out that the translation components are multiplied by 1 (the identity) for geometric points and added to the final result after rotation/scaling, while the components are multiplied by 0 for geometric vectors and hence nothing is added to the final result.

Explanation with pictures and math examples: https://medium.com/hipster-color-science/computing-2d-affine-transformations-using-only-matrix-multiplication-2ccb31b52181

---
Tags: 3d, mathematics, graphics-programming
---


# Question
Title: How to create a split screen display with one frame and canvas
I am creating a 2D Java game, which looks like this:

My question is what should I do to my display to create two 'separate' displays. I plan on doubling the height of the program, and have a second display which is able to render completely separately to the top display. I'd like it to look like this:

I would like to not have to click between the two displays to be able for them to recognize input. I think this could be done by just keeping one canvas and just commanding the canvas to draw in certain areas? I also am not planning on using any external libraries.

Game class: (Some irrelevant code removed)

```
public class Game implements Runnable {

private Display display;
private int width, height;
public String title;

private Thread thread;
private boolean running = false;

private BufferStrategy bs;
private Graphics g;

public State gameState;
public State menuState;

private Handler handler;

public Game(String title, int width, int height) {
    this.width = width;
    this.height = height;
    this.title = title;
}

private void tick() {
    // Ticks the current game state
    if(StateManager.getState() != null) {
        StateManager.getState().tick();
    }
}

private void render() {
    bs = display.getCanvas().getBufferStrategy();
    if(bs == null) {
        display.getCanvas().createBufferStrategy(3);
        return;
    }
    g = bs.getDrawGraphics();

    //Clear screen
    g.clearRect(0, 0, width, height);

    // Gets the current game state and runs its render method
    if(StateManager.getState() != null) {
        StateManager.getState().render(g);
    }

    // End drawing
    bs.show();
    g.dispose();
}

// Initialize the display, assets, and game states
public void init() {
    display = new Display(title, width, height);
    display.getFrame().addKeyListener(keyManager);
    display.getFrame().addMouseListener(mouseManager);
    display.getFrame().addMouseMotionListener(mouseManager);
    display.getCanvas().addMouseListener(mouseManager);
    display.getCanvas().addMouseMotionListener(mouseManager);

    Assets.init();

    handler = new Handler(this);

    gameState = new GameState(handler);
    menuState = new MenuState(handler);

    StateManager.setState(gameState);
}

public void run() {
    init();

    // Some unimportant code is removed for sake of space
    while (running) {
        tick();
        render();
    }

    stop();
}

}

```

Display class:

```
public class Display {

private JFrame frame;
private Canvas canvas;

private String title;
private int width, height;

public Display(String title, int width, int height) {
    this.title = title;
    this.width = width;
    this.height = height;

    createDisplay();
}

private void createDisplay() {
    frame = new JFrame(title);
    frame.setSize(width, height);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

    canvas = new Canvas();
    canvas.setPreferredSize(new Dimension(width, height));
    canvas.setMaximumSize(new Dimension(width, height));
    canvas.setMinimumSize(new Dimension(width, height));
    canvas.setFocusable(false);

    frame.add(canvas);
    frame.pack();
}

public Canvas getCanvas() {
    return canvas;
}

public JFrame getFrame() {
    return frame;
}

}

```

Launcher class:

```
public class Launcher {

private final static String TITLE = "Game";
private final static int WIDTH = 256;
private final static int HEIGHT = 192;

public static void main(String[] args) {
    Game game = new Game(TITLE, WIDTH, HEIGHT);
    game.start();
}

}

```

# Answer
you can create a Component that does the layout for you.

```
private void createDisplay() {
    frame = new JFrame(title);

    canvas = new Canvas();
    Canvas bottomElement = ...;//code your bottem element here

    JPanel layoutComponent = new JPanel(); //your component that does layout
    layoutComponent.setLayout(new BorderLayout());
    layoutComponent.add(canvas, BorderLayout.CENTER);
    layoutComponent.add(bottomElement , BorderLayout.SOUTH);

    frame.add(layoutComponent);//add layout component now (instead of canvas)
    frame.pack();
}

```

maybe JPanel and Borderlayout are not the Components/Layouts of your choice... you can exchange them easily

for your listeners...
...you can let the listeners as they are but you have to handle the input, but you have to ask where the mouse event came from, see `ActionEvent.getSource` to determine the specific source...
> 0 votes

---
Tags: java, 2d, screen, swing
---


# Question
Title: Get internal and external IP addresses in Unity 2018.2.0?
Unity 2018.2.0 makes the Network class obsolete. I have used "Network.player.ipAddress" in my code to get the local LAN IP address.

```
    internalIP = Network.player.ipAddress;
    externalIP = new WebClient().DownloadString("http://icanhazip.com");

```

What code should replace this? What would be best practice for getting internal and external IP addresses for manual LAN and internet direct connections between server and client?

Internal/external IP addresses are needed so players can load the game, then tell their friends what their IP is to direct connect.

# Answer
> 1 votes
This will output the IP for every interface on the machine.

```
foreach(NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
   if(ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
   {
       foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
       {
           if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
           {
               //do what you want with the IP here... add it to a list, just get the first and break out. Whatever.
               Debug.Log(ip.Address.ToString());
           }
       }
   }
}

```

You'll need to have access to `System.Net.NetworkInformation` in your project.

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


# Question
Title: New game shows up as an update instead of a release
I'm not sure if this is the right place to ask this sort of question but since there is a tag...

I've just released a new game (my first one actually) two days ago. And I've just noticed that it showed up as an update instead of a freshly released game: Under ADDITIONAL INFORMATION section on the listing page it shows **Updated** instead of **Released**. I don't know how that happened and I'm worried it may affect the relevance of the game on the store. Is there any way to fix this issue? Am I right about worrying about the relevance of the game?

Link to the listing page of the game: **Google Play link**.

**EDIT:**

To clear any confusion, I'm not talking about people seeing the install/update button when they are about to install/update the game. I'm talking about the game release dateitself. The game shows up as an update from the Google Play Console as if it was released before. Me publishing the game for the first time was interpretted as updating an already released game, why?

# Answer
I assume that while you were developing the game, you had a version of it installed in your device. Development versions of apps are able to be installed on devices without much checking. When you release the app, android checks that your previous version of that app is a development one, so it updates to the release.

Android can tell the difference between apps based on their unique package name (com.mycompany.myapp), and because your app most likely has the same for both development and release versions, both cannot exist on the same device. **This has no impact on random users**.

Keep in mind that when installing a new version of an app, android also takes a look at the build number. So if you try to "force" an installation of your app with the same build number, android will complain that it is the same app so it won't do anything unless you uninstall it yourself (or some android versions can do that for you).

On the bottom of the page it says "Updated" and has a date. This literally means "Last date the app was updated", there is no "Released". The game was last updated the last time you uploaded an apk. If it's the first time you uploaded it, then that's the last time it was updated. This doesn't affect users at all.
> 2 votes

---
Tags: google-play, release
---


# Question
Title: Implement Bubble Shooter arrow rotation using LibGDX?
I'm trying to implement an arrow at the bottom of the screen on an Android device. This arrow is placed in the center of the screen and is supposed to rotate by a given angle. The problem is that when using the SpriteBatch's draw function for a TextureRegion it rotates the whole image, so the y coordinate also moves up a bit.

I want the arrow to always be in the center of the screen with the x, y coordinates and not move up the y coordinate. I want the y coordinate to stick to the bottom of the screen, but I still need to rotate the arrow. So I don't know if this is possible in my approach to do this.

If you have an approach in LibGDX that is very different from mine. I still want to see it because I don't care how I get this to work, I just want to get it to work somehow.

**This far I've found this Rotation - libGDX that helped me get the rotation a little better, but I need an arrow like in the game called Bubble Shooter. Image of Bubble Shooter Arrow**

The arrow should be the radius inside of an invisible circle, I guess, is one way to see it. See images below.

Example:

# Answer
> 0 votes
You can set the origin when using `SpriteBatch#draw` function. You'll have to substract half of the width when setting the x coordinate too:

```
batch.draw(
    yourTexture,                                  // the texture or texture region
    x - yourTextureWidth / 2, y,                  // x and y coordinates taking into account the origin (horizontal origin is the middle yourTextureWidth / 2, vertical origin is the bottom 0)
    yourTextureWidth / 2, 0,                      // the origin (horizontal origin is the middle yourTextureWidth / 2, vertical origin is the bottom 0)
    yourTextureWidth, yourTextureHeight,          // width and height (keep them the same)
    1, 1,                                         // scale (unaffected)
    rotation                                      // rotation in degrees
);

```

According to your needs, you'll have to set `x` to be half the screen width and set `y` to 0.

**Note:** We have to substract or add the origin offset to the position because the `draw` method origin parameters only affect rotation and scale. Thus, the origin to position should be added manually by substracting or adding to the x and y coordinates.

---
Tags: java, libgdx
---


# Question
Title: Swapping out Vertex Buffer Necessary for Terrain LOD?
I am using Directx 11 to try and implement terrain level-of-detail.

I am trying the idea represented in this tutorial: http://www.rastertek.com/tertut18.html

Which is split your terrain into nodes, and render different quality nodes depending on how far away they are from you.

Each of my nodes has its own vertex buffer (bad idea?), however I am trying to map/unmap when I swap out a particular node for its higher quality version. I noticed that unless my vertex buffer is the size of the high quality version, then surrounding nodes gets affected, I believe this is to be expected since I am essentially overwriting memory in the vertex buffers of the other nodes. So is the only way to go about map/umap is to make each node have the space for the high quality terrain?

If so, then I can't do map/unmap because I run out of memory. What's another approach then? Making a new vertex buffer with the desired size whenever I swap? Won't this be too slow?

# Answer
> 1 votes
OK, I will address one specific point of our concern about swapping.

Firstly, you may consider that the vertex buffer itself may contain the highest detail version of the terrain. And that each LOD has its own list of indices that state which vertices are used in that LOD. BUT, in DirectX 11, using the DrawIndexed also allows for you to offset the indices. What does this mean? Well you can pack all your LODs into the same index buffer, and select them by just knowing that:

A) start index of the Indice B) length of the index list you want to render.

https://docs.microsoft.com/en-us/windows/desktop/api/d3d11/nf-d3d11-id3d11devicecontext-drawindexed

This also works as a strategy for Vertex buffers also, you can have all the LOD vertex information in there. SO you could represent multiple LODs easily in the same buffer.

You can also pack all your vertex buffers and indicies into singular mega buffers if you want. But you are then limited on the size of the world which may not be an issue depending on your game.

Having used rastertek, there is some thought behind why each section has its own vertex and index buffer. The main reason being that if you are dealing with larger worlds, then you need to load these in the background process. As its a grid, its easy to understand which resources should be prioritised and as such loaded. The additional calls are not such a large overhead as they are queued, you do get some level of scale from Command queues, which can shrink the impact of multiple buffers. It's a trade off. It's whether you want to swap lots of small buffers, or just large ones.

The trick is, not to continually map/unmap, but line up your buffers in the most ordered way so your calls (on the CPU side), can determine decisions such as LOD.

Hope this is a start for you.

---
Tags: directx11, terrain-rendering
---


# Question
Title: Dragging arrow around using touch point Bubble Shooter libGDX?
So, now I've got into my second problem of implementing the arrow. The rotation works fine from this **link** **but I have to calculate the angle from a touch point to the middle of the arrow placement.**

I've already calculated that angle, well if I'm not mistaken. I used a vertical distance that is just the touch points y coordinate since the center y coordinate is 0. For the x coordinate I subtracted the touch point minus the texture regions x coordinate in draw function.

**Then to calculate the angle I used arcus tangent inside divided the vertical length by the horizontal length, then multiplied by 180 / PI to get the angle in degrees.**

The thing is that this worked a bit like I wanted, but not exactly. Because when taking the touch points coordinates and bottom center coordinates the invisible triangle that is created will be created as a mirrored triangle on the half side of the screen. Meaning when going over to the other side with a finger the angle was negative. Tried using a the math absolute function but then the arrow bounced back when it reached the angle limit.

Draw function:

```
    @Override
    public void draw(SpriteBatch spriteBatch) {
        spriteBatch.setProjectionMatrix(EtherSky.camera.combined);
        spriteBatch.begin();
        spriteBatch.draw(textureRegion,
            x - textureRegion.getRegionWidth() / 2, y,
            textureRegion.getRegionWidth() / 2, 0,
            textureRegion.getRegionWidth(),
            textureRegion.getRegionHeight(),
            1.0f, 1.0f, degrees);
        spriteBatch.end();
     }

```

Input function:

```
    @Override
    public void input() {

    /*
    if (Gdx.input.getAccelerometerX() > 3 && degrees < 90) {
        degrees++;
    }
    else if (Gdx.input.getAccelerometerX() < -3 && degrees > -90) {
        degrees--;
    }*/

    // Distance from arrow bottom center point to touch point
    float distance = (float)Math.sqrt(
                      Math.pow((inputManager.touchPoint.x - (x - textureRegion.getRegionWidth() / 2)), 2) +
                      Math.pow((inputManager.touchPoint.y - 0), 2));

    float verticalDistance = inputManager.touchPoint.y;
    float horizontalDistance = inputManager.touchPoint.x - (x - textureRegion.getRegionWidth() / 2);
    float angle = (float)Math.abs(Math.atan(verticalDistance / horizontalDistance) * 180 / Math.PI);

    if (Gdx.input.isTouched()) {
        degrees = angle;
    }
    System.out.println("Player (" + Gdx.input.getX() + ", " + Gdx.input.getY() + ")");
    System.out.println("Degrees: " + degrees + " Angle: " + angle);
    }

```

The black dots on the image represents touch points and this is what the invisible triangles would look like if I'm not imagining wrongly. Example image:

**UPDATED CODE**

```
    float verticalDistance = inputManager.touchPoint.y;
    float horizontalDistance = inputManager.touchPoint.x - x; // (x - textureRegion.getRegionWidth() / 2)
    float angle = (float)Math.toDegrees(Math.atan2(verticalDistance, horizontalDistance)) - 90;

    if (Gdx.input.isTouched()) {
            degrees = angle;

            if (degrees < 90)
                degrees = 89;
    }

```

I tried to do this but it doesn't work because then I get the arrow stuck at 89 degrees forever. Notice that this is not the arrow pointing straight up, it's the arrow pointing to the left.

I am aware why the code doesn't work but I don't know how to get it to work.

**UPDATED CODE FOR FUTURE READERS (ANSWER)**

```
private void inputFollowFinger() {
        float verticalDistance = inputManager.touchPoint.y;
        float horizontalDistance = inputManager.touchPoint.x - x;
        float angle = (float)Math.toDegrees(Math.atan2(verticalDistance, horizontalDistance)) - 90;

        if (Gdx.input.isTouched()) {
            degrees = angle;
            arrowStayAt90Degrees();
        }
    }

private void arrowStayAt90Degrees() {
    final int stayAtDeg = 90;
    final int adjustDeg = 180;
    if (degrees < -adjustDeg) {
        degrees = stayAtDeg;
    }
    else if (degrees < -stayAtDeg) {
        degrees = -stayAtDeg;
    }
}

```

# Answer
I had the same problem once. Here is how I approach it.

The left side shows how angles are represented in Java (or at least how I see them represented). The `Math.*` functions work like that and give results like that.

With that being said we just calculate the angle this way:

```
angle = atan2(dy, dx)

```

Where `dy` is the vertical distance and `dx` is the horizontal one. Using `atan2` is better, so that you won't get an error when `dx` is 0.

Now, we have to take into account that the arrow in its neutral state is already rotated by 90° as shown on the right side from the image above. So the actual angle should be (substracting 90°):

```
angle = atan2(dy, dx) - 90

```

**Java code:**

```
public void input() {
    float dy = inputManager.touchPoint.y;
    float dx = inputManager.touchPoint.x - x;

    float angle = (float) Math.toDegrees(Math.atan2(dy, dx)) - 90;

    if (Gdx.input.isTouched()) {
        degrees = angle;
    }
}

```

**Notes:**

* The horizontal distance `dx` should be `inputManager.touchPoint.x - x`. We dont care about the origin here, it is only needed in the rendering process.
* It's better to cache the values `textureRegion.getRegionWidth()` and `textureRegion.getRegionHeight()` as properties `width` and `height`, respectively. That will make the code much concise (thus readable) and reduce the overhead caused by `.`.
> 0 votes

---
Tags: java, libgdx
---


title: Follow Player which moves over a sphere

text:
# Question
Title: Follow Player which moves over a sphere
After hours of googling and pulling several hairs out, I decided to open this thread.

I want to make a game, in which the player walks around a sphere (like super Mario galaxy) and the camera should stay fixed over the player and point down on its head but I can't seem to get anywhere near of the right method. So, how can I realise this?

Thanks.

# Answer
> 2 votes
I think that is a fairly simple thing to do. Just get the vector between the sphere center and the player position, let's call it `v`. Normalize `v` and multiply it by the distance you want and then add the result back to `v`. `v` is now the distance from the center of the sphere to where the camera shoud be:

```
Vector3 v = playerTransform.position - sphereCenter;
v += v.normalized * distance;

cameraTransform.position = sphereCenter + v;
cameraTransform.LookAt(playerTransform, cameraTransform.up);

```

**Note:** `distance` should be a number. It represents the distance you wish to have between the player and the camera.

---
Tags: unity, camera, rotation
---


# Question
Title: Trying to draw lines using LineRenderer from tower to spawners
So I have a tower surrounded by 4 spawner gameobjects. I want to draw lines to all of them using `LineRenderer`. I wrote the following code to achieve this but for some reason I am getting `NullReferenceException: Object reference not set to an instance of an object` at the line `myLines[i].transform.position = startPos;`

```
public Transform towerPos;
GameObject[] myLines;

void DrawLines()
        {
            myLines = new GameObject[spawnpoints.Count];
            Vector3 startPos = towerPos.transform.position;
            for (int i = 0; i < spawnpoints.Count; i++)
            {

                myLines[i].transform.position = startPos;
                myLines[i].AddComponent<LineRenderer>();
                LineRenderer lr = myLines[i].GetComponent<LineRenderer>();
                lr.material = new Material(Shader.Find("Particles/Alpha Blended Premultiply"));
                lr.SetColors(Color.red, Color.red);
                lr.SetWidth(0.3f, 0.3f);
                lr.SetPosition(0, startPos);
                lr.SetPosition(1, spawnpoints[i].spawnPoint.transform.position);
                //GameObject.Destroy(myLine, duration);
            }
        }

```

The above function is called at Start(). The tower GameObject is dragged into the `towerPos` variable in the editor so dont know why its a null.

# Answer
In C#, `new SomeReferenceType[length]` doesn't create `length` number of objects of type `SomeReferenceType`. It creates an `Array` that *could* hold that many `SomeReferenceType` references, but *initially* contains **nothing**.

So, if you want to fill that array with actual objects, you need to assign them.

```
void DrawLines()
{
    myLines = new GameObject[spawnpoints.Count];
    Vector3 startPos = towerPos.transform.position;

    // Cache your material so you don't need to make so many copies.
    var material = new Material(Shader.Find("Particles/Alpha Blended Premultiply"));

    for (int i = 0; i < spawnpoints.Count; i++)
    {
        // FIRST: Create & assign your GameObject into the array slot.
        var lineObject = new GameObject("Line" + i);
        myLines[i] = lineObject;

        lineObject.transform.position = startPos;
        LineRenderer lr = lineObject.AddComponent<LineRenderer>();

        // No need to search for the component we just added!
        // LineRenderer lr = myLines[i].GetComponent<LineRenderer>();

        // Use sharedMaterial to be batching-friendly and avoid excess allocation.
        lr.sharedMaterial = material;

        lr.SetColors(Color.red, Color.red);
        lr.SetWidth(0.3f, 0.3f);
        lr.SetPosition(0, startPos);
        lr.SetPosition(1, spawnpoints[i].spawnPoint.transform.position);
    }
}

```
> 3 votes

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


# Question
Title: Libgdx Tiled | Using setTile results in a NullPointerException
So, I'm attempting to change the texture of a block when the player comes in contact with it by using `cell.setTile(tileSet.getTile(926)`. I've already looked at similar questions and I guess the layer in Tiled is coming up as null, but I have no clue how to fix it.

I'm sorry it's a long post.

Here's the World Creator

```
public class B2DWorldCreator {

public B2DWorldCreator(PlayScreen screen) {
    World world = screen.getWorld();
    TiledMap map = screen.getMap();

    BodyDef bdef = new BodyDef();
    FixtureDef fdef = new FixtureDef();
    PolygonShape shape = new PolygonShape();
    Body body;

    //create static bodies for every wall in the game
    for (RectangleMapObject object : map.getLayers().get(2).getObjects().getByType(RectangleMapObject.class)){
        new Wall(screen, object);

    }

}
}

```

Here's the Tile class

```
public class Tile {
protected World world;
protected TiledMap map;
protected Rectangle bounds;
protected Body body;
protected PlayScreen screen;
protected MapObject object;
protected Fixture fixture;

public Tile(PlayScreen screen, MapObject object) {
    this.screen = screen;
    this.map = screen.getMap();
    this.world = screen.getWorld();
    this.object = object;
    bounds = ((RectangleMapObject) object).getRectangle();

    BodyDef bdef = new BodyDef();
    FixtureDef fdef = new FixtureDef();
    PolygonShape shape = new PolygonShape();

    bdef.type = BodyDef.BodyType.StaticBody;
    bdef.position.set(bounds.getX() + bounds.getWidth() / 2, bounds.getY() + bounds.getHeight() / 2);

    shape.setAsBox(bounds.getWidth() / 2, bounds.getHeight() / 2);
    fdef.shape = shape;

    body = world.createBody(bdef);
    fixture = body.createFixture(fdef);
}

public void setCategoryFilter(short filterBit) {
    Filter filter = new Filter();
    filter.categoryBits = filterBit;
    fixture.setFilterData(filter);

}
}

```

Here's the wall class where I call the problematic line at 31.

```
public class Wall extends Tile {
private TiledMapTileSet tileSet;
private TiledMapTileLayer layer;
private TiledMapTileLayer.Cell cell;

public Wall(PlayScreen screen, MapObject object){
    super(screen, object);
    fixture.setUserData(this);
    setCategoryFilter(AdventureCompany.WALL_BIT);
    tileSet = map.getTileSets().getTileSet("PlaceHoldernoTree.tsx");

}

public void onContact(){
    cell = new TiledMapTileLayer.Cell();
    if(object.getProperties().containsKey("Door")){
        layer = (TiledMapTileLayer) map.getLayers().get(1);
        cell = layer.getCell((int) body.getPosition().x / 16, ((int) body.getPosition().y / 16));
        System.out.println(cell.getTile());
        cell.setTile(tileSet.getTile(926));
    }

}
}

```

My Contact Listener

```
public class WorldContactListener implements ContactListener {
private AssetManager manager;

public WorldContactListener(AssetManager manager) {
    this.manager = manager;
}

@Override
public void beginContact(Contact contact) {
    //these are what came in contact
    Fixture fixA = contact.getFixtureA();
    Fixture fixB = contact.getFixtureB();

    int cDef = fixA.getFilterData().categoryBits | fixB.getFilterData().categoryBits; // this will be used to activate specific collision results
    Gdx.app.log("Contact", "ya boi");
    switch(cDef) {
        case AdventureCompany.EXPLORER_BIT | AdventureCompany.WALL_BIT:
            if(fixA.getFilterData().categoryBits == AdventureCompany.WALL_BIT)
                ((Wall) fixA.getUserData()).onContact();
            else
                ((Wall) fixB.getUserData()).onContact();

            break;
    }

}

```

And finally, the Tmx file header

```
    <?xml version="1.0" encoding="UTF-8"?>
<map version="1.0" tiledversion="1.1.5" orientation="orthogonal" renderorder="right-down" width="64" height="64" tilewidth="16" tileheight="16" infinite="0" nextobjectid="135">
 <tileset firstgid="1" source="test6.tsx"/>
 <tileset firstgid="925" source="PlaceHoldernoTree.tsx"/>
 <layer name="Background" width="64" height="64">
  <data encoding="base64">

```

# Answer
After a lot of headache, I figured out that my problem was that in my Wall class when I did `tileSet = map.getTileSets().getTileSet("PlaceHoldernoTree.tsx");` the file type was unnecessary and only needed the file name `"PlaceHoldernoTree"`.
> 1 votes

---
Tags: java, libgdx, tilemap, tiled
---


title: JFrame pack() method

text:
# Question
Title: JFrame pack() method
I was developing a game using java AWT and I realized that the position of pack() method can influence rendering. For instance:

**Frame Class**

```
public class Frame {
    public Frame(int width, int height, Game game) {
        JFrame frame = new JFrame("Practice Game");

        frame.setPreferredSize(new Dimension(width, height));
        frame.setMaximumSize(new Dimension(width, height));
        frame.setMinimumSize(new Dimension(width, height));

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        frame.pack();  // pack method is used before adding game component to frame
        frame.add(game);
    }
}

```

**Game Class**

```
public class Game extends Canvas implements Runnable {
    // Dimension
    public static final int WIDTH = 320;
    public static final int HEIGHT = 320;

    public Game() {
        new Frame(WIDTH, HEIGHT, this);

        menu = new Menu(WIDTH, HEIGHT);

        start();
    }

    public void render() {
        BufferStrategy bs = this.getBufferStrategy();

        if (bs == null) {
            this.createBufferStrategy(3);
            return;
        }

        Graphics2D g = (Graphics2D) bs.getDrawGraphics();

        menu.render(g);

        g.dispose();
        bs.show();
    }

    public static void main(String[] args) {
        new Game();
    }

```

This set of code results in making an empty frame without any component displayed.

However, when I tried putting pack method after I added game component to the JFrame, it successfully displayed what I intended to display.

I heard that pack() method is used to pack the components within the JFrame based on the component’s preferred sizes. However, I don't understand how the position of pack() method could influence the entire rendering (only displaying an empty frame).

---

Also, the actual size of frame doesn't match the dimension that I assigned to the frame. To illustrate this:

**Menu Class**

```
public class Menu {
    public Menu(int width, int height) {
        this.width = width;
        this.height = height;

        squareSize = 64;

        squareRowNum = height / squareSize;
        squareColNum = width / squareSize;
    }

    public void render(Graphics2D g) {
        drawBackground(g);
    }

    public void drawBackground(Graphics2D g) {
        for (int i = 0; i < squareRowNum; i++) {
            for (int j = 0; j < squareColNum; j++) {
                g.setColor(Color.black);
                g.setStroke(new BasicStroke(3));
                g.drawRect(j * squareSize, i * squareSize, squareSize, squareSize);
                g.setColor(Color.white);
                g.fillRect(j * squareSize, i * squareSize, squareSize, squareSize);
            }
        }
    }

```

When running these 3 classes together, it display:

The rectangle box at the bottom are cut off instead of fully displaying 5 * 5 rectangles (each rectangles has dimension of 64, 64 and the frame size is supposedly 320, 320). I assumed that it's because I'm using mac. I think this can also be fixed using pack() method but I don't know how.

# Answer
> 1 votes
You must be careful with setting the size... if you set the size from the JFrame you override the ability of `pack()`.

You should ONLY set the size of the content, not of the JFrame itself. this pic shows you the difference between content size and JFrame size:

---
Tags: java, rendering, graphics, jframe
---


# Question
Title: Given a point on a 2D grid of discrete points, and a normalized direction vector, how to I find the next point in that direction?
Say you have a point on a grid, lets call it P and your have a direction vector called V, how do i find the closest point from P in V's direction ?

Example:

1|2|3
4|P|5
6|7|8

V = (0.5 , 0.5)

In this basic example the next point is 3. How do I make a general algoritm for more complex cases, say V = ( 0.44, -0.56) ?

EDIT: Just to clarify something in my question. The next point has to be a neighbor to point P.

# Answer
The angle of the vector `V` can be calculated as `atan(V.y/V.x)`, and since the angle from one point on the grid to the 8 neighbors is known you can compare the angle of `V` with the angle to each neighbor and take the smallest delta.

The starting point `P` is irrelevant in determining the closest neighbor as that only depends on the direction of `V` (and when found, offset by `P`).

For convenience I've re-numbered your cells so that instead of

```
1 2 3
4   5
6 7 8

```

mine are numbered

```
3 2 1
4   0
5 6 7

```

But that's just because it's more convenient to calculate a lookup-table for the angles to the neighbors.

A naive implementation might look something like this;

```
import static java.lang.Math.abs;
import static java.lang.Math.cos;
import static java.lang.Math.sin;
import static java.lang.Math.atan;
import static java.lang.Math.PI;

public class Program {

    // Class to represent a grid point
    public static class Point {
        public final int x, y;
        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }

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

    private final static double TAU = PI * 2;
    private final static double[] angles = new double[8 + 1];

    // build up a lookup-table to the angle of the neighbors
    // this is calculated as PI * 2 / index of the neigbor in a counter-clockwise rotation
    // which is convenient because that is what cos, sin and atan expects
    // the last index is duplicated so that 0 degrees and 360 degrees are both accounted for.
    static {
        final double step = TAU / (double)(angles.length - 1);
        for(int i=0; i< angles.length; ++i)
            angles[i] = step * (double)i;
    }

    private static double getAngle(double dx, double dy) {
        if (dx == 0 && dy == 0)
            throw new RuntimeException("No direction!");

        if (dx == 0) {
            return dy < 0 ? PI * 0.5 : PI * 1.5;
        }

        if (dy == 0) {
            return dx < 0 ? PI : 0;
        }

        return atan(dy / dx);
    }

    private static int getGridIndex(double angle) {

        int bestIndex = -1;
        double bestDelta = Double.MAX_VALUE;
        for(int i = 0; i < angles.length; ++i) {
            double delta = abs(angle - angles[i]);
            if (delta < bestDelta) {
                bestDelta = delta;
                bestIndex = i;
            }
        }

        return bestIndex;
    }

    private static Point getGridPoint(Point input, double dx, double dy) {
        int index = getGridIndex(getAngle(dx, dy));
        switch(index) {
            case 0:
            case 8: return new Point(input.x + 1, input.y + 0);
            case 1: return new Point(input.x + 1, input.y + 1);
            case 2: return new Point(input.x + 0, input.y + 1);
            case 3: return new Point(input.x - 1, input.y + 1);
            case 4: return new Point(input.x - 1, input.y + 0);
            case 5: return new Point(input.x - 1, input.y - 1);
            case 6: return new Point(input.x + 0, input.y - 1);
            case 7: return new Point(input.x + 1, input.y - 1);
            default:
                throw new RuntimeException("Impossible!");
        }
    }

    public static void main(String[] args) {
        Point p = new Point(0, 0);
        for(double a = 0; a <= TAU; a += TAU / 8.0)
        {
            double dx = cos(a);
            double dy = sin(a);
            System.out.println("Vector: " + dx + ", " + dy);
            System.out.println("Angle : " + getAngle(dx, dy));

            System.out.println("Next point : " + getGridPoint(p, dx, dy));
        }
    }
}

```
> 2 votes

# Answer
Note 1: You're better off not normalizing your direction vector, since normalizing may result in rounding errors. However, assuming no precision issues, take your vector's slope (y / x), and simplify to the simplest fraction with integral numerator and denominator: (y'/x'). Now you can take a new V vector (x', y') . Here are your two examples:

1. **Example 1**: Start = (1, 1), V = (0.5, 0.5). slope as a fraction = ((1/2) / (1/2)) = (1 / 1), end = (1, 1) + (1, 1) = (2, 2)
2. **Example 2**: Start = (-10, 0), V = (0.44, -0.56). Slope as a fraction = (-0.56 / 0.44) = - ((56 / 100) / (44 / 100) = (56 / 44) = (14 / 11). An equivalent V with slope (-14/11) is (11, -14). Our ending point is at (-10, 0) + (11, -14) = (1, -14).

---

If you *are* worried about precision issues causing you to nearly-miss the grid point, you can consider using a rational approximation algorithm, such as by using a truncated continued fraction. For example, if we were looking for a point with `V = (1, 3.14159)`, instead of using `V = (314159 / 1000000)`, we could take one of the continued fraction expansions of 3.14159:

```
V = 3 / 1 = 3.0
V = 22 / 7 = 3.142857...
V = 333 / 106 = 3.1415094...
V = 355 / 113 = 3.1415929...

```
> 1 votes

---
Tags: 2d, vector, grid
---


# Question
Title: SteamVR locks position of dynamically created cameras
I'm having trouble tracking down a problem with SteamVR. Here is a quick way to set up an MWE:

* Create a new Unity project.
* Import the SteamVR package from the Asset Store.
* Create the following script:

```
using UnityEngine;

public class CameraCreator : MonoBehaviour {
    private GameObject cameraObject;

    private void Start ()
    {
        cameraObject = new GameObject("CameraObject");
        cameraObject.AddComponent<Camera>();
        cameraObject.transform.position = Vector3.one;
    }
}

```
* Create an empty game object and add this script to it.

SteamVR seems to lock this object's position (and that of any other game object with a dynamically created camera component) to the origin. No matter what I try to do to change it (inspector; set it inside update; set it in a coroutine), it always ends up back at the origin at some point during the frame (I believe somewhere between `LateUpdate` and `OnRenderObject`, but I'm not entirely sure). Without data breakpoints I find this really hard to track down.

This behaviour isn't really a problem for my actual project, but I need to be able to create cameras and modify their positions in my unit tests, where I'm having the same issue.

Does anyone know what's causing this, or have any advice on how to track down the cause?

# Answer
> 2 votes
As it turns out, SteamVR does start tracking all cameras automatically by default. The relevant property on the `Camera` object is `stereoTargetEye`, or "Target Eye" in the Inspector. So if you want to create a camera dynamically which isn't being tracked by SteamVR, you'll have to do:

```
var camera = cameraObject.AddComponent<Camera>();
camera.stereoTargetEye = StereoTargetEyeMask.None;

```

Likewise, you need to change this property in the Inspector for all cameras which are added to the scene via the editor, if you don't want them to be tracked.

I am a little surprised that `None` isn't the default value of this property.

---
Tags: unity, camera, steam-vr
---


# Question
Title: How to prevent (most) cheating (server-side) in my JavaScript, Node JS, socket.io MORPG?
I'm working on a fairly simple JavaScript + Node JS + socket.io (M)MORPG where multiple people play in the same world. This is actually working, but cheating is insanely easy at the moment.

My goal is not to stop people from cheating client-side, I know this is impossible.
My goal is to have the server know when someone is cheating and do something about it.
What I really want to know is how well a Node JS server would be able to handle the constant anti-cheat checking.

People can just adjust the client-side JS code and the server currently doesn't do too much checking.

So a player could just change his X & Y coordinate and teleport around the map at will.

It would be fairly simple to implement basic checks that don't allow crazy cheats.
But I'd like a real way to prevent this.

One possibility is to keep track of all player data on the server and make sure nothing weird is happening client-side by constantly comparing the data the server has.
My issue with this is that I have a lot of collision checking and my world will become rather big.
I'm not sure how good of an idea it is to do all of this collision checking server side as well. Sure it would work for one or two players, but what about 10? 50? 200?
Especially with all of these players bouncing off walls, shooting bullets, hitting monsters, getting hit by monsters, colliding with monsters, ...

As far as I know, the only way to actually prevent cheating is by making the server check all movement and wall/bullet/monster collisions.

Are there any other options? Like using an anti-cheat engine of some sort? I know games like MapleStory have that, but I have no idea how they work or how affordable that would be?

Or will doing all the collision checks server side be fine?
At some point, like around 50-100 players, I could set up a second server instance to limit the amount of players on each server.
Ofcourse I would also only check collisions near the player, so not map-wide for each player.

Any help/advice on this is appreciated.

Here's a link to my game that will make my questions less abstract.
It's far from finished and the world is still very small, but it should give a good idea of what I'm asking:

http://185.115.218.199:3000/

# Answer
There is just one way to prevent cheating: **Handle all your game mechanics on the server**.

Anthing else is snake-oil.

That applies even more to web-based games where every player can access all kinds of powerful cheating tools just by pressing `F12`.

Anti Cheat Tools (ACTs) work by infiltrating the players operating system and doing all kinds of low-level system checks to find processes, files and memory patterns which might indicate that the player is trying to cheat. This requires an actual program on the user's computer which they need to install (usually they install it together with the normal game client). In a web-based game, this is not an option. The point of web-based games is that the player does *not* need to download and install any additional software.

And besides, ACTs are software, too. They can be hacked just like the game client can be hacked. The companies which make them usually try to make that difficult by using lots of obfuscation methods to make their ACTs harder to reverse-engineer. But that just makes it less convenient to hack their tool, not impossible.

Whether "doing all the collision checks server side is fine" in regards to performance depends on how you implement collision checks. There are all kinds of optimizations you can use to handle collisions of 200 objects in real-time. But this is a very broad topic. The best optimizations are always specific to the game. If you need help with this, please open a new question where you add more details about what kind of collisions you need to detect, how your bounding volumes tend to be distributed, how many of them move and how often, etc., etc..
> 5 votes

---
Tags: javascript, node.js, anti-cheat
---


# Question
Title: Why the canvas position is affected by screen resolution in Unity?
I meet an issue that if I use 1024x768 resolution to run my game, the position(not local position) of the canvas is -1 in z axis. On the other hand, with resolution of 1136x640, the position is -5 in z axis(I never use code or anything to change its position). Is there any reason to cause this issue?

# Answer
you can set the canvas scaler to a constant pixel or physical size rather than scale with screen size. Set the panel to stretch and then you can set the pixels from each edge and it will fix your issue.
> 1 votes

---
Tags: unity
---


# Question
Title: How to: Duplicating and updating component data in systems
I am new to game development. Coming across the ECS (entity-component system) pattern I generally quite liked the idea. I have implemented the current version of my engine using the OOP style approach. In other words, Components are objects that have both state and behaviour and methods that can be polymorphic. My entity manager also means that when a `SpriteRenderComponent` has been added to an entity, `entity.GetComponent<RenderComponent>()` will return a reference to the SpriteRenderComponent. Of course, the problem with this is that components have to communicate with each other. E.g. the draw method will access the `TransformComponent`'s transform data.

Now I have dug a bit deeper and found that most sources recommend the pure ECS approach where the entities are an id or a list of components, components are just structs with public data and the systems are where all the magic happens ie where all the functions are. Of course, components don't depend on each other and the same is ideally true for systems as well.

So now when I want to draw a sprite I create a `SpriteRenderSystem` which *knows* how to draw a sprite. The problem is that drawing concerns all kinds of drawable things e.g. to sort them depending on a zOrder and layer. This is what lead me to the idea of nodes as **objects** that are local to the system. So now the `SpriteRenderSystem` would add a 'SpriteRenderNode' to the `RenderManager`. The `SpriteRenderNode` could inherit from an abstract `RenderNode` and implement the virtual draw method. The `SpriteComponent` would only hold the data specific to the sprite such as colour. The vertex array and all the other stuff that is purely related to rendering is kept encapsulated in the derived `RenderNodes`.

## Problem #1

In order to be drawn by the `RenderManager`, the `SpriteRenderNode` would need to know and therefore store its transform data. The only way to keep this data up to date would be to copy the entity's transform component's transform data to the `SpriteRenderNode` every frame. I am not so much concerned about performance here but about the practice of duplicating the data in the systems. It feels like this is a violation of general good programming practices though I can't see any immediate reasons why it may prove harmful.

## Problem #2

Taking the data out of the components.

From what I understand, the data should live in the components. However, taking the above-presented idea a step further, there may be cases where storing data in components isn't necessary at all. Such an example may be an animation system which may simply store and update animation nodes for each entity and then change their components such as texture, position... The problem with this is that it would take away the ability to save the game by simply serialising all the components.

As you see I am quite confused about how a good pure ECS should look like. Any help would be much appreciated.

# Answer
> 1 votes
First of all, there is no such thing as a good pure ECS. Every ECS system is different, and all of them have their own advantages and disadvantages.

# Problem #1

I'd go with the following setup. `SpriteRenderSystem` would have access to an array of `SpriteComponents` and `TransformComponents`. Internally, it would also have an array of `SpriteRenderNodes` with one to one mapping to `SpriteComponents`.

`SpriteComponent` would be a pure data structure, holding sprite's state information, such as sprite size, color, etc. Serializing all `SpriteComponents` should be enough to restore the state of all the sprites in the game.

Internal `SpriteRenderNode` would be another pure data structure, that would keep cached data required to do the actual rendering of sprites. It could hold things like transformation matrices, vertices and so on.

In update cycle `SpriteRenderSystem` would iterate over `SpriteComponents`. For each `SpriteComponent` it would take the data from it, then take the data from respective `TransformComponent`, combine it, and using combined info update `SpriteRenderNode`. After that, `SpriteRenderSystem` can sort `SpriteRenderNodes` by layers, maybe do some other processing, and finally loop over all of them and submit it to some graphics API (Your own abstraction, or directly to DirectX, OpenGL, etc). (Also note that after all `SpriteRenderNodes` are set up, you can do the further processing on another thread, and since all `SpriteRenderNode` data is internal to the system, it can do all sorts of optimizations, like have separate `SpriteRenderNodes` arrays for each layer, etc).

# Problem #2

Basically I've answered this question with the above example. So in general, it helps to view your whole game in the ECS like this:

Game state:

* System list
* Entity list
* Component list
* Maybe some sort of per system configuration

Cached state:

* Internal state in systems.

Serializing all data in the game state, should be enough to restore the game later. So each time you're dealing with new data, you just ask a question: can you recreate the game without this data? If the answer is no - it goes to a component; if the answer is yes - it goes to internal system state.

So for animations example, you might want to have `AnimationComponent` that would contain basic state for the animation, like which animation is playing, what frame it's at, etc. For something like skinned mesh animations `AnimationSystem` internally could have a respective `AnimationComponentNode`. On update, `AnimationSystem` would update each `AnimationComponent` and generate bone transforms into `AnimationComponentNodes`. Or if you're animating sprites, then `AnimationSystem` can just update `SpriteComponent`.

# Answer
> 0 votes
The differentiation you make whether logic should be in system or in a component sounds like you want to have an elegant system, where a single architecture can handle all problems. For me having systems is just pure necessity, because it is too slow to draw each sprite individually and you have to do stuff like sorting to get the desired result. But this is not true for all components. Game logic or scripts are just other components that do not need this optimization.

## Problem #1

Each component should have a reference to the component it belongs to.

The transform system can then just loop over all nodes and make the update, the sprite renderer can also get the transform component very easily.

e.g. (in C#)

```
foreach (var sprite in sprites)
{
   var worldMatrix = sprite.Entity.Get<TransformComponent>()?.World ?? Matrix.Identity;

   Render(sprite, worldMatrix);
}

```

BTW: Some engines make the transform component required for all entities.

# Problem #2

Depending on your serialization system you can annotate the data/properties/fields you want to persist.

---
Tags: software-engineering, component-based, entity-component, polymorphism
---


title: Dynamic object creation from data

text:
# Question
Title: Dynamic object creation from data
I want to write somewhat randomized object activation effects, like when you step on a trap, you can be tepelorted, damaged, cursed and so on. I applied strategy pattern for this: damage/healing managed by class ChangeHealth, teleportation by class SetPosition etc.

I want to know how can I manage creation of objects in code from data, so, for example I want to be able to set that there will be trap which will damage player and there will be shrine which should teleport you upon activation from, for example, string or bit stream.

I'm working in C#, but interested in overall approach to this problem.

# Answer
> 1 votes
Fundamentally you're looking at creating a mapping from some piece of data (the "key") to some instance of your effect classes (`ChangeHealth`, `SetPosition`, et cetera). A straightforward way to accomplish this is to use

* some kind of delegate (`Func<...>` in C#, for example) to manage the generic creation of effect instances and
* some kind of associative array (`Dictionary<K, V>` in C#) to map from effect to delegate.

To do this you'd decide on a data representation for your traps. For simplicity's sake, I'll suggest you start with something text-based because it's easy to author, consume, and reason about. More complex ("binary") formats for your data may be an option you want to look at in the future, but aren't directly relevant to the mechanics of the technique I'm suggesting.

So, let's say each trap type is just a simple text file with a list of the effects it will apply, one per line. The effect name (a string like `"teleport"` or `"poison"` for example) becomes your dictionary's *key*.

Your dictionary's value is a `Func<T>`. `T` is the base class or interface shared by all your effect strategy classes. So your dictionary might look like:

```
Dictionary<string, Func<IEffect>> m_effectCreators;

```

When you define new effects in code, you can register them with this dictionary, supplying a delegate that creates a new instance of the appropriate effect:

```
m_effectCreators.Add("teleport", () => new SetPosition());
m_effectCreators.Add("poison", () => new ChangeHealth(-100));
m_effectCreators.Add("heal", () => new ChangeHealth(100));

```

Then, when you parse the trap, you read the trap's effect strings and, for each one, look it up in the dictionary to invoke the function to create the appropriate effect instance.

```
foreach(var effectName in trapData) {
  var creator = m_effectCreators[effectName];
  var effect = creator();
  actualTrap.AddEffect(effect); // ...or however you store the instances.
}

```

Hopefully you can see how you could even extend this to allow the trap text data to supply parameters. For example, instead of hard-coding the damage of a heal or poison trap as I did above, you could write "heal(30)" and have your code parse the "parameters" between the `(` and `)` and supply them so that the delegate can in turn pass them to the constructors of the effects.

---
Tags: c#, architecture, code-reflection
---


# Question
Title: Bringing over OpenGL code to unreal engine?
So I've been developing games and apps in C++/OpenGL for a while, and am thinking of starting to use Unreal Engine for many things.

I've built up quite the huge libarry for UI / rendering related code, but they rely on OpenGL for rendering. Will I have no choice but to reimplement these / use unreal engine's, or is there some way to integrate them together?

# Answer
> 1 votes
Integrating your OpenGL-based code is *technically possible*, but likely a bit impractical. It's hard to say for sure without seeing your code (especially since a long time has passed since you asked this question), but...

Unreal has several layers of abstraction between you the user and the underlying graphics API. You can go down into the guts of the engine and implement your OpenGL calls in there, but to get that code to execute you'll need to plumb through an interface all the way up to the user-facing bits of the engine. That's probably a bunch of work.

Similarly you could try to extract only the non-OpenGL bits of your code and lay them on top of UE's existing RHI abstraction. But you'll still have to contend with your existing code not fitting the Unreal object model or memory management techniques, and need to adjust it accordingly. Which is probably a bunch of work.

Between the two options, the second is probably easier: adapting your high-level logic to Unreal's worldview. But unless your circumstances are pretty extreme, I'd be willing to be your best option is to just use Unreal's UI and rendering solutions for everything rather than try to graft your stuff on there.

Cherry-pick only the highest-level logic or game-specific stuff from your own code, or anything Unreal can't actually do directly, and otherwise use the tools it provides you.

---
Tags: opengl, unreal-4
---


# Question
Title: How to handle multiple enemies with the same script?
i'm working on a basic Top-Down Shooter, kind of like... Nuclear Throne or The Binding of Isaac, but since i'm new to Unity, and it's something i'm required to do for school, i'm quite in a rush so i didn't have enought time to look at all the documentation i should've, so i apologize if i'm asking too much.

The thing is like this : I have the Player that moves around, and a Sword that rotates in the mouse direction, clicking the mouse activates a Trigger Collider around the Sword, and it's suposed to Hit all enemies inside its range

The problem :

How should i "plan" my Scripts? i mean, i have a Sword script that handles the click and the OnTriggerEnter, and it should, somehow (Working on it), check if it hit an enemy, and access the Enemy Script to modify its Life Points, but how do handle the `GameObject Enemy = GameObject.FindObjectWithTag("Enemy")[...]`? since this just gives me one enemy...

I apologize again since i'm really bad at focusing on one point, i dont think it's neccessary to provide all the code since i dont really need you to provide me with code, just... guidelines or a basic pattern of doing this kind of things.

Thank you a lot!.

# Answer
The start of your reasoning is good, but you get lost when trying to reduce the enemy HP. Let's restart from the Sword:

In your Sword script, you have a function OnTriggerEnter2D. In this function, you can check if the collider is of type "Enemy", and, if so, apply the "damage" function:

```
void OnTriggerEnter2D(Collider2D collider)
{
    GameObject objectCollided = collider.gameObject;  // Get a reference to the object hit
    if (objectCollided.CompareTag("Enemy")) // If the object is an enemy
    {
        objectCollided.getComponent<EnemyController>().doDamage(swordStrength); // Here you call the enemy function that will lower his health
    }
}

```

A more advanced solution would be to generalize this behavior for any objects that are damageable. Let's imagine that, in the future, you want to add destructible items, like a destructible wall. This wall would have HP, get damaged, and die when its HP gets to 0, just like an Enemy.

This is achievable via a script component "Damageable" that you will add to any prefabs you have that are damageable:

```
public class Damageable : MonoBehavior
{
    public int maxHP;       // This has to be set in the inspector
    private int currentHP;

    void Start()
    {
        currentHP = maxHP;
    }

    void doDamage(int damage)
    {
        currentHP -= damage;
        if (currentHP <= 0)
            Destroy(gameObject);
    }
}

```

By attaching this script to a prefab, it becomes damageable. Then, in your Sword script:

```
void OnTriggerEnter2D(Collider2D collider)
{
    GameObject objectCollided = collider.gameObject;  // Get a reference to the object hit
    Damageable damageableComponent = objectCollided.getComponent<Damageable>();

    if (damageableComponent) // If the object is damageable
    {
        damageableComponent.doDamage(swordStrength); // Here you damage the object, without knowing which type it is
    }
}

```

I hope this helps.
> 6 votes

# Answer
Enemy script

```
void HandleHits(Collision2D col) {

  if(col.gameObject.tag == "beam") {
    Destroy(col.gameObject);
  }

  if(col.gameObject.tag == "beam") {
    timesHit += 1;
    GameObject smokePuff = Instantiate (
      bulletHitParticle,
      transform.position,
      Quaternion.identity) as GameObject;
  }

  if (Ball.PowerBallActive && col.gameObject.tag !="Extra Ball" ) {
    timesHit+=50 ;
  }

  timesHit++;
  int maxHit = hitsSprites.Length + 1;
  if(timesHit >= maxHit) {
    if(isBreakable) {
      brickCount --;
    }

    levelmanager.BrickDestroyed();
    PuffSmoke();
    GameObject newCoin = Instantiate(
      coin,
      transform.position,
      Quaternion.identity) as GameObject;
    Destroy(gameObject);
    Camera.main.GetComponent<CameraShaker>().VibrateForTime(.3f);
  }
}

```
> 0 votes

---
Tags: unity, c#, 2d
---


title: JSON Parse (Invalid Value)

text:
# Question
Title: JSON Parse (Invalid Value)
My settings.json (generated with JsonUtility.ToJson):

```
{
    "masterVolume": 0.10000000149011612,
    "fullScreenMode": 1,
    "cheatsEnabled": false
}

```

Offending line:

```
SettingsData sd = JsonUtility.FromJson<SettingsData>(Application.dataPath + "/Settings/settings.json");

```

My SettingsData-class.

```
[System.Serializable]
public class SettingsData
{
    [SerializeField]public float masterVolume;
    [SerializeField]public int fullScreenMode;
    [SerializeField]public bool cheatsEnabled;

    public SettingsData(float masterVolume, FullScreenMode fullScreenMode, bool cheatsEnabled)
    {
        this.masterVolume = masterVolume;
        this.fullScreenMode = (int)fullScreenMode;
        this.cheatsEnabled = cheatsEnabled;
    }
}

```

I really can't fathom why it's having trouble reading this back in, I even tried to save the enum as an int instead, but still no luck.

# Answer
> 1 votes
I tried to read the filepath as the actual json file, here's the solution:

```
string json = File.ReadAllText(Application.dataPath + "/Settings/settings.json");
SettingsData sd = JsonUtility.FromJson<SettingsData>(json);

```

---
Tags: unity, json
---


# Question
Title: how to put elements around circle with equal distance?
I know circle formula and know how to draw it. but I want put 4 points on it with equal distance from each other. how can I do that?

I work with unity.

# Answer
It sounds like you want to make a regular polygon. It also sounds like you're talking about 2D space, but just for fun, here's a way to do that for any number of points and any arbitrary circle in 3D space:

```
public Vector3[] circlePoints (int n, float radius, Vector3 center, Vector3 normal) {
    var points = new Vector3[n];

    Vector3 offset = Vector3.ProjectOnPlane(Vector3.right, normal).normalized * radius;
    float angle = 0;

    for (int i = 0; i < n; i++) {
        Vector3 rotatedOffset = Quaternion.AngleAxis(angle, normal) * offset;
        points[i] = center + rotatedOffset;

        angle += 360f / n;
    }

    return points;
}

```

Set `normal` so that it's perpendicular to the circle you want to draw on. So if your game is 2D, use `Vector3.forward`, since that's perpendicular to the XY plane.

However, for a 2D game or one where every circle is on the same (axis-aligned) plane, I would just go with a trigonometric solution.
> 2 votes

---
Tags: unity, mathematics, unityscript
---