# Question
Title: Playing one song after another results in horrible grinding noise; how can I fix this?
I'm currently working on a game using slick2d java framework and I want to set it up so that the intro to a piece of music will play once, then the main body of the piece loops infinitely. I've got:

```
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException{
    BossInt = new Music("OST/bossintronly.wav");
    Boss1 = new Music("OST/bossloop.wav");
    Boss1.setVolume(0.5f);
    BossInt.setVolume(0.5f);

    BossInt.play();
}

```

then in my update method

```
if (BossInt.playing() == false) {
        Boss1.loop();
}

```

It ends up playing through the intro once as intended, but then instead of looping the main body as I'd hoped it just blasts a horrible grinding noise. It's definitely not a problem with the wav file, I've checked and replaced that multiple times.

Can anyone help me out?

# Answer
> 2 votes
This is caused by the fact that you start the sound loop every time you call the `update` method.

To fix this, also check if the boss loop sound is currently playing and start it only if it is not:

```
if (BossInt.playing() == false && Boss1.playing() == false) {
    Boss1.loop();
}

```

---
Tags: java, slick, music
---


# Question
Title: Using InputListener touchDown - Unable to jump while pressing direction button
Using `InputListener` attached to images for touchscreen control I initially had the problem of the player being able to *continuously* jump and fix themselves to the top of the screen by simply holding the jump button.

This was resolved by adding a `gdx.input.justTouched()` check before calling the `jump()` method. However, this annoyingly then introduced a new issue of not being able to jump whilst holding a direction button. The direction button first has to be released before the jump will function.

```
if (player.presentState != Player.State.DEAD && player.presentState != Player.State.WIN) {
            if (controller.isRightPressed() && player.body.getLinearVelocity().x <= 1.75)
                player.body.applyLinearImpulse(new Vector2(0.1f, 0), player.body.getWorldCenter(), true);
            if (controller.isLeftPressed() && player.body.getLinearVelocity().x >= -1.75)
                player.body.applyLinearImpulse(new Vector2(-0.1f, 0), player.body.getWorldCenter(), true);
            if (controller.isUpPressed() && controller.isJumpPressed() && player.presentState != Player.State.FALLING)
                if (Gdx.input.justTouched()){
                    player.superJump();
                }
            if (controller.isDownPressed()){
                player.dive();
            }
            if (controller.isJumpPressed() && player.presentState != Player.State.JUMPING){
                if (Gdx.input.justTouched()) {
                    player.jump();
                }

```

The `jump()` method operates under two different state conditions.

If the player is `state.ground` or `state.running`, a positive y-impulse is applied.

If the player is `state.falling` a slight positive y-impulse is applied with `linearDampening` allowing the player to control the descent as to float/glide down.

This all works perfectly via my keyboard input implementation but not in my touchscreen one.

How to resolve this?

# Answer
> 1 votes
You're probably aware, but justTouched() isn't working for you on mobile because another finger is already touching the screen when jump is pressed, causing it to evaluate to false.

I'd look into using touchDown(x, y, pointer, button) from InputProcessor. It is called once per new touch, not just for the first. Add an if statement to it that checks if x&y are on your jump button along with player.presentState != Player.State.JUMPING, then execute player.jump() if both hold true!

---
Tags: libgdx, input
---


# Question
Title: Problem with Material Parameter Collection Reference Variable in Set Scalar Parameter funcion
I was following a tutorial on using GameInstance. Where the guy in the video would teach how to choose the color of the ship by clicking a button on a level (x), so as to affect the ship on another level (y).

**LINK OF VIDEO (in portuguese):**

https://www.youtube.com/watch?v=kTiCjPHMJXI&list=PLnwVxZ2WVVpl1sOPaEzK--4fXzq2ZQvE-&index=42

**LEVEL X:**

**CODE OF BLUEPRINT MENU OF LEVEL X (when buttons are clicked):**

*This code is associated with an enumeration with these three colors (red, green and blue).*

**My problem appears when I set the target in the function (Set Scalar Parameter Value), it only appears these options for me:**

**Much like the problem this person had:**

https://forums.unrealengine.com/development-discussion/blueprint-visual-scripting/90544-material-parameter-collection-reference-variable

**In the video it can give a "get" in the variable, which later (apparently) I discovered to be a reference to the object:**

**I made the "discovery" based on the sign (blue circle):**

I did tests with the "blue circles" type variables, but the ones I did did not work.

https://answers.unrealengine.com/questions/169593/how-to-properly-set-vector-parameter-value.html

I would like to know what I have to do so that the referral is done correctly.

Another link that I researched, but that did not help me much.

---

**EDIT 1 (attempt based on Stephen's answer)**

\**I created a material instance and put it right after the Event Begin Play (I found 2 options, so I did the test with both).

**Available Options:**

**Blueprint:**

I defined them as editable, just as I was instructed.

**But even so, I could not:**

*I could not connect the nodes. Warning "**Material Intance Dynamic Object Reference is not compatible with Material Parameter Collection Object Reference**" is displayed.*

# Answer
> 0 votes
**Exactly at 5:37 minute of that video (same person as the first tutorial) I was able to figure out how to solve my problem:**

https://www.youtube.com/watch?v=0CPFt\_vEqfk&list=PLnwVxZ2WVVpl1sOPaEzK--4fXzq2ZQvE-&index=49

I realized that to call the function he first called the variable (get variable):

But no use, if I do not know the correct type of variable (as you can see in the image above, circled in pink).

**Only write Material Instance when defining the variable type:**

Of the 7 options I tested option 4 and option 7. The correct one is option 7 (circled in pink in the image above).

**To deduce that this option was correct, I had to see the 5:40 moment of the video (https://www.youtube.com/watch?v=0CPFt\_vEqfk&list=PLnwVxZ2WVVpl1sOPaEzK--4fXzq2ZQvE-&index=49):**

**Step by step:**

---

**Important addition.**

For the color to be set correctly, you need to set this variable first.

**Just add this code to the Contruction Script:**

# Answer
> 0 votes
(Apologies, I'm at work so can't provide pictures, hope my descriptions are good enough but I'll try to edit later)

The reference you are referring to isn't just a random reference, you have to tell the editor what you're trying to change the material instance of. In my experience, this would be a static mesh of some sort.

At Begin Play in your ship blueprint, you need to create that Material Instance. From the Return Value of this, right click and choose Promote to Variable. Name it and make it editable.

In the blueprint which is choosing the colour, at Begin Play, get player character (or pawn), pull the right pin and choose CastTo\[YourPlayerBlueprint\] then from the result of this, promote it to a variable as well. You can do this when choosing the colour as well but casting is expensive so it's always worth doing it as few times as possible.

Now when you want to change the colour, drag your character / pawn reference into the blueprint, pull off the pin and choose the material instance reference you made and it's this you plug in to the Target pin.

---
Tags: vector, unreal-4, color, blueprints
---


# Question
Title: How can I launch Visual Studio via a double-click on a C# script in Unity?
This is my first time using Unity and I am following the tutorial for the 2D RogueLike Game. Everythings seems to be working properly, apart that I cant get Visual Studio to launch, if I'm double click my c# scripts.

What I have tried so far:

* Checked my preferences, that External Script Editor says "Visual Studio 2017"
* Reinstalled Unity and Visual Studio.

Unity Version: 2019.3.0a2 Personal

Hope somebody can help me.

Additional information:

* After double click, nothing seems to be happening, even my mouse doesnt show a load icon
* When I create a new project, the bug (dont know if bug, or my fault) is still there.
* I can open the .sln file from my project in Visual Studio. Visual Studio can even autocomplete unity based code then, before it was a "miscellaneous file" and didnt autocomplete code like for example "Transform" or "Rigidbody2D".

# Answer
> 1 votes
Open the Package Manager (Window -\> Package Manager) and scroll down to Visual Studio Editor. In the lower right corner of the window there should be a button that says something like "Update to 1.0.11". Click that button.

Just to be on the safe side, do the same for Visual Studio Code Editor.

That resolved the issue for me. For some reason, having an outdated package causes Unity to just do nothing. No errors, warnings, or anything. But as soon as I updated I was able to launch Visual Studio by double clicking a script file.

---
Tags: unity, c#, visual-studio
---


# Question
Title: Alternative for using game object/prefabs for level generator
I just finished the Unity Tutorial for creating a simple 2D roguelike Mobile Game. Now I wanted to make my level bigger; finding or creating my own algorithm isn't the problem. My problem is that creating a game object or using a prefab for every single floor or wall tile is a bad idea. (Map 200x200 = 40000 objects). A comment under the tutorial said that and I'm incline to believe it. That much I can understand, but I can't find a alternative. What can I use besides object/prefabs?

Sidenote: I have decent programming skills, but am beginner with Unity.

The tutorial I followed: https://www.youtube.com/playlist?list=PLX2vGYjWbI0SKsNH5Rkpxvxr1dPE0Lw8F I want to make the maps there bigger, but then everything goes slow motion.

# Answer
Tile map is one option to use, the other is to maintain only the number of tiles that can be seen on screen at any given moment, and copy the tiles that go offscreen to the location of the next tiles to go on screen.
> 3 votes

# Answer
The basic alternative to having many game objects would be to construct one game object that has all of your geometry. If the game is tile based, then you could have a game object for each of the unique varieties of tiles and then at runtime you could generate the map mesh programmatically from a data structure e.g. a 2D array which represents which tiles to place at which locations.

Essentially you would need read the geometry from the "unique tile" game objects and copy it into the "map" game object, offsetting vertex coordinates for each tile with the proper x/y offset based on where you want to place it in the map.

This is still not completely optimal in that you may end up with a lot more triangles than you really need. If you were really concerned about performance you could try to further simplify adjacent co-planar triangles, but even if you were not doing any geometry simplification it is still probably a whole lot more efficient than one game object per tile.

(My answer is under the assumption that the tiles have interesting 3D geometry. If they are just flat textured tiles then the Tilemaps suggested by another commenter would probably be the better option. It doesn't seem like Tilemaps support 3D tiles though.)
> 1 votes

---
Tags: unity, procedural-generation, gameobject
---


# Question
Title: Unity: Saving scene after using script to change object positions
I have a c# script which makes some edits to object positions in the editor. It does this by reading some values from a csv file and then changing the value of `transform.position` for each gameobject. When I run the script all the objects appear where I want them to be in the editor. However, the editor doesn't seem to recognise any change and when I save and reload the scene the objects have reverted to their previous positions. Any ideas?

Code:

```
GameObject go = GameObject.Find(values[1]);
Undo.RecordObject(go,"setting at rest");
// Do transforms
float x = float.Parse(p_values[0]);
float y = float.Parse(p_values[1]);
float z = float.Parse(p_values[2]);
Vector3 p = new Vector3(x,y,z);

go.transform.position = p;

```

Aha I think I see my error, `Undo.RecordObject` want the specific object that is changing rather than the gameobject. I've edited the code to `Undo.RecordObject(go.transform,"setting at rest");` and it now seems to work

# Answer
I see my error, `Undo.RecordObject` wants the specific object that is changing rather than the gameobject that is being modified (this wasn't that clear to me from the docs). I've edited the code to `Undo.RecordObject(go.transform,"setting at rest");` and it now seems to work
> 1 votes

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


# Question
Title: Detect left and right movement of sprite
I have a sprite of ball which moves when a player tap and holds the ball and move finger on the screen. I have a attached animations on it. straight, left, right and when the ball hits something.

Here is my code: `ball.cs`

```
 public RuntimeAnimatorController straight;
    public RuntimeAnimatorController left;
    public RuntimeAnimatorController right;
    public RuntimeAnimatorController ballHit;

    Animator animator;
    Vector2 prevPos;

    private void Start()
    {
        animator = gameObject.GetComponent<Animator>();
    }

    void Update ()
     {

         //Gets the world position of the mouse on the screen
         Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);

         //Checks whether the mouse is over the sprite
         bool overSprite = this.GetComponent<SpriteRenderer>().bounds.Contains(mousePosition);
         if(GameObject.Find("GameController").GetComponent<brickMovement>().gameOver == true)
        {

            animator.applyRootMotion = true;
            animator.updateMode = AnimatorUpdateMode.UnscaledTime;
            animator.runtimeAnimatorController = ballHit;
        }
         //If it's over the sprite
         if (overSprite)
         {
             //If we've pressed down on the mouse (or touched on the iphone)
             if (Input.GetButton("Fire1") && GameObject.Find("GameController").GetComponent<brickMovement>().gamepaused == false && GameObject.Find("GameController").GetComponent<brickMovement>().gameOver == false)
             {
                 float x = Camera.main.ScreenToWorldPoint(Input.mousePosition).x;
                 float y = Camera.main.ScreenToWorldPoint(Input.mousePosition).y;
                 //Set the position to the mouse position
                 prevPos = this.transform.position;

                 //Debug.Log(animator.runtimeAnimatorController);
                 if ((x > -1.938 && y > -4.51) && (x < 1.98 && y < 4.5))
                 {
                    //Debug.Log("Previous Pos: " + prevPos.x);
                    Debug.Log(IsThisObjectMoving());
                    if (this.transform.position.x < 0 && IsThisObjectMoving())
                     {
                        animator.runtimeAnimatorController = left;
                     }
                     else if (this.transform.position.x > 0 && IsThisObjectMoving())
                     {
                        animator.runtimeAnimatorController = right;
                     }
                     else if (this.transform.position.x == prevPos.x)
                     {
                        animator.runtimeAnimatorController = straight;
                     }
                     this.transform.position = new Vector3(Camera.main.ScreenToWorldPoint(Input.mousePosition).x,
                     Camera.main.ScreenToWorldPoint(Input.mousePosition).y,
                     0.0f);
                 }
             }
         }
     }

    bool IsThisObjectMoving()
    {
        Vector3 sek0pos;
        Vector3 sek1pos;

        sek0pos = gameObject.transform.position;
        StartCoroutine(delay());
        sek1pos = gameObject.transform.position;

        if ((sek1pos.x - sek0pos.x) > 0f)
            return true;
        else
            return false;
    }

    /*

    Make function out of the above function that will check if object is
    moving left or right.

    */
    IEnumerator delay()
    {
        yield return new WaitForSeconds(1.0f);
    }

```

I am having issue in detecting if ball is moving left or right. When ball is not moving straight animation should be played. but when it is the respective direction animation should be played.

Secondly when I do a hit animation it ends quickly without getting played properly.

# Answer
Note that the `IEnumerator delay()` in your code doesn't do anything. In the `IsThisObjectMoving()` function, calling `StartCoroutine(delay())` returns immediately, so `sek0pos` and `sek1pos` are always the exact same.

If you want to add a 1-second delay within the `IsThisObjectMoving()` function, you can mark this function as `async Task<bool>` (including `System.Threading.Tasks`), use `await Task.Delay(1000)` instead of using your `delay()` IEnumerator, and using the function within an `await` statement: `if(await IsThisObjectMoving()){ /*...*/ }` (the function in which this is called will need to be marked `async` as well). The function will then return after one full second. Note that you'd need .NET 4.x to be able to use async functionality natively in Unity.

Depending on what you want to do exactly, you may want to look into other alternatives. For example, you can sample consecutive positions within different frames in `Update()`, or discard `Update()` and rewrite it as a coroutine which runs infinitely on the GameObject, sampling the position every second; something like so:

```
void Start(){
    StartCoroutine(positionSample());
}

IEnumerator positionSample(){
    Vector3 previousPosition = transform.position;
    Vector3 currentPosition;

    while(true){
         yield return new WaitForSeconds(1);
         currentPosition = transform.position;

         // use the two positions to determine what you need

         previousPosition = currentPosition;
    }
}

```
> 0 votes

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


title: How to add a animation to myPlayer

text:
# Question
Title: How to add a animation to myPlayer
I'm currently making a shoot em up in monogame.

I want to add just one animation to my object. No commands or transitions between animations for different actions: just an object swapping between different images all the time.

For example, my player will have 4 different images for it and I'd want it to always swap trough these images.

Animation guides I've reviewed seem way too complicated for my needs. Unlike the examples they cover, I don't want different animations for different commands.

How can I make this type of simple, always-looping frame animation?

Edit

I managed to make a constantly looping animation to a sprite and but I don't know how to insert into myPlayer.

```
Game1:
        Texture2D myPlayerAnim;
        Rectangle myDestRect;
        Rectangle mySourceRect;
        Texture2D myEnemyAnim;
        Rectangle myEnemyDestRect;
        Rectangle myEnemySourceRect;
        float myElapsed;
        float myDelay = 100f;
        int myFrames = 0;

Initialize:
            myDestRect = new Rectangle(0, 0, 512, 512);
            myEnemyDestRect = new Rectangle(0, 0, 808, 608);

LoadContent:

            myPlayerAnim = Content.Load<Texture2D>("SpriteSheetPlayerAnim");
            myEnemyAnim = Content.Load<Texture2D>("SpriteSheetEnemyAnim");

Update:
            myElapsed += (float)aGameTime.ElapsedGameTime.TotalMilliseconds;

            if (myElapsed >= myDelay)
            {
                if (myFrames >= 3)
                {
                    myFrames = 0;
                }
                else
                {
                    myFrames++;
                }
                myElapsed = 0;
            }

            mySourceRect = new Rectangle(512 * myFrames, 0, 512, 512);
            myEnemySourceRect = new Rectangle(808 * myFrames, 0, 808, 608);

Draw:

            mySpriteBatch.Draw(myPlayerAnim, myDestRect , mySourceRect,
            Color.White);
            mySpriteBatch.Draw(myEnemyAnim, myEnemyDestRect, myEnemySourceRect,
            Color.White);´

```

Draw just draws the animations out but I don't know how to insert it into myPlayer. For myPlayer I currently have this but I couldn't figure out how to do it with my animations.

```
Draw:
myPlayer = new Player(TextureLibrary.GetTexture("player"), myPlayerPos, 200, new Vector2(.3f, .3f), 0, Color.White, 1000, 1);

```

# Answer
> 0 votes
Based on your code you have given. I think you just need to change some things.

First, use the `SpriteSheetPlayerAnim` as the texture of your player directly instead of using `player` texture.

Then move the code of `Update` and `Draw` of player's animation to `Update` and `Draw` of `Player` class.

They will be like this:

```
public class Player
{
    //Default constructor
    public Player()
    {
        //default values for your player//for example only
        //this.hp = 100;
        //this.mp = 20;
    }

    //Constructor
    public Player(GameTime myelapsedGameTime, Texture2D texPlayer, Vector2 playerPosition, int something, Vector2 vector2ForSomething, int intFST, Color playerColor, ...)
    {
        //initialise player's attributes

    }

    public override Update(GameTime gameTime)
    {
        if (myElapsed >= myDelay)
        {
            if (myFrames >= 3)
            {
                myFrames = 0;
            }
            else
            {
                myFrames++;
            }
            myElapsed = 0;
        }
    }

    public override Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(myPlayerAnim, myDestRect , mySourceRect,
            Color.White);//for example
    }
}

```

Then in your `Game1` class:

```
public class Game1 : Game
{
    Player player;
    GameTime myElapsed;

    public Game1()
    {
        //
    }

    protected override void LoadContent()
    {
        //Load your animated sprite here
        myPlayerAnim = Content.Load<Texture2D>("SpriteSheetPlayerAnim");

        player = new Player(myElapsed, myPlayerAnim, ...);//constructor with attributes here or whatever you want
    }

    protected override void Update(GameTime gameTime)
    {
        myElapsed += (float)aGameTime.ElapsedGameTime.TotalMilliseconds;
        player.Update(gameTime);
    }

    protected override void Draw(SpriteBatch spriteBatch)
    {
        player.Draw(spriteBatch);
    }
}

```

Hope this helps!

For beginners, I suggest that you get through the tutorial below first.

2D XNA Tutorials - RB Whitaker's Wiki

Also your problem (which we call `texture atlases`) is lying in this link:

Texture Atlases - Part 1

Just follow the tutorial from the beginning. Hope this helps!

---
Tags: xna, animation, monogame, xna-content-pipeline
---


title: Alternative to Game State System?

text:
# Question
Title: Alternative to Game State System?
As far as I can tell, most games have some sort of "game state system" which switches between the different game states; these might be things like "Intro", "MainMenu", "CharacterSelect", "Loading", and "Game".

On the one hand, it totally makes sense to separate these into a state system. After all, they are disparate and would otherwise need to be in a large switch statement, which is obviously messy; and they certainly are well represented by a state system. But at the same time, I look at the "Game" state and wonder if there's something wrong about this state system approach. Because it's like the elephant in the room; it's HUGE and obvious but nobody questions the game state system approach.

It seems silly to me that "Game" is put on the same level as "Main Menu". Yet there isn't a way to break up the "Game" state.

Is a game state system the best way to go? Is there some different, better technique to managing, well, the "game state"? Is it okay to have an intro state which draws a movie and listens for enter, and then a loading state which loops on the resource manager, and then the game state which does practically **everything**? Doesn't this seem sort of unbalanced to you, too? Am I missing something?

# Answer
I think you're just arguing semantics here. It's called Game State because it behaves like a Finite State Machine, with a finite number of states and transitions between them. The 'Game' in 'Game State System' refers to the overall system, with 'Loading', 'MainMenu' etc being states of the game. These could easily be called 'scenes' or 'screens' or 'levels'. Its just semantics.

I'm not sure that a strict FSM applies anymore. In my implementations I call states 'Screens' and allow them to be stackable - ie. screens can be drawn on top of other screens, controlling whether or not screens below them are updated or drawn. In this way, I can have multiple screens active at the same time with self-contained logic and code specific to that screen, without having to worry about any other screen.

A Pause screen, for example, could be opened on top of my main gameplay screen that disallows updates, but allows drawing below itself. A character inventory screen could allow both drawing and updates - so the game keeps playing while you're working in your inventory.
> 31 votes

# Answer
Sure the Game state would be huge, but there's no reason that the Game state itself can't contain a state machine to manage its data. Hierarchical state machines are useful.
> 8 votes

# Answer
I always like to the think of each "state" as a "scene". So the opening video is a scene, just a static one. The credits are a scene. The menu is a scene. The only difference between them all is the level of interactivity and game logic.
> 4 votes

# Answer
I have problems with that too, actually.

Let's say you have a Game.

Instead of making 'Game' a state like 'Loading', 'Main Menu', etc. - IMO it's better to let Game ***have*** several states:

*"Loading"* \- *"showing menu"* \- *"paused"*, etc.

The Game is still running, but when it shows the main menu it would be in 'show menu' mode.

And when Game is not in any particular state, it's just running.

It makes much more sense, at least to me. :)
> 3 votes

# Answer
An online program (in the traditional meaning of online, ie. continually running and responding to input, rather than meaning connected to the internet) typically consists of 3 things:

* input gathering and handling
* updating of logic
* output

Generally speaking, these 3 are related and change at the same time. For example, when displaying a splash screen you might map all your keys to a 'close screen' command and the update may be fading a graphic in slowly with the output just showing that graphic. But when playing a game the keys may all map to different commands and the update is changing properties of many in-game objects.

When you view it this way, it makes sense to separate an Intro from Character Creation and from the Game proper: each has its own set of input, update, and output rules. They're almost like self-contained programs that happen to share some data and library code. And, with this in mind, it usually makes sense to have just one Game state, since the gameplay is fairly homogeneous throughout.

Of course, if you do actually have separate types of gameplay (eg. an RPG example - World Map, Town Map, Cutscene, Combat), with differing input, updates, and output, there's no reason you couldn't have multiple states there too instead of just 1 Game state. But it depends on your game.
> 2 votes

# Answer
I look at it the other way. 'Menu', 'HighScores', "credits" or whathaveyou, could be considered as just another level, and then that state isn't necessarily lighter than your 'game' state (the game state just happens to have more entities in general, and different ones, but in the end it's just another level where the entities happen to show more predicatble behaviour and the 'maps' are generally less intricate).
Making that switch in your thinking definitely pulls you out of the "boring menu" syndrome.
> 1 votes

# Answer
In my game, I have:

**Execution Manager**, which initalizes the application (game), loads resources, releases resources on application exit, etc. It initalizes Application Engine, GameViewEngine, GameLogicEngine.

**Game State Manager**, which resides in the GameLogicEngine, and is responsible for controlling the things related to game main loop: collision detection, physics calculation, keyboard reading, math operations, etc...

Initially, I tended to have only one Game State Manager which was part of my GameLogicEngine. However, I had some difficulties with controll over the intialization of main subsystems (GameLogic, ApplicationEngine, ...). It could have been done, but it was more messy, imo.

Now things look more transparent to me, and I am happy with the design.
> 1 votes

# Answer
Rename the 'Game' state to something like 'Gameplay'. Then your logic seems better; You stop playing to go to th menu : you exit the Gameplay state to go to the MainMenu state.

Also, I think things like pause, which would require the game to be in the same state as when you paused the game, should not be separate states. Child states and nesting, perhaps? The Gameplay has-a pause menu.
> 0 votes

# Answer
I think that there is a good method called a game-state stack. I haven't seen any papers or articles about it but it's been spreading a little bit by voice. Essentially the topmost game-state on the stack is called first and gets to do whatever it wants to with input/rendering etc. The topmost game-state is the only one allowed to push or pop states.

In my engine, game-states are actually just lists of game entities. I then have entities that work as menus. My menu-states either pause the game (by not updating the next item on the stack) but let the other state(s) push their models to the renderer so that my pause-menu (which doesn't cover the entire screen) still has the game rendering in the back.

I hope that gives an idea of a little bit different system that isn't based on a state-machine.
> 0 votes

# Answer
> Is it okay to have an intro state which draws a movie and listens for enter, and then a loading state which loops on the resource manager, and then the game state which does practically everything? Doesn't this seem sort of unbalanced to you, too? Am I missing something?

This is perfectly fine. Or at least, it is an improvement over "having a big ugly switch depending on the state the game it is".

I'd like to point out that in most games you will already need a finite state machine of sorts in order to deal with simple entity AI. The typical example are enemies that are on Iddle state, Attacking or Dieing.

If you have a sufficiently abstracted Finite State Machine, then you can re-use it for both the Game object and your AI; suddenly you are not "investing" lots of effort on the Game state - instead you are reusing code that you used anyway.

Shameless self-plug ensues: I've implemented such a Finite State Machine on my Lua game library, MiddleClass (concretely, the add-on called MindState). Here's how you do a Game State thing with it.
> 0 votes

# Answer
A different approach to this is to use a concept from the functional programming world called a Discriminated Union. Whilst these are *typically* found in FP languages, you can emulate them using classes.

Basically, a *Discriminated Union* is a type that is always one of `n` cases, and the data stored can vary with each case.

For example:

```
type GameState =
  | Menu of MenuState
  | Playing of SimulationState

```

Here, our `GameState` type can be either `Menu` or `Playing`. If it is `Menu`, then it will contain a `MenuState` object. If it is `Playing`, then it will contain a `SimulationState` object.

To update, we would `match` on the state, and call a different function accordingly:

```
let update gameTime =
  let nextState =
    match gameState with
    | Menu menuState -> updateMenu gameTime menuState
    | Playing simulationState -> updateSimulation gameTime simulationState

  // Mutate the current state
  gameState <- nextState

```

And similarly for rendering:

```
let render gameTime =
  let nextState =
    match gameState with
    | Menu menuState -> renderMenu menuState
    | Playing simulationState -> renderSimulation simulationState

```

One advantage of this approach is that you can handle things across states (such as resources) more easily without globals or passing around "service" objects.
> 0 votes

---
Tags: architecture, state
---


# Question
Title: Blender export does not render correctly in Monogame
I am using Monogame `3.7.0.7` on Linux and Blender.

I have exported my model using the "FBX 7.4 Binary" exporter. Here is a render from Blender:

However, when rendered by Monogame, it does not look right:

My render code is very standard (F#)

```
    let model = this.Content.Load<Model> @"Skull"

    for mesh in model.Meshes do
      for effect in mesh.Effects do
        match effect with
        | :? BasicEffect as effect ->
          effect.EnableDefaultLighting ()
          effect.TextureEnabled <- true
          effect.PreferPerPixelLighting <- true

          effect.World <-
            Matrix.CreateScale (16.0f) *
            Matrix.CreateTranslation (Vector3.Up * 32.0f + Vector3.Backward * 128.0f)

          effect.View <- view
          effect.Projection <- projection
        | _ -> ()

      mesh.Draw ()

```

How should I export models from Blender for use in Monogame?

# Answer
The missing piece of the puzzle:

```
use depthStencilState <- new DepthStencilState ()

depthStencilState.DepthBufferEnable <- true

this.GraphicsDevice.DepthStencilState <- depthStencilState

```
> 1 votes

---
Tags: xna, monogame, blender
---


# Question
Title: Apply 2D Texture on all faces of a 3D Cube
I am trying to render a 3D cube, and apply a single texture to all the faces of the cube. I feel like I am missing something critical here as it is applying to the front and back faces of the cube, but 'stretching' it across the other faces.

Example:

Object is created via:

```
void Engine::CreateObjects()
{
    std::vector<unsigned int> indices;
    indices.push_back(0);
    indices.push_back(1);
    indices.push_back(2);
    indices.push_back(2);
    indices.push_back(3);
    indices.push_back(0);
    indices.push_back(1);
    indices.push_back(5);
    indices.push_back(6);
    indices.push_back(6);
    indices.push_back(2);
    indices.push_back(1);
    indices.push_back(7);
    indices.push_back(6);
    indices.push_back(5);
    indices.push_back(5);
    indices.push_back(4);
    indices.push_back(7);
    indices.push_back(4);
    indices.push_back(0);
    indices.push_back(3);
    indices.push_back(3);
    indices.push_back(7);
    indices.push_back(4);
    indices.push_back(4);
    indices.push_back(5);
    indices.push_back(1);
    indices.push_back(1);
    indices.push_back(0);
    indices.push_back(4);
    indices.push_back(3);
    indices.push_back(2);
    indices.push_back(6);
    indices.push_back(6);
    indices.push_back(7);
    indices.push_back(3);

    std::vector<Vertex> vertices;

    //                                   xPos   yPos   zPos             xTex    yTes
    vertices.push_back(Vertex(glm::vec3(-1.0f, -1.0f, 1.0f), glm::vec2(1.0f, 1.0f)));
    vertices.push_back(Vertex(glm::vec3(1.0, -1.0, 1.0), glm::vec2(1.0f, 0.0f)));
    vertices.push_back(Vertex(glm::vec3(1.0, 1.0, 1.0), glm::vec2(0.0f, 0.0f)));
    vertices.push_back(Vertex(glm::vec3(-1.0, 1.0, 1.0), glm::vec2(0.0f, 1.0f)));

    vertices.push_back(Vertex(glm::vec3(-1.0, -1.0, -1.0), glm::vec2(1.0f, 1.0f)));
    vertices.push_back(Vertex(glm::vec3(1.0, -1.0, -1.0), glm::vec2(1.0f, 0.0f)));
    vertices.push_back(Vertex(glm::vec3(1.0, 1.0, -1.0), glm::vec2(0.0f, 0.0f)));
    vertices.push_back(Vertex(glm::vec3(-1.0, 1.0, -1.0), glm::vec2(0.0f, 1.0f)));

    std::vector<Texture> textures;
    Texture texture = Texture("src/Textures/wall.jpg");
    textures.push_back(texture);

    Mesh* obj1 = new Mesh(vertices, indices, textures);
    meshList.push_back(obj1);
}

```

Vertex Struct:

```
#pragma once

#include <glm/glm.hpp>

struct Vertex
{
    Vertex(glm::vec3 position, glm::vec2 texCoords) : Position(position), TexCoords(texCoords) {};

    glm::vec3 Position;
    glm::vec2 TexCoords;
};

```

Texture Struct:

```
#pragma once

#include "External/stb_image.h"
#include <string>
#include <iostream>

struct Texture
{
    Texture(std::string path) : Id(0), Type(""), Path(path), Width(0), Height(0), nrChannels(0)
    {
        LoadTexture();
    }

    unsigned int Id;
    int Width;
    int Height;
    int nrChannels;
    std::string Type;
    std::string Path;

private:
    void LoadTexture()
    {
        glGenTextures(1, &Id);
        glBindTexture(GL_TEXTURE_2D, Id);

        // Wrapping
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

        // Filtering
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

        stbi_set_flip_vertically_on_load(true);
        unsigned char* data = stbi_load(Path.c_str(), &Width, &Height, &nrChannels, 0);

        if (!data)
        {
            std::cout << "Failed to load texture " << this->Path << std::endl;
        }

        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, Width, Height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);
        glBindTexture(GL_TEXTURE_2D, 0);

        stbi_image_free(data);
    }
};

```

And the actual drawing of the Mesh is done via these two functions (Draw, Setup):

```
void Mesh::Draw(Shader shader)
{
    glBindTexture(GL_TEXTURE_2D, textures[0].Id);
    glActiveTexture(GL_TEXTURE0);
    glBindVertexArray(VAO);
    glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0);
    glBindVertexArray(0);
}

void Mesh::SetupMesh()
{
    glGenVertexArrays(1, &this->VAO);
    glGenBuffers(1, &this->VBO);
    glGenBuffers(1, &this->EBO);

    glBindVertexArray(VAO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);

    auto size = vertices.size() * sizeof(Vertex);
    glBufferData(GL_ARRAY_BUFFER,size, &vertices[0], GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW);

    // vertex Positions
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0);
    // vertex texture coords
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, TexCoords));

    glBindVertexArray(0);
}

```

I understand this code is not ideal and am extremely open to different ways of constructing this cube, especially when it comes to listing the indices, but the primary issue is the texture stretching.

To me, it seems like the program is doing exactly what i'm telling it to do, however, I seem to have a knowledge gap on where to go from here to have the texture apply across the entire cube.

# Answer
So the problem you've got is that you have 8 vertices total and re-use them for the different faces. With the way you specify the UV's for the vertices, the faces that look stretched actually have the same UV values for two of the corners on either side of the face.

I think you're best option is to have 4 unique vertices for each face if you plan to try and have the whole texture on each face. If/when you want normals for the faces you'll need to have different vertices for the faces anyway.
> 2 votes

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


# Question
Title: Fixed Timestep with Interpolation | Blurry & Choppy
I've been implementing a game loop with a fixed timestep which uses interpolation as described in the (legendary as I have come to find out as it is referenced in almost every post I have read trying to diagnose this issue) article "Fix Your Timestep" (webarchive link given as the site appears to be down now).

From what I can tell I have implemented everything discussed as closely as I could, however after adding the interpolation phase, I instantly noticed choppiness and a blurry smear effect happening when moving my camera.

This is about as basic of a 3d scene as you can get. There is a single object loaded at a static position, and I have a first person shooter style camera that strafes with wasd and rotates (pitch/yaw) via mouse coordinates.

When my `accumulator` variable is greater than or equal to my fixed `delta_time` variable, an update is performed. The only action that is performed during this update is to move and rotate a set of vectors which are used to position my camera in a later step, and update my previous and current state objects with this updated information. After this my `accumulator` variable is then decremented by the value of my fixed `delta_time`.

Once back in my initial loop, I now perform a render by calculating an interpolated game state and positioning my camera using the vectors created during this interpolation. I then create my view/projection matrices from my camera and render the scene.

Since it is very difficult to explain what I'm seeing, I have uploaded a video to youtube that depicts my results: https://www.youtube.com/watch?v=9zhGxgmpJpA (the smear effect seems to have been lost during the upload, but the choppiness is still visible)

Below is all of the code I believe to be relevant to the question, however if I have missed a chunk somewhere just let me know and I'll throw it up as well:

```
// From main.cpp
int main()
{

    glm::vec2           screen_size = glm::vec2(1280, 720);
    InputState          input;

    Window              window(&screen_size, &input);
    if (window.getInitFailed()) {
        std::cout << window.getInitMessage() << std::endl;
        return -1;
    }

    auto                scene = std::make_unique<Scene>(&screen_size);
    auto                game = std::make_unique<GameLogic>(&input);

    double              delta_time = 0.03;
    double              current_time = window.time();
    double              accumulator = 0.0;

    glEnable(GL_DEPTH_TEST);

    scene->addModel("data/models/bin/actors/knife1/spyderco_tenacious_knife.obj");

    // Render loop
    while (!window.shouldClose())
    {

        if (input.key_esc) {
            window.setToClose();
            continue;
        }

        double new_time = window.time();
        double frame_time = new_time - current_time;
        if (frame_time > 0.25) {
            frame_time = 0.25;
        }
        current_time = new_time;

        accumulator += frame_time;

        // capture input state
        window.update();

        while (accumulator >= delta_time) {

            game->update(delta_time);

            accumulator -= delta_time;

        }

        scene->render(game->getCurrentGameState(),
        game->getPreviousGameState(), (accumulator / delta_time));

        window.vsync();
        window.swapBuffers();

    }

    return 0;
}

// From GameState.h
struct GameState {
    glm::vec3           player_position;
    glm::vec3           player_front;
    glm::vec3           view_position;
    glm::vec3           view_front;
};

// From GameLogic.cpp
GameLogic::GameLogic(InputState* is) : player(is) {}
GameLogic::~GameLogic() {}

void GameLogic::update(double delta) {

    player.update(delta);

    updateState();

}

void GameLogic::updateState() {

    previous_state = current_state;

    current_state.player_position = player.getPlayerPosition();
    current_state.player_front = player.getPlayerFront();

    current_state.view_position = player.getViewPosition();
    current_state.view_front = player.getViewFront();

}

GameState GameLogic::getCurrentGameState() {
    return current_state;
}

GameState GameLogic::getPreviousGameState() {
    return previous_state;
}

// From Scene.cpp
Scene::Scene(glm::vec2* screen_size) : camera(screen_size),
shader(GlobalConstants::VERTEX_SHADER, GlobalConstants::FRAGMENT_SHADER) {}
Scene::~Scene(){}

void Scene::render(GameState current_state, GameState previous_state, float alpha) {

    GameState lerp_render_state = lerpRenderState(current_state, previous_state, alpha);

    camera.setPosition(lerp_render_state.view_position);
    camera.setDirection(lerp_render_state.view_front);
    camera.update();

    // Select a color to clear the screen with and clear screen
    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    shader.use();

    shader.setMat4("view", camera.getViewMatrix());
    shader.setMat4("projection", camera.getProjectionMatrix());

    glm::mat4 model = glm::mat4(1.0f);
    model = glm::translate(model, glm::vec3(0.f, 2.f, -3.f));
    shader.setMat4("model", model);

    for (auto &m : models) {
        m.draw(shader);
    }

}

void Scene::addModel(std::string path) {
    models.push_back(Model(path));
}

GameState Scene::lerpRenderState(GameState current_state, GameState previous_state, float alpha) {

    GameState lerp_render_state;

    lerp_render_state.player_position = glm::lerp(current_state.player_position, previous_state.player_position, alpha);
    if (current_state.player_front != previous_state.player_front) {
        lerp_render_state.player_front = glm::slerp(current_state.player_front, previous_state.player_front, alpha);
    }
    else {
        lerp_render_state.player_front = current_state.player_front;
    }

    lerp_render_state.view_position = glm::lerp(current_state.view_position, previous_state.view_position, alpha);
    if (current_state.view_front != previous_state.view_front) {
        lerp_render_state.view_front = glm::slerp(current_state.view_front, previous_state.view_front, alpha);
    }
    else {
        lerp_render_state.view_front = current_state.view_front;
    }

    return lerp_render_state;

}

// From Camera.cpp
void Camera::update() {

    updateViewMatrix();
    updateProjectionMatrix();

}
void Camera::updateViewMatrix() {

    view_matrix = glm::lookAt(camera_position, camera_position + camera_front, camera_up);

}

```

# Answer
> 4 votes
Your lerps and slerps are backwards:

```
lerp(current, previous, alpha)

```

should be

```
lerp(previous, current, alpha)

```

ie. increasing alpha (more time accumulated since the last update) should move us toward the future, not toward the past.

This could account for at least some of the choppiness you perceive. There could be additional judder coming from the player update methods, depending on how you've incorporated your delta time there.

It doesn't account for the smear you describe though. That could be due to not completely clearing your previous frame, or it could be an artifact of your screen's response rate (this is sometimes be more apparent on moving, dark images like your knife blade, and would explain why it wasn't captured in your video)

---
Tags: c++, game-loop, interpolation, timestep, fixed-timestep
---


# Question
Title: corridors between rooms not generating; dungeon generator
So i'm following this tutorial http://www.rombdn.com/blog/2018/01/12/random-dungeon-bsp-unity/ to make a randomly generated dungeon. everything works fine, until it reaches the bit where the corridors are supposed to be generated. there are no error messages. But, i'm not even getting the Debug.log messages, which means it's not seeing the CreateCorridorBetween void at all. I hope it's some sort of stupid mistake that I've missed somehow, because my brain is pretty much fried at this point. here's my script:

```
public class BoardManager : MonoBehaviour {
public GameObject floorTile;
public GameObject corridorTile;

public int boardRows, boardColumns;
public int minRoomSize, maxRoomSize;

private GameObject[,] boardPositionsFloor;

public class SubDungeon {

    public SubDungeon left, right;
    public Rect rect;
    public Rect room = new Rect(-1,-1, 0, 0); // i.e null
    public int debugId;

    private static int debugCounter = 0;

    public List<Rect> corridors = new List<Rect>();

    public SubDungeon(Rect mrect) {
        rect = mrect;
        debugId = debugCounter;
        debugCounter++;
    }

    public bool IAmLeaf() {
        return left == null && right == null;
    }

    public bool Split(int minRoomSize, int maxRoomSize) {
        if (!IAmLeaf()) {
            return false;
        }

        // choose a vertical or horizontal split depending on the proportions
        // i.e. if too wide split vertically, or too long horizontally,
        // or if nearly square choose vertical or horizontal at random
        bool splitH;
        if (rect.width / rect.height >= 1.25) {
            splitH = false;
        } else if (rect.height / rect.width >= 1.25) {
            splitH = true;
        } else {
            splitH = Random.Range (0.0f, 1.0f) > 0.5;
        }

        if (Mathf.Min(rect.height, rect.width) / 2 < minRoomSize) {
            Debug.Log ("Sub-dungeon " + debugId + " will be a leaf");
            return false;
        }

        if (splitH) {
            // split so that the resulting sub-dungeons widths are not too small
            // (since we are splitting horizontally)
            int split = Random.Range (minRoomSize, (int)(rect.width - minRoomSize));

            left = new SubDungeon (new Rect (rect.x, rect.y, rect.width, split));
            right = new SubDungeon (
                new Rect (rect.x, rect.y + split, rect.width, rect.height - split));
        }
        else {
            int split = Random.Range (minRoomSize, (int)(rect.height - minRoomSize));

            left = new SubDungeon (new Rect (rect.x, rect.y, split, rect.height));
            right = new SubDungeon (
                new Rect (rect.x + split, rect.y, rect.width - split, rect.height));
        }

        return true;
    }

    public void CreateRoom() {
        if (left != null) {
            left.CreateRoom ();
        }
        if (right != null) {
            right.CreateRoom ();
        }
        if (IAmLeaf()) {
            int roomWidth = (int)Random.Range (rect.width / 2, rect.width - 2);
            int roomHeight = (int)Random.Range (rect.height / 2, rect.height - 2);
            int roomX = (int)Random.Range (1, rect.width - roomWidth - 1);
            int roomY = (int)Random.Range (1, rect.height - roomHeight - 1);

            // room position will be absolute in the board, not relative to the sub-dungeon
            room = new Rect (rect.x + roomX, rect.y + roomY, roomWidth, roomHeight);
            Debug.Log ("Created room " + room + " in sub-dungeon " + debugId + " " + rect);
        }
    }

    public Rect GetRoom() {
        if (IAmLeaf()) {
            return room;
        }
        if (left != null) {
            Rect lroom = left.GetRoom ();
            if (lroom.x != -1) {
                return lroom;
            }
        }
        if (right != null) {
            Rect rroom = right.GetRoom ();
            if (rroom.x != -1) {
                return rroom;
            }
        }

        // workaround non nullable structs
        return new Rect (-1, -1, 0, 0);
    }

    public void CreateCorridorBetween(SubDungeon left, SubDungeon right) {
        Rect lroom = left.GetRoom ();
        Rect rroom = right.GetRoom ();

        Debug.Log("Creating corridor(s) between " + left.debugId + "(" + lroom + ") and " + right.debugId + " (" + rroom + ")");

        // attach the corridor to a random point in each room
        Vector2 lpoint = new Vector2 ((int)Random.Range (lroom.x + 1, lroom.xMax - 1), (int)Random.Range (lroom.y + 1, lroom.yMax - 1));
        Vector2 rpoint = new Vector2 ((int)Random.Range (rroom.x + 1, rroom.xMax - 1), (int)Random.Range (rroom.y + 1, rroom.yMax - 1));

        // always be sure that left point is on the left to simplify the code
        if (lpoint.x > rpoint.x) {
            Vector2 temp = lpoint;
            lpoint = rpoint;
            rpoint = temp;
        }

        int w = (int)(lpoint.x - rpoint.x);
        int h = (int)(lpoint.y - rpoint.y);

        Debug.Log ("lpoint: " + lpoint + ", rpoint: " + rpoint + ", w: " + w + ", h: " + h);

        // if the points are not aligned horizontally
        if (w != 0) {
            // choose at random to go horizontal then vertical or the opposite
            if (Random.Range (0, 1) > 2) {
                // add a corridor to the right
                corridors.Add (new Rect (lpoint.x, lpoint.y, Mathf.Abs (w) + 1, 1));

                // if left point is below right point go up
                // otherwise go down
                if (h < 0) {
                    corridors.Add (new Rect (rpoint.x, lpoint.y, 1, Mathf.Abs (h)));
                } else {
                    corridors.Add (new Rect (rpoint.x, lpoint.y, 1, -Mathf.Abs (h)));
                }
            } else {
                // go up or down
                if (h < 0) {
                    corridors.Add (new Rect (lpoint.x, lpoint.y, 1, Mathf.Abs (h)));
                } else {
                    corridors.Add (new Rect (lpoint.x, rpoint.y, 1, Mathf.Abs (h)));
                }

                // then go right
                corridors.Add (new Rect (lpoint.x, rpoint.y, Mathf.Abs (w) + 1, 1));
            }
        } else {
            // if the points are aligned horizontally
            // go up or down depending on the positions
            if (h < 0) {
                corridors.Add (new Rect ((int)lpoint.x, (int)lpoint.y, 1, Mathf.Abs (h)));
            } else {
                corridors.Add (new Rect ((int)rpoint.x, (int)rpoint.y, 1, Mathf.Abs (h)));
            }
        }

        Debug.Log ("Corridors: ");
        foreach (Rect corridor in corridors) {
            Debug.Log ("corridor: " + corridor);
        }
    }
}

public void CreateBSP(SubDungeon subDungeon) {
    Debug.Log ("Splitting sub-dungeon " + subDungeon.debugId + ": " + subDungeon.rect);
    if (subDungeon.IAmLeaf()) {
        // if the sub-dungeon is too large
        if (subDungeon.rect.width > maxRoomSize
            || subDungeon.rect.height > maxRoomSize
            || Random.Range(0.0f,1.0f) > 0.25) {

            if (subDungeon.Split (minRoomSize, maxRoomSize)) {
                Debug.Log ("Splitted sub-dungeon " + subDungeon.debugId + " in "
                    + subDungeon.left.debugId + ": " + subDungeon.left.rect + ", "
                    + subDungeon.right.debugId + ": " + subDungeon.right.rect);

                CreateBSP(subDungeon.left);
                CreateBSP(subDungeon.right);
            }
        }
    }
}
public void DrawRooms(SubDungeon subDungeon) {
    if (subDungeon == null) {
        return;
    }
    if (subDungeon.IAmLeaf()) {
        for (int i = (int)subDungeon.room.x; i < subDungeon.room.xMax; i++) {
            for (int j = (int)subDungeon.room.y; j < subDungeon.room.yMax; j++) {
                GameObject instance = Instantiate (floorTile, new Vector3 (i, j, 0f), Quaternion.identity) as GameObject;
                instance.transform.SetParent (transform);
                boardPositionsFloor [i, j] = instance;
            }
        }
    } else {
        DrawRooms (subDungeon.left);
        DrawRooms (subDungeon.right);
    }
}

void DrawCorridors(SubDungeon subDungeon) {
    if (subDungeon == null) {
        return;
    }

    DrawCorridors (subDungeon.left);
    DrawCorridors (subDungeon.right);

    foreach (Rect corridor in subDungeon.corridors) {
        for (int i = (int)corridor.x; i < corridor.xMax; i++) {
            for (int j = (int)corridor.y; j < corridor.yMax; j++) {
                if (boardPositionsFloor [i, j] == null) {
                    GameObject instance = Instantiate (corridorTile, new Vector3 (i, j, 0f), Quaternion.identity) as GameObject;
                    instance.transform.SetParent (transform);
                    boardPositionsFloor [i, j] = instance;
                }
            }
        }
    }
}

void Start () {
    SubDungeon rootSubDungeon = new SubDungeon (new Rect (0, 0, boardRows, boardColumns));
    CreateBSP (rootSubDungeon);
    rootSubDungeon.CreateRoom ();

    boardPositionsFloor = new GameObject[boardRows, boardColumns];
    DrawCorridors (rootSubDungeon);
    DrawRooms (rootSubDungeon);
}
}

```

I can't seem to figure out what's wrong, I'm doing as the tutorial says, step by step.

# Answer
> 0 votes
Probably due to a typo from part of the author of the tutorial, the original code is missing a call to `CreateCorridorBetween`.

To fix that add the call in `CreateRoom`, like this:

```
public void CreateRoom()
{
    if (left != null)
    {
        left.CreateRoom();
    }
    if (right != null)
    {
        right.CreateRoom();
    }
    if (IAmLeaf())
    {
        int roomWidth = (int)Random.Range(rect.width / 2, rect.width - 2);
        int roomHeight = (int)Random.Range(rect.height / 2, rect.height - 2);
        int roomX = (int)Random.Range(1, rect.width - roomWidth - 1);
        int roomY = (int)Random.Range(1, rect.height - roomHeight - 1);

        // room position will be absolute in the board, not relative to the sub-dungeon
        room = new Rect(rect.x + roomX, rect.y + roomY, roomWidth, roomHeight);
        Debug.Log("Created room " + room + " in sub-dungeon " + debugId + " " + rect);
    }

    if (right != null && left != null)
        CreateCorridorBetween(left, right);
}

```

By adding the call there, you don't need to re-walk the sub dungeons with a loop as I originally suggested in my previous comment.

The `if` is more for safety than for real need, as I didn't try to gain a full understanding of the code, only what was need to apply a quick fix. But at leas I did confirm, to save time for the reader, that my code doesn't create duplicated tiles, you can verify this by inspecting the scene hierarchy in Unity Editor during execution of the game.

Note: if you are getting the corridor tiles over the floor tiles (corridors drawn over rooms) simply do this to place the call to `DrawRooms` before call to `DrawCorridors`.

```
void Start()
{
    SubDungeon rootSubDungeon = new SubDungeon(new Rect(0, 0, boardRows, boardColumns));
    CreateBSP(rootSubDungeon);
    rootSubDungeon.CreateRoom();

    boardPositionsFloor = new GameObject[boardRows, boardColumns];
    DrawRooms(rootSubDungeon);
    DrawCorridors(rootSubDungeon);
}

```

Note that my `Start` method differs of yours in the order of `DrawRooms` and `DrawCorridors`.

There is a lot of room for improvement, have fun with procedural generation.

Tiles from opengameart.org: https://opengameart.org/node/20710 and https://opengameart.org/content/seamless-concrete-floor-tile

---
Tags: unity, 2d, procedural-generation, rpg
---


# Question
Title: Implementing mirrored coloured glass VFX like in Ant Man
This might seem like a strange question but I've been wanting to implement VFX in one of my games similar to what we see in the first Ant Man movie. Specifically only this:

Link to the gif above

1. What do you call a VFX/Object like this? Is there a term for this?
2. I'm assuming this is a job for a 3D artist. If so what is the best approach to building this? We are of course looking for a lower level of detail than the movie.

# Answer
1. This is a Kaleidoscope-like effect.
2. Assuming you're implementing this in Unity or Unreal Engine, you would either use a particle effect or a postprocess effect.

A particle effect would be used if you want the effect to show up somewhere in your 3D (or 2D) game world. A postprocess effect would be used if you want to modify the already-rendered image into this effect, or if you want to display the effect by itself in screen-space for, say, a loading screen.
> 2 votes

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


# Question
Title: Focus object with specific Rotation in unity C#
I have different kind of objects with variable dimensions and placed at different position in a scene. I want to focus/display each object with the camera with a hard code rotation (north rotation). Like with specific camera rotation I want to focus the object that it completely show to the camera and center of the screen. For this reason, I have write this code snippet that 1

1. Get the position behind the specific focus object using `TransformPoint`
2. Provide the elevation using the largest `extent` of the `bound` so that it display maximum area of the object.
3. Assign the `position` and the fixed `rotation`

```
 Vector3 dest = destination.transform.TransformPoint(0, 0, behindPositionDistance);// GetBehindPosition(destination.transform, behindPositionDistance, elevation);
 Debug.Log(dest);
 float eleveMax = Mathf.Max(destination.GetComponent<MeshRenderer>().bounds.extents.x, destination.GetComponent<MeshRenderer>().bounds.extents.z);
 dest = new Vector3(dest.x, eleveMax, dest.z);
 camera.transform.position = dest;
 camera.transform.rotation = lookNorth;

```

But the problem is, it is not accurately working with all objects as every object is at different position and dimension. I want to focus the full object using the camera but without changing the rotation.

# Answer
> 0 votes
Here is the code snippet thanks to one of unity forum thread.

```
public void SetPosition(Bounds bounds)
    {
        Camera camera = Camera.main;
        float cameraDistance = 1.0f; // Constant factor
        Vector3 objectSizes = bounds.max - bounds.min;
        float objectSize = Mathf.Max(objectSizes.x, objectSizes.y, objectSizes.z);
        float cameraView = 2.0f * Mathf.Tan(0.5f * Mathf.Deg2Rad * camera.fieldOfView); // Visible height 1 meter in front
        float distance = cameraDistance * objectSize / cameraView; // Combined wanted distance from the object
        distance += 0.5f * objectSize; // Estimated offset from the center to the outside of the object
        camera.transform.position = bounds.center - distance * camera.transform.forward;
    }

```

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


# Question
Title: How to stop switching between paths to a moving target?
I've noticed after implementing A\* pathfinding into my game, that there is exploitable/unrealistic behavior that goes on when the player moves between two nodes that alter the path of the AI trying to reach them. I have made a few images to demonstrate this problem.

This image above shows how the pathfinding in my game would behave if the player stood on the opposite side of a wall than my AI. If the player doesn't move it will take this single path to reach them. Assume that the red icon is the AI (enemy) and the blue icon is the target (player).

Now, if the player in this image above moves along the white arrows up and down, and the AI is constantly finding the optimal path to the player (ignore the performance costs of doing that), then the AI will also get stuck moving up and down because the optimal path will constantly shift between going above the wall and going under the wall. Is there a way to modify a standard A\* implementation to remedy this? I will include my pathfinding code for clarity, but it's pretty much a standard top down implementation. The "Node" object is a node on my grid, and the grid is an object that holds a list of nodes, with a few functions to find a node from a world point.

```
public class Pathfinding : MonoBehaviour
{

public Transform seeker, target;
AstarGrid grid;

void Awake()
{
    grid = GetComponent<AstarGrid>();
}

public List<Node> FindPath(Vector3 startPos, Vector3 targetPos)
{
    Node startNode = grid.NodeFromWorldPoint(startPos);
    Node targetNode = grid.NodeFromWorldPoint(targetPos);

    List<Node> openSet = new List<Node>();
    HashSet<Node> closedSet = new HashSet<Node>();
    openSet.Add(startNode);

    while (openSet.Count > 0)
    {
        Node node = openSet[0];
        for (int i = 1; i < openSet.Count; i++)
        {
            if (openSet[i].fCost < node.fCost || openSet[i].fCost == node.fCost)
            {
                if (openSet[i].hCost < node.hCost)
                    node = openSet[i];
            }
        }

        openSet.Remove(node);
        closedSet.Add(node);

        if (node == targetNode)
        {

            return RetracePath(startNode, targetNode);
        }

        foreach (Node neighbour in grid.GetNeighbours(node))
        {
            if (!neighbour.walkable || closedSet.Contains(neighbour))
            {
                continue;
            }

            int newCostToNeighbour = node.gCost + GetDistance(node, neighbour);
            if (newCostToNeighbour < neighbour.gCost || !openSet.Contains(neighbour))
            {
                neighbour.gCost = newCostToNeighbour;
                neighbour.hCost = GetDistance(neighbour, targetNode);
                neighbour.parent = node;

                if (!openSet.Contains(neighbour))
                    openSet.Add(neighbour);
            }
        }
    }
    return null;
}

```

# Answer
> 2 votes
Doesn't feel like a problem with your implementation but a problem of A\*. Leave A\* as it is, change when you let it run.

Assume the player will try to confuse his/her pursuer, by doing zigzags for example, and make the pursuer run A\* once, then let it move a random number of frames, it can be constant but random is more like trying to catch the player in its own game.

For example:

* Pursuer runs A\* and also decide in advance the next time it will run A\* again, random is recommended, between reasonable bounds like 2 tiles min and 6 tiles max. But the max number of tiles must not be greater than the distance to the player, or the following situation may happen: pursuer go pass the player's tile and have to turn back because player moved when the pursuer was 2 tiles away and the next time A\* was scheduled to run resulted in 3.
* Player is aware of A\* and tries to exploit it, but he/she cannot predict the next time A\* will run. As a result, the pursuer is more believable.

If for some reason a non believable pursuer behavior is wanted, then you can begin doing the random schedule strategy when you detected that you haven't shortened the distance to the target in a given number of frames, and stop after three or four runs and resume A\* every frame behavior, to enter random schedule strategy again if you detect at some point you are not shortening your distance to the target.

This may result in the pursuer acting "impatient" when the target isn't reachable, if such situation can occur in your game. And this may or may not be a good thing, depending on the game you imagined. But sure it will make the pursuer look alive. Also, this can be prevented with an extra `if` to detect when no path was found in addition to just check distance to target after or before A\* runs.

Note: I didn't try to run your A\* to see if it is correctly implemented, as I don't notice anything wrong in the code at a first glance, and you are already using it, I assuming it is correct.

---
Tags: unity, c#, ai, path-finding
---


# Question
Title: Unity Third Person Controller Camera-Relative Script
I'm an newbie in game developing. So i have a script for a camera that i attach to the player. I was wondering how to make a Third Person Controller with WASD controls that moves in the direction that the camera is facing. If you need it here's the camera script that i use

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

public class ThirdPersonCamera : MonoBehaviour {
    //define some constants
    private const float LOW_LIMIT = 0.0f;
    private const float HIGH_LIMIT = 85.0f;

    //these will be available in the editor
    public GameObject theCamera;
    public float followDistance = 5.0f;
    public float mouseSensitivityX = 4.0f;
    public float mouseSensitivityY = 2.0f;
    public float heightOffset = 0.5f;

    //private variables are hidden in editor
    private bool isPaused = false;

    // Use this for initialization
    void Start () {
        //place the camera and set the forward vector to match player
        theCamera.transform.forward = gameObject.transform.forward;
        //hide the cursor and lock the cursor to center
        Cursor.visible = false;
        Cursor.lockState = CursorLockMode.Locked;
    }

    // Update is called once per frame
    void Update () {
        //if escape key (default) is pressed, pause the game (feel free to change this)
        if (Input.GetButton("Cancel"))
        {
            //flip the isPaused state, hide/unhide the cursor, flip the lock state
            isPaused = !isPaused;
            Cursor.visible = !Cursor.visible;
            Cursor.lockState = Cursor.lockState == CursorLockMode.Locked ?
            CursorLockMode.None : CursorLockMode.Locked;
            System.Threading.Thread.Sleep(200);
        }

        if(!isPaused)
        {
            //if we are not paused, get the mouse movement and adjust the camera
            //position and rotation to reflect this movement around player
            Vector2 cameraMovement = new Vector2(Input.GetAxis("Mouse X"),Input.GetAxis("Mouse Y"));

            //first we place the camera at the position of the player + height offset
            theCamera.transform.position = gameObject.transform.position + new Vector3(0,heightOffset,0);

            //next we adjust the rotation based on the captured mouse movement
            //we clamp the pitch (X angle) of the camera to avoid flipping
            //we also adjust the values to account for mouse sensitivity settings
            theCamera.transform.eulerAngles = new Vector3(
                Mathf.Clamp(theCamera.transform.eulerAngles.x + cameraMovement.y * mouseSensitivityY, LOW_LIMIT, HIGH_LIMIT),
                theCamera.transform.eulerAngles.y + cameraMovement.x * mouseSensitivityX, 0);

            //then we move out to the desired follow distance
            theCamera.transform.position -= theCamera.transform.forward * followDistance;
        }
    }
}

```

# Answer
> 0 votes
Not sure I understand what you really need but I want to suggest two things:

1. Usually you should not move the camera with WASD (keyboard) in a Third Person Controller. You should move your player rotation based on the Mouse X axis during movement.

Example: if player is NOT moving your mouse should be able to move your camera (without moving the player) on Mouse X and Y axis (just remember to change player rotation based on your camera when you start moving). If player is moving your mouse should be able to move on Y axis but while moving on the X axis it should also rotate your player. So, if your player is moving forward with W if you use your mouse you should be able to rotate, if you only press D your player should be able to move right (but your camera should face forward).

2. If you really want to move your camera based on the WASD (like you should do with a joystick). You just need to rotate the camera by using the player rotation (the contrary of what you do in the first example), just remember that the camera rotate as a circle with the player as center.

For the script part: there are many ways to create a Third Person Controller (also lot's of already made scripts, Unity standard assets got one example that you can use to learn how to make your own), you should try to create a basic script and ask for more specific help when you tried to make it and it's not working (and debug until you find where is not working).

Still, just remember my advice. The key is to move the camera and rotate the player rotation based on the X Mouse axis or the camera rotation based on the player rotation as a center of a circle (always apply only when player is moving). Usually the first is great for mouse/keyboard movement, the last is great with joystick movement.

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


# Question
Title: How to set the AudioStreamPlayer to switch between tracks
**Conditional Music Playback**

What's important here is that I know how to switch the track that's being played back to another if some condition is met in the scene. If possible I also want to know where to store the other tracks.

I looked into the documentation and have yet to find a solution that allows me to for example:

* set the new track's file path and play it or...
* store the track names in maybe an array and set them for playback in the script. (still requires something to change the currently playing track)

How do I switch the tracks based on any condition?

# Answer
> 0 votes
**Set\_stream(track)**

where track is the audiostream object. It can be accessed by exporting the value with

```
export (AudioStream) var track

```

And then selecting the track in the inspector.

---
Tags: audio, music, godot
---


# Question
Title: Do meshes marked "shadows only" require light maps to block light?
I want to use an .fbx mesh to block light from entering a room (except for holes cut for windows). The mesh itself must stay invisible. I know marking it "shadows only" will hide it from the camera, but light still passes through it unless I mark the mesh as "lightmap static" as well. The problem is that this is a huge mesh that doubles the number lightmaps required, and it won't even be seen. Is there a better way to do this?

I am using the Lightweight Render Pipeline in Unity 2019.1.4f1 on Windows 10. Using CPU to render on an Intel Core i5 laptop.

# Answer
> 1 votes
Checked over the options again in the `Scene` panel of the `Lighting settings`. Figured out that solution is to set `Scale in Lightmap` from **1** to **0**. Hovering your mouse over this option even says that this will make it so the object does not receive light in the scene but still contributes to the lighting of other objects in the scene, which is exactly what I want.

---
Tags: unity, lighting, lightmap
---


title: Unity crossplatform native plugins

text:
# Question
Title: Unity crossplatform native plugins
I need to create a c++ native plugin for my game. If I want to support macOS and Windows, do I need to write my plugin twice - one in XCode with a bundle project and another in VS for windows or is there a way to support both with one codebase?

# Answer
> 1 votes
Native typically means that made for that target environment. I.e. native for iOS means it will only work on iOS. and native for Android or Windows means it will only run in its respective environment of Android or Windows.

There is no short cut here. The only exception being if you can get Unity directly to do what you need, or technically, if you can find an off the shelf solution that prevents you from having to program anything unique.

# Answer
> 2 votes
No you dont need separate code base for this. Most of the functionality will probably be the same anyways. Only small parts will have to be different between platforms. In this case you can use C++ macro exclusion blocks to switch these parts between the two.

This way you have a single code base then at compile time you define the proper pre-processor variables to determine which code will be compiled.

```
// generic code that is not platform specific

#ifdef MAC_BLOCK
// Mac specific code here
#endif

#ifdef WINDOWS_BLOCK
//windows specific code here
#endif

// non platform specific code again

```

The blocks of code that the define is not set will simply be ignored by the compiler.

---
Tags: unity, c++, plugin
---


# Question
Title: Unity3d OverlapSphere and raycasting problem
I have a grenade (rigidbody) which make a spherecast when it detonates. On each found colliders, i will make a raycast to check if it is visible to the grenade or not.

```
void Explode() {

    Collider[] colliders = Physics.OverlapSphere(transform.position, radius);

    foreach(Collider coll in colliders) {

        // when the collider belongs to a player..
        if(coll.transform.GetComponent<Player_Controller>() != null) {

            RaycastHit hit;

            // ..i want to check whether its behind an obstacle or not
            if(Physics.Raycast(transform.position, (coll.transform.position - transform.position), out hit)) {

                coll.transform.GetComponent<Player_Controller>().TakeDamage();

            }

        }

    }

    Destroy(gameObject);

}

```

My problem is i will get the collider for all players, but when i do the raycast from the grenade to the found collider, i only hit the environment i play in. So basically my map. The grenade is laying on the ground so maybe there is an error in my raycast direction.

**Edit**: I solved this, the raycast was pointing not at the very bottom of the collider instead a little bit below so it was under the ground. I havent seen it unless i draw a debug ray..

# Answer
The raycast was pointing not at the very bottom of the collider instead a little bit below so it was under the ground. I havent seen it unless i draw a debug ray. Because my character has an empty gameobject representing its head, i point at this instead to be sure its above the ground.
> 1 votes

---
Tags: unity
---


# Question
Title: Separating lighting for interior & exterior parts of a scene
I want outdoor areas connected with indoor areas. I use the default setup in Unity. But as you see in image, indoor point light affects the outdoor area (through the walls) and the skybox does more environment illumination in the indoor area.

How to fix that?

So, I want a skybox that only affects outdoor areas, and point lights that only affect interior areas.

# Answer
> 2 votes
The point light is shining through the wall because it doesn't have shadows turned on. To fix this, change the **Shadow Type** variable on the Light component to either **Hard Shadows** or **Soft Shadows**, depending on which one you like best. Also, make sure the walls, ceiling and floor have **Cast Shadows** and **Receive Shadows** on. This means the walls and ceiling will now block light from the point light from passing through.

The reason the Skybox affects the indoors is due to the **Ambient Light** in the scene. **Ambient Light** is light that is added to the object even when it's in shadow. To disable this:

* Open the Lighting window using **Window \> Lighting**
* Open the **Scene** tab
* Slide the **Ambient Intensity** slider all the way to zero.

This will disable the ambient lighting.

# Answer
> 1 votes
You could try these solutions:

1. You can set the wall objects `layer` to "Indoor" and uncheck the layers from point light's `Culling Mask` which you don't want that `Point Light` to affect (You should set your plane object's layer something not "Indoor" in your scene). Also uncheck the "Indoor" layer from the `Directional Light`'s culling mask property.
2. Use dynamic shadows to compensate the areas you dont want to be affected by some specific lights, which is completely the hardest solution to implement for this problem.
3. Try not to use point light. And you should decide which other one could be used for your desires.

And there are other solutions for Unity Pro but I guess you are using not that one. If you do, check this page for further info. Hope this helps!

# Answer
> 0 votes
Just wanted to add more additional info to this thread. If you happen to be working on an interior and the mesh / wall is solid on the inside but transparent on the outside, light will pass through the mesh illuminating the interior unless you switch the Cast Shadows box to 'Two Sided'. This will block light from passing through the open sides of a mesh.

---
Tags: unity, lighting
---


# Question
Title: Can games be made with Win32 for Windows 10?
Based on the news today of Microsoft allowing Win32 games on the Windows store, what does it mean that Win32 can be used for games now? Couldn't Windows 10 already play Win32 games? or is this solely for distribution over the Window Store that is important?

Couldn't Windows 10 already play Win32 games? What were developers using if it wasn't Win32 on Windows 10 (UWP?)

Quoted in many articles, but here is the original,

https://news.xbox.com/en-us/2019/05/30/microsoft-approach-to-pc-gaming/

# Answer
You could always make games for Windows 10 using the Win32 API, yes.

What you could *not* do was distribute those games on the Microsoft Store. Microsoft Store products had to be made with UWP.

The linked announcement is saying (among the Game Pass things) that Microsoft will be enabling a mechanism by which you can distribute Win32 games via the Microsoft Store.
> 3 votes

---
Tags: windows, win32
---


# Question
Title: How to call an event of level blueprint from NPC blueprint?
**I have the following situation:**

1 NPC that follows a path containing 3 parts. **Target Point 1**, **Tower** and **Target Point 2**.

It turns out that the first NPC that passes through the tower destroys it.

This destruction is not instantaneous. The tower has 100 hit points and while in contact with the NPC, it loses 10 life points every second.

With this, the next NPCs will only have to go to **Target Point 1** and finally to **Target Point 2**.

I created a boolean variable for target control (`varTowerDestroyed`). So if it is false, the second target becomes the **tower**, otherwise it becomes the **target point 2**.

**Blueprint showing the variable (varTowerDestroyed) being set to true, right after the tower's destruction:**

**Display of the control in the target definition:**

It turns out that each NPC has its own variables, so there's no use in defining the value of the variable of just one of them. I would need a variable that would control all at the same time.

**I thought of doing the verification based on a variable of the own tower, but as the tower will be destroyed, I imagine the variable will disappear. Impossible to verify:**

**At the Level Bueprint I created an event that will be called soon after the tower's destruction. This event will set the Boolean variable to true, setting all Boolean variables of the NPCs that are created and still generated to be true:**

I would calmly call an event if the event was in the blueprint of the tower, but being on the blueprint level I was unsuccessful.

I thought about using the sleep function. I also thought about creating an actor who was sort of an actor manager (I still want to, but only when I start using HUD). I also thought about doing a check of the existence of tower actors, but this I do not know how to do.

**Links from places I searched:**

https://answers.unrealengine.com/questions/78622/how-can-i-call-an-event-in-my-level-blueprint-from.html

https://answers.unrealengine.com/questions/702964/how-can-i-call-a-event-from-actor-blueprint-in-lev.html

---

**EDIT 1 (Attempt made based on 2 videos I've seen)**

**Link of videos:**

https://www.youtube.com/watch?v=k-MAALv3P-Y

https://www.youtube.com/watch?v=IbiocEDwosw

I tried to use the **Event Dispatcher**.

I created an **Event Dispatcher called Disp**, in the **NPC blueprint**.

Soon after I set it on the Level Blueprint.

**Level Blueprint:**

Nothing happens, nor the impression.

# Answer
> 0 votes
**Create a Interface Blueprint:**

**Create a function in the Blueprint Interface:**

**Add the interface to the actors you want to communicate with the Level Blueprint:**

**Calling the event (NPC blueprint):**

**Defining the event (Level Blueprint):**

---

**I've also tried using the event, but it's not possible to use it in this case since there is no NPC already entered at the level, they are spawned. In this way, an error in referencing occurs.**

---
Tags: unreal-4, events, blueprints
---


# Question
Title: Prevent Wall Clipping with Bouncing Shape
I'm currently working on a demo-type program involving bouncing objects. Currently, I have a rectangle that can bounce around the screen.
When the rectangle bounces against one of the walls imperfectly, part of it will clip into the side of the window (or other objects, in the future).
I'd like to have the rectangle bounce from an accurate position (as in when/where it begins to collide with the object). Is there a better or more efficient way to do this other than by going back a step and checking over again with smaller steps?

The relevant code is here, and for reference the rectangle's velocity is stored as an angle and speed.

```
    //Update position
    rect.setX(rect.getX() + (rect.getVelocity() * Math.cos(rect.getDirection())));
    rect.setY(rect.getY() + (rect.getVelocity() * Math.sin(rect.getDirection())));

    //Check for collisions
    for(Collider c : colliders) {
        if(c.isColliding(rect)) {
            bounce(rect, c);
            System.out.printf("Rect is colliding with %s%n", c);
        }
    }

```

Any help would be appreciated.

# Answer
> 0 votes
Although the updated version of the question hasn't been answered, I figured out a solution to the original question. The updated code is here:

```
    //Update position
    double delX = rect.getVelocity() * Math.cos(rect.getDirection()),
           delY = rect.getVelocity() * Math.sin(rect.getDirection());

    rect.setX(rect.getX() + delX);
    rect.setY(rect.getY() + delY);

    //Check for collisions
    for(Collider c : colliders) {
        if(c.isColliding(rect)) {
            //We found a collision, so now we need to do smaller steps.
            rect.setX(rect.getX() - delX);
            rect.setY(rect.getY() - delY);

            double sDelX = Math.cos(rect.getDirection()),
                   sDelY = Math.sin(rect.getDirection());

            //Loop over small steps (with velocity 1)
            while(!c.isColliding(rect)) {
                rect.setX(rect.getX() + sDelX);
                rect.setY(rect.getY() + sDelY);
            }

            bounce(rect, c);
            System.out.printf("Rect is colliding with %s%n", c);
        }
    }

```

---
Tags: java, movement, objects, clipping
---


# Question
Title: *Python* Class - self.x = self - What does it mean to set it to self?
I have this class for my game that is a scene manager. I followed a tutorial and I am confused on why the self.scene.manager is equal to self

```
class SceneManager(object):
    def __init__(self):
        self.go_to(TitleScene())

    def go_to(self, scene):
        self.scene = scene
        self.scene.manager = self #<--

```

In the main game scene I also have a similar thing happening

```
class GameScene(Scene):
    def __init__(self, levelno):
        super(GameScene, self).__init__()
        self.player = Player(5, 40)
        self.player.scene = self

```

What is the purpose of setting it to self?

Another Question: I have been using classes and for most of them I create a class and I include this within the class

```
Class myClass():
   super(myClass, self).__init__() #<----- This line here

```

Does this have something to do with my original question? What is the purpose of doing this?

# Answer
> 1 votes
When you use something like `self.foo.bar = self` from the class `bar`, you're telling `foo` which `bar` it is linked to. Basically,

```
    self.scene = scene
    self.scene.manager = self

```

is used to set reference in both ways, so that from the SceneManager, you can know which scene is managed, and from the scene, you can get access to the scene manager through the `manager` variable.

> Does this have something to do with my original question? What is the purpose of doing this?

No. Presumably, your current code looks more like this:

```
class myBaseClass:
    def __init__(self):
        # initialize stuff

class myClass(myBaseClass):
    def __init__(self):
        super(myClass, self).__init__()
        # initialize more stuff

```

According to the documentation, what you're actually doing here is calling the `__init__()` method of a parent class; i.e. you're calling the constructor of the parent. You do it like that because since you define the function in both classes, the one defined in the child class (`myClass`) *overrides* the one from the parent class (`myBaseClass`), i.e. it *hides* it. To "force" the usage of the parent's class, using `super` like that seems the way to go.

---
Tags: python, pygame
---


# Question
Title: How can I make a look around effect of the player some kind of cutscene?
I want that at some point in the game the player will be looking over the view out of the window. So I added a new Camera and positioned the camera close to the window. Then using a small script I'm turning the Camera on.

But after turning the camera on I wan to make that the camera will rotate around the window area so it will give a natural feeling that the player is looking over the view outside.

And the script that is attached to another GameObject that activating the Camera:

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

public class ItemAction : MonoBehaviour
{
    public Camera viewCamera;

    private void Update()
    {

    }

    public void ViewCamera()
    {
        viewCamera.enabled = true;
    }
}

```

The part I'm using is the ViewCamera method. But I messed it up. But the idea is after turning on the Camera to make it feel like looking around the view outside.

How can I make the camera move first to one direction and then mirrored to the other direction ?

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

public class ItemAction : MonoBehaviour
{
    public Camera viewCamera;
    public float Speed;

    public void ViewCamera()
    {
        viewCamera.enabled = true;
        StartCoroutine(animate());
    }

    IEnumerator animate()
    {
        while (transform.localEulerAngles.y > -45)
        {
            transform.Rotate(0, -Time.deltaTime * Speed, 0);
            yield return null;
        }
        //and then possibly the same but mirrored to look in the other direction
        while (transform.localEulerAngles.y < 45)
        {
            transform.Rotate(0, Time.deltaTime * Speed, 0);
            yield return null;
        }
    }
}

```

The way it is now it's just keep rotating to the same direction nonstop.

# Answer
The easiest is probably to attach an Animator component to your camera, create an animation for it and then you can add keyframes to change the camera's yaw (and possibly position as well which could make it look more natural). From your script, grab the Animator component and trigger the animation, then return to the main camera once it's over (presumably).

Another approach could be setting up a simple coroutine to do that yourself; you'd have more control over the animation, but less freedom, so it might end up looking quite rigid. I'm talking about something like this:

```
IEnumerator animate(){
        while(transform.localEulerAngles.y > -45){
                transform.Rotate(0,-Time.deltaTime*Speed,0);
                yield return null;
        }
        //and then possibly the same but mirrored to look in the other direction
}

```
> 1 votes

# Answer
localEulerAngles doesn't return negative numbers. so you have to do some calculation on it before checking if its greater than -45 because if you don't, it will always be greater than -45 or any other negative number.

```
IEnumerator animate(){
    float angle = getRealAngle();
    while (angle > -45)
    {
        thisTransform.Rotate(0, -Time.deltaTime * speed, 0);
        angle = getRealAngle();
        yield return new WaitForEndOfFrame();
    }
    while (angle < 45)
    {
        thisTransform.Rotate(0, Time.deltaTime * speed, 0);
        angle = getRealAngle();
        yield return new WaitForEndOfFrame();
    }
}
float getRealAngle(){
    float angle = thisTransform.localEulerAngles.y;
    angle = (angle > 180) ? angle - 360 : angle;
    return angle;
}

```

It's always a good idea to `Debug.Log` values like this to keep track of what is actually happening.

```
void Update(){
    Debug.Log(thisTransform.localEulerAngles.y + " / " + getRealAngle());
}

```
> 0 votes

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


title: Magicavoxel export to Unity offcenter

text:
# Question
Title: Magicavoxel export to Unity offcenter
I am trying to export an object from Magicavoxel to Unity. I have exported it as an `obj` file and dragged it into the scene, but it is completely off centered compared to other objects.

For example, in the image below you can see the object I imported to the top left and a simple box in the middle. Both objects have a `transform.position` of 0,0,0. However, you can clearly see that the objects don't overlap. Is there a way to fix this?

# Answer
> 1 votes
I managed to fix this issue myself.

First, I pressed `tab` to switch to the `World editor`. In there, I moved the object down and into the negative axis so it would line up perfectly. The 2 objects are now within each other for me.

---
Tags: unity, importing, magicavoxel
---


title: Draw trajectory arc predictor in game

text:
# Question
Title: Draw trajectory arc predictor in game
I found this tutorial on youtube and it works pretty well, but I want to add more to it.

How can I draw a smooth arc path in the game view (right now the path is only visible in the editor)?

Here is the code:

```
public class BallLauncher : MonoBehaviour
{

    public Rigidbody ball;
    public Transform target;

    public float h = 25;
    public float gravity = -18;

    public bool debugPath;

    void Start() {
        ball.useGravity = false;
    }

    void Update() {
        if (Input.GetKeyDown (KeyCode.Space)) {
            Launch ();
        }

        if (debugPath) {
            DrawPath ();
        }
    }

    void Launch() {
        Physics.gravity = Vector3.up * gravity;
        ball.useGravity = true;
        ball.velocity = CalculateLaunchData ().initialVelocity;
    }

    LaunchData CalculateLaunchData() {
        float displacementY = target.position.y - ball.position.y;
        Vector3 displacementXZ = new Vector3 (target.position.x - ball.position.x, 0, target.position.z - ball.position.z);
        float time = Mathf.Sqrt(-2*h/gravity) + Mathf.Sqrt(2*(displacementY - h)/gravity);
        Vector3 velocityY = Vector3.up * Mathf.Sqrt (-2 * gravity * h);
        Vector3 velocityXZ = displacementXZ / time;

        return new LaunchData(velocityXZ + velocityY * -Mathf.Sign(gravity), time);
    }

    void DrawPath() {
        LaunchData launchData = CalculateLaunchData ();
        Vector3 previousDrawPoint = ball.position;

        int resolution = 30;
        for (int i = 1; i <= resolution; i++) {
            float simulationTime = i / (float)resolution * launchData.timeToTarget;
            Vector3 displacement = launchData.initialVelocity * simulationTime + Vector3.up *gravity * simulationTime * simulationTime / 2f;
            Vector3 drawPoint = ball.position + displacement;
            Debug.DrawLine (previousDrawPoint, drawPoint, Color.green);
            previousDrawPoint = drawPoint;
        }
    }

    struct LaunchData {
        public readonly Vector3 initialVelocity;
        public readonly float timeToTarget;

        public LaunchData (Vector3 initialVelocity, float timeToTarget)
        {
            this.initialVelocity = initialVelocity;
            this.timeToTarget = timeToTarget;
        }

    }
}

```

I found a way to Instantiate projectile along the path. Now I just need to know how to convert that line in debug mode to make it visible in game mode

# Answer
> 1 votes
This draws a lineRenderer instead of Debug:

```
public Rigidbody ball;
public Transform target;
public float h = 25;
public float gravity = -18;

public bool debugPath;

// Added Code
public LineRenderer lineRenderer;

void Start() {
    ball.useGravity = false;

    // Added Code
    lineRenderer.transform.position = ball.transform.position;
}

void Update() {
    if (Input.GetKeyDown (KeyCode.Space)) {
        Launch ();
    }
    if(debugPath)
        DrawPath ();
}

void Launch() {
    Physics.gravity = Vector3.up * gravity;
    ball.useGravity = true;
    ball.velocity = CalculateLaunchData ().initialVelocity;
}

LaunchData CalculateLaunchData() {
    float displacementY = target.position.y - ball.position.y;
    Vector3 displacementXZ = new Vector3 (target.position.x - ball.position.x, 0, target.position.z - ball.position.z);
    float time = Mathf.Sqrt(-2*h/gravity) + Mathf.Sqrt(2*(displacementY - h)/gravity);
    Vector3 velocityY = Vector3.up * Mathf.Sqrt (-2 * gravity * h);
    Vector3 velocityXZ = displacementXZ / time;

    return new LaunchData(velocityXZ + velocityY * -Mathf.Sign(gravity), time);
}

void DrawPath() {
    LaunchData launchData = CalculateLaunchData ();

    // Added Code
    lineRenderer.positionCount = 1;
    lineRenderer.SetPosition(0, ball.position);

    int resolution = 30;
    for (int i = 1; i <= resolution; i++) {
        float simulationTime = i / (float)resolution * launchData.timeToTarget;
        Vector3 displacement = launchData.initialVelocity * simulationTime + Vector3.up *gravity * simulationTime * simulationTime / 2f;
        Vector3 drawPoint = ball.position + displacement;

        // Added Code
        lineRenderer.positionCount ++;
        lineRenderer.SetPosition(lineRenderer.positionCount-1, drawPoint);
    }
}

struct LaunchData {
    public readonly Vector3 initialVelocity;
    public readonly float timeToTarget;

    public LaunchData (Vector3 initialVelocity, float timeToTarget)
    {
        this.initialVelocity = initialVelocity;
        this.timeToTarget = timeToTarget;
    }

}

```

---
Tags: unity, c#, projectile-physics, curves
---