# Question
Title: uNet - Client cant see server spawned objects
I'm facing a problem where when I connect with the host, all the towers spawn. After I connect with a client only to find out there are no towers visible and I can walk through them when looking at the host screen.

My tower spawn script ( GameManager.cs ) :

```
public int numberOfDestroyedTopTowers = 0;
public int numberOfDestroyedMidTowers = 0;
public int numberOfDestroyedBotTowers = 0;

public GameObject[] topTowerSpawns;
public GameObject[] midTowerSpawns;
public GameObject[] botTowerSpawns;

public GameObject towerPrefab;

void Start() {
    CmdSpawnTowers();
}

[Command]
void CmdSpawnTowers() {

    for (int i = 0; i < midTowerSpawns.Length; i++) {
        GameObject currTower = (GameObject)Instantiate(towerPrefab);
        currTower.transform.position = midTowerSpawns[i].transform.position;
        currTower.name = "Tower [MID] " + i;
        NetworkServer.Spawn(currTower);
    }

    for (int i = 0; i < topTowerSpawns.Length; i++) {
        GameObject currTower = (GameObject)Instantiate(towerPrefab);
        currTower.transform.position = topTowerSpawns[i].transform.position;
        currTower.name = "Tower [TOP] " + i;
        NetworkServer.Spawn(currTower);
    }

    for (int i = 0; i < botTowerSpawns.Length; i++) {
        GameObject currTower = (GameObject)Instantiate(towerPrefab);
        currTower.transform.position = botTowerSpawns[i].transform.position;
        currTower.name = "Tower [BOT] " + i;
        NetworkServer.Spawn(currTower);
    }

}

```

The script is derived from NetworkBehaviour and it does have a Network Identity on it (Server Only checked). Also on my towerPrefab I also have a network identity with server only checked. I have added my tower prefab under the network manager "Registered Spawnable Prefabs".

# Answer
try with a RPC call

`[Command]` are message from a client to the server a `[ClientRPC]` are messages that are send to all the clients from server

so in order to show all your clients the towers use a rpc call

```
void Start() {
RpcSpawnTowers();
}

[ClientRpc]
void RpcSpawnTowers() {

    for (int i = 0; i < midTowerSpawns.Length; i++) {
        GameObject currTower = (GameObject)Instantiate(towerPrefab);
        currTower.transform.position = midTowerSpawns[i].transform.position;
        currTower.name = "Tower [MID] " + i;
        NetworkServer.Spawn(currTower);
    }

    for (int i = 0; i < topTowerSpawns.Length; i++) {
        GameObject currTower = (GameObject)Instantiate(towerPrefab);
        currTower.transform.position = topTowerSpawns[i].transform.position;
        currTower.name = "Tower [TOP] " + i;
        NetworkServer.Spawn(currTower);
    }

    for (int i = 0; i < botTowerSpawns.Length; i++) {
        GameObject currTower = (GameObject)Instantiate(towerPrefab);
        currTower.transform.position = botTowerSpawns[i].transform.position;
        currTower.name = "Tower [BOT] " + i;
        NetworkServer.Spawn(currTower);
    }

}

```
> 1 votes

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


# Question
Title: How to jump exactly X meters in Box2D World?
I want my character to always jump a constant height, let's say 3 meters. Also character has double jump ability so he can jump max 6 meters. For example, let's say I have pressed jump key while player is on the ground, and as soon he reaches 1 meter in height, I press jump key again and he performs double jump and reaches 4 meters.

I am really new to box2d and I have figured out that I can make my character jump using `body.applyForceToCenter(new Vector2(0, 700), true)` but I do not know how much force I need to apply in order to make my character jump exactly 3 meters and perform double jump to jump again exactly 3 meters.

I think what I really need here are just formulas...

# Answer
Formulas:

y = g * t^2 + Vi * t + Iy

V = 2 * g * t + Vi

In another form...

Vi = (y - g * t^2 + Iy) / t

Vi = V - 2 * g * t

To find the first jump initial velocity, you set y = 3, and V = 0, and solve for t which is 0.553, use that to solve for Vi which is 10.84988

The second jump is a little more involved.

Vc = V, and Iy = y, at the beginning of the double jump

You set Iy = the current y, y = 6, V = 0, then solve for the new Vi, subtract the current velocity Vc from the new Vi giving the velocity boost required to reach 6 meters.

Algebra hand waving:

(y - g * t^2 + Iy) / t = -2 * g * t

y - g * t^2 + Iy = -2 * g * t^2

y + Iy = -g * t^2

(Iy - y) / g = t^2

t = sqrt((Iy - y) / g)

Vi = -2 * g * sqrt((Iy - y) / g)

double jump boost in velocity is Vi - Vc
> 0 votes

---
Tags: libgdx, physics, box2d, jumping, jbox2d
---


# Question
Title: Game Maker: is 08 the same as 8 in arrays?
if I make an array `A_[01]`, can I refer to it later with `A_[1]`?

I am asking because I am not sure if this is the reason why I am getting some bugs.

# Answer
> 2 votes
I can't say confidently without testing myself, you should test yourself (see the bold below). However, reading the documentation on Data Types the following line is stated:

> real numbers are any value that is not a string, nor any of the other possible data types.

The documentation makes no mention of octal literals, which is where 0 might be a prefix, and it doesn't make any mention of binary literal values. This documentation page mentions the only hexadecimal format relates to the `$` character which is used for color values.

> Note that you can also create colours from their hexadecimal value using the "$" symbol beforehand

Finally, this page on the arrays and their indexing has no mention of any special array indexing meaning. The data types like map appear to use functions rather than syntax to access the keys so I don't expect this to be an implicit map.

This leads me to conclude that if the GML parser reads a prefixed `0` as a real number, `02` should be equivalent to `2`. **You can test this theory by printing the result of `02 == 2`**, or put `02` into a variable and print the value, if it prints out as `2` it might be parsed as a real number. *Note that I use 2 instead of 1 because if there is a binary literal somehow it won't translate.*

I'd suggest you avoid relying on side effects (I'd consider this a side effect of the first quoted line) and be explicit: use the integer literal without the prefix to be sure and future proof.

---
Tags: game-maker
---


# Question
Title: Make Buttons to Move Character Right and Left
Can someone help me add mobile input controls for my game? I've got this right now:

```
using UnityEngine;
using System.Collections;

public class PlayerControl : MonoBehaviour
{
    [HideInInspector]
    public bool facingRight = true;         // For determining which way the player is currently facing.
    [HideInInspector]
    public bool jump = false;               // Condition for whether the player should jump.

    public float moveForce = 365f;          // Amount of force added to move the player left and right.
    public float maxSpeed = 5f;             // The fastest the player can travel in the x axis.
    public AudioClip[] jumpClips;           // Array of clips for when the player jumps.
    public float jumpForce = 1000f;         // Amount of force added when the player jumps.
    public AudioClip[] taunts;              // Array of clips for when the player taunts.
    public float tauntProbability = 50f;    // Chance of a taunt happening.
    public float tauntDelay = 1f;           // Delay for when the taunt should happen.
    private float direction;
    private bool move;
    private float btnHorizontal;

    private int tauntIndex;                 // The index of the taunts array indicating the most recent taunt.
    private Transform groundCheck;          // A position marking where to check if the player is grounded.
    private bool grounded = false;          // Whether or not the player is grounded.
    private Animator anim;                  // Reference to the player's animator component.

    void Awake()
    {
        // Setting up references.
        groundCheck = transform.Find("groundCheck");
        anim = GetComponent<Animator>();
    }

    void Update()
    {
        // The player is grounded if a linecast to the groundcheck position hits anything on the ground layer.
        grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));
    }

    void FixedUpdate ()
    {
        // Cache the horizontal input.
        float h = Input.GetAxis("Horizontal");

        // The Speed animator parameter is set to the absolute value of the horizontal input.
        anim.SetFloat("Speed", Mathf.Abs(h));

        // If the player is changing direction (h has a different sign to velocity.x) or hasn't reached maxSpeed yet...
        if(h * GetComponent<Rigidbody2D>().velocity.x < maxSpeed)
            // ... add a force to the player.
            GetComponent<Rigidbody2D>().AddForce(Vector2.right * h * moveForce);

        // If the player's horizontal velocity is greater than the maxSpeed...
        if(Mathf.Abs(GetComponent<Rigidbody2D>().velocity.x) > maxSpeed)
            // ... set the player's velocity to the maxSpeed in the x axis.
            GetComponent<Rigidbody2D>().velocity = new Vector2(Mathf.Sign(GetComponent<Rigidbody2D>().velocity.x) * maxSpeed, GetComponent<Rigidbody2D>().velocity.y);

        // If the input is moving the player right and the player is facing left...
        if(h > 0 && !facingRight)
            // ... flip the player.
            Flip();
        // Otherwise if the input is moving the player left and the player is facing right...
        else if(h < 0 && facingRight)
            // ... flip the player.
            Flip();

        // If the player should jump...
        if(jump)
        {
            // Set the Jump animator trigger parameter.
            anim.SetTrigger("Jump");

            // Play a random jump audio clip.
            int i = Random.Range(0, jumpClips.Length);
            AudioSource.PlayClipAtPoint(jumpClips[i], transform.position);

            // Add a vertical force to the player.
            GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, jumpForce));

            // Make sure the player can't jump again until the jump conditions from Update are satisfied.
            jump = false;
        }
    }

    void Flip ()
    {
        // Switch the way the player is labelled as facing.
        facingRight = !facingRight;

        // Multiply the player's x local scale by -1.
        Vector3 theScale = transform.localScale;
        theScale.x *= -1;
        transform.localScale = theScale;
    }

    public IEnumerator Taunt()
    {
        // Check the random chance of taunting.
        float tauntChance = Random.Range(0f, 100f);
        if(tauntChance > tauntProbability)
        {
            // Wait for tauntDelay number of seconds.
            yield return new WaitForSeconds(tauntDelay);

            // If there is no clip currently playing.
            if(!GetComponent<AudioSource>().isPlaying)
            {
                // Choose a random, but different taunt.
                tauntIndex = TauntRandom();

                // Play the new taunt.
                GetComponent<AudioSource>().clip = taunts[tauntIndex];
                GetComponent<AudioSource>().Play();
            }
        }
    }

    int TauntRandom()
    {
        // Choose a random index of the taunts array.
        int i = Random.Range(0, taunts.Length);

        // If it's the same as the previous taunt...
        if(i == tauntIndex)
            // ... try another random taunt.
            return TauntRandom();
        else
            // Otherwise return this index.
            return i;
    }

    public void Jummp()
    {
        // If the jump button is pressed and the player is grounded then the player should jump.
        if (grounded)
            jump = true;
        else
        {
            jump = false;
        }
    }
}

```

# Answer
# Step 1: Get the Unity Standard Assets

You want to implement one or another of the Cross Platform Input controls available in the standard assets package, probably the joysticks.

https://www.assetstore.unity3d.com/en/#!/content/32351

# Step 2: Build your controls

If you look at the various sample scenes, such as 2dCharacter, CharacterFirstPerson, or CharacterThirdPerson, you'll find they have some form of mobile controls set up. CharacterFirstPerson has DualTouchControls in under Scene \> UI. This is also a prefab, under CrossPlatformInput \> Prefabs along with MobileSingleStickControl.

Drag one of those two prefabs into your scene, depending on what sort of controls you want.

You're done.

# Optional Step 3: Previewing

Now, the standard assets are set up to auto-detect if touch input is available (in the editor, it isn't). If you want to check to see that it's working you need to edit two files:

1) MobileControlRig.cs and remove lines 69, 71-73 2) CrossPlatformInputManager.cs lines 26, 28-30

Three of the lines will be compiler control lines with a `#` at the front. The fourth will be the "else" statement which we don't want (it'll undo the work of when the if is true and we want to fake it being true).
> -1 votes

---
Tags: unity, android, mobile
---


# Question
Title: Does anyone know what terrain generation algorithm is used here?
Does anyone know what this terrain generation algorithm is called? I saw it in two places. One was on YouTube, and the other, on Wikimedia.

# Answer
> 6 votes
In addition to what Pikalek said, it's also known as the Midpoint Displacement algorithm (because you perturb the midpoints of each edge) or Diamond-Square algorithm when working with a square instead of a triangle.

# Answer
> 2 votes
I've seen it referred to as 'fractal subdivision.' In this case, you assign a random height perturbation to the corners of the triangle, subdivided it at the midpoints of the edges & repeat the process over again for each triangle until some threshold is met.

---
Tags: algorithm, procedural-generation, terrain, procedural, fractal
---


# Question
Title: Hit detection for partially covered object?
Say you have a character standing behind cover such that some of its body parts like a shoe or a palm is still outside the cover.

An explosion takes place close to the cover . In real life this would mean the player getting damage in his arm or whichever body part was outside the cover.

How would you simulate this kind of hit detection efficiently in a game ?

An approximation would be to line trace from center of the explosion to each bone in the character mesh. But it might still not be accurate enough for larger bones , would be performance intensive and would not work for objects which are not skeletal meshes.

# Answer
A rather cheap but sufficiently accurate method is to mark key points on the character, in a tree structure such as one on the tip of the finger, one on the hand, one on the elbow, one on the shoulder as one branch etc. Note that elbow and shoulders are important points as those parts also have a chance to be exposed while the remaining body/arm is not. If there is room for more calculation you can also add a point for each section of the arm for more accurate damage calculation.

For the leg something like tip of feet, ankle, knee, hip would give a fairly accurate result. You can place the point for hip towards the end of the butt for more accuracy as I am sure no normal animation will make a character trust his/her hip forward out of cover. For the head it is probably as many points as you can but on normal animations, placing one on the forehead and one on the top of the head will cover most possible exposed areas.

To calculate the amount of damage received, you can trace the center of explosion to highest point of that branch or calculate how many points on the branch that is hit and apply a pre-determined multiplier. Or if your game has a body part damage system, damage that part of the body.

I do not suggest calculating by bones as there are usually more in certain places like the hand - each fingers will consist of at least 2 for animation, which there is almost no chance that a single finger is exposed to the explosion while the remaining are completely in cover - unless your character has a weird fetish of sticking his pinky out of cover to test for heat.
> 2 votes

---
Tags: collision-detection, game-design, game-mechanics, raytracing
---


# Question
Title: How to switch screens when a button is pressed? LibGDX
Currently working on a game for school and I ran into a problem. I created a Main Menu for my game with the buttons (Play, Level Picker, and Settings). What I'm trying to do is when the "Play" is pressed it will switch to a different screen where the user will play. The menu is under the name of MainMenu and the screen I want it to switch to is called StartGameScreen. I've tried looking online for my answer but can't seem to find something that will work. If it helps here's my code for the play button. Any help would be fantastic!

```
TextButton playButton = new TextButton("Play", (com.badlogic.gdx.scenes.scene2d.ui.Skin) skin); // Use the initialized skin
playButton.setPosition(Gdx.graphics.getWidth() / 2 - Gdx.graphics.getWidth() / 8, Gdx.graphics.getHeight() / 2 + (playButton.getHeight() + buttonOffSet));
playButton.addListener(new ClickListener() {

    @Override
    public void clicked(InputEvent event, float x, float y) {
        System.out.println("play game button clicked");
    }
});
stage.addActor(playButton);

```

# Answer
> 1 votes
Welcome to Stack Exchange!

A good reference for you to look at would be the libGDX wiki. Chances are it will answer 80% of your questions. Its "A Simple Game" tutorial and "Extending the Simple Game" tutorial walks through what you need (the latter shows how to switch screens).

The general pattern that you'll see though, is that when you have a screen class, you'll pass it an instance of your Game extension like so:

```
class MyScreen implements Screen {
  private Game parent;
  public MyScreen(Game parent) {
    this.parent = parent;
  }
  // Other stuff clipped due to space reasons
}

```

Then when you need to change to a different screen, you call Game's `setScreen()` method to change to a new screen. If you find that `setScreen()` doesn't do what you want, you can use the same pattern but create your own version of the `setScreen()` method.

---
Tags: java, libgdx
---


# Question
Title: How Do I Make an AI Player in Connect Four?
I am trying to create me one of those connect four games. I was doing some research on it and i found it to be quite a nice little self project. So I made strides in getting the game to run. So it works like a two person game but i don't really like the idea of two players. My goal is to create a player vs computer connect four. I took it upon myself and do some reasearch as to how to get an AI vs Human game and I came across using the MinMax algorithm to accomplish my goal. I am a bit lost when it comes to implementing the MinMax algorithm. I came accross which seems to be a marvellous implementation of minmax Here. I have been struggling for the past few days to implement the minmax algorithm in my code. As i said earlier, For now my code is a two player human vs human game. How do I create an AI vs Human game?

Here is my code:

```
    import java.util.Arrays;
    import java.util.Scanner;
    import java.util.stream.Collectors;
    import java.util.stream.IntStream;

     public class ConnectFour {
        private static final char[] players = new char[] { 'X', 'O' };

        private final int width, height;
        private final char[][] grid;
        private int lastCol = -1, lastTop = -1;

        public ConnectFour(int width, int height) {
            this.width = width;
            this.height = height;
            this.grid = new char[height][];
            for (int h = 0; h < height; h++) {
                Arrays.fill(this.grid[h] = new char[width], '.');
            }
        }

        public String toString() {
            return IntStream.range(0, this.width)
                            .mapToObj(Integer::toString)
                            .collect(Collectors.joining()) + "\n" +
                   Arrays.stream(this.grid)
                         .map(String::new)
                         .collect(Collectors.joining("\n"));
        }

        /**
         * Prompts the user for a column, repeating until a valid
         * choice is made.
         */
        public void chooseAndDrop(char symbol, Scanner input) {
            do {
                System.out.print("\nPlayer " + symbol + " turn: ");
                int col = input.nextInt();

                if (! (0 <= col && col < this.width)) {
                    System.out.println("Column must be between 0 and " +
                                       (this.width - 1));
                    continue;
                }
                for (int h = this.height - 1; h >= 0; h--) {
                    if (this.grid[h][col] == '.') {
                        this.grid[this.lastTop=h][this.lastCol=col] = symbol;
                        return;
                    }
                }

                System.out.println("Column " + col + " is full.");
            } while (true);
        }

        /**
         * Detects whether the last chip played was a winning move.
         */
        public boolean isWinningPlay() {
            if (this.lastCol == -1) {
                throw new IllegalStateException("No move has been made yet");
            }
            char sym = this.grid[this.lastTop][this.lastCol];
            String streak = String.format("%c%c%c%c", sym, sym, sym, sym);
            return contains(this.horizontal(), streak) ||
                   contains(this.vertical(), streak) ||
                   contains(this.slashDiagonal(), streak) ||
                   contains(this.backslashDiagonal(), streak);
        }

        /**
         * The contents of the row containing the last played chip.
         */
        private String horizontal() {
            return new String(this.grid[this.lastTop]);
        }

        /**
         * The contents of the column containing the last played chip.
         */
        private String vertical() {
            StringBuilder sb = new StringBuilder(this.height);
            for (int h = 0; h < this.height; h++) {
                sb.append(this.grid[h][this.lastCol]);
            }
            return sb.toString();
        }

        /**
         * The contents of the "/" diagonal containing the last played chip
         * (coordinates have a constant sum).
         */
        private String slashDiagonal() {
            StringBuilder sb = new StringBuilder(this.height);
            for (int h = 0; h < this.height; h++) {
                int w = this.lastCol + this.lastTop - h;
                if (0 <= w && w < this.width) {
                    sb.append(this.grid[h][w]);
                }
            }
            return sb.toString();
        }

        /**
         * The contents of the "\" diagonal containing the last played chip
         * (coordinates have a constant difference).
         */
        private String backslashDiagonal() {
            StringBuilder sb = new StringBuilder(this.height);
            for (int h = 0; h < this.height; h++) {
                int w = this.lastCol - this.lastTop + h;
                if (0 <= w && w < this.width) {
                    sb.append(this.grid[h][w]);
                }
            }
            return sb.toString();
        }

        private static boolean contains(String haystack, String needle) {
            return haystack.indexOf(needle) >= 0;
        }

        public static void main(String[] args) {

            int XColumnPosition;
            int maxDepth = 4;
            MinimaxAI OPlayer = new MinimaxAI(maxDepth, Board.O); // failed attempt to add minmax

            try (Scanner input = new Scanner(System.in)) {
                int height = 6, width = 8, moves = height * width;
                ConnectFour board = new ConnectFour(width, height);
                System.out.println("Use 0-" + (width - 1) + " to choose a column.");
                System.out.println(board);

                for (int player = 0; moves-- > 0; player = 1 - player) {
                    char symbol = players[player];
                    board.chooseAndDrop(symbol, input);
                    System.out.println(board);
                    if (board.isWinningPlay()) {
                        System.out.println("Player " + symbol + " wins!");
                        return;
                    }
                }
                System.out.println("Game over, no winner.");
            }
        }
    }

```

And here is the MinMAx class:

```
 class MinimaxAI {

    //Variable that holds the maximum depth the MiniMax algorithm will reach for this player
    private int maxDepth;
    //Variable that holds which letter this player controls
    private int playerLetter;

    public int getMaxDepth() {
        return maxDepth;
    }

    public void setMaxDepth(int maxDepth) {
        this.maxDepth = maxDepth;
    }

    public int getPlayerLetter() {
        return playerLetter;
    }

    public void setPlayerLetter(int playerLetter) {
        this.playerLetter = playerLetter;
    }

    public MinimaxAI() {
        maxDepth = 4;
        playerLetter = Board.X;
    }

    public MinimaxAI(int maxDepth, int playerLetter) {
        this.maxDepth = maxDepth;
        this.playerLetter = playerLetter;
    }

    //Initiates the MiniMax algorithm
    public Move MiniMax(Board board) {
        //If the X plays then it wants to MAXimize the heuristics value
        if (playerLetter == Board.X) {
            return max(new Board(board), 0);
        }
        //If the O plays then it wants to MINimize the heuristics value
        else {
            return min(new Board(board), 0);
        }
    }

    // The max and min functions are called interchangingly, one after another until a max depth is reached
    public Move max(Board board, int depth) {
        Random r = new Random();

        /* If MAX is called on a state that is terminal or after a maximum depth is reached,
         * then a heuristic is calculated on the state and the move returned.
         */
        if((board.checkGameOver()) || (depth == maxDepth))
        {
            Move lastMove = new Move(board.getLastMove().getRow(), board.getLastMove().getCol(), board.evaluate());
            return lastMove;
        }
        //The children-moves of the state are calculated
        ArrayList<Board> children = new ArrayList<Board>(board.getChildren(Board.X));
        Move maxMove = new Move(Integer.MIN_VALUE);
        for (Board child : children) {
            //And for each child min is called, on a lower depth
            Move move = min(child, depth + 1);
            //The child-move with the greatest value is selected and returned by max
            if(move.getValue() >= maxMove.getValue()) {
                if ((move.getValue() == maxMove.getValue())) {
                    //If the heuristic has the same value then we randomly choose one of the two moves
                    if (r.nextInt(2) == 0) {
                        maxMove.setRow(child.getLastMove().getRow());
                        maxMove.setCol(child.getLastMove().getCol());
                        maxMove.setValue(move.getValue());
                    }
                }
                else {
                    maxMove.setRow(child.getLastMove().getRow());
                    maxMove.setCol(child.getLastMove().getCol());
                    maxMove.setValue(move.getValue());
                }
            }
        }
        return maxMove;
    }

    //Min works similarly to max
    public Move min(Board board, int depth) {
        Random r = new Random();

        if((board.checkGameOver()) || (depth == maxDepth)) {
            Move lastMove = new Move(board.getLastMove().getRow(), board.getLastMove().getCol(), board.evaluate());
            return lastMove;
        }
        ArrayList<Board> children = new ArrayList<Board>(board.getChildren(Board.O));
        Move minMove = new Move(Integer.MAX_VALUE);
        for (Board child : children) {
            Move move = max(child, depth + 1);
            if(move.getValue() <= minMove.getValue()) {
                if ((move.getValue() == minMove.getValue())) {
                    if (r.nextInt(2) == 0) {
                        minMove.setRow(child.getLastMove().getRow());
                        minMove.setCol(child.getLastMove().getCol());
                        minMove.setValue(move.getValue());
                    }
                }
                else {
                        minMove.setRow(child.getLastMove().getRow());
                        minMove.setCol(child.getLastMove().getCol());
                        minMove.setValue(move.getValue());
                }
            }
        }
        return minMove;
    }

 }

```

# Answer
> 0 votes
*I understand that the OP is mostly asking for the integration of his AI in his program, rather than the algorithm itself as he said using min-max already*

My first intuition for a Connect-four game would be to have a game loop processing the turns.

```
while (gameOn)
{
    // Get user or AI input
    // Process the input
}

```

As you have 2 players, you would need to know which turn it is. You can have a variable for that.

```
int playerNb = 0;
while (gameOn)
{
    if (playerNb == 0)
        // Get user input
    else
        // Get AI input

    // Process the input
    // Change playerNb to 1 or 0
}

```

Then just implement your algorithm in the `GetAIInput()` method. A min-max algorithm may be well-suited for this problem, but I would suggest you try different approaches so you can see how the AI reacts each time. That will be a really good exercise which will help you understand the basis of AI development if you are new to this.

---
Tags: java
---


# Question
Title: LWJGL - My glsl code somehow does not work
I am following the tutorial "3D Game Development with LWJGL3" using LWJGL 3.0.2(stable)

https://www.gitbook.com/book/lwjglgamedev/3d-game-development-with-lwjgl/details

I am following the chapter "Rendering" . Since the vertex.vs and fragment.fs did not work, I tried to compile the shaders using Strings.It was supposed to create a triangle on the screen. However, the result console said it was a problem with some newlines. I am using Eclipse and latest jre and jdk and imported the library through the Build path property.

I am NOT using Maven because there is no Apache Maven installed in my workstation and it is very tedious.

Program Directory:-

> LWJGL
>
> > Engine
> >
> > > GameEngine.java
> > >
> > > Window.java
> > >
> > > Timer.java
> > >
> > > Utils.java(unused)
> > >
> > > IGameLogic(interface).java
> > >
> > > Engine.Graph
> > >
> > > > ShaderProgram.java
> >
> > Game
> >
> > > DummyGame.java
> > >
> > > Renderer.java
> > >
> > > Main.java

Renderer.java

```
package game;
import java.nio.FloatBuffer;
import org.lwjgl.BufferUtils;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL15.*;
import static org.lwjgl.opengl.GL20.*;
import static org.lwjgl.opengl.GL30.*;
import engine.Window;
import engine.Graph.ShaderProgram;
public class Renderer {
 public String fragmentShaderData =
                        "#version 330                   /n"+ "/n" +   "/n" +
                                 "out vec4 fragColor;                                    +
                                 "void main()                    /n"+ "/n" +
                                 "{                        /n"+
                                 "fragColor = vec4(0.0, 0.5, 0.5, 1.0);                   /n"+ "/n" +
                                 "}                     /n" +"/n" ;
 public String vertexShaderData =
 "#version 330   /n"+ "/n"+
        "layout (location =0) in vec3 position;      /n"+"/n"+
        "void main()                /n"+"/n"+
        "{                         /n"+"/n"+
        "gl_Position = vec4(position, 1.0);                   /n"+"/n"+
        "}                           /n"+"/n";

    private int vboId;

 private int vaoId;

 private ShaderProgram shaderProgram;

 public Renderer() {
 }

 public void init() throws Exception {
     shaderProgram = new ShaderProgram();
     shaderProgram.createVertexShader(vertexShaderData);
     shaderProgram.createFragmentShader(fragmentShaderData);
     shaderProgram.link();

     float[] vertices = new float[]{
         0.0f,  0.5f, 0.0f,
         -0.5f, -0.5f, 0.0f,
         0.5f,  -0.5f, 0.0f
     };

     FloatBuffer verticesBuffer = BufferUtils.createFloatBuffer(vertices.length);
     verticesBuffer.put(vertices).flip();

     // Create the VAO and bind to it
     vaoId = glGenVertexArrays();
     glBindVertexArray(vaoId);

     // Create the VBO and bint to it
     vboId = glGenBuffers();
     glBindBuffer(GL_ARRAY_BUFFER, vboId);
     glBufferData(GL_ARRAY_BUFFER, verticesBuffer, GL_STATIC_DRAW);
     // Define structure of the data
     glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0);

     // Unbind the VBO
     glBindBuffer(GL_ARRAY_BUFFER, 0);

     // Unbind the VAO
     glBindVertexArray(0);
 }

 public void clear() {
     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
 }

 public void render(Window window) {
     clear();

     if ( window.isResized() ) {
         glViewport(0, 0, window.getWidth(), window.getHeight());
         window.setResized(false);
     }

     shaderProgram.bind();

     // Bind to the VAO
     glBindVertexArray(vaoId);
     glEnableVertexAttribArray(0);

     // Draw the vertices
     glDrawArrays(GL_TRIANGLES, 0, 3);

     // Restore state
     glDisableVertexAttribArray(0);
     glBindVertexArray(0);

     shaderProgram.unbind();
    }

     public void cleanup() {
     if (shaderProgram != null) {
         shaderProgram.cleanup();
     }

     glDisableVertexAttribArray(0);

     // Delete the VBO
     glBindBuffer(GL_ARRAY_BUFFER, 0);
     glDeleteBuffers(vboId);

     // Delete the VAO
     glBindVertexArray(0);
     glDeleteVertexArrays(vaoId);
 }
}

```

The rest of the code is same as of the sources of this repository:-

Source code

Except that Utils.java is not used.

The result:

```
java.lang.Exception: Error compiling Shader code: ERROR: 0:1: '#version' :     syntax error
ERROR: 0:1: '' : syntax error: unexpected tokens following preprocessor directive - expected a newline

 at engine.Graph.ShaderProgram.createShader(ShaderProgram.java:71)
 at engine.Graph.ShaderProgram.createVertexShader(ShaderProgram.java:37)
 at game.Renderer.init(Renderer.java:64)
 at game.DummyGame.init(DummyGame.java:34)
 at engine.GameEngine.init(GameEngine.java:91)
 at engine.GameEngine.run(GameEngine.java:67)
 at java.lang.Thread.run(Unknown Source)

```

Please help!!!!!

There seems to be a problem with my shaders, but I don't know why.

# Answer
The newline argument has to be written as \n (with backslash).
> 0 votes

# Answer
```
 public String fragmentShaderData =
                         "#version 330 \n" +
                          "out vec4 fragColor;" +
                          "void main(){" +
                            "fragColor = vec4(0.0, 0.5, 0.5, 1.0);" +
                          "}";

```

is way more readable and should work, too.
> 0 votes

---
Tags: opengl, java, glsl, lwjgl3
---


# Question
Title: Checking for Weapon Collision in a 2D overhead RPG game
I'm starting development on a 2D overhead RPG game, and am wondering what the best approach for handling weapon collision and dealing damage to enemies is.

I'm currently using a basic Entity/Component structure for my game objects. I have a CharacterEntity, that has an EquipableEntity data member. The CharacterEntity has a component that listens for input. When a command to attack is received, the CharacterEntity is set into an attack mode where an attacking component gets the equipped entity and moves it in the attacking motion. Any collisions detected with the moving equipped entity in the world are then registered as successful attacks. Once the attacking component determines the attack is finished, the CharacterEntity leaves attack mode and returns to it's normal state.

Weapon collision is a basic LWJGL Rectangle that tests the .interesects() method, checking against all enemy rectangles. Currently it's just a stabbing motion (it moves out to x length, then returns).

The reason I did it this way was:

1) I wanted enemies to receive and respond damage as the sword crosses their path, instead of just saying "attack occurred in this general area" and having all enemies update at once. In the stabbing case, an enemy at the full length of the sword wouldn't take damage until the actual sword entity crosses it's path.
2) The weapons define their own appearance and boundary on the screen, making it easier to animate and sync with the game.

I'm entirely new to game development (if you haven't figured that out already). Is this the appropriate way to achieve the result I'm looking for, or complete overkill? How does a game like Terraria (where weapons move in a sweeping motion) or the Zelda series handle attacking and determining what enemies to hit and when? Am I on the right path or totally off?

Any advice or suggestions would be greatly appreciated.

# Answer
> 1 votes
Does the game resolve collisions the way you want it to? If so, I don't think you're off track at all. There is no right or wrong answer here. These kinds of logic decisions are totally open and have to be made based on how you envision your game behaving. Game developers make these decisions on a daily basis.

What I would say is this: Terraria is platform game, and a very retro one at that. What this means is you can typically get away with a more simplistic approach to collision detection, eg. the approach you've implemented. I'm also writing a top down action game with melee combat. My approach was to use Box2D for the collision detection so that sword swings etc. are accurate, realistic, and very fast to process. Realistic means attacks will impart linear and angular impulse to objects. So when you hit something, it can spin and be knocked back. It's a simple step to add breakable objects, too, i.e. `if (force > object.strength) object.break();`

If you are planning on making future games, you can't go wrong learning Box2D, it's available for every major language. However if you are just testing the waters of game development, so to speak, then keep it simple: stick with your present solution for now.

# Answer
> 0 votes
actually theres is a lot of ways of do that, you can calculate the distance of nearbys objects and when you atack, depending of the mouse pos(or the character face atack on that way), also can you can create a empty object whit a collider, this will spawn whit a offset this empty object will have a box collider, and there is the mathematical solution make a radius, pick up a cone to wheres its facing you character, if u atack u will hit the most nearest thing from the cone (to only hit one enemy).

# Answer
> 0 votes
An alternative, much simpler solution is a simple hit-scan solution.

At one specific frame during the animation, damage everything within the attack zone. Define the attack zone as a geometric shape which roughly matches the attack animation and affect all enemies whose hitboxes/hitcircles/hitwhatevers intersect it. This looks reasonably well when you have short attack animations and works around a lot of problems, like for example making sure that each enemy is only hit once by each attack.

You might want to implement this first and see if it is sufficient. Should it turn out that you would rather have "sweeping" attacks which affect different areas during different animation stages, you can still easily upgrade to that later by allowing your attacks to have more than one "hitscan frame" with different shapes over the course of their animations.

# Answer
> -2 votes
The answer to your question depends on the features and style of your game. For example your approach may be useful if it will be possible to throw the sword(dagger) or damage regions of enemies bodies (like in Fallout).

---
Tags: collision-detection, rpg, component-based, entity-system, combat
---


# Question
Title: Transform manipulator for Unity/Oculus Touch game like in Quill, Medium etc
I'm trying to create a script to manipulate the transform of a gameobject using the Oculus Touch just as in for instance Quill or Medium, with rotation, translation and scaling. Can somebody help me with this? My initial attempt was to focus on rotation and I got it almost working I think. Here's the code:

```
void Update()
{
  // On button down
  if (OVRInput.GetDown(OVRInput.Button.SecondaryIndexTrigger))
  {
    originalRotation = transform.localRotation;
    originalControllerRotation =
      OVRInput.GetLocalControllerRotation(OVRInput.Controller.RTouch);
  }

  // While button is down
  if (OVRInput.Get(OVRInput.Button.SecondaryIndexTrigger))
  {
    var controllerRotation =
      OVRInput.GetLocalControllerRotation(OVRInput.Controller.RTouch);

    var rotation = originalRotation;
    rotation *= Quaternion.Inverse(originalControllerRotation);
    rotation *= controllerRotation;
    transform.localRotation = rotation;
  }
}

```

This kind of works but the rotation center doesn't look right. I want it to rotate around the center of the right touch controller and it looks to be rotating around the local origo of the gameobject. How do I modify the code so it rotates around the controller instead?

# Answer
I think I know how to do this now. It easiest way seem to be to "parent" my gameobject's transform to the controller transform somehow. I haven't had time to code this yet but I see this a bit more clearly now...
> 0 votes

---
Tags: unity, input, transformation, quaternion, oculus
---


# Question
Title: How to use one scene's camera in another scene?
I have two scenes in my game: one is the menu scene with the UI and the other is the scene where all my game items are.

Right now my UI looks too plain, so what I want is to display my actual game scene in its background. I have plans to make the camera view move between two points so as to have an animated scene running.

I can think of one way to do this, which will be to duplicate the game scene and bring it to the UI scene but it would be clunky. Can I use other scene's camera to display its content in another scene?

# Answer
> 1 votes
In Unity 5 you can embed multiple scenes in one scene by dragging them from the projects folder into your scene. You can then choose to render multiple cameras at the same time.

For Unity 4 you probably want to either set the level as a prefab if that fits your game structure or just build the main menu into the actual level, which may improve scene transitions.

---
Tags: unity, camera, scene
---


title: Segmenting an MMO market

text:
# Question
Title: Segmenting an MMO market
I've been considering a *segmented* market for an MMO:

1. There is a different market for each in-game level (Level 1 players can only buy/sell items from the Level 1 market)
2. If a player levels up with items still in the market, they remain there, but can be removed if the player wishes.
3. The levelled market is the only way to trade items between players.

A few things I expect to happen:

1. The market won't be completely segmented. If the Level 2 market's price for X is higher, then I'll just keep it to sell (and vice versa).
2. However, despite the above, there will still be X sold, as buying/selling makes it easier for the player to level up.
3. Therefore, there will be an inflation *curve*, where gold will be worth less and less on each level.
4. Inflation over time will occur faster at level 20 than at level 1.

Are my assumptions above correct?

# Answer
Whats the point?

People will try to get to max level anyways. The max level market will have much more volume then all lower level markets combined (thats somewhat your point 1).

Older player will know the prices at max level. Their understanding of the prices will dominate the market. Whenever an older player levels up a new character, he will simply buy cheap items along the way to max level, effectively making money of new players who not yet know the values of their items, while not touching overpriced items anyways.

The only thing this does is creating akward and frustrating situations. If items are cheaper at low levels, people will start leveling up new characters to buy low items from low level markets, level them up to max level and sell items there. It will also create "hoarder" mentality in which you hoard items instead of selling them, since you get more at max level.

If items are more expensive at low levels, you only screw new players.

And if prices are the same, whats the justifications for a fragmented market in the first place?

> However, despite the above, there will still be X sold, as buying/selling makes it easier for the player to level up.

How is that? Do you get experience for market transactions? That would be a nightmare to balance.

And if you make money quite scarce so that selling stuff would allow you to buy better gear and level easier up, then thats great. but who could possibly buy that stuff? Low level markets would be full off stuff nobody has money to buy.

> Therefore, there will be an inflation curve, where gold will be worth less and less on each level.

Yes. however, you can achieve that more easily. Simple increase gold rewards with level. Max level player will get more gold, so its worth less for them.

> Inflation over time will occur faster at level 20 than at level 1.

Not exactly. Since the max level market will dominate all prices anyways (people will hold onto items to sell at max level), the prices at low levels will slowly follow suit. All you accomplish is that low level players can buy less and less stuff over time since there is no transfer of money from the top down.

You need the ability for low level players to sell to high level players, since they are the ones that have gold to spend and low level players are the ones who need it the most. Same with hardcore / casual players. You can't make players stop getting money or spending it. the goal should be to distribute the gold that is made...

So in short, I don't see how most of your assumptions would actually come true.
> 2 votes

---
Tags: game-mechanics, mmo, economy
---


# Question
Title: Can a project made in Unreal Engine be converted to Unity project with a tool?
Recently working on Unreal Engine for a project but want to convert the whole project to Unity. Is there any way?

# Answer
> 10 votes
No.

There's no tool or automatic conversion process for this. You will need to make such a conversion almost entirely manually.

It's possible you will be able to find tools to bulk-convert any assets that are in one format to another, although there is a good chance Unity also supports whatever (source) asset format you're using in Unreal. Unity will not process `.uasset` files directly; you will need the source `.fbx` files, et cetera.

But all the code, anything in Blueprints or C++, will need to be rewritten in C# and `MonoBehavior` and likely heavily adapted in the process to Unity's rather different mode of operation.

---
Tags: unity, unreal-4
---


title: Attack Rating for Weapons

text:
# Question
Title: Attack Rating for Weapons
I'm considering a combat power(CP) estimation for a game I'm working on, which acts as a function of different variables, including attack, def, speed, etc.(I haven't decided the function yet).

Now my game(s) use an ELO Rating system. CP is such that, if two players with same rating and CP battled, they would both have expectations of 0.5

In particular, if we considered two players A & B with CPs X and Y respectively. {X: Y \<= X} and Ratings R1 & R2 respectively. In calculating player's expectation, something called Real Rating(RR) is used.

RR1 = (R1 * X)/Y

The value to be added to RR1 after the match d is calculated as: K\*(SA - EA)

The updated value of R1; R'1 is given by:
R'1 = R1 + (d/RR1)R1

Due to the fact that CP affects player's rankings, I want to calculate it properly.

I'm currently considering an FPS game.

My question is this:

> Given two weapons W1 and W2 with damages: D1 & D2 {D1: D1 \< D2} per shot, but different refire times: T1 & T2 {T1: T2 \< T1} respectively which have the same DPS(Damage Per Second), should they receive the same 'Attack' score? If not how would you distribute their 'Attack' score?

I'm worried about this, since I want my game ratings to be as consistent as possible. I read online about one law which goes like this:

> Speed of iteration is better than quality of iteration.

I'm guessing this means W1 should have a higher score? If so, how much higher in terms of W2?

# Answer
There are a few points to consider on this.

1. Is there a maximum attack speed? If so, how much faster do you get by simply having attack speed modifiers or are there even any other modifiers to attack speed other than weapon speed?
2. Is there a maximum hit point value? If so, could the player be killed in one or two hits? If so, does this make the higher damage weapons more effective in terms of combat?
3. Same DPS could mean a whole lot of things. Depending on character attributes, dodging abilities, map design and general engagement time.
4. Can the characters move while attacking? Being unable to move for X amount of seconds means you're also vulnerable to attacks for that amount of time once you start your animation, that would mean a lower score for the slower weapon.
5. Is there HP regeneration? If so, does this lower the score of a weapon type or the other? (Generally, this would mean lower damage per hit is less effective.)

So, with all those points considered, if we make them all irrelevant to the question we come up with these:

* You can move while attacking
* There is no HP regeneration and players have the same amount of health but this doesn't put them in danger of getting killed too fast
* Map has no elements that can be used to hide, i.e. simple dojo
* Both weapons are identical other than one having higher attack speed but lower damage per hit than the other
* Players cannot dodge hits (other than simply moving away)

Anyway, I have nothing else that comes to my mind, so if these bullet points are all true, then the weapons should be effectively the same.
> 2 votes

# Answer
If you are calculating ONLY the CP value of rate of fire versus damage I would agree that a weapon with higher rate of fire will value greater than a weapon with more damage even if their damage per second is equal.

However, you included ELO rating in the overall value calculation. The main reason fire rate is worth more than damage is because of the skill requirement to use a weapon that hits slow but hard. By having already taken the player's skill into consideration, you might not need to scale the value of a weapon by it's variation of stats.

Do however, take note that ELO rating value will only take effect after a player have faced a certain number of opponents and a player's overall skill level does not indicate his/her effectiveness with a type of equipment. So to calculate a player's overall capability with the current chosen weapon will involve a lot more than just slapping two different rating system together.

Overall, my answer to your question is Yes, but I cannot provide any formulae for you as there is a lot more involved in the calculation such as effective range, accuracy, recoil etc. of a weapon that affects the value of it's damage and rate of fire value. Also, it will instead be inaccurate is you sum it up with ELO rating. So I advise you to rethink another way to calculate a player's overall rating as there is too much room for error this way - or too much formulas, assuming you get it right after a large amount of calculation.
> -1 votes

---
Tags: game-design, game-mechanics, scoring
---


# Question
Title: My character movement doesn't feel smooth.. [Unity]
So I use this code, with a Rigidbody attached to my GameObject (player)..

```
using UnityEngine;

public class Player : MonoBehaviour
{
    public float speed = 4f;
    private float movement = 0f;
    public Rigidbody2D rb;

    private void Update()
    {
        movement = Input.GetAxisRaw("Horizontal") * speed;
    }

    void FixedUpdate ()
    {
        rb.MovePosition(rb.position
            + new Vector2(movement * Time.fixedDeltaTime, 0f));
    }
}

```

The problem is the movement feels jerky / not smooth. It might just be me, though.

No, this is not a duplicate of a similar question. I am using other code and it's not totally similar to what I'm doing

# Answer
> 2 votes
There are a few problems here. First, let's look at a typical series of frames in Unity:

* Frame 1
    + Read Input
    + FixedUpdate
    + FixedUpdate
    + Update
    + Draw
* Frame 2
    + Read Input
    + FixedUpdate
    + Update
    + Draw

So, the first thing to note is that you get different numbers of FixedUpdate calls from one frame to the next. This can create a visible judder, where the character appears to be moving at one speed, then you get a frame with fewer FixedUpdates and they appear to slow or stutter for a frame before continuing.

The simplest solution here is to enable Rigidbody Interpolation, and move the object using velocity. This will offset the rendered position of the object by whatever fractional timestep is needed to keep up with the frame time, without upsetting the predictable fixed timestep of the underlying simulation.

(Some folks don't like controlling characters via velocity, especially player characters, although I've generally found it quite workable. If it's not your style, you might prefer to remove the Rigidbody and move the object directly using its transform in Update, or use a character controller)

The second issue here is that you're capturing input in Update, but not actually using it until FixedUpdate. Since FixedUpdate runs before Update, that means you don't get to act on this information until the next frame, which adds latency to your game. For continuous values like `Input.GetAxis`, this data is already available and usable in FixedUpdate - so you can just grab it fresh when you want to use it. (Special care needs to be given to capturing instantaneous actions like `Input.GetButtonDown` though, to avoid missing or double-counting the events)

So, a fixed version might look like this - and it's simpler too! :)

```
public class Player : MonoBehaviour
{
    public float speed = 4f;
    public Rigidbody2D rb;

    void FixedUpdate ()
    {
        rb.velocity = Vector3.right * Input.GetAxis("Horizontal") * speed;
    }
}

```

# Answer
> 0 votes
You're using Input.GetAxisRaw, which returns the value with no smoothing filtering applied. This is useful ONLY if you want to do all smoothing of input processing by yourself.

In your case, just try to use Input.GetAxis instead.

---
Tags: unity
---


title: Coordinate in LibGDX?

text:
# Question
Title: Coordinate in LibGDX?
Hi i am learning libGDX these days, I followed this example, and I read this wiki

I dont really understand these line of code after adding `viewport`

```
@Override
public void resize(int width, int height) {
super.resize(width, height);
extendViewport.update(width, height);
batch.setProjectionMatrix(orthographicCamera.combined);
}

```

And rendering

```
batch.begin();

banana.setPosition(0, 0);
banana.draw(batch);

banana.setPosition(100, 100);
banana.draw(batch);

batch.end();

```

Looking at the example, they still draw the banana in **bottom-left** of screen, I mean the (0, 0) point still in bottom-left of screen

While in my code, I think it changed the coordinate to **center** of screen, (0, 0) now is center of screen.

I am not clearly understand about this.

# Answer
> 1 votes
When you call `ExtendViewport#update()`, you're not passing the third parameter (like the tutorial does), so it is centering the camera on 0,0 instead of positioning the camera so that 0,0 is in the lower-right corner.

If you change your call to be `extendViewport.update(width, height, false)` it should remedy the issue.

---
Tags: libgdx, coordinates
---


# Question
Title: Unreal Engine Physics creation is slower in Editor
I just figured out that when UPrimitiveComponent::CreatePhysicsState() is called, it calculates the mass, but only in editor, also when i build for non-editor it is faster (standalone) this is not because the editor is eating up resources, because time is measured in code. Why is the mass only calculated in editor?

# Answer
It seems as if you are referring to this block of code, in `OnCreatePhysicsState` for `UPrimitiveComponent`. Specifically the line which calls `BodySetup->CalculateMass()` with `this` as a parameter.

This entire block of code is only run in editor builds (note the `WITH_EDITOR` guards), either because it is slow or because it is relying on assumptions that can be made of a primitive component placed in the editor but not at runtime (such as, perhaps when placing the component a slow operation was run to generate some data the code depends on, but that slow operation is not automatically run if the component is created at runtime).

In general, Unreal does not do cooking of complex physics collision data at runtime, except for a few things (such as for road splines at the like), because it is expensive.

However, `UBodySetup`'s `CalculateMass` function just *calculates* the mass. It doesn't store it anywhere, so just because this code is not executed *here*, in `OnCreatePhysicsState`, does not mean it does not happen elsewhere.
> 1 votes

---
Tags: c++, physics, unreal-4, unreal
---


# Question
Title: AABB Collision Detection: Why does the simple broadphase algorithm work better?
Hi I am working on barrier detection.

I used this swept aabb algorithm http://www.gamedev.net/page/resources/\_/technical/game-programming/swept-aabb-collision-detection-and-response-r3084.

It suggests two ways to detect collision. 1. broadphase: this is a shorter-algorithm which can only detect non-collision 100%. 2. In order to make sure that there is a collision, the more detailed swept aabb algorithm has to be executed right after the broadphase one.

Strangely the broadphase algorithm alone detects a barrier collision each and every time and the more precise one actually doesn't at all times.

What I do in my code is basically the following: My object moves towards the barrier with a constand speed vx = direction * speed * delta (that's the amount it moves each frame). So positionx = positionx + (direction * speed * delta) each frame. The broadphase-collision is calculated each frame by using vx and vy.

Are there some rare cases where the broadphase can actually detect a collision like in this one I described? Thanks so much for your help

Thanks so much

# Answer
For reference, this is the broad-phasing:

The broad phase works 100% if the other object always overlaps with the swept area if it ever overlaps with the broad phase area. Usually this means axis-aligned barriers that are either infinite length, or whose ends/corners aren't inside the broad phase area.
> 0 votes

---
Tags: android
---


# Question
Title: Incentive for players to choose hard difficulty
In a single-player game with difficulty settings, it seems obvious for players to choose the easy difficulty setting. How can I make incentives for players to choose harder difficulty settings?

# Answer
You assume it is "obvious," but that's a faulty assumption. For some players, increased difficulty *alone* is enough of an incentive. Players are driven by a variety of motivating factors, and while story and "experience" is one of those factors (such players may not like challenging gameplay and may thus opt for easier difficulty levels), there are certainly players that revel in overcoming challenging mechanics alone and will always pick the highest available difficulty level.

You can further incentivize players to do this by offering other rewards for completing the game on higher difficulty settings:

* achievements
* unlocks for cosmetic items
* unlocks for new game modes or abilities
* extra story content (the "true ending")

Note however that being too heavy-headed with putting content behind difficulty gates can result in a negative reaction from players, who may be offended by your giving apparent preferential treatment to the gamers who only want the hardest challenges, and thus considering the ones who prefer simpler experiences "beneath" your game.

It's an open question whether or not it's a benefit to lock the hardest difficulty mode behind a slightly-less-hard difficulty mode, as well. Some players will enjoy the discovery of an even more challenging mode, but some will not find the replay value sufficient.
> 5 votes

# Answer
Higher exp multiplier is a common simple incentive to implement. Is seen in games like fallout, project zomboid... This makes up for the time you spend getting killed and keeps the tension up
> -2 votes

---
Tags: difficulty
---


# Question
Title: tile map collision with player not working - 2D c# xna
Currently the tile map is drawing fine but I am not sure how to proceed with collisions between the player and some of the tiles. Would it be better to specify certain tiles that the player can't move through or is there a better way to go about this? I basically want tile number 4 to not be passable when the player hits it. The issue as far as I'm aware is with the logic in the method *Check for colllision* in the *TileMap* class. At the minute I simply want it to state when it hits the tile 4 in the console log. After using the debugging tools the nested for loop in the check for colliision method isn't being run.

Thank you very much in advance and any help is greatly appreciated.

**MapCell**

```
public class MapCell
{

    public int TileID { get; set; }

    public MapCell(int tileID)
    {
        TileID = tileID;
    }
}

```

\`}

**Player class**

in the update method

```
playerRect = new Rectangle((int)Position.X, (int)Position.Y, playerRect.Width, playerRect.Height);

```

**TileMap**

```
class TileMap
{
    Player player = new Player(null, Vector2.Zero);
    private List<Texture2D> tileList = new List<Texture2D>();
    MapCell[,] mapCell;

    public const int TILE_WIDTH = 64;
    public const int TILE_HEIGHT = 64;
    private bool passable = true;

    public TileMap(int[,] exisitingMap)
    {
        //initialise this to a new multidimensional array;
        mapCell = new MapCell[exisitingMap.GetLength(0), exisitingMap.GetLength(1)];

        // x always starts on one
        for (int x = 0; x < mapCell.GetLength(1); x++)
        {
            for (int y = 0; y < mapCell.GetLength(0); y++)
            {
                mapCell[y, x] = new MapCell(exisitingMap[y, x]);
            }
        }

     }

    public void loadTextureFiles(ContentManager content, params string[] fileNames)
    {
        Texture2D tileTexture;
        foreach (string fileName in fileNames)
        {
            tileTexture = content.Load<Texture2D>(fileName);
            tileList.Add(tileTexture);
        }
    }

    public void checkForCollision()
    {
        int tileX = (int)(player.Position.X) / TILE_WIDTH;
        int tileY = (int)(player.Position.Y) / TILE_HEIGHT;

        int left = player.playerRect.Left / TILE_WIDTH;
        int top = player.playerRect.Top / TILE_HEIGHT;
        int right = (int)Math.Ceiling((float)player.playerRect.Right / TILE_WIDTH) - 1;
        int bottom = (int)Math.Ceiling((float)player.playerRect.Bottom / TILE_HEIGHT) - 1;

          for(int y = top; y<= bottom; ++y)
        {
            for (int x = left; x <= right; ++x)
            {
                if (new Rectangle(x * TILE_WIDTH, y * TILE_HEIGHT, TILE_WIDTH, TILE_HEIGHT).Intersects(player.playerRect))
                {
                    Console.WriteLine("collision");
                  if (mapCell[top, tileX].TileID == 4)
                    {
                        Console.WriteLine("tile 4 has been hit");
                        passable = false;
                    }
                }
            }
        }

    }
    public void Update(GameTime gameTime)
    {
        checkForCollision();

    }

    public void Draw(SpriteBatch spriteBatch)
    {
        for (int x = 0; x < mapCell.GetLength(1); x++)
        {
            for (int y = 0; y < mapCell.GetLength(1); y++)
            {
                // setting the index to the tile ID
                int index = mapCell[y,x].TileID;

                // checking if there is a tile
                if(index > 0)
                {
                    // start from the first index.
                    Texture2D texture = tileList[index -1 ];
                    spriteBatch.Draw(texture, new Rectangle(x * TILE_WIDTH, y * TILE_HEIGHT, TILE_WIDTH, TILE_HEIGHT), Color.White);
                }
            }
        }
    }

```

**Game 1**

```
        TileMap tileMap = new TileMap(new int[,]
    {
        // needs to be separated by a comma
        { 4,4,4,4,4,4,4 },
        { 4,1,1,1,1,1,4 },
        { 4,1,1,0,1,1,4 },
        { 4,0,1,0,1,3,4 },
        { 4,3,3,3,3,2,4 },
        { 4,2,0,2,0,0,4 },
        { 4,4,4,4,4,4,4 },
    });

```

# Answer
Each time the player is going to move, save his current position, calculate his new position and determine the tile that he then would stand on. Check your tilemap and determine the type of that tile. If it is 4, don't make the player move.

Using that method, the player will be able to overlap a type-4-tile with half of his sprite. To avoid that, you can incorporate the dimension of the player collision rectangle into the calculation.
> 1 votes

---
Tags: c#, xna, 2d, tilemap
---


# Question
Title: Can I use popular classical music as my game's soundtrack?
Can I use popular classical music in my game as a soundtrack? I'm concerned about copyright protection. I don't plan to make money off of my game.

Will I break some law if I do that?

# Answer
## **No.**

*In most cases... also, I am not a lawyer, find one they help.*

Arrangements of, and recordings of, specific performances of classical music are both copyrighted separately. This means that even if a piece in its original form is in the public domain, the piece itself is still someone's active intellectual property.

## So, when can you use classical music?

*(Also, this list isn't exhaustive; get a lawyer, really.)*

* The piece needs to be in the public domain.
* You have to have the sheet music as it exists in the public domain. This usually means originals, but sometimes people release their later arrangements to the public. It's safer to have someone that can confirm that it is the public domain arrangement and not someone's later copyrighted work.
* You need to then perform & record the piece (yourself, or hire a band or orchestra to play the piece. Make sure you get the rights when you do this also)

Then there may be a few more things to consider. But when it comes down to it unless you are an awesome musician with a lot of time on your hands to find music that is in the clear (and have a lawyer to confirm that it is) you'd save a lot of money to just license music. If you are an awesome musician, you still save a lot of time by just licensing music.
> 33 votes

# Answer
Use a program like "Musescore" and copy the sheet music from classical music into the program. As long as the creator dead for 80 years. Should be ok if you've made your own version.
> 3 votes

# Answer
The copyright isn't on the notes of the musical work, it's on the *specific recording* that you will most likely run into issues with.

If you have a keyboard and play out Fur Elise and put that in your game, *nobody will go after you*. The musical score is in the public domain.

***But***, the musicians and recording company who produced a particular Beethoven recording must be paid for their production costs, as well as the fact that they sat and played the session -- as such you cannot just buy a copy of that recording and use it in your game -- you have to pay additional fees if you plan to use in something that will be further distributed.
> 2 votes

# Answer
Music goes under public domain automatically after 80 years unless specified by a certain agency - some themes and tunes cannot be copyrighted because of their widespread nature. The other thing about this particular law is that the recording of the music does not go into public domain for a lot longer. If you were to use a recording of music created in the 20's (and not continuously copyrighted) then that would be legal, but if the *recording* was from the 50's then you would be breaking the copyright law.

This is good knowledge to have because that means that you may record any performance that you put on if the music itself is in the public domain and there is nothing that anyone can do about it. If you can play a symphony that you have the music to then putting it in your game is just fine. Using the British Orchestra's 2007 recording of Bach is complete copyright infringement.

Be smart, play it safe, don't let something small hurt your game.
> 0 votes

# Answer
You cannot use particular recordings of songs, but you can usually use MIDI files, because they are usually in the public domain.

A MIDI file has no audio, it just has the notes of the song. But it will play like an audio file if you have a MIDI player.

Most old games from the 90s have MIDI players built-in, so you can probably add one to your game.
> -5 votes

---
Tags: legal, music, copyright
---


title: Opengl rotate around global axis

text:
# Question
Title: Opengl rotate around global axis
I want to create a game in which I rotate a cube around 2 fixed axes(x and y) using my mouse.

Here is what I want to do. Just use the mouse to see what kind of rotation I want.

I calculated my yaw and pitch values according to mouse movement and they work fine when I try to rotate only around one axis(x or y), but when I try to rotate around both axes it doesn't work(because OpenGL rotates axes when you apply a rotation). How do I make them both work at the same time? Here my code:

```
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;

float cameraDistance=3.0;

glm::vec3 center=glm::vec3(0.0f, 0.0f, 0.0f);
glm::vec3 cameraFront = glm::vec3(0.0f, 0.0f, -1.0f);
glm::vec3 cameraUp    = glm::vec3(0.0f, 1.0f,  0.0f);
glm::vec3 modelDistance= glm::vec3(0.0,0.0,3.0);

int oldX,oldY;
GLfloat yaw   = 0.0f; // Yaw is initialized to -90.0 degrees since a yaw of 0.0
                      // results in a direction vector pointing to the right (due
                      // to how Euler angles work) so we initially rotate a bit
                      // to the left.
GLfloat pitch =   0.0f;

while (running)
{
    oldX=sf::Mouse::getPosition(window).x;
    oldY=sf::Mouse::getPosition(window).y;

    yaw=oldX*0.1;
    pitch=oldY*0.1;

    projection = glm::perspective(45.0f, (GLfloat)WIDTH / (GLfloat)HEIGHT, 1.0f, 100.0f);

    view=glm::mat4();
    view = glm::lookAt(center+modelDistance, center+modelDistance + cameraFront, cameraUp);

    model= glm::mat4();

    //Here is the problem,how do i use both at the same time?
    model=glm::rotate(model,glm::radians(yaw),glm::vec3(0.0,1.0,0.0));
    model=glm::rotate(model,glm::radians(pitch),glm::vec3(1.0,0.0,0.0));
    //
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    ourShader.Use();

    GLint modelLoc = glGetUniformLocation(ourShader.Program, "model");
    GLint viewLoc = glGetUniformLocation(ourShader.Program, "view");
    GLint projLoc = glGetUniformLocation(ourShader.Program, "projection");

    glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
    glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
    glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));

    glBindVertexArray(VAO);
    glDrawArrays(GL_TRIANGLES, 0, 27*n*n);

```

# Answer
> 1 votes
You could do something like the following:

Instead of applying the delta rotation to the model matrix, try storing the total rotation, and create a new modelnmatrix each frame:

```
int yaw = 0;
int pitch = 0;

// ...

yaw += oldX * 0.1;  // Note the difference
pitch += oldY * 0.1;

model = glm::mat4(); // Set the matrix to identity each frame
model = glm::rotate(model, glm::radians(yaw), glm::vec3(0, 1, 0));
model = glm::rotate(model, glm::radians(pitch), glm::vec3(1, 0, 0));

```

# Answer
> 0 votes
In the example, the cube is rotating first around the z axis based on the x position of the mouse, then it's rotated around the x axis based on the y position of the mouse. When the mouse is in the upper left corner, there is no rotation, in the bottom left corner, there is 90 degrees of rotation around the x axis, and in the top right corner there is 90 degrees of rotation around the z axis.

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


# Question
Title: Implementation of A* Algorithm in a 3D Cube Array
I am working on making a program that finds the most efficient way to a goal from a starting point, with a few random debris set around. The entire thing is a 25x25x25 3d array of Cube objects, which are self explanatory. There are some random debris in random positions in the cube, along with a single block that acts as the goal.

I just want to know if a 3D implementation of the a\* algorithm is possible, because I haven't really seen anything on it.

# Answer
Yes, it is possible.

A\* is an algorithm that works on nodes.

* You code your own efficiency function.
* You supply the nodes and the network.

This means that the nodes can be 1d, 2d, 3d, 4d, or no d at all and use something else.
> 2 votes

---
Tags: 3d, algorithm
---


title: Expected numbers for user engagement

text:
# Question
Title: Expected numbers for user engagement
I run a free-to-play online game that involves collecting creatures and simply clicking on a button to give them a small amount of EXP. The idea is to do this for other people and they're likely to return the favour and help you make your own progress.

The initial tutorial guides you through the basic idea until you've successfully obtained a full Party of 6 before leaving you to your own devices, to make your own objectives and stuff.

I've noticed that players who make it through the tutorial tend to stay quite engaged with the game, but I also found these numbers:

* 25% of users join but never complete the first step of the tutorial, that is they never hatch their very first Egg.
* A further 25% of users drop out of the game before finishing the tutorial, so having hatched only 1-5 Eggs.
* Barely 50% of registered users actually complete the tutorial.

The problem is that I've never run this kind of game before. This is my first real project, but it's been going for several years now. I don't have any kind of baseline on what numbers to expect.

I can only imagine reasons right now, such as it being quite jarring to people that, in order to make progress, they have to help others make their progress and hope they return the favour.

So we have about half our users leaving before the tutorial is complete. Is this kind of thing normal? Am I worrying too much about this?

# Answer
> 17 votes
Without knowing the length and complexity of your tutorial, 50% is pretty damn good. considering 37% of registered games on steam have never been played even after users have purchased them.

This all depends on the type of game though, one would expect a cheap or f2p game to have very low retention rates compared to more expensive games. This means that 50% retention is fairly good for f2p.

However you might still want to look into making your tutorial more engaging if you want to make this retention even better. I'm guessing that your tutorial involves hatching a total of 6 eggs, which sounds pretty long to me. Maybe you should question whether you even need a tutorial or you could teach the player by playing the game. have a look at this fantastic video from Mark Brown for inspiration on how to hide your tutorial within your gameplay.

---
Tags: game-design, retention
---


# Question
Title: Array but with a name for every element (value)
Say I have 10 different types of grenades, I would like to create one variable, to allow me to set the number of grenades given from the inspector, I could create an array with 10 integers and set the number of grenades there, however it would be much easier for me if every element of the array (10 in total) had a name next to its value in the inspector so I could clearly see which grenade type am I assigning the value.

Is there any variable type or something that would allow me to do this? If so what is it? And how can I create what I want?

Thanks in advance!

If more information/ better explanation of some aspect is needed ask.

# Answer
There are multiple methods to deal with this.

1) You could create an enum with custom values that you could refer to:

`public enum Grenades { Standard = 5, Cluster = 10, }`

You can then refer to it by `int value = Grenades.Standard`

2) You could use a dictionary to store values:

```
Dictionary<string, int> grenades= new Dictionary<string, int>();
grenades.add("standard", 5);
grenades.add("cluster", 10)

int value = grenades["standard"];

```

Note: You may be better off building one script for grenades and possibly using prefabs for each of the values.

Link to dictionary info https://msdn.microsoft.com/en-us/library/xfhwa508(v=vs.110).aspx

Link to enum source https://msdn.microsoft.com/en-us/library/sbbt4032.aspx
> 5 votes

# Answer
It sounds like you want to associate a name with an inventory slot containing a count of grenades of that type, exposed so you can edit them in the Inspector.

In that case, I'd expand on Raeles's answer with a custom struct:

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

public class Inventory : MonoBehaviour {

   // Represents the different kinds of items we can carry.
   public enum ItemType {
       Empty, // First value is the default.
       Frag,
       Flashbang,
       Smoke,
       EMP    // (etc.)
   }

   // Represents an inventory slot containing some count of some item.
   [System.Serializable] // This makes the struct visible in the Inspector.
   public struct Slot {
       public ItemType type;
       public int count;
   }

   // Exposes a list of slots in the Inspector.
   public List<Slot> slots;
}

```

In the Unity Inspector, this gives you something like this:

Some things to note:

* Instead of an enum describing the item's type, your slot struct could instead hold a reference to the item's prefab, making it easy to spawn the right grenade when you want to throw it.
* If your struct's first member variable is a string, then that string will be displayed instead of the "Element 1" labels, which can make it easier to navigate the list, as long as you remember to keep the name in synch with the contents. (Sometimes I make a little Editor script that enforces this automatically, and then hide the name field so I can't mess it up)

(I don't recommend using string comparisons on the name to actually decide the item's gameplay, as this is error prone - you lose the built-in validation you get from an enumeration or prefab link)
* To make this even prettier, you can implement your own custom editor or property drawer to customize the interface for your inventory.
> 3 votes

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


title: OpenGL Water Waves Problem

text:
# Question
Title: OpenGL Water Waves Problem
I want to do a simple simulation of water drops producing waves in OpenGL with C/C++. I calculate height for each point of my plane grid in Vertex Shader with formula  but it seems wrong at the beginning. I will atach a photo to ease the understanding:

This is how the grid looks like at time = 0 (when the drop touched the water). The waves weren't generated only near the touch point and gradually advance. In the corners of the grid (and far from the touch point) there should be no change until a created wave approaches.

# Answer
> 1 votes
Try using a variable for amplitude (max height of wave). Pass it to shader. Vertex shader in your case. Multiply it to vertical component. (Some people use y-axis as vertical axis, while others use z-axis as vertical axis)

Initially set it to 0. When ball falls in fluid, set it to a value. And then multiply the that variable by constant less than 1 (for instance 0.97). Multiply it every frame. This will emulate decay.

Edit: for *'s stated goal "In the corners of the grid (and far from the touch point) there should be no change until a created wave approaches."*

Create a function such that

> if 0 \< r \< attenuation distance then
>
> Final height = amplitude variable (from above) * sqrt( power(x - ball.x,2) + power(y - ball.y,2)) / attenuation distance
>
> If r \> attenuation distance then height = 0

# Answer
> 1 votes
You could try to multiply the height by 0 outside the (increasing) radius of the 1st wave.

---
Tags: opengl, vertex, water
---


# Question
Title: How do I properly set criterias, when sending search requests in messaging system?
I'm designing a game engine in C++, and I ran into a problem with my messaging system.

The "`RequestData`, `ResultData`" system is very appealing to me, because I only have to create a `ResultData` object, call the send message method (calling functions in chain while request is not fulfilled), and then use the `ResultData` object.

For example, there is a `GameObjectResultData` object, which will store game object pointers which fulfill a criteria. This can be used to get one object, two objects, etc.

---

I have a `GameObjectRequestData`, which has the following members: 1. `int requestedNum`: the number of game objects to be found, so the request stops broadcasting after the right number is found. 2. `GameObjectResultData`: the resulting data objects pointer, in which the result will be stored.

I have to store the criteria in the request, without creating a lot of different `RequestData` classes. For examples, `IsNameEquals(string)`, `IsTagEquals(string)`, `IsInRangeOfPoint(point, range)`.

When the `RequestData` object arrives at a `GameObject` object, how do I check the criteria?

---

My current idea is to use a `SearchCriteria` abstract class and a `SearchCriteriaType` enum, which will both be stored in the `RequestData`. For example, I could use a `NameEqualsCriteria` class and a `NAME_EQUALS_CRITERIA` enum. In this case, when the `RequestData` arrives at `GameObject`, I check the enum value, and dynamically cast the `SearchCriteria` object to the corresponding class.

```
if(type == NAME_EQUALS_CRITERIA)
    dynamic_cast<NameEqualsCriteria>(SearchCriteria);
    // then, check criteria.

```

I think it should work, but I am not so experienced, so I am not sure. Is this a good practice?

---

I think there is an overhead on creating the new enum and class types. How do I set up the `RequestData.SearchCriteria` object, in the simplest form?

If I use the name criteria, I have to set a string; if I use the range criteria, I have to set a point and a range. My current solution is to pass the enum to the `RequestData` constructor, which will create a corresponding `SearchCriteria` object. Then, back where I called the constructor, I dynamically cast the `SearchCriteria` object to the corresponding class, and call its setters.

How do I properly set criterias, when sending search requests in messaging system?

# Answer
> 1 votes
I think this concept you're describing of building a query language mechanism to match targets of a message is a *bad* idea. It seems over-engineered and too generic to really suit the domain, especially given the processing overhead required to evaluate these abstract queries.

I think you should opt for a simpler approach.

Any message system can be placed into one of two buckets: a system where the *sender* identifies the recipients in some way, or a system where the *recipients* decide if they care about a message.

Your system appears to be basically in the former category: the sender fills out the criteria that must be true for an object to process the message. This means that the sender must, perforce, assume some things about the potential destination types -- that they have certain properties to be queried. In exchange for the downside of having to make this assumption, you have the upside of not having to duplicate "do I care about this message?" logic in different types of target game object.

Instead of trying to build an interpreted, scripted query language over your game objects, why don't you just perform the queries in your native programming language?

When the sender prepares a message, instead of building a query in a DSL, simply give the message a querying function that takes a `GameObject*` and returns a boolean value. So your message might look like:

```
struct Message {
  std::function<bool (GameObject*)> query;
  // ...other stuff...
};

```

When you "send" this message, you essentially do:

```
for (GameObject* object : allGameObjects) {
  if (message.query(object)) {
    object->handleMessage(message);
  }
}

```

(Instead of directly calling `handleMessage` you can store the matching objects in a `vector` or what have you for later processing, if you like.)

That way you can encapsulate any query you could write in C++ in your messaging system, and it will be significantly more natural to read or write, and significantly faster to execute, than any sort of DSL approach.

```
ExplodeMessage message;
message.query = [](GameObject* subject) {
  // any object whose name is "bomb" will process this message
  // and blow up
  return subject->GetName() == "bomb";
}

sendMessage(message);

```

Now you might argue that this approach requires you to make all the properties you might want to query against part of the public interface of the base game object, and that's true, but that's not fundamentally different from before. Before you were positing querying against properties that are *effectively* public since you have to know about (or assume) their existence to write the query operands. Now you're simply formalizing that assumption in a more naturally C++ fashion.

# Answer
> -1 votes
The most generic way to do it would be to store your criteria as strings, or hashed strings, define a set of comparison operators, and use a variant type.

```
Variant
  enum AvailableTypes
    TYPE_INT
    TYPE_FLOAT
    TYPE_STRING

  AvailableTypes mType;

  union {
    int;
    float;
    string;
  } mData;

enum Operator
  EQUAL
  GT
  LT
  GT_EQ
  LT_EQ

RequestData
  string mCriteriaParam;
  Operator mOp;
  Variant mOpParam;

GameObject
  map<string, Variant> mObjectData; // the key is the name of the parameter (tag,
                                    // currentHealth, name, maxHealth)

```

When the `RequestData` arrives at your `GameObject`, you search the mObjectData for the mCriteriaParam, use the operator and compare the mObjectData to the mOpParam.

This design looks generic, but might be inefficient. And this is effectively recoding a small subset of SQL.

---

There are a couple of ways to make variant types:

---

There are ways to organize your code to use either `std::string`s or integer values for keys in these `map`. You chose at compile time. If searching through strings makes your game slow, you could try switching to hashed-to-int versions of these.

---
Tags: c++, architecture, messaging
---


# Question
Title: Unity 2d wall jump/player control script
Been trying to get my player control working with a wall jump. I'm only getting errors from my rigidbody2D.velocity.y; the error states

> are you missing a using directive or an assembly reference.

My script is

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

public class PlayerController : MonoBehaviour
{

    public bool onGround = false;
    public bool jump = false;
    public float maxSpeedX = 3f;
    public float maxSpeedY = 3f;
    public LayerMask whatIsGround;
    public Transform groundChecker;

    private float groundRadius = 0.1f;
    private bool facingRight = true;
    public bool touchLeft = false;
    public bool touchRight = false;
    private CircleCollider2D circleCollider;

    public float velocityX;
    public float velocityY;

    void Start()
    {
        circleCollider = GetComponent<CircleCollider2D>();
    }

    void FixedUpdate()
    {
        float forceX = 0;
        float forceY = 0;

        //Je test si mon personnage est collé à un mur
        checkWallPosition();

        onGround = Physics2D.OverlapCircle(groundChecker.position, groundRadius, whatIsGround);
        float moveH = Input.GetAxisRaw("Horizontal");
        jump = Input.GetButtonDown("Jump");

        //Si je touche le sol
        if (onGround)
        {
            if (moveH != 0)
            {
                forceX = maxSpeedX * moveH;
            }
            if (jump && !touchLeft && !touchRight)
            {
                forceY = maxSpeedY;
            }
            else if (jump && (touchLeft || touchRight))
            {
                if (touchLeft)
                {
                    forceX = maxSpeedX;
                }
                else
                {
                    forceX = -maxSpeedX;
                }
                forceY = maxSpeedY;
                Flip();
            }
            else
            {
                forceY = GetComponent<Rigidbody2D>.velocityY;
            }
        }

        //Si je ne touche pas le sol
        else
        {
            if (!jump && !touchLeft && !touchRight)
            {
                forceY = rigidbody2D.velocity.y;
                forceX = rigidbody2D.velocity.x;
            }
            else if (jump && (touchLeft || touchRight))
            {
                if (touchLeft)
                {
                    forceX = maxSpeedX;
                    if (!facingRight)
                        Flip();
                }
                else
                {
                    forceX = -maxSpeedX;
                    if (facingRight)
                        Flip();
                }
                forceY = maxSpeedY;
            }
            else if (touchLeft || touchRight)
            {
                if (moveH == 0)
                {
                    forceX = 0;
                    forceY = rigidbody2D.velocity.y;
                }
                else
                {
                    if ((touchLeft && moveH == -1) || (touchRight && moveH == 1))
                    {
                        if (moveH == -1 && facingRight)
                        {
                            Flip();
                        }
                        if (moveH == 1 && !facingRight)
                        {
                            Flip();
                        }
                        forceY = rigidbody2D.velocity.y / 3;
                    }
                }
            }
        }

        //Ici les forces sont appliquées
        rigidbody2D.velocity = new Vector2(forceX, forceY);

        //Ici le personnage est retourné en fonction de sa position
        if (onGround)
        {
            if (moveH > 0 && !facingRight)
            {
                Flip();
            }
            else if (moveH < 0 && facingRight)
            {
                Flip();
            }
        }

    }

    private void Flip()
    {
        facingRight = !facingRight;
        Vector3 theScale = transform.localScale;
        theScale.x *= -1;
        transform.localScale = theScale;
    }

    private void checkWallPosition()
    {
        touchLeft = touchRight = false;
        float yCircle = transform.localPosition.y + (circleCollider.center.y * transform.localScale.y);
        Vector3 circlePosition = new Vector3(transform.localPosition.x, yCircle, transform.localPosition.z);
        bool hitRight = Physics2D.Raycast(circlePosition, transform.right, circleCollider.radius * transform.localScale.y + transform.localScale.y, 1 << LayerMask.NameToLayer("Walls"));
        bool hitLeft = Physics2D.Raycast(circlePosition, -transform.right, circleCollider.radius * transform.localScale.y + transform.localScale.y, 1 << LayerMask.NameToLayer("Walls"));
        if (hitRight)
        {
            touchRight = true;
        }
        if (hitLeft)
        {
            touchLeft = true;
        }
    }
}

```

# Answer
`GameObject.rigidbody` and `GameObject.rigidbody2d` have both been removed as of Unity 5.5.0p1.

```
Rigidbody2d rb = GetComponent<Rigidbody2D>();
forceY = rb.velocity.y;

```
> 1 votes

# Answer
This sometimes occurs and if all imports are correct. Try restarting unity editor usually that does the job with me
> 0 votes

---
Tags: unity
---