title: How do dialog trees work?

text:
# Question
Title: How do dialog trees work?
That is, what is connected to what and how to move between lines of speech when a sub-conversation ends?

If you have any examples of a basic dialog tree in C#, please post them.

# Answer
The name "dialogue tree" is a bit misleading - they usually are simple directed graphs, not just trees. The basic data structure of such graphs usually consists of some kind of "data" for the nodes, which represent the points we are at in the conversation, and links from them to other nodes, which represent what is being said and done by the participants and optionally have conditions on them to limit their visibility or scripts to perform various additional actions. Usually one of the nodes is the default starting node (typical labels for that are "ROOT", "START" and "GREETING"), and nodes which have no valid links leading from them end the conversation.

In most cases, the graph is represented in-memory as a list of `Node` data structures, each having at least an ID and a list of 0..n `Link` data structures. The list can be local to the NPC or a global one; the second case is preferred if you have lots of generic NPCs which can be talked to for information, but offer no specific conversations on their own. The system itself finds the starting conversation node for the NPC, remembers its ID as the current conversation ID, presents the currently valid links for the player to chose from (or "\[end conversation\]" if there are no valid links) and waits for input. When the player chooses a link, the associated dialogue lines get displayed and any associated scripts run.

Instead of having complex rules and conditions on links, you can instead get by with a simple "valid" boolean variable, which can be then changed from either the scripts of other conversation links (including the default one from the starting node) or by outside mechanisms. In general, this approach is simpler but only suitable for games with very few such conversations, since it moves the logic of "When is this response possible?" *away* from the response data itself.

---

Note that the structure I describe here is slightly different from Byte56's in that the nodes don't need to have any dialogue lines; the links can have them all. In the most basic variant, this translates to the following structure.
> 30 votes

# Answer
Dialog trees are created with a directed graph structure.

The graph is traversed based on the dialog decisions the player makes. The dialog options provided to the user come from the edges that define the paths to other dialog nodes.

Directed graphs are a basic data structure. They can easily be implemented and you'll likely want to implement it yourself. Since you'll want to tailor the graph to your dialog needs.

Some of the nodes may need to have special conditions met in order to show up. For example, the player would require a skill in speech above X. Or the player needs to have completed mission Z before they can progress down one branch of dialog. Or they need to ask something 4 times before the NPC will discuss it with them. These features will be custom to your game. But are worth mentioning when you're implementing the node and edge traversal. Of course it's always best to start with the simplest form and build up from there.
> 17 votes

# Answer
I've built a simple dialogtree system: http://iki.fi/sol/d3/ the "engine" itself is currently plain c, but the data produced by the editor is pretty simple to use in any language. The tool outputs XML, JSON and a custom binary format.

The main concept is pretty simple:

Each node (which I call "card", as with the above analogue) of the dialog consists of question text and zero or more answers. Each of the answers leads to another card.

There's also a tag system where certain answers are shown to the user only if a tag is set (or a tag is not set). Entering a card sets (or unsets) specified tags.

This is pretty much everything one needs to do just about any kind of dialog in a game. The "question text" can be plain text, or it can be a script to drive animation or whatnot.
> 9 votes

# Answer
You can use TreeSharp and behaviour trees to model a dialogue system. TreeSharp is a library that provides a simple behaviour tree implementation. IA bots for wow are done with this, so it's mature... :)

My implementation has nodes that let choose between answers, and each answer can be joined to othe dialogue or an action, or a sequence of actions, or a node that lets going to another dialog... or what yo want...

I have used brainiac editor to make it visually... but at the end it produces c# code based on treesharp...

http://www.youtube.com/watch?v=6uGg6bUYyUU
> 4 votes

# Answer
You want a directed (possibly cyclic) graph.

You'd model the nodes as objects, and all the outgoing arrows in a graph's node are modeled as separate objects, too. The node has a list of outgoing arrows, and each "arrow" object has a text to display and a reference to the destination. Not sure, but I think in C# objects are always referenced, so you just create the objects first, and then when you create the arrow objects, plug the same object into two arrows' destination field. (In C++ you'd use a reference or pointer type, Node& or Node\*)

For loading things like this from disk, one usually gives each node a unique ID number, then loads all nodes into an array where the index is that unique number. Then the arrows are serialized by writing the number, not the actual object out.

When you load an arrow, you use the array and ID to get a reference to the node it points to. If you wrote out the object twice, you'd get two separate objects that just look identical, which is probably not what you wanted.

Processing a dialog tree becomes very simple. You just put the root node in a `currentNode` variable, display the whole thing somehow, then when a choice is made, set `rootNode` to the arrow's destination. In pseudocode:

```
Node&    currentNode = dialogTree.node[0];
while( currentNode != END_CONVERSATION_PSEUDO_NODE )
{
    stage.displayNode( currentNode );
    currentNode = stage.waitForUserToChoose();
}

```
> 2 votes

# Answer
I recently had to develop something like this using Node, and opted for a very basic text file structure to represent a directed graph of conversation nodes.

You can see the resulting code and text format at:

https://github.com/scottbw/dialoguejs

It doesn't support conditions or event triggers (yet), but is probably simple enough to start with for many game devs.

(The code itself in GPL, btw)
> 1 votes

---
Tags: c#, dialogue-tree
---


# Question
Title: (Gamemaker Studio) How to draw a vector?
Let's say I want to start from the center pixel of a screen of indeterminate size, and I want to be able to draw an arrow from this center pixel to any other pixel.

The only way I know how to do that is to assign entirely new sprites for each and every possible direction and magnitude of the vector...which might work (even if it's tedious) for around 10 or even 20 possible combinations, but much more and it would really chug a system with the switch statement alone to find which sprite to use.

So, the obvious, much better, way of doing this is just to dynamically draw from one point to another...I don't know how to though.

# Answer
You can draw whatever you want on the screen by using the `draw_*` functions related to primitive shapes instead of sprites.

As example, we can dinamically draw the velocity vector of *any* object by considering the built-in variables `x`, `y`, `hspeed` and `vspeed`, or alternatively the variables `speed` (which is the magnitude of the combination of `hspeed` and `vspeed`) and `direction`. In the first case, we can draw such vector as follows:

```
draw_arrow(x,y,x+hspeed,y+vspeed,5);

```

You can multiply `hspeed` and `vspeed` for a given constant if you want arrows to be drawn longer, depending on speed values:

```
var rt = 2.5;
draw_arrow(x,y,x+rt*hspeed,y+rt*vspeed,5);

```

If you are working with a magnitude (like `speed`) and an angle (like `direction`), or similars, you need to add just few more lines:

```
// MAG can be any magnitude
// DIR can be any 0-360 angle
var vec_x = lengthdir_x(mag,dir);
var vec_y = lengthdir_y(mag,dir);
draw_arrow(x,y,x+vec_x,y+vec_y,5);

```

Matter is, you can draw arrows, lines, or even circles (assuming your vector as the circumference radius), etcetera. Also, you can change colour and line style to best fit your game appearance.
> 1 votes

---
Tags: game-maker
---


# Question
Title: StartCoroutine from other MonoBehaviour is not working
I am trying to replicate the model of Unity documentation about coroutines, but I want to partition it in another class:

I have these two:

```
public class A: MonoBehaviour {

    void Start() {
        print("Starting " + Time.time);
        B test = new B();
        StartCoroutine(test.WaitAndPrint(2.0F));
        print("Before WaitAndPrint Finishes " + Time.time);
    }
}

public class B: MonoBehaviour {

    public IEnumerator WaitAndPrint(float waitTime) {
        yield return new WaitForSeconds(waitTime);
        print("WaitAndPrint " + Time.time);
    }
}

```

It prints, ignoring the coroutine:

*Starting 0 Before WaitAndPrint Finishes 0*

The two methods work well in the same class.

# Answer
> 1 votes
`B test = new B()` is not allowed for Components & MonoBehaviours in Unity; there cannot be constructors.

Use something like: `test = gameObject.AddComponent<B>();`

---
Tags: unity, coroutines, monobehaviour
---


# Question
Title: Should I link GLFW and GLEW into my engine directly?
I want to write my own (simple) game engine with OpenGL. I use GLEW and GLFW and so far linked it successfully.

Should the engine or the respective game (which depends on the engine) include GLFW and GLEW?

Ultimately I would like to create a library out off my engine and include it into my game, but I'm not quite sure if that is possible, if its the case, that the engine should depend on GLFW and GLEW. Would I have to link all the libraries that are neccessary for GLEW and GLFW into the game plus the engine-lib itself?

# Answer
> 2 votes
This would depend on whether your game uses direct calls to the bindings or not. So if your library deals with all low level stuff itself, you build it, link to your game and you are good to go, no need for extra linking of GLFW, GLEW, etc. But going this way your game will not have direct access to the recources and functions these helper libraries give. If you are working alone on your library and game, and you are doing it just as a hobby, I'd recommend not to bother yourself with lib/game separation. Just create one project with your game and have all the low level stuff needed at hand.

# Answer
> 0 votes
It's been a while since I've done this sort of thing, but I believe it depends on whether you are using static or dynamic libraries & the GLFW build guide seems to back that up:

> GLFW is essentially a wrapper of various platform-specific APIs and therefore needs to link against many different system libraries. If you are using GLFW as a shared library / dynamic library / DLL then it takes care of these links. However, if you are using GLFW as a static library then your executable will need to link against these libraries.

---
Tags: glfw, glew
---


title: Rounded corners in XNA?

text:
# Question
Title: Rounded corners in XNA?
Is there any way that I can make rounded corners on a rectangle rendered in XNA through primitives (line-strips)? I want to make my UI a bit more fancy than it is already, and I would like the code to be flexible, without too many textures involved.

# Answer
> 8 votes
You can render your primitive, and make a shader that can create these rounded corners.
Here is a simple pixel shader in pseudocode that can draw a rounded square:

```
xDist = abs(x-0.5)
yDist = abs(y-0.5)
xD = xDist*xDist*4
yD = yDist*yDist*4
alpha = floor((1-xD)*(1-yD)*5)

```

Result of this pixel shader:

If you use shaders, you can make really fancy UI, even an animated one.

For me great to prototype simple pixel shaders is program EvalDraw

# Answer
> 5 votes
Another way to do this is to use a 'button stretch' (also called a 'box stretch' or 'nine-patch'). Essentially you create an image that is made up of 9 parts:

In order to draw that button at any size, you draw each piece (from top to bottom, left to right):

1. Draw unscaled at the top left of the destination rectangle.
2. Draw scaled horizontally (with `width - ((1) + (2)).Width`) at the top of the destination rectangle, with the left offset by the width of (1).
3. Draw unscaled at the top right of the destination rectangle.
4. Draw scaled vertically (with `height - ((1) + (2)).Height`) at the left of the destination rectangle, with the top offset by the height of (1).
5. Draw scaled in both directions (with the width of (2) and height of (4)), offset by the width and height of (1).
6. Draw scaled vertically (same height as (4)) at the right of destination rectangle, offset by the height of (1).
7. Draw unscaled at the bottom left of the destination rectangle.
8. Draw scaled horizontally (same height as (2)) at the bottom of the destination rectangle, offset by the width of (1).
9. Draw unscaled at the bottom right of the destination rectangle.

If you look at the button you will see that it doesn't matter if (2), (5) and (7) get scaled horizontally (because it is essentially a straight line); in the same manner (4), (5) and (6) can be scaled vertically without affecting the quality of the image.

# Answer
> 0 votes
Here is the code for the "nine-patch" approach:

```
public static class SpriteBatchExtensions
{
    public static void DrawRoundedRect(this SpriteBatch spriteBatch, Rectangle destinationRectangle,
        Texture2D texture, int border, Color color)
    {
        // Top left
        spriteBatch.Draw(
            texture,
            new Rectangle(destinationRectangle.Location, new Point(border)),
            new Rectangle(0, 0, border, border),
            color);

        // Top
        spriteBatch.Draw(
            texture,
            new Rectangle(destinationRectangle.Location + new Point(border, 0),
                new Point(destinationRectangle.Width - border * 2, border)),
            new Rectangle(border, 0, texture.Width - border * 2, border),
            color);

        // Top right
        spriteBatch.Draw(
            texture,
            new Rectangle(destinationRectangle.Location + new Point(destinationRectangle.Width - border, 0), new Point(border)),
            new Rectangle(texture.Width - border, 0, border, border),
            color);

        // Middle left
        spriteBatch.Draw(
            texture,
            new Rectangle(destinationRectangle.Location + new Point(0, border), new Point(border, destinationRectangle.Height - border * 2)),
            new Rectangle(0, border, border, texture.Height - border * 2),
            color);

        // Middle
        spriteBatch.Draw(
            texture,
            new Rectangle(destinationRectangle.Location + new Point(border), destinationRectangle.Size - new Point(border * 2)),
            new Rectangle(border, border, texture.Width - border * 2, texture.Height - border * 2),
            color);

        // Middle right
        spriteBatch.Draw(
            texture,
            new Rectangle(destinationRectangle.Location + new Point(destinationRectangle.Width - border, border),
                new Point(border, destinationRectangle.Height - border * 2)),
            new Rectangle(texture.Width - border, border, border, texture.Height - border * 2),
            color);

        // Bottom left
        spriteBatch.Draw(
            texture,
            new Rectangle(destinationRectangle.Location + new Point(0, destinationRectangle.Height - border), new Point(border)),
            new Rectangle(0, texture.Height - border, border, border),
            color);

        // Bottom
        spriteBatch.Draw(
            texture,
            new Rectangle(destinationRectangle.Location + new Point(border, destinationRectangle.Height - border),
                new Point(destinationRectangle.Width - border * 2, border)),
            new Rectangle(border, texture.Height - border, texture.Width - border * 2, border),
            color);

        // Bottom right
        spriteBatch.Draw(
            texture,
            new Rectangle(destinationRectangle.Location + destinationRectangle.Size - new Point(border), new Point(border)),
            new Rectangle(texture.Width - border, texture.Height - border, border, border),
            color);
    }
}

```

It is invoked as:

```
spriteBatch.DrawRoundedRect(
    dest, // The coordinates of the Rectangle to be drawn
    rectangleTexture, // Texture for the whole rounded rectangle
    16, // Distance from the edges of the texture to the "middle" patch
    Color.OrangeRed);

```

---
Tags: xna
---


# Question
Title: Render object with different shader depending on the camera
I have an object with a custom shader. When it is being rendered by cameraA, then I want it to render a particular way (ex red). When it is rendered by another cameraB, I want it to render a different way (ex green).

Is there some way I can tell what is the current camera rendering in the shader? Or perhaps I can toggle a boolean value in my shader between rendering of each camera? Where would I do this (OnPostRender() maybe?).

# Answer
**Changing shader properties for each camera**

You can accomplish this with a script on the camera. In my example I change the color but you can extend this idea to any property in the shader.

```
[ExecuteInEditMode]
public class CameraMaterialChanger : MonoBehaviour {

    public Color myColor; // color you want the camera to render it as
    public Material material; // material you want the camera to change
    public string colorPropertyName; // name of the color property in the material's shader

    void OnPreRender() {
        _default = material.GetColor(colorPropertyName);
        material.SetColor(colorPropertyName, myColor);
    }

    void OnPostRender() {
        material.SetColor(colorPropertyName, _default);
    }

    private Color _default;
}

```

It works by changing the color on the material before rendering, and then restoring it to the original color afterwards to avoid permanently altering the material. Note that property names need to be prefixed with an underscore.

**Changing the shader itself for each camera**

This makes use of replacement shaders and might require more work to set up how you want.

```
[ExecuteInEditMode]
public class CameraShaderChanger : MonoBehaviour {

    public Shader replacementShader; // the shader you want to use with this camera
    public string replacementTag;

    void OnValidate() {
        GetComponent<Camera>().SetReplacementShader(replacementShader, replacementTag);
    }
}

```

Replacement shaders work the following way (from the docs):

> It works like this: the camera renders the scene as it normally would. the objects still use their materials, but the actual shader that ends up being used is changed:
>
> * If replacementTag is empty, then all objects in the scene are rendered with the given replacement shader.
> * If replacementTag is not empty, then for each object that would be rendered:
>     + The real object’s shader is queried for the tag value.
>     + If it does not have that tag, object is not rendered.
>     + A subshader is found in the replacement shader that has a given tag with the found value. If no such subshader is found, object is not rendered.
>     + Now that subshader is used to render the object.

Also, the reverse call of `SetReplacementShader(Shader, string)` is `ResetReplacementShader(void)`.
> 4 votes

---
Tags: unity, opengl, shaders, rendering
---


# Question
Title: How to make a moving background with PyGame?
I'd like to create a moving background in my Python game, with an image, that moves up until it reaches the end, then it goes back to its first position. I'm still in my learning process and this is really troublesome, because I don't even know the approach it.

image:

What I have for now:

```
import pygame, random, sys

def main():
  pygame.init()

  global screenSize, allColors, FPS, clock, surface

  screenSize = (640, 480)

  surface = pygame.display.set_mode(screenSize)
  pygame.display.set_caption('Space Shooters')

  black    = (0  , 0  , 0  )
  white    = (255, 255, 255)
  gray     = (100, 100, 100)
  navyblue = (60 , 60 , 100)
  red      = (255, 0  , 0  )
  green    = (0  , 255, 0  )
  blue     = (0  , 0  , 255)
  yellow   = (255, 255, 0  )
  orange   = (255, 155, 55 )
  purple   = (255, 0  , 255)
  cyan     = (0  , 255, 255)
  #             0      1     2      3      4      5       6      7       8       9
  allColors = [white,red, green, blue, yellow, orange, purple, cyan, navyblue, gray]
  clock = pygame.time.Clock()

  FPS = 64
#-------------------------------------------------------------------------------
  spaceship = Spaceship()
  bullets = Bullet(spaceship)
  while True:
    #step1 SetDelay
    clock.tick(FPS)
    #step2 reactOnPlayerInput
    for event in pygame.event.get():
      if event.type == pygame.QUIT:
        terminate()
      if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_ESCAPE:
          terminate()
        if event.key == pygame.K_UP:
          spaceship.moveUp = True
          spaceship.moveDown = False
        if event.key == pygame.K_DOWN:
          spaceship.moveUp = False
          spaceship.moveDown = True
        if event.key == pygame.K_LEFT:
          spaceship.moveRight = False
          spaceship.moveLeft = True
        if event.key == pygame.K_RIGHT:
          spaceship.moveRight = True
          spaceship.moveLeft = False
        if event.key == pygame.K_SPACE:
          bullets.isShooting = True

      if event.type == pygame.KEYUP:
        if event.key == pygame.K_UP:
          spaceship.moveUp = False
        if event.key == pygame.K_DOWN:
          spaceship.moveDown = False
        if event.key == pygame.K_LEFT:
          spaceship.moveLeft = False
        if event.key == pygame.K_RIGHT:
          spaceship.moveRight = False
        if event.key == pygame.K_SPACE:
          bullets.isShooting = False

    #step3 updateClasses/Variables
    spaceship.update()
    bullets.update(spaceship)
    #step4 renderEverything
    surface.fill((255,255,255))
    bullets.render()
    spaceship.render()
    pygame.display.update()

def terminate():
  pygame.quit()
  sys.exit()

class Spaceship():
  def __init__(self):
    self.height = 32
    self.width = 28

    self.ssIMG = pygame.image.load("/home/bucky/Dokumente/Computing/Python/scripts/pygame/spaceShooter/spaceShip.png")

    self.centerx = screenSize[0] / 2
    self.centery = screenSize[1] / 2

    self.speed = 5
    self.color = allColors[9]

    self.moveLeft, self.moveRight, self.moveUp, self.moveDown = False, False, False, False

    self.rect = pygame.Rect(self.centerx - self.width / 2, self.centery - self.height / 2, self.width, self.height)

  def update(self):
    if self.moveLeft and self.rect.left > 0:
      self.rect.centerx -= self.speed
    if self.moveRight and self.rect.right < screenSize[0] - 1:
      self.rect.centerx += self.speed
    if self.moveUp and self.rect.top > 0:
      self.rect.centery -= self.speed
    if self.moveDown and self.rect.bottom < screenSize[1] - 1:
      self.rect.centery += self.speed

  def render(self):
    surface.blit(self.ssIMG, self.rect)

class Bullet():
  def __init__(self, spaceship):
    self.bulletIMG = pygame.image.load("/home/bucky/Dokumente/Computing/Python/scripts/pygame/spaceShooter/bullet.png")

    self.width = 8
    self.height = 12

    self.centerx = spaceship.rect.centerx
    self.centery = spaceship.rect.centery

    self.color = allColors[4]

    self.speed = 16

    self.isShooting = False

    self.listOfBullets = []

  def update(self, spaceship):
    for i in range(len(self.listOfBullets)):
      if i >= len(self.listOfBullets):
        break
      if self.listOfBullets[i]['counter'] >= 64:
        del self.listOfBullets[i]
        continue
      self.listOfBullets[i]['rect'].centery -= self.speed
      self.listOfBullets[i]['counter'] += 1

    if self.isShooting:
      self.listOfBullets.append({
      'rect':pygame.Rect(spaceship.rect.centerx - self.width / 2, spaceship.rect.centery - self.height, self.width, self.height),
      'counter':0
      })

  def render(self):
    for i in range(len(self.listOfBullets)):
      surface.blit(self.bulletIMG, self.listOfBullets[i]['rect'])

main()

```

\[Edit\]:

With the right approach of Areeb I could figure out how to move the background permanently. I added a Background class, with a 'bgY'-variable, which is permanently decreasing, until it goes out of the screen, than it goes back to its first position. But I had to add the same picture twice with the diffrence of a little displacement, because when the background runs out of the screen there will not be any background at all:

```
class Background():
    def __init__(self):
        self.bgimage = pygame.image.load('/home/bucky/Dokumente/Computing/Python/scripts/pygame/spaceShooter/weltraum.png')
        self.rectBGimg = self.bgimage.get_rect()
        self.bgimage = pygame.transform.scale(self.bgimage, (int(screenSize[0] / self.rectBGimg.width * self.rectBGimg.width), int(screenSize[0] / self.rectBGimg.width * self.rectBGimg.height)))
        self.rectBGimg = self.bgimage.get_rect()

        self.bgY1 = 0
        self.bgX1 = 0

        self.bgY2 = self.rectBGimg.height
        self.bgX2 = 0

        self.movingUpSpeed = 5

    def update(self):
        self.bgY1 -= self.movingUpSpeed
        self.bgY2 -= self.movingUpSpeed
        if self.bgY1 <= -self.rectBGimg.height:
            self.bgY1 = self.rectBGimg.height
        if self.bgY2 <= -self.rectBGimg.height:
            self.bgY2 = self.rectBGimg.height

    def render(self):
        surface.blit(self.bgimage, (self.bgX1, self.bgY1))
        surface.blit(self.bgimage, (self.bgX2, self.bgY2))

```

Watch the result: https://youtu.be/dhuPA2v8gG0

# Answer
A background really isn't anything but an image that you draw before anything else.

> The easiest way to do that is to import the image using `image.load()` and save it to the variable background. After doing that create a new variable `background_y` that saves the position of where the background is.
>
> After that, go to your update function and decrement `background_y`, because you want it to move up. Then add an if statement that checks whether `background_y` is equal to the negative height of the background image, which can be gotten using `background.get_height()`. And in that if statement, set `background_y` to whatever it was originally.
>
> Now having done that, just add `surface.blit(background, (0, background_y))` right after you clear the screen using `surface.fill()`. That will draw the background in the right position.

That should get you the results you have been looking for.

If you want an example with code, Just ask in the comments.
> 1 votes

---
Tags: graphics, python, pygame
---


# Question
Title: Should I patent game before putting it on Apple App Store?
If it's a huge hit, I could then patent it. Or, if I put my game up on App Stores before patenting, does this cause a problem? Would this invalidate a patent application?

Should I bother to even patent the game? If I patent my game's pretty innovative algorithm, then it's public and anyone in a foreign country might duplicate it. Also, legal costs can be horrendous defending a patent infringement.

# Answer
> 6 votes
You can't patent a game. You might pattern a particular algorithm but it's unlikely to be of benefit to you to do so because of a couple reasons.

1. Patents are highly specific. I was worried I was violating a memory management patent, but when I looked closely it was obvious the algorithm was completely different. This makes it easy to circumvent many patents.
2. You can't patent obvious things. You can't make a broad patent that patents making shadows in video games. This works together with #2 to mean it is not really possible to totally block people out of doing the same basic idea you do.
3. It costs money to patent.
4. It costs even more money to defend a patent.
5. It is almost impossible to be sure if someone violates an algorithm patent unless they show off the source code. Your patent is useless if it's unenforceable.
6. Prior art. You'd be surprised what is out there. If just one person has something very similar created then your patent is dead, even if you have not found it yourself yet this can crop up later.

So in short it may make sense for a large company to patent things which might help them keep people from making a direct clone of their software, but in software it's expensive and tricky to get anything useful out of the patent process.

---
Tags: ios, legal, appstore
---


# Question
Title: How to use GdxAI with libgdx ashley ecs framework?
I'm planning to use GdxAI Telegraph in GdxAshley ecs framework, my problem is how I'm gonna create a telegraph component if I wanted to dispatch a message? I have created `AIComponent` and `AISystem`.

```
class AIComponent implements Component{
    StateMachine<Entity, EntityState> fsm;
}

class AISystem extends IteratingSystem {

    public void processEntity(Entity entity, float deltaTime) {
         AIComponent ai = Mappers.ai.get(entity);

         ai.fsm.update();
    }

}

```

For example I wanted to dispatch a message using space input.

```
if(Gdx.input.isTouched()) {

     MessageManager.getInstance().dispatchMessage(
                0.0f, // no delay
                entitySender, entityReceiver,
                MessageType.SAYHELLO, null);

}

```

I'm thinking of creating a class that extends `Entity` and implement it to `Telegraph`. But the ashley ECS approach will be disregard here.

```
class EntityAI extends Entity implements Telegraph {

     StateManager fsm;

     public EntityAI (StateManager fsm) {
          this.fsm = fsm;
     }

     @Override
     public boolean handleMessage(Telegram telegram) {
         return fsm.handleMessage(telegram); // In this part, the logic exists. Im thinking of creating a System that will handle message? but how
     }

}

```

**Question** How do I properly convert the this EntityAI to entity-componentbased-system approach? In the below code is not tested but it was the idea entered my mind.

```
class Script implements Telegraph {

     StateManager fsm;

     public Script (StateManager fsm) {
          this.fsm = fsm;
     }

     @Override
     public boolean handleMessage(Telegram telegram) {
         return fsm.handleMessage(telegram);
     }
}

class ScriptComponent implements Component {
     Script script;
}

 ScriptComponent script
 AIComponent ai
 ai.fsm = new StateMachine();
 script.script = new Script(ai.fsm); // as you can see here the fsm is used twice in component

 // AIComponent has StateMachine
 // ScriptComponent need StatMachine
 // do you in the above code is a good idea?

MessageManager.getInstance().dispatchMessage(
                0.0f, // no delay
                scriptSendeer, scriptReceiver,
                MessageType.SAYHELLO, null);

```

# Answer
For now this is the way I handle AI messaging with ashley ECS in libgdx.

```
TelegraphAgent implements Telegraph {

    StateMachine fsm;

    public TelegraphAgent (StateMachine fsm) {
        this.fsm = fsm;
    }

    @Override
    public void handleMessage(Telegram msg) {
        fsm.handleMessage(msg):
    }
}

AIComponent implements Component {

    StateMachine fsm;
    TelegraphAgent telegraph;  // or create another class called TelegraphAgentComponent

}

```
> 0 votes

# Answer
I'd try to avoid using any form of event dispatch within an ECS.

From the looks of it you're trying to change state based on some kind of input. I assume that block of code where you track input is inside a system. So instead of dispatching an event why not just update the requisite components directly from that system.

Systems can process multiple types of components, but more importantly any two Systems can process components of the same kind on a given entity. So say you have a system (call it SytemA) that updates a component based on input, then its possible for another system (call it SystemB) to take up that component to do further processing. That is possible because SystemA and SystemB have components in common. That's how you normally track and respond to changes in state in an ECS.
> 1 votes

---
Tags: c++, java, libgdx, ai
---


# Question
Title: Raycasting against my plane does not detect collisions in Unity
I'm trying to keep the camera above a plane which acts as the ground, so I wrote this bit of code:

```
RaycastHit hit;
if (!Physics.Raycast (transform.position, new Vector3 (0, -50, 0), out hit, 5)) {
    transform.position = new Vector3 (0, 20, 0);
    Debug.Log ("No ground found when raycasting down!");
    Debug.DrawRay (transform.position, new Vector3 (0, -50, 0), Color.red, 0, true);
} else {
    if (hit.distance <= 1) {
        transform.position = new Vector3 (transform.position.x, 1, transform.position.z);
    }
}

```

The camera is clearly over the plane on position 0, 20, 0 while the plane is at 1, 1, 1, with scale 50, 1, 50, but it never detects a hit. The ray drawn by DrawRay() **does** intersect the plane.

The plane is oriented upwards, but just to be sure I tried raycasting from below as well, without success.

I have also tried replacing the mesh collider with a box collider using size 10, 1, 10 (I'm not sure why, this seems to be the same size as my scaled plane) and 10, 10, 10. Neither worked.

What Am I missing?

# Answer
I found the problem while modifying my code to try out `Jon`'s sugestions. Somehow I added a max distance of 5 to the RayCast. Must have gotten confused with the many overloads or something.

It works if I modify the second line like this:

```
if (!Physics.Raycast (transform.position, new Vector3 (0, -50, 0), out hit/*, 5*/)) {

```
> 1 votes

---
Tags: unity, collision-detection, physics, raycasting
---


# Question
Title: Best client/server architecture for a mobile management game?
For the past year I have worked on a small company that develops a traditional browser based strategy game, of the likes of Travian or Ogame, but using a more interactive approach like Tribal Wars 2.

The game is made in a simple php server without frameworks and a simple mysql database, and all of the game happens in a single static page that is changed through ajax calls and has a map made in pixi.js. The automatic updates are delivered to the client side through polling the server which then queries some specific database tables made for the purpose for changes.

While this approach is solid and works, it has 2 big problems:

* Having a mobile app is increasingly more important and there are not enough resources for having two separate codebases. Having a app which is simply a wrapped webview is also not a solution because the performance of a really complex page with a giant webgl map is, while usable, really subpar;
* Polling the server for changes creates a lot of programing challanges that make some simple tasks really complicated and creates a lot of convoluted code if we dont want to hurt the game performance, as we are not going make dozens of database queries every 5 seconds.

I want to start developing a game idea that I have that is basically inserted in the same genre and which is going to be, at least initially, mobile only. The real problem here is that after reading a lot on the internet, I am confused on what should be a good client/server architecture for me to start prototyping in a way that I do not run in the problems mentioned above.

Basically, above all, I want the server to be able to know which page/screen/state is each client looking at, and be able to send them messages when another client changes something on that specific screen. It would also be nice if the solution is something lightweight on the server side to be able to scale a little.

Client side I was thinking about Unity because of being cross platform, of all the environment around it (ads, analytics, a lot of support and answers on the internet), and because I have previous development experience with it.

Server side is the real question.

* Simple http calls will not work and so PHP is out of the equation.
* I have though about using node.js with socket.io to use websockets solving the polling problem. Is this a good idea? Would it be better to store the game state in a relational or nosql database in this case? Would this work on unstable mobile conections?
* Lots of people seem to use a c# and sockets for unity. Would this be overkill in this situation? Taking this approach how would the data be stored? would it be feasible with a linux server or would I need a windows server? Would this work on unstable mobile conections?
* Don't know, I'm open to suggestions.

**tl:dr: I want to make a mobile management game in unity but am confused what to choose for the server side architecture considering that I want the server to be ablose to send a message to the client without the client asking for it. Is there anything I should take in account?**

Sorry for the broad question and thanks for the help.

# Answer
> 1 votes
I think really your question seems to be one of protocol rather than language. You've ruled out HTTP, but that doesn't necassarilly rule out PHP, as you can implement websockets in that as well as other languages. The same is also true of sockest, so if you know PHP my advice would be to stay with that language server side unless there's a compelling reason not to.

You can run C# on a linux server (take a look at Mono or .Net Core), but again, if you're happier in another language then use that.

On the client side, a native Unity app will best support HTTP and Socket connections (there is a Web Socket implementation in the Asset store, but it's not native yet), and there may be other protocols supported in the Asset Store.

For the server side, I would recomend TCP sockets though, as they are fairly reliable, and don't have the overhead of a HTTP request. You can find code examples for both the client and server implementation (as well as a wrapper class for socket interaction) here. The examples assume C# on both the client and the server, but there is no reason you couldn't replace the socket code with a PHP implementation, or Node.js, as the server side language doesn't need to match that of the client side.

In each case the database backend is largely down to what you're comfortable with (MariaDb, Mysql, MongoDb etc) and the connection is language specific. Again, go with what you're familliar with, it'll save you a lot of time.

There is no one-size fits all answer. Really it's donwn to what you're experienced in and what your exact requirements may be (for example, HTTP is a perfectly acceptable implementation for slower paced games). Hopefully this'll give you some ideas about what's ouyt there though, and get you on a path you're comfortable with.

---
Tags: unity, server, mobile, websocket, socket
---


# Question
Title: How to implement accurate frame-rate-independent physics?
So, I have been working on a project for a while now and recently stumbled across a problem:

The common approach to frame-rate independent physics is to either use a fixed update interval (ie. Unity) or just multiply each physical change with delta. So it would look something like this:

```
update(int delta)
{
   ...
   positionX += velocityX * delta;
   ...
}

```

And when acceleration is added, the velocity change is treated similar:

```
update(int delta)
{
   ...
   velocityX += accelerationX * delta;
   ...
}

```

This works fine for most use cases. In fact so fine, that I haven't noticed anything was off for months. But there is a problem with this logic, namely that the position will be slightly off for entirely different frame-rates. This problem is negligible when working with small frame-rate changes, but is entirely noticeable once the delta time is changing by bigger amounts. Say, FPS rate from 30 to 600. Now, in a normal game the FPS are just locked and even if the positions are off for a few frames by like 5% it doesn't matter because one doesn't notice it. But I manually multiply the delta with a factor to accomplish a certain effect, and the error is somewhat noticeable *and game breaking*.

A small example to clarify what I mean:

There is a game object with start position posX = 0 and a x-Velocity of 10 and an horizontal acceleration of 0.1.

After two frames, for 50FPS this would lead to (with an average delta)

```
velocityX += acceleration * delta;
posX += velocityX * delta;

velocityX += 0.1 * 20; //velocityX = 12
posX += 12 * 20 //posX = 240

//next frame

velocityX += 0.1 * 20; //velocityX = 14
posX += 14 * 20 //posX = 520 (240 + 280)

```

After one frame with 25FPS, which equals the same time interval like two frames with 50FPS, this would get us:

```
velocityX += 0.1 * 40; //velocityX = 14
posX += 14 * 40; //posX = 560

```

So two situations with the same time interval elapsed we get different results (520 for 50FPS and 560 for 25FPS).

Now, the problem obviously is that there is one extra frame (in this example, it could be any number of frames but the results still differ for the same interval) in which the acceleration is applied and therefore you get further with less FPS.

Stabilizing the delta is not an option as I need different deltas for said effect, so I need to physics to be entirely independent there. Has anyone ever come across a similar situation and are there any solutions for it?

# Answer
> 5 votes
You can fix this problem by averaging the initial and final velocity:

```
velocityOld = velocityX
velocityX += acceleration * delta;
posX += (velocityX + velocityOld)/2 * delta;
```

In this particular example it will completely remove dependancy on delta. In general this solution will reduce the effect of delta.

# Answer
> 3 votes
> Stabilizing the delta is not an option as I need different deltas for said effect, so I need to physics to be entirely independent there.

Stabilising the delta time is your only option. If we could change the time step of a numerical integration and were guaranteed to get the same results, we could exploit this to get really accurate calculations with barely any computational effort. Unfortunately, there are no free lunches today. If you change the accuracy of your simulation, the result could change.

If you're okay with the results changing slightly, you could opt for a different integration method. Verlet integration performs a lot better than Euler in your example: the position after 40 ms will be estimated at 480 with *Δt = 40* ms and at 480 with *Δt = 20* ms, but they too will vary if you introduce a non-constant acceleration.

I am not completely sure what the effect is that you want to pursue by changing the time step, but if you're looking to create a slow-motion effect that only affects playback, you need to decouple the simulation from the framerate. An example: your simulation normally works with a Δt of 10 ms. Every ten milliseconds, you advance the physics by one tick. The game runs at 25 fps; you redraw the screen every fourth tick. If you want to slow down to half the normal speed, you advance the physics by one tick every 20 milliseconds instead, but you keep Δt at 10 ms (because that's the time that has elapsed in-game). To keep a constant framerate, you now have to redraw the screen every two ticks.

Regardless of playback rate, the results will be the same, but this method has other disadvantages. You can't draw a new frame until at least Δt has elapsed in-game and because that value is fixed, there is a limit to how slow you can go without the framerate dropping. You can push this lower limit by selecting a smaller value for Δt, but you'll be wasting resources for accuracy you don't need at normal speed. Eventually, your game might not be able to run at normal speed at all, if one tick is still being calculated when the next one is scheduled to begin.

# Answer
> 2 votes
Welcome to the wonderful world of integral calculus.

```
Speed = distance / time
Acceleration = distance / (time * time)

```

So to get the correct answer you need to calculate the integral of your speed, and then the integral of your location. The math can be quite daunting, and in most cases it will be overkill and just make things more complicated. You *can* use this to calculate the positions, but detecting collisions means calculating the time an object reaches a certain position and for two moving objects the arrival times of their paths. Well, it's even more calculus to calculate, and for very little gain (if any at all since Float might not be accurate enough for it).

This is why you normally use fixed timestep for the physics calculations, even if you have a variable framerate, simply keep track of time elapsed and then run your physics calculation in a fixed timestep:

```
for (timeElapsed += delta; timeElapsed > timeStep; timeElapsed -= timeStep) {
  velocityX += acceleration * timeStep;
  posX += velocityX * timeStep;
}

```

This can be put in your update loop to keep the physics running at a fixed timestep regardless of what timestep your update loop runs at, timeElapsed's value would have to be kept over time of course. Whenever you want to use fixed timesteps there are some things to pay in mind, Shawn Hargraeves has a very interesting blog post about this, it mentions XNA specifics but the concepts apply to any fixed timesteps.

# Answer
> 0 votes
Calculating physics with a delta is generally not a good idea, not only because of the reasons you gave, but also because you get slightly different results every time you run the app even with similar frame rates, which already might be game breaking. Or, if the frame rate drops too low, fast moving objects can completely clip through each other. (Assuming you aren't using continuous collision detection.) So the usual workaround (or, mine at least) is to have two different "tick events" for your world: A fixed tick and a frame tick. The fixed tick is where you do all the physics stuff and everything that needs to always work exactly the same. That function just advances the simulation state by a fixed amount, every time you call it. You just measure how much time passed and call the function the appropriate amount of times. Of course you should remember how much time passed over multiple frames, so that you don't "lose" time. In the frame tick function/event you do things that have to be time perfect, but where it doesn't matter if the results are reproducible, like the camera. (If you'd move the camera in the fixed tick function/event, you'd be getting slight but noticeable jittering, because it's position wouldn't always be perfectly aligned with how much time actually passed.)

One problem of this is that if you are so CPU-bound that you can't run enough fixed-tick iterations, the game is just gonna completely lag itself out, because every frame takes longer and longer and you have to run more and more iterations each frame. But you can't really get around that, you just have to perform a certain number of simulation steps to get accurate results.

---
Tags: physics, frame-rate
---


# Question
Title: IsolatedStorageException : Could not find file
I'm trying to save/load player data from a file using the persistenceDataPath using the following code:

```
private void Save()
    {
        if (File.Exists (Application.persistentDataPath + "/playerInfo.dat"))
        {
            FileStream file = File.Open (Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
            data.userExperience = userExperience;
            bf.Serialize (file, data);
            file.Close ();
        }
    }

private void Load()
{
    if (File.Exists (Application.persistentDataPath + "/playerInfo.dat"))
    {
        FileStream file = File.Open (Application.persistentDataPath + "/playerInfo.dat ", FileMode.Open);
        PlayerData data = (PlayerData)bf.Deserialize (file);
        userExperience = data.userExperience;
        file.Close ();
    }
}

[Serializable]
class PlayerData
{
    public int userExperience;
}

```

It works fine if I play the game with Unity Editor. However, on Android, when I try to execute this line of code in Load():

```
FileStream file = File.Open (Application.persistentDataPath + "/playerInfo.dat ", FileMode.Open);

```

I get this error:

The file does exist since the code pass through the if(File.Exist...) and it works when I try to access the file from the Save() method.

I really don't know what it could be since the code that open the file in Save() and Load() is the same.

# Answer
I found what was the source of the error.

In the Load() method I was passing the path with a space at the end and that was why on Android it wasn't able to reach the file.

Apparently, when playing from the Unity editor it was still able to access the path even with the space at the end.
> 0 votes

---
Tags: unity, android
---


# Question
Title: Variance shadow maps don't want to render properly
I've implemented VSM (and also ESM) in my engine but results are for me not as I expected and saw in many examples published on network.

I set filtering of shadow maps to GL\_LINEAR but when I compare result to normal shadow map it is visibly worse.

I tried calculate moments directly in point light shader or get it from texture as it is in most tutorials but results are the same.

Code:

```
uniform samplerCubeShadow shadowMap;

...

vec4 worldSpace=inverse(ViewMatrix)*vec4(pos,1);

vec4 coord=LightViewMatrix*worldSpace;
vec4 abs_coord=abs(coord);

float fs_z=-max(abs_coord.x, max(abs_coord.y, abs_coord.z));

vec4 clip=LightProjectionMatrix*vec4(0.0,0.0,fs_z,1.0);
float d2=(clip.z / clip.w)*0.5+0.5; // clamp to [0..1]

...

float shadowTexel=texture(shadowMap,vec4(coord.xyz,d2));

// VSM (Variance Shadow Map)
// get partial derivatives
float dx = dFdx(d2);
float dy = dFdy(d2);
vec2 moments = vec2(d2, d2*d2+0.25*(dx*dx+dy*dy));
return chebychevInequality(moments, shadowTexel);

```

Using this code I get results as on image above. I tried also not to use samplerCubeShadow but samplerCube but results are even worse. First, I got hard shadows. Second, shadows don fill area as they should when getting moments from other texture. Look at second screen. Here is also look at generated cube map. It isn't similar to what is in depth map even if I put depth/moment1 in all 3 channels.

Shader for getting moments:

```
// Vartex shader
gl_Position=ModelViewProjectionMatrix*Vertex;
v_position=gl_Position;

// Fragment shader
float depth = v_position.z / v_position.w ;
depth = depth * 0.5 + 0.5;          //Don't forget to move away from unit cube ([-1,1]) to [0,1] coordinate system

float moment1 = depth;
float moment2 = depth * depth;

// Adjusting moments (this is sort of bias per pixel) using derivative
float dx = dFdx(depth);
float dy = dFdy(depth);
moment2 += 0.25*(dx*dx+dy*dy) ;

FragColor = vec4( moment1,moment2, 0.0, 0.0 );

```

I'm really stuck. I hope you will help mi to solve my problems.

**EDIT:**

I've found the solution to second problem. I had enabled blending and it gaves me wrong depth map.

I also get better result to first problem but now I'm fighting with proper depth to compare it with depth from shadow map.

In simple SM I use this code:

```
vec4 worldSpace=inverse(ViewMatrix)*vec4(pos,1);

vec4 coord=LightViewMatrix*worldSpace;
vec4 abs_coord=abs(coord);

float fs_z=-max(abs_coord.x, max(abs_coord.y, abs_coord.z));

vec4 clip=LightProjectionMatrix*vec4(0.0,0.0,fs_z,1.0);
float d=(clip.z / clip.w)*0.5+0.5; // clamp to [0..1]

```

where pos is position in View Space. Then I read values from shadow map using:

```
texture(shadowMap,vec4(coord.xyz,d))

```

In VSM I store depth in R channel in RG32F texture. Depth value is calculated in this way:

```
// VS
gl_Position=ModelViewProjectionMatrix*Vertex;
v_position=gl_Position;

// FS
float depth = v_position.z/v_position.w;
depth = depth * 0.5 + 0.5;

```

Then in shader for point light I use coord vector (as in standard SM) to read values from shadow map and this works ok. But problem is in this part:

```
// No shadow if depth of fragment is in front
if ( moments.x <= distance)
    return 1.0;

```

In what coordinates distance should be get? In what coordinates I have depth from shadow map? It should be linear? Could someone explain me that? I'm little confused right now, I tried many ways to get this and all results aren't as I expect.

**EDIT2:** Following JarkkoL tip and this tutorial I changed my code. Now I'm storing depth using this code:

```
// VS
v_position=ModelViewMatrix*Vertex;
gl_Position=ProjectionMatrix*v_position;

// FS
const float Near = 0.1;
const float Far = 90.0; // camera far plane
const float LinearDepthConstant = 1.0 / (Far - Near);

float depth = length(v_position)*LinearDepthConstant;

```

And I compare it with value which I obtain in this way:

```
float dist=length( vec3(inverse(ViewMatrix)*vec4(pos,1.0)) - PointLight.position )*LinearDepthConstant; // pos is read from depth buffer and is in view space so I want invert it to world space as it was in tutorial

```

And here is the result:

In the red circle I marked visible borders between cube map faces. There is still something wrong. I think that it could be someting with inversing of View Matrix but I'm not sure.

# Answer
Regarding cubemap seams, you can just filter across edges.

See: `glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);`

As far as your actual shadow quality, the entire benefit of VSM and ESM techniques comes from the special form that the visibility test takes. You probably want to introduce a constant factor for over- or under-darkening the shadows, so that the edge isn't so hard.

For ESM data it's straightforward:

```
light = exp(factor * (occluder - receiver));

```
> 1 votes

---
Tags: opengl, shadows, shadow-mapping, deferred-rendering, blur
---


title: Generate next chunk with perlin noise

text:
# Question
Title: Generate next chunk with perlin noise
I'm actually trying to generate a level with procedural generation using perlin noise. So one chunk has a size of 30x30, it's a float 2d array and at first I'm filling it with values between 0 and 1. Next step is to calculate 7 octaves and merge them. In the end I normalize the values. All this works quiet well if I only want to create one chunk but how can I create one more chunk beside my first so that they fit together smoothly?

# Answer
Just set it up so your chunk has an *origin*, and add that to the values you're using to sample the perlin noise. i.e

```
void GenerateChunk(Chunk chunk, Perlin noise)
{
   for(int x = 0; x < chunk.width; x++)
   {
        for(int y = 0; y < chunk.height; y++)
        {
             chunk.value[x][y] = noise.Generate(x + chunk.origin.x, y + chunk.origin.y);
        }
   }
}

```

Now you've got a chunk at `(0,0)`, one at `(30, 0)`, one at `(0, 30)` and so on.
> 2 votes

# Answer
Expanding on the previous answer what you need is a concept of global coordinates. Every cell in the world has a globally unique coordinate which is used to generate that cell's random value. The cells themselves are stored in chunks in chunk local coordinates though, so you need a way to address each cell by chunk and offset. The spatially coherent properties of Perlin/Simplex noise then takes care of the rest.

I have some basic code examples for chunk addressing and "water-line" random generation in this blog post. Hopefully I will have posts on a more fleshed-out map generation system soon.
> 0 votes

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


title: Skybox rendering

text:
# Question
Title: Skybox rendering
I am sorry if this is trivial, but I got into OpenGL just very very recently.

I am trying to render skybox (with cubemaps) and this is what I have done:

* Created a VBO with vertices positions (36 of them  `+- 10.0f, +- 10.0f, +-10.0f` ). Using gDebugger I know the data are loaded correctly.

```
glGenBuffers(1, &cubeMap.positionBuffer);
glBindBuffer(GL_ARRAY_BUFFER, cubeMap.positionBuffer);
glBufferData(GL_ARRAY_BUFFER, 3*36*sizeof(float), &cubePoints[0], GL_STATIC_DRAW);

```
* I create a texture, bound to `GL_TEXTURE_CUBE_MAP`, and load (using stbi) each face image to the right side. Again gDebugger tells me that the texture is loaded correctly as it shows with all the faces in the right place.

```
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);
glTexParameteri (GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri (GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri (GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTexParameteri (GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri (GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

--- for each image (looping through faces with index i) ---
data = stbi_load_from_file(file,&width,&height,&comp,0);
// determine format based on comp
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X+i, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, &data[0]);

```
* In my draw loop I draw the cube map as:

```
glEnableVertexAttribArray(0);

cubeMapProgram.use();
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, textureID );
setUniform1i("cubeTexture",0); // my wrapper on the glUniform (it is tested)

glBindBuffer(GL_ARRAY_BUFFER, cubeMap.positionBuffer); // the VBO previously filled
vertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);

glm::mat4 pvMatrix = perspectiveMatrix * viewMatrix; // They are fine
setUniformMatrix4fv("pvMatrix", 1, &(pvMatrix[0][0]));

glDepthMask(GL_FALSE);
glDrawArrays(GL_TRIANGLES, 0, 36);
glDepthMask(GL_TRUE);

```

Where the shader program *cubeMapProgram* is very simple:

**vertex shader**

```
#version 330

layout(location=0) in vec3 aVP;
uniform mat4 pvMatrix;
out vec3 vUV;

void main(void){
    gl_Position = pvMatrix * vec4(aVP,1.0);
    vUV = aVP;
}

```

**fragment shader**

```
#version 330

in vec3 vUV;
out vec4 color;
uniform samplerCube cubeTexture;

void main(void){
    color = texture(cubeTexture, vUV);
}

```

All I got with this is a black screen. Again according to gDebugger the right VBO is correctly filled and bound when drawing and the cubeMap is loaded correctly. Am I missing something completely stupid?

Thank you

# Answer
> 1 votes
I didn't see any call to `SwapBuffers` after your draw commands. That's definitely a problem that will cause a blank screen.

As long as there are no OpenGL errors, it's the only problem.

# Answer
> -1 votes
I use XNA, so even looking at GL code makes my head hurt. On top of that, your variable names do not indicate anything obvious. How does "aVP" represent a worldCoordinate? Anyway...

I can't tell if you've done this in the posted code, or elsewhere:
Since you are inside the skybox, all of its triangles are counter-clockwise from the camera's perspective so you probably need to reverse culling when rendering it; leave everything else the same and/or put it back like you had it.

---
Tags: opengl, glsl, cubemap, skybox
---


# Question
Title: In a semi-infinite procedural (chunk based) map, how do you handle objects larger than a single chunk?
I'll use an example to try and be more specific. Assume this is for a 2D top-down game. Chunks in this are made up of 32x32 tiles.

If procedural buildings were to be generated based on some kind of noise algorithm and **a building was typically 3x3 chunks in size**, how do you ensure the seed for this map will always produce the same buildings?

**Given two adjacent chunks: chunk A and chunk B, what if they both meet the noise algorithm's requirement for being a spawn point for a building?**

**If they are both far from the player's current view range, it could depend on how the player approaches these chunks as far as which one gets generated first.**

My first thought was to only check for buildings every so many chunks, however, I'd also like to have some objects that may span tens of chunks. I don't think this is a proper solution.

Should I simply be using a different type of algorithm to identify where buildings should be able to be spawned at, an ever expanding Voronoi diagram as an example, or is there something else I'm just not considering with how I'm already trying to attempt this? Perhaps I should be handling cross chunk objects on a grander scale (like a collection of 32x32 chunks)?

Thanks!

# Answer
First, your generator(s) should definitely be working at the global, world scale and then applied at the chunk scale. You saw that already and it was a great observation. Here are some notes on working with procedurally generated content that will hopefully make sense. I think that you're confusing "Random World" with "Procedural World," and they're related but not the same. What you want is a Procedural World that can be always be the same if you want, or different each time you run.

**Noise is not random**. Noise output is always the same from the same input parameters. The great thing about noise is that it is 100% repeatable.

You control the input parameters, this is how you come up with different noise fields and the only place randomness occurs!

It's very common for one, single seed to change the base set of numbers and then everything else is based on those. In an example case, the input parameters to the noise would be based on chunk location in global space modified by that global base set. It doesn't matter which chunk gets created first since the chunk is always in the same place and parameters are always the same for the same seed.

**Noise does not have to stand alone**. You can have one noise controlling your chunks, another noise controlling your building placement, and so on. This allows you to tweak buildings without messing with your terrain. Each of these noise fields can be at different scales, etc...

**You can use more than one random number generator**. You can seed multiple generators and use each one independently. Random numbers come in a variety of styles depending on what you want from them, it's a deep subject with lots of statistics involved, but something to consider in the future.

In general the idea is that everything your algorithms based on noise create should be 100% repeatable and independent of anything else. *Your choice of seed guarantees not that each run will be different, but that each run will be the same until a different seed is chosen*.

It is this repeatable behavior combined with working globally and applying locally that will solve your buildings problem.
> 4 votes

# Answer
Keep in mind that chunks are only a strategy for storing data. All your world generation, including building placement, should be done at the world level.

That type of generation can be relative to the player or some other strategy that works for your game. For very large buildings you might want to go a little higher level. If your generation range is smaller than the half extents of your largest buildings, you either need to extend the range of your generation range or you need to test conditions for more than just the center of the building. Have conditions that can allow the building to be placed by the edge or corner.
> 4 votes

# Answer
When dealing with your buildings that are bigger than a single chunk simply mark the chunk as not building-checked. When you try to address a chunk that's not checked and far enough from the outer limit to ensure that all relevant chunks have been generated then you do your building check.
> 0 votes

# Answer
I am thinking about this same problem. Like mentioned in another answer I am thinking about having different noise sources at different scales control different parts of generation. Even with that guidance there is still the question of how to implement generation?

Let's imagine you have a "Structures Coordinate System" (SCS) defined with a granularity suitable for the structures you generate. In the same way as chunk addressing collapses all contained cells into a single coordinate the SCS would collapse larger areas into a single coordinate. From there, given any world coordinate, you could sample a noise source with the SCS coordinate to determine if there is a structure "near by".

You could also use the SCS coordinate to sample another noise source to determine what kind of structure to build. As an optimization you could also use the SCS coordinate as the key into a structures map `Dictionary<Vector, IBuilding>`. A quick structures check could be done using the chunk index (chunk -\> global -\> SCS) to determine if this chunk needs to check for structures. If so the structure instance could be pulled from the cached factory, and chunk cells would then be checked against the structure and contained cell generation delegated to the structure generator.

I'll probably be implementing something like the sketch above in my current project. Check out my ongoing series of blog posts for more rambling interspersed with code.
> 0 votes

---
Tags: xna, mathematics, algorithm, procedural
---


# Question
Title: GetComponentsInChildren<GUIText>().text - does not contain a definition
My Slider GameObject has a GUIText child. I am writing a C# script that should change the text component in the GUIText, but instead of this I am getting:

***error CS1061: Type `UnityEngine.GUIText[]' does not contain a definition for`text' and no extension method `text' of type`UnityEngine.GUIText\[\]' could be found (are you missing a using directive or an assembly reference?)***

```
 public Slider timeSlider;
 int i = 5;

 timeSlider.GetComponentsInChildren<GUIText>().text = 'Some Text' + i;
 //timeSlider.transform.GetComponentsInChildren<GUIText>().text = 'Some Text' + i; // doesn't work either

```

From the documentation I understand that GUIText should have a 'text' variable - Would anyone know why ().text is invalid?

Thank you!

How the hierachy is:

# Answer
> 1 votes
You are using `GetComponentsInChildren`, which as the error message tells you, returns an array of `Unity.GUIText` objects. That array doesn't have a `text` property. So you will probably want to iterate over the objects returned or use a different method for accessing the component(s).

# Answer
> 0 votes
Script needs to run on the parent. Then use this:

```
  transform.FindChild("child name").GetComponent<GUIText>().text = "some Text";

```

Now why would you use GUIText and not just Text that is part of the new UI system is beyond me.

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


# Question
Title: How to program friction in an air hockey game in Cocos2d-x 3.11?
I'm developing a simple air hockey game, and I have a question about friction of puck and puddles with the game scene. How can I do that? I'm using cocos2d-x default physics engine, and the friction setting of physic bodies only applies when they collide.

I've found an old air hockey example project, but it seems that it's ported to cocos2d-x 3.x so it doesn't use built in physics engine.

# Answer
So I realized how to do it. You need to override a method called *Scene::update()* with something like

```
ball->getPhysicsBody()->setVelocity(ball->getPhysicsBody()->getVelocity()*0.995f);

```

And later paste this into your *Scene::init()*, so the *update()* method will be called every frame(?).

```
this->scheduleUpdate();

```
> 0 votes

# Answer
the methods you're looking for are:

```
setAngularDamping(float damping);
setLinearDamping(float damping);

```

according to cocos2d-x documentation both methods are used to simulate fluid or air friction forces on the body.
> 1 votes

---
Tags: physics, cocos2d-x
---


title: Cocos2d: Tweening primitive data-types

text:
# Question
Title: Cocos2d: Tweening primitive data-types
I asked in SO, but no responses so I'm posting here since it's probably more relevant here.

EDIT: SO question closed.

I'm trying to tween primitive data-types the way Action tweens position to create movement. The main reason is to take advantage of the easing functions, rather than hand-code all the easing. This is helpful when implementing things like tweening money counter values (When the teller's display goes ka-ching, you can see the number tween towards the final value.)

Is there a way to directly apply Action or some variant of this onto datatypes like int or float?

Or do I have to cheat by keeping a Node, apply the Action onto the node's property, and read the property? (I'd rather not do this)

# Answer
> 1 votes
The base idea is to chain Ease Actions with your normal tween action. Ease action basically changes the flow of time for it's inner action; So by implementing a simple/linear action, and chaining it with an ease action, you'll end up with the ease function you originally intended.

As for the tweening. Let's say you want an object to change, there are two ways you can manipulate custom variables through time:

1. Through ActionTweenDelegate: You have to create a subclass of `Node`, which also implements `ActionTweenDelegate`. You'll then have to implement `updateTweenAction (float value, const char *key)`. In that function you simple do what ever you want to do (e.g. increase the player's money). Note that value is a number between 0 and 1.
2. Through creating a new action: You'll have to create a subclass of `FiniteTimeAction`, and override `update` function. Despite the name, the input is not really the action time but a progress indicator between 0 and 1. Again you don't have to worry about easing at all, and just have to implement a linear modification function; The rest is up to `ActionEase` class chained to your action.

# Answer
> 0 votes
here is how i'm doing it in my score scene:

```
auto score = Label::createWithTTF("Score : 0", MY_FONT_NAME, 18);
score->enableOutline(Color4B::ORANGE, 1);
this->addChild(score);

// increment score
score->schedule([this, score](float dt) {
    int initialValue = 0;
    int finalValue = currentLvScore;
    static float duration = 4.f;
    static float timeElapsed = 0.f;

    timeElapsed += dt;
    float prograss = timeElapsed / duration;

    int val = MathUtil::lerp(initialValue, finalValue, prograss);
    score->setString("Score : " + std::to_string(val));

    if (timeElapsed >= duration)
    {
        timeElapsed = 0.f;
        score->unschedule("CountTo");
        score->setString("Score : " + std::to_string(currentLvScore));
    }

}, 0.f, CC_REPEAT_FOREVER, 2.0f, "CountTo");

```

**Edit:** a much cleaner way to do it would be using **ActionFloat**.

```
    void ::onEnter() {
        Layer::onEnter();

        auto lbl = Label::createWithTTF("0", "fonts/Marker Felt.ttf", 12.f);
        this->addChild(lbl);
        lbl->setPosition(center);

        // animate float from 0 to 100 in 5 sec
        auto actionfloat = ActionFloat::create(5, 0, 100, [=](float value) {
            lbl->setString(std::to_string(value));
        });

        this->runAction(actionfloat);
    }

```

---
Tags: c++, cocos2d-x
---


# Question
Title: How do you render planets without distortion?
I've recently been working on a little spaceship flying sim in Unity and want to add planets. Up till now, I've been hand modeling them in Blender. But I want to have a way to generate large planets with heightmaps. While researching the topic, I found this video about a voxel planet game and its tech, Here. In the video, they describe a way to render a planet with low distortion. They also relate it to how No Man's Sky does it.

My question is, Are there other methods of rendering planets that have zero distortion? I would prefer if the answers wouldn't be Unity3D specific since i'm considering switching to Monogame or DirectX.

Thanks in advance!

Edit. I've been asked to describe the distortion. The distortion is what happens when a cube gets mapped to a sphere. The video suggests a method of using shader warping when on the ground but using the method of squishing a cube to a sphere when in space. This method causes a noticeable warp when going from space to ground because it switches rendering methods. My question is if there is a way to prevent that warp and provide a truly seamless transition from space to ground.

One more edit, I have found another video on a seamless planet engine called Outerra here It seems to have no warping when leaving the atmosphere. It can be seen at 0:50 and at2:22 in this video.

# Answer
The distortion in the video happens because they are mapping cubes on a sphere, which is geometrically impossible without distorting cubes. If you use any modern terrain engine or even a modeling program to model planets, you shouldn't face any kind of distortion.

**Edit for clarification:**
In the second statement, I am not talking about a voxel planet. It is still impossible to render a voxel planet without distortion; but it is possible for a non-voxel planet (a normal planet, basically).

For a non-voxel planet, all you have to do is paint your terrain directly on a sphere. So basically, in game you get what you see in modeling.
> 2 votes

---
Tags: unity, 3d, mathematics
---


# Question
Title: Handling data logic on libgdx ai state machine or in ashley system?
In this below example, I've combined libgdx ashley and AI state machine. Do you think it's a good idea to handle the logic in state machine or stick on handling the data logic on System?

```
public enum TrollState implements State<Entity> {
     MOVE_AWAY() {
         @Override
         public void enter(Entity entity) {

         }

         @Override
         public void update(Entity entity) {
              PositionComponent position = Mappers.position.get(entity);
              ...
         }

         @Override
         public void exit(Entity entity) {

        }

        @Override
        public boolean onMessage(Entity entity, Telegram telegram) {
             if (telegram.message == 0) {
                 Gdx.app.log("Slime", "Waaaah, goo away, big daddy! yummmmmmy");
                 return true;
            }
            return false;
        }
     }
}

```

# Answer
Unless there's a specific reason you'd need (want) to process the data in a `State` you should probably stick to Ashley's own `EntitySystem`. Without you yourself expanding the functionality of `State`, `EntitySystem`s are for sure more flexible, as in you can tell it to not process the system, you can do something when it's added / removed etc.

Also the development team for Ashley probably optimized their framework as much as possible, meaning that even though it might be a small increase the `EntitySystem`s are probably faster.

If you wish to use Ashley together with GdxAI's States perhaps you could implement it by creating a `Component` and `EntitySystem` that handles the states for you:

```
// Component example
public class StateComponent<T> implements Component {
    private State<T> state;

    public StateComponent(State<T> state) {
        this.state = state;
    }
    //  Other methods omitted for clarity.
}

```

```
// System example
public class StateSystem<T> extends IteratingSystem {

    private YourCustomStateMachine machine = new YourCustomStateMachine();

    public StateSystem() {
        super(Family.all(StateComponent<T>).getFamily());
    }

    @Override
    public void update(float deltaTime) {
        super.update(deltaTime);
        // Make sure to update machine in the update() method so it only
        // runs once per frame and not once per entity.
        machine.update();
    }

    @Override
    protected void processEntity(Entity entity, float deltaTime) {
        //Process the entity and update states as usual.
    }
}

```

For a more generalized question on `Finite State Machines` and `Component Based Programming` see this question.
> 1 votes

---
Tags: libgdx, entity-system, fsm, entity
---


# Question
Title: How to handle Tilled Map z index order with player in libgdx?
The below 1st image is the example how I render tiled map with player, I can properly change the player z index, If I want to make the player below the box i just set the z index to 0. But the problem is the 2nd image below, I dont know how do I make the player above the box when the player is in the bottom then when in the top the player index should be less than the box.

# Answer
> 1 votes
Sort by z position. You will probably want to add an origin to every object as well to determine their position in the game world (ie the players feed, the center of where the box touches the ground, etc.).

There are some restrictions for what objects this will work for though. When the players z position becomes larger or smaller than that of an object he switches from in front of the object to behind it, or vice versa, so you want to make sure that the player can not be in a position where the switch becomes obvious. that means that if you draw a line horizontally left and right from the origin, to the far left and the far right of the objects collision geometry it should ideally stay completely within that geometry.

# Answer
> 1 votes
I see two solutions to this:

* Make your player a part of the `TiledMap` by adding him to his own layer. This will automatically render him in the correct order like all of your other tiles.
* Add an integer property to your tiles in whatever program you're using to create your maps named "zIndex" and then sort your tiles by this property and render them in the order of lowest to highest z-index.

For solution 1, in your editor, set up the layers to be something like this:

Then the code should be something like this:

```
// Adding player to a TiledMapObjectLayer
// Create new MapObject to store player object in.
MapObject object = new MapObject();
// Put the player object in the properties of the map object.
object.getProperties().put("player", yourPlayerObject);
// Then add the object to whatever layer you wish.
yourTileMap.getLayers().get("playerLayer").getObjects().add(object);

```

For a more in-depth solution (with several alternatives) you can take a look at this resource.

---
Tags: libgdx, tilemap, tiled, draw-order
---


# Question
Title: How to avoid position increment by velocity multiplied by delta time even the body is not moving?
In the below image, the character texture is properly sync to body even moving on free space.

In the below image, the character is moving downward. But the texture got a span or not sync properly, when there is an obstacle or a wall.

The systems I've use for the data logic (ECS)

```
class MovementSystem extends IteratingSystem {

      @Override
      public void processEntity(Entity entity, float deltaTime) {
            PositionComponent position = ...
            VelocityComponent velocity = ...

            position.x = velocity.x * deltaTime;
            position.y = velocity.y * deltaTime;
      }

}

class PhysicsSystem extends IteratingSystems {

      @Override
      public void processEntity(Entity entity, float deltaTime) {
           PositionComponent position ...
           BodyComponent body...

           position.set(body.getPosition());
      }

}

class RenderingSystem extends IteratingSystem {

      @Override
      public void processEntity(Entity entity, float deltaTime) {
           PositionComponent position ...
           SpriteComponent sprite ...

           batch.draw(sprite.texture, position...);
      }

}

```

I know the problem is in the part of `MovementSystem` positioning, the position is still incremented by velocity multiplied by delta time even the body is not moving while pressing move button.

# Answer
Some years ago, Blizzard had an April fool's joke about World of Warcraft: the Ogre character (two-headed), could be played by two players. This was hilarious, because it's a non-sense.

You're doing the same thing here: you have two different systems that control the same component.

An entity's position should be controlled either by the `PhysicsSystem` **or** by the `MovementSystem`, not by both.

In either case, you'll need to create a controller component. In the case of the Physics system, the controller will apply forces desired by the user. In the case of the Movement system, the movement will be decided by other means, i.e. you'll have to manage the velocity and other parameters by yourself (like what you're doing now).

If the *velocity* is needed by some other systems (for instance the 'rendering' system could use it to render a trail of some kind), you'll have to make sure that this is also updated by the Physics system.
> 1 votes

---
Tags: libgdx, box2d, entity-system
---


# Question
Title: Confused About My Code Suggesting The Normal Matrix Is Equivalent To The ModelView Matrix
I'm learning environment mapping in OpenGL by following this page.

In his vertex shader, the author calculates the vertex normal in eye space with the following code:

```
nEye = vec3(viewMatrix * modelMatrix * vec4(vertexNormal, 0.0));

```

This works, but I've fooled around and made modifications to the shader code, so that it calculates the vertex normal with this code:

```
nEye = vec3(normalMatrix * vec4(vertexNormal, 0.0));

```

Where *normalMatrix* is a uniform 4x4 matrix I calculated outside the shader:

```
objectNormalMatrix = viewMatrix * modelMatrix;
objectNormalMatrix.invert();
objectNormalMatrix.transpose();

```

(I read from this question that the above is how you are supposed to calculate the normal matrix).

For either method of calculating the vertex normal I use, **I get the same (working) graphical result**, and this is what is confusing me.

My question is, why is`(viewMatrix * modelMatrix)` apparently equivalent `normalMatrix`? In calculating the normal matrix, I invert and transpose, but I do none of that when just multiplying by `(viewMatrix * modelMatrix)`.

Here is some extra info that might be relevant:

* The matrix library I use in my application is column major order (same as OpenGL).
* When I pass my matrices to GLSL with `glUniformMatrix`, I have `transpose` as `false`.
* The view matrix and model matrix in GLSL are uniforms from the application, and they are the exact same view matrix and model matrix matrices I use in my calculation of the normal matrix.

# Answer
> 8 votes
When a matrix is orthogonal, inverse and transpose are equivalent making an inverse transpose equal to the original matrix. So if your model view matrix is orthogonal, the normal matrix will be equal to it.

As user41442 pointed out, in most cases modelview matrices are actually orthogonal so this can be a bit of a short hand. There's still cases where it's not true so it's good to know when you can get away with it.

Rotation matrices are always orthogonal. Translations do not affect normals (assuming the w is zero on your normal). Uniform scales are not orthogonal, but they are direction preserving so re-normalizing after a uniform scale will give you the same normal. Therefore if you only use uniform scales, rotations and translations (and re-normalize your normals) you can treat the two as equivalent.

If you ever use non-uniform scales or shears on the other hand you need to calculate a proper normal matrix explicitly. This is also true if you don't have complete control over what transforms are used.

---
Tags: opengl, glsl, matrix, normals
---


title: 2D World Mouse Coordinates - Matrices

text:
# Question
Title: 2D World Mouse Coordinates - Matrices
I'm trying to get the world coordinates out of a mouse click. Currently I'm doing the following:

```
var invertedMatrix = mat4.create();
var viewMatrix = activeCamera.getMatrix();
mat4.invert(invertedMatrix, viewMatrix);

var worldCoord = Vector2.transformMat4(new Vector2(mouseX, mouseY), invertedMatrix);

```

But the values I'm getting are away off. The Y for instance, is between 0 (top of the screen) and 200.000+ on the bottom of the screen. Also, even if I move the camera, let's say 50 in the x axis, if I click in the same spot before and after, the value calculated is the same.

I'm using gl-matrix to generate and calculate the matrices. The used active camera transform was created by using the following instructions:

```
 mat4.ortho(this._matrix, -this.viewWidth / 2.0, this.viewWidth / 2.0, this.viewHeight / 2.0, -this.viewHeight / 2.0, 0.0, 1.0);
 mat4.translate(this._matrix, this._matrix, [-this.x, -this.y, 0]);

```

I've checked both the vector2 transform and matrix invert for any issues but there seems to be none which makes me believe it can be the ortho projection itself but I'm currently lacking the knowledge to understand the problem.

The transform calculation:

```
    return new Vector2(
       (mat[0] * vec2.x) + (mat[4] * vec2.y) + mat[12],
       (mat[1] * vec2.x) + (mat[5] * vec2.y) + mat[13]);

```

Any ideas? thanks!

# Answer
> 1 votes
Ok mystery solved.

The issue was because I wasn't normalizing the mouse x and y before applying the calculations. After doing the following everything started to work correctly:

```
var x = (2.0 * mouseX) / screenWidth - 1.0;
var y = 1.0 - (2.0 * mouseY) / screenHeight;

```

---
Tags: mathematics, matrix, webgl, projection-matrix
---


title: OpenGL ES 2.0 Point Sprites Size

text:
# Question
Title: OpenGL ES 2.0 Point Sprites Size
I am trying to draw point sprites in OpenGL ES 2.0, but all my points end up with a size of 1 pixel...even when I set gl\_PointSize to a high value in my vertex shader.

How can I make my point sprites bigger?

# Answer
> 23 votes
OpenGL ES 2.0 supports Point Sprites; i use them for particles. Just use `glDrawElements` with `GL_POINTS`.

In vertex shader, you set the size with `gl_PointSize` and use `gl_PointCoord` in fragment shader for texture mapping.

My vertex shader:

```
uniform mat4 uMvp;
uniform float uThickness;

attribute vec3 aPosition;
attribute vec2 aTexCoord;
attribute vec4 aColor;

varying vec4 vColor;

void main() {
    vec4 position = uMvp * vec4(aPosition.xyz, 1.);
    vColor = aColor;
    gl_PointSize = uThickness;
    gl_Position =  position;
}

```

My fragment shader:

```
uniform sampler2D tex0;
varying vec4 vColor;

void main()
{
   gl_FragColor = texture2D(tex0, gl_PointCoord) * vColor;
}

```

If you are on Android, you can look my french Tutorial. There is a full project with point sprites.

# Answer
> 1 votes
Surprisingly, glLineWidth() makes points larger too:

```
    GLES20.glLineWidth(8); // Make the edges (and points!) thicker
    GLES20.glDrawArrays(GLES20.GL_POINTS, 0, 38);// 38 is number of my vertexes

```

# Answer
> 0 votes
OpenGLES 2.0 does not directly support point sprites. You can either texture your glPoints or manually create a camera-facing and camera-aligned quad centered on a point.

---
Tags: opengl, 3d, android, opengl-es
---


title: Values or Struct-Like Location Class?

text:
# Question
Title: Values or Struct-Like Location Class?
I'm currently working on a 2D RPG, where the player character moves on a tilemap but is not constrained to the individual tiles. Every tile in a room is referred to by x and y coordinates to an Array. I'm considering using a `Location` class to store a `float x` and `float y` for the player character, as well as, perhaps, a `Room`. What are the advantages and disadvantages of this approach versus keeping the `float x` and `float y` values of the `Player` class (thus not creating a `Location` class)?

Collision detection with walls, objects, and other players will need to be calculated.

# Answer
> 1 votes
This depends on the language. Since you didn't mention language, I am for the moment going to assume either C++ or C# or D or Rust or some similar low-level language (*not* Java!), because game development.

There are zero advantages to keeping `x` and `y` as members of `Player` rather than abstracting out to a `Point`/`Location` type.

There are many many advantages to abstracting tightly-coupled primitive values to a separate type. Abstracting in this way is a fundamental part of writing good, generic, maintainable code. Such abstraction better fits the SOLID principles with a practical result of reducing cut-n-paste code and hence reducing bugs and maintenance costs and allows the creation of reusable algorithms that operate on common data types (e.g., utilities for calculating the distance between points, or rotating points around an origin, or so on).

Quite simply, every single game engine/framework has some kind of `Point`/`Location` type. Not having one is just silly. Going along with this there should be similar classes for things like `AxisAlignedBox` or other geometric primitives that you game frequently uses. Duplicating the data members and algorithms every time you need such a primitive is bad bad coding.

If you are in C#, prefer a `struct` over a `class`, as structs are value types and classes are reference/boxed types. As to why that matters, read on.

When using a language like Python or Java or JavaScript or so on then there *is* a set of disadvantages with having a separate `Location`/`Point` class, though note that the advantages *massively* outweigh the disadvantages. User-defined types in such languages are *always* reference types. That is a problem.

The most frequently-cited but rather least important is that the reference types are always boxed (allocated in the free-store/heap), accessing them incurs a memory indirection, and creating instances increases GC pressure. Basically, they hurt performance. That's not even close to the worst problem, even in games.

The most serious problem is that you can "leak" references easily from your public interfaces and get very bewildering bugs. Code to illustrate:

```
// C++ / C# / any other "good" programming language
player.position.x = 1;
local_pos = player.position; // COPY position to a local
local_pos.x += 3;
print(player.position.x); // prints: 1

// Python / Java / JavaScript / any other "bad" language
player.position.x = 1;
local_pos = player.position; // ALIAS position to a local
local_pos.x += 3;
print(player.position.x); // prints: 4 !!!! oops!

```

In languages with these enforced reference semantics you are required to write more complicated code to ensure that you are avoiding mutating any references. The simple version involves lots of clones but that can result in pretty horrible performance, even for simple 2D games. Production-grade solutions are complicated. Best to just completely shun languages that lack user-defined value types, in my not-so-humble opinion.

---
Tags: collision-detection, architecture
---


title: How to make one 3D object face another?

text:
# Question
Title: How to make one 3D object face another?
I'm writing a simple 3D engine myself and I cannot figure out how to make one object face another. The problem begins with identifying which direction the target object is in relation to the second. Actually rotating an object is not a problem, but essentially identifying the direction a particular object is facing (let's say, by identifying the global direction a key facet is facing) is a problem.

# Answer
There are a couple ways to do this, but here's one way to do it. We can generate a rotation matrix by storing 3 normalized vectors as columns for a 3x3 matrix. The first column will be normalized vector pointing down our "X" axis, the second will be normalized vector pointing down our "Y" axis, and the final one will a normalized vector pointing down the "Z" axis. One example of this is an identity matrix, which is all 0's, except for the diagonal going from top right to bottom left. The first column is **\[1,0,0\]**, which is a normalized vector pointing down the X axis, the second column points "up", and the third column points forward.

The first step is to get the vector from object 1 to object2, and normalize it. You now have a "forward vector". This will be our first column of the matrix.

Now we need a second column, which is our "up vector". Usually, we won't be rotated directly upwards (and if we are, I'll show you how to deal with it at the end), so we're going to guess at that axis. We'll set it to straight up, which is **\[0,1,0\]**. So now we have a 3x3 matrix with the first 2 columns set, it looks like this:

```
[ f.x 0 ? ]
[ f.y 1 ? ]
[ f.z 0 ? ]

```

We need the final column, our "tangent" vector. We can generate it by taking the cross product of the "forward" vector and the up vector, so now we have our forward vector, **\[f.x, f.y, f.z\]**, an up vector **\[0, 1, 0\]**, and a "tangent" vector, which is **\[t.x, t.y, t.z\]**. Remember how I mentioned earlier that our math won't work if our forward vector is pointed in the same direction as the up vector we guessed at? We're going to check for it. You have to check the length of the tangent vector, and if the length is close to 0, then we need to fix it up. Instead of taking the cross product of **\[f.x,f.y,f.z\]** and **\[0, 1, 0\]**, we can pick a new axis for our 2nd vector, say **\[1, 0, 0\]**. Do the cross product again, and that vector is our tangent vector. Important step: **normalize** it. Once you've normalized it, it becomes our 3rd column.

So now we have a matrix with a forward vector in 1 column, a value we hard-coded in the second column, and a tangent vector in the 3rd column. We need to fix up that "up" vector we hard-coded earlier, so we need to take the cross product of the tangent vector and the forward vector, normalize it, and set the "up" column to that vector.

This final matrix is the rotation matrix to rotate object 1 to point at object 2. If you need to, you can convert this matrix to a quaternion, or euler angles, or some other if you need to store it. Here's some pseudo code on this process, just for clarity:

```
Vector3 forward = object2.pos - object1.pos;
forward.normalize();
Vector3 up = new Vector3(0, 1.0, 0);
Vector3 tangent0 = CrossProduct(forward, up);
if (tangent0.length < 0.001f)
{
  up = new Vector3(1.0, 0, 0);
  tangent0 = CrossProduct(forward, up);
}
tangent0.normalize();
up = CrossProduct(forward, tangent0);

Matrix rotation = new Matrix(
  forward.x, up.x, tangent0.x,
  forward.y, up.y, tangent0.y,
  forward.z, up.z, tangent0.z
);

```
> 5 votes

---
Tags: 3d, rotation
---


# Question
Title: unity Tilt Android Device player Freeze When Die
I attached tilt script to my Player to move player x and y Axis. Player have Rigidbody2D and also IsKinematic=true. but the problem when the player can Die i want to stop tilting and player goes down to ground. here is my tilt Code

```
public float Speed=20f;
 void Update () {
  if (PlayerControll.instance.isAlive) {
   transform.Translate (Input.acceleration.x * Speed * Time.deltaTime, Input.acceleration.y * Speed * Time.deltaTime, 0);
  } else {
   PlayerControll.instance.PlayerRigidbody.isKinematic = false;
  }
```

I try to do that using disable tilt script when Player die and Iskinematic=false but the problem is player can freeze to his position not goes down to the ground. I do that so many way but not done so what i do don't know then i post the Question. thanks in advance.

# Answer
You can disable a component (or even destroy it - it'll be removed from your gameObject) to tell Unity to stop calling its Update method.

To disable a component, from inside your tilt component, you can do this in the Update method:

```
if ( PlayerControll.instance.isAlive == false )
{
    this.enabled = false;
}

```

To destroy your tilt component (remove it from your gameObject) you can do this in the Update method:

```
if ( PlayerControll.instance.isAlive == false )
{
    Destroy(this);
}

```

Also, if I understand correctly, you want your player to go down by gravity. So, if it's not alive remember to check if the gravity is applied on the RigidBody doing something like this :

```
PlayerControll.instance.PlayerRigidbody.useGravity = true;

```
> 0 votes

# Answer
I Solve the Problem using attached Player rigidbody2d to the Inspector. Create object of Rigidbody2D `Public Rigidbody2d PlayerRigidBody;` and Attach Player to the PlayerRigidBody in Inspector then Solve The problem. Thank to all who give me any suggestion.
> 0 votes

---
Tags: unity, android
---


# Question
Title: Elements of uniform array are always zero?
I'm building a shader program to render a simple bitmap font in GLSL.

My programming environment is C# so I'm using OpenTK to encapsulate OpenGL 4.0, but the syntax is very similar to any examples in C and C++.

My issue is that I'm trying to pass an array of integers to the fragment shader, but whenever I do, all the array elements end up being zero. The integers should range between 0 and 255 and I've checked the values before and after sending them. It's infuriating.

Currently I'm binding my program, then attempting to send the int\[\] array to the shader using the following instructions:

```
int[] ints = new int[] { 33, 34, 35, 36, 37, 38, 39, 40 };
GL.UseProgram(programLocation);
GL.Uniform1(arrayLocation, ints.Length, ints);

```

My fragment shader takes the array and uses a couple of functions to determine which part of the quad to place which characters. I've tested these functions with static numbers and arrays I build manually in the shader and they work just as I'd expect them to. For some reason the syntax above simply doesn't actually end up sending any data - all elements evaluate to 0.

In my shader, the array is denoted and used like this:

```
uniform int characters[8];
....
gl_FragColor = texture2D(bitmapFontTex, GetBitmapFontStart(characters[0...8etc]));

```

The rest of my code seems to work when tested in isolation - it only falls apart when it comes together, and the above code blocks are where it comes together. Have I made some silly rookie mistake, or is there something more screwy happening? Any help greatly appreciated.

# Answer
Looks like you are using the wrong function, need to use uniform1i instead.

https://www.opengl.org/sdk/docs/man/html/glUniform.xhtml

> glUniform1i and glUniform1iv are the only two functions that may be used to load uniform variables defined as sampler types. Loading samplers with any other function will result in a GL\_INVALID\_OPERATION error.
>
> If count is greater than 1 and the indicated uniform variable is not an array, a GL\_INVALID\_OPERATION error is generated and the specified uniform variable will remain unchanged.
>
> Other than the preceding exceptions, if the type and size of the uniform variable as defined in the shader do not match the type and size specified in the name of the command used to load its value, a GL\_INVALID\_OPERATION error will be generated and the specified uniform variable will remain unchanged.
>
> If location is a value other than -1 and it does not represent a valid uniform variable location in the current program object, an error will be generated, and no changes will be made to the uniform variable storage of the current program object. If location is equal to -1, the data passed in will be silently ignored and the specified uniform variable will not be changed.
> 1 votes

---
Tags: opengl
---