# Question
Title: How do I smooth out latency jitter in my netcode?
I'm developing a multiplayer game and I'm following some articles I've found online to create an authoritative client-server model.

Reading this article, Valve says that every time a message is received, the client assumes the "current" time is the time in the latest packet, in the article they state it:

> It is assumed in this paper that the client clock is directly synchronized to the server clock modulo the latency of the connection. In other words, the server sends the client, in each update, the value of the server's clock and the client adopts that value as its clock. Thus, the server and client clocks will always be matched, with the client running the same timing somewhat in the past (the amount in the past is equal to the client's current latency). Smoothing out discrepancies in the client clock can be solved in various ways.

And interpolation of remote entities:

> 1. Each update contains the server time stamp for when it was generated
> 2. From the current client time, the client computes a target time by subtracting the interpolation time delta (100 ms)
> 3. If the target time is in between the timestamp of the last update and the one before that, then those timestamps determine what fraction of the time gap has passed.
> 4. This fraction is used to interpolate any values (e.g., position and angles).

Now obviously due to jitter, my interpolation looks terrible as I will receive time + latency jitter. So my question is, is on this part: "Smoothing out discrepancies in the client clock can be solved in various ways."

What would be a good way to smooth out any discrepancies?

# Answer
Update: so this is the approach we decided to go for, both for the sake of testing our solution, and if it being a valid solution for future use of anyone else who might need it.

So instead of directly setting the time on the client when a remote packet is received:

1. we store the "debt time" between the client predicted time and the received time
2. If said debt time is higher than a certain treshold, we snap the time to the servers time and reset the debt (causes snap) and stop here
3. If not, then we smooth it out throughout several frames (by max 10% of a frame duration). This causes the entities to slow down and speed up on jitter, but it's very unnoticeable and gives us good results
> 4 votes

# Answer
In my implementation simulation on both client and server is running in discrete "ticks", so I can always slow down client, so it is few ticks behind the currently arriving data according to jitter average, so unless there is "lag spike", the simulation is smooth.
> 0 votes

# Answer
Gaffer on Games, an experienced authority on online multiplayer games, recommends having the clients show one or two ticks behind the server's state.

When the client receives state 100, for example, it starts interpolating from the state it already has (state 99) and state 100 such that it should reach state 100 at the same time that it receives state 101 from the server. The server sends state updates at a fixed rate, so this is predictable, but it does inherently introduce a small bit of extra latency (based on the update rate).

If you want to cover up the occasional lost packet, have the client show two states behind the server. For example, when it receives state 100 it starts interpolating from state 98 to 99, such that it should be showing state 99 when state 101 is received. If state 101 doesn't come through (due to a lost packet), it continues interpolating between 99 and 100, anticipating 102 to come through next. When state 102 comes through, it can interpolate between states 100 and 102 over two update cycles, and the player should be none the wiser. This, of course, doubles that extra latency, but with a high enough update rate, is not a problem.

---

*Edit to better answer your question according to your comment. I've kept the previous part as it informs the example in the latter part:*

Where you have network jitter, my suggestion is that when updates come later than expected (or two in a row do, if you use the two-cycle smoothing described above), they set the new expectation for latency. When packets come sooner than expected, instead of jumping ahead in time, store those states in a buffer and continue catching up at a consistent rate, assuming that packets may still come through with as much latency as your worst case thus far. Of course, you wouldn't want an unlucky spike in latency to add artificial lag to the rest of the session, so as packets continue to come in sooner than expected, slowly bring that simulation lag down to catch up with the server, perhaps with a buffer if the incoming states vary quite a bit in timing.

As an example, you might expect an update rate of 20 updates a second. That's an update every 50ms. If update 100 comes through slower than expected and you aren't using an extra update cycle of smoothing, you're forced to wait for it. But once it does come through, you interpolate between state 99 and 100 such that you should reach state 100 in 50ms. In that time, since you have all that network jitter, state 101 and 102 arrive. But instead of jumping ahead to them, you store them, consistently taking 50ms to move from one state to another. As you continue to sit a few states behind what you've received, you decide to play catch up and start moving from one state to another in only 49ms (or even less), subtly bringing the player forward in time to enjoy the improved latency their connection has been having without any abrupt changes in simulation speed.

In anticipation of further inconsistencies, you may want to remember the worst delay you've had in the last x number of seconds and stop catching up when you reach that delay again (that is, return to 50ms between each state of you're expecting 20 updates per second).

With a two cycle delay, you can ignore one-off delays, and need only remember the best of two consecutive delayed states in the last x seconds. It could be worth switching between a single cycle delay and two cycle delay depending on the quality of the connection.

I hope that's helpful, and if not, hopefully someone with experience in that area can correct me and teach us both!
> 0 votes

---
Tags: networking, client-server
---


# Question
Title: How the game sends force feedback to the steering wheel
How the game will be some of the information feedback to the steering wheel, such as bumps, bumps, vibration and so on. View MSDN, which are introduced from the steering wheel to get the relevant information and control the steering wheel of the force feedback, but how to get from the game inside the type of force feedback?

# Answer
> how to get from the game inside the type of force feedback

This is a game design question.

Once you know what feedback features are available for the controller in use, whether it is a game controller with a rumble pack, or a steering wheel with force feedback, you need to decide what you will do with it.

What will you transfer from the game universe back to the players hands?

Depending on the answer, you'll add some code that will map in-game events to controller feedback events.

For instance, if you want to make the steering wheel harder to manipulate (increasing the force feedback), you can try and detect the following events in your game:

* Powersteering failure (this will be an event that you'll decide to generate)
* The player is taking a sharp turn at a high velocity (you can inspect the current requested steering angle, along with the current linear velocity of the vehicle; combine these to find how hard will it be to steer).

Or if you have a controller with a rumble pack, and you want to detect the bumps, you'll have to inspect the vertical velocity of the wheels: if it gets above a certain threshold, you send a short rumble signal to the controller.

In any case, it will require the programmer and the designer to work together: one to implement the feature, and the other to tune it.

There is no magic to it: plan, code, tune. And there is more than one way to achieve what you need. This will depend on your game and your engine.
> 1 votes

---
Tags: game-design, controllers
---


title: 3D Illusion of a 2D Planet Texture

text:
# Question
Title: 3D Illusion of a 2D Planet Texture
Several years ago I overheard a technique that gives the user the illusion of a rotating planet by using a 2D texture. Given that the user isn't able to change its position or viewport.

What's the name of this technique?

# Answer
*OK I think I have the rep now. Contents of previous post with images embedded. Is this the rotating planet effect you're looking for? Its simply a scrolling 2D image viewed through a semi-transparent "hole" in the star field.*

I put together a quick little animated gif of what the effect would look like. Clearly it could be animated a lot smoother - I shifted the planet surface by 4 pixels each frame. It's also not set to wrap the image so there's a glitch at the end of the loop.

planet http://www.perludus.com/orbit.gif

I did do this all in Photoshop, but the concept should work in a 2D rendering environment that lets you do alpha transparencies, etc. Here are a series of screenshots showing the process...

1. Create a blank star background, and cut a round hole in it.
2. Find a grayscale shaded sphere for your planet, like this one
3. Here is our stars with hole and the shaded sphere on top, semi transparent
4. Make a blue circle the size of the hole, and give it an outer blue glow. Also set it to be semi-transparent. Here's what it looks like with the shaded sphere
5. Now find a planet surface texture. I found this one just googling "planet surface texture"
6. Place the planet texture UNDER the star image with the semi-transparent hole in it to get this look

To animate your planet's surface, just move the underlying planet surface texture. You'll have to get clever about shifting the texture when it reaches the edge to get a seamless and endless rotation.

Hope this helps and is the effect you were looking for!

PS Saw this article about artists with a rather novel way to create planet textures - made me think of this answer :) http://www.behance.net/gallery/Pan-Planets/9557465
> 26 votes

# Answer
im going to guess at what you mean, and just throw an idea out there, but it's certaintly not going to be the 'famous' way to do it.

all in 2D

take 2 textures. one your land mass, the other your clouds. clouds should have a alpha layer that matches so you can 'see thru them'.

make the textures tileable, that is they seamless wrap. there are programs that help you make these or tutorials in photoshop you can follow.

then finally you make a stencil mask that is just a circle, so you are in effect looking thru a round hole at your square textures, thus masking off the corners.

now you animate the texture matrixes of the land and cloud textures to make them move. make them move in different directions and speeds and it will appear to be rotating. it all depends on how seamless you made your textures.
> 3 votes

# Answer
I think this article describes the technique. (It is in Russian, so I post translated link.)

https://translate.googleusercontent.com/translate\_c?depth=1&hl=en&rurl=translate.google.com&sl=auto&sp=nmt4&tl=en&u=https://habrahabr.ru/post/248381/&usg=ALkJrhgViuYdAi-Vav3cyhxvydkaBKh6EQ

I've implemented it here. http://github.com/meric/renderplanet

Basically you take an image that encodes the orthographic projection (http://mathworld.wolfram.com/OrthographicProjection.html) and wrap your planet and cloud texture around it using a shader. Offset the planet texture according to dt to make it rotate. Use an prepared translucent image for the atmosphere ring and shadow, or generate it by drawing translucent arcs and some experimenting with the shader for the shadow.

Here is the image:

For each pixel within the circle, `Red + Green/255` is normalised X coordinate of planet/cloud texture to lookup and `Blue + Alpha/255` is normalised Y coordinate.

Here is the result:

The planet and cloud textures should be in equirectangular projection.
> 2 votes

# Answer
Your question is unclear as to the restrictions on context you're working in. The vast majority of textures in 3D rendering are 2D. So if you're just showing a 3D sphere with a 2D surface texture mapped around it, this isn't really a problem. If you can't use 3D rendering, then you have to say exactly what you can use.

The basic issue is that you have to render a flat texture over the surface of a sphere, which you get for free with 3D rendering. As the planet rotates, the visible portions of the planet's surface animate in a non linear way (the equatorial parts of the texture move faster than the poles). So I think either you have to distort the image yourself as you map it over the disc, or you do as VirtualVoid suggested, and simply have multiple images which you change between over time.

It would be horrible to implement, but if you are able to render the texture, pixel by pixel, then you could basically do the rasterisation calculations for each line of the sphere separately. Let's assume that your surface map texture is flattened out, so that at the equator there are 512px of image. Let's also assume your visible disc is 256 px wide. Now think of each line of the rendered disc as a sliding window on the surface texture. On the equator, the window is 50% of the texture width, and you simply copy each of the 256px onto the equivalent pixel on the disc. The next line down on the disc will be slightly less than 256 px, but because of the distorted surface map, there are still 256px of input surface map data. So you then sub-sample the input surface map data, and render out the resulting pixel. For easy maths, let's assume that 1/3 of the way between the equator and the pole is 128px wide in the output disc. So each of those 128px is going to be the average of 2 neighbouring pixels. When you get down to the pole, you'd be averaging all 256px into only a few output pixels.

You could also do it the other way, and have the lines in the source texture be of different lengths. So while the line containing the source data has 512px in it, the line 1/3 of the way down has only 256px, and the line at the bottom has only a few pixels. But each line is double the width of the disc at the equivalent y coordinate. That sort of a texture would be absolutely horrible to have to create though. And would probably suffer from horrible aliasing issues.

In both of those cases your animation is simply then incrementing the start pixel x in the input texture, and wrapping around to the start of the input texture line.

The more I write about this now, the more I'm convinced that it's a horrible idea, that you'd only implement if you really had absolutely no other choices. And you'd have to be in a very unusual situation to have no other choices.

I don't believe I've heard of any solutions to this (rather vague) problem as a specific named technique.
> 1 votes

# Answer
That might be just a simple animation, using one texture with several frames.
> 0 votes

# Answer
Sprites. It sounds like what you're describing is a 2D sprite in a 3D game engine to render cheaply (the Nintendo64 did this all over the place, as did many early 3d engines).

If you wanted to render a planet rotating, you'd just have to display a 2D sprite that was animated based on a sprite sheet that was a pre-rendered planet rotation. Just like, an animated .GIF for instance. The problem is that it would be pre-rendered, so as you said, this only works if the user isn't allowed to manipulate the view angle.

http://en.wikipedia.org/wiki/Sprite\_(computer\_graphics)
> 0 votes

---
Tags: 2d, 3d, terminology, planet
---


title: minimax AI code stuck in a loop

text:
# Question
Title: minimax AI code stuck in a loop
Disclaimer: First time trying to implement a AI using minimax approach (its a turn-based game). There are not many good resources available online to learn AI (specifically minimax in C#) so I am pretty sure I messed up somewhere as I was rewriting a example I found online.

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

public class GameController : MonoBehaviour {

    public const int tilesX = 14;
    public const int tilesY = 9;
    public int[,] board;

    public GameObject redObject;
    public GameObject blueObject;

    public int currentPlayer = 1;

    //For AI
    public const int maxDepth = 7;
    public const int orangeWins = 1000000;
    public const int yellowWins = -orangeWins;
    public Board aiBoard;
    public int scoreOrig;

    // Use this for initialization
    void Start () {
        board = new int[tilesY, tilesX];
        aiBoard = new Board();              //AI
        scoreOrig = ScoreBoard(aiBoard); //AI

    }

    // Update is called once per frame
    void Update()
    {
        if (getWinner() != 0)
        {
            return;
            //Game Over
        }
        if (Input.GetButtonDown("Fire1"))
        {
            //Translate mousePosition from screenSize to actual gameViewUnits
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            //Run below function only if mouseClick's X/Y are within tileGrid
            mousePressed(ray);
        }
    }

    void mousePressed(Ray ray)
    {
        Vector2 mouseClickVector = new Vector2(ray.origin.x,ray.origin.y);
        int mouseClickX = (int) mouseClickVector.x;
        //Debug.Log(mouseClickX);
        int y = findNextSpace(mouseClickX);
        //Debug.Log("Y: "+y);
        if (y>=0)
        {
            board[y,mouseClickX] = currentPlayer;
            dropDisk(aiBoard, mouseClickX, Mycell.Orange);   //AI
            //Spawn and animate the circleObject
            spawnPlayerObject(mouseClickX, y);

            //End and change turn
            changeTurn();
        }

    }

    int findNextSpace(int x)
    {
        for(int y=0; y<= tilesY - 1; y++)
        {

            if(board[y,x]==0)
            {
                return y;
            }
        }
        return -1;
    }

    void spawnPlayerObject(int x, int y)
    {
        float posX = (float) x + 0.5f; //center in x tile
        float posY = (float)y + 0.5f; //center in y tile
        GameObject g;
        if(currentPlayer==1)
        {
            g = Instantiate(redObject, new Vector3(posX, posY, 0), Quaternion.identity);
        }
        else
        {
            g = Instantiate(blueObject, new Vector3(posX, posY, 0), Quaternion.identity);
        }
    }

    void changeTurn()
    {
        currentPlayer = currentPlayer == 1 ? 2 : 1;
        //check winner
        getWinner();

        int move, score;
        abMinimax(true, Mycell.Orange, maxDepth, aiBoard, out move, out score);
        Debug.Log("Move: "+move+" | Score: "+score);
        Debug.Log(aiBoard);
    }

    int getWinner()    //From rows,columns and diagnoals
    {
        ////////////
        //Columns///
        ///////////
        for(int y=0; y<tilesY; y++)
        {
            for (int x=0; x<tilesX; x++)
            {
                if (checkTile(y,x)!=0 && checkTile(y, x) ==checkTile(y, x+1) && checkTile(y, x) == checkTile(y, x+2) && checkTile(y, x) == checkTile(y, x+3))
                {
                    Debug.Log("Won Columns: "+ checkTile(y, x));
                    return checkTile(y, x);
                }
            }
        }
        ////////
        //Rows//
        ////////
        for (int y = 0; y < tilesY; y++)
        {
            for (int x = 0; x < tilesX; x++)
            {
                if (checkTile(y, x) != 0 && checkTile(y, x) == checkTile(y+1, x) && checkTile(y, x) == checkTile(y+2, x) && checkTile(y, x) == checkTile(y+3, x))
                {
                    Debug.Log("Won Rows: " + checkTile(y, x));
                    return checkTile(y, x);
                }
            }
        }
        /////////////
        //Diagnoals//
        /////////////
        for (int y = 0; y < tilesY; y++)
        {
            for (int x = 0; x < tilesX; x++)
            {
                for (int d = -1; d <= 1; d += 2)
                {
                    if (checkTile(y, x) != 0 && checkTile(y, x) == checkTile(y + 1 * d, x+1) && checkTile(y, x) == checkTile(y + 2 *d, x+2) && checkTile(y, x) == checkTile(y + 3 *d, x+3))
                    {
                        Debug.Log("Won Diagnoals: " + checkTile(y, x));
                        return checkTile(y, x);
                    }
                }
            }
        }
        ///////////////////////////
        //Still possible turns/////
        //////////////////////////
        for (int y = 0; y < tilesY; y++)
        {
            for (int x = 0; x < tilesX; x++)
            {
                if (checkTile(y, x) == 0)
                {
                    //Debug.Log("Still Possible turns left");
                    return 0;
                }
            }
        }

        //draw is default
        return -1;
    }

    int checkTile(int y, int x)
    {
        return (y < 0 || x < 0 || y >= tilesY || x >= tilesX) ? 0 : board[y, x];
    }

    ////////////////
    //////AI///////
    ///////////////

    public static bool g_debug = true;

    public enum Mycell
    {
        Orange = 1,
        Yellow = -1,
        Barren = 0
    };

    public class Board
    {
        // Initially, this was Mycell[,]
        // Unfortunately, C# 2D arrays are a lot slower
        // than simple arrays of arrays (Jagged arrays): Mycell[][]
        // BUT
        // using a 1D array is EVEN faster:
        //    _slots[width*Y + X]
        // is much faster than
        //    _slots[Y][X]
        //
        // (sigh) Oh well, C# is a VM-based language (specifically, .NET).
        // Running fast is not the primary concern in VMs...
        public Mycell[] _slots;
        public Board()
        {
            _slots = new Mycell[tilesY * tilesX];   //height * width
        }
    };

    public static int dropDisk(Board board, int column, Mycell color)
    {
        for (int y = tilesY - 1; y >= 0; y--)
            if (board._slots[tilesX * (y) + column] == Mycell.Barren)
            {
                board._slots[tilesX * (y) + column] = color;
                return y;
            }
        return -1;
    }

    public static int ScoreBoard(Board board)
    {
        int[] counters = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };

        // Horizontal spans
        for (int y = 0; y < tilesY; y++)
        {
            int score = (int)board._slots[tilesX * (y) + 0] + (int)board._slots[tilesX * (y) + 1] + (int)board._slots[tilesX * (y) + 2];
            for (int x = 3; x < tilesX; x++)
            {
                score += (int)board._slots[tilesX * (y) + x];
                counters[score + 4]++;
                score -= (int)board._slots[tilesX * (y) + x - 3];
            }
        }
        // Vertical spans
        for (int x = 0; x < tilesX; x++)
        {
            int score = (int)board._slots[tilesX * (0) + x] + (int)board._slots[tilesX * (1) + x] + (int)board._slots[tilesX * (2) + x];
            for (int y = 3; y < tilesY; y++)
            {
                score += (int)board._slots[tilesX * (y) + x];
                counters[score + 4]++;
                score -= (int)board._slots[tilesX * (y - 3) + x];
            }
        }
        // Down-right (and up-left) diagonals
        for (int y = 0; y < tilesY - 3; y++)
        {
            for (int x = 0; x < tilesX - 3; x++)
            {
                int score = 0;
                for (int ofs = 0; ofs < 4; ofs++)
                {
                    int yy = y + ofs;
                    int xx = x + ofs;
                    score += (int)board._slots[tilesX * (yy) + xx];
                }
                counters[score + 4]++;
            }
        }
        // up-right (and down-left) diagonals
        for (int y = 3; y < tilesY; y++)
        {
            for (int x = 0; x < tilesX - 3; x++)
            {
                int score = 0;
                for (int ofs = 0; ofs < 4; ofs++)
                {
                    int yy = y - ofs;
                    int xx = x + ofs;
                    score += (int)board._slots[tilesX * (yy) + xx];
                }
                counters[score + 4]++;
            }
        }

        if (counters[0] != 0)
            return yellowWins;
        else if (counters[8] != 0)
            return orangeWins;
        else
            return
                counters[5] + 2 * counters[6] + 5 * counters[7] -
                counters[3] - 2 * counters[2] - 5 * counters[1];
    }
    //End Scoreboard

    public static void abMinimax(bool maximizeOrMinimize, Mycell color, int depth, Board board, out int move, out int score)
    {
        if (0 == depth)
        {
            move = -1;
            score = ScoreBoard(board);
        }
        else
        {
            int bestScore = maximizeOrMinimize ? -10000000 : 10000000;
            int bestMove = -1;
            for (int column = 0; column < tilesX; column++)
            {
                if (board._slots[tilesX * (0) + column] != Mycell.Barren)
                    continue;
                int rowFilled = dropDisk(board, column, color);
                if (rowFilled == -1)
                    continue;
                int s = ScoreBoard(board);
                if (s == (maximizeOrMinimize ? orangeWins : yellowWins))
                {
                    bestMove = column;
                    bestScore = s;
                    board._slots[tilesX * (rowFilled) + column] = Mycell.Barren;
                    break;
                }
                int moveInner, scoreInner;
                if (depth > 1)
                    abMinimax(!maximizeOrMinimize, color == Mycell.Orange ? Mycell.Yellow : Mycell.Orange, depth - 1, board, out moveInner, out scoreInner);
                else
                {
                    moveInner = -1;
                    scoreInner = s;
                }
                board._slots[tilesX * (rowFilled) + column] = Mycell.Barren;
                /* when loss is certain, avoid forfeiting the match, by shifting scores by depth... */
                if (scoreInner == orangeWins || scoreInner == yellowWins)
                    scoreInner -= depth * (int)color;
                if (depth == maxDepth && g_debug)
                    Debug.Log("Depth: " + depth+", placing on: " + column+", score: " + scoreInner);
                if (maximizeOrMinimize)
                {
                    if (scoreInner >= bestScore)
                    {
                        bestScore = scoreInner;
                        bestMove = column;
                    }
                }
                else
                {
                    if (scoreInner <= bestScore)
                    {
                        bestScore = scoreInner;
                        bestMove = column;
                    }
                }
            }
            move = bestMove;
            score = bestScore;
        }
    }
    //End abMiniMax

}

```

Pretty sure its stuck in `abMinimax` function.
And yes, its a Connect 4 (Four in a Row).

# Answer
> 1 votes
First of all I will try to mention some frequently found mistakes in your code, because they really disturb from reading:

1. No abstractions at all. Try to use `OOP` and encapsulate some logic to other classes, because right now your `GameController` is just `EverythingGuy` (for example, you can split AI logic from whole game, then split game lifecycle (*start*, *update* ...) from turn-based logic).
2. Code style: hardcode, no empty lines to show logic structure of code, not the best naming and so on. If you want to be good at it, try to read **Steven Mcconnell "Code Complete"** (the aesthetics part).

**To the point:** I've tried to compile this thing in my head, but it worked, so I've debugged the code and found that the problem is surely in `abMinimax` method. So...

In `abMinimax` you have a cycle with `13` iterations. And you also have a `depth`, which initial value equals to `7`. So in pseudocode the complexity of method `abMinimax` looks like:

```
for every x from 0 to 12
    if ( depth > 1 )
        abMinimax( depth - 1 );

```

I can say, that you have kinda `4826809 (13 * 13 * 13 * 13 * 13 * 13)` iterations in that cycle. Maybe this is too much. I can prove it by lowering the whole `tileX` value from `13` to `4` so the program will finish and there is no infinite cycle in it. For example, if we take `6` instead of `13` the program will execute in a few seconds. You can extrapolate and...

Hope this will help you!

---
Tags: unity, c#, algorithm, ai
---


title: Pattern for collision handling?

text:
# Question
Title: Pattern for collision handling?
I am writing a game with Java. There are many different kinds of entities on the screen, like the player, NPCs, monsters, bullets, items, shiftable blocks and so on.

This question is not about collision detection, but about collision handling. If two entities collide, it depends on their type what should happen. Some examples:

* If the player and a monster collide, the player should loose a life.
* If a monster and a bullet collide, the monster should die.
* If the player and an NPC collide, a dialog should start.
* If the player and an item collide, the player should pick it up.

Now this could be done like this:

```
public void checkCollision() {
   for (Entity a: entities) {
      for (Entity b: entities) {
         if (collision(a,b)) {
            if (a instanceof Player && b instanceof Monster) a.loseLife();
            if (a instanceof Player && b instanceof Item) a.pickUp(b);
            ...
         }
      }
   }
}

```

But I heard that `instanceof` should not be used for this purpose. So I wonder what is the best way to handle the collision of the different combinations? I heard about the visitor pattern, but this would require me to change the classes of the entities and handle the collision there, what seems very wrong to me.

# Answer
> 4 votes
Well, as some kind of solution I may suggest that in your case you should use something called **Double Dispatch**: the pattern **Visitor** actually.

Let's look at your example briefly:

1. If the **player** and a **monster** collide, the player should loose a life.
2. If a **monster** and a **bullet** collide, the monster should die.
3. If the **player** and an **NPC** collide, a dialog should start.
4. If the **player** and an **item** collide, the player should pick it up.

The code can be like this:

```
public interface ICollideable
{
    void resolveCollision( ICollideable collideable );

    void resolveCollision( Monster monster );
    void resolveCollision( Npc npc );
    void resolveCollision( Player npc );
    void resolveCollision( Item npc );
    void resolveCollision( Bullet npc );
}

public class Entity implements ICollideable
{
    public abstract void resolveCollision( ICollideable collideable );

    // virtual methods.
    public void resolveCollision( Monster monster ) { }
    public void resolveCollision( Npc npc ) { }
    public void resolveCollision( Player npc ) { }
    public void resolveCollision( Item npc ) { }
    public void resolveCollision( Bullet npc ) { }
}

public class Player extends Entity
{
    @Override
    public void resolveCollision( ICollideable collideable )
    {
        collideable.ResolveCollision( this );
    }

    @Override
    public void resolveCollision( Monster monster )
    {
        this.health -= monster.getDamage();
    }

    @Override
    public void resolveCollision( Item item )
    {
        this.inventory.addItem( item );
    }

    @Override
    public void resolveCollision( Npc npc )
    {
        NavigationManager.openQuestListUI( this, npc );
    }
}

public class Monster extends Entity
{
    @Override
    public void resolveCollision( ICollideable collideable )
    {
        collideable.ResolveCollision( this );
    }

    @Override
    public void resolveCollision( Bullet bullet )
    {
        this.die();
    }
}

```

Sorry, there may be some mistakes, because I'm not really good with java syntax. Such approach is useful if your language supports methods overloading (like java or c#).

*P.S. You can extend the example and implement both reactions of player and monster (remove health from player and monster on interaction).*

Links:

1. https://en.wikipedia.org/wiki/Visitor\_pattern
2. https://sourcemaking.com/design\_patterns/visitor/java/2

**Update 1.**

There are of course some alternatives floating around, however they are more about whole-game-architect patterns. I will try shortly discuss them:

1. **Entity Component Systems (ECS)**

In ECS-like code you want to move far away from holistic classes and objects, so you split the whole state and behaviour into three parts:

a) `Component` \- the pure data. For example `Position` is just a `Component` with `X`, `Y` and `Z` (depends on business-logic ofc).

b) `Entity` \- just an ID with which you can associate a set of components with no intersections in types (no way to get two `Position` in one `Entity` at all).

c) `System` \- static "*whole-universe*" things, that can handle `Entities` with specified set of `Components`. Good example - `GravitySystem`. It takes all the `Entities` with `Position`, `Mass` and changes their `Velocity`. Then `MovementSystem` or `VelocitySystem` then process the velocity and turn it into change of `Position`.

This is just a starting explanation. There are a lot of questions about `ECS` with nice answers. You can find them by tag `entity-system`.

2. **Dynamic message-passing (event-passing)**

For example, instead of calling `resolveCollision` method, you pass the message (like `CollisionWithAnotherEntityOccured`) to whole `Entity`. It then will use something called `MessageBus` to re-transfer the message to all interested `Components`. Maybe there will be `AttackerModule` with code:

```
public void onCollision( CollisionWithAnotherEntityOccured message )
{
    var weapon = GetComponent<Weapon>(); // Unity-style.
    message.Entity.Pass( new AttackMessage( weapon.getDamage() ) );
}

```

The responsibility to handle `AttackMessage` is now on attacked entity, and if and only if it has `HealthComponent` with `AttackReceiver` you can perform a success attack.

This is of course simplified example to demonstrate some powers of such decoupling. It is greatly used in `SQRS`-pattern.

I hope this additional explanation will help you to choose some way to deal with your current and future problems.

---
Tags: java, architecture, collision-resolution, design-patterns
---


# Question
Title: Need help with getting a direction vector between two given points
I need to find the angle of rotation from a bullet traveling from point A to point B, like in my attached diagram. I tried searching, but I got a little lost in which exact formula to use.

I want to find the direction of a bullet, expressed as a vector with X and Y coordinates.

# Answer
> 5 votes
In your situation you need a simple subtraction, with a normalization.

```
vectDistance = B - A
vectDirection = vectDistance / lenght(vectDistance)

```

This will give you the direction.

In LibGDX, you can use the `sub` method from the `Vector2` class, along with the `nor` from the same class:

```
vectDirection = b.sub(a).nor();

```

---

To help figure out if you need to subtract A from B or B from A, try to translate (in your mind) the 'origin' to (0, 0), and move the 'target' along with it. From that perspective, the "direction" should be taken from the position of the 'target'.

Another clue that will make you notice that you used the wrong order: the bullets will fly in the opposite direction of what you're expecting ;P

# Answer
> 0 votes
OK thanks to the help of this community (above) Here is actually how I implemented it:

```
  public Bullet(Texture texture, Vector2 startPosition, Vector2 targetPosition){
    super(texture);
    setSize(0.1f,1f);
    setPosition(startPosition.x, startPosition.y);

    direction = targetPosition.sub(startPosition);
    direction.nor();
    System.out.println("direction " + direction.x + "," + direction.y);

}

public void update(float delta){
    setPosition(getX() + (direction.x * speed), getY() + (direction.y * speed));
}

```

This works with the player character standing near the middle of the screen, it will fire bullet anywhere around him that I press. Thanks

---
Tags: libgdx, vector, linear-algebra
---


# Question
Title: Generate random people with demographics
I would like to have random people with preferences generated for an economic strategy game. For simplicity, lets say each person has age(number), home area and its type (city,village,...) and preferences(likes ice cream,..).
The problem is, if I used uniform random generation(choose random age, home, and preference) all people would be ...uniformly distributed and there would be no demographics for player to discover. By features I mean, for example, young people like soda, in addition people living in village tend to prefer red colored packaging (=\> player shipping it with different packaging to country will sell more). I would like to have the people generated so that there are always some distinctive demographic features(which does not have to be known to the game itself) present in the data.
The features does not have to and should not resemble real-world ones, the algorithm should work without requiring any 3rd party databases. Homes for people are given as input from previous generation step as array of tuples of settlement id and capacity (thus also type).
What could be general procedure for this type of procedural generation?

# Answer
Generate your demographics with weighted random distribution. Before generating the statistics for any individual people, decide the weighted statistics for your groups (i.e. age groups, location, etc.). Then, when generating a person, get their group information first (either randomly or some other method for assigning people to groups). Then use an individual's group information to weight the statistics of their preferences.

Alternatively, you can generate the people in phases. Generate everything randomly, then over multiple iterations, change people's preferences to gravitate towards uniformity. For example, if in region A, young people that say "soda" instead of "pop" is slightly higher, over multiple iterations that lead would increase, and eventually "soda" would be the dominate phrase used to refer to sugar water.

You can even take this a step further and allow surrounding areas to provide influence depending on the uniformity of their preference. For example, if in your iterations it happens that a vast majority of people have one preference over another, that influence can spread to surrounding areas.

Imagine you have an attribute that has two choices, soda or pop. If you were to visualize this information with your location data on a grid with black and white, it would look like white noise. Totally random. Now you start what is essentially a cellular automaton. Attributes will change depending on the frequency of the attributes around them. For example, a soda choice, surrounded by 3 pop choices changes itself to pop. After multiple iterations you'll start to get localized regions where each choice is soda or pop. Those regions will grow and eventually your white noise is turned into islands of black and white. With more choices, it might looks somewhat like this video someone created of a Pokémon battle (more here on that experiment).
> 5 votes

# Answer
You seem to have a bunch of visible attributes which themselves don't actually have a gameplay effect (age, location...) but offer a hint for the invisible, gameplay-related attributes (their preferences).

What you can do is randomly generate the visible attributes first and then when generate the gameplay-related attributes, bias them depending on the visible attributes.

For example, the formula for sweetness-preference could be `random(0, 100) - random(0, age)`. This makes a senior who likes sweets less likely than a child who likes sweets.

---

Another option would be to define a couple of character stereotypes (child, elderly man, businesswoman, hipster, punk...) and assign default values for them.

When you create a new character, pick a stereotype. Then, when you roll for the character attributes, roll multiple random numbers and pick the value which is closest to the default value of the stereotype for that attribute. That way the majority of your characters will tend to conform to their stereotype, but there can and will be outliers. The more rolls you make, the less outliers you will have.

When having a set of predetermined stereotypes is not procedural enough for you, you could even randomly-generate the set of stereotypes and their default attributes. Your players will then still be able to spot correlations between characters based on the same randomized stereotype. For example, people who like soda also like red packing, because (unknown to the player) there is a stereotype which happens to have both a high default soda preference and a high default red preference and they all originate from it.
> 3 votes

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


title: Text in game with not english alphabet

text:
# Question
Title: Text in game with not english alphabet
I need to render some special text in my game. Currently I can render any text that use classic letters of english alphabet, but I have some problems with special alphabets.

**How do I render text:** I am using a simple program called Hiero that makes bitmap form fonts. It looks like this.

It also generates a file with some informations about font (positioning)

```
info face "Verdana" size 23 bold 0 italic 0 charset "" unicode 0 stretchH 100 smooth 1 aa 1 padding 3,3,3,3 spacing 0,0
common lineHeight 35 base 24 scaleW 256 scaleH 256 pages 1 packed 0
page id 0 file "VerdanaDIA.png"
chars count 123
char id 32   x 0     y 0     width 0     height 0     xoffset 0     yoffset 24    xadvance 14     page 0  chnl 0
char id 253   x 0     y 0     width 19     height 32     xoffset -2     yoffset 1    xadvance 20     page 0  chnl 0
char id 381   x 19     y 0     width 22     height 31     xoffset -2     yoffset -3    xadvance 22     page 0  chnl 0
char id 221   x 41     y 0     width 21     height 31     xoffset -3     yoffset -3    xadvance 20     page 0  chnl 0
char id 218   x 62     y 0     width 21     height 31     xoffset -1     yoffset -3    xadvance 23     page 0  chnl 0
char id 356   x 83     y 0     width 22     height 31     xoffset -3     yoffset -3    xadvance 20     page 0  chnl 0
char id 352   x 105     y 0     width 20     height 31     xoffset -1     yoffset -3    xadvance 22     page 0  chnl 0
char id 344   x 125     y 0     width 21     height 31     xoffset -1     yoffset -3    xadvance 22     page 0  chnl 0
char id 211   x 146     y 0     width 24     height 31     xoffset -2     yoffset -3    xadvance 24     page 0  chnl 0
char id 327   x 170     y 0     width 21     height 31     xoffset -1     yoffset -3    xadvance 23     page 0  chnl 0
char id 205   x 191     y 0     width 14     height 31     xoffset -1     yoffset -3    xadvance 16     page 0  chnl 0
char id 201   x 205     y 0     width 20     height 31     xoffset -1     yoffset -3    xadvance 21     page 0  chnl 0
char id 270   x 225     y 0     width 23     height 31     xoffset -1     yoffset -3    xadvance 24     page 0  chnl 0
char id 268   x 0     y 32     width 22     height 31     xoffset -2     yoffset -3    xadvance 22     page 0  chnl 0
char id 193   x 22     y 32     width 23     height 31     xoffset -3     yoffset -3    xadvance 22     page 0  chnl 0
char id 41   x 45     y 32     width 15     height 31     xoffset -2     yoffset 2    xadvance 16     page 0  chnl 0
char id 40   x 60     y 32     width 14     height 31     xoffset -1     yoffset 2    xadvance 16     page 0  chnl 0
char id 366   x 74     y 32     width 21     height 30     xoffset -1     yoffset -2    xadvance 23     page 0  chnl 0
char id 36   x 95     y 32     width 18     height 30     xoffset -1     yoffset 2    xadvance 21     page 0  chnl 0
char id 124   x 113     y 32     width 10     height 30     xoffset 1     yoffset 2    xadvance 16     page 0  chnl 0
char id 125   x 123     y 32     width 18     height 30     xoffset 0     yoffset 2    xadvance 21     page 0  chnl 0
char id 123   x 141     y 32     width 18     height 30     xoffset -1     yoffset 2    xadvance 21     page 0  chnl 0
char id 93   x 159     y 32     width 14     height 30     xoffset -1     yoffset 2    xadvance 16     page 0  chnl 0
char id 91   x 173     y 32     width 14     height 30     xoffset 0     yoffset 2    xadvance 16     page 0  chnl 0
char id 106   x 187     y 32     width 15     height 30     xoffset -4     yoffset 3    xadvance 14     page 0  chnl 0
char id 367   x 202     y 32     width 19     height 29     xoffset -1     yoffset -1    xadvance 21     page 0  chnl 0
char id 357   x 221     y 32     width 17     height 29     xoffset -2     yoffset -1    xadvance 15     page 0  chnl 0
char id 92   x 238     y 32     width 17     height 29     xoffset -2     yoffset 2    xadvance 16     page 0  chnl 0
char id 47   x 0     y 63     width 17     height 29     xoffset -3     yoffset 2    xadvance 16     page 0  chnl 0
char id 64   x 17     y 63     width 27     height 28     xoffset -1     yoffset 3    xadvance 29     page 0  chnl 0
char id 81   x 44     y 63     width 24     height 28     xoffset -2     yoffset 4    xadvance 24     page 0  chnl 0
char id 382   x 68     y 63     width 18     height 27     xoffset -2     yoffset 1    xadvance 18     page 0  chnl 0
char id 250   x 86     y 63     width 19     height 27     xoffset -1     yoffset 1    xadvance 21     page 0  chnl 0
char id 353   x 105     y 63     width 18     height 27     xoffset -2     yoffset 1    xadvance 18     page 0  chnl 0
char id 345   x 123     y 63     width 17     height 27     xoffset -2     yoffset 1    xadvance 16     page 0  chnl 0
char id 243   x 140     y 63     width 20     height 27     xoffset -2     yoffset 1    xadvance 20     page 0  chnl 0
char id 328   x 160     y 63     width 19     height 27     xoffset -1     yoffset 1    xadvance 21     page 0  chnl 0
char id 237   x 179     y 63     width 12     height 27     xoffset -2     yoffset 1    xadvance 12     page 0  chnl 0
char id 233   x 191     y 63     width 20     height 27     xoffset -2     yoffset 1    xadvance 20     page 0  chnl 0
char id 269   x 211     y 63     width 18     height 27     xoffset -2     yoffset 1    xadvance 18     page 0  chnl 0
char id 225   x 229     y 63     width 19     height 27     xoffset -2     yoffset 1    xadvance 20     page 0  chnl 0
char id 271   x 0     y 92     width 25     height 26     xoffset -2     yoffset 2    xadvance 21     page 0  chnl 0
char id 121   x 25     y 92     width 19     height 26     xoffset -2     yoffset 7    xadvance 20     page 0  chnl 0
char id 113   x 44     y 92     width 19     height 26     xoffset -2     yoffset 7    xadvance 20     page 0  chnl 0
char id 112   x 63     y 92     width 19     height 26     xoffset -1     yoffset 7    xadvance 20     page 0  chnl 0
char id 108   x 82     y 92     width 10     height 26     xoffset -1     yoffset 2    xadvance 12     page 0  chnl 0
char id 107   x 92     y 92     width 19     height 26     xoffset -1     yoffset 2    xadvance 20     page 0  chnl 0
char id 104   x 111     y 92     width 19     height 26     xoffset -1     yoffset 2    xadvance 21     page 0  chnl 0
char id 103   x 130     y 92     width 19     height 26     xoffset -2     yoffset 7    xadvance 20     page 0  chnl 0
char id 102   x 149     y 92     width 16     height 26     xoffset -2     yoffset 2    xadvance 14     page 0  chnl 0
char id 100   x 165     y 92     width 19     height 26     xoffset -2     yoffset 2    xadvance 20     page 0  chnl 0
char id 98   x 184     y 92     width 19     height 26     xoffset -1     yoffset 2    xadvance 20     page 0  chnl 0
char id 127   x 203     y 92     width 25     height 25     xoffset 0     yoffset 3    xadvance 29     page 0  chnl 0
char id 35   x 228     y 92     width 22     height 25     xoffset -1     yoffset 3    xadvance 25     page 0  chnl 0

```

Then I load it to my game as a texture and render quads textured with correct part (that I know form file) of this texture (with some transparency, color, ...). This all works perfectly.

I have no problems with render text like:

```
Hi, my name is Kevin.

```

but when I translate this to my language:

```
Čau, mé jméno je Kevin.

```

Now letters like ***Č*** and ***é*** are not rendered.

This is my TextRender Class:

```
class TextRender
{
    private:
    GLuint fontdata;
    int size;
    int chardata[300][8];
    int charcount;
    float cursorx, cursory;
    public:
    void CREATE(string name)
    {
        cursorx=0;
        cursory=0;
        string prefix;
        charcount=0;
        string count="count";
        string sz="size";
        string fnt=".fnt";
        string bmp=".bmp";
        string finalname=name+fnt;
        string finalname2=name+bmp;
        ifstream data(finalname.c_str());
            while(data>>prefix) if(prefix==sz) break;
            data>>size;
            while(data>>prefix) if(prefix==count) break;
            data>>charcount;
            charcount++;
            for(int i=0;i<charcount;i++)
            {
                data>>prefix>>prefix>>chardata[i][0]>>prefix>>chardata[i][1]>>prefix>>chardata[i][2]>>prefix>>chardata[i][3]>>prefix>>chardata[i][4]>>prefix>>chardata[i][5]>>prefix>>chardata[i][6]>>
                prefix>>chardata[i][7]>>prefix>>prefix>>prefix>>prefix;
            } //Loads info about current character
        data.close();

        char jmeno[1000];
        strcpy(jmeno,finalname2.c_str());

        TEXTURA pismo(jmeno,256,0,230,230,230,0); //Creates texture

        glGenTextures(1,&fontdata);
        glBindTexture(GL_TEXTURE_2D,fontdata);
        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,256, 256,0, GL_RGBA, GL_UNSIGNED_BYTE, pismo.tex256);
    }

    void RenderCharAtPosition(float x,float y, char znak)
        {
            glBindTexture(GL_TEXTURE_2D,fontdata);
            glEnable(GL_BLEND);
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
            glColor3f(1,1,1);
            for(int i=0;i<charcount;i++)
            {
                if(znak==chardata[i][0])
                {
                    glBegin(GL_QUADS);
                        glTexCoord2f(chardata[i][1]/256.0,chardata[i][2]/256.0);
                        glVertex2f(x,y);
                        glTexCoord2f((chardata[i][1]+chardata[i][3])/256.0,chardata[i][2]/256.0);
                        glVertex2f(x+chardata[i][3],y);
                        glTexCoord2f((chardata[i][1]+chardata[i][3])/256.0,(chardata[i][2]+chardata[i][4])/256.0);
                        glVertex2f(x+chardata[i][3],y+chardata[i][4]);
                        glTexCoord2f(chardata[i][1]/256.0,(chardata[i][2]+chardata[i][4])/256.0);
                        glVertex2f(x,y+chardata[i][4]);
                    glEnd();
                    break;
                }
            }
            glDisable(GL_BLEND);
        }
};

```

I propably figured out where is the problem, I just don´t know how to solve it. Some of the characters ID are much larger than 256 and thats the max value that can `char` hold.

# Answer
The codes you have are unicode characters code.

When you use unicode chars, you have to use integers instead of chars for glyph indexing.

And therefore get the unicode representation of each letter from the strings you want to convert for a lookup on the glyph array.

Be aware that with bitmap fonts, it's very difficult to cover the whole unicode universe, at least because there will be a lot of bitmaps to store all glyphs.
> 2 votes

# Answer
I'm using the freetype library for international text in my opengl project. This library gives me transparent bitmaps, wich I upload as separate opengl textures and storing id for every symbol I need.

Of course I use more bytes to store my strings of text.

Hope this helps.
> 0 votes

# Answer
primitive asembly glut it's F char:

```
GLubyte letterF[ 16 ] =
{
    0xC0, // 11000000
    0xC0, // 11000000
    0xC0, // 11000000
    0xC0, // 11000000
    0xC0, // 11000000
    0xC0, // 11000000
    0xC0, // 11000000
    0xFC, // 11111100
    0xFC, // 11111100
    0xC0, // 11000000
    0xC0, // 11000000
    0xC0, // 11000000
    0xC0, // 11000000
    0xC0, // 11000000
    0xFF, // 11111111
    0xFF  // 11111111
};

......
glBitmap( 8, 16, 0, 0, 0, 0, letterF );

```
> 0 votes

---
Tags: opengl, c++, text, glut
---


# Question
Title: How to make proper billboarding trees ? (Unity3D & C#)
I make a 2.5D first person game like Doom, Duke Nukem 3D, and Daggerfall used to be. I'm new to Unity and game development in general, so I'm sorry if this seems obvious to some people.

What I want is to have the 2D sprites of the trees to billboard smoothly in the same way they did in the old games. Take a look at this video to understand what I mean: https://www.youtube.com/watch?v=xPwGXf8y6XA&t=277s

I've already tried the proposed solution at http://wiki.unity3d.com/index.php?title=CameraFacingBillboard and it doesn't work the way I want, it's uncanny and off-putting the way it works.

Please help me.

# Answer
> 1 votes
I found a way to come closer to the desired result, but still not perfect.

Here is my code:

```
    var targetPosition = m_Body.transform.position;
    targetPosition.y = transform.position.y;
    transform.LookAt(new Vector3(m_Body.transform.position.x, transform.position.y, m_Body.transform.position.z));

```

Where m\_Body is the GameObject on which the Camera is attached to.

# Answer
> 0 votes
If you want billboarding to work on CPU, you can use predefined methods like Transform.LookAt. The replicated effect from `Transform.LookAt` could be achieved using `Rotate` or setting the rotation of game object. You can use either euler angles or `Quaternion` the second one is the recommended one to avoid different difficulties including *Gimbal Lock* problem.

You could calculate the effect on GPU using shaders - see this for more information: Efficient billboarding sprites in unity.

---
Tags: unity, c#, camera, 2.5d, billboarding
---


# Question
Title: Unity Augmenter Reality on Android with Video playing
Hey sisters and brothers, So, I created an augmented reality marker, which works perfectly, I was able to display 3 shape on the screen with my Nexus 5.

I would like to replace my shapes with a Video. So, when the user track on the marker, I would like to start to play a video above the marker as a part of the augmented reality (No full screen playing).

I tried to use this video tutorial (https://www.youtube.com/watch?v=YBc3ubr18ks) , but on Android you can't use MovieTexture (they say).

My question(s): how can I display a shape above the marker, with a video on it and what it the video format ? When I trying to build the project with mp4, it failing, but when I do with AVI it's okay, but the app crashing.

Thank you,

# Answer
> -1 votes
I did not test this, but I think this should also work with vuforia, since Unity has this Video Textures http://docs.unity3d.com/Manual/class-MovieTexture.html . So you could simply assign your video as texture to an object which is assigned to the marker.

# Answer
> -1 votes
Use the video playback unity package sample from vuforia website.

---
Tags: unity, android, augmented-reality
---


title: Unity2D jumping inconsistancy

text:
# Question
Title: Unity2D jumping inconsistancy
I'm tinkering with a unity2D sidescroller, and am trying to make a player controller to jump. However, when I tell my character to jump, it sometimes jumps twice the distance, and I don't know why. Below is my controller script:

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

public class PlayerMovement : MonoBehaviour
{

    public float playerSpeed = 10;
    public float jumpForce = 20;
    private bool ableToJump = false;
    public GameObject groundCheck;  // place an empty object slightly below the character where it will collide with any ground

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey("space") && ableToJump)
        {
            ableToJump = !ableToJump;
            GetComponent<Rigidbody2D>().AddForce(new Vector3(0,1,0) * jumpForce);
        }
        if (Input.GetKey("a"))
        {
            transform.Translate(-playerSpeed * Time.deltaTime, 0, 0);
        }
        if (Input.GetKey("d"))
        {
            transform.Translate(playerSpeed * Time.deltaTime, 0, 0);
        }

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

```

Here is the glitch as it appears when I am previewing the game (watch how the third jump seems to be twice as high). There is no consistency to when it occurs, but it has occurred any time between two in a row and 10-12 between times it happens. I have tried long versus short presses of the jump key (space bar), moving versus standing still, and jumping on different locations. I have also tried disabling animations and waiting between presses versus pressing and holding space, versus pressing space rapidly. The only consistent thing is that sometimes I jump about three blocks (200 x 200px each) high, and sometimes I jump about six blocks high. Any tips are appreciated. Thanks!

# Answer
> 7 votes
I'd recommend changing `Input.GetKey("space")` to `Input.GetKeyDown("space")`. This way the check is only performed on the initial key press, rather than every frame the spacebar is held.

---

The other issue is at the bottom of your script: `ableToJump = Physics2D.Linecast(...`

Since the physics step (aka fixed timestep) is only updating every 2 milliseconds (by default) rather than every Update frame, the Rigidbody.velocity change (and subsequent Rigidbody.position change) may not happen instantly. As such, checking for the ground position within `Update` may not be 100% accurate until the physics step happens and applies your `AddForce` call.

I'd recommend either:

1. Move the `ableToJump = Physics2D.Linecast(...` line to the top of your `Update` method, so that the order of checking the ground comes *before* performing the jump; or
2. Move the `ableToJump = Physics2D.Linecast(...` line into a `FixedUpdate () { }` method so that it's in sync and true with the physics step. (note that this could be inaccurate if you're altering `transform.position` rather than `Rigidbody.position`, so perhaps use the first option.)

---
Tags: unity, c#, physics, platformer, side-scroller
---


# Question
Title: Libgdx: How to rotate a button on main menu
How to keep rotating a button on main menu screen around its center, here's the code for the button

```
final ImageButton btnSett=UIFactory.createButton(txtrSettings);
btnSett.setScale(1,1);
btnSett.setPosition(Gdx.graphics.getWidth()/ 2,0.f, Align.center);
stage.addActor(btnSett);

```

# Answer
> 2 votes
Try applying an `Action` to the button.

For example, to make the `Button` rotate once apply a *rotate* action:

```
btnSett.addAction(Actions.rotateBy(360, 1));

```

This will rotate `btnSett` once over one second. To make something continuously rotate you can apply a *repeated* action, and actions can also be in sequence, for example;

```
btnSett.addAction(Actions.repeat(RepeatActions.FOREVER,
                  Actions.sequence(
                     Actions.rotateBy(360, 1), // First, rotate once
                     Actions.rotateTo(0));     // Then, instantly set the rotation to 0 so that the previous action makes sense again.

```

You'll also need to set the *origin* of the `Button` to it's center first;

```
btnSett.setOrigin(btnSett.getWidth() / 2, btnSett.getHeight() / 2);

```

To make the actions code look cleaner consider making static imports of the methods in `Actions`, that way the code can look more like;

```
btnSett.addAction(repeat(RepeatActions.FOREVER,
                         sequence(rotateBy(360, 1),
                                  rotateTo(0));

```

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


# Question
Title: How do I set the truck to run on the road, recognizing the black edge as the road?
I am rewriting the Bad Roads game with pygame, for AI research, having extracted the assets from the APK file. I have the truck images and the background:

How do I set the truck to run on the road, recognizing the black edge as the road?

# Answer
*Note: I'd suggest to create your own, instead of ripping these off the original game. That will give you more control, and will avoid any copyright issues.*

---

**how to recognize the black edge as the road?**

You don't, well, sort of.

---

You need an array with the heights of the terrain, such that you can use it to query for the ground at any given X coordinate.

You may want to process the image to get the heights, which would be done by going column by column, from left to right, checking the color of the pixels and exporting them to a file that you would then use in your code.

---

From watching the promotional video for the game you claim to attempt to clone, the terrain is not meant to be smooth. That means that working with a lower resolution and doing interpolation won't replicate the effect correctly.

Another thing to notice is that the trees are not obstacles. The approach above will have a problem with the trees because in the image the trees share color with the floor.

You can identify the trees rather easily (either by hand or by looking for picks in the data), what to replace them with? You can approximate the height of the ground where there is a tree by interpolating the surroundings.

---

In practice the heigh map is not the image, the image is just a visual representation for the user, but it is not mechanically relevant.

Note: the promotional video also shows the truck hitting a water tower, I'd suggest to place the coordinates for such obstacles by hand. Dealing with collisions is beyond the scope of this answer.
> 2 votes

---
Tags: game-mechanics, pygame
---


# Question
Title: Paint a 3D object partially and get percentage of a color in Unity 5 and C#
Im trying to paint an object partially from a raycasthit so it looks partially painted like in Splatoon or e.g.

Is there a way to get this working in 3d, without creating a new gameobject everytime? And is there a possibility getting the pixels of a texture in 3d to calculate the painted percentage of the object?

I tried using 2D sprites and get the pixels from a raycasthit2d, but it didnt work out well. Has anyone an idea? Or has anyone an example for this?

I found some examples on grafittis and footsteps but they are either too old or dont fit...

# Answer
> 2 votes
You could use a black texture and for example with compute shader, paint pixels white aroud position you want to be painted, then in fragment shader you would just multiply color you want, by color from this texture. And for percentage, just have a counter of pixels that you painted white and divide it by texture resolution^2.

---
Tags: unity
---


# Question
Title: Movement of an object based on thrust and gravity force in 2d scrolling game, need help
I want to make a box "fly" so while user press D it's add thrust then on A it decrese untill 0, W and S control the direction of my box.

I have problems after I add the gravity to update correctly my X and Y position. My actual code is like this: (I'm using gamemaker but it's same as other languages, came execute 60 frames per second)

```
frametime = delta_time / 1000000;
spd = sqrt(power(velx ,2)+power(vely ,2));
tempgy = g * frametime ;
//tempay = ((thrust / m) * 32) * frametime; // or my box procede diagonally offcurse
tempax = ((thrust / m) * 32) * frametime;
y -= (vely + tempgy/2   + tempay/2 ) * frametime ;
x += (velx + tempax/2  ) * frametime ;
vely += tempgy + tempay;
velx += tempax  ;

```

m is mass of object = 500

g = 9.81

32 it's pixel per meter

So, basically I calculate the acceleration on gravity, and need to apply acceleration to `x` and `y` based on direction if I not understand wrong. So for the `X` component of thrust I have to multiply `sin(degtorad(dir))` and for the `Y` must multiply `cos(degtorad(dir))`, but I have to apply the `sin` and `cos` only on acceleration?

I think I am doing it wrong because if I use `g=0` and just using thrust my box act not as intended (ex: If I try to do a loop and stop accelerating my box will not follow the loop direction but continue on straight line)

Sorry for the stupid question but I really not know how to fix it. I see lot of tutorials with vectors but it's not supported here so can't use them. Thank you and best regards.

# Answer
Your code seems to be using the formulas correctly, but let us check again what we want to do :

We want to update the position of our object. To do this we use the speed.

```
x += vx * frametime;
y += vy * frametime;

```

And we want to update the speed of our object, using acceleration

```
vx += ax * frametime;
vy += ay * frametime;

```

Now how to calculate the acceleration **a**?

The acceleration is just the composition of the gravity and the thrust as you can see on my beautiful drawing above.

So we have

```
a.x = g.x + t.x;
a.y = g.y + t.y;

```

Now `g.x = 0` and `g.y = -9.81` (if going down means lowering y), so all we need is `t.x` and `t.y`, which can be easily calculated with basic trigonometry. Note that on my drawing I have put the angle compared to the floor, it is possible that you used the other one which means you need to reverse the sin and cos.
> 1 votes

# Answer
I'm not a good physicist, but I'll try to help a little bit.

There are some problems with understanding, what you're really want, but let's start with basic idea of movement and gravitation.

And, of course, we need the beatiful **vector algebra** for that.

**What is a vector?**

**Vector** is a kind of number, but with additional value - *direction*. Two vectors can be compared by value and direction.

**Why vector algebra?**

As in natural numbers, there are some operations, which can be applied to vectors. We will see later. If you have a rigid body and you want to apply gravitation on it, than you should just create a vector with value `9.81` pointing *down to the earth*. I will try to explain the last sentence in details.

**Explanation**

The gravitation is a **force** so it can be represented as *vector* (as I've said previously). The main point is that there are some another things, that can be represented as vector aswell: horizontal movement (your *thrust*), jumps and so on.

Also there is a little hack in **vector algebra**: we can represent a lot of vectors **as one** with calculated value and direction (this is called the **sum**).

Another important thing is that every vector can be splitted onto the *X*-part and the *Y*-part (corresponding axle projections). For velocity this will be your vertical and horizontal **components** of it. In other words: the values to apply at every frame to the body.

**The recipe**

1. Calculate the vector of *gravity* (direction - negative part of y-axis, value - `9.83`).
2. Calculate the vector of *horizontal movement* (*thrust*, direction - positive part of x-axis, value - `thrustPower`).
3. Calculate the vector of *vertical movement* (direction - positive part of y-axis, value - `jumpPower`).
4. Get the **sum** of vectors (this is the best part), *so from three vectors we will get one*.
5. Calculate **y-component** (suppose it is represented as `yVelocity`) and **x-component** (`xVelocity`) of **sum**.
6. Apply the values to the body: `newX = oldX + xVelocity` and `newY = oldY + yVelocity`.

Links:

1. https://www.mathsisfun.com/algebra/vectors.html
2. https://en.wikipedia.org/wiki/Unit\_circle
> 0 votes

---
Tags: game-mechanics, game-maker
---


title: Pokemon Artificial Intelligence

text:
# Question
Title: Pokemon Artificial Intelligence
I'm working on a thesis about programming an AI combat system for Pokemon (To be implemented in Showdown!). However, I would like to include historical information about the existing implementations of Pokemon AI. This information would offer valuable context to my thesis.

I have been scouring the internet for some sort of algorithm that explains how the AI Trainers make their choices, but have found nothing promising. I realize the fan-games have implemented some more interesting AI systems for their trainers, these would be interesting to see as well.

What I am looking for is examples of the methods used for Pokemon Battle AI decision making used in Pokemon videogames, whether from main series by Nintendo or the many fan-games out there. I realize most of these pose no challenge to an experienced player, but I don't mind, I only wish to compile historical information on previous Pokemon AI attempts.

# Answer
First off, I want to say that this particular case can be approached as a generic AI problem and solve it by training a neural network that has for input layer whatever information is relevant in the battle (such as health of the Pokémon, number of items, PP of the attacks, etc...) and having as output layer the different actions to take.

If you want to take that approach, and you have no idea how neural networks work, you can look for an introduction to the topic (there are videos, books, articles, etc...) and I'd suggest the approach described in Evolving Neural Networks through Augmenting Topologies to train and evolve your AI. For abstract, the paper proposes an approach to use genetic algorithms to evolve the topology (the connectivity) of neural networks.

Of course, training the AI requires to have it play multiple times, and using the feedback to improve it.

---

I cannot really comment on AI of third party games, although we can talk about the AI bot created by drac5290 who was kind enough to publish the decision tree it uses combat. We can consider it an expert system.

*Note: Whatever it sucks or not is debatable. The AI beats the Elite Four of Pokémon Blue, but it was given arguably strong Pokémon to battle and an endless supply of healing items. Also, there are new mechanics in newer Pokémon that it doesn't have to bother with.*

The decision tree is the following (Yes to the left, No to the right):

As you see, it requires to calculate if the Pokémon currently out will die of an attack of the enemy in the next turn, it also requires to determinate what Pokémon will take less damage and which one will do most damage to the enemy.

Also, it doesn't have much actions, it only does: Switch, Attack (with the best attack available), and Heal using items. As far as I can tell, inflicting status effects to the enemy is not taken into account.
> 2 votes

# Answer
The AI for Pokemon depends on the version, but it's nothing really advanced. I'll talk about a bit red/blue/yellow in this answer, sources below.

The AI picks a move using rejection sampling from the moves it considers usable, which moves it considers usable depends on the turn the Pokemon is out and what kind of trainer it is.

For example, on turn 1 *if* the trainer class is not youngster or cue ball: do not use an attack that only gives a status if the opponent already has a status.

They also have a preference for super effective moves (with some bugs because gen1 is held together by bugs) and will not pick a "not very effective" move if there's no alternative.

There's also some cases where (for story reasons generally) a specific attack is chosen, this overrides regular selection and can lead to doing impossible things (i.e. a 2-turn move like fly starting, and then a *different* move happening).

Basically the AI does no planning ahead and just looks at the current state, it's not a very good AI because, well it's a game. You don't want a great AI opponent because then you'd lose far too often.

Source: http://wiki.pokemonspeedruns.com/index.php/Pok%C3%A9mon\_Red/Blue/Yellow\_Trainer\_AI
> 1 votes

---
Tags: ai, game-mechanics, turn-based
---


# Question
Title: Find if two triangles are touching each other! To find the edges of a polygon. Unity3d/C#
I need help trying to find if two triangles are touching each other. If vertices are repeated twice in the mesh triangles setup it means they are connected. I then try to calculate the direction between each vertices of the mesh to remove the Vector3 direction which is the sides of the two triangles that are touching each other... which leaves me the edges of the polygon quad... the thing is it doesn't seem to be working... anyone got any ideas?

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

public class example : MonoBehaviour {

int[] triangles;
Vector3[] vertices;
Mesh mesh;

List<Vector3> vertsTrigConnections = new List<Vector3>();
List<Vector3> vertTrigDirToNotCalculate = new List<Vector3>();
List<Vector3> totalDirections = new List<Vector3>();

void Start ()
{
    mesh = GetComponent<MeshFilter>().mesh;
    vertices = mesh.vertices;
    triangles = mesh.triangles;

    for (int i = 0; i < triangles.Length; i += 3)
    {
        Vector3 p0 = vertices[triangles[i + 0]];
        Vector3 p1 = vertices[triangles[i + 1]];
        Vector3 p2 = vertices[triangles[i + 2]];

        vertsTrigConnections.Add(p0);
        vertsTrigConnections.Add(p1);
        vertsTrigConnections.Add(p2);

        Vector3 direction0 = p1 - p0;
        Vector3 direction1 = p2 - p1;
        Vector3 direction2 = p0 - p2;

        for (int h = 0; h < vertsTrigConnections.Count - 1; h++)
        {
            for (int f = h + 1; f < vertsTrigConnections.Count; f++)
            {
                if (vertsTrigConnections[h] == vertsTrigConnections[f])
                {
                    vertTrigDirToNotCalculate.Add(vertsTrigConnections[h]);
                }
            }
        }

        for (int h = 0; h < vertTrigDirToNotCalculate.Count - 1; h++)
        {
            for (int f = h + 1; f < vertTrigDirToNotCalculate.Count; f++)
            {
                if (direction0 == vertTrigDirToNotCalculate[h] - vertTrigDirToNotCalculate[f] ||
                    direction0 == vertTrigDirToNotCalculate[f] - vertTrigDirToNotCalculate[h])
                {
                    totalDirections.Remove(direction0);
                }
                if (direction1 == vertTrigDirToNotCalculate[h] - vertTrigDirToNotCalculate[f] ||
                    direction1 == vertTrigDirToNotCalculate[f] - vertTrigDirToNotCalculate[h])
                {
                    totalDirections.Remove(direction1);
                }
                if (direction2 == vertTrigDirToNotCalculate[h] - vertTrigDirToNotCalculate[f] ||
                    direction2 == vertTrigDirToNotCalculate[f] - vertTrigDirToNotCalculate[h])
                {
                    totalDirections.Remove(direction2);
                }
            }
        }
    }
}

```

}

Edit 22h42: nvm it seems to be working fine. The error was in the next part of my code...

# Answer
The code is based on two examples of mesh cutting. One from MGear found here http://1darray.com/blog/2011/08/09/fake-mesh-slicer-v3-0/ and one from YouTube found here https://www.youtube.com/watch?v=xgoUmrhXyYE. My goal was to find a way of cutting objects and I couldn't figure out how to put back triangles where they shouldve been. although the code below is far from beeing perfect it moves Vertices at the point of the cut made with a Struct plane. It doesn't work from all angles and it lags as hell. Some vertices were not following the cut i was making but by removing 3 if's statements: worldPt0 == currentVert && worldPt1 == currentVert && worldPt2 == currentVert It works ok but with lag. Sorry for the long code. If anyone got any ideas on how to make this better and got the time to check it feel free to give an input. Sorry for the long code. Thank you, Nine.

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

public class example : MonoBehaviour
{
private static Plane blade;

List<Vector3> vertsTrigConnections = new List<Vector3>();
List<Vector3> vertTrigDirToNotCalculate0 = new List<Vector3>();
List<Vector3> vertTrigDirToNotCalculate1 = new List<Vector3>();

List<Vector3> totalDirections = new List<Vector3>();
List<Vector3> rightSideVertTemp = new List<Vector3>();
List<Vector3> leftSideVertTemp = new List<Vector3>();
List<Vector3> newVertices = new List<Vector3>();

public GameObject sphere0;
public GameObject sphere1;

int[] triangles;
Vector3[] vertices;
Mesh mesh;

void Update()
{
    float mouseVert = Input.GetAxisRaw("Mouse Y");
    float mouseHorz = Input.GetAxisRaw("Mouse X");

    transform.Rotate(new Vector3(-mouseVert, mouseHorz, 0));

    Debug.DrawRay(new Vector3(transform.position.x, transform.position.y, transform.position.z), transform.forward, Color.red, 0.1f);

    if (Input.GetMouseButtonDown(0))
    {

        RaycastHit hit;

        if (Physics.Raycast(transform.position, transform.forward, out hit, 20f))
        {
            mesh = hit.transform.GetComponent<MeshFilter>().mesh;
            GameObject hitObject = hit.transform.gameObject;
            blade = new Plane(hit.transform.InverseTransformDirection(transform.right), hit.transform.InverseTransformPoint(transform.position));

            for (int i = 0; i < hit.transform.GetComponent<MeshFilter>().mesh.vertices.Length; i++)
            {
                if (!blade.GetSide(hit.transform.GetComponent<MeshFilter>().mesh.vertices[i]))
                {
                    leftSideVertTemp.Add(hit.transform.GetComponent<MeshFilter>().mesh.vertices[i]);
                }
                if (blade.GetSide(hit.transform.GetComponent<MeshFilter>().mesh.vertices[i]))
                {
                    rightSideVertTemp.Add(hit.transform.GetComponent<MeshFilter>().mesh.vertices[i]);
                }
            }

            vertices = hitObject.transform.GetComponent<MeshFilter>().mesh.vertices;
            triangles = hitObject.transform.GetComponent<MeshFilter>().mesh.triangles;

            for (int i = 0; i < triangles.Length; i += 3)
            {
                Vector3 dir0;
                Vector3 dir1;
                Vector3 dir2;

                Vector3 worldPt0 = vertices[triangles[i + 0]];
                Vector3 worldPt1 = vertices[triangles[i + 1]];
                Vector3 worldPt2 = vertices[triangles[i + 2]];

                vertsTrigConnections.Add(worldPt0);
                vertsTrigConnections.Add(worldPt1);
                vertsTrigConnections.Add(worldPt2);

                dir0 = worldPt1 - worldPt0;
                dir1 = worldPt2 - worldPt1;
                dir2 = worldPt0 - worldPt2;

                if (!totalDirections.Contains(dir0))
                {
                    totalDirections.Add(dir0);
                }
                if (!totalDirections.Contains(dir1))
                {
                    totalDirections.Add(dir1);
                }
                if (!totalDirections.Contains(dir2))
                {
                    totalDirections.Add(dir2);
                }

                for (int h = 0; h < vertsTrigConnections.Count - 1; h++)
                {
                    for (int f = h + 1; f < vertsTrigConnections.Count; f++)
                    {
                        if (vertsTrigConnections[h] == vertsTrigConnections[f])
                        {
                            vertTrigDirToNotCalculate0.Add(vertsTrigConnections[h]);
                            vertTrigDirToNotCalculate1.Add(vertsTrigConnections[h]);
                        }
                    }
                }

                for (int h = 0; h < vertTrigDirToNotCalculate0.Count; h++)
                {
                    for (int f = 0; f < vertTrigDirToNotCalculate1.Count; f++)
                    {
                        if (dir0 == vertTrigDirToNotCalculate0[h] - vertTrigDirToNotCalculate0[f])
                        {
                            totalDirections.Remove(dir0);
                        }

                        if (dir0 == vertTrigDirToNotCalculate0[f] - vertTrigDirToNotCalculate0[h])
                        {
                            totalDirections.Remove(dir0);
                        }

                        if (dir1 == vertTrigDirToNotCalculate0[h] - vertTrigDirToNotCalculate0[f])
                        {
                            totalDirections.Remove(dir1);
                        }

                        if (dir1 == vertTrigDirToNotCalculate0[f] - vertTrigDirToNotCalculate0[h])
                        {
                            totalDirections.Remove(dir1);
                        }

                        if (dir2 == vertTrigDirToNotCalculate0[h] - vertTrigDirToNotCalculate0[f])
                        {
                            totalDirections.Remove(dir2);
                        }

                        if (dir2 == vertTrigDirToNotCalculate0[f] - vertTrigDirToNotCalculate0[h])
                        {
                            totalDirections.Remove(dir2);
                        }
                    }
                }

                var enumerator999 = rightSideVertTemp.GetEnumerator();
                while (enumerator999.MoveNext())
                {
                    var currentVert = enumerator999.Current;
                    var enumerator888 = leftSideVertTemp.GetEnumerator();
                    while (enumerator888.MoveNext())
                    {
                        var currentVert1 = enumerator888.Current;
                        Vector3 dir = (currentVert1 - currentVert);
                        Vector3 diri = (currentVert - currentVert1);

                        for (var g = 0; g < vertices.Length; g++)
                        {
                            for (int j = 0; j < totalDirections.Count; j++)
                            {
                                if ( totalDirections[j] == dir)
                                {
                                    Ray vecRay0 = new Ray(worldPt0, totalDirections[j]);
                                    float dist0;
                                    if (blade.Raycast(vecRay0, out dist0))
                                    {
                                        if (!newVertices.Contains(vecRay0.GetPoint(dist0)))
                                        {
                                            newVertices.Add(vecRay0.GetPoint(dist0) + hit.transform.position);
                                        }
                                        if (worldPt0 == vertices[g])
                                        {
                                            vertices[g] = vecRay0.GetPoint(dist0);
                                        }
                                    }
                                }
                            }
                            for (int j = 0; j < totalDirections.Count; j++)
                            {
                                if (totalDirections[j] == dir)
                                {
                                    Ray vecRay1 = new Ray(worldPt1, totalDirections[j]);
                                    float dist1;
                                    if (blade.Raycast(vecRay1, out dist1))
                                    {
                                        if (!newVertices.Contains(vecRay1.GetPoint(dist1)))
                                        {
                                            newVertices.Add(vecRay1.GetPoint(dist1) + hit.transform.position);
                                        }
                                        if (worldPt1 == vertices[g])
                                        {
                                            vertices[g] = vecRay1.GetPoint(dist1);
                                        }
                                    }
                                }
                            }
                            for (int j = 0; j < totalDirections.Count; j++)
                            {
                                if (totalDirections[j] == dir)
                                {
                                    Ray vecRay2 = new Ray(worldPt2, totalDirections[j]);
                                    float dist2;

                                    if (blade.Raycast(vecRay2, out dist2))
                                    {
                                        if (!newVertices.Contains(vecRay2.GetPoint(dist2)))
                                        {
                                            newVertices.Add(vecRay2.GetPoint(dist2) + hit.transform.position);
                                        }
                                        if (worldPt2 == vertices[g])
                                        {
                                            vertices[g] = vecRay2.GetPoint(dist2);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    mesh.vertices = vertices;
    mesh.RecalculateBounds();

    rightSideVertTemp.Clear();
    leftSideVertTemp.Clear();
    newVertices.Clear();
    vertsTrigConnections.Clear();
    vertTrigDirToNotCalculate0.Clear();
    vertTrigDirToNotCalculate1.Clear();
    totalDirections.Clear();
}

```

}
> 0 votes

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


# Question
Title: Player field of view, Physics.overlap, onTrigger performance
I would like to ask you what is the best way to accomplish my problem. I have a player who can detect ennemy with raycast in a zone, or in a certain angle, like in this picture:

As you see I want to get only green one.

I'm in topDown view. I was thinking about using Physics.OverlapSphere first, and then try Angle between player and target. But: In the picture I don't want to get the Purple one.

Also: what is the best way to do that with the best performance ?

# Answer
There are 3 approaches I know about, how to do this.

1) Like in your picture. First one and maybe one of the most efficient and accurate ways to do it.

1. You check for `Physics.OverlapSphere` and get all the objects that could potentially be in field of view.
2. Then you iterate through them in `for` loop (no need for `while` as length of array doesn't change during loop(clean code)). In the loop you check if if for example enemies `enemies[i]` is in your field of view. We do that first because we don't need to `Physics.Raycast` him if he is not in the field of view of, course to save some performance. After checking if the object is in your field of view (I would checking the field of view as different method where you pass direction(Vector3) to enemy). Remember if he is not in the field of view - just ignore him and continue the loop, if he is then you `Physics.Raycast` from `transform.position`(players position) in this direction `enemies[i].transform.position - (player.)transform.position`.

**@@@@@** Also when you check if the `enemies[i]` is in the field of view, you also check if the radius squared (save this squared radius in some variable) is bigger than distance square magnitude(no need to take a square root - it's heavy operation). This distance `Vector3` is the same vector as direction.**@@@@@**)

**You don't need to do @@@@@ step in case `Physics.OverlapSphere` because the radius is already specified in `Physics.OverlapSphere`. Also in this case you already have the distance to specify in your rayscasts - it's the `radius`.**

**Remember to use Layers, you don't need to raycast objects that don't affect your field of view. You should have `LayerMask` variable to save layers raycasts are going to hit. `Physics.OverlapSphere` in this case should only use layer of "MyEnemy" script, so you could use it as a parent class of your different type of enemies (OOP: Inheritance + Polymorphism in this case) so you won't have objects like walls in your array** After raycasting you should check if object that was hit by raycast is really the one you need: `enemy`. It's not efficient to compare tags even if you use `CompareTag(string otherTag)` method. The fastest way to check this in Unity for now is `hit.collider.GetComponent<MyEnemy>()` *"MyEnemy" - name of your script(class type (generics))*.

2) Second would be to do many raycasts in field of view and check if any hits the object you need.

Not very efficient as you see, for every raycast check if there is an object you need. Also the angle between raycasts should be small enough not to miss the object it's trying to hit.

In this case you would loop through resolution of your field of view (number of raycasts) and translate angle into direction, raycast and check for the object you need on every iteration.

3) Would be to create a collision mesh like your field of view.

Then you would use method `OnCollsionEnter(Collision other)` or `OnTriggerEnter(Collider other)`, but let's be real it's bad way to do this, because you would check for every object that enters field of view and for every object it would constantly check for collisions with this field of view. In physics engine of course, so we would see it only in the profiler. Also then every object that should have rigidbody and we would raycast them anyway to check if nothing blocks path to them.

To sum up - the best practice I know about for now is the (1) method.
> 2 votes

# Answer
I solve my problem, with pretty good performance, here is the code: (assuming I'm in top-down view, with `transform.up` the actual "forward" of the player. The script is attached to the player gameObject; and my function is called every `Update()`)

**EDIT:** Thanks to Candid Moon, I change i little mit my function, also I **change of procedure**, by testing the difference of angle between 2 vector, unlike before (I was testing if B is beteen A & C)

```
private int layerMask = 1 << 8; //select layer 8 (target and walls)
[Range(0, 360)]         public float fovAngle = 30.0f;

float SignedAngleBetween(Vector3 a, Vector3 b, Vector3 n)
    {
        float angle = Vector3.Angle(a, b);                                  // angle in [0,180]
        float sign = Mathf.Sign(Vector3.Dot(n, Vector3.Cross(a, b)));       //Cross for testing -1, 0, 1
        float signed_angle = angle * sign;                                  // angle in [-179,180]
        float angle360 =  (signed_angle + 360) % 360;                       // angle in [0,360]
        return (angle360);
    }

void Force()
{
    Collider[] hitColliders = Physics.OverlapSphere(gameObject.transform.position, fovRange, layerMask);

    for (int i = 0; i < hitColliders.Length; i++)
    {
        if (hitColliders[i].tag == "Metal")
        {
            Vector3 B = hitColliders[i].transform.position - gameObject.transform.position;
            Vector3 C = Quaternion.AngleAxis(90 + fovAngle / 2, -transform.forward) * -transform.right;
            if (SignedAngleBetween(transform.up, B, transform.up) <= SignedAngleBetween(transform.up, C, transform.up) || fovAngle == 360)
            {
                RaycastHit hit;
                if (Physics.Raycast(transform.position, B, out hit, layerMask))
                {
                   Debug.DrawRay(transform.position, B, Color.red, 0.5f);
                }
            }
        }
    }
}

```

**Old method:**

```
void Force()
    {
      // get every object in a sphere, from this.position, with fovRange = Radius, and layerMask:
      // I have target, and wall, both ones are in that layerMask, for testing if my target are behind wall or not
        Collider[] hitColliders = Physics.OverlapSphere(gameObject.transform.position, fovRange, layerMask);
        int i = 0;
        while (i < hitColliders.Length)
        {
          //test the tag
            if (hitColliders[i].tag == "Metal")
            {
              //create raycast
                RaycastHit hit;
              //create vector director from player to target
                Vector3 vectorDir = hitColliders[i].transform.position - gameObject.transform.position;

              //if Raycast touch something...
                if (Physics.Raycast(transform.position, vectorDir, out hit, layerMask))
                {
                  //if the collider is my target (else, nothing happend)
                    if (hit.collider.tag == "Metal")
                    {
                        //For my purpose, i'm in top-down view, I want to test if vectorDir is between
                        //vector A & vector C
                        Vector3 A = Quaternion.AngleAxis(90 - fovAngle / 2, -transform.forward) * -transform.right;
                        Vector3 B = vectorDir;
                        Vector3 C = Quaternion.AngleAxis(90 + fovAngle / 2, -transform.forward) * -transform.right;

                        //draw vector
                        Debug.DrawRay(transform.position, A, Color.blue);
                        Debug.DrawRay(transform.position, B, Color.blue);
                        Debug.DrawRay(transform.position, C, Color.blue);

                        //test if B is in middle of A & B
                        Vector3 AB = new Vector3(B.x, B.y, B.z) - new Vector3(A.x, A.y, A.z);
                        Vector3 AC = new Vector3(C.x, C.y, C.z) - new Vector3(A.x, A.y, A.z);

                        Vector3 CB = new Vector3(B.x, B.y, B.z) - new Vector3(C.x, C.y, C.z);
                        Vector3 CA = new Vector3(A.x, A.y, A.z) - new Vector3(C.x, C.y, C.z);

                        float ab = Vector3.Dot(A, B);       //test inverse
                        float abc = Vector3.Dot(AB, AC);
                        float cba = Vector3.Dot(CB, CA);

                      //if vectorDir is in the middle, OR if my fovAngle is 360, the algo work !
                        if ((abc >= 0 && cba >= 0 && ab >= 0) || fovAngle == 360)
                        {
                            Debug.DrawRay(transform.position, vectorDir, Color.green, 0.5f);
                            Debug.Log("OK  !");
                        }
                    }
                }
            }
            i++;
        }
    }

```
> 0 votes

---
Tags: unity, raycasting
---