title: Tile-Based Deferred Lights Flicker

text:
# Question
Title: Tile-Based Deferred Lights Flicker
I'm using Tile-Based Deferred rendering and I have run into an issue with my lights flickering.

For a long time now I would just add all my lights at once and let the renderer do its thing eg. build a big light list while generating my world data and just upload the light list to the GPU and leave it there.

This wasn't an issue because I can render 1000's of lights and the render would just take it but because I'm not uploading them every frame the lights are static and that works well for world lights but now I want my projectiles\other things to have dynamic lights so I now upload the light list every frame after culling it with my octree\frustum of course and it works well apart from flickering as I pan the camera\frustum moves.

I update my mesh data the same way and meshes don't flicker so I'm kinda stumped, I have tried offsetting the frustum I use for culling so that my camera is about 25% inside the frustum rather than have the frustum start at the camera position and also widening the FOV.

If there is any code you need to see let me know.

Edits:

It happens to all the lights but I notice it much more as the light moves from in front of me to the sides of the screen, it seem like it would be the lights flickering off for a frame, I have been trying to debug it with the VS GFX tools but I only happens when the camera moves, as soon as I stop moving the lights are fine, I'm trying to cap a frame that shows the lights in the midst of a flicker so I can check for NAN's or Inf. I had a read of another answer for the same type of thing but his fix didn't do anything.

Last night I also tried changing the way I do my containment\intersection tests and still no change.

My directional light is fine no flickering there its just point lights\spot lights that flicker.

While writing this I had a brain storm, another thing I did over the weekend was offset my camera to a 3rd person view so maybe I'm passing my player object position to the renderer and not the actual offset camera position.

# Answer
> 0 votes
The root of the problem was that I had offset my camera to be 3rd person and in doing so I didn't update my camera bounds(bounding sphere) to match the new offset so the renderer was using the wrong positon value and that's why the lights were flickering more as I moved past them.

It was a simple change of just updating the camera bounds center vector to match the new offset camera position I use to build my view matrix.

```
Dim BasePos As Vector3 = _position
camera.CameraTarget = BasePos + CType(Vector3.Transform(New Vector3(0, 25, 1000), Matrix.RotationX(MathHelper.ToRadians(camera.Pitch)) * Matrix.RotationY(MathHelper.ToRadians(camera.Yaw))), Vector3) // offsetting the camera
camera.CameraBounds.Center = BasePos //this right here is the problem

camera.CameraBounds.Center = camera.CameraTarget //this is the fix, very simple

```

---
Tags: directx11, sharpdx, deferred-rendering
---


# Question
Title: How do I create my own GPU accelerated graphics API in C#?
I am creating 2D game engine in C# and I need some graphic API, so that user can draw sprites or convex vector shapes. I tried to use GDI+ for it. But I discovered that GDI+ is not GPU accelerated and it is too slow. XNA (a toolset for game developers form Microsoft) and it is GPU accelerated.

So I made a performance comparison between XNA and GDI+. XNA draws 2048x2048 px sprite in ~0.05 ms in GDI+ it takes about 400-500 ms. How to start? How to make my own graphic API (like DirectX/OpenGL).

# Answer
> 6 votes
Practically speaking, you can't.

The parts of D3D or OpenGL that provide the *hardware acceleration* are the drivers that talk to the underlying GPU hardware. For the most part these are provided by the manufacturers of the GPU hardware itself, because they know all of the ins and outs of how that hardware works.

A big portion of "creating your own" hardware-accelerated graphics API would be writing these drivers, which is a monumental undertaking, especially when you don't have all the proprietary information about the hardware. You can take a look at some of the open-source nVidia drivers to get an idea of the scope here.

And to write such a driver in C#, instead of C, would require an operating system that would accept such a driver, one that had a CLR runtime that operated in kernel mode. While such operating systems exist, they are largely toys or research projects.

# Answer
> 2 votes
*How to create your own GPU accelerated graphics API in C#?*

Short answer: You don't.

---

Long answer:

you said you tried GDI+ and XNA and you want do something like DirectX or OpenGL... well, why have you not tried a low level DirectX wrapper such as SlimDX SharpDX or a low level OpenGL wrapper for C# such as OpenTK?

Mono is building a Vulkan wrapper for .NET \- do you wanna try and help them?

Note: DirectX is not equivalent to OpenGL, as DirectX includes libraries not related to graphics. You can find comparisons and debates of which is better *elsewhere*.

Some game engines would wrap those and hide them behind their own API, in such way that the game developer can switch from one to the other without having to change all the code. If that is what you want to do, then you start by learning to use those and adding an absctraction layer ontop.

On the other hand, if what you want is to compete with DirectX and OpenGL... well, you could try inventing a graphics API, but then no hardware would support it... so you get no hardware accelaration (if get it to work). You could then decide to speak to the standards to support the wider range of hardware possible, turns out that by doing that you are using their API. So, no, you don't make your own GPU accelerated graphics API unless you have some control over the hardware (or you control a huge share of the operating system market to pressure those who do).

---
Tags: c#, xna, graphics-programming, hardware-acceleration
---


title: OpenGL 2D camera

text:
# Question
Title: OpenGL 2D camera
I'm trying to implement a 2D camera in modern OpenGL.

Before I moved over to OpenGL, I used SDL to make my games and their concept of a camera is by creating a camera quad and each time the camera moves, objects is being offset by this camera quad's position, giving the effect that the game world is scrolling when the camera moves.

I have a working 3D camera at the moment, which are using a view matrix and a look at-matrix to construct the final view projection matrix, which are then sent to the shader(s). So I know the concept of an actual camera.

I have checked a few tutorials and code examples that are using a orthographic matrix to create the 2D camera, followed by calling glViewport to construct the viewport of the game. However, none of the tutorials (and such) that I've watched is using the orthographic camera and the glViewport to actually scroll the camera and are instead only using it to render HUD objects and such.

How is a scrolling 2D camera usually made in OpenGL? Using the same concept of a 2D camera as SDL uses or are the matrices used to offset the objects being affected by the 2D camera? I am having a hard time understanding the concept of a orthographic camera aswell.

# Answer
OpenGL represents the screen as a 2x2x2 cube (-1 to 1 on each axis). So your camera matrix needs to squish the scene into that box. The box is then stretched to size of the viewport. So make sure your conceptual camera has the same aspect ratio as your viewport otherwise it will look squished.

If your conceptual camera is 320 pixels wide then your camera matrix needs to scale the scene by a factor of 2/320. The camera's offsets have to be scaled by this factor too, which makes life difficult. The easier way is to make a camera matrix that moves the conceptual camera into place and then invert the matrix.

So if you have a 320x200 camera centered on pixel 50,60 - create a scaling matrix that scales the scene 160x100x1 and then multiply by a translation matrix of 50,60,0. Take the resulting matrix and invert it and that's the camera matrix to give OpenGL.

Also don't forget that OpenGL has y-axis up like in algebra class and not y-axis down like SDL's surfaces.
> 0 votes

---
Tags: opengl, 2d, camera
---


# Question
Title: is mvc design pattern good for developing video games?
how mvc design structure works in game development and specially in unity game development.

I know what mvc is and how it works but in coding structure for game development specially in unity I don't know how it really works.

as you may know is it a good structure for developing video games? if its a yes, why and how it should be used?

thank you for helping

# Answer
> 2 votes
Unless you're making a game like solitaire or minesweeper, the design pattern that games typically use is called the game loop.

1. Read Inputs
2. Update State
3. Draw
4. Go to 1.

You can see that it has similarities to MVC, but there are some differences. MVC typically does all 3 steps per action. The game loop takes all actions then does all updates then draws everything. MVC is typically reactive to input. The game loop does all three steps every frame whether there was input or not (ai always needs to update).

---
Tags: unity, design-patterns, mvc
---


# Question
Title: Unity : how to Rotate GameObject back to Indentity position?
Hello i m trying to rotate my object smoothly over MouseButtonDown and rotate to identity position on MouseButtonUp and this code rotate my GameObject smoothly but it won't come back to identity position in time.

```
void Update ()
    {
        if (GameControls.Games.stateOfGame == GameControls.gameState.inStart || GameControls.Games.stateOfGame == GameControls.gameState.inPlay) {
            if (Input.GetMouseButtonDown (0) || Input.GetKeyDown (KeyCode.Space)) {
                StartCoroutine(FlyCat ());
            }
            if (Input.GetMouseButtonUp (0) || Input.GetKeyUp (KeyCode.Space)) {
                StartCoroutine (ResetCat ());
            }
        }
    }

    IEnumerator FlyCat()
    {
        animate.enabled = false;
        rigidbodyObject.bodyType = RigidbodyType2D.Dynamic;
        tempTimer = 0.0f;
        if (rigidbodyObject.position.y < maxUpperBorder) {
            rigidbodyObject.velocity = Vector2.zero;
            rigidbodyObject.AddForce (jumpForce);
            while (tempTimer < 0.5f) {
                tempTimer += Time.deltaTime;
                transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.Euler (rotationForce), Time.deltaTime * smooth);
            }
            rigidbodyObject.gravityScale = gravity;
            yield return null;
        }
        if (InstantiateOnce == true) {
            InstantiateOnce = false;
            GameControls.Games.GamePlay ();
        }
        yield return null;
    }

    IEnumerator ResetCat()
    {
        while (tempTimer > 0f) {
            Debug.Log (tempTimer);
            tempTimer -= Time.deltaTime;
            transform.rotation = Quaternion.Inverse (Quaternion.Euler(rotationForce));
        }
        transform.rotation = Quaternion.identity;
        yield return null;
    }

```

# Answer
> 3 votes
I'd usually approach it like this:

```
// Tracks whether we have a movement in progress.
Coroutine _currentMovement;

// Interrupts the current movement, if any, and starts a new one.
void StartMovement(IEnmumerator movement) {

     if(_currentMovement != null)
         StopCoroutine(_currentMovement);

     _currentMovement = StartCoroutine(movement);
}

// I pass the duration of the transition as an argument.
// That way it's local to the coroutine and I don't get side-effects
// from modifying a shared member variable in other code.

// Let's also add a parameter for the position to blend back to.
IEnumerator BlendBack(Vector3 homePosition, float duration) {

    // Keep track of where we started from.
    Quaternion startRotation = transform.rotation;
    Vector3 startPosition = transform.position;

    // Over the course of duration seconds...
    for(float time = 0f; time < duration; time += Time.deltaTime)
    {
        // Compute our progress through the transition, between 0 and 1
        float t = time/duration;

        // Blend smoothly between the start and end rotation using this progress.
        transform.rotation = Quaternion.Slerp(startRotation, Quaternion.identity, t);

        transform.position = Vector3.Lerp(startPosition, homePosition, t);

        // Wait for the next frame.
        yield return null;
    }

    // Finish any leftover fraction from the last run of the loop:
    transform.rotation = Quaternion.identity;
    transform.position = homePosition;

    // Mark this movement as complete.
    _currentMovement = null;
}

```

Or, if you're using physics, you can replace `transform.rotation = ...` with `rigidbody.MoveRotation(...)` and `position` with `MovePosition`

By using `StartMovement(BlendBack(homePosition, duration))` or `StartMovement(SomeOtherMovementCoroutine(foo, bar))` you can transition from one move to another, without the two sets of movement logic overlapping & fighting over the object's transformation. ;)

# Answer
> 0 votes
```
IEnumerator RotateSmooth() {

        iTween.RotateTo(gameObject,rotationForce,Time.deltaTime * smooth);
        yield return new WaitForSeconds(0.5f);
        iTween.RotateTo(gameObject,Vector3.zero,0.5f);

    }

```

This exactly solves my problem. Thank you @DMGregory

---
Tags: unity, physics, rotation, quaternion, rigidbody
---


# Question
Title: How do I load/use substances with libgdx?
I've been looking at some substances (.sbsar file format) but I have no clue how to load or use these files. The links I find brings me to Unity & Unreal Engine, but if I search up anything related to libgdx or opengl, I can't get any results. Does anyone know how I can use these textures in my libgdx java game?

# Answer
> 0 votes
LibGDX isn't as advanced in 3D as Unreal Engine 4 by a long shot. Substances do not exist in LibGDX, you can use the `Material` for this. Out of the box it comes with Difuse, Specular, Glow, Reflection and some other maps. I think you need to roll your own shader for something like a normal map. LibGDX simply does not offer you the power UE4 does with shaders so if you want to create high-end 3D models and environments I would leave LibGDX and go with something like UE4.

---
Tags: opengl, java, libgdx
---


# Question
Title: How to make the 2D sprites into 3D game objects?
I got this code and this code uses sprite as chess pieces. All I want to do is to use 3D game objects instead of sprite. And I am confused on how to do that. I already got the code and it is using sprite as chess pieces. I want to use 3D models as chess piece instead of 2D sprites. How do I convert these 2D sprites codes to 3D codes? I already used using public GameObjects as a solution but there are too many errors happening.

Here is my code

```
public class LuxChess2D : Engine {

  /// <summary>
  /// Pieces set.
  /// </summary>
  [Serializable]
  public class PieceSet
  {
    public Sprite Pawn;
    public Sprite Bishop;
    public Sprite Knight;
    public Sprite Rook;
    public Sprite Queen;
    public Sprite King;
    public Sprite Square;
  }

  /// <summary>
  /// White pieces.
  /// </summary>
  public PieceSet WhitePieces;

  /// <summary>
  /// Black pieces.
  /// </summary>
  public PieceSet BlackPieces;

  [HideInInspector]
  public Transform[] SquaresObj; //From 0-to 63
  public Transform CanvasTr; //Squares should be parented to the canvas
  public GameObject SquareObj; //Square prefab
  public Sprite NoPieceSprite; //If there is no piece then use this sprite for the piece image - should be transparent

  /// <summary>
  /// Comuputer thinking time. He will 'force' stop after this time.
  /// </summary>
  public int ComputerThinkingTime = 3;

  /// <summary>
  /// Starting FEn.
  /// </summary>
  public string StartingFen = FEN.Default;

  [HideInInspector]
  public int DragingFrom; //We are dragging piece from this position

  public UnityEvent OnWhiteTurn; //Event
  public UnityEvent OnBlackTurn; //Event

  //UI
  public Text GameStateUI;
  public InputField FENOutputUI;

  private void Start() {

    DragingFrom = -1; //Not dragging from any square
    SquaresObj = new Transform[64]; //Inti squares

    for (int i = 0; i < 64; i++)
    {
      int x= i%8;
      int y = i/8;

      //Create square
      GameObject obj = Instantiate(SquareObj, Vector3.zero, Quaternion.identity) as GameObject;
      obj.transform.SetParent(CanvasTr, true); //set parent
      obj.transform.localPosition = new Vector3(-244 + 64 * x, 204 - 64 * y, 0); //Position it

      PieceMover pm = obj.GetComponent<PieceMover>(); //Get piece component
      pm.index = i; //Set index
      pm.manager = this; //Set manager reference

      if ((i + y) % 2 == 0) //Change sprites according to squares
      {
        obj.GetComponent<Image>().sprite = WhitePieces.Square; //White square
      }
      else
        obj.GetComponent<Image>().sprite = BlackPieces.Square; //Black square

      //Save a square in a squares array at right index
      SquaresObj[i] = obj.transform;
    }

    //Calls the init in the engine class
    InitChess(StartingFen);

    //Updates the board changes
    UpdateBoard();
  }

  /// <summary>
  /// Updates all pieces based on board pieces.
  /// </summary>
  public void UpdateBoard() {
    //Initialize grid
    for (int i = 0; i < 64; i++)
    {
      int piece = GetPieceAt(i);

      switch (piece)
      {
      //Button will shrink texture, which creates much better 'piece' effect
      case Defs.WPawn: CreatePiece(WhitePieces.Pawn, i); break;
      case Defs.WBishop: CreatePiece(WhitePieces.Bishop, i); break;
      case Defs.WKnight: CreatePiece(WhitePieces.Knight, i); break;
      case Defs.WRook: CreatePiece(WhitePieces.Rook, i); break;
      case Defs.WQueen: CreatePiece(WhitePieces.Queen, i); break;
      case Defs.WKing: CreatePiece(WhitePieces.King, i); break;
      case Defs.BPawn: CreatePiece(BlackPieces.Pawn, i); break;
      case Defs.BBishop: CreatePiece(BlackPieces.Bishop, i); break;
      case Defs.BKnight: CreatePiece(BlackPieces.Knight, i); break;
      case Defs.BRook: CreatePiece(BlackPieces.Rook, i); break;
      case Defs.BQueen: CreatePiece(BlackPieces.Queen, i); break;
      case Defs.BKing: CreatePiece(BlackPieces.King, i); break;
      case Defs.Empty:
        CreatePiece(NoPieceSprite, i);
        break;
      }
    }
  }

  private Squares LastSquare = Squares.None;
  public override void OnTurnSwitched() //Turn was switched
  {

    //Who's turn?
    if (SideToPlay() == 1) //White
    {
      if (OnWhiteTurn != null)
        OnWhiteTurn.Invoke();
    }
    else {
      if (OnBlackTurn != null)
        OnBlackTurn.Invoke();
      ComputerPlay(ComputerThinkingTime); //Computer should play as black
    }

    GameStateUI.text = Regex.Replace(GameState().ToString(),"[A-Z]", " $0"); //Space before capital letter
    FENOutputUI.text = GetFen();

    //Check if in check
    Squares sq = IsInCheck();
    if (sq != Squares.None) { //If in check mark square
      LastSquare = sq;
      SquaresObj[(int)LastSquare].gameObject.GetComponent<Image>().color = new Color32(255,15,15,255);
    }
    else if (LastSquare != Squares.None) {//Remove last marked square
      SquaresObj[(int)LastSquare].gameObject.GetComponent<Image>().color = Color.white;
    }
  }

  private Vector2 origPieceSize = Vector2.zero;
  private void CreatePiece(Sprite piece, int index, float scale = 1f)
  {
    Image image = SquaresObj[index].GetChild(0).gameObject.GetComponent<Image>();

    //Get the size of the first piece and store it
    if (origPieceSize == Vector2.zero)
      origPieceSize = image.rectTransform.sizeDelta;

    image.rectTransform.sizeDelta = origPieceSize*scale;
    image.sprite = piece;

  }

  private Squares LastSquareFrom = Squares.None;
  private Squares LastSquareTo = Squares.None;
  public override void OnComputerPlayed(int from, int to)
  {

    //Mark the squares that piece traveled
    SquaresObj[(int)from].gameObject.GetComponent<Image>().color = new Color32(73, 35, 0, 255);
    SquaresObj[(int)to].gameObject.GetComponent<Image>().color = new Color32(73, 30, 0, 255);

    //Reset colors
    if ((int)LastSquareFrom != from && (int)LastSquareFrom != to && LastSquareFrom != Squares.None)
    {
      SquaresObj[(int)LastSquareFrom].gameObject.GetComponent<Image>().color = Color.white;
    }

    if ((int)LastSquareTo != to && (int)LastSquareTo != from && LastSquareTo != Squares.None)
    {
      SquaresObj[(int)LastSquareTo].gameObject.GetComponent<Image>().color = Color.white;
    }

    //Store marked squares
    LastSquareFrom = (Squares)from;
    LastSquareTo = (Squares)to;

    //Since board was changed by computer update board
    UpdateBoard();
  }

  public void Undo() {

    //Calls the engine undo move
    UndoMove();

    //Reset color
    SquaresObj[(int)LastSquareFrom].gameObject.GetComponent<Image>().color = Color.white;
    SquaresObj[(int)LastSquareTo].gameObject.GetComponent<Image>().color = Color.white;

    //Sinde the board has changed update the move
    UpdateBoard();
  }
}

```

# Answer
> 0 votes
You currently have a very tight coupling between your game logic and your game visualization. Your `CreatePiece` method does literally nothing but change an image (the method name itself is in fact quite misleading. It doesn't *create* anything. It *changes* an "Empty space" into a "Black Rook space". So a better name would be `ChangePiece`)

A better architecture would be to have a separate prefab for every type of chess piece and then handle the pieces on the board as `GameObject`s which are `Instantiate`d as children of the tiles when a new game is started, made a child of a different tile when a player makes a move and `Destroy`ed when taken by an opponent piece. The nice thing about this architecture is that the game object prefabs control how they are displayed. They can have a SpriteRenderer component, a MeshRenderer, a TextRender or whatever. The part of your code architecture which handles the actual game mechanics doesn't care.

With this architecture you could also add a script to each prefab which implements the movement rules for that chess piece. When you move all piece-specific game mechanics into the piece-prefab, you can very easily add new kinds of pieces to the game (you don't really want to make the 165745345th simulation of classic FIDE chess without any form of new gameplay ideas at all, do you?).

But if you would like to stick with your architecture, then all you need to do is replace the `SpriteRenderer` on your tiles with a MeshRenderer and a MeshFilter. If you want to change the color of a piece, switch out the material of the MeshRenderer. If you want to change the type of a piece, change the Mesh (3d model) of the MeshFilter.

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


# Question
Title: Directx 11 not drawing scene despite all math being correct
I have a graphics engine that i writing in Directx11 and I changed the way objects are drawn, and the way assets for the game are loaded. Everything in my draw call is set correct and I thought that it might be that the way the Buffers for the Vertices and the Indices are set but they seem to have the data set, same with my texture it is also loading so i have no idea why it is not drawing anything when the camera in pointed at where the object is set to be, and I have no translations set for the object.

```
//Clearing the Back Buffer
devcon->ClearRenderTargetView(backbuffer, Blue);
//Clearing the Depth Buffer
devcon->ClearDepthStencilView(zbuffer, D3D11_CLEAR_DEPTH, 1.0f, 0);
//Projection Matrix
D3DXMATRIX matProjection;
//View Matrix
D3DXMATRIX matView;
//Setting it to the only Viewport that i have set, it is a array because of an idea i have for later
devcon->RSSetViewports(1, &viewport[0]);

//Setting my projection Matrix
D3DXMatrixPerspectiveFovLH(&matProjection, (FLOAT)D3DXToRadian(45), (FLOAT)(SCREEN_WIDTH) / (FLOAT)SCREEN_HEIGHT,
    1.0f,
    200.0f);

//Setting my View Matrix
D3DXMatrixLookAtLH(&matView,
    &D3DXVECTOR3(0, 10, 0),    // the camera position
    &D3DXVECTOR3(0, 0, 0),    // the look-at position
    &D3DXVECTOR3(0.0f, 1.0f, 0.0f));

//VERTEX is custom struct that holds position as three floats, the surface normal as a custom VECTOR3 Struct, and two floats for the UV map
UINT stride = sizeof(VERTEX);
UINT offset = 0;
//Constant buffer for the Vertex Shader it holds the light, and direction of the main light, the ambient color, and also the rotation and final matrix for the object
CBUFFER cb;
//the light vector
cb.LightVector = D3DXVECTOR4(0.0f, 1.0f, 0.0f, 0.0f);
//A medium color for it
cb.LightColor = D3DXCOLOR(0.7f, 0.7f, 0.7f, 1.0f);
//A lower level for the ambient
cb.AmbientColor = D3DXCOLOR(0.2f, 0.2f, 0.2f, 1.0f);

//setting my primative topology as a triangle list, which is what is always use and has always worked
devcon->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
//allThingsToDraw is a vector which holds a stuct that all things that want to be drawn have and give to my main directx class to use to draw
for (int i = 0; i < allThingsToDraw.size(); i++)
{
    //Creating the Translation matrix, the position is set to 0,0,0
    D3DXMatrixTranslation(&matTraslate, allThingsToDraw[i].position.X, allThingsToDraw[i].position.Y, allThingsToDraw[i].position.Z);
    //The scale is set to 1,1,1 so that it is just a regular size
    D3DXMatrixScaling(&matScale, allThingsToDraw[i].scale.X, allThingsToDraw[i].scale.Y, allThingsToDraw[i].scale.Z);
    //All of the rotation at set to zero so that it has not moved in any way
    D3DXMatrixRotationX(&matRotateX, allThingsToDraw[i].roation.X);
    D3DXMatrixRotationY(&matRotateY, allThingsToDraw[i].roation.Y);
    D3DXMatrixRotationZ(&matRotateZ, allThingsToDraw[i].roation.Z);
    //Creating my world Matrix
    matWorld = matRotateX * matRotateY * matRotateZ * matScale * matTraslate;
    //My final matrix
    matFinal = matWorld * matView * matProjection;
    //The final matrix being placed into my Constant buffer
    cb.Final = matFinal;
    //The rotation matrix being placed into the constant buffer
    cb.Rotation = matRotateX * matRotateY * matRotateZ;
    //My Vertices buffer, this is loaded and then held in a ModelLoader class, and the model class grabs that pointer and that is what is used to drawn, i think that this might be where the problem comes in
    devcon->IASetVertexBuffers(0, 1, &allThingsToDraw[i].modelData->Direxctx11VerticesBuffer, &stride, &offset);
    //My indices buffer this is also held inside the modelloader class paired with the Vertices that it is going to be with
    devcon->IASetIndexBuffer(allThingsToDraw[i].modelData->Direxctx11IndicesBuffer, DXGI_FORMAT_R32_UINT, 0);
    //Sending my Shader my Constant Buffer
    devcon->UpdateSubresource(pCBuffer, 0, 0, &cb, 0, 0);
    //Loading my texture this uses a similar way to my model, and is loaded on the model after i load the model so that differnet textures can be loaded onto to different models
    devcon->PSSetShaderResources(0, 1, &allThingsToDraw[i].modelData->Texture);
    //I have this hardcoded to 36 because i am stil testing if this way works and i only have the one object that i am drawing
    devcon->DrawIndexed(36, 0, 0);

}
//After this function the swapchain->Present(0,0); is called

```

# Answer
You need to scale before rotating. Otherwise the model is skewed, possibly the point of not being visible.
> 1 votes

# Answer
Matrix Multiplication is not commutative as it represents functions compositions (for example, sqrt of x² is the same as (sqrt x)². Okay is example is not really good because it's not from linear algebra).

A rule to remember when doing 3D is the "SRT" rule, as an order of application. That means you must Scale first, then rotate, then translate.

In matrix multiplication, the order is reversed, and it makes T * R * S as the final matrix, where T is the Matrix of translation, R of rotation, S of scale.

> matWorld = matRotateX * matRotateY * matRotateZ * matScale * matTraslate;

I Believe that line is wrong, because you apply the scale and the rotation to your translation.
> 1 votes

---
Tags: c++, directx11
---


title: Calculate position on Isometric grid

text:
# Question
Title: Calculate position on Isometric grid
I created the following tile grid in unity3d: The blue dot is the absolute center point (0,0) of both scene space and tile map.

Now I am trying to calculate the X/Y position of points on the tile map ( the black coordinates). The red coordinates are positions in the scene space. Every calculation I make just gives me a wrong result. Is the tile map roatated the wrong way? Any help really apreciated!

# Answer
Looks like you want:

```
tileExtents = new Vector2(0.3f, 0.17f);

scenePos.x = tileExtents.x * (tilePos.x - tilePos.y);
scenePos.y = tileExtents.y * (tilePos.x + tilePos.y);

```

so we can solve these equations to get the result:

```
scenePos.x/tileExtents.x = tilePos.x - tilePos.y
scenePos.y/tileExtents.y = tilePos.x + tilePos.y

```

adding the two to get x:

```
scenePos.x/tileExtents.x + scenePos.y/tileExtents.y = 2 * tilePos.x

tilePos.x = (scenePos.x/tileExtents.x + scenePos.y/tileExtents.y) * 0.5f;

```

subtracting the two to get y:

```
scenePos.x/tileExtents.x - scenePos.y/tileExtents.y = -2 * tilePos.y

tilePos.y = (scenePos.y/tileExtents.y - scenePos.x/tileExtents.x) * 0.5f

```
> 3 votes

---
Tags: unity, mathematics, isometric, coordinates, grid
---


title: Linking my game forum to my game

text:
# Question
Title: Linking my game forum to my game
I am thinking of adding a special achievement in my game where if the player reaches a certain score in my game forum ( my forum is kind of like SE where you get score instead of rep when answering questions ) he then gets a reward in the game. I just want to know if it is even possible to do such thing as I want more players to participate in the forum. Thanks!

# Answer
It certainly is possible. In order to do that you would have to give your game the ability to somehow identify what forum account belongs to the player.

You could do that by having the player enter their username and password in the game options. Doing that just to get the achievement would be a bit bothersome, though. But you could justify this if your game actually offers an in-game UI for viewing your forum (which is another good way to drive more traffic to it, by the way).

Another option which would be more user-friendly would be to check if any of the web browsers the user has installed has a login cookie stored for your forum. But note that a game looking at the user's browser history is quite suspicious behavior.

After you identified the user's account, your game could then use a webservice provided by your forum to check if that forum account exists, if the password matches and if the forum account has the required post score.

Implementation details for all this depend on what forum software you are using.
> 1 votes

# Answer
Yes this is possible trough a webrequest. You sent a request to your web server to update the database. All you actually do is run a server side script, such as PHP, you feed it some additional post data and of course you need to verify everything that is being posted along with the request.
> 1 votes

---
Tags: unity
---


# Question
Title: How can I render images to multiple windows without creating double textures in SDL2?
Simply put: What is the simplest way to render an image to two different sdl2 windows?

I'm pretty new to SLD2, but I have a nice little level editor working. I then decided to move the area with edit tools to a separate window. I immediately got the following error:

> Texture was not created with this renderer.

Alas, it looks like each window needs to have its own `SDL_Renderer`, and each renderer needs to create its own textures for the images I want to display.

`IMG_LoadTexture()` needs a renderer and will only render the resulting texture to that renderer.

`SDL_CreateRenderer()` then needs a window as a parameter and doesn't seem to be able to ever render to another output window.

So does this really mean I have to create separate textures of each of my images for each and every renderer/window? Or is there a way to load graphics into textures that can be used by any renderer, or on any window?

# Answer
All right, so this is an interesting topic. As per this forum topic, this isn't natively supported by SDL.

However, with some minor tinkering I was able to setup a quick and dirty demo that loads a texture just once, for one rendering. I'll go through my setup step by step. Do note that you probably want to change most of the hardcoded stuff (such as the color masks for the surface) to dynamically chosen ones. These values work for me.

1. You setup your windows and renderers:

```
SDL_Window* window1 = SDL_CreateWindow("Window 1", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, 0);
SDL_Window* window2 = SDL_CreateWindow("Window 2", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, 0);

SDL_Renderer* renderer1 = SDL_CreateRenderer(window1, -1, 0);
SDL_Renderer* renderer2 = SDL_CreateRenderer(window2, -1, 0);

```
2. You load your texture for your first, or main, renderer:

```
SDL_Texture* texture1 = IMG_LoadTexture(renderer1, "path_here.png");

```
3. Now, this is where stuff gets interesting. You create a streaming texture for the second renderer and a target texture for the first:

```
SDL_Texture* texture2 = SDL_CreateTexture(renderer2, SDL_GetWindowPixelFormat(window1), SDL_TEXTUREACCESS_STREAMING, 640, 480);
SDL_Texture* target = SDL_CreateTexture(renderer1, SDL_GetWindowPixelFormat(window1), SDL_TEXTUREACCESS_TARGET, 640, 480);

```
4. Finally, for easier access, we create an `SDL_Surface` that we'll be using as a buffer.

```
SDL_Surface* buffer = SDL_CreateRGBSurface(0, 640, 480, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000);

```
5. Now we are ready to get rendering! Start your rendering with clearing both renderers:

```
SDL_RenderClear(renderer1);
SDL_RenderClear(renderer2);

```
6. Then comes the interesting stuff: This is where you would render everything you want to display on the second monitor to the render target:

```
SDL_SetRenderTarget(renderer1, target);
SDL_RenderCopy(renderer1, texture1, NULL, NULL);
SDL_RenderReadPixels(renderer1, NULL, SDL_GetWindowPixelFormat(window1), buffer->pixels, buffer->pitch);
SDL_SetRenderTarget(renderer1, NULL);

```

So, we simply set the render target, and draw our loaded texture onto it. After that, as you can see, we read the pixels from the renderer into our buffer surface. This is the real trick of the approach.
7. Now we just need to pass the data in `buffer` to the streaming texture we created for the second renderer:

```
SDL_UpdateTexture(texture2, NULL, buffer->pixels, buffer->pitch);

```
8. Then you can render the streaming texture onto the second window:

```
SDL_RenderCopy(renderer2, texture2, NULL, NULL);

```
9. And finally update the displays:

```
SDL_RenderPresent(renderer1);
SDL_RenderPresent(renderer2);

```

Now you've rendered a texture loaded on the main renderer onto your secondary window. It is a little hacky and perhaps a little slow, but for something like a secondary window for a level editor it might be enough. I didn't do any sort of stress-testing for this but both `SDL_RenderReadPixels` and `SDL_UpdateTexture` can be a little slow.

In any case, you might want to try this out and see if the performance is good enough for you. Having double textures on the other hand can be tedious and memory intensive, but the performance should be better.
> 9 votes

---
Tags: textures, rendering, sdl2, window-management, multiple-render-targets
---


# Question
Title: Keep balls in the box and prevent intersection
I'm coding a one-dimentional elastic collision animation (**demo**) with balls. I've used fixed position values when testing and now I want to use random values.

The problem with random values is that at the beginning (no animation, initial setup), balls might intersect. If this happens between two balls and in the middle of the container, current collision detection handles this kind of intersection. But if the balls are at the ends of the box and one intersects with both the wall and the other, this causes a problem.

For example, examine the below image.

1. One ball is randomly assigned a position and is in the middle.
2. Again, one ball is randomly assigned a position and it overflows to the left. It is repositioned to stay in the container.
3. Two balls are randomly assigned a position (no intersection) and are in the middle.
4. Two balls are randomly assigned a position (they intersect) and are in the middle. They're repositioned to touch each other.
5. Two balls are randomly assigned a position (they intersect) and one of them overflows to the left. Both should be repositioned with respect to each other and to the left wall. (**demo**)

Currently, I don't know how to handle the fifth case. I'll also increase the number of the balls, so the solution should be appliable to multiple balls.

If I can't find an easy solution, I'm gonna try empty space detection and reposition the balls starting from the farthest to the wall.

Most relevant parts:

```
var balls = [
    new Ball(25, 25, 25, 0, 0),
    new Ball(25, 50, 25, 0, 0, "blue"),
    // new Ball(25, random(0, 400), 25, 0, 0, "purple"),
];

function draw() {
    context.clearRect(0, 0, canvas.width, canvas.height);
    trackCollisions();
    balls.forEach(function(ball) {
        ball.draw();
    });
}
draw();

function trackCollisions() {
    // wall collisions
    balls.forEach(function(ball) {
        if (ball.intersectingWithWall()) {
            ball.snap2wall();
            ball.wrframe();
        }
        else if (ball.collidingWithWall()) {
            ball.flash("red");
        }
    });
    // ball collisions
    for (var i = 0; i < balls.length; i++) {
        for (var j = i + 1; j < balls.length; j++) {
            if (balls[i].intersectingWith(balls[j])) {
                balls[i].snap2ball(balls[j]);
                balls[i].wrframe();
                balls[j].wrframe();
            }
            else if (balls[i].collidingWith(balls[j])) {
                balls[i].resolveCollision(balls[j]);
                balls[i].flash("lime");
                balls[j].flash("lime");
            }
        }
    }
};

```

---

I've decided to share this *experiment* I'm working on here in case people came across similar problems or just want to know more about collisions: https://github.com/akinuri/bouncing-balls

# Answer
> 1 votes
DMGregory's answer gave me an idea. Let's say I have 5 balls and I want to place them in 400px wide area randomly. I could divide 400 by 5. Now I have 80px wide cells. Something like

```
cells = [ [0,80], [80, 160], [160, 240], [240,320], [320, 400] ];

```

I can generate random positions inside every 80px cells. Of course, I need to consider the edges and overlaping of balls at the edges. But this approach works:

```
function init() {
    balls = spawnBalls(5, 25);
    balls.forEach(function(ball) {
        ball.draw();
    });
    // draw();
}

function draw() {
    context.clearRect(0, 0, canvas.width, canvas.height);
    balls.forEach(function(ball) {
        ball.move();
    });
    trackCollisions();
    balls.forEach(function(ball) {
        ball.draw();
    });
    requestAnimationFrame(draw);
}

function spawnBalls(count, radius) {
    var balls = [];
    var cellWidth = Math.floor(canvas.width / count);       // 80
    var cellEdgeOffset = 1;                                 // prevent balls from touching walls and each other
    var allowedCellWidth = cellWidth - 2 * cellEdgeOffset;  // 78
    if (allowedCellWidth < 2 * radius) {
        throw new Error("There's not enough room for " + count + " balls.");
    }
    var cells = []; // [ {"x1":26, "x2":54}, {"x1":106, "x2":134}, {"x1":186, "x2":214}, {"x1":266, "x2":294}, {"x1":346, "x2":374} ]
    for (var i = 0; i < count; i++) {
        cells.push({
            x1 : i * cellWidth + (radius + 1),       // left side of the cell
            x2 : (i + 1) * cellWidth - (radius + 1)  // right side of the cell
        });
    }
    for (var i = 0; i < cells.length; i++) {
        balls.push(new Ball(radius, random(cells[i].x1, cells[i].x2), 25, random(0, 4), 0));
    }
    return balls;
}

```

Five random placement:

# Answer
> 0 votes
I'd be tempted to make the placement method avoid collisions by construction.

Here's an example that tries to place a ball inside a given interval. Then, it looks at the remaining room on either side of that interval. If either/both are big enough to fit another ball inside, it keeps them around, then tries to place the remaining balls in the leftover space.

By construction, it won't place two balls so close that they overlap, because it shrinks the intervals to only include valid placements.

```
function Interval(start, end) {
    this.start = start;
    this.end = end;
    this.length = end - start;
}

function SpawnBallsInRange(start, end, radius, ballCount) {
    var intervals = [new Interval(start + radius, end - radius)];
    var totalLength = intervals[0].length;

    while(ballCount > 0)    {
        var placement = Math.random() * totalLength;
        var intervalID = 0;
        while(intervalID < intervals.length - 1 && intervals[intervalID].length < placement) {
            placement -= intervals[intervalID].length;
            intervalID++;
        }

        var interval = intervals.splice(intervalID, 1)[0];

        totalLength -= interval.length;

        if(placement > 2.0 * radius) {
           var child = new Interval(interval.start, interval.start + placement - 2.0 * radius);
           intervals.push(child);
           totalLength += child.length;
        }

        placement += interval.start;

        SpawnBallAt(placement);

        if(end - placement > 2.0 * radius) {
           var child = new Interval(placement + 2.0 * radius, interval.end);
           intervals.push(child);
           totalLength += child.length;
        }

        ballCount--;

        if(intervals.length == 0 && ballCount > 0) {
            console.log("Ran out of room with " + ballCount + " remaining to place.");
            // Maybe abort and try again?
            break;
        }
    }
}

```

---
Tags: collision-detection, javascript, html-canvas
---


# Question
Title: Qt based C++ game structure : which class types to use here, and how to correctly structure the relationship between these objects
I am writing a C++ game using Qt. As this is the first time, I am trying to understand how the structure should be.

I have two objects derived from the type QGraphicsRectItem which appear as boxes on the screen, which will each represent a player. I want to make them move independently in response to key presses, with a different set of keys assigned to the motion of each object. These are added to a QGraphicsScene object, which is set by a QGraphicsView inherited object.

As only one of these can be focused at any given point of time, and thus respond to key press events, I have defined a function in a class which inherits from QGraphicsView (and is used as a view for viewing the scene) that receives all the key press events. Its constructor receives pointers to the two box objects, and sends the required information (by setting a variable) to the appropriate object through the pointer based on the key press.

I have a few questions regarding this:

* Is QGraphicsRectItem (or QGraphicsItem) the correct class for creating such "objects"? I see that there is a QObject class, but I could not understand where it is meant to be used.
* Sending pointers of the box objects to the constructor of the view during initialization doesn't seem right. What would be a more appropriate way to design this? The idea is that based on the key pressed, the corresponding box should respond. The problem is, how does this class access the object, unless it is declared inside it or passed as an argument?
* Is there a better or more commonly used way to handle the requirement of different objects responding to different key presses, even if done simultaneously? I have seen suggestions for using Event filters, which would pass the event using postEvent. However, event filters send messages to objects of type QObject, which is not what I am currently using. Additionally, the question again arises - who would receive the key press events? How would it know about the existence of the box objects?

I have been reading about design patterns. Is there any particular pattern that would be suitable for this?

Thank you.

# Answer
QGraphicsItem is the correct base for *things drawing pixels on screen*, but that is a much tighter responsibility than "The model of the player's actions".

More traditionally, you would have something like

```
class GameObject : QObject
{
    void draw() { QRectF bounds = m_graphic->rect(); bounds.moveCenter(m_position); m_graphic->set_rect(bounds); }
    void update(std::chrono::duration delta_time) { do_update(delta_time); }
protected:
    virtual void do_update(std::chrono::duration delta_time) = 0;

    QGraphicsItem * m_graphic;
    QPointF m_position; // or 3d point
}

class Player : GameObject
{
    // event handlers
public:
    Player(QGraphicsScene & scene) : m_graphic(new PlayerGraphic) { scene.addItem(m_graphic); }
public slots:
    void keyPressEvent(QKeyEvent * event) { /* set movement direction */ }
private:
    void do_update(std::chrono::duration delta_time) { /* handle movement that occurs in this time step */ }
}

class PlayerGraphic : QGraphicsRectItem
{
    void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = 0) { /* art here*/ }
}

```
> 1 votes

---
Tags: c++, architecture, multiplayer, design-patterns, qt
---


# Question
Title: I'm having resolution issues; does my math suck?
There are a lot of scripts involved so I'm just going to give a generalized description of the process.

First, a 1x1 square tile is created. Second, that tile is placed out of the way, and 16 x 10 (160) new tiles are created starting at the (0,0) position and building outward in positive numbers. Now, the camera is a 16:10 display. At this point, I wanted to scale up the tiles. If I want to scale the map up I start by scaling the camera by 100, and then I scale the tiles, and align their position (edge to edge). At this point, scaling the tiles by 100 seems logical, but that didn't work correctly, for some reason. Scaling by 50 almost works, but the resolution is no longer a 16:10 grid like it was before the scaling.

What am I doing wrong? I am using Unity.

# Answer
> -2 votes
First, I counted the tiles left to right to find it was only 15:9. Then, I checked the script to see if it was instantiating these tiles correctly: and it was.

Finally I restarted the Unity Editor and MonoDev, which fixed the issue. I believe the last correction I had made to the script was just not being properly applied.

---
Tags: unity, mathematics, resolution
---


# Question
Title: convert gl_Position into screen coordinates
Pretty simple question I think. I need to convert model space coordinates into screen space coordinates for a special shader effect.
I am of course able to just convert them into gl\_Position coordinates by just multplyng them with the wold view and projection matrices.
Unfortunately though, thats where I am at my wits end. Since opengl somehow converts normal vertices them into screen coordinates itself, and I need a few extra vertices for a special effect, I have no idea how to achieve this.
So does anybody have any idea how I convert model space coordinates into gl\_Fragcoord screen coordinates? I basicly want to be able to give the vertex shader a bunch of model space coordinates and have it spit out where exactly they are on the screen if they were rendered.

# Answer
> 0 votes
If I understand the problem right, you should look at **glm** function **project**:

> Map the specified object coordinates (obj.x, obj.y, obj.z) into window coordinates.

But I think that every shader effect do not need a screen space coords. There are must be some way to avoid this, since the operation that converts model space to screen space coords would be very costly.

If you can specify the shader effect you want to implement, I will update the post.

---
Tags: opengl, mathematics, glsl, matrix
---


title: Unity script blocks normal movement

text:
# Question
Title: Unity script blocks normal movement
I've made a script to avoid the double jump problem but, when it's active, I can't move my character without being in the air. If I comment out the double jump script, it works like a charm. This is a strange, buggy charm, because I still need to improve it.

My script looks like this:

```
public class PlayerMovement : MonoBehaviour
{
    public Rigidbody rb;
    public float Speed = 10f;
    public float Jump = 1f;

    void Start ()
    {
        rb = GetComponent<Rigidbody>();
    }

    void FixedUpdate ()
    {
        if (Input.GetTouch(0).phase == TouchPhase.Began && transform.position.y == 0.55f)
        {
            // Double Jump
            rb.AddForce(0f, 1f * Jump, 0);

            // Regular Movement
            rb.AddForce(Input.acceleration.y * Speed, .0f,  -Input.acceleration.x * Speed);
        }
    }
}

```

This is used on a sphere object, if it matters. What am I doing wrong?

# Answer
> 0 votes
Ok ,I worked around it and switched the `Input.GetTouch(0).phase == TouchPhase.Began` with `Input.touchCount > 0`. Now it all works.

# Answer
> 1 votes
First of all you have `transform.position.y == 0.55f` \- I hope it's supposed to be like that, assuming that your player or whoever with this script is supposed to jump only when position on y axis is 0.55.

And as I have seen in previous comments, you said that your ball on the ground is on the position 0.55, then there is no double jump at all, you just check for simple jump when your ball is on 0.55f y level.

If your script works fine without this "if" part - then it makes no sense, because part after the if should invoke anyway. You can check that by `Debug.Log("Invoked");` inside your `FixedUpdate();`.

Also it's bad practice to use this kind of logic for jump like `==`. Try checking for ground collisions, there are plenty tutorials about jumping in Unity. And why - because platforms could be on different y level - it's first. Secondly, because in Unity in world space `position.y` is a `float`value as I remember, so it's not always rounded, it can be on 0.55134f level and you could not even notice it. Why? - Because of the collisions and update. Collisions are checked every frame and your machine(PC, Mac...) sometimes has more frames per second and sometimes less. Also it doesn't work at the same speed all the time - which means even if the collider edge is on 0.55f on y, your ball could have stopped at 0.54923f and other values like that. So it may never even be on 0.55f.

Couldn't help you more with it with the information you have provided, try first go through some tutorials and just make the same actions step by step, then try to understand how Unity works and what algorithms it uses for it. That is a long road, good luck.

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


# Question
Title: Make variables public, or make functions to get/set variables?
Dumb question but I want my game to be secure as possible. Right now I have classes interfacing with each other in order to save/load player information. Right now I have all the variables in my classes as public, and saving / loading the saved variables into them. But I don't think that's as secure.

Code:

```
public class PlayerRP : MonoBehaviour {

public string charName;
public string charRace;
public string charClass;
public string charClassSpec;
public string charBackground;
public string charGender;

}

public class CharacterManager : MonoBehaviour {
public void SaveCharacter() {
    BinaryFormatter bf = new BinaryFormatter();
    FileStream file = File.Create(Application.persistentDataPath + slotFile);

    CharacterSaveFile data = new CharacterSaveFile();

    // Character RP
    data.charName = playerRP.charName;
    data.charRace = playerRP.charRace;
    data.charClass = playerRP.charClass;
    data.charGender = playerRP.charGender;

    bf.Serialize(file, data);
    file.Close();

    LoadCharacter();
}
}

```

Would it be safer (or more efficient) to instead make methods in the playerRP class to get/set the variables separately, rather than have them as public?

# Answer
> 3 votes
From a security standpoint, where security means "protecting the data against access or modification," it does not really matter. Access specifiers like public and private are generally relevant only to the compilation process (and for C# and other languages with reflection support, occasionally to the reflection process).

Making data private and exposing it via accessors will not make the source of that data any harder to find and modify in memory at runtime. There may be (and often are) good reasons to do this from a software architecture standpoint, but from a security standpoint the impact is essentially zero.

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


# Question
Title: Large amounts of strings to be used, but how to store them?
This is a question I've been meaning to ask. I have thought about it for a little bit and have a few ideas, but I'm not sure which is most secure, and will give me the most functionality with the most efficiency. For my game (being a story game) I have a plethora of strings that I'm going to need to display. I decided to split up the story into chapters, each chapter being a new scene(This way I could organize the content for the chapter). What I was thinking was that I could write regular text files with the chapter's content, while efficient and practical, this seems highly insecure. Then I thought, why not put it into large string arrays on a separate C# file. Well that's more secure, but it's not really practical and it has less efficiency. So I have found pretty much the two extremes here.

**What would be the best way to deal with large amounts of strings in a secure, efficient, and functional way? Think about a happy medium compared to my two extremes.**

# Answer
The most secure method is to store them on a server, and transmit them to the client game only when absolutely required by that game.

If you store the text on the user's machine *in any form*, it can be retrieved and viewed (and modified, potentially) by that user. You can prevent casual inspection of the text data by storing it encrypted, and decrypting it at runtime. This will usually stop casual snoopers from poking around in the game's data files and finding the text. It will not stop anybody who can poke around in the game's memory at runtime, as you will eventually need to decrypt the strings and once you do the user has the decryption algorithm and keys and can decrypt the rest of the text whenever they want. Nothing on the end-user's machine can be trusted, from a security standpoint.

Notably, moving the text around into different C# source files has no impact on anything, security-wise. It is not more secure, it is not less secure, you've just moved the data a little.
> 1 votes

---
Tags: unity, text, security
---


# Question
Title: Stopping Actor tap/click event from propagating
I've been struggling with this for hours now and have read posts, docs and libgdx sources to better understand what's happening, but I still can't make any sense of this.

I want to accomplish something very simple: stopping a tap on an Actor from propagating through the stage.

The setup is as follows:

* `GameStage` defines a gesture listener (for map panning and propagating taps in the map to the `Player` actor so it can move around)
* `Player` has a child actor which can receive clicks

It is on that last child actor that I want to detect clicks, but then not have them propagate to any other actors or be handled by the stage. I define the click handler as follows:

```
// in child actor:
addListener(new ClickListener() {
   void clicked(...)
});

```

Nothing surprising here.

The problem is: since the actor is physically located outside the Player parent actor, any clicks on it get picked up by the stage's map gesture handler which then propagates these taps back to the player which makes it move around. I don't want that; this click listener is supposed to handle and swallow the event.

However, none of the following calls I make inside `clicked` actually cancel the event:

```
event.handle()
event.stop()
event.cancel()

```

The only way I could make the event stop from propagating is to use `Stage#cancelTouchFocus`. However, this has the side effect of dispatching a `touchUp` event on the stage (why?), which ends up in my gesture listener and gets interpreted as a `longPress`! Probably because it is paired up with the wrong `touchDown`...

What am I missing? It can't be that complicated to stop an event from propagating given all the supposed options?

**UPDATE:** I believe the problem lies in `Stage`: https://github.com/libgdx/libgdx/blob/2bd1557bc293cb8c2348374771aad832befbe26f/gdx/src/com/badlogic/gdx/scenes/scene2d/Stage.java#L348

It walks over all the listeners that have touch focus, and let's them handle the event. However, it does not break out of the loop as soon as a listener has handled it, thus propagating it further. Is that just a bug?

# Answer
> 0 votes
So, it turns out that this is not possible out of the box. The reason it works the way it does is apparently because the `touchUp` event is not a self-contained event, but is a follow up to `touchDown`. So in order to cancel them, one has to handle the `touchDown` in the first place.

Since most event handlers return void (thus cannot signal to their callers that the event has been handled) the only thing one can do is in the gesture handler, check manually if an event was handled by an actor and only propagate it if not, or write your own gesture handler (i.e. not use `ActorGestureListener`).

# Answer
> 2 votes
I had the same problem with a window (scene2d.ui.Window). It would propagate click and other events though it shouldn't. I solved it by doing this:

```
window.addListener(new ActorGestureListener());

```

As simple as that. Not sure if this is the correct way to do it or if it has some undesirable side effects, but it worked in my case.

---
Tags: libgdx, scene2d
---


# Question
Title: Using Multiple Viewports in LibGDX?? help needed badly
I've asked this question before but i am still unclear of how to do this after hours of frustration I have messed up yet another decent project I've been working on. I had a fully functioning Snake game which I was very happy with but I had the idea that I wanted to put the entire game id created onto the screen inside of an image of something similar to an old GameBoy. (in case im not describing this clearly I have made a quick diagram): https://i.stack.imgur.com/3J1Ol.jpg I've read so much on this matter before but I just can't make it work in my own projects.

No matter what I have done (ie. where i set ScreenX position for my inner viewport) the inner viewport always positions at the very left edge of screen and spans the width of screen - even though I have set the "World Width", I want the inner screen inset inside the controllerViewport so that it looks like you are playing it on that device. (I tried using things other than FitViewport, but i need the inner screen to be relative to the VIRTUAL WIDTH, HEIGHT I created.

I will paste the code now (sorry i have it all in one class on this project as it started from a tutorial i completed - i dont usually write my code like this):

```
public class GameScreen extends ScreenAdapter {

    private static final float WORLD_WIDTH = 640;
    private static final float WORLD_HEIGHT = 480;

    private static final float TOTAL_HEIGHT = 1920 / 2;
    private static final float TOTAL_WIDTH = 1080 / 2;

    private static final float MOVE_TIME = 0.15f;
    private static final int SNAKE_MOVEMENT = 32;
    private static final int GRID_CELL = 32;

    private static final int RIGHT = 0;
    private static final int LEFT = 1;
    private static final int UP = 2;
    private static final int DOWN = 3;

    private static final String GAME_OVER_TEXT = "Game Over... Punk!!";

    private static final int POINTS_PER_APPLE = 20;

    private SnakeGame game;

    private SpriteBatch batch;
    private Texture snakeHead;
    private Texture snakeBody;
    private Texture apple;

    private boolean appleAvailable = false;
    private int appleX, appleY;

    private float timer = MOVE_TIME;
    private float snakeX = 0, snakeY = 0;
    private float snakeXBeforeUpdate = 0, snakeYBeforeUpdate = 0;

    private int snakeDirection = RIGHT;
    private Array<BodyPart> bodyParts = new Array<BodyPart>();

    private ShapeRenderer shapeRenderer;

    private boolean directionSet = false;
    private boolean hasHit = false;

    private enum STATE { PLAYING, GAME_OVER }

    private STATE state = STATE.PLAYING;

    private BitmapFont bitmapFont;
    private GlyphLayout layout = new GlyphLayout();

    private int score = 0;

    private Viewport viewport1;
    private Camera camera;
    private Viewport controllerViewport;

    private Dpad dpad;
    float dPadWidth;
    private Texture dPadTexture;
    Vector3 touchPos;

    Texture background;
    Texture gameboyTexture;

    public GameScreen(SnakeGame game){
        this.game = game;
        batch = new SpriteBatch();
        snakeHead = new Texture(Gdx.files.internal("snakehead.png"));
        snakeBody = new Texture(Gdx.files.internal("snakebody.png"));
        apple = new Texture(Gdx.files.internal("apple.png"));
        background = new Texture(Gdx.files.internal("backgroundTile.png"));
        dPadTexture = new Texture(Gdx.files.internal("dpad.png"));
        gameboyTexture = new Texture("gameboy.png");
        shapeRenderer = new ShapeRenderer();
        bitmapFont = new BitmapFont();
        bitmapFont.getData().setScale(2f,2f); // set font size here
        camera = new OrthographicCamera();
        camera.position.set(TOTAL_WIDTH / 2, TOTAL_HEIGHT / 2, 0);
        camera.update();
        controllerViewport = new FillViewport(TOTAL_WIDTH, TOTAL_HEIGHT, camera);
        viewport1 = new FitViewport(WORLD_WIDTH, WORLD_HEIGHT);
        viewport1.setScreenBounds((int)(controllerViewport.getWorldWidth() * 0.25f), (int)(controllerViewport.getWorldHeight() - (controllerViewport.getWorldHeight() * 0.1f)),
                (int)(controllerViewport.getWorldWidth() * 0.75f) , (int)(controllerViewport.getWorldHeight() * 0.33f));

        switch (game.dpadSize){
            case 1:
                dPadWidth = viewport1.getWorldWidth() / 4 * 0.75f;
                break;
            case 2:
                dPadWidth = viewport1.getWorldWidth() / 4 * 1.00f;
                break;
            case 3:
                dPadWidth = viewport1.getWorldWidth() / 4 * 1.25f;
                break;
            case 4:
                dPadWidth = viewport1.getWorldWidth() / 4 * 1.50f;
                break;
        }

        float dPadHeight = dPadWidth;
        dpad = new Dpad(dPadTexture, viewport1.getWorldWidth() - dPadWidth, viewport1.getScreenY(), dPadWidth, dPadHeight);
        touchPos = new Vector3();

    }

    @Override
    public void show() {

    }

    @Override
    public void render(float delta) {
        switch (state) {
            case PLAYING:
                updateSnake(delta);
                queryInput();
                checkAppleCollision();
                checkAndPlaceApple();
                break;
            case GAME_OVER:
                checkForRestart();
                break;
        }

        clearScreen();
//        drawGrid();
        draw();
    }

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

    private void checkForRestart(){
        if (Gdx.input.isKeyPressed(Input.Keys.SPACE)){
            doRestart();
        }
        if (state == STATE.GAME_OVER && Gdx.input.isTouched()){
            doRestart();
        }
    }

    private void doRestart() {
        state = STATE.PLAYING;
        bodyParts.clear();
        snakeDirection = RIGHT;
        directionSet = false;
        timer = MOVE_TIME;
        snakeX = 0;
        snakeY = 0;
        snakeXBeforeUpdate = 0;
        snakeYBeforeUpdate = 0;
        score = 0;
        appleAvailable = false;
    }

    private void updateSnake(float delta) {
        if (!hasHit) {
            timer -= delta;
            if (timer <= 0) {
                timer = MOVE_TIME;
                moveSnake();
                checkForOutOfBounds();
                updateBodyPartsPosition();
                checkSnakeBodyCollision();
                directionSet = false;
            }
        }
        // add transparency to snake tail:
        for (int i = 0; i < bodyParts.size; i++){
            bodyParts.get(i).setAlphaValue(0.02f * (i + 6));
            if (bodyParts.get(i).alphaValue <= 0.15f){
                bodyParts.get(i).alphaValue = 0.15f;
            }
            if (bodyParts.get(i).alphaValue >= 0.95f){
                bodyParts.get(i).alphaValue = 0.95f;
            }
        }
    }

    private void updateIfNotOppositeDirection(int newSnakeDirection, int oppositeDirection){
        if (snakeDirection != oppositeDirection || bodyParts.size == 0){
            snakeDirection = newSnakeDirection;
        }
    }

    private void updateDirection(int newSnakeDirection){
        if (!directionSet && snakeDirection != newSnakeDirection){
            directionSet = true;
            game.step2Sound.play();
            switch (newSnakeDirection){
                case LEFT:
                    updateIfNotOppositeDirection(newSnakeDirection, RIGHT);
                    break;
                case RIGHT:
                    updateIfNotOppositeDirection(newSnakeDirection, LEFT);
                    break;
                case UP:
                    updateIfNotOppositeDirection(newSnakeDirection, DOWN);
                    break;
                case DOWN:
                    updateIfNotOppositeDirection(newSnakeDirection, UP);
                    break;
            }
        }
    }

    private void queryInput() {
        boolean lPressed = Gdx.input.isKeyPressed(Input.Keys.LEFT);
        boolean rPressed = Gdx.input.isKeyPressed(Input.Keys.RIGHT);
        boolean uPressed = Gdx.input.isKeyPressed(Input.Keys.UP);
        boolean dPressed = Gdx.input.isKeyPressed(Input.Keys.DOWN);

        boolean leftDpadPressed = false;
        boolean rightDpadPressed = false;
        boolean upDpadPressed = false;
        boolean downDpadPressed = false;

        touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
        camera.unproject(touchPos, viewport1.getScreenX(), viewport1.getScreenY(), viewport1.getScreenWidth(), viewport1.getScreenHeight());

        if (touchPos.x >= dpad.upRect.x && touchPos.x <= dpad.upRect.x + dpad.upRect.width
                && touchPos.y >= dpad.upRect.y && touchPos.y <= dpad.upRect.y + dpad.upRect.height)
            upDpadPressed = true;
        if (touchPos.x >= dpad.downRect.x && touchPos.x <= dpad.downRect.x + dpad.downRect.width
                && touchPos.y >= dpad.downRect.y && touchPos.y <= dpad.downRect.y + dpad.downRect.height)
            downDpadPressed = true;
        if (touchPos.x >= dpad.leftRect.x && touchPos.x <= dpad.leftRect.x + dpad.leftRect.width
                && touchPos.y >= dpad.leftRect.y && touchPos.y <= dpad.leftRect.y + dpad.leftRect.height)
            leftDpadPressed = true;
        if (touchPos.x >= dpad.rightRect.x && touchPos.x <= dpad.rightRect.x + dpad.rightRect.width
                && touchPos.y >= dpad.rightRect.y && touchPos.y <= dpad.rightRect.y + dpad.rightRect.height)
            rightDpadPressed = true;

        if (lPressed || leftDpadPressed) updateDirection(LEFT);
        if (rPressed || rightDpadPressed) updateDirection(RIGHT);
        if (uPressed || upDpadPressed) updateDirection(UP);
        if (dPressed || downDpadPressed) updateDirection(DOWN);
    }

    private void moveSnake() {
        snakeXBeforeUpdate = snakeX;
        snakeYBeforeUpdate = snakeY;
        if (!directionSet) {
            game.step1Sound.play(0.1f);
        }
        switch (snakeDirection) {
            case RIGHT: {
                snakeX += SNAKE_MOVEMENT;
                return;
            }
            case LEFT: {
                snakeX -= SNAKE_MOVEMENT;
                return;
            }
            case UP: {
                snakeY += SNAKE_MOVEMENT;
                return;
            }
            case DOWN: {
                snakeY -= SNAKE_MOVEMENT;
                return;
            }
        }
    }

    private void checkForOutOfBounds() {
        if (snakeX >= viewport1.getWorldWidth()) {
            snakeX = 0;
        }
        if (snakeX < 0) {
            snakeX = viewport1.getWorldWidth() - SNAKE_MOVEMENT;
        }
        if (snakeY >= viewport1.getScreenY() + viewport1.getWorldHeight()) {
            snakeY = viewport1.getScreenY();
        }
        if (snakeY < viewport1.getScreenY()) {
            snakeY = viewport1.getScreenY() + viewport1.getWorldHeight() - SNAKE_MOVEMENT;
        }
    }

    private void updateBodyPartsPosition() {
        if (bodyParts.size > 0) {
            BodyPart bodyPart = bodyParts.removeIndex(0);
            bodyPart.updateBodyPosition(snakeXBeforeUpdate, snakeYBeforeUpdate);
            bodyParts.add(bodyPart);
        }
    }

    private void checkAndPlaceApple() {
        if (!appleAvailable) {
            if (!(appleX == snakeX && appleY == snakeY)) {
                if (bodyParts.size == 0) {
                    appleX = (MathUtils.random((int) (viewport1.getWorldWidth() / SNAKE_MOVEMENT) - 1) * SNAKE_MOVEMENT) + viewport1.getScreenX();
                    appleY = (MathUtils.random((int) viewport1.getWorldHeight() / SNAKE_MOVEMENT - 1) * SNAKE_MOVEMENT) + viewport1.getScreenY();
                    appleAvailable = true;
                }
                for (BodyPart bodyPart : bodyParts) {
                    if (!(appleX == bodyPart.x && appleY == bodyPart.y)) {
                        appleX = (MathUtils.random((int) (viewport1.getWorldWidth() / SNAKE_MOVEMENT) - 1) * SNAKE_MOVEMENT) + viewport1.getScreenX();
                        appleY = (MathUtils.random((int) viewport1.getWorldHeight() / SNAKE_MOVEMENT - 1) * SNAKE_MOVEMENT) + viewport1.getScreenY();
                        appleAvailable = true;
                    }
                }
            }
        }
    }

    private void checkAppleCollision() {
        if (appleAvailable && appleX == snakeX && appleY == snakeY) {
            BodyPart bodyPart = new BodyPart(snakeBody);
            bodyPart.updateBodyPosition(snakeX, snakeY);
            bodyParts.insert(0,bodyPart);
            score += POINTS_PER_APPLE * bodyParts.size;
            game.pickupSound.play(0.7f);
            appleAvailable = false;
        }
    }

    private void checkSnakeBodyCollision(){
        for (BodyPart bodyPart : bodyParts){
            if (bodyPart.x == snakeX && bodyPart.y == snakeY){
                state = STATE.GAME_OVER;
                game.loseSound.play();
            }
        }
    }

    private void clearScreen() {
        Gdx.gl.glClearColor(Color.BLACK.r, Color.BLACK.g, Color.BLACK.b, Color.BLACK.a);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    }

    private void draw() {
        batch.setProjectionMatrix(camera.combined);
        batch.begin();
        batch.draw(gameboyTexture, 0, 0, controllerViewport.getWorldWidth(), controllerViewport.getWorldHeight());
        batch.draw(background, viewport1.getScreenX(), viewport1.getScreenY(), viewport1.getWorldWidth(), viewport1.getWorldHeight());
        batch.draw(snakeHead, snakeX, snakeY);

        for (int i = 0; i < bodyParts.size; i++){
            bodyParts.get(i).draw(batch);
        }
        if (appleAvailable) {
            batch.draw(apple, appleX, appleY);
        }
        if (state == STATE.GAME_OVER) {
            layout.setText(bitmapFont, GAME_OVER_TEXT);
            bitmapFont.draw(batch, GAME_OVER_TEXT, (viewport1.getWorldWidth() - layout.width) / 2, (viewport1.getWorldHeight() - layout.height) / 2);
        }
        dpad.setColor(1,1,1,0.3f);
        dpad.draw(batch);
        batch.setColor(1,1,1,1);
        drawScore();
        batch.end();
    }

    private void drawScore(){
        if (state == STATE.PLAYING){
            String scoreAsString = Integer.toString(score);
            layout.setText(bitmapFont, scoreAsString);
            bitmapFont.draw(batch, scoreAsString, (viewport1.getWorldWidth() - layout.width) / 2, viewport1.getWorldHeight() - layout.height * 2);
        }
    }

    private void drawGrid(){
        shapeRenderer.setProjectionMatrix(camera.combined);
        shapeRenderer.begin(ShapeRenderer.ShapeType.Line);
        for (int x = 0; x < viewport1.getWorldWidth(); x += GRID_CELL){
            for (int y = 0; y < viewport1.getWorldHeight(); y += GRID_CELL){
                shapeRenderer.rect(x, y, GRID_CELL, GRID_CELL);
            }
        }
        shapeRenderer.end();
    }

    private class BodyPart {

        private float x, y;
        private Texture texture;
        private float alphaValue;

        public BodyPart(Texture texture) {
            this.texture = texture;
        }

        public void updateBodyPosition(float x, float y) {
            this.x = x;
            this.y = y;
        }

        public void setAlphaValue(float alpha){
            alphaValue = alpha;
        }

        public void draw(Batch batch) {
            if (!(x == snakeX && y == snakeY)){
                batch.setColor(1,1,1,alphaValue);
                batch.draw(texture, x, y);
                batch.setColor(1,1,1,1);
            }
        }
    }
}

```

If anyone can help me finally figure this out I would be eternally grateful

# Answer
Rather than focusing on the idea of multiple viewports, you should approach this problem in the same way that you approach any game with the game world rendered on one layer, and the HUD rendered on a layer above it.

Simply create a stage, camera, and batch for the world and another one for the HUD. You could use a `ScreenViewport` for the world and zoom the camera out so that it is small enough to fit inside whatever gameboy image you want to layer on top of it.

You could then use any kind of Viewport for the HUD, whether it be Stretch or Screen, whatever works best. Add the image of the gameboy to the hud stage, and then add the buttons on top of that.

You can then play around with the camera of the world stage in order to zoom and position the stage exactly where it needs to be to fit inside the gameboy hud.

I should mention that if you do not want to use a stage for drawing the world, you can still use the batch and camera and the necessary `draw` methods inside of the render method. The key difference between your code and what I am suggesting is that you would have a separate camera and batch for the HUD rather than trying to use the same one for both.
> 2 votes

---
Tags: java, 2d, libgdx, viewport
---


# Question
Title: What FOV does Unity show in a 16:9 aspect ratio, when set to FOV 60?
**Preamble:**

I noticed the FOV in Unity is only correct when the screen resolution is square, in other words when the width of the screen is the same as the height.

When you add more width to the screen, the camera shows a greater FOV sideways. (The FOV remains the same up and down.)

To see this is true, set the resolution to be square, set the FOV to be 90, and go into a corner and look out and compare the positions of both walls: They will match the sides of the screen.

So even 4:3 screens show more FOV. 16:9 shows way more. I am not sure of the math to determine how much.

**Question:**

I wonder what aspect ratio shows a FOV of 90 (sideways) when it is set to the default 60? Does anyone know the math?

# Answer
> 3 votes
Assuming Unity3D does not add further scaling on your platform (TV safe zone) 16:9 gives a little bit above 90 degrees wide (91.49284452 degrees) when set to 60 vertical.

The formula is:

```
float f = Mathf.Tan(Mathf.Deg2Rad(fov_y / 2.0f));

fov_x = Mathf.Rad2Deg(Mathf.Atan(f * aspect_ratio)) * 2.0f;

```

To find the exact ratio that will give you 90 degrees horizontal with 60 degrees vertical:

```
float ratio = Mathf.Tan(Mathf.Deg2Rad(90/2.0f)) / Mathf.Tan(Mathf.Deg2Rad(60/2.0f));

```

or 1.732050808:1 or 15.588457268:9

---
Tags: unity, mathematics, camera
---


# Question
Title: How to handle equipment on a 3D animated character
Im working on a 3D engine in Java using OpenGL. Animated models are set up and working by transforming vertices based on joint weights in the vertex shader, i think this is common practice.

I am now trying to figure out how to manage equipment that can be worn or carried by a character, like armor and weapons. How is this commonly done, or whats the best way to do it?

Im imagining that you make some sort of attachment point for weapons on the character model, but since that all happens in the vertex shader, how do you go about that? Would you "intercept" the joint transformations and render the weapon independently? Also, how do you find out what the attachment point for the weapon is? Im using a collada file loader to parse .dae files for models and animations, can you somehow "index" bones with special attributes in Blender/other 3D programs?

And for armor: Since armor has to not just move with the character but also stretch and deform with him, do you somehow merge the models, or overlap them?

Im really in the dark about the practices for this but i can't find anything comprehensive on the internet that explains it.

# Answer
This is handled differently depending on the equipment type.

You already have the rotation matrices per bone if you are doing vertex skinning, so you can just use those for the equipment. You should be able to rename bones in Blender to find them that way, but this gets into file loading, which is a very vast topic.

# Rigid Items

These are the easiest the only deformation they undergo are per-object transformations depending on the bone(s) the object is attached to. An example of this would be a tool such as flashlight attached to single hand bone (or multiple bones).

# Armor/Clothes

These are usually treated just like a character. For applications that have customizable characters, this becomes tricky because the clothes must fit the characters. It's usually best to just break down the characters into different meshes for each "part" (such as an arm, or the whole torso). You can even just replace part of the VBO for the character and swap in/out armor parts in some cases if you have a small number of textures. Otherwise, render each part as everything as a separate mesh (or do some sort of batching, to help with performance).

The problem with overlapping is that there can sometimes be strange offsets from bones that contribute to the base mesh clipping through, not to mention this adds to the computation needed. Even floating point precision can be an issue here and lead to z-fighting. It's very difficult to make overlapping skinned meshes work together.

# Realistic Capes/Cloth

Realistic capes (applicable to other cloth materials) are an especially difficult object to render because they are impacted by both physics and the skeletal animation. Capes in this case can be done either on the CPU or on the GPU (with computer shaders or an alternative) via physics computations on a coarse cape mesh. Each vertex of this coarse mesh is then treated as a bone of a cape skeleton and then the higher resolution rendering mesh is deformed according to this coarse mesh, usually using a bezier curve or something similar. Ubisoft used this technique.
> 1 votes

---
Tags: opengl, 3d, rpg
---


# Question
Title: Instant replay system by saving frames to memory in Unity
When designing an instant replay system that will playback the last n seconds of gameplay, I've seen people essentially record all of the game events and game object states and play it back. This seems like a very heavy weight solution. TowerFall achieves its instant replay by saving the last n seconds of the frame buffer and simply plays them back in order.

How would you achieve this in Unity? My initial attempt was to simply keep a `Queue` of `Texture2D` objects of the entire screen, ensuring the `Queue` never got larger then a few seconds worth of `Texture2D` objects.

However, I quickly discovered this was extremely inefficient as memory ballooned to several gigs and the frame rate dropped significantly. I know TowerFall wasn't developed in Unity, but it seems like it was able to efficiently achieve this, so I'm curious if my approach was just wrong?

Here is the code I used (from memory)

```
Queue<Texture2D> frames = new Queue<Texture2D>();

// 130 frames is the equivalent of ~5 seconds.
if (frames.Count > 130) {
    var trash = frames.Dequeue();
    trash = null;
}

var frame = new Texture2D (Screen.width, Screen.height, TextureFormat.RGB24, false);
// Read screen contents into the texture
frame.ReadPixels(Rect(0, 0, Screen.width, Screen.height), 0, 0);
frame.Apply();
frames.Enqueue(frame);

```

# Answer
Texture2D in Unity are not garbage collected as readily as other content, because they live partly in graphics memory - so Unity can't easily verify they're not in use without a time-consuming sweep. Usually loose materials and textures are swept up when loading a new scene (and in-Editor, you'll get a warning about unreferenced assets left dangling)

So, it's better to explicitly reuse your textures - using a ring buffer to overwrite the contents of old ones rather than continually constructing new ones - and explicitly delete them with Destroy() when you're finished with them.

You can also reduce the performance impact by using RenderTextures instead of Texture2D. These live GPU-side, so you're not tying up CPU-GPU bandwidth every time you save a frame using Graphics.Blit to copy the framebuffer. You can still pull them down one at a time into a Texture2D if you need to read them CPU-side or store them to disc, but basic in-memory recording and playback can live entirely GPU-side.
> 1 votes

# Answer
In film 24fps is common. I see no reason why you can't use 20fps capping the Queue to 100 frames. Then you'll need to calculate the current fps and make sure you are skipping the appropriate number of frames. Example: if you have 60fps you are going to exceed your limit in not 5 seconds, but 2. So if the you have 60fps you'll need to record every 3rd frame instead.

Also, make sure to yield and WaitForEndOfFrame() before you begin your capture or weird shit will happen. Lastly there's no reason the texture needs to be full res, cut that bitch in half or even a quarter till you get the performance you desire.

Follow these steps and your framerate/memory issues will go away. A 640x320 jpg is roughly 50kb, which results in ~1mb per second you'd like to record.
> -1 votes

---
Tags: unity
---


# Question
Title: How to keep a square in front of moving camera?
I'm currently attempting to create a Lens of Truth effect like what we find in Zelda: Ocarina of Time:

> The Lens of Truth allows \[the player\] to see things that are not normally visible to the naked eye. It can show fake walls and floors, and invisible objects and enemies. (Source: Zelda wiki)

I'm attempting it by using a square frame that is positioned in a scene and an object that should only be visible when viewed through that frame.

The way I tried it is, I defined the square `vec4`s like this and transform it using the world, view and projection matrix:

```
vec4 fc[4];
fc[0]=vec4(0,0,0,1);
fc[1]=vec4(1,0,0,1);
fc[2]=vec4(1,1,0,1);
fc[3]=vec4(0,1,0,1);
for(int i=0;i<4;i++){
   fc[i].xyz =  vec4( (worldMat * fc[i]) ).xyz;
   fc[i].w=1.0;
   fc[i] = pass.Proj*(pass.View*fc[i]);
}

```

In theory I should now get the positions of these 4 points in screen space relative to the position of the object.

Now I should just be able to do this:

```
if(!inside(inPs.glPosition.xy,fc[0].xy,fc[1].xy,fc[2].xy,fc[3].xy) ){
    discard;
}

```

to clip the fragment if it is outside the quad of those points (inside is function by me, the problem is not here), since I basically figure out the screen space coordinates of the square frame.

But if I run the thing the coordinates of the square corners move all over the place.

If I debug the thing by displaying the position of those points on the object, they don't move at all when I translate the camera, but only when I rotate it, when It should logically be the other way around. Imagine a sheet with a ligthbulb behind it. If you stand still, the position of the lamp on the sheet doesn't change, but when you move around, the light will be on other places of the sheet. I have a feeling, there's something wrong with my thought process here, but I can't figure out why.

# Answer
> 0 votes
I'm not sure what's wrong with your math, but you're tackling this the wrong way. The way to do the lens of truth is with a stencil buffer. Basically you mark the pixels that the lens is covering then draw the hidden objects only on the marked pixels.

1. Draw your scene as normal except for the lens and hidden objects.
2. Disable color writes and depth writes and enable stencil writes.
3. Draw the polygons for just the glass of the lens and not the border.
4. Enable color writes, depth writes, and stencil test and disable stencil updates. Also create a clip plane parallel to the surface of the lens to hide objects that are between your eye and the lens.
5. Draw all the hidden objects. They will only be drawn on the pixels that the lens touched.
6. Disable stencil test and clip plane. (Your render settings are back to normal at this point. )
7. Draw the lens and frame, this time it will actually draw.

Don't forget to clear your stencil buffer for the next frame.

# Answer
> 0 votes
Quote from user2741831:

> If anyone finds this thread, the answer is to calculate `gl_position.xy/gl_position.w` to get 2D screen coordinates

---
Tags: opengl, mathematics, glsl
---


# Question
Title: Applying different materials to an object
I'm currently implementing an Object Loader for the Wavefront File Format (`*.obj`). When exporting a model (with associated materials) from blender, a material for a group of faces is specified like this:

```
usemtl MyMaterial
s off
f 2/1/1 4/2/1 3/3/1
f 1/4/1 2/1/1 3/3/1

```

Since each material consists of (at least) 3 components for each of ambient, diffuse specular color and also shininess (which totals up to 10 floats) I would consider it to be a tremendous waste of memory to store all of these values for each vertex.

Does OpenGL provide us with a more elegant/viable way to achieve the same result with a more reasonable memory consumption or do I have to swallow the bitter pill?

# Answer
The simplest implementation would be to do N Draw-Calls per mesh (where N is the number of unique Materials of the mesh). Each time passing next meterial settings via shader uniforms.

Another approach could be to add material index attribute to each vertex and pass an array of N material settings as uniform. Then you can choose appropriate material properties in shader.

Note: Both solutions do not handle materials transitions between vertexes within single polygon.
> 1 votes

---
Tags: opengl, models, materials
---


title: How to create a walkable crate box?

text:
# Question
Title: How to create a walkable crate box?
I have a 2D platformer with each platform having a `PlatformEffector2D` component. I want to create a crate that can be pushed.

When I jump into the edge of the crate, my player gets stuck, so I added `PlatformEffector2D` to the crate. But when the crate has a `PlatformEffector2D` component it falls below the platform.

I can remove the component and add a `Physics2D` Material with zero friction to prevent the player from getting stuck in the crate's edge, but I can't walk above the crate (because the zero friction). The images below illustrate it.

Player getting stuck in the edge of the crate that don't have `PlatformEffector2D`.

If it has a `PlatformEffector2D` it will fall below the platform.

My objects have the following components (when the player gets stuck at the edge of a crate):

* `Player (BoxCollider2D, Rigidbody2D)`
* `Crate (BoxCollider2D, Rigidbody2D)`
* `Platform (EdgeCollider2D, PlatformEffector2D)`

What should I do so my player can push the crate and walk above the crate? Would anyone happen to have a sample script?

FYI: I use Physics2D.OverlapCircle to detect the ground. (Unity 5.4.0)

# Answer
Finally I fixed it. I added two empty `GameObject`s to check the right and left side of the player. Now he can push the crate and walk above it without being stuck at the edge of the crate.

```
// Check if player is on the ground or not
grounded = Physics2D.OverlapCircle (groundCheck.position, groundRadius, whatIsGround);
rightSided = Physics2D.OverlapCircle (rightSideCheck.position, groundRadius, whatIsGround);
leftSided = Physics2D.OverlapCircle (leftSideCheck.position, groundRadius, whatIsGround);

// Movement
if (!grounded && (rightSided || leftSided)) {
    // Do nothing
} else {
    // Handle movement input
}

```
> 3 votes

---
Tags: unity, 2d, platformer
---


title: LibGDX Crash when destroying a body?

text:
# Question
Title: LibGDX Crash when destroying a body?
So I'm working on a LibGDX game, and when a bullet body collides with a block, I want to destroy the bullet. I'm calling:

```
Globals.gameMan.world.destroyBody(bullet.body);

```

and for whatever reason, the entire game crashes after this. I'm given a message with the option to debug twice, and when I click it, nothing happens. Thank you, and sorry for the noob question.

# Answer
> 1 votes
You can't destroy a body inside the cycle of Box2d World. You need to mark that body to be destroyed and destroy it after the `world.step()` is finished executing. Get an array of bodies to be destroyed and destroy them afterwards.

# Answer
> 1 votes
Make sure you're not calling `World.destroyBody` passing a `Body` that has already been destroyed.

Also, from where are you calling `World.destroyBody`, if it's from a **Box2D** call-back (a collision handler, for example) you are not allowed to destroy bodies. If that is the case you need to make note of the `Body` to destroy and then destroy it outside of the call-back.

---
Tags: java, libgdx, box2d
---


# Question
Title: Geometry shader wireframe not rendering correctly GLSL/OpenGL/C++
Im trying to make a tool for skinning 3D models, and as part of that, I need to show faces wireframed, making use of the geometry shader stage.

Im following the approach suggested here and here. My problem however, is that it ends up looking like this:

Where some of the lines get thicker when the faces are oriented in a specific way. This is my geometry shader: (The vertex shader just passes vertices, so theres no need to show it)

```
#version 400

layout(triangles) in;
layout(triangle_strip, max_vertices = 3) out;

noperspective out vec3 gDist;

void main()
{
//800,600=window size(make uniform later)
vec2 p0 = vec2(800,600) * gl_in[0].gl_Position.xy/gl_in[0].gl_Position.w;
vec2 p1 = vec2(800,600) * gl_in[1].gl_Position.xy/gl_in[0].gl_Position.w;
vec2 p2 = vec2(800,600) * gl_in[2].gl_Position.xy/gl_in[0].gl_Position.w;

vec2 v0=p2-p1;
vec2 v1=p2-p0;
vec2 v2=p1-p2;
float area = abs(v1.x*v2.y - v1.y * v2.x);

gDist = vec3(area/length(v0),0,0);
gl_Position = gl_in[0].gl_Position;
EmitVertex();

gDist = vec3(0,area/length(v1),0);
gl_Position = gl_in[1].gl_Position;
EmitVertex();

gDist = vec3(0,0,area/length(v2));
gl_Position = gl_in[2].gl_Position;
EmitVertex();

EndPrimitive();
}

```

and frag shader:

```
#version 400

noperspective in vec3 gDist;

const vec4 wire_color = vec4(0.0,0.5,0.0,1);
const vec4 fill_color = vec4(1,1,1,0);

void main()
{
float d = min(gDist[0],min(gDist[1],gDist[2]));
float i = exp2(-2*d*d);

gl_FragColor = i * wire_color + (1.0 - i) * fill_color;
}

```

So what am I doing wrong here? I feel like im missing something. Is anyone familiar with this?

# Answer
I suspect the main problem with my original attempt was thinking in 2D only. Before I was calculating the edge distance as it appears onscreen, when I should be calculating the value with 3D space in mind. The solution I reach is not the same outlined here on page 216, but it still seems to be correct. It looks like this using the Stanford bunny:

As before, the vertex shader doesn't do anything for now, other than pass vertices after being put in projection*view*model space, so I wont bother posting it.

In the geometry shader there are some differences however, notice how I don't divide by .w and just extract the values directly:

```
#version 400

layout(triangles) in;
layout(triangle_strip, max_vertices = 3) out;

in vec2 fUV[]; //uv coordinates
out vec2 gUV;

noperspective out vec3 GEdgeDistance;

void main()
{
    float a = length(gl_in[1].gl_Position.xyz - gl_in[2].gl_Position.xyz);
    float b = length(gl_in[2].gl_Position.xyz - gl_in[0].gl_Position.xyz);
    float c = length(gl_in[1].gl_Position.xyz - gl_in[0].gl_Position.xyz);

    float alpha = acos( (b*b + c*c - a*a) / (2.0*b*c) );
    float beta = acos( (a*a + c*c - b*b) / (2.0*a*c) );
    float ha = abs( c * sin( beta ) );
    float hb = abs( c * sin( alpha ) );
    float hc = abs( b * sin( alpha ) );

    gUV=fUV[0];
    GEdgeDistance = vec3( ha, 0, 0 );
    gl_Position = gl_in[0].gl_Position;
    EmitVertex();

    gUV=fUV[1];
    GEdgeDistance = vec3( 0, hb, 0 );
    gl_Position = gl_in[1].gl_Position;
    EmitVertex();

    gUV=fUV[2];
    GEdgeDistance = vec3( 0, 0, hc );
    gl_Position = gl_in[2].gl_Position;
    EmitVertex();
}

```

In the frag shader there are some options to how you want to display the final model, perhaps only parts of it wireframed, perhaps with phong shaders etc, so Im only posting a basic frag shader that leaves everything to the inquisitive:

```
#version 400

in vec2 gUV;

uniform sampler2D png_tex;
uniform float wire_thickness;

noperspective in vec3 GEdgeDistance;

void main()
{
//base fragment color off of which edge is closest
float distance = min(GEdgeDistance[0],min(GEdgeDistance[1],GEdgeDistance[2]));

//draw the each side with different color, displaying the barymetric concept
//if (distance==GEdgeDistance[0])gl_FragColor=vec4(0.52,0,0,1);
//else if (distance==GEdgeDistance[1])gl_FragColor=vec4(0,0.52,0,1);
//else if (distance==GEdgeDistance[2])gl_FragColor=vec4(0,0,0.52,1);

if (distance<wire_thickness)gl_FragColor=vec4(1); //draw fragment if close to edge
else if (distance>=wire_thickness)discard; //discard if not
}

```

The main issue now is whether the geometry shader is as efficient as it could be. I'm certain there is a way to do this making use of dot products and less costly operations than sin/cos/tan trigonometry.

Further reading:

NVIDIA: white paper - solid wireframe,

Two Methods for Antialiased Wireframe Drawing with Hidden Line Removal

David Wolff - OpenGL 4.0 Shading Language Cookbook
> 1 votes

---
Tags: opengl, c++, glsl
---


# Question
Title: Why do I get this error with FB.LogInWithPublishPermissions?
I don't know what's wrong. I know that `FB.Login` is already deprecated. I don't know what syntax to use.

```
public class FBholder : MonoBehaviour {
    void Awake(){
        FB.Init (SetInit, OnHideUnity);
    }

    private void SetInit()
    {
        Debug.Log ("FB Init Done");

        if (FB.IsLoggedIn) {
            Debug.Log ("FB Logged in");
        } else {
            FBlogin ();
        }
    }

    private void OnHideUnity(bool isGameShown)
    {
        if (!isGameShown) {
            Time.timeScale = 0;
        } else {
            Time.timeScale = 1;
        }
    }

    void FBlogin()
    {
        FB.LogInWithPublishPermissions ("user_about_me, user_birthday", AuthCallback);
    }

    void AuthCallback(ILoginResult result)
    {
        if (FB.IsLoggedIn) {
            Debug.Log ("FB Logged in worked");
        } else {
            Debug.Log ("FB Logged in failed");
        }
    }
}

```

and I'm getting this error

> Assets/FBholder.cs(40,6): error CS1502: The best overloaded method match for \`Facebook.Unity.FB.LogInWithPublishPermissions(System.Collections.Generic.IEnumerable, Facebook.Unity.FacebookDelegate)' has some invalid arguments

and this

> Assets/FBholder.cs(40,35): error CS1503: Argument `#1' cannot convert`string' expression to type \`System.Collections.Generic.IEnumerable'

# Answer
> 1 votes
According to this link, function LogInWithPublishPermissions has 2 arguments: IEnumerable permissions , FacebookDelegate callback. That's why your code dont compile.

If you took this code from tutorial, it maybe just outdated. Change according to FB API Documentation.

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