# Question
Title: What does mean the float value in a voxel data?
We know that a voxel can be represented by a three dimensional array of boolean or float values. There is an answer that demonstrates this perfectly: the difference between binary/boolean or floating-point voxel.

If we use the binary way, we probably use a byte\[,,\], so we have 256 slots. They can be used to represent the content. For example, 0 can be air, 1 grass, 2 stone, 3 water.

By this way, we can define what is solid or not and which colour where.

But what about the floating-point way? So my question: **What does the float value mean in a floating-point voxel context? Is there a way to use it as the binary way to describe the content and keep the terrain smooth?**.

## What I've experimented & What I get it?

I've tried to build a mesh with Marching Cube, filled with "random" 3d fractal from Perlin Noise. The result looks very good, but now how I am supposed to define what is what? (Air, Stone, ...)

I am pretty sure the solution was already answered in this answer. Unfortunately, even if I read the answer 5-6 times, I don't get it.

I understand there is a threshold which defines what is solid or not.

Giving me 3 for-loop pseudo code to fill with floating-point the three dimensional array would probably be helpful.

# Answer
You are actually confusing a few values.. Basically a Voxel is just a point in space followed by how 'full' that space is. If you are using a boolean system then its either full or empty. Minecraft is a common example of this, though the data has started becoming more complicated, they used an integer value of 0 to mean the space was completely empty while a number greater than 0 meant it was full as well as being the material id used to render that block.

For float values in a voxel situation its still generally tracking the same data, just how much of the voxel is 'solid'. This value would then be used in conjunction with the ones around it to translate it from voxel data to mesh data for rendering. For example say we have a voxel that has a value of 0.5 (I am going to assume 0.0 is empty and 1.0 is a completely full location). This would give us a block (if you are rendering cubes) that would be half full. Now when you use this value in association with the other values around it you would get a slope up or down to each location around it depending on if their value is higher or lower.

Note however that I have said nothing about what type of material or texture this block uses. If you are using floats you generally are going to be looking for slopped and smooth meshes to come out of them and another value, maybe an integer still, that actually links to the texture information. The down side to voxels is they take up a lot of space and their translation can be taxing on a computer when they are changed and need to regenerate the mesh. Games like Minecraft, Terraria, and I presume (though have never seen their code) Trove and Creativerse take a shortcut and put both the density and material values into the same data slot to preserve space and lookup times, when you find a block that isn't empty you already have the material Id for example.

Hope this clears up what you were looking for.
> 0 votes

# Answer
Marching Cube is a so called isosurface extraction algorithm.

That is (in this case) an algorithm which creates a 3D mesh based on where the voxel values change from *positive* to *negative*, i.e. where they are 0.

The floating point values are exactly that, they're used by marching cubes to determine where to place the mesh. Marching cubes has no concept of material types, it only cares about whether or not something is at the sample points.

What you want to do is one of two things:

If you want every triangle to be of only *one* material, loop through the triangles created and:

* Calculate the voxel positions of each vertex (i.e. round their positions assuming no scaling)
* Retrieve what material each vertex is made of, you know what voxel they are in, those voxels also have a material that marching cubes doesn't know about.
* Set the triangle's material to the material most often encountered (with some edge cases where three materials meet)

If you want the triangles to smoothly interpolate between materials you're gonna need to do pretty much the same thing but set different data for each vertex in some complicated method depending on how you are rendering things.
> 0 votes

---
Tags: voxels, perlin-noise, marching-cubes
---


title: Animation position leftover

text:
# Question
Title: Animation position leftover
I am fairly new to unity and I have encountered this same problem previously.

I have a gun with hands and I created an animation that simulates shot movements with properties `transform.position` and `transform.rotation`. Root motion is applied and motion curves are generated for the animation.The default state animation for that object has no properties assigned to it and as much as I understand from the animation controller window, the shot animation is completed before the transition to the default state is made.

The problem is that on every 3 shots 0.001 is added to the X rotation; Y and Z positions are losing some small values.

I tried to prolong the animations exit time but the result is the same. I checked the key values and the motion curves, the first and last ones are the same. Why is this happening and how can I fix it ?

# Answer
> 0 votes
If you're using `Update()`, `DeltaTime`, and/or `floats` to do your calculations, it's likely that very small discrepancies are starting to crop up. Try using `FixedUpdate`, not using `DeltaTime`, and try using `ints`, see what happens.

---
Tags: unity, animation
---


# Question
Title: How to unload/remove body components in Box2D?
I want to know how to release/clear/remove a variable. (specifically b2BodyDef, b2Body, b2FixtureDef, b2PolygonShape types.)

I've heard there's a keyword called `delete`, guessing by it's name it may have something to do with this subject?

---

I'm totally new to these things and I've just heard that there's a way to do this.

I might be wrong and there isn't a way to do this at all.

Which also means that I have no idea if I should include code or what information I should include at all :P

# Answer
> 1 votes
i dont know if its the same for c++ but in java its

```
world.destroyBody(body);

```

and after in java we do `body = null;`
in c++ do like this : http://www.cplusplus.com/reference/cstdlib/free/ to free all memory that we dont need anymore.

# Answer
> 1 votes
When allocating memory for an object in C++ using `new`, you must later deallocate it with `delete` or you will likely have a memory leak. In C, `malloc` corresponds with `free`.

When it comes to Box2D, `world.CreateBody` and `world.DestroyBody` handle `b2Body` creation and clean up for you. Additionally, you do not need to allocate the `b2BodyDef`, `b2FixtureDef`, and `b2PolygonShape` objects on the heap using `new`. Instead, create them on the stack like so:

```
b2BodyDef bodyDef;
bodyDef.position.Set(center.x + size/2, center.y + size/2);

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

b2PolygonShape box;
box.SetAsBox(size / 2, size / 2.0f);

b2FixtureDef fixtureDef;
fixtureDef.shape = &box;
fixtureDef.friction = 0.3f;

body->CreateFixture(&fixtureDef);

```

Notice that no usage of `new` is necessary.

Finally, be careful when using `SetUserData` to store pointers to your own custom data in `b2Body` and `b2Fixture` using `new`. You must iterate over the body's fixtures and call `delete` on any user data that you stored in there.

You can learn more about the C++ stack vs. heap here: https://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap

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


# Question
Title: Python collision left works, but not right
I am continuing to work on collision detection. It appears for the most part, everything I have implemented is working. When the game starts, the character is on the left side of the screen (plus a few pixels). If I hold down the left key so he is pushed against the wall, he doesn't go anywhere like is supposed to happen.

However, when I move the character to the right up to the first ledge something weird happens:

At first, he doesn't go through the ledge like he's supposed to:

But then, after holding down the right key for a while, he starts to creep into the ledge:

If I hold down the right key long enough, he ends up inside the ledge completely:

(can't post another pic, because I don't have enough rep)

There is no rhyme or reason as to how long it takes for him to creep forward. It seems to happen at random intervals.

Any clues as to what is happening? The weirdest thing to me is that it only happens when he is colliding with the left side of a "wall" and not the right side. I held down the left key on the left side of the map (the beginning) for quite a while and nothing happened, again like is supposed to happen.

Relevant code:

```
def col_ground(self, sprite, wall):
    return self.walls[wall].collidepoint(sprite.feet.midbottom)

def col_left(self, sprite, wall):
    return self.walls[wall].collidepoint(sprite.feet.midleft)

def col_right(self, sprite, wall):
    return self.walls[wall].collidepoint(sprite.feet.midright)

def update(self, dt):
    """ Tasks that occur over time should be handled here
    """
    self.group.update(dt)
    # sprite must have a rect called feet, and move_back method,
    # otherwise this will fail

    # TODO: this could probably be modified to handle anytime
    # the sprite is just on the ground or hitting a corner instead
    # of having seprate instances of where the sprite hits the right
    # or left side of a wall
    for sprite in self.group.sprites():
        wall_collide = sprite.feet.collidelist(self.walls)
        walls = sprite.feet.collidelistall(self.walls)

        if wall_collide > -1:
            # if the sprite hits the ground
            if self.col_ground(sprite, wall_collide):
                self.hero.jumping = False
                sprite.move_back_y(dt)
            # if the sprite's right side hits a wall
            if self.col_left(sprite, wall_collide):
                sprite.move_back_x(dt)
            # if the sprite's left side hits a wall
            if self.col_right(sprite, wall_collide):
                sprite.move_back_x(dt)
            # if the sprite is in a corner
            if len(walls) == 2:
                # if in a corner, keep him from going up or down (x, y)
                if not self.walls[walls[1]].collidepoint(sprite.feet.topleft) and \
                not self.walls[walls[0]].collidepoint(sprite.feet.topleft):
                    sprite.move_back_x(dt)
                if not self.walls[walls[0]].collidepoint(sprite.feet.topright) and \
                not self.walls[walls[1]].collidepoint(sprite.feet.topright):
                    sprite.move_back(dt)

```

If you need any more code snippets or explanation, please let me know.

Edit (movement functions):

```
def move_back_x(self, dt):
    """ If called after an update, the sprite can move back
    in the x
    """
    self._position[0] = self._old_position[0]
    self.rect.topleft = self._position
    self.feet.midbottom = self.rect.midbottom

def move_back_y(self, dt):
    """ If called after an update, the sprite can move back
    in the y direction
    """
    self._position[1] = self._old_position[1]
    self.rect.topleft = self._position
    self.feet.midbottom = self.rect.midbottom

def move_back(self, dt):
    """ If called after an update, the sprite can move back
    """
    self._position = self._old_position
    self.rect.topleft = self._position
    self.feet.midbottom = self.rect.midbottom

```

# Answer
A good way to handle this is to use a separate variable for your position - one which can be a float. Do your calculations on this variable, and then just use that to set your rect position each frame.

For example:

```
def update(self, dt):
    posx += self.vel * dt
    # collision code here, adjust posx
    self.rect.x = posx

```
> 0 votes

---
Tags: collision-detection, python, pygame
---


# Question
Title: How to interact with object in HTC-vive Unity
I just start to learn HTC vive app development with unity and want to interact with Object and want to get it as controller interact with it. Try to learning form StreamVR Unity Toolkit documentation. I found a scene in sample demo where Gameobject are interacting through controller but there are so many scripts involved. I am amazed that on a cube VRTK\_InteractalbeObject is attached and it is responding to controller. how can i get interacted object in htc vive.?

# Answer
NewtonVR (github) is what I have used to make objects interactable. You can pick items up, throw them, push other objects with the objects you're holding and in general it behaves realistically. You can see animations of what it can do here.

Using it is very simple:

> To integrate NewtonVR into a project you can use our included player prefab in NewtonVR\NVRCameraRig. This is a copy of the steamvr camerarig prefab with the newtonvr scripts added. Specifically, there's a NVRPlayer component on the root, a NVRHead component on the head, and NVRHand components on both hands. Alternatively, you can just add those components to your player. Take note though, if you're not using the standard controllers in your project then the physical hand option will not work correctly.
>
> When you've got an item you'd like to pick up, simply drop a NVRInteractableItem component on it. You'll need to give it a Rigidbody (and ideally set the mass) if you haven't already. If the item has a specific point that you'd like to pick it up at you can create a new GameObject, parent it to your item, and position it in the location and at the rotation that you'd like the controller to be. Then set NVRInteractableItem.InteractionPoint to that new gameobject.
> 0 votes

---
Tags: unity, c#, virtual-reality, htc-vive
---


# Question
Title: Lengthen Line (bidirectional) - crossing zero line
I'm trying to lengthen a line, by a certain amount. I want to apply the modification to both points on the line, expanding it in both directions. without moving it from it's current position (center point expansion would be acceptable, but I'n not sure how to apply it).

**Exact details:**

***Line:***

Point 1 \[X = 1 , Y = 4\], Point 2 \[X = -1, Y = 6\]

***Line Normalized Vector:*** V = \[X = -0.707106, Y = 0.707106\]

***Expand by:*** E = 1

So the result I'm looking for is

New Line = \[ 1.707 , 4.707 \] ~ \[ -1.707 , 6.707 \]

My problem happens when I multiply Point2\[X\] + ((0-V\[x\])\*E) = - 0.292

Can someone give a SIMPLE example. Psudo code, is great!

I know it is because I'm crossing the zero line, but I'm sure there's a better way to do this than testing if the point is greater than zero or less than zero.

# Answer
```
StartX, StartY <---> EndX, EndY
Normalised = -0.707, 0.707
Inverse Normalised = 0.707, -0.707

Extend in both directions by E
NewStartX = StartX + (E * InvNormX)
NewStartY = StartY + (E * InvNormY)

NewEndX = EndX + (E * NormX)
NewEndY = EndY + (E * NormY)

```

ie, using your numbers above it would be

```
NewStartX = 1 + (E * InvNormX) = 1 + (1 * 0.707) = 1.707
NewStartY = 4 + (E * InvNormY) = 4 + (1 * -0.707) = 3.293

NewEndX = -1 + (E * NormX) = -1 + (1 * -0.707) = -1.707
NewEndY = 6 + (E * NormY) = 6 + (1 * 0.707) = 6.707

```
> 1 votes

---
Tags: vector, geometry, normals, computational-geometry
---


# Question
Title: Zobrist Hashing equivalent for Simple Knights Game with only 1 unique piece
I looked over the Zobrist hashing function used for getting a unique hash id of the board state in a chess game. https://en.wikipedia.org/wiki/Zobrist\_hashing

Martin Fierz explains it very well in his post:

> Assume you have a board with S squares and P different types of pieces. You allocate an array:
>
> ```
> int zobristnumbers[S][2*P];
>
> ```
>
> and fill it with random numbers. The hash number is now calculated as an **XOR** over the occupied squares of the entire board:
>
> ```
> key = 0;
> for(i=0; i<S; i++) {    if(board[i] != EMPTY)
>   key ^= zobristnumbers[i][piece[i]];
> }
>
> ```

Now this works very well for chess because you have 6 unique pieces and 64 squares - so the probability of getting a clash in the keys is very small.

I am trying to find a variant of this hashing function or another one, which would work smoothly in a more simple zero-sum game called Knights: 49 squares, and only one kind of piece - a knight from chess - which moves exactly like a knight in chess.

I want to use it as a transposition table key, for storing best moves and game states.

Any ideas or hints of how could this be achieved?

Thanks!

# Answer
Zobrist hashing is also used for the game Go. Since you basically have the same situation - each cell can only have 3 different states (black piece, white piece or empty), I wouldn't bother changing the standard algorithm other than modifying it for your board size.
> 2 votes

---
Tags: mathematics, algorithm
---


# Question
Title: Having issue having AI move after changing directions
I've frankenstein'd together an AI script for the enemy to chase the player once the player enters the AI's collider. If the player's X is lower than the enemy's X aka he's on his left the enemy turns and should start chasing the player again. My debug log fires saying the enemy should be chasing left and the enemy turns, but he does not chase the player.

Can someone take a look and see if the solution to the issue I'm having is apparent? I'm assuimg it has something to do with my leftward movement but im not experienced enough to know what it is, when I enter the values in different ways I can get the enemy to move left however so I'm not sure what exactly is wrong.

```
using UnityEngine;
using System.Collections;

public class EnemyMovement : MonoBehaviour
{

    public float movementspeed;
    public Transform player;
    Renderer enemyRenderer;
    bool engage = false;
    public GameObject enemySprite;
    public bool spriteFacingRight = true;
    Rigidbody2D rigid;

    //Animator enemyAnimator;

    void Start()
    {
        enemyRenderer = GetComponent<Renderer>();
        rigid = GetComponent<Rigidbody2D>();
        //enemyAnimator = GetComponent<Animator>();
    }

    void FixedUpdate()
    {
        if (engage == true)
        {

            if (spriteFacingRight && rigid.transform.position.x < player.position.x)
            {

                chargePlayer();

            }

            if (spriteFacingRight && rigid.transform.position.x > player.position.x)
            {

                turnFacing();
                chargePlayer();

            }
        }
    }

    void OnTriggerEnter2D(Collider2D col)
    {
        if (col.tag == "Player")
        {
            engage = true;
            Debug.Log("player engaged");
        }
    }

    void turnFacing()
    {
        float facingX = enemySprite.transform.localScale.x;
        facingX *= -1f;
        enemySprite.transform.localScale = new Vector3(facingX, enemySprite.transform.localScale.y, enemySprite.transform.localScale.z);
        spriteFacingRight = !spriteFacingRight;
        Debug.Log("facing player");
    }

    void chargePlayer()
    {
        if (!spriteFacingRight)
        {
            rigid.AddForce(new Vector2(-1, 0) * movementspeed);
            Debug.Log("chasing left");
        }

        if (spriteFacingRight)
        {
            rigid.AddForce(new Vector2(1, 0) * movementspeed);
            Debug.Log("chasing right");
        }
        //enemyAnimator.SetBool("isCharging", charging);
        Debug.Log("charging player");
    }
}

```

# Answer
The sprite was no longer facing right so the `if` condition was no longer true. Replacing the body of the `if(engage == true)` code with the snippet below is the result of what I was trying to accomplish.

```
if (spriteFacingRight && rigid.transform.position.x < player.position.x)
    chargePlayer();

if (spriteFacingRight && rigid.transform.position.x > player.position.x)
    turnFacing();

if (!spriteFacingRight && rigid.transform.position.x < player.position.x)
    turnFacing();

if (!spriteFacingRight && rigid.transform.position.x > player.position.x)
    chargePlayer();

```

---

We can also simplify this logic using the Exclusive OR operator:

```
bool isFacingPlayer = (rigid.transform.position.x > player.position.x) ^ spriteFacingRight;

if(isFacingPlayer == false)
    turnFacing();

chargePlayer();

```

To see why this works, we can construct the truth table for the `isFacingPlayer` variable:

```
         XOR                 spriteFacingRight == true     spriteFacingRight == false
(this x > player x) == true            false                         true
(this x > player x) == false           true                         false

```

See how `isFacingPlayer` is false only when we need to turn to face the player. :)
> 0 votes

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


title: Parametric form of a cubic function

text:
# Question
Title: Parametric form of a cubic function
After researching about curves in computer graphics (splines in my case), I have come across something I did not know: Explicit functions like: \\$y=x^2+2\\$ are not the best way to interpolate between points because you could get 2 or more values for y for the same x. So, parametric functions seem much better for this if we make the commonly used t parameter, the distance from origin, time, etc...

After studying a bit how to convert from explicit to parametric form I have been shocked when I have found in some texts they use these parametric cubic functions to interpolate through points: $$\begin{align} x(t)&=at^3 + bt^2 + ct +d \\ y(t)&=2at^3 + 2bt^2 + 2ct +2d \end{align} $$ but wait... this is the exact same form the explicit function was: $$ y(x)= ax^3 + bx^2 + cx + d $$ From what I have seen for other example functions in some math books the parametric funcions where not the same form that its explicit form counterpart.

Am I missing something?

Examples of the texts I'm refering to could be:

https://www.cs.helsinki.fi/group/goa/mallinnus/curves/curves.html

http://escience.anu.edu.au/lecture/cg/Spline/parametricCubicCurves.en.html

# Answer
It's trivial to make a parametric equation that has the same form as the explicit function.

Take for example: $$ y = x^2 $$ Here \\$y\\$ is a quadratic polynomial in \\$x\\$. We can use \\$t = x\\$ as our parameter to get: $$ p(t) = ( t, t^2 ) $$ Where \\$p\_x\\$ and \\$p\_y\\$ are quadratic polynomials in \\$t\\$. (Okay, \\$x\\$ is linear polynomial, which is only a degenerate quadratic, but the salient point is that it's a polynomial of order at most 2)

This is not guaranteed though. Let's use the alternate parameter \\$u = t^{1/3}\\$ $$ q(u) = (u^3, u^6) $$ This describes the same parabola, but now it's using third & sixth-order polynomials instead of second-order.

So the choice of parameter can wildly affect the form of the parametrized equation. (Some natural choices of parameter, like arc length, often have no closed-form equation at all!)

We can also attack this in reverse. Take for example this parametric equation: $$ f(t) = (t^2, t^2 + t) $$ Here both components \\$f\_x\\$ and \\$f\_y\\$ are quadratic polynomials in \\$t\\$, but \\$y\\$ can't be expressed as a quadratic polynomial in \\$x\\$. (The closest would be \\$y = x ± \sqrt x\\$ which isn't even a single-valued function)

So, it's not a rule that the parametric equation *must* **or** *must not* have the same form as the explicit version of the equation (and neither is guaranteed to even exist as a closed form expression). Some parametrizations will have a similar form and some won't, depending on the choice of function and parameter.
> 1 votes

# Answer
The first example you are parametric equations: $$\begin{align} x(t)&=at^3 + bt^2 + ct +d \\ y(t)&=2at^3 + 2bt^2 + 2ct +2d \end{align}$$ In the parametric equations, x & y are found independently of each other; this independence is what makes them parametric. In contrast, your second equation: $$ y(x)= ax^3 + bx^2 + cx + d $$ defines y as a function of x. Since y depends on x, the second equation is not parametric. Your examples have both been expressed as polynomials, but they are not the same.
> 0 votes

---
Tags: mathematics, interpolation, splines
---


# Question
Title: How to make objects collisions act differently
I am making an arkanoid type game and have it mostly working. I can destroy the bricks when hit by the ball, but I am adding a twist. I want to have a object on top of the bricks that will interact with the bricks but not destroy them. It needs to still be affected by gravity and collisions because when you collect them all you win the game(you collect them by getting rid of the bricks below them. Everything is pretty much working except for when this object collides with the bricks it triggers the destroy function within the brick script. I am using C# and unity 4.6.9. Thanks in advance! I can give pictures and scripts if people want, IDK what would be exactly relevant here though because I'm not sure if this is something done in unity, in the brick script, or in the falling object script.

# Answer
> 1 votes
There are two ways to attack this.

**1) The *ball* breaks bricks**

Create a "Breaker" component and attach it to your ball. This component's `OnCollisionEnter` method should check if the other collider is a brick (depending on your style, you can do this by checking whether it's in the "bricks" physics layer, or has the tag "brick", or has a "Breakable" component attached, etc) and if it is, destroy it.

(Or, ask that object's "Breakable" component to `TakeDamage()` or `Shatter()` \- which might involve playing some VFX & sound specific to each kind of brick)

Something like...

```
public class Breaker : MonoBehaviour {

    // Tune this if you want a "superball" that breaks bricks faster...
    public int damagePerHit = 1;

    void OnCollisionEnter(Collision collision) {
        // Request a Breakable component from the thing we collided with.
        var breakable = collision.gameObject.GetComponent<Breakable>();

        // If it gave us a Breakable component, deal damage to it.
        if(breakable != null)
           breakable.TakeDamage(damagePerHit);
    }
}

public class Breakable : MonoBehaviour {

    // Tune this to adjust how many hits each brick type takes to break.
    public int hitsRemaining = 3;

    public GameObject breakFX;

    public void TakeDamage(int damageAmount) {
        // Apply damage to our hit counter.
        hitsRemaining -= damageAmount;

        // Add code here if you want the brick to show a damaged state,
        // like changing colours or becoming cracked.

        // If we have no hits remaining, break this brick.
        if(hitsRemaining <= 0)
            Shatter();
    }

    public void Shatter() {
        // Here we do whatever the brick needs to do when broken.
        // Spawn VFX, sound, shake the screen, increment score, etc.
        // We can also farm this out to other components if we want lots of
        // different brick behaviours (eg. explosive bricks, money bricks...)
        var fx = (GameObject)Instantiate(
                               breakFX,
                               transform.position,
                               breakFX.transform.rotation);

        // Now we'll destroy ourselves as requested.
        Destroy(this.gameObject);
    }
}

```

Don't put this `Breaker` component on the new objects you're adding on top of the bricks, and now they won't break the bricks, because there's nothing to trigger the break action. That capability lives solely on the ball object.

I prefer this method because it puts the onus for triggering the action on the object that, from a player perspective, visibly causes the action. That makes it intuitive for me & other team members to know where to look if we want to tweak the trigger conditions (say, changing the damage done on each hit, or only dealing damage on collisions above a certain velocity, or only when the ball is in a "supercharged" state, or...)

**2) Bricks are broken *by the ball***

As an alternative, you can invert this logic. Have a `Breakable` component on each brick that, `OnCollisionEnter`, checks whether the object that collided with it was a ball (as before, using layers, tags, or a component check), and if so it destroys itself.

Personally, I don't like this second style as much, because if I add a new type of thing that should break bricks (say, I introduce shrapnel objects spawned by hitting explosive bricks), then I need to go back and edit the brick's script to make it aware of this new thing.

I'd prefer to keep such changes centralized to the new content I'm adding. ie. putting a `Breaker` component on the shrapnel object: then the existing brick-breaking behaviour will be triggered by the shrapnel without needing to update each breakable thing. This keeps the code less coupled and easier to iterate on, especially for level designers on the team who can add/remove components and change inspector parameters but aren't necessarily accustomed to making code changes.

See this question for more exploration of these two styles.

Last note: remember to change this to **OnCollisionEnter2D** etc if you're using 2D physics!

---
Tags: unity, c#, collision-detection, scripting
---


title: Unity Class Inheritance Problems

text:
# Question
Title: Unity Class Inheritance Problems
Hi I am trying to create a game where there are different types of zombies. I decided to create a base class for the zombies that includes methods for moving and flipping characters and then I have individual classes for each type of zombie where I will modify things like health and damage.

I made it so the zombie prefab I put in the game has a script that inherits from the Zombie class but when I run the game nothing in the Zombie.cs script is run.

Anyway, here are my classes:

Zombie.cs

```
public class Zombie : MonoBehaviour {

    //zombie goes after this target
    Transform targetPlayer;

    //Zombie Rigid Body
    Rigidbody2D zombieRB;

    //The speed the zombie will move
    public float moveSpeed;

    //Used for flipping zombie based on which way it is going
    bool facingRight = true;

    // Use this for initialization
    void Start () {

        zombieRB = GetComponent <Rigidbody2D> ();

        //This finds the player object to follow it
        targetPlayer = GameObject.FindGameObjectWithTag ("Player").transform;
    }

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

        //Checks zombies position in comparison to player to see where it should move.
        if (transform.position.x < targetPlayer.position.x) {
            //zombie to the left of target go right

            if (!facingRight) { //Check if needs flipping
                flipZombie ();
            }

            zombieRB.velocity = new Vector2 (moveSpeed, zombieRB.velocity.y);

        } else {
            //zombie to the right of target go left

            if (facingRight) { //Check if needs flipping
                flipZombie ();
            }

            zombieRB.velocity = new Vector2 (moveSpeed * -1, zombieRB.velocity.y);
        }

    }

    /// <summary>
    /// Flips the zombie when moving
    /// </summary>
    void flipZombie() {
        facingRight = !facingRight;
        Vector3 theScale = transform.localScale;
        theScale.x *= -1;
        transform.localScale = theScale;
    }
}

```

And then I have a pulserZombie.cs but there is nothing in it but the inheritance:

```
public class pulserMovement : Zombie {

```

Here is my image of the prefab I have:

# Answer
By not specifically setting your methods as `public`, your methods are set to `private`. They should be set to `protected`.

When we inherit, we lose access to all private methods and variables. We use `protected` to say "this is still private from the outside, but it is still accessible through inheritancy".

Note that if you intend to add any extra functionality to a method in your child class, you will also need to set it as `virtual`, with the child class referencing it as `override`. You can than write a new method, using `base.methodName` to call the base version of the method, if needed.

```
virtual protected void Update() {...}

override protected void Update()
{
 ...

 base.Update();
}

```
> 2 votes

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


title: How to achieve partial pathfinding?

text:
# Question
Title: How to achieve partial pathfinding?
Let's say I already have an A\* algorithm.

How can I handle the cases when the goal cannot be reached, and still attempt to get there?

For instance on the following example:

*Notice the amazing GIMP skills!*

The yellow unit needs to reach the green spot, but it's on island and can't actually reach it.

Yet, on a typical RTS, the unit will try to go as close as possible.

My problem is that I don't know how to tell A\* that the closest tile to the goal is the square near the sea.

How can I have this partial pathfinding? Is A\* still a good choice?

# Answer
> 3 votes
In theory, you dont need to modify anything. Just remember the closest point you ever been to. The A\* will attempt to find the path and will fail for you example, but that doesnt mean it will not first establish the path you drawn, you only have to remember path to the closest point the A\* ever been to.

# Answer
> 0 votes
Using A\* alone (and going to the closest searched point) is ok for small maps, but it will perform badly if the map is larger. If the target is unreachable, A\* will search the entire reachable space before figuring out that the target is unreachable. This may involve lots of search points, and can be very slow. In this situation, A\* has no advantage over algorithms like Dijkstra.

For a more efficient solution, you need three parts:

* Find all the groups of mutually-unreachable regions
* Find the closest reachable position
* Pathfind to this position

The first step can be pre-calculated so you can cheaply find whether your destination is reachable. Flood-fill (a.k.a. BFS) will suffice.

The second will typically be Dijkstra or a similar looking algorithm. You can even pre-calculate it (for each unreachable position, search for the closest reachable position and save it before the game starts).

You can then use A\* for the third step.

---
Tags: path-finding
---


# Question
Title: In Libgdx sprite displaced from their bodies position just after colliding with another body
In my game i have a ball falling from above and a rectangle below. when my rectangle collide with ball,sprite position displaced from body automatically,i could not understand this. and i also tried moving Dynamic body using linear velocity it works fine but give problem after collision. here are picture before colliding and after colliding

and my code is

```
  public class Ball extends ApplicationAdapter implements InputProcessor {
        SpriteBatch batch;
        Sprite sprite,sprite2;
        Texture img;
        Texture img1;
        World world;
        Body body,body2;
        Body ground;

        Matrix4 debugMatrix;
        OrthographicCamera camera;
        ExtendViewport viewport;
    Box2DDebugRenderer debugRenderer;

        float SCALE=0.05f;

        @Override
        public void create (){
            batch = new SpriteBatch();
            img = new Texture("ball.png");
            img1=new Texture("badlogic.jpg");
            camera=new OrthographicCamera();
            viewport= new ExtendViewport(50,50,camera);

            sprite = new Sprite(img);
            sprite2 = new Sprite(img1);
            sprite.setSize(sprite.getWidth()*SCALE,sprite.getHeight()*SCALE);
            sprite2.setSize(sprite2.getWidth()*SCALE,sprite2.getHeight()*SCALE);

            world = new World(new Vector2(0, -10f),true);
             createBall();
            createRect();
            debugRenderer = new Box2DDebugRenderer();
            Gdx.input.setInputProcessor(this);
        }
        @Override
        public void resize(int width, int height) {
            viewport.update(width, height, true);

        batch.setProjectionMatrix(camera.combined);
            createGround();
        }

        private void createBall(){
            BodyDef bodyDef = new BodyDef();
            bodyDef.type = BodyDef.BodyType.DynamicBody;
            bodyDef.position.set(MathUtils.random(15,30),50);
             CircleShape circleShape=new CircleShape();
            circleShape.setRadius(1.2f);
            body = world.createBody(bodyDef);
            FixtureDef fixtureDef = new FixtureDef();
            fixtureDef.shape = circleShape;
            fixtureDef.density = 0.1f;
            fixtureDef.restitution = 0.2f;
            fixtureDef.friction=0.2f;
            body.createFixture(fixtureDef);
            circleShape.dispose();
        }

        private void createRect(){
            BodyDef bodyDef2 = new BodyDef();
            bodyDef2.type = BodyDef.BodyType.DynamicBody;
            bodyDef2.position.set(25,10);
            body2 = world.createBody(bodyDef2);
            FixtureDef fixtureDef2 = new FixtureDef();
            PolygonShape shape = new PolygonShape();
            shape.setAsBox(sprite2.getWidth()/2, sprite2.getHeight()/2);
            fixtureDef2.shape = shape;
            fixtureDef2.density = 0.1f;
            fixtureDef2.restitution = 0.7f;
            fixtureDef2.friction=0.2f;
            body2.createFixture(fixtureDef2);
            shape.dispose();
        }

            private void createGround() {

                BodyDef bodyDef = new BodyDef();
                bodyDef.type = BodyDef.BodyType.StaticBody;
                FixtureDef fixtureDef = new FixtureDef();
                PolygonShape shape = new PolygonShape();
                shape.setAsBox(camera.viewportWidth, 1);
                fixtureDef.shape = shape;
                ground = world.createBody(bodyDef);
                ground.createFixture(fixtureDef);
                ground.setTransform(0, 0, 0);

                shape.dispose();

            }
        @Override
        public void dispose() {
            img.dispose();
            world.dispose();
        }

        @Override
        public void render () {
            Gdx.gl.glClearColor(1, 1, 1, 1);
            Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
            world.step(1f/60f, 6, 2);
            sprite.setPosition(body.getPosition().x-sprite.getWidth()/2,
                    body.getPosition().y-sprite.getHeight()/2 );

            sprite.setRotation((float)Math.toDegrees(body2.getAngle()));
            sprite2.setPosition(body2.getPosition().x - sprite2.getWidth()/2,
                    body2.getPosition().y -sprite2.getHeight()/2 );
            sprite2.setRotation((float)Math.toDegrees(body.getAngle()));

            batch.begin();
            batch.draw(sprite, sprite.getX(), sprite.getY(),sprite.getOriginX(),
                    sprite.getOriginY(),
                    sprite.getWidth(),sprite.getHeight(),sprite.getScaleX(),sprite.
                            getScaleY(),sprite.getRotation());
            batch.draw(sprite2, sprite2.getX(), sprite2.getY(),sprite2.getOriginX(),
                    sprite2.getOriginY(),
                    sprite2.getWidth(),sprite2.getHeight(),sprite2.getScaleX(),sprite2.
                        getScaleY(),sprite2.getRotation());
            batch.end();
            debugRenderer.render(world, camera.combined);
        }

        @Override
        public boolean keyDown(int keycode) {
            if(keycode== Input.Keys.LEFT)        //get some linear velocity
                body2.setLinearVelocity(-10f,0);
            if(keycode==Input.Keys.RIGHT)
                body2.setLinearVelocity(10f,5);
            return true;
        }

        @Override
        public boolean keyUp(int keycode) {
            if(keycode== Input.Keys.LEFT)
                body2.setLinearVelocity(0,0);
            if(keycode==Input.Keys.RIGHT)
                body2.setLinearVelocity(0,0);
            return true;
        }

        @Override
        public boolean keyTyped(char character) {
            return false;
        }

        @Override
        public boolean touchDown(int screenX, int screenY, int pointer, int button) {
            return false;
        }

        @Override
        public boolean touchUp(int screenX, int screenY, int pointer, int button) {
            return false;
        }

        @Override
        public boolean touchDragged(int screenX, int screenY, int pointer) {
            return false;
        }

        @Override
        public boolean mouseMoved(int screenX, int screenY) {
            return false;
        }

        @Override
        public boolean scrolled(int amount) {
            return false;
        }
    }

```

# Answer
finally got this problem solved by just adding this line of code to the bodies

```
body.setFixedRotation=true;

```
> -1 votes

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


title: Unity Ads showing test ads

text:
# Question
Title: Unity Ads showing test ads
I am implementing Unity Ads in my game and for some reason I have the test ads showing up in my production version of my app. I have the advertisements initialized with test ads turned off and I have even gone into my settings on the Unity Ads admin and set it to force test ads to be off. I'm not sure what else to do here.

Here is how I am initializing:

```
Advertisement.Initialize("myID", false);

```

# Answer
First make sure you have correctly entered your App Details on Unity Ads Dashboard after throwing it live on store.

Second, make sure you must not enabled test ads via Unity Ads Dashboard Settings.

Have a look,
> 1 votes

# Answer
Make sure that you have not registered your device as a test device!
> 0 votes

---
Tags: unity
---


# Question
Title: Sprite rotation: is it better to rotate with a quaternion or via sprite swap?
Considering this question: "In a generic game engine where you have an object sprite (e.g. Unity), is it better (in terms of performance) to implement a clockwise rotation calculating at each frame the incremented rotation (e.g. having a quaternion "q" representing a rotation of n degrees and at each frame computing newrotation = q * oldrotation) or having say 20 snapshot sprites of a complete rotation and changing the sprite at each frame (effectively a 2D animation)? "

Is there a non engine-specific answer to this question? If so, which one?

# Answer
> 1 votes
There is no way that a animation will bring better performance wise than operating with a quaternion, let alone the memory difference. Think of it like this : Which one is easier ? Add 2+2 in your head or draw by hand using only dots a set of 2's a + sign a = sign and a 4? The answer is obvious.

---
Tags: 2d, animation, sprites, rotation, quaternion
---


# Question
Title: What's the difference between Gameplay Programming and Graphic Programming?
I know the answers are obvious, someone told me this: Graphics Programming: DirectX(or Direct3d), OpenGL, Vulkan, Metal..

Gameplay Programming: Bringing everything together. From design, music, levels, etc.

But could you please explain me in depth the difference? This way i can focus on a specific role in game programming!

# Answer
Graphics programmers do tasks like the following:

* Implement high-level effects like bloom, chromatic aberration or object outlines
* Write low-level code to handle API (D3D, GL etc.) objects for textures, buffers, shaders etc. that the high-level functionality is built upon.

Gameplay programmers:

* Call functions that graphics programmer wrote or let scripters call them.
* Write a save/load system
* Handle game state (player's health, weapons etc.)
* Player and camera movement code etc.
> 3 votes

# Answer
Well, graphics programming is programming how the primitives are drawn on the screen or somewhere else (e.g. image file). Using one of the APIs like OpenGL, DirectX or more recent ones or not using them at all. Real-time and static graphics.

Game engines to the graphic engines is like an operating system to e.g. boot loader - games programming includes graphics programming amoung dozens of other tasks, i.e.:

* Graphics
* Game world physics
* Network
* User interaction (input)
* Real-time audio effects
* Game logic programming (story)

It's very helpful to read a book about how game engines work before you decide which activity to pick. A good starting point is a book called Game Programmings Gems.

**EDIT** Just google for a game engine development books and pick one with good reviews: https://www.amazon.com/Game-Programming-Computers-Internet-Books/b?ie=UTF8&node=15375251
> 0 votes

---
Tags: game-design, software-engineering, graphics-programming
---


title: Saving Information in Byte[]

text:
# Question
Title: Saving Information in Byte[]
sorry for the unhelpful title. I'm trying to understand how to convert information to bytes so that I can save it using Google's Saved Games feature that comes with Play Services, as explained here.

https://codelabs.developers.google.com/codelabs/playservices\_unity/index.html?index=..%2F..%2Findex#9

I've mostly copy-pasted the code but it's not really working out for me.

However, my initial question is about bytes. So it looks like Google stores game information in bytes\[\] . The example only shows a single int being converted to byte and then being saved. What if I wanted to save multiple integers in Google's Saved Game services? I'm not exactly sure what this byte array is in the first place and how everything can be converted to bytes. If anybody has any good resources or examples, it would be much appreciated! Thank you

# Answer
You can convert pretty much anything to a `byte[]` but the built-in methods are not all the same.

For numeric, non-string values you can do:

```
byte[] _intValue = BitConverter.GetBytes(_someInt);

```

For string values, you can do:

```
byte[] _stringValue = Encoding.ASCII.GetBytes(_someString);

```

If this is something you plan to do a lot of, you may want to create your own overloaded classes so you have a single call you can make to convert any data you need, probably with methods to covert to and from `byte[]` for each.
> 1 votes

---
Tags: unity, data-structure
---


# Question
Title: Showing the steps of a level generation process over multiple frames
I seem to be misunderstanding part of Unity. I'm generating a maze similar to the one here: http://journal.stuffwithstuff.com/2014/12/21/rooms-and-mazes/

I put the whole of the generation in `Update()` and used a `bool` to ensure it only runs once. However, right now the whole thing runs before the editor becomes available - it behaves exactly as if I had the whole thing in a `Start()` section. Do I need to use coroutines to watch it build out? In the link above, if you click the first demo box, you can watch the maze place itself and build. I'd like to be able to see that in the scene view in Unity. Thoughts?

Edit:

This is my `Update()` method currently:

```
void Update()
{
    while (_continue)
    {
      _continue = false;
      Dictionary<String, Tile> _dict = FetchTileList();

      Tile _wall = _dict["Wall"];

      for (int x = 0; x < width; x++)
      {
        for (int y = 0; y < height; y++)
        {
            var _go = Instantiate(_wall.gameObject, new Vector3(x, y, 0), Quaternion.identity);
        }
      }

      _addRooms();

      for (var y = 1; y < height; y += 2) {
        for (var x = 1; x < width; x += 2) {
            Vector2 pos = new Vector2(x, y);
            Rect _rect = new Rect(x, y, 1, 1);
            bool _add = true;

            foreach (var other in _rooms)
            {
                if (_rect.Overlaps(other))
                {
                    _add = false;
                }
            }

            if (_add)
            {
                _growMaze(pos);
            }
        }
      }
   }
}

```

# Answer
**A MonoBehaviour's Update() method runs once, to completion, before each game frame is rendered**. So if you change things in the middle of your Update method, you won't see that change until the Update method finishes (by reaching the closing brace at the end or a `return` statement), giving the engine a chance to continue with the rest of its work for the frame, rendering, and displaying the results.

In this case, that means the first frame isn't rendered until your Update method has finished all of its work and the maze is already complete.

To spread execution across multiple frames, the usual method is, as you say, a Coroutine. Then we can use `yield` statements to pass control back to the engine periodically to render a new frame, and resume generation exactly where we left off sometime later.

Here's how we might rewrite your maze generation to use this feature:

(I've omitted the `while(_continue)` section since I couldn't see anywhere in your code that \_continue is set back to true to make it loop a second time. Please include that code if it's needed)

```
void Start() {
    StartCoroutine(GenerateMaze());
}

IEnumerator GenerateMaze() {
    Dictionary<String, Tile> _dict = FetchTileList();

    Tile _wall = _dict["Wall"];

    for (int x = 0; x < width; x++)
    {
        for (int y = 0; y < height; y++)
        {
            // Wait one frame before adding each wall
            // (so we see an empty maze on the very first frame)
            yield return null;

            var _go = Instantiate(_wall.gameObject, new Vector3(x, y, 0), Quaternion.identity);
        }
    }

    // Wait one frame before adding rooms.
    // You may also want to make _addRooms a coroutine if you want to see it
    // perform its steps one by one. ie. yield return StartCoroutine(_addRooms());
    yield return null;
    _addRooms();

    for (var y = 1; y < height; y += 2) {
        for (var x = 1; x < width; x += 2) {
            Vector2 pos = new Vector2(x, y);
            Rect _rect = new Rect(x, y, 1, 1);
            bool _add = true;

            foreach (var other in _rooms)
            {
                if (_rect.Overlaps(other))
                {
                    _add = false;
                }
            }

            if (_add)
            {
                // Wait one frame before growing the maze.
                // Again, if this involves multiple steps, you might want to
                // make _growMaze a coroutine itself.
                yield return null;

                _growMaze(pos);
            }
        }
    }
}

```

Instead of `yield return null` which waits exactly one frame, you can also use `yield return new WaitForSeconds(0.1f);` if you want the generation speed to run slower, or be more consistent across devices running at different framerates.

See this answer - especially the list of Coroutine return values at the bottom - for more on ways you can control when your code runs.
> 3 votes

---
Tags: unity, procedural-generation, coroutines
---


# Question
Title: Developing a platform - why are age verifications even a thing?
I'm building an online gaming platform and have bumped into the question of age verification. Checkboxes such as "I verify that I am 13 years old or older" or a slider where you put in your age are common online when registering for accounts.

Why? I've been checking that box since I was a kid, it doesn't stop anyone. If you put it in your Terms of Service, is that enough?

Does any of this actually matter?

# Answer
> 3 votes
COPPA (in the U.S.) and similar laws abroad require children be of a certain age to provide information about themselves or utilize online services. Ostensibly, the "I am 13" checkbox protects the owners of the server or software from violating such acts, even though there is no guarantee that the user is being truthful (is there ever?).

There are other methods to "ensure" age, such as validating a credit card. This, I believe, is also acceptable. However, just including a "you must be 13 years old or older to use this service" in your TOS will not protect you from violating COPPA.

# Answer
> 1 votes
It does actually matter. Children under 13 can't give out personal information without their parents permission. Because most sites are directed towards grown ups (like stackoverflow for example), they have no way of checking if the registered user is over 13.

Sites for children can avoid this by usually asking for the parents email where the children can get the activation code for his/her profile. There are sites which make you accept an agrrement.

---
Tags: platform
---


title: GameObject walk onto platform Unity2D

text:
# Question
Title: GameObject walk onto platform Unity2D
I currently am working on a 2D game designed for android and iOS. I have a repeatedly spawning enemy game object which comes in from the left. I want the enemy game object to walk onto a slope which leads to a platform. I've tried adding physics rendering but it doesn't seem to work. I tried adding colliders to both and still nothing. The enemy object just goes straight through the slope and doesn't actually climb it.

# Answer
> 1 votes
You have to add both Colliders and Rigidbodies to both the enemy object and to the platform.

**Platform:** Set it to kinematic (and no-gravity just cuz, and lock the position/rotation) and set its position to where you want it.

**Enemy:** Set it non-kinematic and to use gravity, and add a velocity to it to make it move up the slope.

For fun you can add materials to the ground and the player to control their friction (is your platform icy/slippery? etc.).

---
Tags: unity
---


title: move camera with button in unity c#

text:
# Question
Title: move camera with button in unity c#
I want to move Main Camera with button. Here's my gameplay:

Here's my scene:

I want that when I click a button, main camera moves to right in another pic.

# Answer
Get the transform of the Camera and translate its position with the function to be called on button click

```
public Transform cameraTransform;
public void TranslateCamera() {
  cameraTransform.transform.Translate (new Vector3 (20, 0, 0));
}

```

Like this
> 0 votes

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


# Question
Title: How to make a map (game world) based on a real world place or city?
As a disclaimer before my real question, I have little experience in game development, only basic Unity knowledge.

I noticed a lot of games are based on real world places and cities, for example GTA 5 on Los Angeles and Watch Dogs. What is the process of making such a virtual version of a real world place or city? Or at least, what is a good starting point?

I imagine you could get some sort of map data or satellite images and import this in a tool, from which you can start modelling the buildings etc. But if this is the case I don't know how to do that.

# Answer
> 7 votes
Here is the map of Chicago from Watch\_Dogs:

And here is the map of Chicago from Google Maps:

As you see, these maps don't have much in common. When seen from a birds-eye perspective there isn't even a superfluous similarity. You will also notice that the map from Watch\_Dogs is *tiny* compared to real-world Chicago. Actually, Watch\_Dogs Chicago has barely the size of a small town. Yet, it feels like a real metropolis.

How did the artists and mappers pull this off?

They picking the most distinguished and iconic places in Chicago and replicating them by hand in 3d modeling programs. I am quite sure that they worked based on photos, likely even visited Chicago themselves to get an own impression of the real-world places.

Then they moved them as closely together as possible without them blending too much into each other and placed a few generic buildings between them as separators. The result is a map which still *feels* like real Chicago and lets the player find a lot of famous sights, even though it only has a tiny fraction of the size of the real Chicago.

You might wonder: Why were they so lazy? Why didn't they recreate *all* of Chicago? There are several reasons for that:

1. Budget constraints. Watch\_Dogs already was a AAA title with a million dollar budget. They had a whole army of 3d artists working on the game for years. Yet, creating a city the size of real Chicago with that level of detail and variation was still far from humanly possible.
2. Technical constraints. Even when it *would* have been possible to create all that (maybe through procedural generation based on map data), it might simply not have been possible to simulate such a huge world on present-day hardware.
3. Gameplay considerations. Let's be honest: Most parts of a real-world metropole are *boring*. In a real city you have blocks after blocks of office and residential buildings without anything extraordinary to them. And with the typical grid-layout of most North-American cities it is not even very interesting to navigate. But by only focusing on the most interesting parts of it, you can create a world which is far more interesting to explore. You find something interesting *literally* at every street corner.
4. It would not have been worth it anyway. According to Steam, the game occupied me for 52 hours. And seriously, that was more than enough. The main story was already overstretched, I had mastered all the game mechanics and the optional challenges had already gotten dull, too. Honestly, I was glad the game was over. But that was also the point where I had explored most of the game world. I can say with confidence that I have seen and appreciated at least 80% of the work of the map team. And I think they did a fantastic job (better than that of the writers and game designers, at least). But when the game would have taken place in a real-size Chicago, I would have still seen only a glimpse of the whole city. And with the gameplay being exhausted, I wouldn't really have felt like exploring it all. That means most of their work would have been in vain.

No, Watch\_Dogs Chicago is exactly the right size. Not too small but not too large either.

# Answer
> 2 votes
Philipp's answer is slightly misleading, because it places the wrong maps against each other. In the maps below, look at the river, the Navy Pier, and the park.

The rest of the answer I agree with: You pick some iconic parts of the actual city (usually the city center and a few iconic places), rearrange as needed (due to gameplay or legal reasons), and shrink the parts in between.

To model the actual buildings, you send some of the artists there, and let them make pictures - they need to know what the place looks like anyway, and while they're there they take the pictures.

---
Tags: maps, world-design, 3d-modeling, world-editor
---


# Question
Title: Algorithm for "healing" multiple rectangles into a smaller number of rectangles?
Say I have a grid of rectangles of different shapes and colors and I want to reduce (reasonably close to optimal is fine, optimal is not necessary) the number of rectangles to represent the same layout of colors.

The image above is a very simplified case and the whitespace between the rectangles is for visualization only -- they would actually be tightly packed.

What is an approach or algorithm name (happy to google) that can help me do this?

# Answer
First, we can convert your source rectangles to cells in your underlying grid, to make the input more uniform. (Effectively rasterizing the problem)

This will let us find optimizations that might not be obvious when working directly with the source rectangles - particularly when it involves splitting multiple source rectangles to recombine them differently.

Next we can find connected regions of the same colour, using depth-first-search or flood filling algorithms. We can consider each connected region (a polyomino) in isolation - nothing that we do to a different region needs to influence this one.

Effectively we want to find a way to dissect this polyomino into rectangles (unfortunately most of the literature I can find is about the opposite problem: dissecting rectangles into polyominoes! This makes it tricky to search for leads...)

One straightforward method is to combine horizontal runs of adjacent squares into long skinny rectangles. Then we can compare against the row above and combine if our run starts & ends match up - either as we finish each run/row, or as we consider each cell to add to the current run.

I don't know yet how close this method gets to optimal. It seems it can run into a bit of trouble when a row it hasn't considered yet suggests a different split than the rows it's seen so far:

Detecting when a run/rectangle is exactly covered by runs above & below, then splitting it and merging them will solve this particular case, but I haven't explored how general the problem is.

I've also looked at methods where we walk the perimeter of the polyomino, and cut across anytime we encounter a concave corner, but this approach looks more error-prone to me. Getting optimal results seems to require prioritizing cuts that join two concave corners, and shapes containing hollows need special handling, so the row scan method seems to have the simplicity advantage.

One more method I'm looking at is to take the first run found in the top row & extend it down as far as you can. Then take the first run in the top row of what's left... This gets tripped-up on inverted T shapes though, so it's not optimal either.

I feel like there's probably a way to use dynamic programming to find the optimal split, but I haven't found it yet.
> 19 votes

---
Tags: algorithm, geometry, space-partitioning
---


# Question
Title: Cannot get a handle on a GameObject velocity through another GameObject in Unity
I'm trying to make a brick breaker game in Unity, using 2D. I have an object that randomly spawns when a brick is destroyed. One of them is a "slowdown" object to slow down the projectile. However, whenever I "catch" the spawn with my paddle, it seems as if I don't have the same instance of the ball.

For instance, I `Debug.Log` the velocity of the ball through `RandomSpawns.cs`script, it will show as (0,0). At the same time, if I show the ball velocity through `ball.cs`, it will show the right velocity

**RandomSpawning.cs:**

```
using UnityEngine;
using System.Collections;

public class RandomSpawns : MonoBehaviour
{
    public paddle paddle;
    public LoseCollider loseCollider;
    public ball ball;
    public Brick brick;

    public string nameOfSpawn;

void Update()
{

    // Finds object with Spawn tag and if lower than paddle y pos, means
    // that player missed the spawn -->destroy to not reset the game

    if (GameObject.FindGameObjectsWithTag("Spawn") != null)
    {
        if (this.transform.position.y < paddle.transform.position.y)
        {
            Destroy(gameObject);
        }
    }
}

void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.gameObject.tag == "paddle")
    {
        triggeredEffect();
        Debug.Log("Right here");
        Destroy(this.gameObject);
    }
}

void triggeredEffect()
{
    if (string.Equals(nameOfSpawn, "slowdown"))
    {
        Debug.Log("current velocity " + ball.GetComponent<Rigidbody2D>().velocity);
        Vector2 velocity = ball.GetComponent<Rigidbody2D>().velocity;
        ball.GetComponent<Rigidbody2D>().velocity = velocity * 0.5f;
        Debug.Log("slowdown: new velocity" + ball.GetComponent<Rigidbody2D>().velocity);
    }
}

```

I also tried using this, to no avail:

```
 GameObject ball = GameObject.Find("ball");
 ball currentBall = ball.GetComponent<ball>();
 Debug.Log("current velocity " + currentBall.GetComponent<Rigidbody2D>().velocity);
 Vector2 velocity = currentBall.GetComponent<Rigidbody2D>().velocity;
 currentBall.GetComponent<Rigidbody2D>().velocity = velocity * 0.5f;
 Debug.Log("slowdown: new velocity" + currentBall.GetComponent<Rigidbody2D>().velocity);

```

This just gives me an "Object reference not set to instance of object" error.

**ball.cs**:

```
using UnityEngine;
using System.Collections;

public class ball : MonoBehaviour
{
    private paddle paddle;
    private bool hasStarted = false;
    private Vector3 paddleToBall;

    void Start ()
    {
        paddle = GameObject.FindObjectOfType<paddle>();
        paddleToBall = this.transform.position - paddle.transform.position;
        print(paddleToBall);
    }

    // Update is called once per frame
    void Update ()
    {
        if (!hasStarted)
        {
            this.transform.position = paddle.transform.position + paddleToBall;
            if (Input.GetMouseButtonDown(0))
            {
                this.GetComponent<Rigidbody2D>().velocity = new Vector2(.5f, 10f);
                hasStarted = true;
            }
        }
    }

    void OnCollisionEnter2D(Collision2D collision)
    {
        Vector2 tweak = new Vector2(Random.Range(0f, .2f),Random.Range(0f, .2f));
        if (hasStarted)
        {
            GetComponent<AudioSource>().Play();
            GetComponent<Rigidbody2D>().velocity += tweak;
        }
    }
}

```

# Answer
> 1 votes
Your referencing your ball incorrectly. I believe that your second attempt *may* expose an additional error, but you still use incorrect naming conventions, that potentially lead to completely loosing reference to your `ball.cs` class.

### Attempt One - Naming Conventions and Class References

It is *very* important that you ensure the use of *unique* names. This includes between references and class names. You can give the name "ball" to both the class and the instance name.

In both scripts, this is how you create your references:

```
ball ball;
paddle paddle;

```

This is an example of how you *should* be creating your references:

```
ball _ball;
paddle paddleInstance;

```

When you use identical names for the instance, as you did for the actual class, you leave the door open for many peculiar behaviors. In this case, I believe you are creating a reference that is automatically interpreted as an 'instantiated default', leading to the wrong reference.

### Attempt Two - Finding via Tag and Name

In your second attempt, you hit an error before you even look to the class. This could also be caused by the way you are looking for the object. When you use `GameObject.Find(string)`, you are looking for the actual name you have given the game object in the Unity editor. You *can not* provide the name of a component or script in this way, as `GameObject.Find()` only looks at `GameObject.name`.

You may very well be using it correctly, in your example. Once again, your naming your *game object* with the *identical* name you give to your class. This can cause additional problems, including those which may lead to an error in linking the reference to an actual game object, in the first place.

---
Tags: unity
---


# Question
Title: Why does my point light shader shows a strange behaviour, and how do I fix it?
I follow the well known tutorial about lighting and model importing using Learn opengl, i copy paste the code from the site. The author claims that the shader works but when i compile the source code, i got strange behaviour.

The texture loading is done using this function:

```
GLint TextureFromFile(const char* path, string directory, bool gamma)
{
    //Generate texture ID and load texture data
    string filename = string(path);
    filename = directory + '/' + filename;
    GLuint textureID;
    glGenTextures(1, &textureID);
    int width, height;
    unsigned char* image = SOIL_load_image(filename.c_str(), &width, &height, 0, SOIL_LOAD_RGB);
    // Assign texture to ID
    glBindTexture(GL_TEXTURE_2D, textureID);
    glTexImage2D(GL_TEXTURE_2D, 0, gamma ? GL_SRGB : GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
    glGenerateMipmap(GL_TEXTURE_2D);

    // Parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glBindTexture(GL_TEXTURE_2D, 0);
    SOIL_free_image_data(image);
    return textureID;
}

```

When I only use ambient lighting from the fragment shader, the textures are shown as expected, but when the normal and light direction are used in shader, i got this strange image. My code asked ASSIMP to generate normals when it loads the model, but still getting this as results.

(The remaining files are below)

Here is the **vertex shader**:

```
// Vertex shader:
// ================
#version 330 core
layout (location = 0) in vec3 position;
layout (location = 1) in vec3 normal;
layout (location = 2) in vec2 texCoords;

out vec2 TexCoords;
out vec3 fragPosition;
out vec3 Normal;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

void main()
{
    gl_Position = projection * view * model * vec4(position, 1.0f);
    fragPosition = vec3(model * vec4(position, 1.0f));
    Normal = mat3(transpose(inverse(model))) * normal;
    TexCoords = texCoords;
}

```

And the **fragment shader**:

```
// Fragment shader:
// ================
#version 330 core
struct Material {
    sampler2D texture_diffuse1;
    sampler2D texture_specular1;
    float shininess;
};
/* Note: because we now use a material struct again you want to change your
mesh class to bind all the textures using material.texture_diffuseN instead of
texture_diffuseN. */

struct PointLight {
    vec3 position;

    float constant;
    float linear;
    float quadratic;

    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
};

#define NR_POINT_LIGHTS 2

in vec3 fragPosition;
in vec3 Normal;
in vec2 TexCoords;

out vec4 color;

uniform vec3 viewPos;
uniform PointLight pointLights[NR_POINT_LIGHTS];
uniform Material material;

// Function prototypes
vec3 CalcPointLight(PointLight light, Material mat, vec3 normal, vec3 fragPos, vec3 viewDir);

void main()
{
    vec3 result;
    vec3 viewDir = normalize(viewPos - fragPosition);
    vec3 norm = normalize(Normal);

    for(int i = 0; i < NR_POINT_LIGHTS; i++)
        result += CalcPointLight(pointLights[i], material, norm, fragPosition, viewDir);

    color = vec4(result, 1.0f);
}

// Calculates the color when using a point light.
vec3 CalcPointLight(PointLight light, Material mat, vec3 normal, vec3 fragPos, vec3 viewDir)
{
    vec3 lightDir = normalize(light.position - fragPos);
    // Diffuse shading
    float diff = max(dot(normal, lightDir), 0.0);
    // Specular shading
    vec3 reflectDir = reflect(-lightDir, normal);
    float spec = pow(max(dot(viewDir, reflectDir), 0.0), mat.shininess);
    // Attenuation
    float distance = length(light.position - fragPos);
    float attenuation = 1.0f / (light.constant + light.linear * distance + light.quadratic * (distance * distance));
    // Combine results
    vec3 ambient = light.ambient * vec3(texture(mat.texture_diffuse1, TexCoords));
    vec3 diffuse = light.diffuse * diff * vec3(texture(mat.texture_diffuse1, TexCoords));
    vec3 specular = light.specular * spec * vec3(texture(mat.texture_specular1, TexCoords));
    ambient *= attenuation;
    diffuse *= attenuation;
    specular *= attenuation;
    return (ambient + diffuse + specular);
}

```

Here is **the c++ source code** (using assimp for model loading, SOIL for image loading, and glm for matrix calculations):

```
// Std. Includes
#include <string>

// GLEW
#define GLEW_STATIC
#include <GL/glew.h>

// GLFW
#include <GLFW/glfw3.h>

// GL includes
#include "Shader.h"
#include "Camera.h"
#include "Model.h"

// GLM Mathemtics
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>

// Other Libs
#include <SOIL.h>

// Properties
GLuint screenWidth = 800, screenHeight = 600;

// Function prototypes
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
void mouse_callback(GLFWwindow* window, double xpos, double ypos);
void Do_Movement();

// Camera
Camera camera(glm::vec3(0.0f, 0.0f, 3.0f));
bool keys[1024];
GLfloat lastX = 400, lastY = 300;
bool firstMouse = true;

GLfloat deltaTime = 0.0f;
GLfloat lastFrame = 0.0f;

// The MAIN function, from here we start our application and run the Game loop
int main()
{
    // Init GLFW
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    GLFWwindow* window = glfwCreateWindow(screenWidth, screenHeight, "LearnOpenGL", nullptr, nullptr); // Windowed
    glfwMakeContextCurrent(window);

    // Set the required callback functions
    glfwSetKeyCallback(window, key_callback);
    glfwSetCursorPosCallback(window, mouse_callback);
    glfwSetScrollCallback(window, scroll_callback);

    // Options
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

    // Initialize GLEW to setup the OpenGL Function pointers
    glewExperimental = GL_TRUE;
    glewInit();

    // Define the viewport dimensions
    glViewport(0, 0, screenWidth, screenHeight);

    // Setup some OpenGL options
    glEnable(GL_DEPTH_TEST);

    // Setup and compile our shaders
    Shader shader("../../../Path/To/Shaders/model_loading.vs", "../../../Path/To/Shaders/model_loading.frag");
    Shader lampShader("../../../Path/To/Shaders/lamp.vs", "../../../Path/To/Shaders/lamp.frag");

    // Load models
    Model ourModel("../../../Path/To/Nanosuit/nanosuit.obj");
    // Used a lamp object here. Find one yourself on the internet, or create your own one ;) (or be oldschool and set the VBO and VAO yourselves)
    Model lightBulb("../../../Path/To/Lamps/Bulb.obj");

    // Draw in wireframe
    //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

    // Point light positions
    glm::vec3 pointLightPositions[] = {
        glm::vec3(2.3f, -1.6f, -3.0f),
        glm::vec3(-1.7f, 0.9f, 1.0f)
    };

    // Game loop
    while(!glfwWindowShouldClose(window))
    {
        // Set frame time
        GLfloat currentFrame = glfwGetTime();
        deltaTime = currentFrame - lastFrame;
        lastFrame = currentFrame;

        // Check and call events
        glfwPollEvents();
        Do_Movement();

        // Clear the colorbuffer
        glClearColor(0.05f, 0.05f, 0.05f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        shader.Use();   // <-- Don't forget this one!
        // Transformation matrices
        glm::mat4 projection = glm::perspective(camera.Zoom, (float)screenWidth/(float)screenHeight, 0.1f, 100.0f);
        glm::mat4 view = camera.GetViewMatrix();
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection));
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view));

        // Set the lighting uniforms
        glUniform3f(glGetUniformLocation(shader.Program, "viewPos"), camera.Position.x, camera.Position.y, camera.Position.z);
        // Point light 1
        glUniform3f(glGetUniformLocation(shader.Program, "pointLights[0].position"), pointLightPositions[0].x, pointLightPositions[0].y, pointLightPositions[0].z);
        glUniform3f(glGetUniformLocation(shader.Program, "pointLights[0].ambient"), 0.05f, 0.05f, 0.05f);
        glUniform3f(glGetUniformLocation(shader.Program, "pointLights[0].diffuse"), 1.0f, 1.0f, 1.0f);
        glUniform3f(glGetUniformLocation(shader.Program, "pointLights[0].specular"), 1.0f, 1.0f, 1.0f);
        glUniform1f(glGetUniformLocation(shader.Program, "pointLights[0].constant"), 1.0f);
        glUniform1f(glGetUniformLocation(shader.Program, "pointLights[0].linear"), 0.009);
        glUniform1f(glGetUniformLocation(shader.Program, "pointLights[0].quadratic"), 0.0032);
        // Point light 2
        glUniform3f(glGetUniformLocation(shader.Program, "pointLights[1].position"), pointLightPositions[1].x, pointLightPositions[1].y, pointLightPositions[1].z);
        glUniform3f(glGetUniformLocation(shader.Program, "pointLights[1].ambient"), 0.05f, 0.05f, 0.05f);
        glUniform3f(glGetUniformLocation(shader.Program, "pointLights[1].diffuse"), 1.0f, 1.0f, 1.0f);
        glUniform3f(glGetUniformLocation(shader.Program, "pointLights[1].specular"), 1.0f, 1.0f, 1.0f);
        glUniform1f(glGetUniformLocation(shader.Program, "pointLights[1].constant"), 1.0f);
        glUniform1f(glGetUniformLocation(shader.Program, "pointLights[1].linear"), 0.009);
        glUniform1f(glGetUniformLocation(shader.Program, "pointLights[1].quadratic"), 0.0032);

        // Draw the loaded model
        glm::mat4 model;
        model = glm::translate(model, glm::vec3(0.0f, -1.75f, 0.0f)); // Translate it down a bit so it's at the center of the scene
        model = glm::scale(model, glm::vec3(0.2f, 0.2f, 0.2f)); // It's a bit too big for our scene, so scale it down
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model));
        ourModel.Draw(shader);

        // Draw the lamps
        lampShader.Use();
        glUniformMatrix4fv(glGetUniformLocation(lampShader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection));
        glUniformMatrix4fv(glGetUniformLocation(lampShader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view));
        for(GLuint i = 0; i < 2; i++)
        {
            model = glm::mat4();
            model = glm::translate(model, pointLightPositions[i]);
            model = glm::scale(model, glm::vec3(0.3f, 0.3f, 0.3f)); // Downscale lamp object (a bit too large)
            glUniformMatrix4fv(glGetUniformLocation(lampShader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model));
            lightBulb.Draw(lampShader);
        }

        // Swap the buffers
        glfwSwapBuffers(window);
    }

    glfwTerminate();
    return 0;
}

#pragma region "User input"

// Moves/alters the camera positions based on user input
void Do_Movement()
{
    // Camera controls
    if(keys[GLFW_KEY_W])
        camera.ProcessKeyboard(FORWARD, deltaTime);
    if(keys[GLFW_KEY_S])
        camera.ProcessKeyboard(BACKWARD, deltaTime);
    if(keys[GLFW_KEY_A])
        camera.ProcessKeyboard(LEFT, deltaTime);
    if(keys[GLFW_KEY_D])
        camera.ProcessKeyboard(RIGHT, deltaTime);
}

// Is called whenever a key is pressed/released via GLFW
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
    if(key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
        glfwSetWindowShouldClose(window, GL_TRUE);

    if(action == GLFW_PRESS)
        keys[key] = true;
    else if(action == GLFW_RELEASE)
        keys[key] = false;
}

void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
    if(firstMouse)
    {
        lastX = xpos;
        lastY = ypos;
        firstMouse = false;
    }

    GLfloat xoffset = xpos - lastX;
    GLfloat yoffset = lastY - ypos;

    lastX = xpos;
    lastY = ypos;

    camera.ProcessMouseMovement(xoffset, yoffset);
}

void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
    camera.ProcessMouseScroll(yoffset);
}

#pragma endregion

```

Here is the **camera.h header file**:

```
#pragma once

// Std. Includes
#include <vector>

// GL Includes
#define GLEW_STATIC
#include <GL/glew.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>

// Defines several possible options for camera movement. Used as abstraction to stay away from window-system specific input methods
enum Camera_Movement {
    FORWARD,
    BACKWARD,
    LEFT,
    RIGHT
};

// Default camera values
const GLfloat YAW        = -90.0f;
const GLfloat PITCH      =  0.0f;
const GLfloat SPEED      =  3.0f;
const GLfloat SENSITIVTY =  0.25f;
const GLfloat ZOOM       =  45.0f;

// An abstract camera class that processes input and calculates the corresponding Euler Angles, Vectors and Matrices for use in OpenGL
class Camera
{
public:
    // Camera Attributes
    glm::vec3 Position;
    glm::vec3 Front;
    glm::vec3 Up;
    glm::vec3 Right;
    glm::vec3 WorldUp;
    // Euler Angles
    GLfloat Yaw;
    GLfloat Pitch;
    // Camera options
    GLfloat MovementSpeed;
    GLfloat MouseSensitivity;
    GLfloat Zoom;

    // Constructor with vectors
    Camera(glm::vec3 position = glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f), GLfloat yaw = YAW, GLfloat pitch = PITCH) : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVTY), Zoom(ZOOM)
    {
        this->Position = position;
        this->WorldUp = up;
        this->Yaw = yaw;
        this->Pitch = pitch;
        this->updateCameraVectors();
    }
    // Constructor with scalar values
    Camera(GLfloat posX, GLfloat posY, GLfloat posZ, GLfloat upX, GLfloat upY, GLfloat upZ, GLfloat yaw, GLfloat pitch) : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVTY), Zoom(ZOOM)
    {
        this->Position = glm::vec3(posX, posY, posZ);
        this->WorldUp = glm::vec3(upX, upY, upZ);
        this->Yaw = yaw;
        this->Pitch = pitch;
        this->updateCameraVectors();
    }

    // Returns the view matrix calculated using Euler Angles and the LookAt Matrix
    glm::mat4 GetViewMatrix()
    {
        return glm::lookAt(this->Position, this->Position + this->Front, this->Up);
    }

    // Processes input received from any keyboard-like input system. Accepts input parameter in the form of camera defined ENUM (to abstract it from windowing systems)
    void ProcessKeyboard(Camera_Movement direction, GLfloat deltaTime)
    {
        GLfloat velocity = this->MovementSpeed * deltaTime;
        if (direction == FORWARD)
            this->Position += this->Front * velocity;
        if (direction == BACKWARD)
            this->Position -= this->Front * velocity;
        if (direction == LEFT)
            this->Position -= this->Right * velocity;
        if (direction == RIGHT)
            this->Position += this->Right * velocity;
    }

    // Processes input received from a mouse input system. Expects the offset value in both the x and y direction.
    void ProcessMouseMovement(GLfloat xoffset, GLfloat yoffset, GLboolean constrainPitch = true)
    {
        xoffset *= this->MouseSensitivity;
        yoffset *= this->MouseSensitivity;

        this->Yaw   += xoffset;
        this->Pitch += yoffset;

        // Make sure that when pitch is out of bounds, screen doesn't get flipped
        if (constrainPitch)
        {
            if (this->Pitch > 89.0f)
                this->Pitch = 89.0f;
            if (this->Pitch < -89.0f)
                this->Pitch = -89.0f;
        }

        // Update Front, Right and Up Vectors using the updated Euler angles
        this->updateCameraVectors();
    }

    // Processes input received from a mouse scroll-wheel event. Only requires input on the vertical wheel-axis
    void ProcessMouseScroll(GLfloat yoffset)
    {
        if (this->Zoom >= 1.0f && this->Zoom <= 45.0f)
            this->Zoom -= yoffset;
        if (this->Zoom <= 1.0f)
            this->Zoom = 1.0f;
        if (this->Zoom >= 45.0f)
            this->Zoom = 45.0f;
    }

private:
    // Calculates the front vector from the Camera's (updated) Euler Angles
    void updateCameraVectors()
    {
        // Calculate the new Front vector
        glm::vec3 front;
        front.x = cos(glm::radians(this->Yaw)) * cos(glm::radians(this->Pitch));
        front.y = sin(glm::radians(this->Pitch));
        front.z = sin(glm::radians(this->Yaw)) * cos(glm::radians(this->Pitch));
        this->Front = glm::normalize(front);
        // Also re-calculate the Right and Up vector
        this->Right = glm::normalize(glm::cross(this->Front, this->WorldUp));  // Normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement.
        this->Up    = glm::normalize(glm::cross(this->Right, this->Front));
    }
};

```

The \** filesystem.h \**:

```
#ifndef FILESYSTEM_H
#define FILESYSTEM_H

#include <string>
//#include "root_directory.h" // This is a configuration file generated by CMake.

class FileSystem
{
private:
  typedef std::string (*Builder) (const std::string& path);

public:
  static std::string getPath(const std::string& path)
  {
    static std::string(*pathBuilder)(std::string const &) = getPathBuilder();
    return (*pathBuilder)(path);
  }
  //const char * logl_root = "H:/OpenGLDev/LearnOpenGL-master";
//static char * logl_root = "C:/Users/Michael/Documents/Visual Studio 2015/Projects/glGame/glGame";
private:
  static std::string const & getRoot()
  {
    /*static char const * envRoot = getenv("LOGL_ROOT_PATH");
    static char const * givenRoot = (envRoot != nullptr ? envRoot : logl_root);*/
    /*static char const * givenRoot =  logl_root;
    static std::string root = (givenRoot != nullptr ? givenRoot : "");
    return root;*/
      return std::string("C:/Users/Michael/Documents/Visual Studio 2015/Projects/glGame/glGame");
  }

  //static std::string(*foo (std::string const &)) getPathBuilder()
  static Builder getPathBuilder()
  {
    if (getRoot() != "")
      return &FileSystem::getPathRelativeRoot;
    else
      return &FileSystem::getPathRelativeBinary;
  }

  static std::string getPathRelativeRoot(const std::string& path)
  {
    return getRoot() + std::string("/") + path;
  }

  static std::string getPathRelativeBinary(const std::string& path)
  {
    return "../../../" + path;
  }

};

// FILESYSTEM_H
#endif

```

The \** mesh.h \**:

```
#ifndef MESH_H
#define MESH_H
// Std. Includes
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <vector>
using namespace std;
// GL Includes
#define GLEW_STATIC
#include <GL/glew.h> // Contains all the necessery OpenGL includes
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>

struct Vertex {
    // Position
    glm::vec3 Position;
    // Normal
    glm::vec3 Normal;
    // TexCoords
    glm::vec2 TexCoords;
    // Tangent
    glm::vec3 Tangent;
    // Bitangent
    glm::vec3 Bitangent;
};

struct Texture {
    GLuint id;
    string type;
    aiString path;
};

class Mesh {
public:
    /*  Mesh Data  */
    vector<Vertex> vertices;
    vector<GLuint> indices;
    vector<Texture> textures;
    GLuint VAO;

    /*  Functions  */
    // Constructor
    Mesh(vector<Vertex> vertices, vector<GLuint> indices, vector<Texture> textures)
    {
        this->vertices = vertices;
        this->indices = indices;
        this->textures = textures;

        // Now that we have all the required data, set the vertex buffers and its attribute pointers.
        this->setupMesh();
    }

    // Render the mesh
    void Draw(Shader shader)
    {
        // Bind appropriate textures
        GLuint diffuseNr = 1;
        GLuint specularNr = 1;
        GLuint normalNr = 1;
        GLuint heightNr = 1;
        for(GLuint i = 0; i < this->textures.size(); i++)
        {
            glActiveTexture(GL_TEXTURE0 + i); // Active proper texture unit before binding
            // Retrieve texture number (the N in diffuse_textureN)
            stringstream ss;
            string number;
            string name = this->textures[i].type;
            if(name == "material.texture_diffuse")
                ss << diffuseNr++; // Transfer GLuint to stream
            else if(name == "material.texture_specular")
                ss << specularNr++; // Transfer GLuint to stream
            else if(name == "material.texture_normal")
                ss << normalNr++; // Transfer GLuint to stream
             else if(name == "material.texture_height")
                ss << heightNr++; // Transfer GLuint to stream
            number = ss.str();
            // Now set the sampler to the correct texture unit
            glUniform1i(glGetUniformLocation(shader.Program, (name + number).c_str()), i);
            // And finally bind the texture
            glBindTexture(GL_TEXTURE_2D, this->textures[i].id);
        }

        // Draw mesh
        glBindVertexArray(this->VAO);
        glDrawElements(GL_TRIANGLES, this->indices.size(), GL_UNSIGNED_INT, 0);
        glBindVertexArray(0);

        // Always good practice to set everything back to defaults once configured.
        this->unbindTextures();
    }

private:
    /*  Render data  */
    GLuint VBO, EBO;

    /*  Functions    */
    // Initializes all the buffer objects/arrays
    void setupMesh()
    {
        // Create buffers/arrays
        glGenVertexArrays(1, &this->VAO);
        glGenBuffers(1, &this->VBO);
        glGenBuffers(1, &this->EBO);

        glBindVertexArray(this->VAO);
        // Load data into vertex buffers
        glBindBuffer(GL_ARRAY_BUFFER, this->VBO);
        // A great thing about structs is that their memory layout is sequential for all its items.
        // The effect is that we can simply pass a pointer to the struct and it translates perfectly to a glm::vec3/2 array which
        // again translates to 3/2 floats which translates to a byte array.
        glBufferData(GL_ARRAY_BUFFER, this->vertices.size() * sizeof(Vertex), &this->vertices[0], GL_STATIC_DRAW);

        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->EBO);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, this->indices.size() * sizeof(GLuint), &this->indices[0], GL_STATIC_DRAW);

        // Set the vertex attribute pointers
        // Vertex Positions
        glEnableVertexAttribArray(0);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)0);
        // Vertex Normals
        glEnableVertexAttribArray(1);
        glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)offsetof(Vertex, Normal));
        // Vertex Texture Coords
        glEnableVertexAttribArray(2);
        glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)offsetof(Vertex, TexCoords));
        // Vertex Tangent
        glEnableVertexAttribArray(3);
        glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)offsetof(Vertex, Tangent));
        // Vertex Bitangent
        glEnableVertexAttribArray(4);
        glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)offsetof(Vertex, Bitangent));

        glBindVertexArray(0);
    }

    void unbindTextures()
    {
        for (GLuint i = 0; i < this->textures.size(); i++)
        {
            glActiveTexture(GL_TEXTURE0 + i);
            glBindTexture(GL_TEXTURE_2D, 0);
        }
    }
};

#endif

```

And the image below is **the supposed image** shown when it runs:

**EDIT3:** This is **the image i got** (just changed the background color to white), now my point light directions and the triangle normals are working fine but still getting bug on my final fragment color:

And below are the image i get when i deactivate the "spec" and "attenuation" values into fragment color calculations (the diffuse and specular texture seems to be loaded succesfully, but their modifier **spec** and **attenuation** seems to cause the bug):

I'm nearly sure that **the bug is in fragment shader** but i don't know how i should modify it so that it works as claimed by the author of the tutorial.

I'm not an expert of GLSL, i'm just learning. Please help

# Answer
> 1 votes
I started with the same tutorials. None of them ever seem to work properly to be honest, I think that is intentional.

This is my oldest/simplest backup - I do more in here but you can use it as a template. The c++ code won't help you because it is not doing the same things the same way you are but once you get the hang of it that part should be easy.

vertex:

```
#version 330 core

layout (location = 0) in vec3 position;
layout (location = 1) in vec3 normal;
layout (location = 2) in vec2 texCoord;
layout (location = 3) in mat4 model;

out vec2 TexCoord;
out vec3 FragPos;
out vec3 Normal;
out vec3 VertexPosition;

    uniform mat4 view;
    uniform mat4 projection;

    void main()
    {
        gl_Position = projection * view * model * vec4(position, 1.0f);
        TexCoord = vec2(texCoord.x, 1.0 - texCoord.y);
        FragPos = vec3(model * vec4(position, 1.0f));
        Normal = mat3(transpose(inverse(model))) * normal;
        VertexPosition = (view*model*vec4(position, 1.0)).xyz;
    }

```

frag:

```
#version 330 core

    struct DirectionalLight {
        vec3 direction;
        vec3 ambient;
        vec3 diffuse;
        vec3 specular;

    };

    struct PointLight {
        vec3 position;
        vec3 ambient;
        vec3 diffuse;
        vec3 specular;
        float constant;
        float linear;
        float quadratic;
    };

    struct Material {
        sampler2D diffuseMap;
        sampler2D specularMap;
        sampler2D normalMap;
        float shininess;
    };

    in vec2 TexCoord;
    in vec3 FragPos;
    in vec3 Normal;
    in vec3 VertexPosition;

    out vec4 color;

    uniform vec3 viewPos;
    uniform DirectionalLight directionalLight;
    uniform PointLight light;
    uniform Material material;

    vec3 CalcDirLight(DirectionalLight dl, vec3 normal, vec3 viewDir, vec3 objectColor, vec3 specularColor);
    vec3 CalcPointLight(PointLight l, vec3 normal, vec3 viewDir, vec3 objectColor, vec3 specularColor);
    mat3 cotangentFrame(vec3 N, vec3 p, vec2 uv);
    vec3 applyNormalMap(vec3 N, vec3 V, vec2 texcoord);

    void main()
    {
        //vec4 objectColor = mix(texture(ourTexture1, TexCoord), texture(ourTexture2, TexCoord), 0.2);
        vec3 objectColor =  texture(material.diffuseMap, TexCoord).xyz;
        vec3 specularColor = texture(material.specularMap, TexCoord).xzy;

        vec3 vertexToEye = normalize(-VertexPosition);

        vec3 norm = normalize(applyNormalMap(Normal, vertexToEye, TexCoord));

        vec3 viewDir = normalize(viewPos - FragPos);

        vec3 result = CalcDirLight(directionalLight, norm, viewDir, objectColor, specularColor);
        result+=CalcPointLight(light, norm, viewDir, objectColor, specularColor);

        color = vec4(result, 1.0f);

    }

    vec3 CalcDirLight(DirectionalLight dl, vec3 normal, vec3 viewDir, vec3 objectColor, vec3 specularColor)
    {
        vec3 ambient = dl.ambient * objectColor;

        float diff = max(dot(normal, dl.direction), 0.0);
        vec3 diffuse = dl.diffuse * (diff * objectColor);

        vec3 halfwayDir = normalize(dl.direction + viewDir);
        float spec = pow(max(dot(normal, halfwayDir), 0.0), material.shininess);
        vec3 specular = dl.specular * (spec * specularColor);

        return (ambient + diffuse + specular);
    }

    vec3 CalcPointLight(PointLight l, vec3 normal, vec3 viewDir, vec3 objectColor, vec3 specularColor)
    {
        vec3 lightDir = normalize(l.position - FragPos);

        float distance    = length(l.position - FragPos);
        float attenuation = 1.0f / (l.constant + l.linear * distance + l.quadratic * (distance * distance));

        vec3 ambient = l.ambient * objectColor * attenuation;

        float diff = max(dot(normal, lightDir), 0.0);
        vec3 diffuse = l.diffuse * (diff * objectColor) * attenuation;

        vec3 halfwayDir = normalize(lightDir + viewDir);
        float spec = pow(max(dot(normal, halfwayDir), 0.0), material.shininess) * attenuation;
        vec3 specular = l.specular * (spec * specularColor);

        return (ambient + diffuse + specular);
    }

    mat3 cotangentFrame(vec3 N, vec3 p, vec2 uv)
    {
        // get edge vectors of the pixel triangle
        vec3 dp1 = dFdx(p);
        vec3 dp2 = dFdy(p);
        vec2 duv1 = dFdx(uv);
        vec2 duv2 = dFdy(uv);

        // solve the linear system
        vec3 dp2perp = cross(dp2, N);
        vec3 dp1perp = cross(N, dp1);
        vec3 T = dp2perp * duv1.x + dp1perp * duv2.x;
        vec3 B = dp2perp * duv1.y + dp1perp * duv2.y;

        // construct a scale-invariant frame
        float invmax = inversesqrt( max( dot(T,T), dot(B,B) ) );
        return mat3( T * invmax, B * invmax, N );
    }

    vec3 applyNormalMap(vec3 N, vec3 V, vec2 texcoord)
    {
        // assume N, the interpolated vertex normal and
        // V, the view vector (vertex to eye)
        vec3 map = texture2D( material.normalMap, texcoord ).xyz;
        //#ifdef WITH_NORMALMAP_UNSIGNED
            map = map * 255./127. - 128./127.;
        //#endif
        //#ifdef WITH_NORMALMAP_2CHANNEL
        //  map.z = sqrt( 1. - dot( map.xy, map.xy ) );
        //#endif
        //#ifdef WITH_NORMALMAP_GREEN_UP
        //  map.y = -map.y;
        //#endif
        mat3 TBN = cotangentFrame( N, -V, texcoord );
        return normalize( TBN * map );
    }

```

I recommend that you implement the tutorial to see where your normals are. From the results it seems your resulting normals are a big mess either from normal maps or else from bad lighting algorithm.

I dislike the way he does normals in that tutorial, instead I implemented this other way, which does not completely destroy your normal data so it's simple to debug and understand.

Sorry I do't have a one line fix but hopefully this helps. Good luck.

# Answer
> 1 votes
**Fragment Shader**

```
struct Material {
    sampler2D texture_diffuse1;
    sampler2D texture_specular1;
    float shininess;
};

```

Does not match:

**Mesh.h**

```
string number;
string name = this->textures[i].type;
if(name == "texture_diffuse")
    ss << diffuseNr++; // Transfer GLuint to stream
else if(name == "material.texture_specular")
    ss << specularNr++; // Transfer GLuint to stream
else if(name == "material.texture_normal")
    ss << normalNr++; // Transfer GLuint to stream
else if(name == "material.texture_height")
    ss << heightNr++; // Transfer GLuint to stream

```

Your names have to match your shader names.

**Fixed Mesh.h**

```
string number;
string name = this->textures[i].type;
if(name == "material.texture_diffuse")
    ss << diffuseNr++; // Transfer GLuint to stream
else if(name == "material.texture_specular")
    ss << specularNr++; // Transfer GLuint to stream
else if(name == "material.texture_normal")
    ss << normalNr++; // Transfer GLuint to stream
else if(name == "material.texture_height")
    ss << heightNr++; // Transfer GLuint to stream

```

---
Tags: opengl, shaders, glsl
---