# Question
Title: How do I debug Azure Spatial Anchors with Unity on an Android device?
I've been building an AR app that's already been a pain to debug, because instant preview refuses to work over wifi and usb debugging causes the phone camera to not display on the phone itself. Now I'm at the point where I can integrate Azure Spatial Anchors and I cannot seem to be able to be able to play in the editor. I receive the message:

DllNotFoundException: azurespatialanchorsndk Microsoft.Azure.SpatialAnchors.CloudSpatialAnchorSession..ctor () (at Assets/AzureSpatialAnchorsPlugin/Plugins/Common/AzureSpatialAnchorsBridge.cs:6864) SpatialAnchors.GetCloudManager () (at Assets/Scripts/SpatialAnchors.cs:60) tester.Start () (at Assets/tester.cs:18)

# Answer
That error message you have looks like one I saw last week, but I was not using the ARCore Instant Preview. But maybe this is still relevant?

It sounds like your situation is that the Azure Spatial Anchors NuGet package did not install into the Visual Studio solution like it was supposed to. It's possible this bug occurred because your Azure Spatial Anchor packages were added after the Visual Studio solution was already built out?

The workaround I found was to manually install the NuGet package. You can resolve the issue by manually installing it through the NuGet website.

You may also use Visual Studio's Package Manager Console to do it like this:

`Install-Package Microsoft.Azure.SpatialAnchors.WinCPP -Version 1.1.1`
> 1 votes

---
Tags: unity, c#, android, cloud-computing
---


# Question
Title: Nonsense error when increasing LightSource angle?
My project has a **Light Source** and a **Sky Sphere Blueprint**.

The rotation on the y axis (Light Source) defines the position of the sun (Sky Sphere Blueprint).

**Character Blueprint (increases by 10 degrees on the y-axis rotation of Light Source, the updates the position of the sun):**

**When you click the button (Angulo, circled in pink), the angle increases by 10 and works to a certain moment:**

**Image with angle increased by 10:**

**When it reaches 100 degrees, it starts to go wrong. Each time I click the button it goes from 90 to 100 and vice versa in an infinite loop:**

I've already tried to turn it around, subtracting instead of adding, but at one point it also gives error (in the case with 110 degrees).

# Answer
> 0 votes
Based on **@DMGregory** comment and also on his answer given in another question.

**Question link where he gave the answer that helped me:**

Why rotating an object only on its local X axis result in sudden 180 degrees changes in Y and Z axis rotation values

I stopped using the value coming from the rotation of **Light Source**. I have stored the desired value in a variable and set it directly in the rotation of the **Light Source**.

**First I did a test using a switch and it worked:**

**To optimize this, I used a structure and a data table:**

---
Tags: lighting, unreal-4, angles
---


title: LibGDX/Tiled rendering order

text:
# Question
Title: LibGDX/Tiled rendering order
I'm using LibGDX and Tiled. I need to render a Texture for my repeated background, then myTiled map and finally the sprites.

My problem is that if I put `mapRenderer.render()` between `batch.begin()` and `batch.end()`, the background texture is not being rendered. If I render the map before or afterthe batch, some objects are hided.

So the logic of what I want to do is:

```
public void render(float delta) {
  // update

  // clear screen

  batch.begin();

  // draw repeated background texture

  // draw map
  mapRenderer.setView(camera);
  mapRenderer.render();

  // draw sprites

  batch.end();
}

```

Any idea what I might be missing and how to fix it?

**Edit**

Followup question, to make sure that what I'm asking is valid. I was under the impression that calling `batch.begin()` and `batch.end()` multiple times was inefficient. But from what I've been searching it seems that it's not. I was confusing it with creating more than one SpriteBatch. So I guess it's fine to do more then one begin/end call in each frame? Sorry if my question is trivial, but I'm new to LibGDX.

# Answer
> 0 votes
In this case, there is no other solution than to call it multiple times. That is, to render your background, the map, and the sprites.

I assume all of them have different textures anyway, so there won't be any performance difference.

```
batch.begin();
// draw repeated background texture
batch.end();

// draw map
mapRenderer.setView(camera);
mapRenderer.render();

batch.begin();
// draw sprites
batch.end();

```

---
Tags: libgdx, tiled
---


# Question
Title: Animation is not starting even though collider is triggered?
progress is steady but it is a bumpy road. I have removed the animation script from my character and reworked it into the controller script. I have also added new animations. Doing this required replacing the character FBX I was using earlier.

Doing this has caused an unexpected problem: Remember that super-cool item box that I made, that the character can trigger when he jumps under it, causing it to play an animation where the lid pops off? Well, that's broken now. The box's idle animation still plays, but the GetItem animation does not. Before importing the new character, his animations and the box's animations were in the same animation controller. I separated them into their own controllers, and applied them each where they belong. I did not make any more changes ( you can see all its properties in the demos below). There are still no transitions or parameters for the ItemBox. Funny enough, I tested it and the ItemBox's trigger is being activated. What could be wrong?

Video links (SHORT):

Link to video of new character demo

Link to Animators Panels Video

How can I get the GetItem animation to play for my itemBox again?

whoops, here is the relevant script:

ItemBox.cs:

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

public class ItemBox : MonoBehaviour
{
    // Start is called before the first frame update

    bool disabled = false;
    Animator anim;

    void Start()
    {
        anim = GetComponentInChildren<Animator>();
        if (!disabled)
        {
            anim.Play("ItemBox_Idle");
        }
    }

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

    }

    void OnTriggerEnter (Collider other)
    {
        if (!disabled && other.gameObject.tag == "Player")
        {
            print("itembox triggered");
            anim.Play("ItemBox_GetItem");
            disabled = true;
        }
    }
}

```

\**This is the heirarchy for the ItemBox prefab. Notice that animation frames can only be seen from first child ("Parent") of that prefab, downward: \**

**UPDATE!** GetItem animation is playing in the animation graph while I play the game, hitting the box from below, but the animation doesn't play in the game! The plot thickens! See (shorter) video:

shorter video

# Answer
> 1 votes
I fixed it.

With elbow grease and magic.

There were some complications that contributed to this problem:

* First, the prefab consist of an empty called "parent" and 4 children under that (so there are 5 objects inside the prefab). It is "parent" WITHIN the prefab that contains the animations. In the original working version, I had the trigger, script, and regular collider at the top level of the prefab and the animation controller attached to "parent". This was weird from the start but I still don't know why it suddenly STOPPED working just by re-importing the character.
* What worked was moving all 3 components (script, trigger, and plain-old box collider) to "parent" which already has the animator attached to it. After doing this, none of the animations could be seen playing live in the Animator panel anymore, but the idle animation still played. I got lucky on one of my jumps and activated "GetItemState" animation in the Game. This meant that on top of all the problems I knew I had, I also had to enlarge the trigger again to make activation reliable. So I shrunk the plain box-collider by 1/10, moved it up, and scaled the depth of the trigger so my character would be reliably read as passing through it.

+ Checking "apply root motion" had effects when other components were at the top level, sometimes moving the prefab instance to the origin during preview, but had no effect at all after every component got moved to "parent".

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


# Question
Title: Rendering to Texture with Transparency in Monogame?
Please forgive me if I'm asking a question that has been answered before, but for the life of me, search as I might, I couldn't find a problem exactly like this anywhere.

I'm trying to render a series of sprites, all sourced from transparent PNGs, to a texture. Each of these rendered textures would be layers in a 2D environment which could be subjected to shaders/effects before being placed on the screen.

My problem is that when I try this, the screen fills with black, and only the last texture rendered is visible.

I have tried: * clearing the graphics device after setting my render target, using color.transparent. * every surface format (those formats mean nothing to me at this interim)

I am new to this particular environment, so I am probably missing something that I can't easily look up.

# Answer
> 1 votes
Turns out, while no documentation I've seen backs this up, that if you throw a texture2D directly at the screen via rendertarget being null, it gets wiped out by any RenderTargets you draw via SpriteBatch.Draw(). I've never encountered this in any other platform, but I also haven't used every platform in the universe, so this could be more commonplace than I would initially think.

Feel free to correct me if this is a symptom of something I'm missing, but problem solved regardless.

---
Tags: monogame, transparency, rendertexture
---


# Question
Title: Instant Animation Transitions? Nothing I read about is working
re-imported my character today with 3 new animations (JumpStartState, JumpDownState, JumpEndState) and moved all animation code into the PlayerController script. All of my animations are handled by transitions and their parameters in the Animator. The controls are very responsive but I can't get the transitions to end immediately before before an animation plays out.

I can make the character jump instantly after hitting the ground from a previous jump (a la *Mario 64*), but his animation is delayed until the landing animation finishes. This is the most notable example of animation not being responsive.

I have read through forums going back to 2011 trying to find a solution to this problem and everyone says either "un-check 'Has-Exit-Time'," "set 'Exit Time' to zero," or "move the blue bars close together (same thing, by the way)". None of that has worked for me. Most of the time there was no difference at all; Other times my character would just skate frozen through the scene like a cardboard Frosty (animation stalls on start).

I have a link to a NEW short demo where I bounce my player around the room while the animation graph is giving live feedback here (01:50):

Character Animation Graph Live with Preview

**EDIT:** Looking at the footage, maybe there is an animation "kink" between the "JumpDownState" and "JumpEndState" that is happening at least half the time but even when it doesn't, the animation must play through for the next to start.

I am attaching my code just in case:

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

public class PlayerController : MonoBehaviour
{

    private float charSpeed;
    public float walkSpeed;
    private float runSpeed;
    public float jumpForce;
    private float coyoteTime = 0;
    private const float MAXCOYOTETIME = 0.1f;
    private float currentHeight;
    private float previousHeight;
    private float travel;
    public CharacterController controller;
    private Animator animator;
    public float gravityScale;
    private Rigidbody rb;

    public static Vector3 moveDirection;

    // Start is called before the first frame update
    void Start()
    {
        controller = GetComponent<CharacterController>();
        rb = GetComponent<Rigidbody>();
        animator = GetComponent<Animator>();
        charSpeed = walkSpeed;
        runSpeed = walkSpeed * 2;
        previousHeight = currentHeight;
    }

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

        currentHeight = transform.position.y;
        travel = currentHeight - previousHeight;
        if (Input.GetButton("Fire3"))
        {
            charSpeed = runSpeed;
            animator.SetBool("isRunning", true);
        }
        else
        {
            charSpeed = walkSpeed;
            animator.SetBool("isRunning", false);
        }

        // Declare movement vector
        moveDirection = new Vector3(Input.GetAxis("Horizontal") * charSpeed,
            moveDirection.y,
            Input.GetAxis("Vertical") * charSpeed);

        // Set y-axis movement conditions (jumping, grounded, free-fall)
        #region jumping
        if (IsGrounded() && Input.GetButton("Jump"))
        {
            animator.SetBool("isJumping", true);
            moveDirection.y = jumpForce;

        }

        else if (IsGrounded() == false)
        {
            moveDirection.y = moveDirection.y + Physics.gravity.y * gravityScale * Time.deltaTime;
            if (moveDirection.y < 0)
            {
                animator.SetBool("isJumping", false);
                animator.SetBool("isFalling", true);
                if (travel == 0 && Input.GetButton("Jump"))
                {
                    animator.SetBool("isJumping", true);
                    animator.SetBool("isFalling", false);
                }
            }
        }
        #endregion
        if (travel == 0)
        {
            animator.SetBool("isFalling", false);
            animator.SetBool("isJumping", false);
        }

        // rotated 45 deg to align controls to camera instead of world space:
        Vector3 rotated = Quaternion.Euler(0, -45, 0) * moveDirection;
        controller.Move(rotated * Time.deltaTime);

        if (Input.GetAxis("Horizontal") == 0 && Input.GetAxis("Vertical") == 0)
        {
            animator.SetBool("isMoving", false);
        }
        else
        {
            animator.SetBool("isMoving", true);
        }

        Vector3 lookDir = new Vector3(rotated.x, 0, rotated.z);

        if (lookDir != Vector3.zero)
        {
            transform.rotation = Quaternion.LookRotation(lookDir);
        }

        previousHeight = currentHeight;
    }

    public bool IsGrounded()
    {
        return coyoteTime < MAXCOYOTETIME;
    }

    void LateUpdate()
    {
        if (controller.isGrounded)
        {
            coyoteTime = 0;
        }
        else
        {
            coyoteTime += Time.deltaTime;
        }
    }
}

```

**EDIT: IRONING OUT THE LAST WRINKLE! NEW DEMO!**(6:30 or less)

Excited to say that all animations proceed immediately now except that repeated jump. Still, half the time the transition to a new jump doesn't happen at all. New footage of improved movement though, plus further description of problem:

Snappier Locomotion; Ironing out the last wrinkle!

# Answer
> 2 votes
From Screen shot its look like the animation transition has some value to "Transition duration(%)" and also I guess "Fixed duration" is checked.

So My suggestion is to set "Transition duration(%)" to 0 also uncheck the "Fixed duration" and "Has Exit" Check boxes as shown in the screen shot. I hope it works, Cheers!

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


# Question
Title: Libgdx actions to image is applied to whole actors
I am trying to make the Image hidden then fade in and this is working but the background image is also become hidden the fade in : here where I apply the action in this class:

```
   public class MainButtons {
    public Viewport viewport;
    public Stage stage;
    public boolean centerPressed;

    public Image fire;
    public Image center;
    public Sound flap;

    public OrthographicCamera camera;
    public static Table table;

    //Constructor.
    public MainButtons(SpriteBatch spriteBatch) {
        camera = new OrthographicCamera();
        viewport = new StretchViewport(KidTele.V_WIDTH,KidTele.V_HIEGH,camera);
        stage = new Stage(viewport, spriteBatch);
        //InputMultiplexer this is why only input handling  from controller
        flap= Gdx.audio.newSound(Gdx.files.internal("one.mp3"));
        Gdx.input.setInputProcessor(stage);

        fire= new Image(new Texture("cars/fire.png"));

        //buttonone.setSize(10, 5);

        menuTable();
        defineCenter();

    }
    public void defineCenter()
    {
        center=new Image(new Texture(Gdx.files.internal("0.png")));

        center.setBounds(viewport.getWorldWidth() / 5f, viewport.getWorldHeight() / 3f, viewport.getWorldWidth() / 1.5f, viewport.getWorldHeight() / 3f);
        center.addListener(new InputListener() {
            @Override
            public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
                centerPressed = true;
                return true;
            }

            @Override
            public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
                //center.setOrigin(center.getWidth()/2,center.getHeight()/2);
                //center.addAction(Actions.sequence(Actions.rotateTo(360, 2), Actions.fadeIn(1)));
                center.addAction(Actions.sequence(Actions.fadeOut(1), Actions.fadeIn(1)));
                centerPressed = false;
            }
        });
        //center.setVisible(false);
        stage.addActor(center);
    }
    public void draw() {
        stage.draw();
    }
    public void resize(int width, int height) {
        viewport.update(width, height);
    }
}

```

and this is the code of the screen:

```
public class PlayScreen implements Screen {
    private KidTele game;
    private OrthographicCamera gamecam;
    private Viewport gameport;
    private World world;
    private Box2DDebugRenderer b2dr;
    private MainButtons mainButtons;
    private Texture background;
    private Sound flap;
    public PlayScreen(KidTele game)
    {
        this.game=game;
        gamecam=new OrthographicCamera();
        gameport=new StretchViewport(KidTele.V_WIDTH,KidTele.V_HIEGH,gamecam);
        //stage=new Stage(gameport,((KidTele) game).batch);
        background=new Texture("background2.png");
        gamecam.position.set(gameport.getWorldWidth()/2f,gameport.getWorldHeight()/2f,0);
        b2dr=new Box2DDebugRenderer();
        world=new World(new Vector2(0,0.8f),true);
        flap= Gdx.audio.newSound(Gdx.files.internal("one.mp3"));
        mainButtons=new MainButtons(game.batch);
    }
    @Override
    public void show() {

    }
    public void handleinput(float dt)
    {

        if(Gdx.input.isKeyJustPressed(Input.Keys.BACK)) {
            mainButtons.stopMusic();
            game.setScreen(new PlayScreen(game));
        }

    }
    public void update(float dt)
    {
        handleinput(dt);
        world.step(1 /60f, 6, 2);
        //player.update(dt);

        gamecam.update();
    }

    @Override
    public void render(float delta) {

        update(delta);
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

         b2dr.render(world, gamecam.combined);
        game.batch.setProjectionMatrix(gamecam.combined);

        game.batch.begin();

        game.batch.draw(background, 0, 0, gameport.getWorldWidth(), gameport.getWorldHeight());
        game.batch.end();
        mainButtons.stage.act();
        mainButtons.stage.draw();
        mainButtons.draw();
    }

    @Override
    public void resize(int width, int height) {
        gameport.update(width, height);
        mainButtons.resize(width, height);
    }

```

Also when I apply the rotation Action (which is commented) it rotates the image only one time although I put it on the event Touchup, while the fading in and out is applied on each touch but fading applied on image and background

# Answer
Set batch color to default every frame. This is partial solution.

```
public void render(float delta) {
    batch.setColor(1, 1, 1, 1);
    // ...

```

In case of your (stage) example:

```
public void draw() {
    stage.getBatch().setColor(1, 1, 1, 1); //add this line
    stage.draw();
}

```

Also sometimes is good to set Actions.alpha(0) at start of animation.

```
center.addAction(Actions.sequence(Actions.alpha(0), Actions.fadeOut(1), Actions.fadeIn(1)));  //Used in LibGDX dialog.show method

```

Another source: https://stackoverflow.com/questions/38113003/libgdx-actions-to-image-is-applied-to-whole-actors
> -1 votes

---
Tags: java, android, libgdx
---


title: How should the player unlock things?

text:
# Question
Title: How should the player unlock things?
Imagine a mobile phone game that is meant to be played in short sessions (5-10 mins). You can choose one out of many characters, and each character slightly alters the way the game plays.

Those characters are all locked and have to be unlocked by purchasing them with in-game money.

**Should the player be able to choose which one to unlock?**

Besides the obvious benefit of being able to **choose** who you want to unlock, the downside of this method is that players often end up having **choice paralysis**: With tons of characters to choose from, the player will just not bother reading every character's pros and cons and make a choice.

**Should the player just be able to unlock a random character?**

This is a more casual friendly method, as the player will just spend their in-game money without thinking because there's no other options. The downside of this is that paying for a character that doesn't suit your playstyle may feel bad.

**Other solutions?**

Maybe you have another solution on your mind? Note that some characters make the game more **high risk/high reward**, aimed for veteran players, while other characters just make the game easier to play.

# Answer
> 24 votes
The practice of letting the player pay to receive random rewards has gotten a lot of bad press lately because it preys on gambling instincts and is customer-unfriendly because the customer who wants one specific piece of content doesn't know how much money they have to spend for it. But large, profit-optimized companies like EA wouldn't do this if it wouldn't be profitable. Do you want to join the dark side? We can not make moral decisions for you.

If you are afraid that giving the player too many options might cause choice paralysis, then there are a couple solutions you can try:

* Give the player an opportunity to try out content before they buy. That way they can make a more informed decision about what to buy. Some approaches to this I have seen are:
    + A "training mode" were all unlockables are available and can be experimented with, but there is no real core gameplay.
    + A "free character of the week" which is available to all players, but only for a limited time. If they want to keep playing the character after that time window, they have to buy it.
    + A mechanic to switch to the character of the opponent who just defeated you for one round, even if you didn't unlock that character yet. Also has the positive side-effect that it is an anti-frustration feature.
* Inform the players well about which characters might suit their playstyle. This is mostly a matter of UI design and communicating their pros and cons properly.
* Limit the choices the player can do by some kind of choice tree or by hiding each character behind some achievements the player has to complete in order to be allowed to play that character (you might want to consider to make them pay extra for overriding the prerequisites if they really, really want a specific character).

# Answer
> 6 votes
I would point out that there are ways you can build in-game systems to address both of your concerns.

**Choice Paralysis**

Your first stated concern was with the route of choosing your character, as is may cause choice paralysis. **This can be solved by adding filters to facilitate player choices**. You could allow for search queries that show you characters who have specific pros and lack specific cons, etc. This is beneficial for a number of reasons:

1. Looking through the search options will give the player a general ideas of the types of pros/cons (s)he can unlock, prompting them to start recognizing what strategies are feasible and conceptualize how to implement them, even before they reach "veteran" level.
2. If a player wants to test a certain strategy but lacks the deck to do so, (s)he can obtain the characters (s)he needs in a comparatively short and simple process than had the search option not been present.

**Randomness**

The reason you gave for leaning towards randomness at all was that it would be a quick and easy way for casual players to get a new character and move on. But this ease can easily be preserved in a player-choice system **by adding a "Unlock Random Character" button!**

In fact, if you were to combine the aforementioned search query with the random button, allowing the player to say, "select a random character with this pro/without this con," you can even avoid the potential scenario in which a player pays for a character that does not suit his/her playstyle, even if they let the computer choose a character for them.

# Answer
> 3 votes
Do you have evidence of choice paralysis? Did you run play tests this?

Let us assume you did test it, and found this result...

I will not suggest to hide characters. That can also lead to some other predatory practices (loot-boxes are not the only bad thing out there). In fact, many people enjoy shopping. If the decision is hard, it could spark a community of character reviews in social media, that is all good.

Furthermore, I would like to encourage the philosophy that players should enjoy buying. You want them to like to buying things in your game. So spice up the market!

Besides pure user experience, you can address that choice paralysis with non-premium version that can be acquired by other means. Sure, they would try to get the non-premium first, but it also means they will be buying something they know they like. That is good customer satisfaction. Perhaps you can limit the number of non-premium character they can have at a time as a side incentive.

And of course the premium version would be extra fancy... they may even have slightly better stats, never to the point where the non-premium version are not usable. You want them to enjoy the non-premium so they know they will enjoy the premium one.

Addendum: to make sure you are not making a pay to win. The improvement should not be in power, just in convenience.

Which remind me. You want differences in kind, the characters should differ in mechanics, not just stats. There should be no clear better character, getting a character should feel game changing, and you should offer characters that lead well to different character styles (ranged, melee, stealth, etc...). That last point should also help the player decide what to buy.

If you are thinking in offering multiple variants with different stats... Instead provide ways to alter the stats of the characters (leveling up, power up items, collectible cards, whatever).

Also do not forget to offer alternative skins for sale. Let the player express themselves with the customization. In fact, in multiplayer, that is advertisement! If a player can see another player with a cool cosmetic, they might want to get it too.

---

**Addendum**: I understand the argument against the premium version having better stats. It easy to make it so that player with premium versions dominate. I suppose it works better in some games, for instance if the game is cooperative instead of competitive. Another things that helps is having things that can only be acquired by playing, and let those be tradable with other players, plus allowing trading premium currency among players. That way, if you put the time you can still get the premium content despite not using real money by selling things to those who do.

However, please understand the argument against hiding characters and rotations. **It is easy to design rotations in such way that it prays on the fear of missing out**. Not to mention making it so that everything in the rotation is not an easy combination of the amounts of premium currency that can be acquired... making it so that you always need just a little more premium currency, but you got to buy a bundle bigger than what you actually want to expend... leaving you with little extra that sets you to need just a little more premium currency on the next rotation.

# Answer
> 1 votes
It would be cool if the player could level up, thereby unlocking WHICH characters could be unlocked at particular levels. It pushes the player to continue progressing and leveling up.

Think Fortnite. I hate to reference it, but dammit if it doesn't work.

# Answer
> 0 votes
Expectation / psychology angle:

If I **purchase** something, I expect to choose. There are very rare exceptions, such as sneak previews at the local cinema and raffle tickets, but the general expectation is that the person spending currency (whether real or in-game) has the choice what to spend that currency on.

# Answer
> 0 votes
I’d say random character is the best choice and I might go as far as saying it will result in more money.

Here’s why: The way human psychology works and why gambling industry is so popular is exactly that, the random chance.

An simple example could be the “Mystery Box” in Call of Duty Zombies, people love it and at least in the early days it might’ve been one of the things that fueled the success of the game mode.

Another example is cases in CSGO and Call of Duty again.

So I would go with the random system, and despite the bad press and all, players still get hooked, meaning they don’t have a problem.

They would spin it again and again to see what they get, the mystery is key...

Hope that helps

---
Tags: game-design
---


# Question
Title: Two player platformer game - gameover issue
I'm creating a two player platformer game but facing issues when one of the player dies. So far I have created two players and added the following script to both. The issue I'm facing is that once any of the players hits an obstacle, the dying animation and the gameover screen just keep on repeating. I think this is because I have the code to check if the player is dead in the update function of the gamemanager script. I would like the game to stop as soon as any player hits an obstacle and then the gameover screen should pop up.

```
public class Player: MonoBehaviour {

public Rigidbody2D myRigidbody { get; set; }

public float jumpForce = 2.0f;

[SerializeField]
public Animator animator;

public bool isDead = true;

public GameManager gameManager;

public bool IsDead
{
    get
    {
        return isDead;
    }
}

void Start () {
    myRigidbody = GetComponent<Rigidbody2D>();
}

void Update () {

        if (Input.GetMouseButtonDown(0) && !IsDead)
        {
           jump = true;
           animator.SetBool("jump", true);
        }else
        {
           animator.SetBool("jump", false);
        }
}

public void OnTriggerEnter2D(Collider2D collision)
{
    if (!isDead && collision.tag == "Obstacle")
    {
        StartCoroutine(Die());
    }

}

public IEnumerator Die()
{
    isDead = true;
    animator.SetBool("Die", true);
    yield return new WaitForSeconds(2);
    gameManager.GameOver();

}

public void Jump()
{
    myRigidbody.AddForce(jumpForce* Vector2.up, ForceMode2D.Impulse);
}

```

This is the gamemanager script:

```
public enum GameStates { Start, InGame, GameOver};

[SerializeField]
private Player player;

[SerializeField]
private Player player1;

public GameObject startPanel, ingamePanel, gameoverPanel;

void Update () {

    if(player.IsDead )
    {
        StartCoroutine(player.Die());
        GameOver();

    }

    if (player1.IsDead)
    {
        StartCoroutine(player1.Die());
        GameOver();
    }
}

public void GameOver()
{
    UpdateUI(GameStates.GameOver);
}

```

# Answer
> 1 votes
Really simple solution, In Game Manager script, just add another Boolean “died”

Like so

```
bool died = false;

```

Then, in your game over code set `died = true;`

In your “if statements” in Update() add a check

```
&& !died

```

So your code will look like this

```
private bool died = false;

void Update () {

    if(player.IsDead && !died)
    {
        StartCoroutine(player.Die());
        GameOver();
    }

    if (player1.IsDead && !died)
    {
        StartCoroutine(player1.Die());
        GameOver();
    }
}

public void GameOver()
{
    died = true;
    UpdateUI(GameStates.GameOver);
}

```

# Answer
> 0 votes
So to start off, you're exactly right about the cause of your problem.

You're creating Coroutines in `Update()` \- you should try to avoid this.

Every time you create a Coroutine, imagine that you're creating an instance of your method and letting it run to the first yield command. On subsequent frames, it's going to run to the next and so forth. You can create one or as many of these routines as possible, they're each going to update to the next yield once per frame.

In `OnTriggerEnter2D()` you're creating an enumerator which sets the boolean value `isDead` to true. Then, in the same frame (or next frame) you'll create a new Coroutine in `Update()` method and do this again. And the next frame again. Even if we were to stop here, you'll have numerous coroutines being created every frame that wait two seconds before calling `GameOver` again.

This is going to be the root cause of your problem.

So as a general rule - don't create coroutines in `Update()`.

If you remove these from `Update()` you'll now be able to trigger death from `OnTriggerEnter2D()` \- provided that it's being triggered correctly from the obstacle.

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


# Question
Title: How should I go about creating a multiplayer pac-man game in python?
For some context, I am making a Pac-Man game (using pygame) and I need a little guidance on how to structure the multiplayer side (using sockets). I have a few ideas (the first of which I have tried)

Have the clients send their move (north, east, south or west) to a server. Then, have the server move sprites with these moves and send back the images of each sprite so all the clients can then draw them on the screen. (I have tried this but keep getting an error as I think the data takes too long to send.

I could have the server simply relay all incoming moves to all other clients, but I feel as though this may lead to glitches if the connection is slow for one of the clients (i.e. the different client screens may go out of sync with nothing to correct them as all they are receiving are instructions. I think this would be relatively simple to implement.

Another option would be to send the positions of each sprite over the network instead of the move. This way if any client experienced lag their screen would be corrected as soon as they reconnect. This would, however, be the hardest to implement as I would have to write new sprite classes and I'm lazy.

My question is, do these make any sense at all? Why don't they make sense (because I doubt they do)? Is there a better way to approach this task entirely?

Thanks in advance, I'll try and stay active to quickly answer questions.

# Answer
> 0 votes
Once I was thinking about making a MMO, and also had lots of questions about how to handle data on the network.

Gladly, I found this amazing article (too bad it's in portuguese) by Ivan Luiz Picoli called *"Server-Client Architecture in multiplayer games"* (he also uses PyGame), in which he analyzes 2 main methods of doing so:

* **Sending player's coordinates** (topic 3.5.2.1 of the article)
This technique consists on the client sending it's X and Y coordinates everytime it moves. The implementation is pretty easy, but the results are not that good. This may lead to miss syncing and server overload. If you try to fix the overload by sending all coordinates at a certain time on a loop, this might result in "jumpy" sprites, as if there were frames being skipped on the players movement. We can assume this is not a good approach.
* **Sending player's actions** (topic 3.5.2.2 of the article)
All the player sends is its actions, such as "move\_forward", then the server broadcasts this to other clients and they can "emulate" what another remote client is doing. This fixes many issues that happen when we only send coordinates, such as overload and the "frame skipping" effect, but this implementation must be done very carefully and send only important and relevant actions.

By reading this I personally think it's a very good idea to **mix both methods**. You mainly use the second method, but from time to time you send coordinates, in order to fix some small discrepancies.

---
Tags: python, pygame
---


# Question
Title: How can I use a coroutine and GetAxis to rotate a game object?
For the sake of learning about coroutine, I want to convert the following to a cleaner `Update` that just calls a coroutine. How would I do that?

```
using UnityEngine;

public class Controller : MonoBehaviour
{
    public float speed = 5f;
    private float deltaX;

    void Start()
    {
        deltaX = transform.localEulerAngles.x;
    }
    void Update()
    {
        deltaX += Input.GetAxis("Vertical") * speed;
        deltaX = Mathf.Clamp(deltaX, -90f, 90f);
        transform.localEulerAngles = new Vector3(deltaX, transform.localEulerAngles.y, transform.localEulerAngles.z);
    }
}

```

# Answer
> 3 votes
If each call to `Update` calls a coroutine, then you are creating a new coroutine each update and each coroutine will run in parallel with those created before. Your object will rotate faster and faster, while your framerate will get lower and lower due to the huge number of coroutines executed in parallel. That's unlikely to be what you want. If you want to run a coroutine, you generally only create that coroutine *once*.

So if your intention is to put the rotation code into a separate method so your `Update` function is "cleaner", then you would usually do that by creating a private method in the class and calling it as a regular method call:

```
using UnityEngine;

public class Controller : MonoBehaviour
{
    public float speed = 5f;
    private float deltaX;

    void Start()
    {
        deltaX = transform.localEulerAngles.x;
    }

    void Update()
    {
        UpdateRotation();
    }

    private void UpdateRotation()
    {
        deltaX += Input.GetAxis("Vertical") * speed;
        deltaX = Mathf.Clamp(deltaX, -90f, 90f);
        transform.localEulerAngles = new Vector3(deltaX, transform.localEulerAngles.y, transform.localEulerAngles.z);
    }
}

```

If you really want to do this with a coroutine (although I see no good reason here why you should), then you would want to start that coroutine from the `Start` method so it only gets created once:

```
using UnityEngine;

public class Controller : MonoBehaviour
{
    public float speed = 5f;
    private float deltaX;

    void Start()
    {
        deltaX = transform.localEulerAngles.x;
        StartCoroutine(UpdateRotationCoroutine());
    }

    private IEnumerator UpdateRotationCoroutine()
    {
        while(true) { // coroutine runs forever
            deltaX += Input.GetAxis("Vertical") * speed;
            deltaX = Mathf.Clamp(deltaX, -90f, 90f);
            transform.localEulerAngles = new Vector3(deltaX, transform.localEulerAngles.y, transform.localEulerAngles.z);
            yield return new WaitForFixedUpdate();
        }
    }
}

```

Here is an example of a more useful application of coroutines - one where a coroutine is started when the user presses the `F` key and that coroutine runs for 100 fixed updates. The player is able to start multiple coroutines in parallel by mashing the `F` key which will result in a faster rotation:

```
using UnityEngine;

public class Controller : MonoBehaviour
{
    public float speed = 90f;

    void Update() {
        if (Input.GetKeyDown(KeyCode.F)) {
             StartCoroutine(UpdateRotationCoroutine());
        }
    }

    private IEnumerator UpdateRotationCoroutine()
    {
        for (int i = 0; i < 100; i++) { // coroutine runs for 100 updates
            transform.Rotate(speed * Time.fixedDeltaTime, 0.0f, 0.0f);
            yield return new WaitForFixedUpdate();
        }
    }
}

```

---
Tags: unity, c#, rotation, coroutines
---


title: Rotate coplanar 3D points to XY

text:
# Question
Title: Rotate coplanar 3D points to XY
I have a set of 3D points. All these points are on the same plane. I have the normal of the plane.

Now I need to rotate them in such a way that the Z value of all these points become zero. (that is, 3D to XY plane)

I have Googled a lot. I got very few results and most of them are very much mathematical. Few are about projection and few are with solution with OpenGL APIs.

I have seen this solution: Rotating 3d plane to XY plane

Based on this, I have implemented something like this:

```
public static List<Vector3D> RotateCoplanar3DPointsToXY(IList<Vector3D> points, Vector3D planeNormal)
        {
            var zAxis = new Vector3D(0, 0, 1);
            var rotationAxis = zAxis.Cross(planeNormal);
            rotationAxis.Normalize();
            var rotationAngle = (float)Math.Acos(zAxis.Dot(planeNormal));
            var matrix = Matrix4x4.FromAngleAxis(rotationAngle, rotationAxis);
            var newPoints = new List<Vector3D>();
            for (var i = 0; i < points.Count; i++)
            {
                var p = points[i];
                var newPoint = p.Transform(matrix);
                newPoints.Add(newPoint);
            }
            return newPoints;
        }

```

But this implementation is not working.

I have another implementation below based on @Bálint's comment. This is also not working.

```
public static Vector3D Cross(Vector3D a, Vector3D b)
        {
            return new Vector3D(
                a.Y * b.Z - a.Z * b.Y,
                a.Z * b.X - a.X * b.Z,
                a.X * b.Y - a.Y * b.X);
        }

        public static Matrix4x4 GetMatrixForRotatingCoplanar3DPointsToXY(Vector3D planeNormal)
        {
            var Z_NORMAL = new Vector3D(1, 0, 0);
            var d = planeNormal;
            var u = Z_NORMAL;

            var r = Cross(d, u);
            var t = Cross(r, d);
            var matrix = new Matrix4x4(
             r.X, t.X, d.X, 0,
             r.Y, t.Y, d.Y, 0,
             r.Z, t.Z, d.Z, 0,
             0, 0, 0, 1);

            return matrix;
        }

```

# Answer
Doing this requires high-level mathematics (college/university), so it's no wonder those are the only solutions you found. If you know how matrices work, it's pretty simple.

I already described how you can get a rotation matrix from a normal in this post. Your problem is the exact inverse of this: instead of going from points in the XY plane to a rotated version, you need to go from the rotated version back to the XY plane. To do this, you need the **inverse** of the rotation matrix.

Thankfully, it's pretty simple to do that with rotation matrices, since to inverse one, you just need to transpose it. There should be a method for it in your library of choice, but if there isn't one, it's simply swapping the values out in the following way:

$$\begin{bmatrix} a & b & c & d\\ e & f & g & h\\ i & j & k & l\\ m & n & o & p \end{bmatrix}\rightarrow \begin{bmatrix} a & e & i & m\\ b & f & j & n\\ c & g & k & o\\ d & h & l &p \end{bmatrix} $$

Now just multiply every point with this matrix and you'll transform them in the XY plane.
> 1 votes

---
Tags: rotation, matrix
---


title: NPC Melee fighting movement issue

text:
# Question
Title: NPC Melee fighting movement issue
So i have been struggling with this for ages and I have now decided to reach out for help.

**The Problem:**

The game has two NPCs for reference we will call them "Ally" and "Enemy"

Ally and Enemy each have their own weapon:

* Ally has a sword with a reach `0.1 - 2` meters
* Enemy has a long sword that has a reach of `0.5 - 3` meters.

Now these two NPC's wish to fight each other. They need to make sure that they stay within the reach of their weapons while also making sure that they don't bump into each other.

For this I attempted the following algorithm:

```
bool shouldMove = false;
Vector3 lToTarget = Target.transform.position - transform.position;
lToTarget.y = 0f;

Vector3 lToTargetDirection = lToTarget.normalized;
float lToTargetDistance = lToTarget.magnitude;
float lRange = MinMeleeReach + MaxRange;
if (!shouldMove && lToTargetDistance > lRange + 1f)
{
    shouldMove = true;
}

if (shouldMove && lToTargetDistance <= Mathf.Max(lRange))
{
    shouldMove = false;
}

if (shouldMove)
{
    float lSpeed = Mathf.Min(MovementSpeed * Time.deltaTime, lToTargetDistance);
    transform.position = transform.position + (lToTargetDirection * lSpeed);
}

```

Now if they should not move then they would attack their target.

However as you might have guessed this has an issue:

*The agent tries to keep his distance to the max of his range!*

This sadly causes the agents to bug out in a way where they are never close enough to attack each other resulting in something that looks like this:

So i thought to my self how can i change this behavior.

I came up with another idea which sadly had the same problem this time using navmesh agent:

```
Vector3 direction =
    (transform.position - Target.position).normalized;
Vector3 finalPosition = Target.position + direction * maxRange;
navMeshAgent.SetDestination(finalPosition);

```

Again sort of same behavior, however, this time they just kept their distance and if the other agent came to close they would start moving backward. Which basically meant that they would move back to the end of the world.

So this is where I am at right now. I have attempted to google this issue however without much luck.

So i am really praying that you guys have an answer for me :)

if you need more information please do not hesitate to comment!

# Answer
I would try using springs - for each of the two characters a compression spring representing "defensivness", and an extension spring representing "aggression".

The force generated by the spring is calculated as F=kx, where *x* says how much is the loose end of the spring displaced from its relaxed position, *k* is the stiffness of the spring - the sign depends on type of the spring (compression/extension).

Summing up the forces for each character (for more units force vectors) gives direction in which the character should move. The force magnitude could probably somehow be mapped to speed.

The stiffness of the springs could vary over time (using some noise function), or be fixed per character to represent his fighting style. Combination of both should probably work best.

I have no idea how well this will work in practice though. :-)
> 1 votes

---
Tags: unity, game-design, movement, npc
---


title: Multiple Bitmaps in Rectangle area

text:
# Question
Title: Multiple Bitmaps in Rectangle area
I am trying to build a card based game in which a card is added to player after every round. To win the match player has to remove all cards from his deck. However I have also drawn some additional button for some other purposes. The issue is that when the number of cards got high, they hide behind the buttons like below image.

Is there any way through which i can draw the bitmaps in a fixed area? Something like below image (highlighted rectangle behind the card images).

Following is my code to draw Bitmaps for one player

```
private void setMainPlayer() {
    //    Log.d(TAG, "Inside Set Main Player Method");
    Card localcard = null;
    Bitmap localimage = null;
    int currentiteration = 0;
    int Card_Gap = Screen_Width / 10;
    int Down_Card_Gap = 0;
    int Down_Card_Gap_positive = 0;
    int Down_Card_Gap_negative = 0;
    playerList.get(0).sortBySuit();

    //  Log.d(TAG,"Main Player Deck size"+MainPlayer.Count());
    while (currentiteration < playerList.get(0).decksize()) {
        localcard = playerList.get(0).getCard(currentiteration);
        localcard.setCurrent_Y(Screen_Height - localcard.getImage(context, Card_Width, Card_Height).getHeight());
        playerList.get(0).setCurrentCard(localcard, currentiteration);
        currentiteration++;
        if (Down_Card_Gap >= 0) {
            Down_Card_Gap_positive = Down_Card_Gap;
            localcard.setCurrent_X(Screen_Center_X + Down_Card_Gap_positive);
            Down_Card_Gap += Card_Gap;
        } else {
            Down_Card_Gap_negative = Down_Card_Gap;
            localcard.setCurrent_X(Screen_Center_X + Down_Card_Gap_negative);
        }
        Down_Card_Gap *= -1;

    }

}

private void DrawMainPlayerDeck(Canvas canvas) {
    // Log.d(TAG, " Inside Draw Main Player Deck");
    Card localcard;
    int currentiteration = 0;
    while (currentiteration < playerList.get(0).decksize()) {
        localcard = playerList.get(0).getCard(currentiteration);
        canvas.drawBitmap(localcard.getImage(context, Card_Width, Card_Height), localcard.getCurrent_X(), localcard.getCurrent_Y(), null);
        currentiteration++;
    }

}

```

I am drawing bitmaps on `surfaceview`.

Any suggestion (even if it involves a game engine like libGDX) would be really helpful.

# Answer
> 0 votes
Most cards are designed in a way that lets you tell what it is by seeing very little of them. Most cards do this by having the symbols in the upper left and lower right corners. Due to this, you can stack them up pretty tightly before it becomes a problem.

There are two approaches you can take:

1.) Have them always stacked up. You can make the distance between the edges really small, this way you can store a bunch of cards in that rectangular area and simply not bother limiting it.

2.) Make the distance dynamic. If we know the cards have to go from x=100 to x=900 on the screen for instance, and we have 20 cards we need to display, then obviously the first one has to go to x=100 ans the last to x=900. The remaining can be placed based on a simple linear interpolation. If \\$n\\$ is the number of cards on the table, then the position of any card with the index \\$i\\$ is:

$$100 + i\cdot \frac{900 - 100}{n}$$

---
Tags: libgdx, android
---


# Question
Title: Get JSON property dynamically in Unity C#?
I'm saving game data into JSON, however basically I can't get property with just string just like in JavaScript.

This makes my code to write so many if/switch statements, looks very not clean, hard to read.

For instance, if I have this struct to save data as JSON:

```
public struct PlayerData {
    public int compensator;
    public int silencer;
    ...
}

```

I want to do something like this:

```
string attachmentName = "compensator";

if (PlayerData[attachmentName]) {
    weapon[attachmentName].gameObject.SetActive(true);
}

```

This part:

```
weapon[attachmentName].gameObject.SetActive(true);

```

Can do with Dictionary, but this part can't, because it's C# struct/class:

```
if (PlayerData[attachmentName]) {

```

Is there a way to access JSON data dynamically in this case?

# Answer
> 1 votes
Since the objects seam to be of the same type, you can just rearrange them into a dictionary for easier access. That way you can do string based lookup.

Or if you don't mind it being (really really) slow, then you can use reflection. The method below returns an object based on the field name you pass in:

```
public static object GetAttachment(object obj, string fieldName)
{
    return obj.GetType().GetField(fieldName).GetValue(obj);
}

```

Use it like this:

```
GetAttachment(playerData, "compensator");

```

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


# Question
Title: What is the physical interpretation of Input.GetAxis("Horizontal")?
Actually I want to edit my previous question titled What is the geometrical interpretation of `Input.GetAxis("Mouse X")` and add a related question "What is the physical interpretation of `Input.GetAxis("Horizontal")`?" to it.

However, I was asked to create a new question about it.

The longer I press the key, the greater the value returned by `Input.GetAxis("Horizontal")`. If I don't press, it returns 0. The value seems to be a function of time interval the key is pressed. What is the empirical relationship between the relevant quantities?

# Answer
> 3 votes
Althought the doc covers how this works, it does not state why it does it like that.

I don't have first hand experience with that, but here is what I think.

Keyboard keys don't naturally offer gradual values like other types of input such as mouse/finger drag speed, joystick axis, etc. This gradual value returned for the keys lets you emulate a joystick that is "slowly" deflected to its maximum.

It's useful in situations where you need to roughly test something when you don't have access to joysticks (it's not a drop in replacement), or it could be useful in situations where you'd want to move a slider in the UI (e.g. for the volume), or any other object with more or less precision.

---
Tags: unity
---


# Question
Title: Rigidbody script throwing error CS0246: The type or namespace name `MouseLook' could not be found. Are you missing an assembly reference?
I've been stuck on this for the last 3 days and I really need some help.

Now, I have 2 scripts that are giving me some grief, the RigidbodyFirstPersonController.cs and the MouseLook.cs scripts. On my player model, I have a custom script for the controls and finally got working, so I moved onto the camera (as it would spin way out and cause a "screen position out of view frustum" error and crash the game) and was following this tutorial:

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

And I was only following the Camera's side of the tutorial (as I already had my script and just really needed help with the camera) and I'm following the tutorial and get an error for the TargetRotation (and you can see others are stuck on this too) and after looking up definitions and trying to find replacement code for that line and doing everything I can think of, I get frustrated, make a copy of the file, disable and remove it, then added the MouseLook.cs file (which I think is the standard asset that comes with Unity's package) and this is when the error started.

Again, I keep checking between the two scripts (I did not drag and drop the RigidbodyFirstPersonController script on there, I clicked Add Component, and selected it from the list) and I still can't get it to work. So I try adding the rigidbody's script on there, this time by dragging and dropping it, thinking I could fix it in the inspector by assigning the main camera and the MouseLook, except I'm unable to select the MouseLook script.

I then disable the MouseLook file and remove the component, only to have RigidBody's script throw the same error again. I remove the MouseLook script from the Camera and the rigidbody script (I reset and put it to how it was when it was working) but it still showed this error.

I'm going to put a copy of both the RigidbodyFirstPersonController and the MouseLook scripts, because it never had this problem before and I'm really stuck here :(

RigidbodyFirstPersonController.cs:

```
 using System;
 using UnityEngine;
 using UnityStandardAssets.CrossPlatformInput;

 namespace UnityStandardAssets.Characters.FirstPerson
 {
     [RequireComponent(typeof (Rigidbody))]
     [RequireComponent(typeof (CapsuleCollider))]
     public class RigidbodyFirstPersonController : MonoBehaviour
     {
         [Serializable]
         public class MovementSettings
         {
             public float ForwardSpeed = 8.0f;   // Speed when walking forward
             public float BackwardSpeed = 4.0f;  // Speed when walking backwards
             public float StrafeSpeed = 4.0f;    // Speed when walking sideways
             public float RunMultiplier = 2.0f;   // Speed when sprinting
             public KeyCode RunKey = KeyCode.LeftShift;
             public float JumpForce = 30f;
             public AnimationCurve SlopeCurveModifier = new AnimationCurve(new Keyframe(-90.0f, 1.0f), new Keyframe(0.0f, 1.0f), new Keyframe(90.0f, 0.0f));
             [HideInInspector] public float CurrentTargetSpeed = 8f;

 #if !MOBILE_INPUT
             private bool m_Running;
 #endif

             public void UpdateDesiredTargetSpeed(Vector2 input)
             {
                 if (input == Vector2.zero) return;
                 if (input.x > 0 || input.x < 0)
                 {
                     //strafe
                     CurrentTargetSpeed = StrafeSpeed;
                 }
                 if (input.y < 0)
                 {
                     //backwards
                     CurrentTargetSpeed = BackwardSpeed;
                 }
                 if (input.y > 0)
                 {
                     //forwards
                     //handled last as if strafing and moving forward at the same time forwards speed should take precedence
                     CurrentTargetSpeed = ForwardSpeed;
                 }
 #if !MOBILE_INPUT
                 if (Input.GetKey(RunKey))
                 {
                     CurrentTargetSpeed *= RunMultiplier;
                     m_Running = true;
                 }
                 else
                 {
                     m_Running = false;
                 }
 #endif
             }

 #if !MOBILE_INPUT
             public bool Running
             {
                 get { return m_Running; }
             }
 #endif
         }

         [Serializable]
         public class AdvancedSettings
         {
             public float groundCheckDistance = 0.01f; // distance for checking if the controller is grounded ( 0.01f seems to work best for this )
             public float stickToGroundHelperDistance = 0.5f; // stops the character
             public float slowDownRate = 20f; // rate at which the controller comes to a stop when there is no input
             public bool airControl; // can the user control the direction that is being moved in the air
             [Tooltip("set it to 0.1 or more if you get stuck in wall")]
             public float shellOffset; //reduce the radius by that ratio to avoid getting stuck in wall (a value of 0.1f is nice)
         }

         public Camera cam;
         public MovementSettings movementSettings = new MovementSettings();
         public MouseLook mouseLook = new MouseLook();
         public AdvancedSettings advancedSettings = new AdvancedSettings();

         private Rigidbody m_RigidBody;
         private CapsuleCollider m_Capsule;
         private float m_YRotation;
         private Vector3 m_GroundContactNormal;
         private bool m_Jump, m_PreviouslyGrounded, m_Jumping, m_IsGrounded;

         public RigidbodyFirstPersonController(MouseLook mouseLook)
         {
             this.mouseLook = mouseLook;
         }

         public Vector3 Velocity
         {
             get { return m_RigidBody.velocity; }
         }

         public bool Grounded
         {
             get { return m_IsGrounded; }
         }

         public bool Jumping
         {
             get { return m_Jumping; }
         }

         public bool Running
         {
             get
             {
  #if !MOBILE_INPUT
                 return movementSettings.Running;
 #else
                 return false;
 #endif
             }
         }

         private void Start()
         {
             m_RigidBody = GetComponent<Rigidbody>();
             m_Capsule = GetComponent<CapsuleCollider>();
             mouseLook.Init (transform, cam.transform);
         }

         private void Update()
         {
             RotateView();

             if (CrossPlatformInputManager.GetButtonDown("Jump") && !m_Jump)
             {
                 m_Jump = true;
             }
         }

         private void FixedUpdate()
         {
             GroundCheck();
             Vector2 input = GetInput();

             if ((Mathf.Abs(input.x) > float.Epsilon || Mathf.Abs(input.y) > float.Epsilon) && (advancedSettings.airControl || m_IsGrounded))
             {
                 // always move along the camera forward as it is the direction that it being aimed at
                 Vector3 desiredMove = cam.transform.forward*input.y + cam.transform.right*input.x;
                 desiredMove = Vector3.ProjectOnPlane(desiredMove, m_GroundContactNormal).normalized;

                 desiredMove.x = desiredMove.x*movementSettings.CurrentTargetSpeed;
                 desiredMove.z = desiredMove.z*movementSettings.CurrentTargetSpeed;
                 desiredMove.y = desiredMove.y*movementSettings.CurrentTargetSpeed;
                 if (m_RigidBody.velocity.sqrMagnitude <
                     (movementSettings.CurrentTargetSpeed*movementSettings.CurrentTargetSpeed))
                 {
                     m_RigidBody.AddForce(desiredMove*SlopeMultiplier(), ForceMode.Impulse);
                 }
             }

             if (m_IsGrounded)
             {
                 m_RigidBody.drag = 5f;

                 if (m_Jump)
                 {
                     m_RigidBody.drag = 0f;
                     m_RigidBody.velocity = new Vector3(m_RigidBody.velocity.x, 0f, m_RigidBody.velocity.z);
                     m_RigidBody.AddForce(new Vector3(0f, movementSettings.JumpForce, 0f), ForceMode.Impulse);
                     m_Jumping = true;
                 }

                 if (!m_Jumping && Mathf.Abs(input.x) < float.Epsilon && Mathf.Abs(input.y) < float.Epsilon && m_RigidBody.velocity.magnitude < 1f)
                 {
                     m_RigidBody.Sleep();
                 }
             }
             else
             {
                 m_RigidBody.drag = 0f;
                 if (m_PreviouslyGrounded && !m_Jumping)
                 {
                     StickToGroundHelper();
                 }
             }
             m_Jump = false;
         }

         private float SlopeMultiplier()
         {
             float angle = Vector3.Angle(m_GroundContactNormal, Vector3.up);
             return movementSettings.SlopeCurveModifier.Evaluate(angle);
         }

         private void StickToGroundHelper()
         {
             RaycastHit hitInfo;
             if (Physics.SphereCast(transform.position, m_Capsule.radius * (1.0f - advancedSettings.shellOffset), Vector3.down, out hitInfo,
                                    ((m_Capsule.height/2f) - m_Capsule.radius) +
                                    advancedSettings.stickToGroundHelperDistance, Physics.AllLayers, QueryTriggerInteraction.Ignore))
             {
                 if (Mathf.Abs(Vector3.Angle(hitInfo.normal, Vector3.up)) < 85f)
                 {
                     m_RigidBody.velocity = Vector3.ProjectOnPlane(m_RigidBody.velocity, hitInfo.normal);
                 }
             }
         }

         private Vector2 GetInput()
         {

             Vector2 input = new Vector2
                 {
                     x = CrossPlatformInputManager.GetAxis("Horizontal"),
                     y = CrossPlatformInputManager.GetAxis("Vertical")
                 };
             movementSettings.UpdateDesiredTargetSpeed(input);
             return input;
         }

         private void RotateView()
         {
             //avoids the mouse looking if the game is effectively paused
             if (Mathf.Abs(Time.timeScale) < float.Epsilon) return;

             // get the rotation before it's changed
             float oldYRotation = transform.eulerAngles.y;

             mouseLook.LookRotation (transform, cam.transform);

             if (m_IsGrounded || advancedSettings.airControl)
             {
                 // Rotate the rigidbody velocity to match the new direction that the character is looking
                 Quaternion velRotation = Quaternion.AngleAxis(transform.eulerAngles.y - oldYRotation, Vector3.up);
                 m_RigidBody.velocity = velRotation*m_RigidBody.velocity;
             }
         }

         /// sphere cast down just beyond the bottom of the capsule to see if the capsule is colliding round the bottom
         private void GroundCheck()
         {
             m_PreviouslyGrounded = m_IsGrounded;
             RaycastHit hitInfo;
             if (Physics.SphereCast(transform.position, m_Capsule.radius * (1.0f - advancedSettings.shellOffset), Vector3.down, out hitInfo,
                                    ((m_Capsule.height/2f) - m_Capsule.radius) + advancedSettings.groundCheckDistance, Physics.AllLayers, QueryTriggerInteraction.Ignore))
             {
                 m_IsGrounded = true;
                 m_GroundContactNormal = hitInfo.normal;
             }
             else
             {
                 m_IsGrounded = false;
                 m_GroundContactNormal = Vector3.up;
             }
             if (!m_PreviouslyGrounded && m_IsGrounded && m_Jumping)
             {
                 m_Jumping = false;
             }
         }
     }
 }

```

MouseLook.cs:

```
 using System;
 using UnityEngine;
 using UnityStandardAssets.CrossPlatformInput;

 namespace UnityStandardAssets.Characters.FirstPerson
 {
     [Serializable]
     public class MouseLook : MonoBehaviour
     {
         public float XSensitivity = 2f;
         public float YSensitivity = 2f;
         public bool clampVerticalRotation = true;
         public float MinimumX = -90F;
         public float MaximumX = 90F;
         public bool smooth;
         public float smoothTime = 5f;
         public bool lockCursor = true;

         private Quaternion m_CharacterTargetRot;
         private Quaternion m_CameraTargetRot;
         private bool m_cursorIsLocked = true;

         public void Init(Transform character, Transform camera)
         {
             m_CharacterTargetRot = character.localRotation;
             m_CameraTargetRot = camera.localRotation;
         }

         public void LookRotation(Transform character, Transform camera)
         {
             float yRot = CrossPlatformInputManager.GetAxis("Mouse X") * XSensitivity;
             float xRot = CrossPlatformInputManager.GetAxis("Mouse Y") * YSensitivity;

             m_CharacterTargetRot *= Quaternion.Euler (0f, yRot, 0f);
             m_CameraTargetRot *= Quaternion.Euler (-xRot, 0f, 0f);

             if(clampVerticalRotation)
                 m_CameraTargetRot = ClampRotationAroundXAxis (m_CameraTargetRot);

             if(smooth)
             {
                 character.localRotation = Quaternion.Slerp (character.localRotation, m_CharacterTargetRot,
                     smoothTime * Time.deltaTime);
                 camera.localRotation = Quaternion.Slerp (camera.localRotation, m_CameraTargetRot,
                     smoothTime * Time.deltaTime);
             }
             else
             {
                 character.localRotation = m_CharacterTargetRot;
                 camera.localRotation = m_CameraTargetRot;
             }

             UpdateCursorLock();
         }

         public void SetCursorLock(bool value)
         {
             lockCursor = value;
             if(!lockCursor)
             {//we force unlock the cursor if the user disable the cursor locking helper
                 Cursor.lockState = CursorLockMode.None;
                 Cursor.visible = true;
             }
         }

         public void UpdateCursorLock()
         {
             //if the user set "lockCursor" we check & properly lock the cursor
             if (lockCursor)
                 InternalLockUpdate();
         }

         private void InternalLockUpdate()
         {
             if(Input.GetKeyUp(KeyCode.Escape))
             {
                 m_cursorIsLocked = false;
             }
             else if(Input.GetMouseButtonUp(0))
             {
                 m_cursorIsLocked = true;
             }

             if (m_cursorIsLocked)
             {
                 Cursor.lockState = CursorLockMode.Locked;
                 Cursor.visible = false;
             }
             else if (!m_cursorIsLocked)
             {
                 Cursor.lockState = CursorLockMode.None;
                 Cursor.visible = true;
             }
         }

         Quaternion ClampRotationAroundXAxis(Quaternion q)
         {
             q.x /= q.w;
             q.y /= q.w;
             q.z /= q.w;
             q.w = 1.0f;

             float angleX = 2.0f * Mathf.Rad2Deg * Mathf.Atan (q.x);

             angleX = Mathf.Clamp (angleX, MinimumX, MaximumX);

             q.x = Mathf.Tan (0.5f * Mathf.Deg2Rad * angleX);

             return q;
         }

     }
 }

```

I'm also using Unity 2018.10f1 because any time I try to use newer versions, it ruins the project completely.

# Answer
> 1 votes
Check the assembly definition for your `RigidbodyFirstPersonController`, if `MouseMove` is in a different assembly file and you haven't included the reference to the other assembly file that problem can happen. Read more about Assembly Definitions

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


title: Centring content within a scroll area

text:
# Question
Title: Centring content within a scroll area
I've got a Scrollbar with a dynamically generated number of entries, and I'm trying to figure out how to get it to act so that there's a lead-in of the first 3 items (example number based on the size of my scroll area) where the area won't move. This then leaves the current selected item as the one in the centre of the area, and the content should move up so that the selection remains in the centre until the last 3 are visible, when the selection continues down to the bottom.

My efforts so far have varied from calculate the percentage through the content (currentSelected / numItems) & assign the scrollbar.value, to putting that percentage through an AnimationCurve, which gives me the "dead zones" at the beginning & end, but introduces unpleasant skipping & doesn't centre the selected item.

Also, this is intended to be for navigating through discrete objects using a gamepad.

# Answer
Really depends on how your scrolling is setup. Do you know the height of each entry? If you do then you can loop through the child count and offset the height for each entry until you hit your selected target.

```
public ScrollRect ScrollerRect;
public RectTransform SelectedEntry;

void Start()
{
    //test the selected entry - remove and add your own selection method.
    if (SelectedEntry != null)
        ScrollToEntryView();//--pass in selected entry and scroll to view
}
void ScrollToEntryView()
{
    float scrollToPos = 0;
    float yMax = ScrollerRect.content.rect.yMax;
    float entryHeight = 150;
    for (int i = 0; i < ScrollerRect.content.childCount; i++)
    {
        if (SelectedEntry.gameObject.name == ScrollerRect.content.GetChild(i).gameObject.name)
            SetScrollContentPoint(scrollToPos);
        else
            scrollToPos = yMax += entryHeight;
    }
}
void SetScrollContentPoint(float yPos)
{
    ScrollerRect.content.offsetMax = new Vector2(0, yPos);
    EventSystem.current.SetSelectedGameObject(SelectedEntry.gameObject, null);
}

```
> 0 votes

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


# Question
Title: Repeating a mesh instead of stretching it
I would like to put acoustic foam into a case object:

To do that, I have created a foam object:

Now I'm having a really hard time to cover the case in Unity with this object:

I have to adjust multiple foam objects absolutely exactely besides each other. This is really time taking.

I was thinking that it would be great that if I could use scaling, and instead of scretching, Unity would repeat the object.

Is that perhaps somehow possible?

Thank you very much!

# Answer
> 2 votes
If you don't think rendering performance might be an issue, you could consider placing the foam object with a Script. This way it would be 100% precise. If you prefer seeing and working with the result in Edit mode, an Editor Script might be the better choice.

Here is an example for Instantiating a prefab mesh as children of the GameObject the script is attached to:

```
public class ReplicateMesh : MonoBehaviour
{
    public int rows;
    public int columns;
    public GameObject meshPrefab;

    public void Start()
    {
        if (meshPrefab == null)
            return;

        for (int rowIndex=0; rowIndex < rows; rowIndex++)
            for (int colIndex = 0; colIndex < columns; colIndex++)
                Instantiate(meshPrefab, new Vector3(rowIndex - rows/2f, 0, colIndex - columns/2f), Quaternion.identity, this.transform);
    }
}

```

*Note:* This example assumes the prefab mesh has unity scale. If your use-case requires different scaling, a position offset needs to be considered when computing the position of the prefab instances.

---

If you prefer instantiating the prefab mesh in edit mode you can change the code to be triggered from an Editor GUI. For exmaple, check out the tutorial about how to add a Button to a CustomInspector: https://unity3d.com/de/learn/tutorials/topics/interface-essentials/adding-buttons-custom-inspector

This way, you could generate the majority of the instances via code and add/remove/adjust some manually.

---
Tags: unity
---


title: Algorithm for generating a 2d maze

text:
# Question
Title: Algorithm for generating a 2d maze
What algorithm have you used in the past to generate a simple 2d maze?

# Answer
There are a lot of various ways of making mazes. There's a huge list of them and their descriptions here: http://www.astrolog.org/labyrnth/algrithm.htm

I think I used the one described under "Perfect".
> 21 votes

# Answer
I prefer the tightly wound mazes that Kruskal's Algorithm creates.

The standard description of Kruskal's Algorithm is inappropriate in that it fails to distinguish locations in the graph from location groups, while relying on a pun about datastructure choice, leading to description ambiguities that confuse novices. Therefore I reject Kruskal's termonology.

I will use the following terms:

* **Graph**
    + the maze itself.
* **Node**
    + a location in the maze. On a square maze, this is a square cell.
* **Edge**
    + the connection between two nodes. On a square maze, this is a 1-length bar.
* **Tree Group**
    + a set of nodes, which may be empty, arranged as a tree

And from those, we get:

1. Create a group **GTG**, for the *Graph Tree Group*, containing tree groups
2. Populate **GTG** with one tree group containing one node, for every location in your maze
3. Create an edge set **E**
4. Populate **E** with every valid edge in your maze
5. While there is more than one group in **GTG**, and while **E** is not empty:
6. Pick a random edge **rE** from **E**
7. Identify endpoints **p1** and **p2** of **rE**
8. Remove **rE** from **E**
9. Check which groups **p1** and **p2** belong to (**p1g** and **p2g** respectively).
10. If **p1g** and **p2g** are different, join tree group **p1g** and **p2g** at **p1** -\> **p2**, and rewrite all group ownership of one tree to the other, thus joining the trees.
11. Return to step 5.
12. If you have no edges left, but more than one tree, either the graph is not connected or there's a bug.
13. If you have just one tree, you have a complete no-loop maze.
> 8 votes

# Answer
Wikipedia has a great resource on maze generation. I've use randomized prims algorithm with great results. The division algorithm looks looks interesting but I've never used it.

Here is wikipedia example of prim's at work.
> 1 votes

# Answer
One easy way is to make a list of north walls and west walls, then permute them. Give each room a number. Then blow up one of the walls in the list, as long as the two rooms don't have the same number, then propagate one of the numbers to all the other rooms with the same number. Keep going until you run out of walls. This works for rectangular mazes or, really, any other maze where you can give a list of "potentially connected rooms". Plus, it's pretty straightforward to program.
> 1 votes

# Answer
I would also take a look at some of the algorithms used in Roguelike development. There's a good starting resource at Rogue Basin
> 1 votes

# Answer
There's a good run-though here: https://journal.stuffwithstuff.com/2014/12/21/rooms-and-mazes/

Basic steps were:

* Place rooms
* Fill empty space with maze
* Connect rooms to the maze
* Carve out dead-ends

Code here: https://github.com/munificent/hauberk/blob/db360d9efa714efb6d937c31953ef849c7394a39/lib/src/content/dungeon.dart
> 1 votes

# Answer
You asked which one I used, so I will make sure to answer that. I used the Recursive Backtracker Algorithm in my maze game on Rootbeer Games.

This is evidence that I used the algorithm, please don't view it as an advertisement of my work.
> 0 votes

---
Tags: algorithm, procedural-generation
---


# Question
Title: How long does one have to pay the $150 per month subscription fee for Unity pro?
I'm a bit confused by how the subscription for Unity Pro works. If I were to get Unity Pro, do I have to keep paying $150 per month for as long as I'm using Unity pro? Or do I have to keep paying $150 per month until certain period, after which I am no longer required to pay anything?

Furthermore, if I developed a game with the personal version of Unity and the game made over $100K, would that result in an immediate penalty or will Unity give me a deadline before which I must get Unity Plus/Pro?

# Answer
> 4 votes
> How long does one have to pay the $150 per month subscription fee for Unity pro?

The Unity store currently only offers *annual* plans, either paid monthly or paid yearly. Assuming you cancelled the renewal before the end of your annual plan, it's 12 months after you purchased your license.

> If I were to get Unity Pro, do I have to keep paying $150 per month for as long as I'm using Unity pro?

You need to pay until your contract ends, one year after you purchased your license. Before the license automatically renews, you need to decide if you still want to use it. If you still want to use Unity Pro, you'll start another contract of 12 months.

Now let's tweak this question a bit:

> If I were to get Unity Pro, do I have to keep paying $150 per month for as long as I'm using Unity?

No, you pay until your subscription plan ends, then, as described above, you're free to cancel the plan (*before* the automatic renewal occurs) unless you still use Unity (for anything) *and* your company has more than 100k revenue. If you did not make 100k in revenue in the previous 12 months, you *can* downgrade to Unity Personal for free (or to Unity Plus if you made less than 200k).

> Or do I have to keep paying $150 per month until certain period, after which I am no longer required to pay anything?

The $150 per month payments that you are required to do are when you subscribe to the *1 year, paid monthly* plan, or that your subscription ends *and* you chose not to renew. As previously said, you're no longer required to pay anything if your subscription plan ends, and you don't work with Unity or you don't make more than 100/200k a year.

> Furthermore, if I developed a game with the personal version of Unity and the game made over $100K, would that result in an immediate penalty or will Unity give me a deadline before which I must get Unity Plus/Pro?

The documentation is not very clear about this, but you can assume that as soon as you've made 100k based off you using Unity in the previous 12 months, you need to upgrade to a paid plan.

---

If you made your game in year one using Unity Personal, and your game had a big success and you made 100k during that first year, and you still want to push updates to your players, even if you plan that it's your last game and you quit gamedev after that, you're forced to buy the Pro license, at least for one year.

# Answer
> 2 votes
# Its a subscription and you can't cancel

From the FAQ:

> ### Can I cancel my subscription before the end of my commitment period?
>
> There is no cancellation policy or reimbursement for a subscription. Once you commit to a subscription you are obligated to pay all monthly payments owing.

Note that this is based on the *commitment period,* i.e. if you say "I'll pay for a year" you pay for a year. After that, you will move to the flex plan.

> ### Will my subscription automatically renew?
>
> For Pro subscribers, when your commitment period ends your plan will automatically convert to a flexible month-to-month subscription. The key things to note about the flex option:
>
> * You pay month-to-month and can cancel your subscription at any time. However, cancellation will take effect from the following month.
> * If you choose to expire your plan, your version of Unity will switch to Personal.

Additionally, from the Personal FAQ:

> ### Can I use Personal for commercial development?
>
> If you or your company currently makes more than $100k in annual gross revenues or has raised funds in excess of $100k, you are not permitted to use Unity Personal, for prototyping or otherwise, as defined in our EULA Agreement.
>
> You may use Unity Plus for up to $200k in annual gross revenues, or Unity Pro with an unlimited revenue or fundraising capacity.

This means that if you make a game, and then earn $100k in revenue from it, you are obligated to purchase a Plus or Pro license.

---
Tags: unity
---


title: OpenGL: glTangent?

text:
# Question
Title: OpenGL: glTangent?
In the `glext.h` header there is the group of functions with the prefix `glTangent`. It has signatures similar to the `glVertex` and `glNormal` function groups (it contains functions for each type and `glTangentPointer`). I guess it is an vertex attribute as the normal, the color, etc...

But what meaning does the tangent attribute have? And in which context is it used?

**Edit:** The term *Tangent* does make sense to me. But when the normal vector is already given, why also give the tangent vector?

# My approach to answer my own question:

The `glTangent` allows to add a tangent vector to a vertex. It has no special meaning in classic rendering and does not replace normals. But it is used to implement bump maps. The shader brings the attribute into scope through the following GLSL declaration:

```
attribute vec4 glTangent4f;

```

The following sources only focus on the shader code and only mention, that the attribute is given by an engine. I guess that the engine itself calls one of the `glTangent`-functions.

**Sources:**

1. https://www.geeks3d.com/20091019/shader-library-bump-mapping-shader-with-multiple-lights-glsl/
2. http://probesys.blogspot.com/2011/01/tbn-matrix-explained\_02.html?m=1

**/Sources**

The following code snipped I found sets up the shader variables. It names the tangent vector variable `GLTangent`. It also sets up more common variables like `GLVertex` or `GLColor`.

```
glBindAttribLocation(p, VETYPE_TANGENT, "GLTangent");

```

Then the variable is accessed through

```
attribute vec4 GLTangent;

```

# Answer
> 0 votes
Tangent is a regular math term. As google describes it:

> a straight line or plane that touches a curve or curved surface at a point, but if extended does not cross it at that point.

It's always perpendicular with the normal vector.

It can be calculated from the normal vector alone, but since there are infinitely many tangents to any 3d vector, it's not always ideal to let OpenGL do it. It's used to create a 3d coordinate system where the normal always points upward (with two perpendicular axes, there can only be one, that's perpendicular to both). Illustration from http://www.opengl-tutorial.org/hu/intermediate-tutorials/tutorial-13-normal-mapping/:

Vector based coordinate systems are great, because we can create matrices, that transform arbitary vectors from the global coordinate system into the one we defined (in this case, into the tangent space) and vice-versa.

OpenGL probably uses the tangents to do normal mapping, since normals maps (almost) always contain the vectors in a local coordinate system. You need to transform them from the tangent space back to global space for them to be useful.

---
Tags: opengl
---


# Question
Title: Replacement for glMatrixMode() in OpenGL 4?
In OpenGL version 3.x the function `glMatrixMode()` specifies which matrix is the current matrix, i.e., which matrix stack is currently the target of all matrix operations based on the parameter, the choices being `GL_MODELVIEW`, `GL_PROJECTION`, and `GL_TEXTURE`.

`glMatrixMode()` had been deprecated in OpenGL version 4.x.

I have tried to find the equivalent way of performing the same effect in 4.x without success.

I suspect there has been a change in philosophy in OpenGL 4 which I am overlooking.

How is the `glMatrixMode()` equivalent performed in OpenGL version 4.x?

# Answer
`glMatrixMode` has been a legacy function for ages even before OpenGL 4 arrived. Since it only works with immediate mode, it hasn't been supported very well. **There's no alternative for it.**

You need to learn the programmable pipeline. It uses shaders instead of predefined effects (e.g. you need to create your own distance based fog instead of simply asking the video card to do it). It's obviously much harder to use, but the performance gains far outweigh the negatives.
> 3 votes

# Answer
I found this tutorial to be very helpful in learning how Modern OpenGL does things without `glMatrixMode()`: LearnOpenGL - Coordinate Systems

Legacy OpenGL implemented a series of transformation matrices that allowed you to define how a vertex would be transformed to get from world space to screen space.

Generally that formula looks like this:

```
Vec_screen = Mat_projection x Mat_view x Mat_model x Vec_local

```

So you see the built-in matrix functions from legacy OpenGL allow you to modify these matrices when their respective mode is active. `GL_PROJECTION` would be the product of your projection and view matrices, and `GL_MODELVIEW` would be the current model matrix on the stack.

Modern OpenGL does away with the built-in matrices entirely, it's now up to the programmer to implement those transformations from world space to screen space. This is precisely what the Vertex Shader is meant to do! It provides more control & freedom to the programmer and it is trivial to implement once you get the basics of shaders.

Here is a GLSL vertex shader implements the transformation of a vertex from model space into screen space: (taken from the linked tutorial)

```
#version 330 core
layout (location = 0) in vec3 aPos;
...
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

void main()
{
    // note that we read the multiplication from right to left
    gl_Position = projection * view * model * vec4(aPos, 1.0);
    ...
}

```

Any time you want to draw a model with a particular world-space transformation you just provide that model's local transformation in the `model` uniform, while your camera implementation would normally provide the other two matrices.
> 1 votes

# Answer
In modern OpenGL, you define any matrix you want to use as part of the shader program you load. *Get used to the idea that you will write shader code. It is scary, I know. It is not that bad, I promise.*

In particular, you will define them as "uniforms", which are data that will be available to the shader (but not associated to a vertex). You could pass other data as uniforms aside, including the inverse of the matrices for those cases where you need it...

For instance, some of my shader code starts like this:

```
#version 330 core

uniform vec2 resolution;
uniform float time;

uniform mat4 projection;
uniform mat4 inverseProjection;
uniform mat4 view;
uniform mat4 inverseView;
// ...

```

Here I am passing the size of the screen as a `vec2 resolution`, the current `time` as a `float` for animating in the GPU, and then some `mat4`, each one a transformation matrix.

So, how do we specify which of these uniforms we are setting?

We, will call `glGetUniformLocation`, with the `id` of our shader program (which you get from `glCreateProgram` as part of the process of setting your shaders) and the string name of the uniform you want.

Afterwards, you call a `glUniform` function, according to the datatype you want, passing the location you got from `glGetUniformLocation`.

Since we will setting a `mat4`, we will call `glUniformMatrix4fv`. You will find that you also need to specify a `bool` if you want to transpose the matrix when setting it (just in case you are using row major order, but OpenGL wants column major order).

Example:

```
// Get the location of the matrix you want to set
int modelLocation = glGetUniformLocation(shader_id, "model");
// Set it
glUniformMatrix4fv(modelLocation, 1, false, model[0]);
//                 ^              ^  ^      ^
//                 |              |  |      |
//                 |              |  |      pointer to the start of the matrix
//                 |              |  no, do not transpose my matrix
//                 |              only take one matrix from that pointer, thank you
//                 the location on the shader program where we are setting...
//                 ... that identifies what uniform we are setting

```

Oh, right, you can have an array of `mat4` as a `uniform`, for example:

```
// somewhere in the shader header
uniform mat4 bones[10];

```

Then set it in your code:

```
int bonesLocation = glGetUniformLocation(shader_id, "bones");
glUniformMatrix4fv(bonesLocation, 10, false, bones[0]);
//                                ^
//                                |
//                                Take 10 mat4

```

So, in a sense `glGetUniformLocation` is the replacement for `glMatrixMode`. *Please tell me are not using `glBegin` and `glEnd`.*

---

Finally, of course, if you want to mimic the old behavior, the matrix multiplication order would be `projection * view * model * vector` somewhere on your vertex shader.

Know that by writing your own shaders, you can go crazy...

I am currently writing a ray caster, and I have code like this:

```
// ...
gl_Position = vec4(position.xy, 0.0, 1.0);
cameraRayDirection = ((inverseView * inverseProjection) * gl_Position).xyz;
cameraRayPosition = (inverseView * vec4(0.0, 0.0, 0.0, 1.0)).xyz;
// ...

```
> 0 votes

---
Tags: opengl
---


# Question
Title: How do I cover a plane in a bumpy foam material effect?
I need to fill a weapon bag with foam material.

This is what it should look lik:

The material in the upper part of the bag looks like this:

I'm using HDRP.

How could I do this?

Thank you!

Edit: I have played around with Parallax Occlusion mapping, and I got this result.

Edit2: I am not sure if I use the Pixel Displacement as it has been suggested to me.

Also, I'm not sure if I use it the correct way:

I have created a Height map and put it into the Height map slot. This doesn't create any effect. I have to put the same map into the Base map slot in order to see the effect. If I put a black image into the Base map slot or if I choose Black as the Base color, no effect is visible.

I don't understand why this is so. I think even if my Base map is black, the Shader has pixels that it can move.

This is my height map:

Edit 3: It was suggested that I should use a normal map. This doesn't look at all what I expected. The normal map was created from the Height map using an online tool:

By Philipp's answer I found out that the normal map alone is not enough.

# Answer
A heightmap changes the *position* of the texels, but not their *color shade*. If you want some parts of the texture to be brighter and others darker depending on how they face the light source, then you want a normal map.

I used the texture you provided as both a normal map and a height map and created this material:

For the normal map image, select the import settings "Texture Type: Normal map" and switch on "Create from Grayscale". If you apply the import settings, the texture should appear light blue in the editor:

If you also want to use the same texture as a heightmap for displacement, then you need to create a copy of the image under a different name, so you can apply different import settings. It will work with the default settings, but because we only care about the brightness we don't need all 3 color channels. So you can reduce a bit of overhead by turning it into a "single channel" texture:

These are my material settings. I highlighted all values which I changed from the defaults:

Further steps you can take to improve these textures further:

* Make both maps less "pointy"
* Add some noise to the normal map
> 4 votes

---
Tags: unity
---


# Question
Title: How to assign separate controller axes to Player1, Player2?
I need to have two players moving in a level for a school project and my player controller is already set up for using axis inputs (as opposed to discreet buttons) for directional input. I already know I can assign custom *key* inputs from the inspector if I just declare a public variable (initialization optional because there is a drop-down list in the inspector):

```
public KeyCode jumpInput = KeyCode.Space;

```

How can I assign custom *directional axis* inputs from the inspector? I already have alternative horizontal and vertical axes defined in my preferences, I just need to know how to assign them.

Been putting this project together for **36 CONTIGUOUS** hours and I am ready to put it (and myself) to bed. Thank you in advance for your time.

**EDIT:** My confusion was coming from (beyond being awake too long) thinking that I needed a special data type (like KeyCode) for an Axis, and couldn't find it in the reference. But I didn't consider making a public *string* and plugging that into the input. This way, I just need to know what I named the new axes and use that for the public string.

# Answer
> 1 votes
if you assigned a new Axes in the ProjectSettings\>Input you can use it the same as you would the normal one. Assign the positive and negative buttons player 2 uses to move.

```
float newHorizontal = Input.GetAxis ("YourNewHorizontalInputName");

```

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