# Question
Title: Why do we refer to a "model view" matrix and not a "viewprojection" matrix?
Why there is a model-view matrix, but not a view-projection matrix?

A view-projection matrix would make much more sense to me, since every entity in the scene has his own position and therefore its own model-matrix, **but** there is only one camera, so you could just precalculate the view-projection matrix and then use this matrix to multiply it with every models model-matrix to get every models MVP-matrix. Am I wrong?

# Answer
> 16 votes
The graphics pipeline (typically) involves transformation from model space to world space, from world space to view space, and from view space to clip space. There is a transformation matrix associated with each of these (the world, view and projection transformations, respectively). There are of course stages of the pipeline after geometry reaches clip space, but they are not relevant to your question.

Because each transformation is a matrix, you can combine them: you can create a "model-view" matrix or a "view-projection" matrix or even a single combined "model-view-projection" matrix. They're all perfectly reasonable and are in fact used fairly commonly, when appropriate.

The reason that the term "modelview matrix" is so prevalent is because of classical graphics pipeline theory and OpenGL, where it was considered standard practice to combine the model-to-world and world-to-view transformations. This was done because there was a very common reason to have geometry in view space: *it simplified the computation of lighting effects*.

There wasn't a particularly common reason to have geometry in world space, particularly since the pipeline was not programmable the way it is today. Consequently, there was not really a common need to go from world space directly to clip space, and thus a "viewprojection matrix" was not a common thing and did not gain a foothold in the vernacular of the industry.

If you have a good reason to have your geometry in world space for some intermediate computations during the pipeline, but have no reason to have your geometry in view space, then it is perfectly acceptable to use a combined view-projection matrix.

# Answer
> 2 votes
The camera analogy is a lie because there is no camera. Instead all that happens is a transformation of points in 3D space to points on a 2D screen, and the matrices define how that transformation happens.

Modelview and projection are conceptually different although mathematically the same (it's all just matrix multiplication).

Modelview just moves points from one 3D space to another.

Projection defines how those points are then *projected* onto the 2D display; i.e how perspective, foreshortening, etc happen.

Since you mention "modelview" I'm going to deduce that you're talking about OpenGL and with specific reference to the old fixed pipeline. The fixed pipeline in other APIs, such as D3D need not have the same concepts. In fact in the old D3D fixed pipeline there are 3 matrices used: projection, view and world. In this case "view" is what you might call the "camera" and "world" is what you call "each model's model-matrix".

It therefore becomes clearer that you concatenate projection and view, and apply world separately.

The use of a concatenated "modelview" in OpenGL (which corresponds to D3D's "view" and "world") is therefore just an artefact of OpenGL's design but need not specifically refer to the way things are actually done.

With the programmable pipeline all of this goes away, and you can use as many (or as few) matrices as you like, concatenating any you like in order to get the end result.

# Answer
> 0 votes
You answered your question well. This is exactly how it should be done for a 3D scene at least in OpenGL (not used other graphics APIs). You create your projection matrix using your FOV, aspect ratio, near and far planes and use it to render your entities, by multiplying it against each entities own model matrix. You should only need to set your projection matrix once when you start up your rendering system.

---
Tags: mathematics, matrix
---


# Question
Title: How to distort graphics in a wave-like way?
I saw a certain graphics distortion effect on multiple games over time and am interested in doing it in 2D. It is like a wave-like texture distortion, I am not entirely sure what it is called actually. Super Mario 64 had an effect like that when you enter a painting depending on your position (https://www.youtube.com/watch?v=H6r5oF73gNI#t=72), also Braid has one which is even more similar to that what I am trying to achieve when you use the time ring (https://www.youtube.com/watch?v=uqtSKkyJgFM#t=38).

I would really like to know how those effects were implement and if there is support for something like that in LWJGL (or even Slick2D). So far, I found absolutely nothing explaining on how it was done.

# Answer
The Mario64 effect is done by moving vertices.

You need a grid for fluid quantity (a water level height value) represented by the black dots height. And a grid of direction & speed of transfer between the former grid's cells which simulates water's inertia (the red arrows).

Every simulation tick each height cell tries to return to 0 by pushing out or sucking in water to/from its neighbors, this is added to the transfer movement values at the cell boundaries, friction is applied to this, then these transfer movement values are applied to every height cell.

Friction is approximated by `speed = speed * (1 - tiny_value)`

Inertia is approximated by `speed = speed + (push * small_value)`

Due to rounding errors ""water"" will be lost or gained overall so a very small correction toward height=0 should also be applied every N frames to help the simulation come to rest if a state of rest is required.

If one cell (vertex) is to be pushed down (ie: by -4) then all neighbors must be pushed up by an equal total amount (left, right, up, and down: each by +1).

To cause the initial impulse you don't push down the cell, you set its transfers to transfer height away from it, then height gets transfered away at that stage of the simulation.
> 1 votes

---
Tags: graphics, lwjgl, slick
---


# Question
Title: Breakout Collision Detection: Ball gets trapped inside block
I'm writing a breakout clone where blocks to hit can be of various sizes and the projectile can move at different speeds, and I seem to be having some trouble getting the collision detection perfectly right.

I have a side-detection algorithm working just fine (projectile reflects in the proper direction when hitting top/side of a block), but sometimes the projectile seems to get stuck inside the blocks, especially when the projectile is moving fast. The function I have simply tells the projectile to reflect it's X or Y axis, but, when the projectile can't get away from the block in time, it gets trapped constantly reflecting on its axes, causing it to "freak out" and get trapped bouncing around inside the block itself.

I attempted to fix this by disabling collision detection for a very short time after each detected collision (defined as PROJECTILE\_TICK = 0.05f in the code below), but this doesn't seem to solve the problem, and the projectile still gets trapped.

Is there a standard way this sort of problem is typically handled? I know I'm far from the first person to try and make a breakout clone, so someone must have run into this problem before.

My collision detection function is below. The blocks are referred to as "ptfm" in the code below.

```
 private void checkPlatformCollisions(float deltaTime) {
    tickTime += deltaTime;

    for(int i = 0; i < projectiles.size(); i++) {
        Projectile proj = projectiles.get(i);

        for(int j = 0; j < platforms.size(); j++) {
            Platform ptfm = platforms.get(j);
            if (OverlapTester.overlapCircleRectangle(proj.boundingRadius,
                    ptfm.bounds)) {

                if(ptfm.breakable) {
                    //this part works just fine; it's the else clause that's screwy

                    }
                } else {

                    //tick is so projectile wont get stuck in a reflection loop
                    //move these to the projectile class later
                    if(tickTime > PROJECTILE_TICK) {

                        //reset tick time
                        tickTime = 0;

                        if(ptfm.type == Platform.PLATFORM_TYPE.WALL) {
                            proj.reflectX();
                            continue;
                        }

                        float angle = (float) Math.atan2(ptfm.pos().y - proj.pos().y,
                                ptfm.pos().x - proj.pos().x);

                        //atan2 returns in radians
                        angle *= Vector2.TO_DEGREES;

                        if(angle < 0) {
                            angle = 360 - (-angle);
                        }

                        if ((angle >= 0 && angle <= 45) ||
                                (angle >= 315 && angle <= 359)) {
                            //hit from top
                            proj.reflectX();
                        } else if ((angle >= 45 && angle <= 135)) {
                            //hit from left
                            proj.reflectY();
                        } else if ((angle >= 135 && angle <= 225)) {
                            //hit from bottom
                            proj.reflectX();
                        } else if ((angle >= 225 && angle <= 315)) {
                            //hit from right
                            proj.reflectY();
                        } else {
                            proj.reflectX();
                        }

                    }

                }

            }

        }
    }

```

# Answer
> 4 votes
While you may have other problems to solve, and I have to assume that there is a best practice for bouncing balls off blocks, one thing that stands out to me is the test for an angle between centers. The current code determines a bottom vs side collision based on four equal quadrants. When the ball is near a corner, that test will give an undesirable reading.

I really think you can skip the trigonometry and just do a few greater-than comparisons of x and y.

If the ball's center is between the x values of the rectangle's sides, you have either a top or bottom hit. Same goes for y values and side hits. If you have a top or a bottom hit, you do the same reflection. If you're in one of the four corners, which would be vanishingly rare, you have a few options:

* Default to a top/bottom bounce.
* Reflect on both x and y (for a surprising reaction that emphasizes the corner hit)
* Calculate if it is the x or y axis with the greater difference to more accurately determine if you have a top/bottom or side hit.

For this last option, let's say that `ax` and `ay` are the x and y of the ball, `bx` and `by` are the x and y of the brick, `bw` is half the width of the brick, and `bh` is half of the height of the brick. I'm going to use `abs()` for getting the absolute value. I believe that Java uses `Math.abs()`.

If we define `dx` to be `abs(ax - bx) - bw` and `dy` to be `abs(ay - by) - bh`, then we check to see if `dx > dy`. If so, perform a side-hit reflection. Else perform a top-bottom reflection.

In the following image, `dx` is greater than `dy` in the blue and magenta areas. `dy` is greater than `dx` in the green and yellow areas. `dx` and `dy` are both positive values in the yellow and magenta areas. In the green area, `dx` is negative. In the blue area, `dy` is negative.

# Answer
> 0 votes
Oh, hi! I also run into some troubles of the sort when handling collisions. Your problem is that the ball is going too fast, so, by the time your program realised that it collided, it's already inside the brick. Then, in the next iteration collides again, and bounces in the opposite direction, and so on. :D

**Solution:** Just move the ball outside the box `ball.set(x,y);//or something of the sort` The easiest way would be to simply

```
proj.x -=proj.xSpeed; //or whatever way you have to produce this result
proj.y -=proj.ySpeed; //with functions and the sort.

```

after you detect a collision, and then do the `reflectX()//or reflectY()` thing. Of course, that'd move your ball too far sometimes (it would look as if it's bouncing on air), so, another approach would be

```
if(/*collision came from the bottom*/){
    proj.x =ptfm.x + ptfm.xSize + proj.xSize;
}

```

and 4 more changes depending on the direction of the hit. That'd "pull" the ball out of the brick in the direction it came! Then `reflectX()//or reflectY()` and you got it bouncing!

There are of course more complex solutions. But I assumed this is probably one of your first attempts, so I thought it was cooler to keep it simple.(Maybe other answers with super cool, accurate ways will appear soon ^^) I hope I helped a little!

Cheers!

---
Tags: java, collision-detection
---


# Question
Title: Replacing a sprite for another on runtime (Unity3D)
I need to replace the sprite of a face down card for another sprite (of a face up card).

This is the C# script attached to the face down card:

```
using UnityEngine;
using System.Collections;

public class Entra : MonoBehaviour
{

    public float velocidadDeRotacion = 100.0f;
    public Sprite CartaBase;
    public Sprite CartaDelantera;

    private bool clickActivado = false;
    public void OnMouseDown()
    {
        clickActivado = true;
    }

    // Use this for initialization
    void Start ()
    {

    }

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

        if (clickActivado)
        {
            transform.Rotate(Vector3.up * Time.deltaTime * velocidadDeRotacion);
            if (transform.eulerAngles.y >= 90)
            {
                SpriteRenderer Carta;
                Carta = GetComponent<SpriteRenderer>();
                if (Carta.sprite == CartaBase)
                {
                    Carta.sprite = CartaDelantera;
                    transform.Rotate(Vector3.up * Time.deltaTime * velocidadDeRotacion);
                    if (transform.eulerAngles.y >= 0 && transform.eulerAngles.y <=10)
                    {
                        transform.eulerAngles = new Vector3(0, 0, 0);
                        clickActivado = false;
                        return;
                    }

                }
                clickActivado = false;
                return;
            }

        }

    }
}

```

As you can see, I rotate the card when I click on it, when the angle reach 90º I stop the rotation and change the sprite, from CartaBase to CartaDelantera.

Right now I have two problems.

1. When the sprite has an angle of 1º or more, the image breaks. I lose the right half of the image from the center to the right border, and I don't understand why.
2. Using VS2013 as debugger, I make a step by step walkthrough and when it reach

if (Carta.sprite == CartaBase)

it jumps stright to

```
clickActivado = false;

```

So, obviously it's not "seeing" the sprite used by the card. Why???

I'm using this script as reference for the change of sprites.

If you don't understand my problem, you can see live here.

# Answer
I solve the second problem. It was in front of me all the time.

As I said, I was using this code as example. What this awesome answer doesn't explain you is that once you compile the code, if you select the sprite back on hierchy you'll notice two variables available, corresponding to the one you declare back in the code.

My BIG mistake was not understanding the folowing, in the example @Savlon said: "// Drag your first sprite here" wich I literally understood as "drag your sprite to the VS". Yes, I know, I'm a huge dumbass, please don't say it...

What I needed to do was draging the sprites to THE INSPECTOR, back on Unity3D. More specifically, to the new variable available on the sprite.

I also solve the first problem by setting the camera as many units on the Z axis as wide was the sprite. The problem was that the camera was too damn close to the sprite, so when the sprite turns it was behind the camera and therefore that part of the sprite was not rendered. The original suggestion of @Nosekills point me to the right direction.

Thanks to @Nosekill and @hexagonius for the help supplied.
> 0 votes

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


# Question
Title: Collision Detection algorithm using Line Detection
For a 2D physics sandbox I am working on, I need a way of detecting detecting a collision using lines. This sandbox uses a class called `Particle`, which has a x and a y (stored as a struct called `vector2`) and a velocity, which also has a x and y. Previously, to find a collision, I tried to detect if the coordinates + the velocity was where another particle's coordinates + velocity was, and then I divided the velocities by the highest velocity, then checked all the velocities incrementally, to prevent tunneling. However, I could not get this to work, and I had suspicions it would be slow when velocities were very large. I now want an algorithm that detects whether two lines (one point is the coordinates, the other is coordinates + velocity) intersect, then put the particles one space before the collision. Since this algorithm is for a physics sandbox, it has to detect any collision, including, for example, if the two lines will collide but are parallel. For simplicity's sake, I won't post the `Particle` class code, so feel free to create the function using whatever variables you wish (as long as they're self-explanatory)

# Answer
> I now want an algorithm that detects whether two lines (one point is the coordinates, the other is coordinates + velocity) intersect

If I understood you correctly you want to detect the collision between lines. Two lines intersect if they have a matching pair of x/y coordinates.

For example, if we have `line a (y = 0.5x + 1)` and line `b (y = 0.1x + 3)`. we get the following four equations:

1. `y = 0.5x + 1`
2. `y = 0.1x + 3`
3. `x = (y-1) / 0.5`
4. `x = (y - 3) / 0.1`

From that you can check if these equations are true:

`y = 0.5x + 1 = 0.1x + 3`

`x = (y-1) / 0.5 = (y - 3) / 0.1`

If they are, you have an intersection, if not (i.e. 4 = 7), you don't.

This will check if two lines intersect, however, what you probably want is to check if two line segments intersect. As far as I am aware, you can't check that in `y = mx + b` form. You can, however, check it through parametric form:

`position = initialPoint + direction * scalar` where `initialPoint` and `direction` are vectors(in your case, vector2's).

You can do with this equation as I did in the previous example. If you don't know how to do it, it is shown at the top of SIGHT & LIGHT: how to create 2D visibility/shadow effects for your game

After you got the points, you can check to see if the scalar value of the intersection makes sense. I would use the magnitude of your velocity vector.

Finally, if you just want to restore the state if there is a collision, you can simply save it before the move, and if it collides post-move, restore it.
> 0 votes

---
Tags: c++, collision-detection, algorithm, geometry
---


# Question
Title: How to draw the simplest grid map OpenGL 1.0
I want to draw a simple black & white grid map, like that:

I have been searching for a way to generate tile, a tile map and tho and I want to draw this map and thats all. I mean that I want to draw it only once so it should be easy. I use OpenGL 1.0. How can I draw that and how should I draw - should I draw an Image and place it like a map, should I draw a tile and multiple it ?

# Answer
First of all, OpenGL 1.0 is **very** outdated. What you probably mean is, that you are using immediate mode. If you are still learning, I strongly suggest to adapt to modern OpenGL ASAP. Immediate mode is inefficient, as every time you draw a vertex, you have to do a driver/GL call, which is very expensive.

So, if you insist on doing it the immediate way, the simplest way I can think of is to:

1. Set viewport size and eventually clear the screen to black and a blank depth buffer
2. Load an identity matrix (no transformation)
3. Begin an immediate draw block
4. Draw vertical lines using coloured vertices.
5. Draw horizontal lines as well.
6. End the draw block and swap the front and back buffer if you are using a double buffered context.

```
glViewport(0, 0, windowWidth, windowHeight);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); //RGBA
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glLoadIdentity();

glBegin(GL_LINES);
glColor3f(1.0f,1.0f,1.0f); // White (RGB)
for( float x = 0; x < windowWidth; x += lineHDistance )
{
    glVertex3f(x, 0.0f, 0.0f);
    glVertex3f(x, float(windowHeight), 0.0f);
}
for( float y = 0; y < windowHeight; y += lineVDistance )
{
    glVertex3f(0.0f, y, 0.0f);
    glVertex3f(float(windowWidth), y, 0.0f);
}
glEnd();

wglSwapBuffers(); // Windows-way to swap buffers

```

Hope that helps!
> 1 votes

---
Tags: opengl, tilemap, maps
---


# Question
Title: Are these functions and parameters used in DirectX 11.2?
Functions and parameters like WINAPI, hPrevInstance, hInstance , PSTR etc are used in DirectX 11.2?

# Answer
The Direct3D 11.2 and the rest of the DirectX API's are based on COM interfaces, which does not use the Win32 API directly for their interfaces. **But!**

In order to create a context for D3D11, to handle mouse/keyboard input etc., DirectX needs to know which window you are using and which window to handle input from. As the Win32 API is responsible for window management, yes you can't get around using the Win32 API. Else, how would you create a window for your context?

In cases where a cross-platform GUI library is used for window management like Qt, GTK etc., you still need to extract a HWND handle for your window from these libraries as the D3D11 API operates on Win32 window handles (HWND) and again at this point, you are using the Win32 API.
> 1 votes

---
Tags: directx, directx11
---


# Question
Title: Finding neighboring coordinates on offset tile map
I have a grid of hexagonal tiles. Every other row is slightly offset for visual reasons. Imagine a player touches any tile - I need to compare the coordinate of that tile, with any tile they touch next so that I can ensure they're right next to each other.

If the grid had no offset, I could simply ensure we were within 1 x and 1 y coordinate, but that fails in certain scenarios here.

I can get extremely close - the following code works in all cases, but still allows coordinates 3,2 and 4,3 to count as neighbors, among others with a similar mathematical relationship.

```
int diffX = abs(newCoord.x - lastCoord.x);
int diffY = abs(newCoord.y - lastCoord.y);

// Never allow jumping rows
if( diffY > 1 || diffX > 1 ) return false;

// Allow same columns
if( diffX == 0 || diffY == 0 ) return true;

return false;

```

A friend had an idea about combining the coordinates into single numbers and ensuring the neighbor was within a certain amount, but that fails for several combinations as well.

# Answer
If I understood you correctly, you only want to know whether two tiles, specified by their 2D offset coordinates, are adjacent or not.

For any question related to hexagon grids, I'd recommend to refer to the Hexagonal Grids page by Amit Patel. It contains the mathematical backgrounds as well as excellent animated interactive examples, and probably *Everything You Always Wanted to Know About Hex* grids (*But Were Afraid to Ask*)

Your grid type is called the "*odd-row horizontal layout*" there. Handling these grids properly is a bit tricky, because the relationship between a tile in an *odd* row and its neighbors, and the relationship between a tile in an *even* row and its neighbors are so different. So for nearly all computations, you have to take into account whether the tiles are located in odd or in even rows.

I had to solve a similar problem recently, namely computing the *distance* between two such tiles - but your case is just the special case of detecting whether they have a distance of 1. As recommended on the linked site, I solved this by converting the offset coordinates to cube coordinates, and using the cube coordinates to compute the distance. The final method is this:

```
int distance(int x0, int y0, int x1, int y1)
{
    int cx0 = x0 - (y0 - (y0&1)) / 2;
    int cz0 = y0;
    int cy0 = -cx0-cz0;
    int cx1 = x1 - (y1 - (y1&1)) / 2;
    int cz1 = y1;
    int cy1 = -cx1-cz1;
    int dx = abs(cx0 - cx1);
    int dy = abs(cy0 - cy1);
    int dz = abs(cz0 - cz1);
    return max(dx, max(dy, dz));
}

```

which you could use to implement your adjacency check by just returning

```
return distance(newCoord.x, newCoord.y, lastCoord.x, lastCoord.y) == 1;

```

The different treatment of odd and even rows is "hidden" in the `&1` that is done during the conversion: For odd values, this will be 1, and for even values, it will be 0.

Note that there may be a more efficient or elegant implementation for this special case, but when you want to do more with hex grids, such a distance function may come in handy as well.
> 3 votes

# Answer
You'll probably want distance eventually, so I'd use Marco13's solution.

However if you only need adjacency, there's a simpler way. Because every other row is offset, the logic is going to be different for odd and even rows. Look around 2,3 (odd y) and you'll see the x==2 column bends to the right like "\>". If you look at 2,2 (even y), the x==2 column bends to the left like "\<". So we'll need the code to treat odd and even rows separately. The `x` logic isn't symmetric for positive and negative so I won't take the absolute value:

```
int dx = newCoord.x - lastCoord.x;
int distY = abs(newCoord.y - lastCoord.y);

if (lastCoord.x & 1) {
    // Odd rows
    return (0 <= dx && dx <= 1 && distY <= 1) || (dx == -1 && distY == 0);
} else {
    // Even rows
    return (-1 <= dx && dx <= 0 && distY <= 1) || (dx == 1 && distY == 0);
}

```

The logic of the code here treats the adjacent hexes as either "・\>\>" or "\<\<・" (there are two bent columns and one extra hex), and the "\<" or "\>" part is the first (....) condition and the "・" part is the second (...) condition. (I'm not sure this explanation helps)
> 0 votes

# Answer
In my HexGridUtilities project (Open Source, MIT Licence) I found it both useful and performant to define the coordinates of a hex as a vector of four integers - the rectangular coordinates and the obtuse (120 degrees between basis vectors) coordinates. Although I initially used Lazy calculations, it turned out to be more performant to always track both.

The code to generate the adjacency list for a hex is the following extract from the library's HexCoords struct:

```
static readonly IntVector2D vectorN  = new IntVector2D( 0,-1);
static readonly IntVector2D vectorNE = new IntVector2D( 1, 0);
static readonly IntVector2D vectorSE = new IntVector2D( 1, 1);
static readonly IntVector2D vectorS  = new IntVector2D( 0, 1);
static readonly IntVector2D vectorSW = new IntVector2D(-1, 0);
static readonly IntVector2D vectorNW = new IntVector2D(-1,-1);
static readonly IntVector2D[] HexsideVectorsCanon = new IntVector2D[] {
  vectorN,  vectorNE, vectorSE, vectorS,  vectorSW, vectorNW
};

static readonly IntVector2D userEvenN  = new IntVector2D( 0,-1);
static readonly IntVector2D userEvenNE = new IntVector2D( 1, 0);
static readonly IntVector2D userEvenSE = new IntVector2D( 1, 1);
static readonly IntVector2D userEvenS  = new IntVector2D( 0, 1);
static readonly IntVector2D userEvenSW = new IntVector2D(-1,+1);
static readonly IntVector2D userEvenNW = new IntVector2D(-1, 0);
static readonly IList<IntVector2D> HexsideVectorsUserEven = new List<IntVector2D>() {
  userEvenN,  userEvenNE, userEvenSE, userEvenS,  userEvenSW, userEvenNW
}.AsReadOnly();

static readonly IntVector2D userOddN  = new IntVector2D( 0,-1);
static readonly IntVector2D userOddNE = new IntVector2D( 1,-1);
static readonly IntVector2D userOddSE = new IntVector2D( 1, 0);
static readonly IntVector2D userOddS  = new IntVector2D( 0, 1);
static readonly IntVector2D userOddSW = new IntVector2D(-1, 0);
static readonly IntVector2D userOddNW = new IntVector2D(-1,-1);
static readonly IList<IntVector2D> HexsideVectorsUserOdd = new List<IntVector2D>() {
  userOddN,  userOddNE, userOddSE, userOddS,  userOddSW, userOddNW
}.AsReadOnly();

static readonly IList<IList<IntVector2D>> HexsideVectorsUser = new List<IList<IntVector2D>>() {
  HexsideVectorsUserEven,HexsideVectorsUserOdd
}.AsReadOnly();
#endregion

/// <summary>Returns an <c>HexCoords</c> for the hex in direction <c>hexside</c> from this one.</summary>
public HexCoords GetNeighbour(Hexside hexside) {
  var i = User.X % 2;
  return new HexCoords(Canon + HexsideVectorsCanon  [(int)hexside]
                      ,User  + HexsideVectorsUser[i][(int)hexside] );
}

```

Similarly, taking advantage of the properties of the obtuse coordinate system, the range between two hexes is readily obtained with this method, allowing adjacency to be tested as the case when Range = 1:

```
/// <summary>Modified <i>Manhattan</i> distance of supplied coordinate from this one.</summary>
public int       Range(HexCoords coords) {
  var deltaX = coords.Canon.X - Canon.X;
  var deltaY = coords.Canon.Y - Canon.Y;
  return ( Math.Abs(deltaX) + Math.Abs(deltaY) + Math.Abs(deltaX-deltaY) ) / 2;
}

```

Using an integer matrix implementation IntMatrix2D the conversion between the rectangular and obtuse coordinate systems is down thus:

```
static readonly IntMatrix2D MatrixUserToCanon = new IntMatrix2D(2, 1,  0,2,  0,0,  2);
static readonly IntMatrix2D MatrixCanonToUser = new IntMatrix2D(2,-1,  0,2,  0,1,  2);

/// <summary>Create a new instance located at the specified vector offset as interpreted in the Canon(ical) frame.</summary>
public static HexCoords NewCanonCoords (IntVector2D vector){ return new HexCoords(vector, vector * MatrixCanonToUser); }
/// <summary>Create a new instance located at the specified vector offset as interpreted in the Rectangular (User) frame.</summary>
public static HexCoords NewUserCoords  (IntVector2D vector){ return new HexCoords(vector * MatrixUserToCanon, vector); }

private HexCoords(IntVector2D canon, IntVector2D user) :this() {
  _canon = canon;
  _user  = user;
}

```

Note that the **Norm** of the conversion matrices is 2 rather than 1, allowing the arithmetic to be quite elegant:

```
/// <summary>(Contravariant) Vector transformation by a matrix.</summary>
/// <param name="v">IntVector2D to be transformed.</param>
/// <param name="m">IntMatrix2D to be applied.</param>
/// <returns>New IntVector2D resulting from application of vector <c>v</c> to matrix <c>m</c>.</returns>
public static IntVector2D operator * (IntVector2D v, IntMatrix2D m) {
  return new IntVector2D (
    v.X * m.M11 + v.Y * m.M21 + m.M31,   v.X * m.M12 + v.Y * m.M22 + m.M32,  v.W * m.M33
  ).Normalize();
}

/// <summary>Returns a new instance with coordinates normalized using integer arithmetic.</summary>
public IntVector2D Normalize() {
  switch (W) {
    case 0:   throw new InvalidOperationException("IntVector2D is uninitialized.");
    case 1:   return this;
    case 2:   return new IntVector2D(X >> 1, Y >> 1);
    case 4:   return new IntVector2D(X >> 2, Y >> 2);
    case 8:   return new IntVector2D(X >> 3, Y >> 3);

    default:  return new IntVector2D(Math.Sign(X)*Math.Sign(W)*Math.Abs(X)/Math.Abs(W),
                                     Math.Sign(Y)*Math.Sign(W)*Math.Abs(Y)/Math.Abs(W));
  }
}

```

Yes, all the above is C# code, but translating to Objective-C should not be an undue hardship. My orientation convention for hexes is the transpose of yours, but this is easily addressed either with a transpose matrix, or swapping North with East and West with South.
> 0 votes

---
Tags: ios, tiles, objective-c, grid
---


# Question
Title: Changing FPSInputController controls through script
For a game I am making I would like the user to be able to change the controls (in game, NOT through the clunky launch window (which I disabled))

I have the system working, but don't know how to change the controls for my FPS controller. I am okay with writing my own version of the `FPSInputController` but I don't really know how to do that (the good way (using the `CharcaterMotor`))

I looked at the original `FPSInputController` script but that used axes (from the "conventional" input settings in Unity) and I don't really know how to do that with:

```
if (Input.GetKey(controls.forward))

```

# Answer
> 1 votes
I would create a separate InputMapping class that simply correlates different Unity input names with my own input names. Then other parts of the game (eg. a keyboard settings popup) can change these mappings (eg. what InputMapping.Forward maps to). Now change the FPS movement script to use the settings from InputMapping instead of referring to Unity inputs directly.

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


# Question
Title: Use Slick2D for standard application instead of game
I was wondering how well Slick2D would work when used for a custom rendered GUI in a standard application? A standard application not being a game. More like a text editor or 2D level editor that doesn't strictly need to render at 30/60fps.

More specifically, can Slick2D be configured to only render when a change has occurred in the user interface?

Background: I want to develop a level editor for a 2D puzzle game called Enigma that takes advantage of hardware rendering and cross platformness offered by Slick2D. I have decided that implementing the whole interface with Slick's rendering will give me the greatest flexibility when it comes to user interaction. However, rendering at a constant fps would be a bit wasteful, which is why I ask the question above about rendering only when needed.

# Answer
For any basicgame or gamestate that you write in Slick2D, you have to override the render method and so you always have control of what renders and when. You can build in logic to only render if something has been changed by a user at that point.

Alternatively, the call to render() in each loop is done from within the AppGameContainer (which extends GameContainer). In theory, I guess you could override the methods there to control when rendering takes place from that point rather than in a given basic game or gamestate (i.e. for the whole application as opposed to on a per gamestate basis).

Either way, that *could* be a lot of work if you have a lot of things to track in your level editor just to reduce the rendering overhead. If the application is PC-based then what is the problem with restricting FPS to something like 60 or 30FPS and letting it run? I am developing a game that has level menus in between live-action rounds and in the menu states the application barely uses any CPU at all. I see about 4% cpu usage when scrolling around a map on-screen for example (that's on a 2.4Ghz quad-core system, but it works just as well on an old laptop). Also, if your level editor is gui-based (i.e. a real-time, drag and drop affair) then won't you need regular graphic rendering anyway?

And finally... I have just tested stopping the rendering after setting up the screen in one of my applications and the screen just goes blank. So that leads me to assume that the render() method is also ensuring that the screen is refreshed or that something at the AppGameContainer or GameContainer level is clearing the screen before each frame. Overall, I'd recommend just restricting the FPS to something relatively low, e.g. using:

```
private AppGameContainer app;
app = new AppGameContainer(this);  // Create new game container in main class
app.setTargetFrameRate(60);

```
> 0 votes

---
Tags: java, slick
---


title: Unity: DontDestroyOnLoad

text:
# Question
Title: Unity: DontDestroyOnLoad
I'm viewing tutorial of Unity. In this tutorial, I see this piece of code:

```
public class GameControl : MonoBehaviour {
    public static GameControl control;

    public void Awake() {
        if (control == null) {
            DontDestroyOnLoad(gameObject);
            control = this;
        } else if (control != this) {
            Destroy(gameObject);
        }
    }
}

```

I don't understand above code very much. I just understand the first if. it means: when we first use this class, we will initialize control object and set attribute `dontdestroyonload` for this. But I don't understand second if, when will it meet condition `control != this` ?

Thanks :)

# Answer
This is the implementation of a very simple version of a programming pattern called Singleton. For more context, see Unity Singleton Pattern.

The basic idea is, the designer wants that there should only be one instance of the `GameControl` object. Therefore, before everything else (in `Awake()` function), the designer checks if the object is initialized or not. This first case of if the case that the object is not initialized, thus being the first instance of the object.

The second case is, the scene is changed and the same object is present in the new scene hierarchy, therefore `control` is already assigned and thus not equal to `this`. In this case, remove the newly created object from the scene.
> 2 votes

# Answer
The `control` variable is a static variable. The code you're looking at is for ensuring there's always a `GameControl` object in the world, and *only one*.

The first time a `GameControl` object is loaded, `control` is set. If a `GameControl` is ever attempted to be loaded again, it will not match the already loaded `control` object and will be destroyed.
> 1 votes

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


# Question
Title: How to represent ray and line segment in parametric form?(Visibility)
I am trying to implement this algorithm but am not sure how I am supposed to represent my ray and my line segments(walls).

For the r\_px/r\_py do I just use the position of the light? For the r\_dx/r\_dy do I just use the normalized vector pointing from the light position to the direction of the ray?

For the s\_px/s\_py do I just use the location of one of the two points of the line segment. Finally for the s\_dx/s\_dy do I just use the normalized vector pointing from the first point, to the second point?

Thanks!

# Answer
> 0 votes
mklingen's comment answered my question. I was correct in my initial guess.

---
Tags: raycasting, linear-algebra, intersection
---


# Question
Title: Why do games like Guild Wars 2 and Clash of Clans require you to manually collect loot?
For example, in world vs world in Guild Wars 2, enemies drop bags that you have to manually collect. Then you have to manually open the bag which may contain other bags that you have to open.

In Clash of Clans, you have to click on the gold mines to collect the gold. This same principle is in Farmville also.

Why don't these games put the loot directly into your bags or gold storage?

Are the players unlikely to notice that they are getting bags or gold unless they take a physical action?

Is there a behavioral reinforcing that's happening by requiring a physical gesture?

This irritates me but when I see it in multiple games it makes me wonder if there is a gaming concept behind it that is fun for some people (or if not fun, part of the "addictive" nature of the game).

# Answer
1. It builds on the primal instinct to gather. Humans used to be hunters and gatherers. Feeling gratification when collecting things is still deeply rooted in our psyche. That's why so many games have a game mechanic which can be described as "collect stuff".
2. Forcing the player to participate makes the reward stronger because the information that the player received a reward is conveyed using more communication channels. There are three communication channels you can use when you want to convey something to your player: Seeing, hearing and doing. Seeing that their score increased already gives a bit gratification. When it is accompanied by a pleasuring sound effect, the effect is amplified. But when you force the player to interact with the event, it becomes almost impossible to not notice.

By forcing players to make another click to get their reward instead of giving it to them automatically, the reward is noticed much more intensely.

By the way: A very simple way of reinforcing an event by forcing interaction is giving the player a popup message they have to confirm. A message "Welcome back! Here are 1250 gold from your mines" would also be a solution.
> 2 votes

---
Tags: psychology
---


# Question
Title: How to initialize once for all a static field of a custom editor in unity
I have a custom editor wich has a static field.

Suppose you have a static field of type `MyObject`:

```
public class myEditor : Editor {

...

private static MyObject myObj;

...
}

```

I'd like to initialize the field `myObj` directly on the same line of the declaration, but in this way I get a `TypeInitializationException`.

I could initialize the field `myObj` in the method `OnEnable`, but in this way I have to use an if statement like the following:

```
if ( myObj == null )
    myObj = new MyObject();

```

Is there a way to initialize `myObj` once for all without using if statement?

# Answer
> 0 votes
You could use a static constuctor

```
Static myEditor(){
    myObj = new MyObject();
}

```

This will run the first time you access the class

---
Tags: c#, unityscript
---


# Question
Title: How do I get GLEW to use my Nvidia GPU instead of an integrated Intel card?
I'm new to graphics programming, though not to coding generally. I've been learning opengl from the *OpenGL Superbible, 6th Edition*. I was trying out the shader examples from the book but couldn't get them to work. The logged error says approximately "incorrect #version". The book uses GLSL 4.3 core.

I ran `glewinfo.exe` and the generated text file said that the core OpenGL version on my system was OpenGL 4.0, but it was the stats of my integrated Intel GPU, not my Nvidia GT720m GPU. I'm pretty sure the nvidia gpu supports a higher opengl version.

How do I get GLEW to detect the high-performance GPU and make calls to the Nvidia drivers instead of the integrated Intel HD GPU?

---

A similar question has been asked there, but it concerned only running the program on the gpu. How do I tell which version of OpenGL the Nvidia GPU supports?

# Answer
> 2 votes
You didn't mention your platform, but assuming it is Windows, this blog post appears to address your exact question, between OpenGL 4.0 vs 4.3 on integrated vs nvidia gpus:

http://stevendebock.blogspot.com/2013/07/nvidia-optimus.html

It mentions using the "NVIDIA Control Panel" to change from autoselect to specifically the nvidia card. And that on a laptop, your selection would be influenced by battery life.

---
Tags: opengl, c++, nvidia, glew, intel
---


# Question
Title: How to detect a cursor inside a non-rectangle shape
How can I detect and do something if the cursor is inside a hexagonal shape? Is there any way other than detecting if it's in a rectangle area close to the shape of the hexagon? It would also have to work with a grid of hexagons, detecting each individually.

# Answer
> 1 votes
You can detect on which side of a line the cursor is by using a cross product. If the cursor is on the "inside" of all edges then it is inside of the hexagon. This only works for convex polygons though.

For a grid You can approximate is with a rectangular grid and then refine it by testing just a few lines.

# Answer
> 0 votes
One way of testing whether or not your point is inside a simple polygon is to use what is called a ray casting algorithm http://en.wikipedia.org/wiki/Point\_in\_polygon.

What you do is create a line that goes through the point you are checking, and count how many times it intersects with all of the line segments that make up your Polygon.

If the number of intersections is divisible by 2 then the point is outside the Polygon, otherwise it is inside. (Zero is even in this case)

I implemented this function in python using an arbitrarily large line segment for my 'ray'. And used two functions to test line segment intersection.

```
def counterclockwise(self, A, B, C):
    return (C[1]- A[1]) * (B[0] - A[0]) > (B[1] - A[1]) * (C[0] - A[0])

def segment_intersect(self,A, B, C, D):
    return counterclockwise(A,C,D) != counterclockwise(B,C,D) and counterclockwise(A,B,C) != counterclockwise(A,B,D)

def ray_cast(self, point, polyPoints, farAwayPoint):
    intersections = 0
    for i in range(len(polyPoints)-1):
        if segment_intersect(point, farAwayPoint,  polyPoints[i], polyPoints[i+1]) :
            intersections += 1
    if intersections % 2 == 0:
        return 'outside'
    else:
        return 'inside'

```

Notice I used point and farAwayPoint as my arbitrarily large segment. Obviously you could just choose any arbitrarily large point like (point.x + 10000, point.y + 10000) without making an extra function argument.

I hope this helps.

---
Tags: python, pygame
---


title: Rotation and timer at the same time

text:
# Question
Title: Rotation and timer at the same time
I have a project where I flip a card after 5 seconds, then I want to start a countdown timer of x seconds. After x seconds the card flips again.

I found a good example for the timer here, but that works inside a Update() method. My problem comes from the fact that the rotation of the card is made also inside the Update() method.

If I put the timer inside the Update() method, as soon as the Update() method is called the timer starts, and I don't want it to start it as soon as I call the Update() method, but when I want to start ip, wich is 60 seconds after I flip the card.

If I put the timer inside a method other than Update() then the timer start but never decrease.

```
 using UnityEngine;
 using System.Collections;
 public class Juego1Carta2 : MonoBehaviour
 {
     public float velocidadDeRotacion = 100.0f;
     public Sprite cartaBase;
     public Sprite cartaDelantera;
     private bool carta2Activada = false;
     private bool cartaDeLado = false;
     float tiempoDeJuego = 2;
     IEnumerator Esperar()
     {
         yield return new WaitForSeconds(5);
         transform.position = new Vector3(Screen.width / 2, Screen.height / 2 +GetComponent<SpriteRenderer>().bounds.size.y, 0);
         carta2Activada = true;
         Regresa();
     }
void Regresa()
{
    Update();
}
// Use this for initialization
void Start ()
{
    StartCoroutine (Esperar());
}
// Update is called once per frame
void Update ()
{
    if (carta2Activada)
    {
        transform.Rotate(Vector3.up * Time.deltaTime * velocidadDeRotacion);
        if (transform.eulerAngles.y >= 90)
        {
            SpriteRenderer Carta = GetComponent<SpriteRenderer>();
            if (Carta.sprite == cartaBase)
            {
                Carta.sprite = cartaDelantera;
                cartaDeLado = true;
                carta2Activada = false;
            }
            else
            {
                Carta.sprite = cartaBase;
                cartaDeLado = true;
                carta2Activada = false;
            }
            tiempoDeJuego = 60;
        }
    }
    tiempoDeJuego -= Time.deltaTime;
    if (tiempoDeJuego <= 0)
    {
        print("Fin del tiempo");
    }
    if (cartaDeLado)
    {
        transform.Rotate(Vector3.up * Time.deltaTime * velocidadDeRotacion);
        if (transform.eulerAngles.y >= 180)
        {
            transform.eulerAngles = new Vector3(0, 0, 0);
            cartaDeLado = false;
            carta2Activada = false;
            return;
        }
     }
   }
}

```

Is there a way to rotate the card and make a countdown timer at the same time?

I'm sorry, maybe this is a very obvious question but after 3 consecutive days working on this, I'm more than burnout...

# Answer
> 1 votes
You're using `Update` incorrectly. `Update` is called automatically every frame by Unity, on every component attached to every object (you can see this with the default comment that still exists in your code `// Update is called once per frame`). You don't need to call `Update` manually.

I see you're aware of having conditionals in the Update loop. What's wrong with having a `if(timerStarted)` conditional statement and putting all the timer code inside that? Then when you want to start your timer, just set `timerStarted` to true.

You can use use the coroutine like you are now, or simply have a different timer that sets `timerStarted` to true. Either one, will be activated in the `Start()` method, and 5 seconds later, `timerStarted` will be set to true, and will start being activated inside the `Update` loop.

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


# Question
Title: What's the difference between Rendering pipeline and compute shader?
What's the difference between rendering pipeline - https://msdn.microsoft.com/en-us/library/windows/desktop/ff476882.aspx and compute shader - https://msdn.microsoft.com/en-us/library/windows/desktop/ff476331.aspx ?

# Answer
The basic difference is simple: The standard Rendering pipeline configures the GPU so it processes data as vertices, then rasterizes them into points/lines/triangles, and then processes the result as pixels which are written into a buffer using optional blending.

A DirectCompute shader just takes data from a buffer and then process them in parallel to produce data in another buffer. The data could be visual, it could result in something that could be reused in the standard Rendering pipeline, or it could just be data that is used in some custom way that has not at all to do with graphics rendering.
> 2 votes

---
Tags: shaders, directx, rendering
---


# Question
Title: How do I make a time lapse in my code so it updates slower?
I have made some collision if statements, but they didn't work.

```
            birdbox3.X += 5;
            birdbox3.Y -= 5;

            if (birdbox3.Intersects(Banner1)) {

                birdbox3.Y += 10;

            }
            else if (birdbox3.Intersects(Banner2)) {

                birdbox3.Y = -birdbox3.Y; }

```

So if we take the first statement, the box is initially on the left down corner. According to my code, it would ideally be going right+up in my game, once it hits the banner on the extreme top, it should go down+right, thus both the X and the Y positions will increase. But what happens is that is starts bouncing really fast, after debugging I realised it was forever stuck in the first if, it's almost as if it collides 2 times, reverting Y to its initial movement, colliding a 3rd time, and doing the process over and over.

Which brings us to the question, how can I make the Update code run a tad bit slower, or after half a second or such passes, so when it runs, it doesn't misinterpret collisions?

# Answer
I have found the solution to this somewhere else. Adding a bigger if statement such as this :

```
private int elapsedTime = 0; //Declared at class level

public override void Update(GameTime gameTime)
{
    elapsedTime += gameTime.ElapsedGameTime.TotalMilliseconds;

if (elapsedTime > 500)
{
    elapsedTime = 0;
    birdbox3.X += 5;
    birdbox3.Y -= 5;

    if (birdbox3.Intersects(Banner1))
    {
        birdbox3.Y += 10;
    }
    else if (birdbox3.Intersects(Banner2))
    {
        birdbox3.Y = -birdbox3.Y;
    }
}
}

```

easily splits frames apart from each other, which helps with handling such issues, additionally this code sort of goes too far down the Y axis, so it goes further than the banner before it actually tests for it. I hope this helps anyone running into the same problem.
> 0 votes

---
Tags: xna, 2d, collision-detection, physics
---


# Question
Title: How to rotate an object to face another in Unity?
I'm having an issue where I can't seem to rotate my bullet appropriately whenever I spawn one. I currently have a capsule prefab I am testing with. I spawn it with the following code.

```
        GameObject b = (GameObject)Instantiate(Resources.Load<GameObject>("Prefabs/Bullet"));

```

I am using the following code to try and orient the bullet so that it lays along the imaginary ray between it's spawn location and the centre of the target.

```
    void Start() {
    go = InputController.instance.hit.transform.gameObject;
    transform.position = new Vector3(transform.parent.position.x, transform.parent.position.y - 5, transform.parent.position.z);
}

void Update () {
    transform.LookAt(go.transform.position);
    Vector3 rotation = transform.eulerAngles; //THIS IS THE LINE I NEED TO ALTER
    transform.rotation = Quaternion.Euler(rotation);
    transform.position = Vector3.MoveTowards(transform.position, go.transform.position, SPEED * Time.deltaTime);
    Debug.DrawRay(transform.position, transform.forward * 10000000, Color.red); //DEBUGGING
    Debug.DrawRay(transform.position, transform.up * 1000000, Color.green); //DEBUGGING
}

```

Essentially the issue I am having is how I can calculate the rotation of the object based on the two I have available.

As you can see the line that I can't seem to calculate is the second line of the Update method, what it needs to do is orient the `Vector3.up` direction of the object to run along the `Vector3` created by linking its position with the target location.

Interestingly the bullet is already laying horizontally but the `LookAt` method changes its rotation so I just need to fix it but I'm not sure on the math to do that.

# Answer
`LookAt` definition:

```
 public void LookAt(Transform target, Vector3 worldUp = Vector3.up);

```

The default orientation, `Vector3.up`, it's not correct in your case (that's why the bullet is oriented upwards). Use:

```
transform.LookAt(go.transform.position, Vector3.right);

```
> 2 votes

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


# Question
Title: What are names like "net.minecraft.blocks" called?
I'm trying to find these types of names for certain Minecraft blocks to add them to a block whitelist for one of my mods. Is there an actual name for these? If not, how would I go about finding a list of or searching for them?

# Answer
> 3 votes
These are **java package namespaces**, based on the conventions for that language. See this question: https://stackoverflow.com/questions/2661698/java-com-package-namespace .

Namespaces are used to group together and scope different code components within a project.

---
Tags: minecraft-modding, modding
---


# Question
Title: How can I hide game asset files in my release build?
My SFML 2.0 release build has a file path to game assets relative to the *.exe* file, so folders such as *Fonts*, *SoundEffects*, etc. are explicitly listed in Windows Explorer with the *.exe*. I'd like to somehow have these game asset folders not appear in Explorer.

I know I can mark the folders "hidden" in folder properties, but I've seen games that only have an .exe and nothing else, yet the game plays properly. How do I do that?

# Answer
> 1 votes
The games that have nothing but an .exe have compiled their executable with the assets inside. This is generally poor practice. By embedding your assets into the executable, they will stay loaded into memory while the program is running, even when not in use. For your scale and with modern machines this might not be much of an issue, but as the executable gets larger, this can be an extremely large and unnecessary performance sink.

Similarly, keeping your assets separate enables the program to load into memory much faster as only the necessary data is put into memory on launch.

To give you an extreme example, think of a game like Deus Ex: Human Revolution. If it was all compiled into an executable, it would consume somewhere in the area of 8GB of memory at any given moment. However the recommended specs suggest 2GB of memory. These recommended specs are usually the maximum amount of data that the game may need stored in memory at any moment. 2GB "occasionally" is a lot better than "8GB all the time"

As for the actual process of embedding the assets, it depends a lot on how exactly you're developing. Many IDEs have functionality that will do it for you. In your situation it probably isn't a big deal for convenience sake, but a much better method would be to have an installer that extracts the assets and necessary executables for the user.

---
Tags: sfml, release, filesystem
---


title: How to move dashes towards target?

text:
# Question
Title: How to move dashes towards target?
Would you know how to create a dash line that moves towards the direction of the target, and if it collides with a wall, goes to the opposite angle? I have seen atan2 but I am not sure what it does, and I am quite confused about the movement of the dashed line. A point can be found with cos() and sin() depending on a radius... should I change the radius to place each dash? Then how to move them with the same speed?

Example here :

Any advice would be much appreciated.

Thanks

# Answer
You get the path the same way you'd move the object when you shoot it. Just have a tight loop that simulates the movement of the object and keep track of the position every so often. Now you have a list of positions, if you draw a dot at each position, you have a dotted line the represents the path of the object if it were to be shot from that angle.
> 3 votes

# Answer
Byte56's answer is very good, especially for the example image given where simulating the movement of each "ball" in the line will work well. I'll give you an alternative idea however which might work better, or might be easier to implement if you are trying to work with a dashed line (with or without animation), something like `-- -- -- --`

1. Calculate the angle at which your dashed line is aimed, and the distance (T) it should extend from the start (call it point S).
2. Check for an intersection with the wall(s) you have present. There are lots of ways to do this, for example see this question.
3. If there is no intersection, simply draw your line with whatever tools you use in your engine.
4. If there *is* an intersection (call it point I):
    1. Draw the first section of your line between the start point and the intersection point SI, as in 3.
    2. Calculate the angle for the 2nd line segment by reflecting it in the surface you have intersected (see for example this question.
    3. Calculate the remaining line distance (T - SI)
    4. Draw the remaining line segment from point I with the appropriate angle.
5. Repeat 2 - 4 if more intersections are possible.

As for animation in this case, that heavily depends on how you are drawing the line. If you are using a "dashed" texture you may be able to achieve this by:

* Tiling / Repeating the texture along the length of the line and then "animating" / adjusting the texture offsets each frame such that you achieve the illusion of the dashes moving along the line.

Otherwise, if using vectors etc.

* By similarly drawing the individual dashes based on some "offset" from the beginning of the line, and then moving this offset over time.
> 2 votes

---
Tags: 2d, mathematics, angles, trigonometry, spritekit
---


title: Getting a Ranged AI "In Range" to shoot

text:
# Question
Title: Getting a Ranged AI "In Range" to shoot
In my game, ranged units and melee units have the same behavior. Ranged units try to maintain a fixed distance `r`, from their targets. If they're within `r + d` of the target (where `d` is a small value) they stop and shoot it. Note that this means the ranged unit can't be *closer* than `r - d`. Melee units are the equivalent of ranged units, but with `r` set to zero.

Right now, my AI for ranged units is as follows:

1. Find a path to the target using A\*.
2. Walk along the path until you are within `[r - d, r + d]` of the target.
3. Stop and shoot. If the target is dead, quit.
4. If you are still within `[r - d, r + d]`, goto 3.
5. Otherwise, move away/towards the target until you are within `r + d` again. Goto 4.

Here's a sort of diagram.

My problem is, if there are obstacles and the target moves, step `5` causes a lot of problems. Ranged units will end up backing into walls, unable to shoot. If instead of going to step `5` I go back to step `1` (planning a path), the problem still isn't solved, because walking toward the target will only decrease the range, not increase it.

How can I get ranged units to successfully follow and shoot their targets?

# Answer
> 3 votes
There is really nice article at Rogue Basin on Dijkstra Maps about the problem you are encountering. This kind of "exploit" can be easily overused, cornering range units, while they are try to flee, they really stuck and can't move away.

The article describes making "negative" Dijkstra maps. You create normal Dijkstra map, multiply result by value -1.2, and pass that value back through same function. You will get map with negative values which negative values showing most optimal range away from player. Basically you will have your A\* map for approaching algorithm and negative Dijkstra map for flee.

My own implementation shows really nice AI routines, removing exploit noticed above. When enemy is cornered in small room, he will try to pass you trying to flee to space which have exit, and then again shoot at you.

# Answer
> 6 votes
First think of what you would do as a player (and/or ask others what they would do) and then try to program one or more of those strategies.

There are probably several situations where a simple rule won't be a good idea to follow. This is actually a good thing, because otherwise your game would be fairly pointless to play as a human. Having an AI that can respond to many situations in interesting and challenging ways that make sense often makes all the difference between an interesting fascinating game, and one that seems very predictable and artificial.

In this case, consider that it is interesting and good for a melee unit to be able to out-maneuver a ranged unit in this way, pinning it against an obstacle. The only question is what you want the ranged unit to do when that happens. It might be good if it has a random choice between possible approaches.

If it makes sense in your game world, you might have the ranged unit detect when it would move to a wall, and if so, prepare a melee weapon and fight as a melee unit at least until it was another option.

If it doesn't make sense, the ranged unit who is trapped could at least try to run away (a\* variation to nearest place that is far enough away, or safest overall for current situation - perhaps by running towards nearest friendly melee units), or even surrender if really cornered and helpless.

For an RTS game with many units, it may make sense to keep a pathfinding map for each side which rates each part of the map for how good it is for your ranged or melee units to be there, based for instance on where the enemy threats are. You can update that one map gradually (nowhere near every frame or it will take a lot of unneeded processing), and use it for tactical pathfinding like this. For example, for rating how good a spot is for ranged units, you can say it's bad if there are enemy melee units too close, unless there are some friendly melee units there too, but it's good if there are enemy targets somewhat nearby, and it's a little bad if there is too much terrain nearby that limits fire or movement.

---
Tags: ai, path-finding
---


# Question
Title: Can someone explain to me the difference between 2 XNA methods?
I was recently trying to make a boucing ball off the environment walls. I apparently had everything correct, except for one thing, that I corrected stupidly, which made my code work, but I don't understand why.

So I had set the value of a 2d vector's X and Y inside `protected override void Update(GameTime gameTime)`; this vector was what I would add to the object's X and Y so it could move according to whatever logic.

But it didn't work, the fix to this problem was to apparently declare the vector's values inside `protected override void LoadContent()`.

So can anyone explain to me, what is the difference between declaring your variables/constants inside these two methods? And why?

EDIT : Wrong Sourcecode :

```
  protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);

        // Loaded content
}
 protected override void Update(GameTime gameTime)
    {

        // Allows the game to exit
        if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Escape))
            this.Exit();

         //Code logic

            movement.X = 5;
            movement.Y = 5;
            birdbox3.X += (int)movement.X; //this variable was declared outside of any local field as a rectangle

            if (birdbox3.X <= 0)
            {

                movement.X = -movement.X;
            }
            else if (birdbox3.Y <=0)
            { movement.Y = - movement.X;
            }
            base.Update(gameTime);
        }

```

So when I would run this code, the birdbox3 would just stop when the if statement is fulfilled. The correct version would be to cut the

```
            movement.X = 5;
            movement.Y = 5;

```

and paste it into `LoadContent()` instead. The problem is I do not know why.

# Answer
> 0 votes
Assuming "LoadContent" gets called once at startup and "Update" gets called every frame, your issue is probably because the ball's X and Y coordinate got set to 5 every frame in the update method, therefore, it wouldn't be moving around freely...

If it gets called once in the LoadContent method then it does not continually update the X and Y position to be at position X:5 and Y:5.

Setting the position of x and y in the once called "LoadContent" method allows for the movement logic to operate. Setting the position in "Update" would override your movement logic.

:)

---
Tags: xna, c#, logic
---


title: 2D indicator for Rotation in 3D space

text:
# Question
Title: 2D indicator for Rotation in 3D space
This is the view from my spaceship. It can move around in 3d space and turn up, down, left and right.

The planet Earth on the top right is selected. Now I want to create the red arrow to always point to the direction of Earth even if my ship is facing away from it.

this is my code so far

```
//These are euler angles
Vector3 wantedheading = SelectedObject.transform.position - Statics.Player.transform.position;
Vector3 curentheading = Statics.Player.transform.localRotation.eulerAngles;

Quaternion qwanted = Quaternion.Euler(wantedheading);
Quaternion qcurent = Quaternion.Euler(curentheading);
Quaternion qMove = Quaternion.FromToRotation(curentheading, wantedheading);

```

but now I have a 3d rotation... what do I do to make it into a 2d rotation always pointing to the shortest direction to the planet?

# Answer
When you have a vector from your spaceship to the earth you can just calculate the projection of the vector onto your 'camera plane'. You can normalize this vector and you have the direction the arrow should point to.

So you can use what you already have, rotate a vector and project it onto the 'camera plane'.
> 1 votes

# Answer
You can create a 2D rotation from a 3D one by just ignoring an axis (usually Z).

```
Quaternion 3dRotation = Quaternion.Euler(myRotation);
Quaternion 2dRotation = Quaternion(3dRotation.x, 3dRotation.y, 0.0f, 3dRotation.w);

```

Using this method you can modify your rotation to ignore one or two axis.

Or, you could use the same aproach when working with the headings:

```
Quaternion 2dRotation = Quaternion.Euler(new Vector3(myRotation.eulerAngles.x, myRotation.eulerAngles.y, 0.0f));

```
> 0 votes

---
Tags: c#, unity, vector, quaternion
---


# Question
Title: 2D character with baseball bat implementation in Unity
I'm making a 2D baseball game in Unity and I'd like to know how the player and the bat should be connected. For instance, if I use single sprite for both the player and the bat, then how should the collision between the bat and the ball be detected?

# Answer
> 1 votes
To keep it simple you can just use a fixed collider (as a component of your player or of any of its children so it moves with it) and enable it for a short time when your player swings the bat then immediately disable it. There are several ways to do it other than all-code with timers. For example if you have an animation (Animation not Animator) that plays when your player swings, you can simply add a curve for the BoxCollider.Enabled value (assuming your collider is BoxCollider).

In the picture above the collider will be enabled between 0.20 and 0.43 as the entered values are, in order from the left: false, true, false, false. (Last false isn't needed but just to be safe).

Once you've done this, detecting the collision is done the standard way. Here's a nice tutorial in case you need.

---
Tags: unity
---


# Question
Title: How do I create and implement a sprite sheet for my SFML game?
I have a game I am currently working on, and I have created 6 16 frame animations for my player character. Currently each of these are saved as seperate .jpg files, which are about 1.5x bigger than I want them to be in game. Each animation has a different size for the image, so I have 6 different image sizes. For example, here is the first frame for two different animations:

So I have 6x16 images in a folder, and I want to create a sprite sheet out of them, which I can use in my c++ SFML game. When I create a spritesheet, using a tool like texture packer, I have the sprites in all sorts of positions on a sprite sheet, and I don't know how I can the proceed to implement them in my game. How can implement them such that they 1) Keep in the same position relative to each other in the game 2) Have it so that the game knows the bounding box for the current image that I can use as both a hitbox for collision, as well as the rectangle the game displays the sprite for.

How can I achieve this? My guess is some sort of data file attached to the sprite sheet, but I dont know how to create one.

Additional info: Some images are duplicated, such as my idle frame 2 and idle frame 16. I would like to be able to only put one of those on the sprite sheet.

# Answer
> 1 votes
Put all your frames into 1 image, then load that image into an `sf::Texture`. In your spritesheet class, have that texture (or a ref to it) as a member along with an array (vector) of `sf::IntRect` objects, which each represent the parts of the texture that the frames are from. When you want to draw a frame from your spritesheet, create a temporary `sf::Sprite` and use `sf::Sprite::setTextureRect` with the corresponding IntRect as input, then draw that temporary sprite.

As for keeping the same position relative to all frames ingame, you'll need to do that manually using an image editor.

See https://www.binpress.com/tutorial/creating-a-city-building-game-with-sfml-part-3-textures-and-animations/125 for a very simple example of this type of spritesheet.

# Answer
> 1 votes
As far as I know, this is possible using the `sf::Image` class:

```
sf::Image spritesheet;
spritesheet.loadFromFile("spritesheet.png");
int currentSprite = 2;
sf::Texture texture;
texture.loadFromImage (spritesheet, currentSprite*spriteWidth, spriteHeight);
sf::Sprite sprite;
sprite.setTexture(texture);

```

If you do this in a for-loop, you could create a fluent animation by increasing `currentSprite`.

For more information on spritesheets, you should take a look at the docunentation, or you should read *'SFML Game Development'*

In this book, you will see an example on an Animation class. This has a basic update function which updates the current texture. You could link this to some XML-file or a JSON-file, in which gou define each sprite in the spritesheet by it's height, width and the duration it should be displayed.

---
Tags: c++, sprites, spritesheet, sfml
---


# Question
Title: How can I avoid sending the full game state so often?
I'm making a real-time 2D MMORPG in Java. Currently data all surrounding NPCs' and players' data is sent so frequently that the client crashes—it can't handle the data quickly enough. I'm sending data so frequently to make sure the game state stays up to date.

Is there an alternative? Should I make it send information only when needed, like when health is lost or something moves, instead of updating the whole object every time? How do I do this?

# Answer
> 1 votes
NPC on a path only need to be sends periodically.

However instead of only the position you also send the speed and direction the NPC is going. That you only need to send the data a few times a second and the client can extrapolate the current position of the NPC.

Health should only be sent when it updates and once every few seconds as a sanity update.

# Answer
> 1 votes
Crashing? Does not make sense. You can send a lot of data nowadays. There is no reason using a lot of bandwidth would crash a properly implemented client. If it is literally crashing, you may need to debug some more.

## What to send:

You don't need to send everything.

Remember the client program is only used (normally):

1. To accept input from the user, parse it and send it to the server.
2. To render and display what the player is seeing.

You only need to send information about what is visible to the player. Creatures that are out of sight, don't need to be updated at all until the server decides there is a good chance they are visible again to the player (always err on the side of sending a little too much).

Stats that haven't recently changed, don't need to be sent at all. You normally only need to send the "diff" between the previous state and the current state. For that purpose you need to keep track of the last known update that was sent to the players. Movement doesn't need to be updated each frame. You could instead compute a spline that describes the npc movement to save space. If the npc is alerted and changes its behavior because of player characters then update about that.

# Answer
> 1 votes
Game states can be synchronised by sending "deltas"—messages that describe *how to get from one game state to the next*, rather than sending the whole state. You seem to have figured out that this is possible.

---

To get you started on the right path of thinking, here's a more concrete (but naïve) way that could be implemented:

In server code, store a `boolean` "change flag" for each property that you might want to send to a client. Whenever the property is changed, set the corresponding flag. On update, only send properties which flag is set, then unset all flags again. When the client receives any message, it overwrites the given properties on its own copies of the game objects, but doesn't change any of the properties that weren't mentioned.

This works well if your game world is small and all clients need to get all changes.

---

It might also be worth looking into event architectures, as they're a very effective and commonly used abstraction for synchronising just this kind of thing.

If your world is large, you might want to look into partitioning it into regions. Clients could then request a full state update when entering a region, but receive deltas about objects in *the nearby region only* while they remain there.

# Answer
> 0 votes
you should try to minimize the amount of data you're sending - only send what is needed. Like ratchet freak said, for movement you could only send the direction if it updates. health also only on update.

could you post a "log" of all things you're sending each time? We could then better help you to reduce it size.

---
Tags: java, multiplayer, online, data, synchronization
---


# Question
Title: Have several classes with a common interface, but still able to access MonoBehaviour methods through that interface?
In our project we used to have a PlayerObject class and then Unit and Building derived from that class. We recently started taking a look at Bolt, which requires classes that define objects that may have different states to inherit directly from a Bolt class. So Unit and Building can no longer inherit from PlayerObject.

This turns out to create a few problems, a significant portion of our game uses PlayerObject rather than Unit or Building to perform actions that are the same for both. Separating them would really throw a wrench into the program, since you now have to have methods that use both Unit and Building instead of just PlayerObject.

I thought making a common interface IPlayerObject, and defining common properties and methods in the interface and making Building and Unit both derive from IPlayerObject would do the trick. I did not think it through enough and came to find out that if I use IPlayerObject I can no longer access MonoBehaviour methods and fields (such as transform, or render).

Can I make this in such a way that I can use the IPlayerObject type, with a Unit or Building type and still have access to MonoBehaviour through that interface?

If not, is there a proper way to do this, past just adding in extra methods to handle Unit and Building types separately.

# Answer
> 1 votes
I guess you have two suboptimal options here. So my short answer would be:No, you cannot do this.

Either go the way of composition (as suggested in the comments) or design your IPlayer Interface. That, however requires you to write a complete Interface for MonoBehaviour. If you have done that, I don't think you'll going to be happy because you would basically have to implement all the MonoBehavior implementation again on the Class which inherits IPlayerObject.

---
Tags: unity, interface, inheritance, monobehaviour
---


# Question
Title: How should my game characters store their abilities/spells?
I'm new to game development and a bit confused about how to effectively store an object's access to certain spells/abilities.

The player and mob objects are all generated from the same class. However, each object may have access to different abilities and spells. How do I keep track of a specific object's access to these?

Example: My player object might have access to *Fireball* and *Haste*, while a goblin might have access to *Confusion*.

I followed the RogueBasin Python Libtcod tutorial, and I understand how to attach a spell function to scroll use. I'm just not sure how to emulate a character memorizing a spell and using it as an ability.

# Answer
> 4 votes
The idea is to have spell objects hold some reference to the in-code action you want that spell to do.

Python's first-class functions make this quite nice (I'll assume Python 2.7.x):

```
class Spell:
    def __init__(self, name, description, activationFunction):
        self.name = name
        self.description = description
        self.activationFunction = activationFunction
    def cast(self, gameState):
        return self.activationFunction(self, gameState)

# Create a function to be called when the spell is cast. Give it as many
# parameters as you like.
def activationFunction(thisSpell, gameState):
    print thisSpell.name, 'was cast at game state', gameState

# Pass the function to a spell when instantiating it
fireballSpell = Spell('Fireball','standard spam spell', activationFunction)

# Cast the spell (with a dummy value representing the gameState parameter)
fireballSpell.cast("zero")

```

This prints

```
Fireball was cast at game state zero

```

You could then store instances of `Spell` in some class `Creature` if you like. You could add a `caster` parameter to every spell to which the creature passes `self`, or whatever other parameters you'd like.

Instead of `def`ing the `activationFunction`, you could also create an anonymous function with `lambda`. (Though only if it fits on one line… Sorry if I got your hopes up.)

---

For language-completeness:

In JavaScript, Lua, CL, and other FP-languages or languages with first-class functions, the above works with few conceptual modifications.

For a similar idea in C#, Java, C++ and OOP-languages, the strategy pattern is a good analogue for this. (Some even write Python in this style. I wouldn't bother.)

In C or other system programming languages you *could* use function pointers, but those can quickly get fiddly to work with. It may just be best to declare one big function `struct SpellResult castSpell(...)` that takes all spell parameters, then `switch`es on a passed-in `enum spellType` specifying which particular spell was meant. Values of that `enum` could then be stored by other game objects, for passing to `castSpell`.

---
Tags: architecture, python, oop, roguelikes
---


# Question
Title: Dot based light mask with shader on sprites
So I have a scene, completely based on 2D sprites. I want to render "light sources" into a seperate frame buffer (so mostly dots around, for example, the centre of a flame) and then render that frame buffer with my "lighting" shader above my whole scene, causing the light sources to "tint" the surrounding pixels, mostly by blending a pixel with the light source's color dependant on it's distance to the nearest light source.

The question: What concepts should I apply here to get the results I want? What am I doing wrong right now?

I have here a few concept drawings:

The scene without lighting:

The framebuffer of the scene containing the light source (the top yellow pixel of the flame):

The result of rendering the framebuffer as a texture with the glow shader. I also "simulated" a 2nd buffer with a smaller radius and a yellow light at the same position.

Alternatively, and closer to my first approach to the idea, imagine the whole framebuffer of the 2nd pixel transparent but the dot at the center.

What I wasn't able to mock up quickly was a gradient of the lighting, dimming it at the edges and having it brighter at the center.

The current idea needs to conform this fragment shader's layout:

`#version 400
uniform sampler2D color_map;
layout(std140) uniform Sprite {
 vec2 position;
 vec2 size;
 vec2 position_in_texture;
 vec2 size_in_texture;
 float rotation;
};
in vec2 texture_coordinate;
layout(std140) uniform Color {
 vec4 color;
};
layout(location = 0) out vec4 out_color;
void main(){
 vec4 tex_color = texture2D(color_map, texture_coordinate);
 vec2 diff;
 vec2 norm;
 vec2 sample_coordinate;
 out_color = tex_color;
 int radius = 4;
 int count = 1;
 norm = vec2(radius/size.x, radius/size.y);
 for(int i=-radius; i < radius; i++){ //Sample each pixel around the one rendered right now and add it's color to the current one with a certain gradient factor
 for(int j=-radius; j < radius; j++){
 diff = vec2(i/size.x, j/size.y);
 sample_coordinate = texture_coordinate + diff;
 if(0.0 <= sample_coordinate.x && sample_coordinate.x <= 1.0 && 0.0 <= sample_coordinate.y && sample_coordinate.y <= 1.0){
 tex_color = texture2D(color_map, sample_coordinate);
 if(tex_color != vec4(0.0,0.0,0.0,0.0) && sample_coordinate != texture_coordinate && length(diff) <= length(norm)){
 out_color = (out_color * count + tex_color * (1.0 - (length(diff) / length(norm)))) / (count+1);
 count++;
 }
 }
 }
 }
}`

I am planning on making the radius variable by passing it as another uniform element. With what I am doing there, I don't get the results I am looking for.

Though through experimenting I got this glow-shader, which I like, but the edges of the logo are still a bit too dark though (left the passed frame above the original, that is right):

# Answer
> 4 votes
You're doing it wrong - very inefficiently. Instead of rendering lightsources to your "lighting framebuffer", render the lighting contribution. That would be a soft disk centered at your light source instead of a single pixel. Example disk:

... and you can render that as a sprite! (Additive blending, clamp to 1 for best results).

You can now bind that lighting framebuffer and just sample the texel location that you're interested in and you get the lighting contribution directly.

If you want to create the texture yourself, it's as easy as writing a shader like this: (run via shadertoy)

```
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    vec2 uv = fragCoord.xy / iResolution.xy;
    float d = length(uv - 0.5); // distance to center
    float c = 1.0-smoothstep(0.3,0.5,d); // apply smoothing curve
    fragColor = vec4(c,c,c,1.0);
}

```

---
Tags: 2d, shaders, glsl, lighting
---


# Question
Title: Do I have too many colliders on my screen?
I'm running into a situation where my frame rate drops from 70 FPS (on my desktop computer) down to 5 FPS (on my iphone) and I'm trying to understand why. At the moment, I'm only drawing simple tiles, with box colliders attached to them, on the screen...

I've read that colliders are very expensive to have and I have 2400 of them on the screen at any given time. My questions are...

1. Do you think it's the number of colliders that are causing the slowdown?
2. If so, what are some ways I can optimize this?
3. If not, what do you think the problem is?

Thanks so much for your wisdom!

Also, it's worth noting that I'm using 2D Toolkit in Unity for drawing.

***UPDATE:*** I just removed all the colliders in the scene and I'm still experiencing the slowdown. Your thoughts?

# Answer
I'm new to this, but it would seem to me that if things aren't working, you should try something else. So maybe try a fewer colliders?

EDIT: You also might try using a fixed frame rate, like described here: http://obviam.net/index.php/the-android-game-loop/ Maybe you can fix the framerate so it stays high

EDIT2: Maybe you have a memory leak? This article talks about that possibility on iOS: http://www.cocos2d-iphone.org/forum/topic/6641
> 1 votes

# Answer
Any time slowdown is an issue, the important thing to do is test and measure. There are a variety of tools available to do so, but even without a profiler you can do this simply by measuring the time different sections take via things like System.Diagnostics.Stopwatch (if using C#) or even the base unity Time information.

You've already determined the colliders, while very numerous, don't seem to be the cause of the performance drop between systems so see if you can rule out other large sections of your code, either by timing or by simply commenting them out and testing framerate again. Chances are you'll find a big chunk somewhere that suddenly brings the framerate up when you leave it out and you can then repeat the process inside that chunk until you've found the offending section.
> 1 votes

# Answer
I think Unity uses Box2d? IIRC from an old read box2d uses some sort of spatial trees so that inactive colliders should not consume much CPU power.

My guess is, check your draw calls which are very often the cause for lags on mobile, make the colliders invisible and see if it helps in your frame rate, good luck.
> 0 votes

---
Tags: 2d, collision-detection, unity
---


title: Inline-Building a World (SRT) Matrix

text:
# Question
Title: Inline-Building a World (SRT) Matrix
Currently, to construct a world matrix, I have the following code:

```
return FromScale(scale) * rotation.RotMatrix * FromTranslation(translation);

```

However, this is constructing three matrices, and then applying two multiply operations between them in order to assembly the final world matrix.

However, I'm pretty sure there must be an algorithm or listing for constructing the SRT matrix 'in-place', by doing the necessary multiplications for each matrix element first, and then simply assembling the resultant matrix from that.

However, I can't seem to find a reference for that anywhere; the closest I found was for an SRT transformation with a rotation around a single axis.

Can anyone show me how to make an 'inline' SRT matrix? Or TRS, I don't mind. Row-major or column-major is fine, also.

# Answer
> 4 votes
A homogenous transformation matrix (aka a "World matrix") is a 4x4 matrix that defines the translation and rotation of one coordinate system with respect to another. It looks like this:

```
H = [xx, xy, xz, tx;
     yx, yy, yz, ty;
     zx, zy, zz, tz;
      0,  0,  0,  1];

```

*(Note on notation: This just lays out the matrix row by row. Each row is separated by a semicolon)*

The rotation part (the upper 3x3 block `[xx, xy, xz; ... zz]`) are the axes of the new coordinate system with respect to the old coordinate system as column vectors. In your case, this block is the variable you've called `RotationMatrix`. By *scaling* the rotation matrix uniformly, you can change the scale of the coordinate system.

The upper right 3x1 column vector `[tx, ty, tz]` is the translation of the new coordinate system with respect to the old coordinate system. It's the variable you've called `translation`.

To construct the matrix inline, do this:

```
 // A 3x3 scaled rotation matrix
 R = [x-axis * scale; y-axis * scale; z-axis * scale];
 // A 3x1 translation vector
 t = [translation];
 // The final transformation
 H = [ R ... t;
       0 ... 1];

// Therefore:
 H = [xx * scale, xy * scale, xz * scale, tx;
      yx * scale, yy * scale, yz * scale, ty;
      zx * scale, zy * scale, zz * scale, tz;
      0,  0,  0,  1];

```

This is assuming that you do not want the translation vector to be scaled.

---
Tags: mathematics, matrix, transformation
---


title: How to install Unreal Engine 4?

text:
# Question
Title: How to install Unreal Engine 4?
As soon as I found out that Unreal Engine 4 is now free, I decided to get it in order to tinker with it.

So I clicked on the blue "*Get Unreal*" button, signed up, and downloaded (and installed) the MSI installer (working on Windows here).

After the installation completed, the "*Epic Games Launcher*" launched, asking me to log in. Once logged in, I selected the "*Unreal Engine*" tab and was greeted by a page with several tutorials and demo projects for download, while the left side offered an orange button saying "*No engine installed*" and no option to click on it to install one.

After some time, I found this Unreal documentation explaining how to install the engine. According to it, the engine should start downloading the moment I log in to the launcher, which didn't happen.

What am I doing wrong? How can I install the Unreal Engine?

# Answer
After spending 10 minutes rummaging through documentations and Google, I finally succeeded in downloading the actual engine.

I was too focused on the orange button in the left pane, that I didn't try clicking on "*Library*", which is where I can choose to download the *Unreal Engine* version of my choice.

Simply click on "*Add Versions*" (hard to miss with its orange + sign) next to "*Engine Versions*". All that's left to do is selecting a version and clicking on the orange "*Install*" button, then wait for the download to complete.
> 26 votes

---
Tags: unreal-4
---


# Question
Title: How to figure out a vector based on 2 points that add up to a certain value
I am writing a game in which I am representing a velocity with a vector. I have a starting point and a point that I want the object to move towards at a certain speed. (I need the resulting vector's x and y values to add up to 800). I'm not sure what kind of formula I can use to accomplish this.

SO! I have a starting point. An "ending point". And need a vector whose x and y values add up to 800.

Here is the code I came up with:

```
dx = size.width / 2 - ball.position.x
dy = 800 - size.height / 2 - ball.position.y
ball.physicsBody?.velocity = CGVectorMake(dx, dy)

```

Although this appears to work, |dx| + |dy| != 800 and therefore the balls move at slightly different speeds. I'm sure I'm doing this wrong, but I'm not sure how to go about fixing it.

# Answer
> 1 votes
If you want a velocity of 800, you actually **don't** want x and y to add up to 800, you wan't the vectors length to be 800.

If you already have the correct direction, you could normalize the vector, which would then be a unit-vector (length 1) and multiply this unit-vector by any scalar (number) you want to get the length you need, for example:

```
int neededLength = 800;
vec2 velocity = normalize(direction) * neededLength;

```

If you **really** want x + y to be 800, you would need something like this:

```
vec2 direction; //Your direction-vector
vec2 out = new vec2;
out.x = direction.x / (direction.x + direction.y) * 800;
out.x = direction.y / (direction.x + direction.y) * 800;

```

---
Tags: ios, linear-algebra, spritekit
---


# Question
Title: Calling Shader Functions Inside Other Shaders
I'm new to OpenGL and GLSL, and bit confused about calling conventions of shader functions.

I'm trying to implement various procedural noise algorithms in GLSL. I'd like to have separate files for each noise and call these functions inside other fragment shaders.

Let say I have 2 files perlin.glsl and simplex.glsl.

perlin.glsl consists of pnoise2, pnoise3, pnoise4

simplex.glsl consists of snoise2, snoise3, snoise4

I have another fragment shader marble.frag which calls both **snoise2**, **pnoise2** and has a main()

1. How do I call fragment shader functions inside other fragment shaders?
2. Is this considered a good practice?
3. Can you think of a better alternative?

Thanks

# Answer
When uploading shader source, you may provide more than one string. The lines of the strings are concatenated into the full text source for the shader compiler.

You can thus emulate an include system (poorly) by putting the text of the required sources before the string with the main shader source.

This is the origin of the numbers before the line numbers you may see in shader error logs, it's simply the index in the string array that contains the faulting source.

If you do not control the shader compilation stage but control the program linking stage, you may also attach multiple shader objects of the same kind to a program. This however requires forward declaration of the functions used.
> 4 votes

---
Tags: opengl, glsl, fragment-shader
---