# Question
Title: What is the proper way to convert meters to pixels when using Box2D?
I'm working on a platformer and I've chosen to use Box2D for physics but I'm having trouble converting meters to pixels. I have a static object and a dynamic object. The dynamic object falls onto the static object but when the dynamic object hits the static object, they don't touch, they're about a meter apart when they're supposed to be touching.

As you can see from the screenshot, the dynamic object (rat) is hovering above the static object (blue rectangle) when they're supposed to be touching. I assumed it was a problem with my meters-to-pixels code so I fiddled with it and inspected variables in the debugger and still can't figure out what I'm doing wrong.

Rendering is done in pixels (via SDL2) and the origin is in the top-left corner of the window. +x is right and +y is down.

Physics is done in meters (via Box2D) and the origin is in the bottom-right corner of the window. +x is right and +y is up.

Heres the code to create the dynamic object.

```
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.fixedRotation = true;

b2Body *body = world.CreateBody(&bodyDef);

b2PolygonShape shape;
shape.SetAsBox(1.0f, 1.0f);

b2FixtureDef fixtureDef;
fixtureDef.shape = &shape;
fixtureDef.density = 10.0f;

body->CreateFixture(&fixtureDef);
body->SetTransform({0.0f, 10.0f}, 0.0f);

```

And here's the code to create the static body

```
b2BodyDef bodyDef;
bodyDef.type = b2_staticBody;

b2Body *body = world.CreateBody(&bodyDef);

b2PolygonShape shape;
shape.SetAsBox(WINDOW_METER_SIZE.x, 2.0f);

b2FixtureDef fixture;
fixture.shape = &shape;
fixture.friction = 0.0f;

body->CreateFixture(&fixture);
body->SetTransform({0.0f, 0.0f}, 0.0f);

```

The `Rect` and `RectPx` classes represent a rectangle as a top-left point `p` and a size `s`.

To get the `Rect` of the `b2Body` used for drawing.

```
b2Body *body;
const Rect rect = {body->GetPosition(), {1.0f, 1.0f}};

```

Heres the code to transform a rectangle in meters to a rectangle in pixels

```
RectPx transform(const Rect rect) {
  return {
    {
      rect.p.x * PIXELS_PER_METER,
      (-rect.p.y + WINDOW_METER_SIZE.y - rect.s.y) * PIXELS_PER_METER
    },
    rect.s * PIXELS_PER_METER
  };
}

```

I later use the `RectPx` to call `SDL_RenderFillRect` and `SDL_RenderCopy` which both expect a rectangle in the described format.

I really hope there's an obvious mistake in my code somewhere that a Box2D guru can spot.

Thank you in advance for reading this very long question.

# Answer
> 1 votes
After implementing debug draw I noticed that Box2D was rendering my objects twice the size that I was. So then I looked at the implementation of `b2PolygonShape::SetAsBox`. Here it is

```
void b2PolygonShape::SetAsBox(float32 hx, float32 hy)
{
  m_count = 4;
  m_vertices[0].Set(-hx, -hy);
  m_vertices[1].Set( hx, -hy);
  m_vertices[2].Set( hx,  hy);
  m_vertices[3].Set(-hx,  hy);
  m_normals[0].Set(0.0f, -1.0f);
  m_normals[1].Set(1.0f, 0.0f);
  m_normals[2].Set(0.0f, 1.0f);
  m_normals[3].Set(-1.0f, 0.0f);
  m_centroid.SetZero();
}

```

It expects half width and half height. After I passed half the size of the box to this function, I made a few tweaks to my camera code and everything worked as expected.

---
Tags: c++, box2d, transformation
---


# Question
Title: Where to store contiguous arrays of components?
I've been working on an entity component system and have the trouble of where to define/put the arrays of each component type. Each component type is user defined so I do not know what or how many arrays to create so I am guessing I need to do something with templates.

This is what I have done so far with example usage. I am rather confused and not sure if what I have done so far is the way to go about this.

```
template<class T>
class Component
{
public:

    Component() = default;
    virtual ~Component() {};

private:

    friend class Entity;

    uint64 m_entity_id;

    static std::vector<T> COMPONENTS;

};

```

Example component:

```
class Velocity : public Component<Velocity>
{
public:

    ~Velocity();

    float get_x() const;

    float get_y() const;

private:

    float x;
    float y;

};

```

The idea is that this would create a static array for each component type. This feels like a weird way to achieve my goal but I can't think of any other way.

Have I missed an obvious solution to this problem?

# Answer
> 2 votes
The solution you described is using the so called "curiously recurring template pattern", often abbreviated as CRTP and is very common in C++ programming.

This is a straightforward solution to the problem at hand and I use it in my entity component system in the same way. It is in not weird and seems to be the standard way to do this.

# Answer
> 1 votes
This question is depending on more factors based on what you want to do. First you said, you want the components to be user defined, so i guess you are working on a game library/engine for multiple game uses.

LukeG's answer with the CRTP is the right way to answer the "how to" part of you question. Problem is, you need a system to register the content the user has defined. You can't just use classes a user has defined.

That's why i suggest some sort of manager, where you register each used component type, that creates the array for the component. This will be useful if you want to reference those components in more than one part of your design, without that part knowing, if this component is registered or not. You can also use that component manager for multithreading or network purposes later on.

In my library i have a data manager for that, where every other manager registers the component it will need. You will need something similar, since your components need to be user defined, your managers will need the same.

---
Tags: c++, entity-system, component-based
---


title: Click to move interaction with UI

text:
# Question
Title: Click to move interaction with UI
In my game I have a simple click to move character. On GetMouseButtonDown(0) (when mouse is clicked) I want the character to move to the location of the click, as long as the click does not occur on a UI element.

That's simple enough, I can use `if(Input.GetMouseButtonDown(0) && !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())`

However, in every GetMouseButton(0) case except when mouse is initially clicked (when mouse button is held down), I want to be able to move even if my mouse is positioned behind a UI element.

So let's say I have an inventory open. I do not want clicking on the inventory to move my character. But if I click somewhere else and begin to move my character, and then move my mouse cursor behind the inventory, I want the character to continue moving. That is why I can't just do `if(Input.GetMouseButton(0) && !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())`.

I also can't do `if(Input.GetMouseButtonDown(0) && !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject()) || !Input.GetMouseButtonDown(0) && Input.GetMouseButton(0))`

Using a counter to measure elapsed time and then doing something like `if(Input.GetMouseButton(0) && timer > 0.2f)` doesn't seem to solve the problem either because I never want to move if the click origin is on a UI object, despite how much time has elapsed.

# Answer
> 2 votes
What if you had a toggle that said whether the current click was started not over a UI element.

```
// class variable
bool clickNotOverUI;

if (Input.GetMouseButtonDown(0) &&
      !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())) {
    clickNotOverUI = true;
else if (Input.GetMouseButtonDown(0)) {
    clickNotOverUI = false;
}

if (Input.GetMouseButton(0) && clickNotOverUI) {
     // do whatever
}

```

There's a decent chance I forgot some piece of logic but the idea is there.

---
Tags: unity
---


# Question
Title: Where is the best place to find modeling artists that are loyal?
For the past 3 years I have been working on my first indie game with a few friends but had to learn how to do everything myself, from coding, to creating models in blender and how to use Unity.

After a while I found a few people to help but they're either young or busy and I would like to find dedicated members for my game who won't leak or share things online.

I'm new to this and I would love some advice on where I can recruit members for my team who are loyal and dedicated to my game and it's cause.

(also if I posted this in the wrong place or said something odd I'm sorry, I don't know where else to ask as I've been stuck trying to find help for a good while now)

My biggest worry is that someone will steal or copy my idea if I post anything about the game online(we've had a few scares like that before) so it's the biggest thing for members to be loyal and not leak anything.

# Answer
My experience with people is that you need to assure that in some form, whether financial, career-wise or whatever, their security lies with you. That is, *bind them* to you, in every way possible. You need a watertight contract holding them to their word, and the ability to enforce it when the time comes. NDAs are only as good as your ability to pay to have them enforced. Otherwise it's a bluff that will be assumed as being such.

**Option #1:** Do everything you can, by yourself, until you get investors and thus *can* pay to have contracts drawn up, enforced etc. Lot of work, but the payoff is peace of mind and zero communications overhead... which itself can take lots of time. You will have to be extremely efficient in your use of time in order not to spend the next 5 years on said project. You could mix in option 3.

**Option #2:** Find people you genuinely trust, people you have known for a long time. But this can also get tricky when they want to exit, as you don't want to look like you're trying to control their lives, ruining your non-work relations. But you may not have the relevant job titles among your social/family circles.

**Option #3:** Keep work modular at every stage, so that you never have to let anyone in on the bigger picture. Problem here is having solid engineering and specifications experience to be able to separate the project that way, and ensure things will work once integration time arrives, otherwise you could be severely out of pocket with little to show for it. With this option you can use either volunteers or paid pro's, since compartmentalising the work keeps you safe from blunders.

**Option #4:** Accept the risks and move forward. You will still need protections in place, however, if only a contract for which the threat of breach is sufficient to deter bad behaviour (Not my ideal choice).
> 1 votes

---
Tags: unity, blender
---


# Question
Title: Is it possible to make an input field with non selectable text in Unity?
Can I make an input field with non selectable text in Unity?

# Answer
You can make InputFields non selectable by setting enabled to false.

```
inputfield.enabled = false;

```

This will disable input though.

Use the API documentation to experiment with the input field: https://docs.unity3d.com/460/Documentation/ScriptReference/UI.InputField.html
> 1 votes

---
Tags: unity, input, text
---


# Question
Title: Noisy edges, smoothing out edges between faces via fragment shader
I have a generated terrain, with hexagonal geometry, as per screenshot below:

I then generate biomes, but as you can see the borders between them are really ugly and straight. To hide that hexagonal origin, I would need to smooth out the borders between biomes. This is how it looks now in wireframe with real tringular faces:

What I'm aiming for is something more like this:

Each vertex has attibute that holds the biome type, I can also add special attributes to the vertices on the edge between two biomes, but I just don't seem to be able to figure out how to pull this off in shader code, obviously noise is involved here, but how do I make it continous across multiple faces and entire border of multiple biomes?

I'm rendering with WebGL using THREE.js

# Answer
Other answers here suggest using a texture. Here's a technique that doesn't use textures.

You want the boundaries between hexagons to be interesting. It's easier to make interesting boundaries when you move them into the center of what you're drawing. Instead of drawing the tiles directly, you draw the “dual” of the tile. This technique is called “corner tiles” (here and here and here). The dual of a hexagon is a triangle, so we would draw these triangles instead of the hexagons:

The boundaries between hexagons are now in the middle of the rendered triangles, so that'll let us do more interesting things with them. Bonus: you only need to draw *two* triangles per hexagon, instead of six (or twenty four as you are doing now).

Inside each of those triangles we want the fragment shader to draw the hexagons. We can do that with *barycentric coordinates*. Put (1,0,0), (0,1,0), and (0,0,1) at each vertex of the triangle. Inside the triangle, those coordinates will be interpolated. The fragment shader will receive (a,b,c) and can look to see which value is largest — that will tell us which of the three hexagons should be drawn at this point.

`float max_n = max(barycentric.r, max(barycentric.g, barycentric.b));
 if (max_n == barycentric.r) { color = v_color0; }
 else if (max_n == barycentric.g) { color = v_color1; }
 else if (max_n == barycentric.b) { color = v_color2; }`

That's for straight lines.

If you want noisy edges, you can add noise to the barycentric coordinates:

By playing with the amplitude wavelength/frequency of noise, you can get some cool effects:

You need to be careful with the noise, making sure it's consistent across triangle boundaries. One way to do that is to pass in a hex id and use that as the seed value for each of the three noise values added to the barycentric coordinates.

I made an interactive demo here. (For the demo I didn't implement the hex id or some of the other things you might need if you were making this work in a real project — it's just a quick & dirty demo)
> 11 votes

# Answer
I'm sure that "could" be solved with some image algorithm but if it was me I'd probably solve it with textures. I'd make hexagonal textures, put them all in a texture atlas, then for each hexagon I'd look at its neighbors and decide which texture to apply.

The textures would need to have versions for each type of terrain plus versions for each type of transition.

This is similar to how many tile based systems do terrain. Here's an example from 2d games.

Another possibility would be to just have your textures for your various types of terrain (water, snow, dirt, grass) and add mix amounts to each vertex of hexagon to decide how to mix them.

This article shows the idea of mixing terrain textures. I'm not suggesting following their implementation but it shows the idea.
> 0 votes

# Answer
First, render your biomes to a texture. Map the triangles to texcoords. You can do this using a mercator projection, or, better, a cube map. Now, in the fragment shader, do something like this:

```
// frequency and magnitude of the noise in texels.
uniform float frequency;
uniform float magnitude;

// This function should just look like random smooth noise in x,y
// This one isn't great, but you can experiment.
vec2 noise(vec3 vertexPos) {
    return vec2(sin(vertexPos.x * frequency + vertexPos.y * frequency) * magnitude,
                cos(vertexPos.y * frequency * 2 + vertexPos.z * frequency) * magnitude);
}

// Sample the texture and preturb it with noise based on the world
// position of the fragment.
vec4 frag(vec2 texCoord, vec3 fragmentPos) {
   return texture(mySampler, texCoord + noise(fragmentPos));
}

```

where `noise` is some pseudo-random function (using, say, sinusoids) on the 3D position of the vertex in model space which returns a noisy offset to the texture coordinate. Sample the texture using `GL_NEAREST` to keep sharp borders.
> 0 votes

---
Tags: opengl, shaders, webgl, terrain-rendering, noise
---


title: Place hexagons together

text:
# Question
Title: Place hexagons together
Just made it with some more investigation thanks to this site: Hexagonal grid math, but the hexagons have a little bit spacing horizontally.

Here is the code:

```
include('class/hexagon.php');

$hexagon = new hexagon(16);

$png_image = imagecreate(500, 500);
imagecolorallocate($png_image, 255, 255, 255);
$black = imagecolorallocate($png_image, 0, 0, 0);

for($i=1;$i<12;$i++) {
    for($j=1;$j<10;$j++) {
        $x = $i * $hexagon->ver;
        $y = $j * $hexagon->height + ( ($i%2) * ( $hexagon->height / 2 ) );
        $points = $hexagon->drawHex($x,$y);
        $last_line = array($points[0][0],$points[0][1]);
        imagettftext ($png_image , 5 , 0 , $x , $y , $black , "C:/Windows/Fonts/Arial.ttf" , "{$i},{$j}" );
        foreach($points as $c):
            imageline($png_image, $last_line[0], $last_line[1], $c[0], $c[1], $black);
            $last_line = $c;
        endforeach;
    }
}
header('Content-type: image/png');
imagepng($png_image);
imagedestroy($png_image);

class hexagon {
    public $size;
    public $width;
    public $height;
    public $hor;
    public $ver;
    public $angle;
    public $rad_angle;
    public $side;
    public function __construct($xsize = 32) {
        $this->angle = 60;
        $this->rad_angle = $this->angle * (pi() / 180);
        $this->side = $this->size * cos($this->rad_angle);
        $this->size = $xsize;
        $this->width = $this->size * 2;
        $this->height = $this->width * sin($this->angle * (pi()/180));
        $this->hor = $this->width * ( 3/4 );
        $this->ver = $this->height;
    }

    public function drawHex($x, $y) {
        $points = array();
        for($i=0;$i<7;$i++) {
            $angle_deg = $this->angle * $i;
            $angle_rad = pi() / 180 * $angle_deg;
            $points[$i] = array($x + $this->size * cos($angle_rad),$y + $this->size * sin($angle_rad));
        }
        return $points;
    }
}

```

Result:

Any advice?

# Answer
> 2 votes
Just fixed by doing the X coordinate with

$x = $hexagon-\>ver + $i * $hexagon-\>size * 1.5;

Looks beautiful now.

---
Tags: php, hexagonal-grid
---


# Question
Title: How to implement a save/load system in Unity?
Many game allows the player to save progress at any time and load the save back at any time (like Minecraft and Doom 3).

I would like to implement it in Unity.

I think I will need to put the value of every variable in every script into a save file, but how? Or maybe not?

# Answer
Unity doesn't offer a savegame system out-of-the-box. You won't get around writing and reading files yourself using the usual file access tools the .NET standard library offers (check stackoverflow.com about how to read and write files in C#. That topic got asked and answered to death by now).

But Unity comes with one class which can make your life a lot easier: `JsonUtility`. This class allows you to convert objects to JSON strings and back. You can only use it on classes which have the `Serializable` attribute.

Note that it will only serialize/deserialize `public` variables and attributes.
> 2 votes

---
Tags: unity, savegame
---


title: 3D Thrust velocity

text:
# Question
Title: 3D Thrust velocity
How do I create 3D velocity with a 3D angle and 1D thrust like the 2D algorithm below?

```
angle.z += angularVelocity.z * timeStep;

velocity.x = thrust * cosf(angle.z);
velocity.y = thrust * sinf(angle.z);

position.x += velocity.x * timeStep;
position.y += velocity.y * timeStep;

```

I want to simplify my 3D OpenGL motion by having the final angle and position correct no matter where the spaceship's thrust is.

My spaceship uses the OpenGL motion functions below:

```
glPushMatrix();
    glTranslatef(position.x, position.y, position.z);
    glRotatef(rad2deg(angle.x), 1.0, 0.0, 0.0);
    glRotatef(rad2deg(angle.y), 0.0, 1.0, 0.0);
    glRotatef(rad2deg(angle.z), 0.0, 0.0, 1.0);
    glBegin(GL_QUADS);
        // CCW Quad
    glVertex3f(-1.0, 1.0, 0.0);
    glVertex3f(-1.0,-1.0, 0.0);
    glVertex3f( 1.0,-1.0, 0.0);
    glVertex3f( 1.0, 1.0, 0.0);

    glEnd();
glPopMatrix();

```

The problem is that the 3D spaceship rotates but the thrust always goes off toward the positive x axis. The angles are Euler in degrees and radians.

# Answer
> 2 votes
# Trigonometry

As stated in this article, 3D rotations (`rX`, `rY`, `rZ`; for their respective axes) transform a point P (`xi`,`yi`,`zi`) into another point P' (`xf`, `yf`, `zf`) in the following way. *Note: the rotations can be ordered in any way, but I'm going to do XYZ.*

### X-Axis rotation

```
yf = yi*cos(rotX) - zi*sin(rotX)
zf = yi*sin(rotX) + zi*cos(rotX)
xf = xi

```

### Y-Axis rotation

```
zf = zi*cos(rotY) - xi*sin(rotY)
xf = zi*sin(rotY) + xi*cos(rotY)
yf = yi

```

### Z-Axis rotation

```
xf = xi*cos(rotZ) - yi*sin(rotZ)
yf = xi*sin(rotZ) + yi*cos(rotZ)
zf = zi

```

# Application

With this knowledge, we can construct a unit vector that represents the direction that your spaceship is moving in. Let's start by having it point forward, since opengl's view matrix point's forward (`-Z`) by default.

```
dir_init = vec3( 0, 0, -1 )
dir = vec3()

```

Now, we can plug `dir_init.x` in for `xi` and `dir.x` in for `xf`, and the same for the other two dimensions, and do the math above. After that, all we have to do is add each component to its respective component in the spaceships coordinates.

```
spaceship.x += dir.x * speed
spaceship.y += dir.y * speed
spaceship.z += dir.z * speed

```

Disclaimer: I started working with this concept today, and if I'm missing anything, feel free to comment.

# Answer
> 0 votes
Looking again at the code again gave me a great idea! Since velocity is just the change of position use OpenGL to do the grunt work. I was able to get the code below working, although, the answer above is better optimized. The code below is updated inside the drawing function and thrustSpeed and angularVelocity are changed in the keyboard function.

```
angle.x += angularVelocity.x * timeStep;
angle.y += angularVelocity.y * timeStep;
angle.z += angularVelocity.z * timeStep;
float matrix[16];

glPushMatrix();
    glLoadIdentity();

    glRotatef(degreesFromRadians(angle.z), 0.0, 0.0, 1.0);
    glRotatef(degreesFromRadians(angle.y), 0.0, 1.0, 0.0);
    glRotatef(degreesFromRadians(angle.x), 1.0, 0.0, 0.0);
    glTranslatef( 0.0, thrustSpeed, 0.0);

    glGetFloatv(GL_MODELVIEW_MATRIX, matrix);
glPopMatrix();

position.x += matrix[12] * timeStep;
position.y += matrix[13] * timeStep;
position.z += matrix[14] * timeStep;

glPushMatrix();
    glTranslatef( position.x, position.y, position.z);
    glRotatef(degreesFromRadians(angle.z), 0.0, 0.0, 1.0);
    glRotatef(degreesFromRadians(angle.y), 0.0, 1.0, 0.0);
    glRotatef(degreesFromRadians(angle.x), 1.0, 0.0, 0.0);

    glBegin(GL_QUADS);
    // CCW Quad
    glColor3f(1.0,1.0,1.0);

    glVertex3f(-1.0, 1.0, 0.0);
    glVertex3f(-1.0,-1.0, 0.0);
    glVertex3f( 1.0,-1.0, 0.0);
    glVertex3f( 1.0, 1.0, 0.0);

    glEnd();
glPopMatrix();

```

I’m just rotating around the OpenGL origin and then adding the matrix’s position as velocity.

---
Tags: opengl, vector, angles, motion
---


# Question
Title: Model disappears when viewing from up vector
I'm sure there is a simple explanation for this behavior that makes mathematical good sense, but I need a way to look at my model along the up vector. I have tested it with the three unit vectors to confirm it is viewing along the up vector that causes my model to disappear, at least in the current configuration.

tldr; Model disappears when camera is along up vector, how do I fix it?

Edit: Also forgot to mention besides changing the up vector to confirm, I also confirmed this was the problem by looking off the up factor by a small amount like so, which works fine I could potentially use this fact, but on principle I would like to know why I can't view along the up vector and possibly correct it in a way that makes mathematical sense:

```
if (Keyboard.GetState().IsKeyDown(Keys.D3))
    _cameraPosition = new Vector3(0f, 1f, 0.000001f);

```

One Solution, as suggested by DMGregory. You can change the up vector when switching to the top view like so and that works, better than using float epsilon I suppose. Code below, but I am still not sure that this is the best way to accomplish this effect:

```
        if (Keyboard.GetState().IsKeyDown(Keys.D1))
        {
            _cameraUp = Vector3.UnitY;
            _cameraPosition = Vector3.UnitX;
        }

        if (Keyboard.GetState().IsKeyDown(Keys.D2))
        {
            _cameraUp = Vector3.UnitY;
            _cameraPosition = Vector3.UnitZ;
        }

        if (Keyboard.GetState().IsKeyDown(Keys.D3))
        {
            _cameraUp = -Vector3.UnitZ;
            _cameraPosition = Vector3.UnitY;
        }

```

Code to follow, monkey from blender is the idol:

```
public class MyGame : Game
{
    private GraphicsDeviceManager _graphics;

    private Model _idol;
    private Matrix _idolWorld;
    private Vector3 _idolPosition;

    private Vector3 _cameraPosition;
    private Vector3 _cameraUp;

    private float _width;
    private float _height;
    private float _near;
    private float _far;

    private Matrix _view;
    private Matrix _projection;

    public MyGame()
    {
        _graphics = new GraphicsDeviceManager(this);
        _graphics.PreferredBackBufferWidth = 1920;
        _graphics.PreferredBackBufferHeight = 1080;
        _graphics.ApplyChanges();
        Content.RootDirectory = "Content";
    }

    protected override void Initialize()
    {
        // TODO: Add your initialization logic here
        _width = (float)(_graphics.PreferredBackBufferWidth >> 1);
        _height = (float)(_graphics.PreferredBackBufferHeight >> 1);
        _near = -MathHelper.Max(_width, _height) - 1f;
        _far = -_near;

        _idolPosition = Vector3.Zero;
        _idolWorld = Matrix.Identity;

        _cameraPosition = new Vector3(0f, 0f, 1f);
        _cameraUp = Vector3.UnitY;

        _view = Matrix.CreateLookAt(_idolPosition + _cameraPosition, _idolPosition, _cameraUp);
        _projection = Matrix.CreateOrthographicOffCenter(-_width, _width, -_height, _height, _near, _far);

        base.Initialize();
    }

    protected override void LoadContent()
    {
        // TODO: use this.Content to load your game content here
        _idol = Content.Load<Model>("Idol");
    }

    protected override void UnloadContent()
    {
        // TODO: Unload any non ContentManager content here
    }

    protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            Exit();

        // TODO: Add your update logic here
        if (Keyboard.GetState().IsKeyDown(Keys.D1))
            _cameraPosition = new Vector3(1f, 0f, 0f);

        if (Keyboard.GetState().IsKeyDown(Keys.D2))
            _cameraPosition = new Vector3(0f, 0f, 1f);

        if (Keyboard.GetState().IsKeyDown(Keys.D3))
            _cameraPosition = new Vector3(0f, 1f, 0f);

        _view = Matrix.CreateLookAt(_idolPosition + _cameraPosition, _idolPosition, _cameraUp);

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        // TODO: Add your drawing code here
        foreach (ModelMesh mesh in _idol.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {
                effect.EnableDefaultLighting();
                effect.World = _idolWorld;
                effect.View = _view;
                effect.Projection = _projection;
            }
            mesh.Draw();
        }

        base.Draw(gameTime);
    }
}

```

Edit for clabe45 (the model, near and far seem fine):

# Answer
> 0 votes
DMGregory suggested this answer. Thanks!

What he suggested seemed reasonable: https://en.wikipedia.org/wiki/Hairy\_ball\_theorem

To put this to the test, I created a bottom view perspective. The model did disappear as in accordance with the theorem, I should have at least two cow licks in this case.

Changing the up vector to accommodate the two unique cow licks turned out to be the answer:

```
    // side
    if (Keyboard.GetState().IsKeyDown(Keys.D1))
    {
        _cameraUp = Vector3.UnitY;
        _cameraPosition = Vector3.UnitX;
    }
    // front
    if (Keyboard.GetState().IsKeyDown(Keys.D2))
    {
        _cameraUp = Vector3.UnitY;
        _cameraPosition = Vector3.UnitZ;
    }
    // top
    if (Keyboard.GetState().IsKeyDown(Keys.D3))
    {
        _cameraUp = -Vector3.UnitZ;
        _cameraPosition = Vector3.UnitY;
    }
    // bottom
    if (Keyboard.GetState().IsKeyDown(Keys.D4))
    {
        _cameraUp = Vector3.UnitZ;
        _cameraPosition = -Vector3.UnitY;
    }

```

---
Tags: c#, xna, 3d, monogame
---


title: Libgdx, lines between tiles

text:
# Question
Title: Libgdx, lines between tiles
I'm trying to make smooth following camera using this algorithm:

```
camera.position.add((pos.x - camera.position.x) * 1.2f * deltaTime, (pos.y - camera.position.y) * 1.2f * deltaTime, 0);

```

It works fine(camera movements are smooth), but when I move the player appears this artifacts:

Player move() function:

```
moveX(SPEED  * deltaTime);

```

```
protected void moveX (float amount) {
        float newX = pos.x + amount;
        if (!map.doesRectCollideWithMap(newX, pos.y, getWidth(), getHeight()))
            pos.x = newX;
    }

```

# Answer
I found the solution.

1. Set texture filtering of TiledMap to Nearest.
2. Add 2px padding to your tileset.
3. Draw yor sprites 1px broeder each direction.
4. Profit!
> 2 votes

---
Tags: java, libgdx
---


title: Making random spawn points fair?

text:
# Question
Title: Making random spawn points fair?
If all players are spawned at random positions the same distance from adjacent players, the number of players will be proportional to the likelihood of their spawn positions being unfair. The closer players spawn to the centre of the map, the more likely they are to encounter other players and the less likely they are to survive, compared with players on the edge of the map. Assume all players are spawned at the same time.

Is there a way to shape spawn points, or change the map, so that:

1. All players have a limited number of adjacent foes.
2. All players have equal chance of encountering adjacent foes.
3. Map size does not have to increase proportional to the number of players.
4. These limitations are not enforced with arbitrary impassable spaces.

The answer does not have to be perfect, just obviously better than the alternative. Out of the box thinking welcome.

# Answer
Let the players pick their start locations themselves.

At the beginning of the game, spawn all players in the center of the map, but without any means of harming the other players. They will then have to swarm out and acquire the means to engage each other (build a base, pick up a weapon, gather resources, etc.)

There is either a bit of luck or map knowledge involved in finding a good start location early (depending on whether you use procedural or handmade maps). But when and where to settle is mostly a strategic decision. Deploying early gives you a time advantage, but puts you in a dangerous position. Picking your base carefully puts you behind in the early-game, but can be a decisive advantage in the mid- and late-game.
> 26 votes

# Answer
## Understanding the requirements

> 1. All players have a limited number of adjacent foes.

First off, we are talking about the spawn points of the players, not the current position of the players at a given point in the game. *Just getting that out of the way.*

Adjacent is well defined when we talk about a graph. We can think of a map that represent navigability on the map - from now on "the graph".

If can node can have at most one spawn point, then talking of them being "adjacent" makes sense. Note: I will not constraint nodes to have one single spawn point at most, for reasons that will be apparent later.

To build the graph we will need to consider things such as walls, bridges, ladders, teleportation points, or even consider flight space if there could be player that can fly. Each node represents a traversable location; each connection represents a possible movement.

Note: know size and shape of the nodes, and work with actually adjacent nodes. Do not consider nodes a point. Do not consider connections as having length. Also, use convex nodes.

The graph could have been precompiled (the map was created by a designer); otherwise, it can be created on the fly if the map is randomly generated.

> 2. All players have equal chance of encountering adjacent foes.

I will assume foes are other players. *Again, just getting that out of the way.*

Assuming each player makes a random walk, the probability of finding a player at a given point - on a flat space, free of obstacles - will be given by a (Gaussian) function of the distance to the spawn point - from now on "the function".

Since we are working on the graph, we will instead annotate the values on the graph.

> 3. Map size does not have to increase proportional to the number of players.

If we had the constraint of having a single spawn point per node, then to add more player we would need smaller nodes. If we decide the graph before we know how many player we will have, we may have to subdivide nodes for the particular game.

> 4. These limitations are not enforced with arbitrary impassable spaces.

I do not intend to add obstacles to solve the problem. *Au contraire*, I need to work arround the obstacles. If they were not there, the implementation would be simpler.

---

## Solution

We are trying to place N spawn points such that the chance of encountering another player at all those spawn points is equal.

We can get a measure of the error as the sum of the differences of the chances to the mean of the chances. We are trying to minimize that (in fact, we want to make it 0).

To do so, we need to know the chance of encountering a player on each node of the graph.

To compute that chance, start with zero. *Since the chance of finding a player on any given node, when there are no players, is zero.* And then, for each spawn point, walk the graph adding to the annotated chance the value of the function for the current spawn point.

Note 1: Adding or moving a spawn point will affect the chance of encountering a player for all the map.

Note 2: Keeping track of how much each spawn point affects the chance, will make things easier.

Note 3: Since nodes have size, how close you can get to error = zero depends on the size of the nodes. You can be more precise by working with ranges of values (minimun and maximun chance, depending on the particular position of the spawn points within the node).

Place spawn points at random, then start moving them in such way that error becomes smaller (consider a possible movement, and if causes the error to decrease keep it, otherwise revert it). And continue doing so until we cannot improve any further (too many iterations without improvement, or error is zero).

Note 4: When moving a spawn point, you can use the chance of encountering a player (excluding the spawn point you will move) to randomly select a new position for a spawn point such that position that have a chance of encountering a player closer to the mean are more likely. I remind you that moving the spawn point will affect the mean.

The expected behavior is that spawn point that are too close together move apart and spawn points that are too far apart come closer. Until they reach equilibrium.

If at any given iteration you have multiple spawn points on a node (which is unlikely, since they should tend to move apart, but possible if you have large enough nodes), split the node and continue solving. Any division of the node is valid.

---

The above solution will approach error = zero, but not guaranteed to reach zero. You can do is run it until it reaches a local minimum... In theory, you can then divide nodes to make it exactly zero... Yet, that is equivalent of tweaking the spawn point coordinates!

Try simulated annealing to move the spawn point within the node. Although, honestly, it probably is not worth it to bother with such level of detail.

---

I want to make it clear that the result for a flat map free of obstacles will not be uniformly distributed points. Instead, if the map has edges (that is, if it does not wrap around), then there will be more spawn point closer to the edges, this is because points at the center can be reached from more directions, increasing the chance of encountering other players there. Thus, points further apart near the center to compensate.
> 8 votes

# Answer
It depends on what kind of game you want to create and how fast paced it is. The perfect evenly spaced distribution is possible on a sphere like world (for example Planetary Annihilation). But is that a fair option in your game? Even if all people are spawning on equal distance, some spawns may still have better advantage.

* Closer/ better weapons in range/ more resources
* Better cover/ more hidden/ overview
* the 'flow' of the players, some places are more attractive than others (think of a full forest map with a single house at one place, regardless where that house is, good chance that people are checking it out)

Is your map a fixed one or a procedural generated one? And ever tried to play Age of Empires with 8 people on a 2 person map? It's not possible to scale the players infinite without making adjustment to the map size. Even an unfair start placement can bring a lot of dynamic in the game (see the Worms series). Nobody complained if you spawned right in a big cluster, as long as your one round alliance with another player lasted or you had not the most surviving worms after the first round.

(I will add a few more examples if I know more about your type of game)
> 5 votes

# Answer
Going for something not suggested so far: Make it so there is no centre of the map. What I mean by this is that the map edges join onto the opposite sides. This would take a lot of programming work, but in practise it can make the level repeat itself infinitely if you walk in one direction. This means that there is no centre, and a random spawn position will have no advantages or disadvantages.

You can do this by making a flat map which is square, and joining each edge to a copy of the opposite edge. When a player walks off the side, they are teleported without the player's knowledge to the opposite edge. Of course, theoretically you would not be able to see players on the other side of the boundary. To fix this, create clones of that player which appear to walk around on the other side of the boundary so that you can see them, and when you run towards them you teleport across and the actual player is stood where the dummy was.

Alternatively, the entire map could exist on the outside of a sphere, however this makes coordinates difficult for spawning.
> 4 votes

# Answer
Here are some possible solutions:

* Spawn randomly on the circumference of the circle
* Spawn randomly on radii (not spawning to close the center)
* Add a random spawn time component
> 3 votes

# Answer
Fundamentally I believe this is a graph distribution problem. Assuming a deathmatch situation (every other player is an enemy), you need to model your maps as an interconnected graph, and track which node on the graph each player is closest to. Not every node need be a spawn point, but you need the complex graph to model distances between spawn points. At spawn time, you're then iterating the graph and scoring each spawnable-node based on whether it nearby nodes have players.

The ideal node then has:

* No players currently in it
* More than zero players in nodes nearby (some small number of links away)

Imagine that your graph has been regularised, and you're drawing concentric zones around each node. You penalise the node if the inner zones already have players in them, and reward nodes that have players at the right distance away. You want to encourage spawning near enough to other players that they can find interest quickly, but not so near that they get jumped on before they've had a chance to get their bearings.

You **will** need to increase the map size as the number of players grows, but the `k` need not be 1 or greater. Your worst case is still going to be that every node on the graph has at least one player - in which case there are no good nodes to use, and you're going to have to suffer that case and spawn a player knowing that they will land right on top of another. The scoring algorithm should still weight the nodes so that you spawn in the node with the fewest other players.

Bear in mind that your map graph will have to be carefully built, with knowledge of the map, its routes, any chokepoints, and *effective* distance between node points, not *actual* distance. As in, use something like measured time to traverse between nodes rather than distance, to account for more difficult terrain. Also you need to account for open-ness vs cover; two nodes might be physically far apart, but because they are very open, spawning a player at each node might mean they are equally as vulnerable as if you'd spawned them right next to each other.

Refinements:

* Add a temporary penalty to score if a player has spawned in that node recently, to stop chokepoints from forming (an endless stream of players coming from the same direction and getting picked off)
* Add randomness within a range (e.g. pick the best 3 nodes and then randomly choose between them with equal probability) to get more variation.
* Add an initial weight to the centre of the map (or the most interesting points) when no-one has yet spawned, so that you spawn in known places, even when every node has a score of zero because no other players are present.
> 0 votes

# Answer
A few others have already discussed the limitations of your requirements (map will need to scale at some point to prevent overcrowding, etc.), and have ultimately eluded to the fact that there likely isn't a "perfect" placement algorithm. When there likely is no "perfect" algorithm, I always look towards heuristics. You have several criteria that are either directly or indirectly at odds with eachother, along with a very complicated search space. Finding an optimal solution may not be feasable or practical, but with a little tuning, a statistical approach can perform very well the majority of the time.

**Addressing your third and fourth criteria:** *"The map shouldn't have to expand."*

I would make sure at the beginning you have an over-abundance of nodes (ie: as dense as a navigation mesh for path-finding). This makes calculating the distance to other players more expensive (not directly neighboring nodes), but this is not a process that will happen more than once per round (I assume). A bonus of this is you can use a pre-rolled nav library for most of your operations. Additionally this will respect traversal around obstacles in a fair manner where euclidean distance may not (players in a maze might be placed closer together than in an open field)

**Calculate heuristics for your desired spawn characteristics:**

After randomly placing all the players, calculate the performance of the surrounding nodes based on your criteria (distance from other players, distance to spawn, etc.) The weights of your values can be tweaked, and manipulated to be nonlinear to tune exactly the performance you want in a sanitized ideal case (flat rectangular grid with no obstacles), and the performance should be similar when you add the world back in. From there you can decide how many nodes to search, what is the threshold for moving a starting point, and how many iterations you want to perform before finalizing the spawn and beginning the game.
> 0 votes

# Answer
If the playing field is a topological torus (i.e. a rectangle where going “out of bounds” means entering at the opposite side), this is likely to be a good answer: player `j` spawns at `x = (pjW/N) mod W, y = (qjH/N) mod H`, where `W,H` are the dimensions of the rectangle, `N` is the number of players, and `p,q` are integers to be determined; they are distinct, (probably) relatively prime, and not too far from `sqrt(N)`. The spawn points form an oblique ‘wallpaper’ pattern.

That's supposing that the players spawn only at the beginning of the game. If they spawn later, I guess you'd want to put them as far as possible from any player's current position – at a vertex of the Voronoi diagram defined by the other players.
> 0 votes

# Answer
How about:

**Each player is surrounded by a non-spawning box** (or circle).

As in, there's a square of a certain size that spawns around every player and follows that player around - no other player can spawn within that square.

These squares only affect spawning and not any other movement during the game.

This works with either initial-only spawning or continuous spawning.

(Dots indicate players and green indicates possible spawn area for new players)

> Map size does not have to increase proportional to the number of players

To deal with this, you can do one of two things: (or both)

* Decrease the size of the non-spawning boxes based on the number of players.
* Allow up to X enemy players to spawn in each box.
    + This number can increase as you go (starting at 0).
    + Variant 1: have a smaller no-spawn box and a larger limited-spawn box.
    + Variant 2: weight probabilities according to how close the new spawn is to this player (if inside the box) - might be hard to implement efficiently.
> 0 votes

---
Tags: game-design, level-design
---


# Question
Title: how to save Audio Volume to playerprefs to mute all scenes sounds
Please Explain me how to Save or Set Audiolistner or scene Audio to playerprefs to control game all scene sound by a simple Button On and Off ..

Please Give Me C sharp Script as a Example To Mute and UnMute Full Game All Scenes Sound from Scene 1.

Thanks ..Waiting

# Answer
> 0 votes
First of all you need to use is the pattern below to control all the scene's sounds in one place:

-Create a **MusicManager** class. It would better be singleton.

-Initialize an object from this class, and use DontDestroyOnLoad() in order to keep musicmanager alive when scene changes;

-Declare a static methods like:

* `public static void PlaySound(AudioClip clip);`
* `public static void SetVolume(float volume);`
* public static void Mute(){audioSourceObject.volume = 0f;}

-Then when it comes to play any audio, use these methods for playing sound by giving the sounds as a parameter.

-Also when it comes to mute just call the mute function.

For saving purposes:

```
PlayerPrefs.SetFloat("soundVolume", currentVolume);  //Note that you need to keep the volume in a variable called currentVolume or whatever you name it.

```

And also when the game starts, put the code below in MusicManager class' `void start()` method:

```
currentVolume = PlayerPrefs.GetFloat("soundVolume");
SetVolume(currentVolume);    //This function has been defined above

```

By doing these, if the player mutes the game, the musicmanager will set the volume to 0f, then save it as 0f when the game gets closed. And also be re-set as 0f when the game is opened again.

Hope this helps!

---
Tags: unity, sound
---


# Question
Title: How to move sprite as if not rotated when rotated 90 degrees?
We're making a Tetris like game and need help rotating shapes.

Moving the shape works when there is no rotation.

However, after rotation, snapping the shape to the grid fails because the vector between the shape's current position and destination is affected by the amount of rotation (e.g., rotated 90 degrees).

As a simple example, let's assume a shape consists of one square and currently sits at (8, 0).

If the user rotates the shape 90 degrees (ignore that this functionally does nothing since the shape is only one square) then wants to move the shape to (1,0), what should the vector be? And how do you generalize the vector math?

We're using Swift 3 for an iOS game.

```
    if isShapePosValid(shape: curShape) {
        let firstTile = curShape.getLowestTile()
        let nearestBoardTile = getNearestBoardTile(shapeTile: firstTile)!
        let newTilePos = firstTile.parent!.convert(nearestBoardTile.position, from: nearestBoardTile.parent!)
        let moveVector = CGVector(point: newTilePos - firstTile.position)
        let move = SKAction.move(by: moveVector, duration: 0.1)
        curShape.run(move) {
            self.printShapeToBoard(shape: curShape)
        }
    }

fileprivate func rotateShape(shape: BoardShapeSprite) {
    let rotate = SKAction.rotate(byAngle: CGFloat(Double.pi/2), duration: 0.1)
    shape.run(rotate)
}

fileprivate func printShapeToBoard(shape: ShapeSprite) {
    let tiles = shape.getTiles().filter{ $0.value != .Empty }

    for t in tiles {
        let boardTile = getNearestBoardTile(shapeTile: t)
        boardTile?.setValue(value: .Taken)
    }
}

```

# Answer
> 1 votes
Are you using a game engine? you didn't clarify that. (I assume you are using Unity) You should change the tetris piece's world position instead of moving in the direction of the right or forward vector. Or you make the tetris piece the child of another object and move the parent instead.

---
Tags: vector, swift
---


title: How to implement jump in NavMesh?

text:
# Question
Title: How to implement jump in NavMesh?
I want my NavMeshAgent to jump when `Space` key is hit.

The Script (*in Unityscript*) I tried is **:**

```
var isJump:boolean=false;

function Update () {

  if(Input.GetKeyDown(KeyCode.Space)){

     GetComponent.<UnityEngine.AI.NavMeshAgent>().enabled=false;
     GetComponent.<Rigidbody>().isKinematic=false;
     GetComponent.<Rigidbody>().AddForce(0,400,0);
     isJump=true;

 }
}

 function OnCollisionEnter(col:Collision){

   if(col.gameObject.layer==4 && isJump){

     GetComponent.<UnityEngine.AI.NavMeshAgent>().enabled=true;
     GetComponent.<Rigidbody>().isKinematic=true;
     isJump=false;
  }

}

```

The ground where the NavMeshAgent stands is in layer 4. But the Agent is not jumping in the first place. But when I don't used the *OnCollisionEnter* function it jumps. But I need some function to return it to the initial state.

I tried a *print("something")* inside *if* statement of *OnCollisionEnter* function and it prints it as soon as I hit `Space`. That *if* statement should have executed when the object jumped and collides with the ground.

How to make it work?

# Answer
## Why it is not working

As you said, the function is called as soon as you hit `Space`. That's why it doesn't work because `isKinematic` is then instantly reset to `true` before your character can even start his jump. You must have another object other than the ground that is in layer 4 and is colliding with the player.

## How to make it work

Instead of using the layer, I would give the Ground object (and any other similar object) a **Tag**, like "Ground" for instance. And use :

```
function OnCollisionEnter(col:Collision){

   if(col.gameObject.tag == "Ground" && isJump){

     GetComponent.<UnityEngine.AI.NavMeshAgent>().enabled=true;
     GetComponent.<Rigidbody>().isKinematic=true;
     isJump=false;
  }
}

```
> 2 votes

# Answer
Just hold for sometime before changing isJump to true.

Here's the edited script **:**

```
 var hold:boolean=true;
 var isJump:boolean=false;
 function Update () {

if(Input.GetKeyDown(KeyCode.Space)){

  gameObject.GetComponent.<UnityEngine.AI.NavMeshAgent>().enabled=false;

  GetComponent.<Rigidbody>().isKinematic=false;
  GetComponent.<Rigidbody>().AddForce(0,400,0);
  if(hold)
  Hold();

  }
}

function Hold(){
   hold=false;
   yield WaitForSeconds(0.1);
   isJump=true;
   hold=true;
 }

  function OnCollisionEnter(col:Collision){

     if(col.gameObject.layer==4 && isJump){

     GetComponent.<UnityEngine.AI.NavMeshAgent>().enabled=true;
     GetComponent.<Rigidbody>().isKinematic=true;
     isJump=false;

    }
   }

```
> 0 votes

---
Tags: unity, unityscript, navmesh
---


title: Walk to mouse click position in Java

text:
# Question
Title: Walk to mouse click position in Java
I am very new to programming, and trying to get my player to walk to the mouse click position. I currently have this script, which "teleports" my character to the clicked position:

```
private void getInput() {
    xMove = 0;
    yMove = 0;

    float tempX = handler.getMouseManager().getMouseX();
    float tempY = handler.getMouseManager().getMouseY();
    float diffX = tempX - x;
    float diffY = tempY - y;

    if (handler.getMouseManager().leftPressed) {
        x = tempX;
        y = tempY;
    }
}

```

The first thing that came to my mind was to use the following script, for moving to a click which is to the right:

```
if (handler.getMouseManager().leftPressed) {
    if(diffX>0) {
        for(float counter = 0; counter = diffX; counter++)
            xMove = speed;
    }
}

```

However, this doesn't work. How would I go about making my player walk to the mouse click position?

# Answer
> 1 votes
So first thing to be aware of is that the movement is a small bit at a time per game loop. It happens over a number of frames. And so the code here should help once you are sure about the concept of a game loop.

I guess there are a few ways to achieve this. This method uses a direction to move. It may seem a bit over the top but once you have a direction you can multiply it easily in order to adjust speed for gameplay reasons. It can also help if you are not using fixed frame rates.

I've just hard codes target and source here, but target would be your click position and source would be your character position.

```
        double targetX = 100;
        double targetY = 100;

        double sourceX = 200;
        double sourceY = 10;

        // tweak this to alter movement speed
        double speed = 2.0;

        // create a vector from source to target
        double vx = targetX - sourceX;
        double vy = targetY - sourceY;

        // create a normalised direction (in the range 0-1)

        // .. we'll need the distance of the vector to figure out a normalised vector.
        double distance = Math.sqrt(vx * vx + vy * vy);

        // figure out the direction
        double dirX = vx / distance;
        double dirY = vy / distance;

        // dirX,DirY is now normalised vector to target from source.
        sourceX += (dirX * speed);
        sourceY += (dirY * speed);

```

\`

# Answer
> 0 votes
First of all, the loop in the second code snippet you gave doesn't terminate. You don't have a condition for termination. I think you meant `counter <= diffX`. Secondly, when you assign something in a loop, it will just get overwritten each time - so instead of setting `xMove` to `speed` inside the loop, you could just do it without the loop entirely, so this is probably not what you want.

To get your player towards the mouse position you could create a loop and in each step, just walk a very short amount. Here's an example:

```
private void walkToPosition(float toX, float toY, int steps) {
    float diffX = toX - x;
    float diffY = toY - y;

    // The increments are our step sizes. In each step of the for-loop,
    // the player walks as much as incrementX, resp. incrementY indicates.
    float incrementX = diffX / steps;
    float incrementY = diffY / steps;

    for (int i = 0; i < steps; i++) {
        x += incrementX;
        y += incrementY;
        // if the drawing doesn't happen in parallel, we'll need to do it explicitly
        updatePlayerView();
        Thread.sleep(1);
    }
}

```

One disadvantage of this method is that you have to choose a really large step size, because otherwise the player moves really fast. Also, how fast the player moves depends on the speed of your PC because the for loop just executes as fast as possible. If you want to fix this, it gets a bit more complicated. Essentially, your goal is to make the player speed independent of how fast your code is running (so that the player moves with the same speed on every PC, and also so that the player doesn't slow down when your PC is running many programs at the same time).

To decouple player speed and PC computation speed, you'll have to measure how much time your computer takes to do each loop step. This is a bit more complicated, so if you want to learn how to do that, I suggest you try this tutorial: http://www.java-gaming.org/index.php?topic=24220.0

Hope this helps!

---
Tags: java
---


title: Compute Corners of Cuboid In 3D

text:
# Question
Title: Compute Corners of Cuboid In 3D
How can I compute the eight corners of a cuboid given a Depth and Height and two points: A(x,y,z) and B(x,y,z)?

Is it possible to calculate the eight corners/points of a cuboid given only a limited data? I'm trying to make a cuboid with only two 3D vectors by computing the eight vectors.

# Answer
This would do the trick for the 4 points around A

* Corner1 = (A.x + Depth/2, A.y + Height / 2, A.z)
* Corner2 = (A.x - Depth/2, A.y + Height / 2, A.z)
* Corner3 = (A.x + Depth/2, A.y - Height / 2, A.z)
* Corner4 = (A.x - Depth/2, A.y - Height / 2, A.z)

And for the 4 points around B

* Corner5 = (B.x + Depth/2, B.y + Height / 2, B.z)
* Corner6 = (B.x - Depth/2, B.y + Height / 2, B.z)
* Corner7 = (B.x + Depth/2, B.y - Height / 2, B.z)
* Corner8 = (B.x - Depth/2, B.y - Height / 2, B.z)

**EDIT :** As pointed out by @DMGregory, my solution only works with the cuboid being parallel to the Z axis.
> 2 votes

# Answer
I'll assume you have a Vector3 and a Matrix3 class. First of all, let's define a unit cube:

```
(-0.5, -0.5, 0)
(0.5, -0.5, 0)
(0.5, 0.5, 0)
(-0.5, 0.5, 0)

(-0.5, -0.5, 1)
(0.5, -0.5, 1)
(0.5, 0.5, 1)
(-0.5, 0.5, 1)

```

Now, to create the rectangle you need, you need to scale the vectors based on the height, depth and the distance between **A** and **B**. To do this, you need a scale matrix:

```
    | Depth 0      0       |
S = | 0     Height 0       |
    | 0     0      |A - B| |

```

Where |**A** \- **B**| is the length of the **A** \- **B** vector

Now the cuboid has the correct size. The next step is to rotate it.

Because the **A** and **B** vectors only define the rotation around the X (pitch) and Y (yaw) axis, you only need to calculate those:

Let **C** be **A** \- **B** for convenience.

The yaw can be calculated by throwing away the y axis, which projects the vector to the XY plane. Then the angle becomes

```
yaw = atan(C.y / C.x)

```

The pitch is a little bit different. You need the length and the z component of the vector:

```
pitch = arccos(C.z / |C|)

```

Now that you have the angles, you need to construct a rotation matrix:

```
    | 1 0          0           |   | cos(yaw)  0 sin(yaw) |
R = | 0 cos(pitch) -sin(pitch) | * | 0         1 0        |
    | 0 sin(pitch) cos(pitch)  |   | -sin(yaw) 0 cos(yaw) |

```

To get the angles of the cuboid you need to take every vector of the cuboid, multiply it by the matrices and add **A** to it:

```
newPoint = R * S * point + A

```
> 2 votes

---
Tags: 3d, geometry
---


# Question
Title: How to deal with collision detection result
I have a render loop. In it I always call the `update()` method which moves all the objects in their own directions. Then after that I call `checkCollision` on each object with each object like that:

```
for (GameBodyObject gbo1 : objects) {
   for(GameBodyObject gbo2 : objects) {
      if(!gbo1.equals(gbo2)) {
         gbo1.checkCollision(gbo2);
      }
   }
}

```

btw I am using `Circle` as collider

now in `checkCollision` I first check if they collide and then if yes I calculate the displacement like this:

```
if(CircleCollider.collide(p1, r1, p2, r2)) {
   double totalR = r1 + r2;
   double a = new Vector(p1.getX() - p2.getX(), p1.getY() - p2.getY()).getAngle();

   double intersection = Math.abs(totalR - p1.distance(p2));

   return new Vector(Math.cos(a) * intersection, Math.sin(a) * intersection);
} else {
   return new Vector(0, 0);
}

```

then I move the `GameBodyObject` by this displacement vector like this:

```
public Point moveByVector(Vector v) {
    if(v.getX() == 0 && v.getY() == 0) {
        return this;
    }
    double a = v.getAngle();
    double l = v.getLength();
    x += l * Math.cos(a);
    y += l * Math.sin(a);
    return this;
}

```

However I get a bouncing effect so the one gameBodyObject goes into another gameBodyObject and back and again into that gameBodyObject and back. I want it to stop, not to bounce.

How could I do that?

One way that come up to my mind is that I will check for collision in the `update()` function directly and if it occurs I won't move the guy, but then it may get stuck if he runs into another gameBodyObject...

How should I deal with that?

(BTW did you play Dota 2? I want the mechanics similar to that game so that one player can block another player and trees are static so they don't move so the player can't push them instead he stops...)

# Answer
> 1 votes
You need to check whether or not collision will occur before you transform the object. When collision is imminent change the transformation number to be small enough so that the colliding object only touches the border of the other object.

# Answer
> 1 votes
If you want to use collision detection to prevent movement, then don't do collision checks for everything with everything in your update loop. Do a collision check whenever you change the position of an object. Check if the destination is clear, and when it is not, don't execute the move (or alternatively, only execute it up to the collision position).

When you do this rigorously on **every** position change (including newly spawned entities), then there **can not** be a situation where two objects share the same space. But if there is some obscure corner-case where two entities sharing the same space can not be avoided, then you might want to at least allow the space-sharing entities to move away from each other. You can do that by checking for collisions with the old position of an object and then ignore any objects you find there when you check for collisions with the new position.

By the way, you can drastically improve collision detection performance by only checking collisions with objects which are close enough that they could potentially collide. So when you run into performance problems, check out data structures like spatial hashing or 2d trees which allow you to quickly get all objects in a given area.

---
Tags: collision-detection
---


# Question
Title: How to get the rotation matrix to transform between two 3d cartesian coordinate systems?
I'd like to know how to get the rotation matrix for the transformation from one cartesian coordinate system `(X, Y, Z)` to another one `(X', Y', Z')`.

Both systems are defined with three orthogonal vectors as one would expect. No scaling or translation occurs. I'm using *OpenSceneGraph* and it offers a `Matrix` convenience class, if it makes finding the matrix easier:

> http://www.openscenegraph.org/documentation/OpenSceneGraphReferenceDocs/a00403.html.

# Answer
> 6 votes
One easy way is to think of both coordinate systems as transforms from the unit vectors (1,0,0) (0,1,0) and (0,0,1). You start off in this coordinate space (I will call it '1')whose transform matrix is the identity matrix:

```
    [1,0,0]
I = [0,1,0]
    [0,0,1]

```

then your first coordinate space (I will call it '2') has the transform matrix:

```
    [Xx,Xy,Xz]
A = [Yx,Yy,Yz]
    [Zx,Zy,Zz]

```

and your second coordinate space (I will call it '3') has the transform matrix:

```
    [Xx',Xy',Xz']
B = [Yx',Yy',Yz']
    [Zx',Zy',Zz']

```

For your points to be in the first coordinate system, then you have transformed them from 1 to 2. If you want to go from 2 to 3 then you can undo the transform from 1 to 2 then do the transform from 1 to 3. You can reverse the transform by inverting 2's transform matrix.

A point v in 2 can be transformed to a point v' in 3 with this equation: v' = B(A^-1)v where (A^-1) is the inverse of A.

Note this also handles scaling even though you don't need it. This approach will work with translation as well, though you would need a 4x4 matrix instead of a 3x3.

# Answer
> 1 votes
I worked on a project that had lots of transformation to do. I found lots of links on the subject, but they used math that I couldn't comprehend because the symbology was alien. I finally found this paper, which revealed the contents of the matrix to use. The short answer is that the matrix is composed of the dot product of the different axis that you're trying to convert to and from.

In order to save some pain for the next developer I posted some C# in GitHub that has a working sample. The program was derived from one that I found on Code Project, which was written to demonstrate using quaternions but which I found to be useful as a ready-to-go program that would let me rotate and display a surface.

If you want to see what's under the hood here is the essential code. This doesn't show the actual transformation, that's in the code, but the secret sauce of how to do it is located here.

```
Vector3d X1 = XAxisWorld;            // This is vector (1,0,0)
Vector3d X2 = YAxisWorld;            // This is vector (0,1,0)
Vector3d X3 = ZAxisWorld;            // This is vector (0,0,1)

// These vectors are the local X,Y,Z of the rotated object
Vector3d X1Prime = XAxisLocal;
Vector3d X2Prime = YAxisLocal;
Vector3d X3Prime = ZAxisLocal;
// This matrix will transform points from the rotated axis to the world
LocalToWorldTransform = new Matrix3x3()
{
    M11 = (float)Vector3d.DotProduct(X1, X1Prime),
    M12 = (float)Vector3d.DotProduct(X1, X2Prime),
    M13 = (float)Vector3d.DotProduct(X1, X3Prime),
    M21 = (float)Vector3d.DotProduct(X2, X1Prime),
    M22 = (float)Vector3d.DotProduct(X2, X2Prime),
    M23 = (float)Vector3d.DotProduct(X2, X3Prime),
    M31 = (float)Vector3d.DotProduct(X3, X1Prime),
    M32 = (float)Vector3d.DotProduct(X3, X2Prime),
    M33 = (float)Vector3d.DotProduct(X3, X3Prime),
};
// This matrix will transform points from the world back to the rotated axis
WorldToLocalTransform = new Matrix3x3()
{
    M11 = (float)Vector3d.DotProduct(X1Prime, X1),
    M12 = (float)Vector3d.DotProduct(X1Prime, X2),
    M13 = (float)Vector3d.DotProduct(X1Prime, X3),
    M21 = (float)Vector3d.DotProduct(X2Prime, X1),
    M22 = (float)Vector3d.DotProduct(X2Prime, X2),
    M23 = (float)Vector3d.DotProduct(X2Prime, X3),
    M31 = (float)Vector3d.DotProduct(X3Prime, X1),
    M32 = (float)Vector3d.DotProduct(X3Prime, X2),
    M33 = (float)Vector3d.DotProduct(X3Prime, X3),
};

```

---

The text is copied from an archived version of the page originally presented as the answer and that had rot.

---
Tags: matrix, linear-algebra, openscenegraph
---


title: How to make my animation play once?

text:
# Question
Title: How to make my animation play once?
In 3ds max, I've made a Cannon that sets itself up, but I only want this animation to play once, here's where I'm trying to make it loop only once:

When I click the toggle at the bottom, it stops the animation for constantly looping, but when I click 'Save', and run my game, it still continues to loop.

What am I doing wrong?

# Answer
It sounds like you want the animation to stop on the last frame. To do this, open up your Animation Blueprint, and select the animation state associated with your animation in the Viewport. Then simply uncheck the 'Loop Animation' box under the Settings options of the details panel, as shown in the picture below. I hope that answers your question!
> 0 votes

---
Tags: animation, unreal, skeletal-animation
---


# Question
Title: Programming Pattern: Representation of pick up objects
I'm pondering about the best way to represent objects that can be picked up in my 2D engine.

I have an **Actor** class which is the base for all objects that can be spawned into the game. This class offers a location and some other information needed by all actors.

Now, let's take an Apple for example. It's derived from **Actor** and carries with it all the information needed to be in the game-world. But when I pick this item up and put it inside an inventory, I don't need all that **Actor** stuff. So I was pondering. Does it make sense to maybe have an **AppleActor** class instead that derives from **Actor**, and inside it have an **Apple** class derived from something like **InventoryItem**?

When I pick up an **Actor**, I would take the **InventoryItem** out of it, store it in my inventory and destroy the **Actor**. Then, when I drop the **InventoryItem**, I would first create the corresponding **Actor** for it, put the **InventoryItem** inside it and spawn that **Actor** in the world.

Does this make sense at all? Any feedback or advice from more experienced people here is welcome.

# Answer
I would keep the underlying data model for my inventory separate from the visual representation (MVC basically) for exactly the reasons you bring up. I'd have an AppleActor while the object is actually spawned out in the world, but once I pick it up it's just an ID (probably a key in a dictionary that associates ID with amount) in the InventoryModel.
> 1 votes

# Answer
I wouldn't make `Apple` an `Actor`. Make `Apple` an `Item` and allow `Actor`s to hold references to them via a backpack, which could just be a `List` or array of `Item`, or a hand which is a `Item` ref. Now your `Actor` can just walk around picking up and dropping `Item`s, as in the real world.

Related: You'll find dynamic languages tend to have a top-level `object` type. You'll notice these usually don't have much in them, because when that `object` can represent just about anything in its role as a base class, it's very difficult to get specific about it without forcing derived objects to carry around unnecessary methods and members. The same is true in your case; while it may seem attractive to have some sort of generic, top-level `GameObject` class (in your case, `Actor`), it's not always the right way to go about things. You've said you need e.g. `position`... so, OK then.

I would keep `Actor` for actual walking, talking things and use a different name for your top level... if you decide to have a top level at all.

The way to decide that is to ask, "In what ways are these objects processed similarly?" If they are never processed or held in the same ways, then don't bother having them derive from the same base class. If they are processed in some similar yet abstract way, then do give them a base.
> 1 votes

---
Tags: architecture, gameobject
---


# Question
Title: How do I get the collision position of the gaze input
I'm trying to move a Third-Person character by looking at random objects in the scene using the googleVR Rectile, what I had in mind is lerping the character to the collision point position. Any Help how to do this ?

# Answer
> 1 votes
In first person mode, where the user is moving themselves by looking around, the reticle is always in the center of the screen. So you can just as easily move forward to achieve the same effect.

Either with a straight constant movement:

```
void Update() {
    this.transform.Translate(transform.forward * Time.deltaTime);
}

```

or do a Raycast to ensure the player is looking at one of your specified objects:

```
void Update() {
   if(Physics.Raycast(transform.position, transform.forward,
        Mathf.Infinity, LayerMask.GetMask("MyObjectLayer")))
    {
        this.transform.Translate(transform.forward * Time.deltaTime);
    }
}

```

Where all the objects that cause the player to move forward are in the layer 'MyObjectLayer".

In a third person scenario, or if you've moving something other than the player, you'll want to get the position of the hit, so you can move the target object toward that position.

For that, use this version of Raycast:

```
public GameObject targetObject;

void Update() {
    RaycastHit hit;
    if (Physics.Raycast(transform.position, transform.forward, out hit,
        Mathf.Infinity, LayerMask.GetMask("MyObjectLayer")))
    {
        Vector3 direction = MoveTowards(TargetObject.transform.position,
                                        hit.point, Time.deltaTime);
        targetObject.transform.Translate(direction);
    }
}

```

Where `targetObject` is the object you want to move toward the hit point.

---
Tags: unity, virtual-reality, google-cardboard
---


# Question
Title: Libgdx: Using an AssetManager in every Screen or use a single AssetManager in Game class
I have a `HexGame` class extending `Game` and various `Screen`s that receive the game object in their constructor. I was thinking of having one `AssetManager` in the game class and using it to load the necessary assets in each screen's constructor and unload them in the screen's dispose method. The alternative would be to use a new AssetManager in every screen. What would be best practice?

# Answer
> 1 votes
I would suggest using a single AssetManager, unless your assets are so large that memory would be a problem.

Again, depending on your size, you may also want to just load all assets up front. You would probably prefer to not load and unload assets during game play if it can be avoided. This will make screen transitions quicker/smoother.

One reason though to use multiple AssetManagers is if you're loading from different locations. As an example, for my last LibGDX project, I was loading a small number of included assets locally, but also loading assets from AWS S3, with some local caching. So I had two AssetManagers to handle those cases.

---
Tags: libgdx, asset-management
---


title: Error once unity got updated to 2017.1

text:
# Question
Title: Error once unity got updated to 2017.1
I am working on a 2D platformer and I decided to update unity to the lastest version. Everything went well but once I got the project updated I got 2 error that I am not sure how to fix. Some help would be greatly appreciated!!!

Here is what the console is saying

```
Assets/Scripts/GameMaster.cs(148,112): error CS0039: Cannot convert type UnityEngine.Transform' to UnityEngine.GameObject' via a built-in conversion

Assets/Scripts/GameMaster.cs(111,96): error CS0039: Cannot convert type UnityEngine.Transform' to UnityEngine.GameObject' via a built-in conversion

```

Here are the lines that it is pointing to

```
GameObject clone = Instantiate (spawnPrefab, spawnPoint.position, spawnPoint.rotation) as GameObject;

GameObject _clone = Instantiate(_enemy.deathParticles, _enemy.transform.position, Quaternion.identity) as GameObject;

```

Thanks!!!!

# Answer
What is the variable type of *spawnPoint* if it is *GameObject* change it into *Transform*.

Define another variable as

```
public Transform enemyPos;

```

Now change the code for enemy instantiate

```
GameObject _clone = Instantiate(_enemy.deathParticles, enemyPos.position, Quaternion.identity) as GameObject;

```

Now drag the *spawnPoint* and *enemy* GameObjects to the *spawnPoint* and *enemyPos* variables respectively...

The error is happening because *position* and *rotation* are properties of *Transform* class not *GameObject*
> 1 votes

---
Tags: 2d, unityscript
---


title: Painel setting in canvas scene

text:
# Question
Title: Painel setting in canvas scene
This is where I am having to place my panel in canvas scene for it goes to the right place when I play it in full mode. Anyone knows how to do it correctly?

**In scene:**  **Play mode:**

# Answer
> 2 votes
It looks like you want your panel to stay docked against the left side of your screen, and enlarge to fill the vertical height.

To do that, click on the little box on the left side of your `RectTransform` inspector that currently says "Center Middle" - this lets you control the alignment of the object using Anchor Presets.

Clicking it opens a matrix of various options:

You want the one I've highlighted in yellow on the bottom left. That says "Align relative to the left edge of your parent element, and enlarge with your parent element vertically"

Unity will automatically adjust the other parameters in the `RectTransform` to preserve the panel's current appearance under the new preset, but you can modify them to nudge it around or change the amount of margin it leaves.

You can also constrain your game window to your play mode resolution/aspect so that at edit time you're working with the same framing as you'll see during play.

---
Tags: unity, gui
---


title: Box2D in 3D space

text:
# Question
Title: Box2D in 3D space
I am trying to combine a perspective camera with a box2D world using libgdx and I am having some problems getting the two to synch up. I want to do this so I can use 3D models but keep the game in a fixed plane like a 2D platformer and I will not move, angle or zoom the camera. I set the Box2D world to a fixed size, say 35x20 meters. The problem I have is calculating how much I need to move the 3D models so they synch up with the Box2D world. Lest say I move the Box2D body of a character 1 meter to the left how much should I move the 3D model then?

I tried to simply calculate pixels per meter and use that to move the 3D models. But I guess that I need to take the distance from the camera into account? So if someone have a formula or can point me in the right direction on which formula to use I would really appreciate it, thanks!

# Answer
> 1 votes
It should be pretty much the same as if you were using sprites. I would just keep it simple and say that one Box2D meter is one game unit.

# Answer
> 0 votes
The way I find the 3D units from pixels is by using ratios. If you want to find how far the 3D object's x is from the center of the screen then use a ratio like:

```
x2D = 10.0; // pixels of object from center
width2D = 60.0; // pixel width of view from center
width3D = 10.0; // 3D unit width of view from center

x3D = (x2D * width3D) / width2D

```

To find the 3D width use glFrustum()'s xLeft and zNear and find the z position from the modelview matrix like so:

```
width3D = (xLeft * z) / zNear

```

You can use the a / b = c / d ratio to solve for a lot of other graphics problems too, like scroll bars and radians to degrees.

# Answer
> 0 votes
Start with a bouncing ball on the ground. If it feels like moving slow, you have to increase your multiplier, say 10x. Multiply position in physics with 10 to calculate the display position and size of the ball, if that makes it feel better, it is the right constant. As long as your orthographic camera shows all of your sprite display, that can count as your resolution.

---
Tags: libgdx, 3d, mathematics, box2d, perspective
---


# Question
Title: How to transfer a variable from script to another in Godot
I have 3 sprites A, B and C, each one has area2d attached to it and collision shape

the script for A

```
extends Area2D
var done = 0

func _input_event(viewport, event, shape_idx):
    if event.type == InputEvent.MOUSE_BUTTON \
    and event.button_index == BUTTON_LEFT \
    and event.pressed:
        get_parent().hide()
        done = 1

```

And all like that

Now the main node has a script attached to it

```
extends Node2D

func _ready():
    if get_node("lA").get("done")==1 && get_node("B").get("done")==1 && get_node("C").get("done")==1:
            get_tree().change_scene("res://scenes/scene2.tscn")

```

But it doesn't work, why?

The error when doing `if get_node("lA").done == 1` is

`Invalid get index 'done' (on base: 'Sprite').`

What I'm trying to do is collect some items, when done, move to a new scene

# Answer
> 1 votes
According to this QA post you should be able to access your variable doing `get_node("node").variable`

If that doesn't work try using a getter method for your variable:

```
var done = 0 setget ,done_get

func done_get()
    return done

```

# Answer
> 3 votes
The reason why you get an invalid index error is that not your Sprite node holds the done variable but the Area2D node. That means you have to use:

```
if get_node("1A/Area2D").done == 1 and get_node("B/Area2D").done ...:
    get_tree().change_scene("res://scenes/scenes2.tscn")

```

If you renamed the Area2D node you must change the names accordingly.

Hope that helps.

---
Tags: godot
---


# Question
Title: How is Signed Distance Field Ray Marching implemented for a dynamic world?
I think I understand the basics of Signed Distance Field Ray Marching. You model your scene with a bunch of distance fields (such as these: http://iquilezles.org/www/articles/distfunctions/distfunctions.htm), then for each pixel you cast a ray, start from the start of the ray, find the distance to the nearest object at that point, and increment the point by the nearest distance, until you hit something. I managed to do a simple renderer, and that is where most descriptions of the technique stop.

This leaves me with some questions on how SDF Ray Marching can be used in a real world scenario:

Question 1: In a real game, the scene is usually complex and loaded on the CPU, with many dynamic objects. I understand basic occlusion culling (such as octrees), and with polygonal rendering, I would create a list (on the CPU) of items in the view frustrum to render.

So, imagine I have a very complex scene with many characters and dynamic objects moving on the screen, controlled by the CPU. How would I stream the objects I want to render to the GPU each frame? Every example has the scene hardcoded in GLSL. Can someone share an example of the level being streamed to the shader dynamically?

Question 2: How can objects have multiple colours? The distance functions only return a distance, but how do implementations commonly pass the colour back? (e.g. you hit a red sphere and not a blue cube.) If this were a CPU implementation, I could call a global function inside of the distance function when it's a hit to terminate the ray marcher, and that could also pass the hit object's texture/colour. But, how would you return the item's colour or texture in GLSL?

Thank you.

# Answer
This is a minimal answer, but wanted to share the info in case you didn't get a better answer.

Regarding how real games use ray marching, they usually don't. Only in the last couple years have games started raymarching the depth buffer to do screen space reflections, but no game I'm aware of uses ray marching in the way you describe - yet?

For the other question about colors and such, people commonly associate materials with objects and use "texture coordinates" of the point where the ray hits the object to figure out the material properties at that point on the object. Common materials include things like diffuse color, specular intensity, emissive color and transparency/refraction index.

Hope that is at least some help for you! You might also get good answers from the graphics stack exchange site.
> 2 votes

# Answer
I am currently developing a game engine that utilises signed distance fields as a rendering technique to display smooth procedural geometry (generated with simple primitives like the ones in your link for now, looking to implement Julia and IFS fractals in the future). Since my engine is focussed on procedural generation and *must* define figures in a way that makes them ray-marcher friendly, I figure I'm in a good place to answer this question :P.

Regarding streaming, the simple solution is to use a typed buffer of some sort and throw it onto the GPU when you want to do your ray-marching. Each element of the buffer is a complex type (e.g. a struct in C/C++), and each type contains elements defining what function you should use to represent it, it's position, rotation, scale, etc., and an average color. The process then simplifies down to:

1. Cull your scene into a manageable subset (note that frustum culling and occlusion culling are partly performed automatically by the ray-marching algorithm anyways)
2. Pass the subset into your render input buffer
3. Pass the buffer to the GPU if it isn't there already, then render your scene with ordinary traditional ray-marching. You will need to perform some kind of per-step search to evaluate which item in the input buffer is closest to each ray for each iteration of the ray-marcher, and you'll need to apply transforms to either the rays (in which case you'll need to invert figure rotations before they reach the GPU) or the distance functions themselves (moving the function origin for position changes, adjusting e.g. cubic side lengths for scale changes, etc.) The simplest approach is to just modify the rays before you pass them along to the actual core distance function.

Regarding figure colors, remember that shaders allow you to define complex types as well as primitives ;). That allows you to throw everything into a C-style struct, then pass those structs back from your distance function.

In my engine, each struct contains a distance, a color, and an ID that ties it to the corresponding figure definition in the input buffer. Each ID is inferred from the surrounding context of the relevant distance function (since my mapping function loops through the input buffer to find the closest figure to each ray for each step, I can safely treat the value of the loop counter when each SDF is called as the figure ID for that function), while distance values are defined using an arbitrary core SDF (e.g. `point - figure.pos` for a sphere), and colors are either defined from the average color of the appropriate element in the figure buffer (hence why it's useful to keep the figure ID's around) or through a procedural color weighted towards the stored average (one example might be taking an iteration count for some point on the Mandelbulb, mapping your "average color" from FP color space to integer color space, then using the mapped color as a palette by XOR'ing it against the iteration count).

Procedural textures are another approach, but I've never used them myself. iq has done quite a lot of research in that area and posted some interesting demonstrations on Shadertoy, so that could be one way to gather some extra information.

Regardless of whether your color is static for each figure, procedurally generated, or magically sampled from a procedural texture, the basic logic is the same: Abstract figures into some sort of intermediate complex type (e.g. a struct), store **both** local distance *and* local color in an instance of that type, then pass the complex type as a return value from your distance function. Depending on your implementation, the output color can then pass directly through to the screen, or follow the collision point into your lighting code.

I don't know if the above was clear enough or not, so don't worry about asking if anything doesn't make sense. I can't really give any GLSL/pixel-shading code samples since I'm working with HLSL and compute shading, but I'm happy to try and go over anything that I didn't write properly in the first place :).
> 2 votes

---
Tags: shaders, algorithm, glsl, voxels
---


# Question
Title: How to correctly enable anti aliasing in XNA?
In my project when I add `graphics.PreferMultiSampling = true;` this line in the Game1 Constructor (as the msdn website suggests), anti aliasing does not enable. Any idea what I might be missing ? Here is the full code:

```
public Game1() : base()
{
    graphics = new GraphicsDeviceManager(this);
    graphics.PreferredBackBufferWidth = 720;  // game's width
    graphics.PreferredBackBufferHeight = 720; // game's height
    graphics.PreferMultiSampling = true;
    Content.RootDirectory = "Content";
}

protected override void LoadContent()
{
    spriteBatch = new SpriteBatch(GraphicsDevice);
    LightningSegment = Content.Load<Texture2D>("Lightning Segment");
}

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.DarkCyan);

    Matrix skew = Matrix.Identity;
    skew.M12 = (float)Math.Tan((double)Math.PI / 6);
    spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, skew *
         Matrix.CreateScale(1.5f, 3f, 1));
    spriteBatch.Draw(LightningSegment, new Vector2(200, 200), null, Color.Red, 0,
         new Vector2(0f, 300f / 2f), new Vector2(250f, 1f), SpriteEffects.None, 0f);
    spriteBatch.End();

    base.Draw(gameTime);
}

```

# Answer
First of all your hardware has to support MultiSampling. You can check this with the below property.

```
GraphicsAdapter.CheckDeviceMultiSampleType

```

In addition to enabling it for the back buffer

```
graphics.PreferMultiSampling = true;

```

You can create a new `RasterizerState` that has the field `MultiSampleAntiAlias` set to true and pas this into SpriteBatch.Begin.

Creating the needed RasterizerState.

```
RasterizerState = new RasterizerState { MultiSampleAntiAlias = true };

```

If you want the default state pass in null.

```
SpriteBatch.Begin(
    SpriteSortMode.Immediate,
    null,
    null,
    null,
    RasterizerState);

```

The above can cause changes to the graphics card's state even after SpriteBatch.End is called. Use the below if you want to revert the state back to the defualt.

```
GraphicsDevice.BlendState = BlendState.Opaque;
GraphicsDevice.DepthStencilState = DepthStencilState.Default;
GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;

```
> 3 votes

# Answer
If anyone here is using MonoGame instead of XNA, the process is ever so slightly different. Notice that we change the graphics profile to `HiDef`. This allows more advanced shader features (like AA) to be enabled (as some are disabled when the default `Reach` profile is enabled).

```
protected override void Initialize()
{
    _graphics.GraphicsProfile = GraphicsProfile.HiDef;
    _graphics.PreferMultiSampling = true;
    GraphicsDevice.PresentationParameters.MultiSampleCount = 8;
    _graphics.ApplyChanges();

    // your stuff here
}

```

The MultiSampleCount can be either 2, 4, 8, 16, or 32. I would only go up to 8 maximum though since not all computers support higher than that. 4 is the safest bet.

This should work on both the DX and GL versions.

If you'd like to know how to do this with RenderTargets, have a look at this useful post by Kosmonaut Games.
> 5 votes

# Answer
Well, since you asked for "properly" I would recommend shader based AA, but it depends on specific project. Look for FXAA if you want cheap AA, or there is SMAA for XNA somewhere around (although not as effective as its common implementation due to XNA stencil limitations).
> 0 votes

---
Tags: xna, c#, monogame, antialiasing
---


title: Anti-Aliasing Issues in MonoGame

text:
# Question
Title: Anti-Aliasing Issues in MonoGame
My anti-aliasing is not working in MonoGame. I'm not sure if I'm doing something wrong. See the image below (rotating the screen -- coordinates are all overlapping/adjacent, so should blend them):

https://i.stack.imgur.com/lcd2G.jpg

On the ctor of my Game, I have the following:

```
        Graphics = new GraphicsDeviceManager( this )
        {
            PreferredBackBufferHeight = 720,
            PreferredBackBufferWidth = 1280,
            PreferMultiSampling = true
        };

        Graphics.ApplyChanges();

```

Which, should enable Anti-Aliasing. Further, I have:

```
                GraphicsDevice.RasterizerState = new RasterizerState()
                {
                    CullMode = CullMode.None,
                    MultiSampleAntiAlias = true,
                };
                TileMeshEffect.CurrentTechnique.Passes[0].Apply();
                GraphicsDevice.SetVertexBuffer( TileMeshVertexBuffers[Coordinate] );
                GraphicsDevice.DrawPrimitives( PrimitiveType.TriangleList, 0, TileMeshVertexBuffers[Coordinate].VertexCount / 3 );

```

Right as I'm rendering the Mesh, which should, I would think, do everything necessary. I was able to confirm via debugger that both are set, and that furthermore, the number of passes was 4 (GraphicsDevice.PresentationParameters.MultiSampleCount).

Any clue what I'm doing wrong?

# Answer
### Solution

Try and add these lines just before `Graphics.ApplyChanges();`:

```
Graphics.GraphicsProfile = GraphicsProfile.HiDef;
GraphicsDevice.PresentationParameters.MultiSampleCount = 8;

```

You can, of course, change 8 to whatever level of AA you want. The available options are 2, 4, 8, 16, and 32. I would only use up to 8 as an absolute max though. 4 is the safest bet.

### Explanation

To increase compatibility, MonoGame sets the graphics profile to `Reach` by default. This disables certain features (like MSAA) in order to target a wider range of devices.

You can change this profile to `HiDef` to get MSAA but your project may not run properly on mobiles or consoles, but if you're only targeting Windows then that's not a problem!
> 2 votes

---
Tags: xna, monogame, antialiasing
---


title: How to detect matches in match-3 game?

text:
# Question
Title: How to detect matches in match-3 game?
I am working on a match 3 game where the number of matched cells matters

> (if you match 3 then they just get removed, if you match exactly 4 then something happens, and if you match more than 4 then something else happens)

Basically this image sums it up :

cells in the green frame should match and disappear, the ones in the red shouldn't. Could anyone please help me out, am kinda stacked on how to tackle this. Thank you

**Edit** Thank you all for your help! flood-fill was the right thing to do, i made a good progress and faced a different problem, please check the new thread

# Answer
> 1 votes
I'm guessing you set the cells using an array.

You could define variables as array. Evey time you place a figure, save it's coordinates on a variable and ask if any neighboring cell (on a X or Y axis) has a figure too, if it does, save those too and repeat until there are three or more matches.

You can use a loop that works as long as there are neighboring cells.

If there are more than three matches, then delete the cells on the already saved coordinates.

# Answer
> 1 votes
In your case, matching symbols dissappear with 3 or more, right? And the chained amount only changes one tile at a time (except when matches get erased)?

If you only got one symbol, you only need one matrix of int. Every entry of that matrix is zero. Whenever a field is changed and not erased, do the following:

1. add the numbers of every adjacent cell + 1 to the selected cell **C** (up, down, left and right)
2. Now do for every adjacent cell the following:

* for 0, do nothing
    * for a 1, change that cell to the content of **C**
    * for a 2, change that cell to the content of **C** and do the same for every adjacent cell (one cell adjacent should be a 1)
3. Check the content of **C**. If it's greater than two, check for a possible bonus and set every cell greater than 2 to 0 ( to delete the matching cells)

This works because of your two cell matching doesn't do anything and for more than one symbol, you need at least one more matrix for every symbol. Preferably symbol number + 1 matrix that keeps track, what symbol is in what cell (0 is empty cell, 1 is symbol a, 2 is symbol b and so on).

---
Tags: algorithm, puzzle
---


# Question
Title: How can I hide the collision layer in libGDX with TiledMap?
I'm making a 2D game with libGDX, and I'm using its TileMapRenderer to render my map which I have made in the map editor Tiled. In Tiled, I have a dedicated collision layer. However, I can't figure out how I'm supposed to hide it and its tiles in the game.

This is how a map is loaded:

```
TiledMap map = TiledLoader.createMap(Gdx.files.internal("maps/map.tmx"));
TileAtlas atlas = new TileAtlas(map, Gdx.files.internal("maps"));
tileMapRenderer = new TileMapRenderer(map, atlas, 32, 32);

```

Currently the collision tiles are rendered on top of everything else, as I see them in the map editor.

# Answer
At this time, you'd have to create an int array of the layer indexes you do want to draw, and then use the `render` method which takes a camera and the layer indexes.

So, if you have three layers and the last one is the collision layer you do not wish to draw, you'd do:

```
int[] layers = new int[] {0, 1}; // preferably outside of the render loop, to avoid gc

```

then when you wish to render:

```
tileMapRenderer.render(camera, layers);

```

This is certainly less than ideal as the layer itself should have a visibility flag (as it does in tiled) which would be used to determine if the layer should be drawn as opposed to relying on whether or not the index is passed in to the render function.

I've been working on a new version of the Tiled module in LibGDX which hopefully will make it easier to work with.
> 6 votes

# Answer
Easiest way is to set the visibility to false tiledMap.getLayers().get(index).setVisible(visible);

EDIT: Reference to the libGDX API http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/maps/MapLayer.html#setVisible-boolean-
> 1 votes

# Answer
In Lua, I set the opacity to zero or the named layer, like:

```
if map.layers["collision"] then
   map.layers["collision"].opacity = 0
end

```

You need to search in libgdx how to get a layer by name, and then set its opacity.
> 0 votes

# Answer
You can also try hiding your collision layer by using this

```
TiledLayer collision;
// [...]

// search the collision layer
for(int i=0;i<map .layers.size();i++){
    if(map.layers.get(i).name.equals("collision")){
        collision=map.layers.get(i);
        map.layers.remove(i); // remove the collision layer.
        break;
    }
}

```
> 0 votes

# Answer
The easiest way to do this it to simply not hide them at all. You should create a set of blank tiles on your PNG tile sheet. Use the blank tiles to create your collision layer and render it. Since all the tiles you use are transparent in nature, the image it writes is nothing.
> 0 votes

# Answer
If, when in the Tiled IDE, you click the eye in the layers tab.

It will deselect the layer as being visible both inside the IDE and when used in a game engine.

All the layer data is still there and can be used for collision.
> 0 votes

---
Tags: libgdx, tiled
---