title: Double jump help

text:
# Question
Title: Double jump help
I'm trying to make double jumps for my FPS game in Unity. I have written so that if I press "Jump", (the space bar) and that I'm not grounded, I will jump again and that I wont be able to double jump any more by turning off a public bool. Normally if I'm falling and I press jump, I will jump and it works, but when I jump the first time, the `canDoublejump` bool just turns off, so could you someone maybe help me with it?

Code:

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

public class PlayerMovement : MonoBehaviour
{
    //Character Controller new name
    public CharacterController controller;
    //Basic Starting values
    public float speed = 12f;
    public float gravity = -9.81f;
    public float jumpHeight = 2.5f;
    public float doublejumpMultiplier = 0.5f;
    public bool canDoublejump = true;
    public bool grounded = true;

    //Assingables
    public Transform playerCam;

    //Other
    private void Jump()
    {
        velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
    }

    //New names for stuff and assignables
    private Rigidbody rb;

    //Not falling forever lol
    public Transform groundCheck;
    public float groundDistance = 0.4f;
    public LayerMask groundMask;

    Vector3 velocity;
    bool isGrounded;

    // Update is called once per frame
    void Update()
    {
        //Random Bullshit
        if (isGrounded) grounded = true;
        if (!isGrounded) grounded = false;

        //Gravity stuff
        velocity.y += gravity * Time.deltaTime;

        controller.Move(velocity * Time.deltaTime);

        //Walking
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

        if (isGrounded && velocity.y < 0)
        {
            velocity.y = -2f;
        }

        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");

        Vector3 move = transform.right * x + transform.forward * z;

        controller.Move(move * speed * Time.deltaTime);

        //Jumping
        if (Input.GetButtonDown("Jump") && isGrounded)
        {
            Jump();
            canDoublejump = true;
        }

        //Running
        if (Input.GetButton("LeftShift")) speed = 12f;
        if (Input.GetButtonUp("LeftShift")) speed = 6f;
        if (Input.GetButton("LeftShift")) jumpHeight = 4.25f;
        if (Input.GetButtonUp("LeftShift")) jumpHeight = 2.5f;
        //Crouching
        if (Input.GetButton("LeftCtrl")) controller.height = 1.2f;
        if (Input.GetButtonUp("LeftCtrl")) controller.height = 2f;
        if (Input.GetButton("LeftCtrl")) speed = 3f;
        if (Input.GetButtonUp("LeftCtrl")) speed = 6f;
        //Crawling
        if (Input.GetButton("C")) controller.height = 0.25f;
        if (Input.GetButtonUp("C")) controller.height = 2f;
        if (Input.GetButton("C")) speed = 1.75f;
        if (Input.GetButtonUp("C")) speed = 6f;
        //DoubleJump
        if (isGrounded) canDoublejump = true;
        if (!isGrounded && canDoublejump == true)
        {
            if(Input.GetButton("Jump"))
            {
                Jump();
            }
        }
        if (!isGrounded && Input.GetButton("Jump"))
        {
            canDoublejump = false;
        }
    }
}

```

# Answer
> 2 votes
Compare the three places you check the Jump button.

In one you use "GetButtonDown" to detect the press only on the frame when the button transitions from up to down.

In the other two, you use "GetButton" - this will also fire as long as the button is held down. Including on the frame after you successfully jump from the ground, immediately burning your double jump.

You can also simplify your code to something like...

```
if (isGrounded) {
    canDoublejump = true;
}

if (Input.GetButtonDown("Jump") && canDoubleJump) {
    canDoubleJump = isGrounded;
    Jump();
}

```

Handling both single and double-jumps in one place like this avoids code duplication, so you can't accidentally use the right function in one place and the wrong function in a different place: there's only one place where the functionality lives, making it leaner and easier to reason about.

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


# Question
Title: Networked game with physics and client side prediction and server reconsiliation causes lag
I'm trying to make a multiplayer platformer game. I can almost get client side prediction and server reconsiliation to work, but there is one issue that I just can't wrap my head around.

Lets say that the following scenario takes place.

* The server is running at a tick rate of 30 fps.
* State updates are being sent at a rate of 10 fps.
* Player movement events are being sent at a tick rate of 30 fps.

The player movement event consists of two fields `dx` and `jump`. Which tells the server what directions the player wants to move in. Now lets say the player presses the jump button and then mid-air decides to move sideways. This becomes very problematic as the client starts to move the player instantly. Meanwhile, the server starts to move the player a bit later, due to latently. Eventuelly missing one or two ticks. This leads to gravity pulling the player further downwards on the server before moving sideways, then on the client.

When the server sends the next state update that means the state is massively out of sync because in the servers eyes the player started moving left a bit later then they actually did. Here is a image that describes the situation better:

This problem have kept me up at night, because I can't see a single way the client is going to handle this without ending up the "wrong" position. I've tried multiple forms of client side correction. My most promising solution that still failed were:

* On the server when receiving a player event. Go back in time to the state that was current when that event was sent. Then reapply every event from that point on the server side. This seems like it would work but didn't for some reason.

This seems like such a fundamental flaw of networked game that I can't understand how ANY networked game works what so ever.

Any help would be very appreciated

# Answer
> 1 votes
Keep track of unconfirmed inputs (basically an array of the actual state of player's control buttons in each frame) on the client. Upon receiving the game state from the server, put the player back into the position that the server dictates. And now just replay all the inputs that server has not confirmed yet on the client. With this approach you don't need to go back in time on the server. The client simply lags a bit behind the server, but as it always replays its remaining inputs, it effectively hides the lag.

---
Tags: physics, networking, state, game-state
---


# Question
Title: How can I ease in and out of a Lerp motion over a set duration?
Here is the code I am using:

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

public class MoveToTarget : MonoBehaviour
{
    public enum TransitionState
    {
        None,
        MovingTowards,
        Transferring
    }

    public Transform destinationTransform;
    public float speed;
    public float lerpTime;
    public bool isChild = false;

    private Transform originTransform;
    private float timer;
    private TransitionState state = TransitionState.MovingTowards;

    void Start()
    {

    }

    void Update()
    {
        switch (state)
        {
            case TransitionState.MovingTowards:
                var v = destinationTransform.position - transform.position;
                if (v.magnitude < 0.001f)
                {
                    state = TransitionState.Transferring;
                    originTransform = destinationTransform;
                    timer = 0;
                    return;
                }
                Vector3 moveDir = v.normalized;
                transform.position += moveDir * speed * Time.deltaTime;
                break;

            case TransitionState.Transferring:
                timer += Time.deltaTime;
                this.transform.position = Vector3.Lerp(originTransform.position, destinationTransform.position, timer);
                if (timer >= 1.0f)
                {
                    this.transform.parent = destinationTransform;
                    isChild = true;
                    state = TransitionState.None;
                    this.enabled = false;
                    return;
                }
                break;

            default:
                this.enabled = false;
                return;
        }
    }
}

```

I have two questions :

1. How can I use the `lerpTime` variable to control the speed of the motion? Now it's taking a second more or less before the moving object finishes its motion and gets parented to the destination (at line 50):

this.transform.parent = destinationTransform;
2. How can I make the object increase its movement speed slowly to max and then gradually slow down and until it stops at the target? Should I use smoothdamp or lerp here?

# Answer
> 1 votes
```
case TransitionState.Transferring:

    // Divide deltaTime by your travel duration.
    // The longer you set the duration, the smaller the increments.
    timer += Time.deltaTime / lerpTime;

    // Compute a blend weight that eases in at the start and out at the end.
    float blend = Mathf.SmoothStep(0, 1, timer);

    // Use the blend weight for your lerp.
    this.transform.position = Vector3.Lerp(
                                 originTransform.position,
                                 destinationTransform.position,
                                 blend);

```

---
Tags: unity, c#, lerp, easing
---


title: Connecting rooms after BSP

text:
# Question
Title: Connecting rooms after BSP
```
package byog.Core;

import byog.TileEngine.TERenderer;
import byog.TileEngine.TETile;
import byog.TileEngine.Tileset;

import java.util.ArrayDeque;
import java.util.Random;

public class World {
    private final long SEED;
    private final Random RANDOM;
    private final TETile[][] world;
    private final int WIDTH;
    private final int HEIGHT;
    private boolean occupied[][];
    private ArrayDeque<Room> rooms = new ArrayDeque<>();

    public World(long SEED, TETile[][] tiles, int width, int height) {
        this.SEED = SEED;
        this.RANDOM = new Random(SEED);
        this.world = tiles;
        this.WIDTH = width;
        this.HEIGHT = height;
        this.occupied = new boolean[width][height];
    }

    public void render() {
        initialize();
        split();
        //connectRooms();
        TERenderer ter = new TERenderer();
        ter.initialize(WIDTH, HEIGHT);
        ter.renderFrame(world);
    }

    // fill with nothingness
    private void initialize() {
        for (int i = 0; i < WIDTH; i++) {
            for (int j = 0; j < HEIGHT; j++) {
                world[i][j] = Tileset.NOTHING;
            }
        }
    }

    private void split() {
        split(new Position(0, 0), new Position(WIDTH - 1, HEIGHT - 1), 0);
    }

    private void split(Position bottomLeft, Position topRight, int recursionDepth) {
        String direction = getRandomOrientation();
        // stop after 4 splitting iterations
        if (recursionDepth == 4) {
            makeRandomRoom(bottomLeft, topRight);
            return;
        }
        recursionDepth++;
        switch (direction) {
            case "vertical": {
                splitVertically(bottomLeft, topRight);
                // calculate positions for splitting the left side
                // bottomLeft will remain same and the topRight's y will remain same but
                // the new X will be halved
                int midX = (bottomLeft.x() + topRight.x()) / 2;
                Position midTopRight = new Position(midX, topRight.y());
                split(bottomLeft, midTopRight, recursionDepth);

                // for right half:
                Position midBottomLeft = new Position(midX, bottomLeft.y());
                split(midBottomLeft, topRight, recursionDepth);
                break;
            }
            // case horizontal
            default: {
                splitHorizontally(bottomLeft, topRight);
                int midY = (bottomLeft.y() + topRight.y()) / 2;

                // for top half:
                Position midTopLeft = new Position(bottomLeft.x(), midY);
                split(midTopLeft, topRight, recursionDepth);

                // for bottom half:
                Position midTopRight = new Position(topRight.x(), midY);
                split(bottomLeft, midTopRight, recursionDepth);
            }

        }
    }

    private void makeRandomRoom(Position bottomLeft, Position topRight) {
        int width, height;
        do {
            width = RANDOM.nextInt(Position.xDistance(bottomLeft, topRight) - 2); // -2 because of walls
            height = RANDOM.nextInt(Position.yDistance(bottomLeft, topRight) - 2); // -2 because of walls
        } while (width <= 0 || height <= 0);

        /* TODO - add randomness to room generation; rn we start at bottom left coordinate,
                  you should be able to start at a different reasonable coordinate
         */
        // +1 to not collide with the walls
        int x = bottomLeft.x() + 1;
        int y = bottomLeft.y() + 1;
        for (int i = x; i <= x + width; i++) {
            for (int j = y; j <= y + height; j++) {
                world[i][j] = Tileset.GRASS;
            }
        }

        Room room = new Room(new Position(x, y), new Position(x + width, y + height));
        // adjacent rooms will be added adjacently in the deque
        rooms.add(room);
    }

    // since adjacent rooms were added together, we may remove two rooms at once and connect them
    private void connectRooms() {
        while (!rooms.isEmpty()) {
            Room r1 = rooms.poll();
            Room r2 = rooms.poll();

            // horizontally aligned
            if (r1.getBottomLeft().x() == r2.getBottomLeft().x()) {
                Room atBottom = Room.smallerBottomLeftY(r1, r2);
                Room atTop = atBottom == r1 ? r2 : r1;
                int bottomY = atBottom.getBottomLeft().y() + atBottom.getHeight() + 1;
                int topY = atTop.getBottomLeft().y() - 1;
                int x = atBottom.getBottomLeft().x();
                for (int i = bottomY; i <= topY; i++) {
                    world[x][i] = Tileset.GRASS;
                }
            } else {
                Room atLeft = Room.smallerBottomLeftX(r1, r2);
                Room atRight = atLeft == r1 ? r2 : r1;

                int leftX = atLeft.getBottomLeft().x() + atLeft.getWidth() + 1;
                int rightY = atRight.getBottomLeft().x() - 1;

                int y = atLeft.getBottomLeft().y();

                for (int i = leftX; i <= rightY; i++) {
                    world[i][y] = Tileset.GRASS;
                }
            }

        }
    }

    private void splitVertically(Position bottomLeft, Position topRight) {
        int midX = (bottomLeft.x() + topRight.x()) / 2;
        for (int i = bottomLeft.y(); i <= topRight.y(); i++) {
            world[midX][i] = Tileset.WATER;
        }
    }

    private void splitHorizontally(Position bottomLeft, Position topRight) {
        int midY = (bottomLeft.y() + topRight.y()) / 2;
        for (int i = bottomLeft.x(); i <= topRight.x(); i++) {
            world[i][midY] = Tileset.WATER;
        }
    }

    private String getRandomOrientation() {
        int direction = RANDOM.nextInt(2);
        switch (direction) {
            case 0:
                return "horizontal";
            default:
                return "vertical";
        }
    }

}

```

Using the BSP algorithm, I am able to generate rooms (green floor) like: (The blue walls are just for clarity and will be removed later)

I cannot figure out how to connect adjacent rooms. I tried the `connectRooms()` method and it does work for 2 rooms but it cannot handle further connections:

So how do I proceed with connecting the rooms?

# Answer
The answer is in your question title. You are meant to assign doors just *after* each `split()`, hierarchically, **not* after* the entire BSP process has run. OR, you can do it after the process has run, but then you need to have kept the original BSP tree (see right hand side of diagrams below), so that you can rewalk the entire tree again. I'd just do it while the tree is being created, as below,

This ensures connectedness at every level of the tree and thus solves your problem. Visualising your structure as nodes on a binary tree should help you understand. The initial state is the "root" of the tree, the second state the first two "branches", etc. Each split "replaces" the rendering of the parent room, with that of its 2 children. Yet if you maintain the underlying BSP tree structure, all those ancestors still exist.

Here is a linear example (straight tunnel maze, no forks). **D** are doors.

```
+-----------+                      0
|0          |
|           |
|           |
|           |
|           |
|           |
|           |
|           |
|           |
+-----------+

```

1st split

```
+-----------+                      0
|1          |                     / \
|           |                    1=D=2
|           |
|           |
|           |
+--------D--+
|2          |
|           |
|           |
+-----------+

```

2nd split, notice how **1**'s connection to **2** now gets delegated down to **1**'s children, **3** & **4**:

```
+-----------+                      0
|3    D    4|                     / \
|     |     |                    1 D 2
|     |     |                   /|
|     |     |                  3D4
|     |     |
+-----+--D--+
|2          |
|           |
|           |
+-----------+

```

3rd split

```
+-----------+                      0
|3    D    5|                     / \
|     |     |                    1 D 2
|     +----D|                   /|
|     |     |                  3D4
|     |    6|                   /|
+-----+--D--+                  5D6
|2          |
|           |
|           |
+-----------+

```

4th split

```
+-----------+                      0
|3    D    5|                     / \
|     |     |                    1 D 2
|     +----D|                   /|   |\
|     |     |                  3D4   7D8
|     |    6|                   /|
+-----+--D--+                  5D6
|7  |      8|
|   D       |
|   |       |
+---+-------+

```

Step 5 shows forking. Note how this can only happen at one of the ends of the linear path (could also happen in bottom left most room **7**, as that is the other end of the chain):

```
+-----------+                      0
|3    D    5|                     / \
|     |     |                    1 D 2
|     +----D|                   /|   |\
|D-+-D|     |               ...3D4   7D8
|9 |10|    6|               .   /|\
+--++-+--D--+               .  5D6 \
|7  |      8|               .      |\
|   D       |               ...D...9 10
|   |       |               .        .
+---+-------+               ...D......

```

Notice how when forking (creating **9 & 10**), we pick their parent's (**4**'s) sibling (**3**) and join 9 & 10 to it via **D**oors. Let's call this "the nephew effect". ;) Here, *branches* are `/|\`, maze forks are represented by `...`.

*Forks* mean *branches* in a maze sense, but I prefer the use of *fork* here because graph terminology has *branch* meaning something else (which you can already see in step 1). Note than until step 4, you could lay one straight string through the entire maze (all rooms) from start to finish. At step 5 (fork), you could not, as the end of the string would have to be in *either* room 9 or 10.

P.S. Note that I say fork "could only happen at the ends" - actually no, you could also fork in the middle of the linear flow, but this leads to cycles, and those can cause problems with pathfinding etc. (not always, though).
> 1 votes

---
Tags: java, 2d, algorithm, grid, binary
---


# Question
Title: Returns an error : index was outside the bounds of the array
```
public int Money1;
public Text MONEYtext;

public void Save()
{
    PlayerPrefs.SetString("VideoCard", JsonUtility.ToJson(VideoCard));
}

public void Load()
{
    VideoCard = JsonUtility.FromJson<GameObject[]>(PlayerPrefs.GetString("VideoCard"));
}

private void Update()
{
    MONEYtext.text = Money1.ToString();
    Money1 = PlayerPrefs.GetInt("Money1");

    //----------------------------------------

    if (BuyCard <= 4)
    {
        BuyButton.SetActive(true);
    }
    else
    {
        BuyButton.SetActive(false);
    }

}

//--------------------------------------------------

public GameObject BuyButton;
public int BuyCard = 0;
public GameObject[] VideoCard;

private void Start()
{
    BuyCard = PlayerPrefs.GetInt("BuyCard", BuyCard);
    Load();
}

public void BuyCards()
{
    if (Money1 >= 299)
    {
        BuyCard++;
        Money1 -= 299;
        PlayerPrefs.SetInt("Money1", Money1);
        PlayerPrefs.GetInt("BuyCard", BuyCard);
        VideoCard[0].SetActive(true);
        Save();
    }
}

```

}

I can't understand why it gives an error , because the size of the array is 5 , I put the value of the first element of the array

# Answer
> 1 votes
You cannot deserialize GameObjects from JSON the way you are attempting to do here.

`VideoCard = JsonUtility.FromJson<GameObject[]>(PlayerPrefs.GetString("VideoCard"));`

It tells you so right in the documentation \- so please don't neglect to read it, especially when troubleshooting a problem!

> Only plain classes and structures are supported; classes derived from UnityEngine.Object (such as MonoBehaviour or ScriptableObject) are not.

So what's happening is that when you try to deserialize the GameObject array from JSON, the method refuses to do this forbidden thing, just like the docs tell you it will, and you get back an empty array.

Trying to access the first element of an empty array naturally throws an exception - it doesn't *have* a first element!

If you want to deserialize information stored in UnityEngine.Object types, you'll need to first create the objects you want within your scene or via script, and then load the data *into* them using eg. FromJsonOverwrite for `MonoBehaviour` components on those objects.

So your real problem here appears to be "How do I save and load information about the player's purchases". Asking about a the exception only obfuscates that problem. So in future, please ask about what you are trying to accomplish, not about standard exceptions you can easily search on StackOverflow.

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


# Question
Title: How to complete a level and move on to the next level?
So, I need to load a different level when the user has crossed the entire level and collides (or triggers) a certain object. For that I have declared

```
using UnityEngine;
using UnityEngine.SceneManagement;

public class PacMan : MonoBehaviour
{
    bool GameEnded = false;
    public float delay;

    // Ends the level
    public void GameOver()
    {
        if (GameEnded == false)
        {
            GameEnded = true;
            Invoke("Restart", delay);
        }
    }

    public GameObject LvlCompleteUI;

    // Restarts the level
    void Restart()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }

    public void LvlComplete()
    {
        LvlCompleteUI.SetActive(true);
        Debug.Log("GameOver");
    }
}

```

and then calling the function via

```
public class WinTrigger : MonoBehaviour
{
    // public PacMan pacMan;

    void OnCollisionEnter(Collision collision)
    {
        if (collision.collider.tag == "LvlWon")
        {
            FindObjectOfType<PacMan>().LvlComplete();
        }

        // FindObjectOfType<PacMan>().LvlComplete();
        // pacMan.LvlComplete();
    }
}

```

But, this is not working as the collision doesn't seem to be working. Neither does trigger. Any ideas why this is not working? Maybe the way I am doing it is wrong.

Edit:

* PacMan is my PACkage MANager; basically it loads the scenes.
* The WinBox is the object that will load the next scene on collision.
* I did have Is Trigger on when I was trying the OnTriggerEnter() method.

**PacMan script:**

```
    using UnityEngine;
    using UnityEngine.SceneManagement;

    public class PacMan : MonoBehaviour
    {
        bool GameEnded = false;
        public float delay;

        // Ends the level
        public void GameOver()
        {
            if (GameEnded == false)
            {
                GameEnded = true;
                Invoke("Restart", delay);
            }
        }

        public GameObject LvlCompleteUI;

        // Restarts the level
        void Restart()
        {
            SceneManager.LoadScene(SceneManager.GetActiveScene().name);
        }

        public void LvlComplete()
        {
            LvlCompleteUI.SetActive(true);
            Debug.Log("GameOver");
        }
    }

```

**Movement Script:**

```
    using UnityEngine;

    public class Movement : MonoBehaviour
    {
        public Rigidbody RB;

        // public bool forward;
        // public bool back;
        public bool left;
        public bool right;

        // public string isTrueF;
        // public string isTrueB;
        public string isTrueL;
        public string isTrueR;

        void Update()
        {
            // bool forward = Input.GetKey(KeyCode.W);
            // bool back = Input.GetKey(aKeyCode.S);
            bool left = Input.GetKey(KeyCode.A);
            bool right = Input.GetKey(KeyCode.D);

            // if (forward == true)
            // {
            //     isTrueF = "True";
            // } else {
            //     isTrueF = "False";
            // }
            // if (back == true)
            // {
            //     isTrueB = "True";
            // } else {
            //     isTrueB = "False";
            // }
            if (left == true)
            {
                isTrueL = "True";
            } else {
                isTrueL = "False";
            }
            if (right == true)
            {
                isTrueR = "True";
            } else {
                isTrueR = "False";
            }
        }

        void FixedUpdate()
        {
            // if (isTrueF == "True")
            // {
            //     RB.AddForce(1000 * Time.deltaTime, 0, 0);
            // }
            // if (isTrueB == "True")
            // {
            //     RB.AddForce(-1000 * Time.deltaTime, 0, 0);
            // }
            RB.AddForce(0, 0, 500 * Time.deltaTime);

            if (isTrueL == "True")
            {
                RB.AddForce(-25 * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
            }
            if (isTrueR == "True")
            {
                RB.AddForce(25 * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
            }

            if (RB.position.y <= 0f)
            {
                FindObjectOfType<PacMan>().GameOver();
            }

            // if (Input.GetKey("d"))
            // {
            //     RB.AddForce(1000 * Time.deltaTime, 0, 0);
            // }
            // if (Input.GetKey("a"))
            // {
            //     RB.AddForce(-1000 * Time.deltaTime, 0, 0);
            // }
            // if (Input.GetKey("w"))
            // {
            //     RB.AddForce(0, 0, 1000 * Time.deltaTime);
            // }
            // if (Input.GetKey("s"))
            // {
            //     RB.AddForce(0, 0, -1000 * Time.deltaTime);
            // }
        }
    }

```

**Win Trigger Script:**

```
    using UnityEngine;

    public class WinTrigger : MonoBehaviour
    {
        // public PacMan pacMan;

        void OnCollisionEnter(Collision collision)
        {
            if (collision.collider.tag == "Finish")
            {
                FindObjectOfType<PacMan>().LvlComplete();
            }

            // FindObjectOfType<PacMan>().LvlComplete();
            // pacMan.LvlComplete();
        }
    }

```

**Player Collision Script:**

```
    using UnityEngine;

    public class PlayerCollision : MonoBehaviour
    {
    void OnCollisionEnter (Collision collisionInfo)
    {
        if (collisionInfo.collider.tag == "Obstacles")
        {
            GetComponent<Movement>().enabled = false;
            FindObjectOfType<PacMan>().GameOver();
        }
    }

```

Here's the hierarchy and first map:

# Answer
> 1 votes
The object passed to an `OnCollisionEnter` method is the other object triggering the collision. The method of your class `WinTrigger` is checking if that object has the tag `"Finish"` before doing anything else. But the player does not have that tag. It doesn't have a tag at all. So nothing is going happen here.

I would write the method like this:

```
void OnCollisionEnter(Collision collision)
{
    var pacMan = collision.gameObject.GetComponent<PacMan>();
    if (pacMan != null)
    {
        pacMan.LvlComplete();
    }
}

```

This code attempts to retrieve the `PacMan` component from the object which triggered the collision. When the object has such a component, then it calls the `LvlComplete` method on it. When the object doesn't have such a component, the method does nothing.

I greatly prefer this pattern of identifying collision partners via their components over the use of tags for several reasons:

1. You can only put one tag on an object, which quickly becomes insufficient in more complex games with multiple interlocking systems. But you can add any number of components to an object. Sometimes I create pure "tag components" which are completely empty classes inheriting from `MonoBehaviour` and only exist to tag a gameObject as eligible for some interaction which is implemented somewhere else.
2. You usually only care about whether or not the colliding object supports certain operations this collision will cause. Which it usually does if it has all the required components.
3. Your development environment will tell you immediately when you misspell a component name in `GetComponent<PakMan>()`. But tag names are string literals. So when you misspell them, then your code just won't work and no error or warning message will give you a hint why.

---
Tags: unity, c#, levels, scenemanager
---


# Question
Title: How can I increase the amount of peaks in Perlin noise without decreasing sampling frequency?
I'm generating my game's map using Perlin noise. It's an infinite 2D world with terrain data loaded on demand. I'm using Perlin noise to generate terrain. However, I've noticed that the Perlin noise implementation I'm using is periodic, and this is at a noticeable distance (repetition begins at about 400 tiles).

Many answers I've seen online involve sampling at a higher frequency, but this decreases the number of peaks and troughs in a given area. **I'm not looking for layering techniques which only add more octaves, I need the variation to be along the entire range of the noise function.** An example of what I mean:

This is an image of roughly what I have currently, which is basically what I want:

Increasing the sampling frequency yields this result, which is noticeably flatter:

Adding more octaves on top of that flatter noise makes it more jagged locally, but doesn't create peaks or troughs on the global level:

Is there a way to get a result like the first one with lots of peaks and troughs on a macro scale using Perlin noise, while keeping the period reasonably large, say, 5000 tiles?

# Answer
> 1 votes
## Dynamic Implementation

Optimally, I would just use a Perlin-noise implementation which doesn't repeat so quickly, or at all. If speed isn't of utmost importance, then I don't see a reason that Perlin-noise can't be generated dynamically at runtime based on some non-repeating random number generator, rather than from a look up table.

## Working with what you got

##### 2D

You could try using the output of one Perlin noise function as the input to another - now you're sampling a point from 2-dimensional Perlin-noise-space and it'll be very unlikely to get repetition.

```
x += noise(time);
var y2 = noise(x);

```

##### Layered

You could also try layering outputs of two independent Perlin-noise functions, perhaps sampling them at different rates with different levels of octaves. $$ y = noise(time, octave) + noise(a \*time + constant, b\*octave) $$

## More Control

If you really want to fine tune the feel of perlin noise -- in terms of adjusting the appearance of macroscopic vs microscopic features -- you could try manipulating the influence of noise at various "octaves".

You could give yourself complete control over this function using a Bezier curve or some other spline. Of course this would mean creating your own Perlin-noise inspired implementation, or modifying an existing algorithm.

# Answer
> 1 votes
Your issue is that it's tileable, and you don't want it to be, if I understand correctly? In that case, I would seek a noise implementation that isn't periodic, at least not on the scale of your world.

Secondly Perlin as a noise function is very square-aligned. It's an artifact of its fundamental inner workings that not enough people talk enough about. Take it with a grain of salt when sources recommend it with no caveats or clarifications. It's better generally to use a good implementation of a Simplex-type noise, or a Perlin that has its artifacts mitigated (e.g. through 3D domain rotation).

FastNoiseLite's noise functions are not periodic. You can take it and then use the OpenSimplex2 or OpenSimplex2S options. https://github.com/Auburn/FastNoiseLite/

p.s. In your second image where you describe increasing the sampling frequency, you actually have the frequency decreased, not increased. Doesn't affect the conclusion you came to, just the technicalities behind it.

---
Tags: procedural-generation, perlin-noise, procedural, noise
---


# Question
Title: Why the AnimationCurve is not working with Lerp?
The main goal is to move an object to target with ease in out speed. The speed should increase at the start to max than near the target to slow down smoothly and stop at the target.

At the top of the script, I did

```
public AnimationCurve curve = AnimationCurve.EaseInOut(0.0f, 0.0f, 1.0f, 1.0f);
public Transform start;
public Transform end;
public float duration = 10.0f;
private float t;

```

At the Start

```
void Start()
    {
        t = 0.0f;
    }

```

The Update

```
void Update()
    {
        switch (state)
        {
            case TransitionState.MovingTowards:
                var v = destinationTransform.position - transform.position;
                if (v.magnitude < 0.001f)
                {
                    state = TransitionState.Transferring;
                    originTransform = destinationTransform;
                    timer = 0;
                    return;
                }
                t += Time.deltaTime;
                float s = t / duration;
                transform.position = Vector3.Lerp(transform.position,
                    destinationTransform.position, curve.Evaluate(s));
                break;

            case TransitionState.Transferring:
                timer += Time.deltaTime;
                this.transform.position = Vector3.Lerp(originTransform.position, destinationTransform.position, timer);
                if (timer >= 1.0f)
                {
                this.transform.parent = destinationTransform;
                isChild = true;
                state = TransitionState.None;
                this.enabled = false;
                return;
                }
                break;

            default:
                this.enabled = false;
                return;
        }
    }

```

This is where I use the lerp and the animation curve :

```
t += Time.deltaTime;
float s = t / duration;
transform.position = Vector3.Lerp(transform.position,
destinationTransform.position, curve.Evaluate(s));

```

The variable destinationTransform is the target.

No matter what value I put in the duration variable the transform is moving too fast to the target. Tried to change the duration to 1 to 100 to 10 same speed.

This is how the animation curve graph is in the inspector :

I changed the animationcurved to be like that in the editor in the inspector but it's not affecting the speed of the transform movement in any way. There is no ease in/out effect. The speed is constant at a very very high speed.

The full script :

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

public class MoveToTarget : MonoBehaviour
{
    public enum TransitionState
    {
        None,
        MovingTowards,
        Transferring
    }

    public Transform destinationTransform;
    public float speed;
    public float lerpTime;
    public bool isChild = false;

    public AnimationCurve curve = AnimationCurve.EaseInOut(0.0f, 0.0f, 1.0f, 1.0f);
    public Transform start;
    public Transform end;
    public float duration = 10.0f;
    private float t;

    private Transform originTransform;
    private float timer;
    private TransitionState state = TransitionState.MovingTowards;

    void Start()
    {
        t = 0.0f;
    }

    void Update()
    {
        switch (state)
        {
            case TransitionState.MovingTowards:
                var v = destinationTransform.position - transform.position;
                if (v.magnitude < 0.001f)
                {
                    state = TransitionState.Transferring;
                    originTransform = destinationTransform;
                    timer = 0;
                    return;
                }
                Vector3 moveDir = v.normalized;
                //transform.position += moveDir * speed * Time.deltaTime;
                t += Time.deltaTime;
                float s = t / duration;
                transform.position = Vector3.Lerp(originTransform.position,
                    destinationTransform.position, curve.Evaluate(s));
                break;

            case TransitionState.Transferring:
                timer += Time.deltaTime;
                this.transform.position = Vector3.Lerp(originTransform.position, destinationTransform.position, timer);
                if (timer >= 1.0f)
                {
                this.transform.parent = destinationTransform;
                isChild = true;
                state = TransitionState.None;
                this.enabled = false;
                return;
                }
                break;

            default:
                this.enabled = false;
                return;
        }
    }
}

```

The part I'm using the lerp this time is to move the transform to the target not to make the transform child like in the other question.

From lines 49 to 52 :

```
t += Time.deltaTime;
float s = t / duration;
transform.position = Vector3.Lerp(originTransform.position,
    destinationTransform.position, curve.Evaluate(s));

```

# Answer
Solution :

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

public class MoveToTarget : MonoBehaviour
{
    public enum TransitionState
    {
        None,
        MovingTowards,
        Transferring
    }

    public Transform destinationTransform;
    public float speed;
    public float lerpTime;
    public bool isChild = false;

    public AnimationCurve curve = AnimationCurve.EaseInOut(0.0f, 0.0f, 1.0f, 1.0f);
    public Transform start;
    public Transform end;
    public float duration = 10.0f;
    private float t;

    private Transform originTransform;
    private float timer;
    private TransitionState state = TransitionState.MovingTowards;
    private Vector3 originTrans;

    void Start()
    {
        t = 0.0f;

        curve.postWrapMode = WrapMode.PingPong;
        originTrans = transform.position;
    }

    void Update()
    {
        switch (state)
        {
            case TransitionState.MovingTowards:
                var v = destinationTransform.position - transform.position;
                if (v.magnitude < 0.001f)
                {
                    state = TransitionState.Transferring;
                    originTransform = destinationTransform;
                    timer = 0;
                    return;
                }
                Vector3 moveDir = v.normalized;
                t += Time.deltaTime;
                float s = t / duration;
                transform.position = Vector3.Lerp(originTrans,
                    destinationTransform.position, curve.Evaluate(s));
                break;

            case TransitionState.Transferring:
                timer += Time.deltaTime;
                this.transform.position = Vector3.Lerp(originTransform.position, destinationTransform.position, timer);
                if (timer >= 1.0f)
                {
                    this.transform.parent = destinationTransform;
                    isChild = true;
                    state = TransitionState.None;
                    this.enabled = false;
                    return;
                }
                break;

            default:
                this.enabled = false;
                return;
        }
    }
}

```

and the graph in the editor :

I selected the last one to the right on the bottom graphs options :
> 0 votes

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


# Question
Title: What is the difference between "8 bit" and "16 bit" in the context of retro game aesthetics?
I am not a game dev here but have a few queries. I was recently playing a game called "The messenger" where you move from 8bit to 16bit when travelling through time. So whenever we are in future the graphics and the sound turned to 16 bit and in the present the graphics were 8bit.

Now my query is regarding the 8bit/16bit sound and graphics? What do they exactly mean?

I read about the canvas size when making a pixel art game tends to be 8\*8/16\*16/32\*32/64\*64 which directly means the number of pixels in a sprite, so if there are more pixels we can have more detailed sprites and animations.

For music, I read that it represents the number of instrument choices that you have when creating music.

Do you consider these explanations to be correct?

# Answer
When people talk about 8bit graphic and sound vs. 16bit graphics and sound in the context of retro-game aesthetics, then they often talk about the graphic and sound capabilities of gaming consoles and PCs of the 8bit generation vs. those of the 16bit generation.

The main contenders of the 8bit generation were the Sega Master System and the Nintendo Entertainment System (NES). The 16bit generation were the Sega Mega Drive (Sega Genesis in North America) and the Nintendo Super-NES.

The hardware capabilities of those consoles were different, so **there is no clear-cut definition of 8bit or 16bit**. But in contrary to the answer by DHarding **they did not support full 8bit or 16 bit color depth**. The hardware of that time only offered a reduced color palette. Further, developers had to choose a limited palette of those visible on the screen at once and an even smaller palette per unique spirite.

| Conosle | Colors | Colors per screen | Colors per sprite |
| --- | --- | --- | --- |
| NES | 54 | 25 | 4 |
| Master System | 64 | 32 | 16 |
| SNES | 32768 | 256 | 16 |
| Mega Drive | 512 | 61 | 16 |

These palette restrictions were a main driver behind the visual aesthetics of the games of that time. They resulted in typical stylistic choices of that time:

* Environments using a single dominant color, because complimentary colors would have used up too many of the colors per screen.
* Or alternatively, environments which were more colorful, but with a lot of "flat" colors and little shading.
* Sprites with even more limited color palettes.
* Palette swapping. Some of these systems were able to switch out palettes of sprites on the fly. This didn't just allow to reuse sprites for different game entities by simply changing their color. It also allowed to create some neat (for that time) animation effects based on color-cycling without requiring to add the sprite data for all animation phases.
* Dithering to mix colors and to do brightness gradients (which actually looked a lot better on old CRT TVs than it looks on modern LED screens).

The screen resolutions of those consoles were actually all the same: 256 x 240 in Europe and 256x224 in North-America. Why? Because that was the resolution of TV sets of that time. It just wouldn't have been possible to go higher without requiring to sell a dedicated monitor with the gaming system. Yet modern retro-games aiming for a 16bit aesthetic often tend to use higher resolutions than those aiming for an 8bit aesthetic.

When it comes to audio capabilities it becomes even more confusing than with graphics, due to the very different ways the consoles of that time created sound. But in general the consoles only had very limited capabilities for playing pre-recorded digital audio (like all the sound you hear in games of today). There just wasn't enough storage space for that. They instead synthesized music and sound effects right on the device. They usually had a limited number of oscillators on board with a limited number of settings. The technical details of synthesizers are not my area of expertise, but you can definitely hear the difference in audio between the two generations. The 8bit generation was a lot more dominated by beeps and buzzes, while the 16bit generation could produce sounds which sort of sounded like modern synths, occasionally even real instruments and a few games even managed to get halfway decent voice samples out of that hardware.

Music produced today under the restrictions of 8bit and 16bit hardware is often called "chiptune". But you don't need to use old audio hardware for making chiptune music, because modern digital audio workstations are capable of replicating those sounds pretty faithfully.
> 5 votes

# Answer
I agree that the developer is referring to storage classes. Wider (more bits in the storage class) storage class’s make it possible to store larger objects or finer detail.

In the example below I use a wave file format to represent the storage class. I am much more familiar with rendering graphics (Video) but have a sound class in my game as well. It plays wave files that I pass to it without regard to fidelity. I give an example from that class below.

In general, 8Bit and 16Bit represent storage classes such as the following BYTE is 8Bit = 2^8 or 256 colors WORD is 16Bit = 2^16 or 65,536 colors

If what you are saying is correct about transitioning to a higher number of bits as the game progresses, then the developer is rendering graphics (or can) with a higher number of colors (also called higher resolution).

For example, the initial storage class would be BYTE then transition to WORD. I would not code this way in practice however, since a WORD is two BYTEs, and I could code 1 BYTE of storage in a WORD and then later store a full word. This would be simpler and would not require changing the underlying storage class for an object.

With regard to sounds, I will leave an example of a storage class that I use in practice. The PCMWAVEFORMAT to represent a wave object, which is represented by the following data structure. Again, here you can see the usage of the WORD to buffer sound, were a WORD is 2 BYTES

typedef struct pcmwaveformat\_tag { WAVEFORMAT wf; WORD wBitsPerSample; } PCMWAVEFORMAT, \*PPCMWAVEFORMAT, \*NPPCMWAVEFORMAT, \*LPPCMWAVEFORMAT;

A little research on these storage classes would help to clarify this final example.
> 0 votes

---
Tags: terminology, music, pixel-art
---


# Question
Title: Tile based collision detection errors if player is smaller than tiles
I have implemented a tilemap where each tile is at a non-negative x and y position. (So at the moment think like chess)

At the moment a tile is `16, 16` pixels in size

`Tile 0,0` is at the **left bottom corner**

Some tiles should be collidable. I've never implemented something like that and during research stumbled upon: https://jonathanwhiting.com/tutorial/collision/

The general idea + collision response handling:

```
let mut new_pos = Point2::new(curr_pos.x + x_offset, curr_pos.y);

let collision_on_x = collide_with_world(&new_pos, &world);

if !collision_on_x  {
    transform.translate_x(x_offset);
}

new_pos.y = curr_pos.y + y_offset;

let collision_on_y = collide_with_world(&new_pos, &world);

if !collision_on_y  {
    transform.translate_y(y_offset);
}

```

The collision detection

```
fn collide_with_world(new_pos: &Point2<f32>, world: &World) -> bool {
    // TODO make these sizes i16 instead so we can grow in any direction!
    let mut left_tile: u16 = (new_pos.x / TILE_SIZE_IN_PIXELS as f32) as u16;
    // -1 so that we do not collide until we are exactly at the thing
    let mut right_tile: u16 = ((new_pos.x + PLAYER_WIDTH - 1.0) / TILE_SIZE_IN_PIXELS as f32) as u16;
    let mut top_tile: u16 = ((new_pos.y + PLAYER_HEIGHT - 1.0) / TILE_SIZE_IN_PIXELS as f32) as u16;
    let mut bottom_tile: u16 = (new_pos.y / TILE_SIZE_IN_PIXELS as f32) as u16;

    println!("new_pos: {:?}, left {}, right {}, top {}, bottom {}", (new_pos.x, new_pos.y), left_tile, right_tile, top_tile, bottom_tile);

    // Useless as long as we use unsigned coordinates
    //if left_tile < 0 {
    //    left_tile = 0;
    //}

    if right_tile > WORLD_WIDTH_IN_TILES {
        right_tile = WORLD_WIDTH_IN_TILES;
    }

    // Useless as long as we use unsigned coordinates
    //if bottom_tile < 0 {
    //    bottom_tile = 0;
    //}

    if top_tile > WORLD_HEIGHT_IN_TILES {
        top_tile = WORLD_HEIGHT_IN_TILES;
    }

    let mut any_collision = false;

    for i in left_tile..=right_tile {
        for j in bottom_tile..=top_tile {
            let tile = world.get_tile(i, j);
            println!("tile at {:?} is {:?}", (i, j), tile);

            match tile {
                Some(tile) => {
                    if tile == WALL {
                        println!("hit a wall at {:?}!", (i, j));
                        any_collision = true;
                    }
                }
                None => (),
            }
        }
    }

    return any_collision;
}

```

I basically took (or tried to take) the optimised version of the linked blog-entry.

Now to the problems:

If `PLAYER_WIDTH` and `PLAYER_HEIGHT` are both 16.0 - collision works fine

***But note*** that I had to put `-1.0` in the calculation of the `right_tile` and `top_tile`, else the collision for UP and RIGHT would occur one pixel to early (so the player would never touch walls to their top or right)

This change alone makes me a bit suspicious - looks like I made an error there.

The real problems start if the player is smaller than a tile:

In the following screenshots the following rules apply:

\*) the `PLAYER_WIDTH` and `PLAYER_HEIGHT` are both `8` \*) Greenish tiles are the only walls! \*) **All the screenshots were taken in ONE run - no parameters were changed during this run!**

1)  -\> Trying to collide with right tile -\> overlapping 2)  -\> Trying to collide with top tile -\> cannot go any nearer than 4 pixels (half the height of the player) 3)  -\> Trying to collide with left tile -\> cannot go any nearer than 4 pixels (half the width of the player) 4)  -\> Trying to collide with top tile -\> suddenly overlapping although different tile didn't collide? 5)  -\> Trying to collide with bottom tile -\> cannot go any nearer than 4 pixels

I cannot grasp 2 and 4 at the moment.

# Answer
Does new\_pos define the player's center, or its bottom-left corner? Because your checks make sense if it's the corner, but usually location is defined by centers. Try this -

```
let width_change = PLAYER_WIDTH /2;
let height_change = PLAYER_HEIGHT /2;
let mut left_tile: u16 = ((new_pos.x - width_change) / TILE_SIZE_IN_PIXELS as f32) as u16;
let mut right_tile: u16 = ((new_pos.x + width_change - 1.0) / TILE_SIZE_IN_PIXELS as f32) as u16;
let mut top_tile: u16 = ((new_pos.y + height_change - 1.0) / TILE_SIZE_IN_PIXELS as f32) as u16;
let mut bottom_tile: u16 = ((new_pos.y - height_change) / TILE_SIZE_IN_PIXELS as f32) as u16;

```
> 0 votes

# Answer
Consider this an answer also. This example isolates the hit detection to movement in the upward direction only, with further isolation from sprite to a single non playable object. It uses rectangular hit detection. I am placing non playable objects on a tiled background also. The sprite and non playable objects are at the same z-order for now.

else if (up) { pGraveyard\_Objects-\>DisplayGraveyardFence();
pGraveyard\_Objects-\>DisplayGraveyardObjects();

```
    // NonPlayableObject npo_pumpkin
    // PlayableObject po_sprite

    po_sprite.x = buzzR->row;
    po_sprite.y = buzzR->col;

    po_sprite.width = TILE_WIDTH;
    po_sprite.height = TILE_HEIGHT;

    //NonPlayableObject npo_pumpkin;
    npo_pumpkin.x = FENCE_RIGHT;
    npo_pumpkin.y = FENCE_BOTTOM + (TILE_HEIGHT);

    npo_pumpkin.width = TILE_WIDTH;
    npo_pumpkin.height = TILE_HEIGHT;

    if (rectHit(po_sprite, npo_pumpkin))
    {
        wave2->Play();
        buzzR->MoveTo(buzzR->row, buzzR->col -= GRANULARITY_IN_Y); // show
    }
    else
    {
        buzzR->MoveTo(buzzR->row, buzzR->col -= GRANULARITY_IN_Y); // show

    }

}

```

// site source of algorithm // take from https://github.com/jeffThompson/CollisionDetection //
BOOL rectHit(SceneObject r1, SceneObject r2) { TRACE("rectHit Invoked\n");

```
// are the sides of one rectangle touching the other?

if (r1.x + r1.width >= r2.x &&    // r1 right edge past r2 left
    r1.x <= r2.x + r2.width &&    // r1 left edge past r2 right
    r1.y + r1.height >= r2.y &&    // r1 top edge past r2 bottom
    r1.y <= r2.y + r2.height) {    // r1 bottom edge past r2 top
    return TRUE;
}
return FALSE;

```

}
> 0 votes

---
Tags: collision-detection, tiles, rust
---


title: Unity XR Spectator Camera

text:
# Question
Title: Unity XR Spectator Camera
I would like to have a VR camera (for the player) but also have another camera (spectator).

I am using Unity 2019.4.8f1 on the Universal Render Pipeline

I have only been able to find outdated articles:

https://blogs.unity3d.com/2017/12/12/spectating-vr/

https://unity3d.college/2017/05/08/unity3d-spectator-mode-vr/

https://forum.unity.com/threads/using-a-second-cam-while-still-rendering-the-vr-camera-for-the-vr-headset.659434/

Thanks!

# Answer
It seems the "Target Eye" property now hides from the Inspector unless you change it via a script at runtime.

```
camera.stereoTargetEye = StereoTargetEyeMask.None;

```

Which causes to correctly take over the desktop display without rendering in the HMD.
> 2 votes

# Answer
I get a 2nd camera output in unity by using KlakSpout (requires URP and Unity 2020+).

It re-routes a camera to VPT8 \- which displays full screen on my 2nd monitor - where I can record it with OBS.

This way I have the VR headset for my immersive experience, and I can record a motion-smoothed version of my POV or a 3rd person - or static - can put the 2nd camera anywhere.
> 0 votes

---
Tags: unity, 3d, rendering, virtual-reality, oculus
---


title: Could not find SyncVar hook

text:
# Question
Title: Could not find SyncVar hook
I've been following a guide on building a 2D MMORPG, and I ran into a problem when creating a health bar for my players. I get this error message:

> Could not find hook for 'CurrentHealth', hook name 'OnChangeHealth'. Method signature should be void OnChangeHealth(System.Int32 oldValue, System.Int32 newValue) (at System.Int32 Player::CurrentHealth)

Here is my code; please could someone explain to me why it is giving me this error?

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using Mirror;

public class Player : NetworkBehaviour
{
    // We have an invetory system
    // We have action abilities, interact wit the world
    // Our stats and skill levels are here

    // Character speed variable
    public float speed;

    // Character Health variable | Sync Var syncs all health across the server
    public const int MaxHealth = 100;

    //Detects when a health change happens and calls the appropriate function
    [SyncVar(hook = "OnChangeHealth")]
    public int CurrentHealth = MaxHealth;
    public RectTransform healthBar;

    //Decrease the "health" of the GameObject
    public void TakeDamage(int amount)
    {
        if (!isServer)
            return;

        //Decrease the "health" of the GameObject
        CurrentHealth -= amount;
        //Make sure the health doesn't go below 0
        if (CurrentHealth <= 0)
        {
            CurrentHealth = 0;
        }
    }

    void Update()
    {
    // If the player is a (client)
        if (isLocalPlayer)
        {

    // Controls player movements
        transform.Translate(Vector3.right * Input.GetAxis("Horizontal") * speed * Time.deltaTime);
        transform.Translate(Vector3.up * Input.GetAxis("Vertical") * speed * Time.deltaTime);

            if (Input.GetKeyDown(KeyCode.Space))
            {

                CmdTakeHealth();
            }
        }
    }

    // Updates healthBar
    void OnChangeHealth(int health)
    {
        healthBar.sizeDelta = new Vector2(health, healthBar.sizeDelta.y);
    }

    //This is a Network command, so the damage is done to the relevant GameObject
    [Command]
    void CmdTakeHealth()
    {
        //Apply damage to the GameObject
        TakeDamage(2);
    }

    public override void OnStartLocalPlayer()
    {
   // When a new player joins, run this code for the new client
        GetComponent<Renderer>().material.color = Color.blue;
    }

}
  ```
</code></pre>

# Answer
This is one of those cases where the error message tells you exactly what you need to change. It's looking for a method with this signature:

```
void OnChangeHealth(System.Int32 oldValue, System.Int32 newValue)

```

Note that it has two parameters: an old value, and a new value.

Compare this to the method signature that you wrote:

```
void OnChangeHealth(int health)

```

Only one parameter: the new value. You're missing the old value parameter.

These signatures do not match, so the function you wrote cannot be used directly as a hook for the SyncVar's change callback. You can fix this by adding an overload that matches the signature that the error asks for:

```
// Updates healthBar
void OnChangeHealth(int health)
{
    healthBar.sizeDelta = new Vector2(health, healthBar.sizeDelta.y);
}

void OnChangeHealth(int oldHealth, int newHealth)
{
    OnChangeHealth(newHealth);
}

```

Here I left your existing version as-is, in case you need a 1-parameter version for some other reason, and made the new 2-parameter overload just call it, discarding the unused parameter. That helps avoid code duplication, so the action happens in just one place, even if you have more than one way of initiating it.

If you don't need the 1-parameter version for anything, then you can just replace it with the 2-parameter version instead.

Moral of the story, as usual: read your error messages and take time to understand them in detail. The good ones have been carefully crafted to tell you exactly what's wrong and how to fix it.
> 1 votes

---
Tags: unity, c#, multiplayer, synchronization
---


# Question
Title: How can I create this springy oscillating motion chasing / orbiting the mouse?
I'm trying to recreate this motion,

I think most of the motion is based on this formula

\begin{eqnarray} x(t) &=& A e^{-\gamma t/2} \cos(\omega t - \phi) \\ y(t) &=& B e^{-\gamma t/2} \cos(\omega t - \psi)\\ \end{eqnarray}

where \\$A\\$ and \\$B\\$ are the amplitude of the oscillation, \\$\gamma\\$ is the friction, \\$\omega\\$ is the frequency, \\$t\\$ is the time, and \\$\phi\\$ and \\$\psi\\$ are the phase shift.

I've nearly reproduced successfully the motion except I don't know how to calculate phi and psi according to the mouse movement and t to reproduce this "rope" effect.

When phi and psi are set to 0, the ball oscillates in one direction on a straight line, but as you can see in the video when the mouse is moved the phase shift angle is shifted according to some factor I don't know about and the ball starts rotating around the clicked point (the equilibrium) until it finally stops.

So my question is how can I calculate phi and psi to recreate this motion?

**EDIT**

After looking @DMGregory's answer I've tried applying what he told me and after few refactoring I managed to do this

# Answer
> 1 votes
This looks like basic spring physics.

Each frame, you compute an acceleration vector, by taking the offset from your current position to your target position (the other end of the spring), and scaling it by the spring stiffness factor `k`. The higher the `k` value, the more sharply the spring pulls.

```
acceleration_x = k * (target_x - position_x)
acceleration_y = k * (target_y - position_y)

```

On frames where the mouse isn't clicking to attract the object, you can set `acceleration_x/y` to zero to "release" the object and let it drift using its own momentum without outside interference.

Then you can integrate that acceleration over time to get a changing position, using your favourite numerical integration method. Here's a basic Euler method:

```
velocity_x = velocity_x * inertia + acceleration_x * deltaTime
velocity_y = velocity_y * inertia + acceleration_y * deltaTime

position_x = position_x + velocity_x * deltaTime
position_y = position_y + velocity_y * deltaTime

```

Here `velocity_x/y` form an extra pair of state variables that you maintain about your object from one frame to the next. That gives it some memory of how it was moving, allowing it to retain some momentum in the old direction when the target is moved, creating that effect you described where the object can overshoot the target sideways and orbit around it, rather than only ever approaching/receding along the line joining the two points.

`deltaTime` is the duration of one step of your physics simulation, in the appropriate units. (eg. if `position` is measured in pixels and `velocity` in pixels per second, then `deltaTime` would be measured in seconds). Small timesteps of consistent duration help you get smooth, plausible physics.

`inertia` is a constant you choose between 0 and 1, that controls how much of the speed is retained from one simulation step to the next. At high values, the object will overshoot the target and travel almost as far as its original displacement before turning around, making big, long-lasting oscillations. Lower values act like a dampened spring, or an object with friction, where the excess velocity bleeds off quickly and the object can settle down near the target without huge overshoots / long oscillations.

To keep the expression simple, I didn't adjust `inertia` for the duration of your time step - basically assuming that you'll fix your time step first, then tune inertia to your liking. But if you want to dynamically adjust the inertia value to get similar behaviour under different time step values, you can use `inertia = power(speedRemainingAfter1Second, deltaTime)` where `speedRemainingAfter1Second` is a ratio between 0 and 1.

---
Tags: physics, mathematics, spring
---


title: How to integrate Firebase to Libgdx?

text:
# Question
Title: How to integrate Firebase to Libgdx?
I have an android game built with libgdx and what I'd like to do is to add some kind of authentication so I can connect the game with user data to firebase database.

I have some experience with firebase using it in native android apps, but I have no idea on how to connect "native code" with libgdx.

Researching I found these third party libs https://github.com/mk-5/gdx-fireapp/tree/master/gdx-fireapp-core and https://github.com/TomGrill/gdx-firebase

But as it does not provide any example it didn't help me much.

So what's the best way to "mix" native android code and libgdx? I want to be able to achieve things like storing data on db, implementing in-app-purchases, authenticating users. If I'm looking the wrong way please let me know too.

# Answer
> 2 votes
In a `libGDX` application, you have 2 'main' types of codebase. The first is the `libGDX` game itself - this contains all your screens, assets, engine code ... the stuff that makes the game work.

The other is the target specific code needed to start the application. This is the desktop, Android or iOS code. I'm going to talk about Android only here (as desktop is ... just easy, and I know nothing about iOS), but these principles apply to all of them.

Android (and I suspect iOS) are a little harder than desktop as there are environment specific things going on. You need to call out to the outer system for things like Toast messages and you need the Android `Context` to connect to databases (well, at least SQLite, I suspect Firebase is similar).

So, when you create your game you need to hand it a link to the outer system. If you are targeting only one outer system type, this becomes easier (eg: does Firebase even exist on iOS?)

The start for this is the `Launcher` class of the project - this is where the program starts and then fires up the actual game. Before you start the game, you can do anything you like that is native to the target. In my code, I start up a database handler class.

```
@Override
protected void onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    actionResolver = new AndroidActionResolver(this);
    AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
    initialize(new Game(actionResolver), config);
}

```

Here is my `AndroidActionResolver`:

```
public class AndroidActionResolver implements ActionResolver {

    Handler uiThread;
    Context appContext;
    private AndroidDataSource dataSource;

    public AndroidActionResolver(Context appContext) {
        uiThread = new Handler();
        this.appContext = appContext;
        dataSource = new AndroidDataSource(appContext);
    }

    @Override
    public AndroidDataSource getDB() {
        return dataSource;
    }

    public void makeToast(final String message) {
        uiThread.post(new Runnable() {
            @Override
            public void run() {
                  Toast.makeText(appContext.getApplicationContext(), message,
                  Toast.LENGTH_SHORT).show();
            }
        });
    }
}

```

You can see in here that I have exposed a database connection and provided a method for the game to call back to the native code to raise a Toast.

Then, when you launch your game class, you pass in the native handler instance that you just created;

```
initialize(new Game(actionResolver), config);

```

Over on the game side, create an interface for the resolver class, including all methods you want to expose. Make sure that your resolver on the native side `implements` this interface.

```
public interface ActionResolver {
    public DataSource getDB();
    public void makeToast(String message);
}

```

Then, in your main game class on the `libGDX` side, store this class as a local member and declare it to be of the interface type:

```
private ActionResolver actionResolver;

public Game(ActionResolver actionResolver) {
    this.actionResolver = actionResolver;
}

```

Now that you have this class in your game, you can pass it around as needed and it provides the bridge between your native code and the game code. You can put in as many methods as you need to pass information between the two.

Apologies if some of the Android code presented here is a little dated - I've copied and pasted from an old project where I've had this stuff working.

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


# Question
Title: Drawing multiple simulation ticks in a single render frame
I have a 2D fixed-timestep simulation (a bunch of moving sprites) that ticks several times per render frame.

I would like to render the state of each tick, so that all the ticks between render frames A and A+1 contribute to the image at A+1: a discrete approximation of motion blur. I assumed this would be trivial, but so far I'm pretty stumped!

My current approach is: given N sim ticks, draw the sprites at each tick with alpha = 1/N. However, so far this feels like it's not the correct approach, and I was hoping someone here could point me in the right direction.

I've tried alpha compositing (ie equivalent to (GL\_SRC\_ALPHA, GL\_ONE\_MINUS\_SRC\_ALPHA)), but this doesn't work: the sprites all become somewhat transparent, because by definition if you alpha-composite N images which have alpha \< 1, you'll always get some background colour blended into the result.

Then I tried additive blending (ie (GL\_ONE, GL\_ONE)): this produces the correct result in isolation (ie a stationary sprite is drawn fully opaque, since it gets drawn N times with 1/N alpha; a moving sprite is opaque where all its ticks overlap, and transparent at the edges where only some ticks overlap), however if there's anything behind the sprites (which there will be – ie sprites moving through each other, a parallax background, etc.) then the additive blend ruins this by making everything over-bright.

Am I missing something basic?? This seems like it should be pretty straightforward, but so far all I can think of is that I would need to composite things in multiple steps: for each sprite, use additive blending to render it into a buffer, then alpha-composite that buffer with the rest of the scene.

Is that really the best I can do? It seems ugly and complicated; why shouldn't I be able to draw the background image, along with everything else in the scene, N times with 1/N alpha?

Everything I've found via google is for pixel shaders which approximate motion blur per-object via multisampling. In my case, I already have the scene multi-sampled, I just don't understand how to correctly blend all the samples together!

Anyway, any tips or pointers are greatly appreciated! Thanks. : )

# Answer
> 1 votes
You can draw your first tick at 100% alpha.

Your second tick can be drawn at 50% alpha, so you get 50% of tick 1 showing through.

Your third tick can be drawn at 33% alpha, so you get 67% of ticks 1+2 (50% each, so about 33% net).

Your fourth tick can be drawn at 25% alpha, so you get 75% of ticks 1-3 (at 33% each, so 25% net).

And so on. The \\$i^{\text{th}}\\$ layer can be drawn with alpha \\$\frac 1 i\\$ to get approximately equal weighting of this and all underlying layers.

Note however that if you want an object to be opaque relative to things it overlaps in a single tick, then you'll want to pre-compose the entire rendered frame for the tick into its own buffer using the sprites' normal alpha values. Then you can blend that pre-composed frame with the accumulated frames from previous ticks in a separate buffer.

---
Tags: 2d, graphics-programming, alpha-blending, multisampling
---


# Question
Title: Space torque semi-independent of center of mass
I am making a 2d user build spaceship game that allows the user to place thrusters where they would like. I've read a bunch of posts in a lot of places including stack exchange on how determine the lateral force and torque force.

My problem so far with the information that I have is that it seems to me that they all are assuming that the axis of rotation for torque will always be at the center of mass. Obviously a well designed thruster placement will have the rigid body rotate about its center of mass but some damage can ruin that and to be frank I want the user to be able to make not well designed ships just because it's fun.

My main question really is what terminology am I missing that allows me to find out the relationship between the center of thrust and the center of mass so that I can find the true rotation axis for torque.

Here is an example of a craft that won't rotate about its center of mass:

# Answer
> 1 votes
(consolidated my comments and moved them into this answer)

#### Physics Answer

I'm fairly certain rigidbodies do always rotate around the center of mass. The thing is that if the thrusters aren't directly negating eachothers' forces (say if they're irregularly placed), then there will simply be a rotation about the center of mass AND a translation. See this post for a more thorough and rigorous explanation.

#### Real (game design) Answer

I actually had this exact same problem for a game I was making where players could design their own (2D) ships.

If you want to let players have reasonable (in terms of controllability) centers of rotation no matter their design, then I wouldn't worry about modelling physical reality in the first place -- in fact, I would avoid it. I've found personally that asking the question "is this physically accurate" can often become an excuse (for the programmatically inclined) to avoid the work game design.

Instead I would try to think of the set of ship designs I want to allow in my game, and then design faux physics systems to support these designs. Specifically I would think try to find a good balance between allowing players creating visually eccentric and fun designs, while still having their placement decisions have meaningful(/interesting) effects on the ships' handling.

---
Tags: physics, mathematics
---


# Question
Title: How can I create a Minecraft: Bedrock Edition add-on?
I would like to create a custom add-on for Minecraft: Bedrock Edition, but I'm not understanding everything involved with getting started. After reading a few tutorials, I have *some* understanding of what to do, but there is nothing that wholly gives an up-to-date complete process of how to do so.

How can I create a custom add-on for Minecraft: Bedrock Edition?

---

Note that I've decided to post this question/answer because of the issues described above. I thought it would help others avoid doing all the research I had to go through.

##### Related Posts

| Title |
| --- |
| How To: Create Custom Blocks |
| How To: Rename Items |

# Answer
### Objectives

After reading this answer through and through, you should be able to effectively answer the following questions:

* What is an add-on?
    + What is a resource pack?
    + What is a behavior pack?
    + What is the difference between the two?
* What does `JSON` stand for?
    + What is `JSON` used for?
* What tools are required to create an add-on?
* What official resources are available for creating add-ons?
* What official documentation is available for reference when creating add-ons?

### Overview

Creating add-ons for Minecraft: Bedrock Edition (henceforth referred to as simply BE) is a relatively straightforward process that, more often than not, requires little to no knowledge of programming. Getting started, you'll need to have an understanding of some basic terminology:

| Term | General Definition |
| --- | --- |
| Resource Pack | *A partial add-on for Minecraft that enables creators to alter the **appearance** of the Minecraft worlds that implement them.* |
| Behavior pack | *A partial add-on for Minecraft (specifc to BE) that enables creators to alter the **behavior** of the items and entities used in the Minecraft worlds that implement them.* |
| JSON | ***JavaScript Object Notation** is a lightweight format for storing and transporting data that is often used when data is sent from a server to a web page. It is "self-describing" and easy to understand.* |
| UUID | *A universally unique identifier (**UUID**) is a 128-bit label used for information in computer systems. The term globally unique identifier (**GUID**) is also used, often in software created by Microsoft. When generated according to the standard methods, UUIDs are, for practical purposes, unique.* |
| .mcpack | *The file extension used for individual resource or behavior **packs**. This is used in a one or the other situation.* |
| .mcaddon | *The file extension used for **add-ons**. This is used when there is a resource ***and*** behavior pack included in a single package.* |

### Required Tools

The only tools ***required*** for creating an add-on for BE are text editors. Some of the most popular OS agnostic text editors are:

Alternatively, here is an article reviewing a list of 10 text editors that are OS agnostic.

### Getting Started

Once you've chosen and installed the text editor of your choice, the first thing you'll want to do is download the vanilla packs. The vanilla packs are going to be a point of reference for anything and everything (excluding scripts) that you may want to accomplish with your custom add-on. It is also recommended that you watch the official introduction to add-ons video.

Once you've downloaded the vanilla packs, feel free to explore their contents and get familiar with the structure:

***Note**: I'm using Visual Studio Code in the screenshot above, but you can browse the folder structure in the file explorer or text editor of your choosing.*

### Hello Minecraft

Now that you've familiarized yourself with the content structure of the vanilla packs, you're ready to start getting your feet wet by creating your very first add-on. The basic requirements of an add-on are:

* A resource ***or*** behavior pack.
    + A manifest file describing that pack.

You're probably wondering, "is that it?!", well, yeah, it is. Your add-on doesn't actually require a behavior pack ***and*** a resource pack. In-fact, only one ***or*** the other is required, though both can be included. For the purposes of this answer, the resulting add-on will include both.

To get started, create a folder with the name of your add-on (I called mine ***Hello Minecraft***) and then two folders within that one called ***Behavior Pack*** and ***Resource Pack*** respectively (henceforth referred to jointly as the pack folders). Within the newly created pack folders, create a file named `manifest` with a file extension of `.json`. The resulting stucture should look like this:

The manifest file is different for behavior packs and resource packs. However, you can grab a sample of both from the vanilla packs to populate the files you just created. Next, you'll need to generate ***four*** UUIDs two for each pack. Both packs have a header UUID and a module UUID:

```
{
    "format_version": 2,
    "header": {
        "description": "An example resource pack for demonstration purposes.",
        "name": "Hello Minecraft! - Resources (0.0.1)",
        "uuid": "efcd2de9-44b2-4201-ba94-6b82ef59de0f",
        "version": [0, 0, 1],
        "min_engine_version": [ 1, 17, 0 ]
    },
    "modules": [
        {
            "description": "An example resource pack for demonstration purposes.",
            "type": "resources",
            "uuid": "fca45bed-c308-42ad-9b54-690083e7dc3e",
            "version": [0, 0, 1]
        }
    ]
}

```

The manifest file has an additional field available labeled `dependencies` which you'll see in the vanilla behavior pack manifest:

```
"dependencies": [
    {
        "uuid": "efcd2de9-44b2-4201-ba94-6b82ef59de0f",
        "version": [0, 0, 1]
    }
]

```

The UUID in this section is set to the header UUID of the respective dependency. So in the case of this add-on, the behavior pack will be dependent on the resource pack. As a result, the dependency UUID is the header UUID of the resource pack.

### Bundling and Importing

Once you've set your UUIDs, you can then bundle your add-on and import it into Minecraft! To do this, you can store the folders relevant to your add-on (in this case the pack folders) in a single archive file (commonly referred to as `.zip` files, but this can vary based on OS). After you've placed your add-on contents into an archive file, you can change the file's extension to `.mcaddon` which will allow you to open the add-on with Minecraft. Importing is as simple as opening the file with Minecraft, from there the process is automated.

Once imported, you should see your packs in Minecraft:

### Further Reading

Now that you've created your first custom add-on for Minecraft: Bedrock Edition, you may be curious as to what documentation is available to you. Fortunately, the vanilla packs include some basic, but official documentation within the behavior pack:

In addition to this, there are online resources (such as Bedrock.dev) that add styling to the aforementioned documentation, making it easier to follow, along with official resources from Microsoft. Also, the fandom wiki is a great resource to utilize when trying to find data values and really detailed information about Minecraft in general.

---

***Note**: The add-on created for this answer is available on GitHub for those interested in reviewing the complete package.*
> 4 votes

---
Tags: minecraft-modding
---


# Question
Title: How to import images as sprites instead of default textures in Unity?
Basically, unity imports new images (png, jpg) as default textures but I need to import them as sprites instead.

As there are lots of sprite sheet new assets in my game, it's time consuming to change the import setting for many assets.

I know I can make an `AssetImporter` and use it but it doesn't work and I don't know how to use it for sprites.

# Answer
Under Edit \> Project Settings, select the Editor section and change Default Behaviour Mode to 2D:

This does two things:

* Any newly-added images will be imported as sprites by default
* When you create a new scene, it will be created with the 2D preset (orthographic camera, no light, scene view 2D toggle on) instead of the 3D preset (perspective camera, directional light, scene view 2D toggle off)

This second effect isn't one you want, but it doesn't do anything irrevocable - you can turn off the 2D toggle, add a light, and change the camera mode after the fact. Or you can switch to 3D mode when you're creating a bunch of scenes, and switch back to 2D mode when importing a bunch of images. Or you can take an existing template scene and save it under a new name, then work from that - no defaults to fight against.

You'll likely have more images to import than scenes to create, so this should still give you a net savings in time and labour, even if you have a little extra fussing to do when making scenes.
> 3 votes

---
Tags: unity
---


# Question
Title: Why unity has shadowmask mode for light baking?
To bake a extra shadowmask map, what issue will be solved?

Since subtractive mode also bakes shadow infomation into lightmap, why these two functions split?

The extra shadowmask map is only for blending realtime shadow and baked shadow depending on distance?

# Answer
The unity manual actually answers your question:

> Shadowmask Lighting Mode provides the highest fidelity shadows among all the Lighting Modes, but has the highest performance cost and memory requirements. It is suitable for rendering realistic scenes where distant GameObjects are visible, such as open worlds, on high-end or mid-range hardware.

The shadowmask lighting mode allows Unity to combine baked and real-time shadows at runtime, and to render shadows in the far distance. It does this by using an additional lightmap texture known as a shadow mask, and by storing additional information in Light Probes.
> 0 votes

---
Tags: unity
---


# Question
Title: Relocate texture regions with pixel shader
I'm new to DirectX and pixel shader development. I want to know how to relocate region of input image in post processing.

What I want to achieve is to divide my image into 4 pieces and then relocate them clockwise or counterclockwise.

# Answer
> 0 votes
Let's assume you have an input texture coordinate variable called `uv`, running from (0,0) in the bottom-left to (1,1) in the top right.

If you wrote just

```
return tex2D(InputTexture, uv);

```

...then we'd pass through the source texture to the output texture unchanged. So to get the re-arrangement you want, we'll need to play with the `uv` coordinates a bit.

First, we can do some rounding to establish which quadrant we're in:

```
float2 floored = floor(uv * 2);
float2 quadRelative = uv - (floored * 0.5f);

```

`floored` will take on the values (0,1) (1,1) (0,0) and (1,0) in the input quadrants you labelled 1-4, respectively, and `quadRelative` will give our pixel's texture coordinate offset from the bottom-left of its containing quadrant.

Now we can remap our quadrants as desired. If we want to shuffle counter-clockwise, then we need to sample from the next quadrant clockwise:

```
(0,1)->(1,1)
(1,1)->(1,0)
(1,0)->(0,0)
(0,0)->(0,1)

```

Here's a formula that achieves that:

```
float2 remapped = float2(floored.y, 1 - floored.x);

```

(The formula to rotate in the opposite direction is left as an exercise for the reader )

And finally we can reconstruct our new uv by adding our relative offset to our new quadrant:

```
float2 samplePoint = 0.5f * remapped + quadRelative;

```

You can pass this modified texture coordinate into your sampling function to read from this new quadrant. (I showed the old-style `tex2D()` version above, but this works just as well with other sampling functions)

You'll want to ensure that mipmapping is disabled for your source texture sampler — otherwise the discontinuities in sampling coordinates at the quadrant boundaries will make the GPU think it needs to read from a tiny mip level, resulting in unnecessary blurry pixels. If you can't disable mipmapping, then you can use the gradients from the original `uv` variable with `tex2Dgrad()` or similar.

---
Tags: shaders, directx, fragment-shader, post-processing
---


# Question
Title: 'WWW' is obsolete: 'Use UnityWebRequest'
I am creating a 2D MMORPG, I created a forum to store player information( username, password etc.). Could someone please help me understand the new Unity Web System so i can change my code for optimal functionality.

```
IEnumerator ProcessRequest(string username, string password, string url, string age = null, string email = null)
{

    WWWForm form = new WWWForm();

    form.AddField("username", username);
    form.AddField("password", password);
    form.AddField("age", age);
    form.AddField("email", email);

    WWW request = new WWW(url, form);

    yield return request;

    if (string.IsNullOrEmpty(request.error))
    {
        Debug.Log(request.text);
    }

```

This results in:

> 'WWW' is obsolete: 'Use UnityWebRequest, a fully featured replacement which is more efficient and has additional features'

I read over the official documentation `UnityWebRequest` , however in my contents I honestly did not really understand how I can implement it...

# Answer
There are three primary methods for sending data to a server, formatted as an HTML Form using unity web request.

1st : Using `WWWForm` (which is a legacy method, that `UnityWebRequest` still supports)

```
IEnumerator ProcessRequest(string username, string password, string url, string age = null, string email = null)
{
    WWWForm form = new WWWForm();

    form.AddField("username", username);
    form.AddField("password", password);
    form.AddField("age", age);
    form.AddField("email", email);

    UnityWebRequest www = UnityWebRequest.Post(url, form);
    yield return www.SendWebRequest();

    if (www.result != UnityWebRequest.Result.Success)
    {
        Debug.Log(www.error);
    }
    else
    {
        Debug.Log("Form upload complete!");
    }
}

```

2nd: Using IMultipartFormSection

```
List<IMultipartFormSection> form = new List<IMultipartFormSection>();

form.Add(new MultipartFormDataSection("username", username));
form.Add(new MultipartFormDataSection("password", password));
form.Add(new MultipartFormDataSection("age", age != null ? age : "0"));
form.Add(new MultipartFormDataSection("email", email));

UnityWebRequest www = UnityWebRequest.Post(url, form);
yield return www.SendWebRequest();

if (www.result != UnityWebRequest.Result.Success)
{
    Debug.Log(www.error);
}
else
{
    Debug.Log("Form upload complete!");
}

```

3rd: JSON Serialization Use the JsonUtility class to convert Unity objects to and from the JSON format. - this would require some additional code

You would begin by creating a new class that would be used to serialize your form:

```
[Serializable]
public class myForm
{
    public string username;
    public string password;
    public string age;
    public string email;
}

```

The class is using the \[Serializable\] attribute, in order to work with the JSON serializer. Then create an instance of your class, for example:

```
myForm form = new myForm();
form.username = "UsrNamesss";
form.password = "11111111";
form.age = "23";
form.email = "foo@foo.com";

```

And to wrap it up - Serialize it using `JsonUtility` and Post it using `UnityWebRequest`

```
IEnumerator ProcessRequest(string url, myForm form)

```

Convert it (which can be done on the other direction like this: `newForm = JsonUtility.FromJson<myForm>(json);` )

```
string json = JsonUtility.ToJson(myForm);

```

and just post it using `UnityWebRequest`:

```
UnityWebRequest www = UnityWebRequest.Post(url, form);
yield return www.SendWebRequest();

if (www.result != UnityWebRequest.Result.Success)
{
    Debug.Log(www.error);
}
else
{
    Debug.Log("Form upload complete!");
}

```

I find the 3rd solution better in most cases as it allows me to better manage data and models within my apps.
> 2 votes

# Answer
Using the 2nd Method

```
List<IMultipartFormSection> form = new List<MultipartFormDataSection>();

```

Unity Error :

> Assets\NetworkManager.cs(96,48): error CS0029: Cannot implicitly convert type 'System.Collections.Generic.List\<UnityEngine.Networking.MultipartFormDataSection\>' to 'System.Collections.Generic.List\<UnityEngine.Networking.IMultipartFormSection\>'

While a MultipartFormDataSection can be used as a IMultipartFormSection (which it implements), the same does not apply to collections. So List is not compatible with new List, for C# those are completely separate types even if they are seemingly compatible.

You can just turn the list into List, adding the individual data sections will still work.

```
 form.Add(new MultipartFormDataSection("age", age != null ? age : 0));

```

Unity Error :

> Type of conditional expression cannot be determined because there is no implicit conversion between 'string' and 'int'

age is a string but the 0 in your conditional expression is an int. Both sides of a conditional expression need to return the same type, so you have to use "0" instead.
> 0 votes

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


# Question
Title: How to fix : Cannot create a multipart form data section without body data
I successfully coded my game to register a player with their 'username, password, email' After Registering id like a player to fill in their username & password and have it checked by the db. Upon 'Login' i ran into this :

> "ArgumentException: Cannot create a multipart form data section without body data"

```
public class NetworkManager : MonoBehaviour
{

    public void SignupComplete()
    {
        // Make sure nothing is blank

        if (usernameSignup.text == "" || passwordSignup.text == "" || passwordVerification.text == "" || age.text == "" || email.text == "")
        {
            return;
        }

        // Check if passwords match

        if (passwordSignup.text != passwordVerification.text)
        {
            return;
        }

        // Check Age

        if (int.Parse(age.text)< 13)
        {
            return;
        }

        // IF the client makes it this far, send their data to the website!

        Debug.Log("Processing Request");

        StartCoroutine(ProcessRequest(usernameSignup.text, passwordSignup.text, DATA_URL_SIGNUP, age.text, email.text));

    }

    // ERROR WHEN LOGIN  "ArgumentException: Cannot create a multipart form data section without body data"
    public void LoginComplete()
    {
        if(usernameLogin.text == "" || passwordLogin.text == "" )
        {
            return;
            Debug.Log("Please fill in all fields!");
        }

        StartCoroutine(ProcessRequest(usernameLogin.text, passwordLogin.text, DATA_URL_LOGIN));
        Debug.Log("Processing Request");
    }

    IEnumerator ProcessRequest(string username, string password, string url, string age = null, string email = null)
    {
        List<IMultipartFormSection> form = new List<IMultipartFormSection>();

            form.Add(new MultipartFormDataSection("username", username));
            form.Add(new MultipartFormDataSection("password", password));
            form.Add(new MultipartFormDataSection("age", age != null ? age : "0"));  //age != null ? age : "0"
            form.Add(new MultipartFormDataSection("email", email == null ? "" : email));

            UnityWebRequest www = UnityWebRequest.Post(url, form);
            yield return www.SendWebRequest();

            if (www.result != UnityWebRequest.Result.Success)
            {
                Debug.Log(www.error);
            }
            else
            {
                Debug.Log("Signup completed!");
            }
    }

```

# Answer
> 1 votes
Instead of `List<IMultipartFormSection>`, use `WWWForm`:

```
WWWForm form = new WWWForm();
form.Add("username", username));
form.Add("password", password));
form.Add("age", age != null ? age : "0"));
form.Add("email", email == null ? "" : email));
UnityWebRequest www = UnityWebRequest.Post(url, form);
//...

```

See also: POST request documentation

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


# Question
Title: Adding a shader graph material as a second material
I'm attempting to make an outline shader that I can attach to selected objects by following this guide. After making a new material and assigning the new Shader Graph as the shader, I'm not sure how to add it to my object while keeping it's normal material. Dragging it on just replaces it and nothing in the Add Component menu is standing out. How are you supposed to include regular materials and shaders on the same object?

# Answer
> 2 votes
There is nothing different about shader graph materials here. A material is a material.

Inside your `Renderer` component, you'll find there is an array of material references. Just like any array in Unity, you can increase its size to add more slots, then assign your second material to one of the extra slots.

I've shown an example with the `MeshRenderer` component, but this is available on other `Renderer` subtypes too. You can also assign an array of materials to the `renderer.materials` or `renderer.shaderMaterials` properties in script.

---
Tags: unity, unity-shader-graph
---


# Question
Title: How can I enable intellisense for Stride 3D in Visual Studio?
I have installed Visual Studio and Stride 3D, but, when I'm using Visual Studio it doesn't help me with code recommendations. For example, if I write "Ent" it doesn't show me `Entity`, or, if I have more assets code it doesn't help me find that component.

How do I enable intellisense for Stride 3D in Visual Studio?

# Answer
> 1 votes
The only thing I see available to support this is the official Visual Studio extension for Stride 3D:

> The Stride Visual Studio extension adds syntax highlighting, live code validation, error checking, and navigation. It also lets you you edit shaders directly from Visual Studio.
>
> You don't need to install the extension to use Stride, but we recommend it, especially for programmers.

When you install Stride 3D, you're given the option to install the extension:

If you elected not to install the extension on initial setup, you can install it from the launcher:

---

Unfortunately, for VS Code users, there doesn't seem to be an extension available.

---
Tags: visual-studio, stride
---