# Question
Title: Calculating damage reduction of armor parts
I am currently implementing a turn-based puzzle/RPG game.
The situation now is the following: The player can have up to 4 armor parts: Helmet, Gloves, Trousers and upper-body-armor.
I actually planned to calculate the damage reduction like this:
*ActualDamage = Damage\*(1-helmetReduction-gloveReduction-trousersReduction-upperArmorReduction)*

But I see some problems with that: If the player collects 4 armor parts with, let's say 0.3, 0.4, 0.2, 0.1 reduction, then the damage will be removed completely.
This is not what I want to achieve.
So I am no looking for a way to consider all armor parts, but have a different formular for calculating then together.
I know a way would be to have an upper limit of damage reduction, but that seems like a dirty hack for me.

I know there are games which already do this (e.g. Diablo 3). In Diablo 3 all armor parts add to the global toughness value which then seems to reduce the damage.
How could such a thing be done for example?

**Edit:**
To clarify: I am acutally looking for a way/formula which takes every armor piece into account and gives an overall damage reduction value, which is, in every case \< 100%.

# Answer
> 7 votes
You could reduce the damage for each piece individually. That way you never reach 0 unless a piece reduces it by 100%. You can get very low though.

You could also make the different pieces never total 100%.

* Helmet max 15%
* torso max 20%
* arms max 10%
* legs max 10%

Max damage resistance would be 55% like that.

You could also go with a much more refined system as complicated as you want. I like this system:

* Attacker will do 100 `damage`.
* Defender has 50 `armor`
* `damageMultiplier` = `damage` / `(damage + armor)`
* `finalDamage` = `damage` * `damageMultiplier`

In this case the multiplier will be .66. So a total of 34% will be absorbed. Let's hava a look at a extreme example.

```
damage = 100;
armor = 1000;
damageMultiplier = damage / ( damage + armor); // .09
totalDamage = damage * damageMultiplier; // 9 damage, 91 damage absorbed by a whooping 1000 armor.

```

This is a fairly simple system. It also allows you to work magic on the damage and armor. Add bonuses and multiply it by the players strength and if you do this formula last you will always be good.

# Answer
> 2 votes
Think ease of use.

You always have to start with what you want to achieve first.

And it can all be made simple - I want the weakest unit to kill the weakest player with 20 hits. I want the strongest unit to kill the strongest player with 10 hits. The rest is just curving the increments between them.

You can build any game on these two considerations alone. Anything else is just style.

Chasing individual numbers on individual pieces, without a good overall concept results in those games where you get so beefed up, nothing is a threat to your shiny armor, and any monster is just a tedium waiting to happen - a formality that you have to resolve by clicking on it to kill it.

E.G.

Think of your maximum reduction - then you always know what the max possible is. Then spread your reduction among your sources. These numbers almost fall in place themselves if you have the starting concept clear.

If you know 50% dr is the max you can have. You can easily split that between the sources. Say 50% (25%) to the armor, 15%(7.5%) to boots, 35%(17.5) to helmet. Round one up the other one down if you want to lose the decimals.

And group things, damage - or * (armor set 1) .... (armor set = the pieces) Its way easy to have configs that work with group attributes.

Now... people usually go for % multipliers because its easy. Slapping 50% damage reduction on something guarantees you get the same result even if you do 10 damage or 904004 damage. And its an easy shortcut in the original concept, put the good gear on - you die in 20 hits, take it off you die in 10.

If you really want to toy with damage reduction however you simply subtract damage and give flat damage reduction. You can scale it a lot better, and its portrayed more meaningfully to the player. If you ignore functionality - people would usually like to have 50'000 damage reduction as opposed to 50%. Then a guy can boast having 10'000 more than the other guy - instead of 0.7 percent.

Most designers don't bother and just slap some numbers to get along with the ride. Blizzard is known for actually planning ahead for their dps outputs. And that is much better seen in diablo 2 rather than 3. Even though diablo 2 has a bunch of useless modifiers the low end and the high end are done very comfortably.

If you can plan your dps scale. You can know your weakest unit will never be too weak, and your strongest unit will never be too strong.

Diablo 3 failed massively on damage progression when it first came out - it don't know how it is now but progression was horrid, the developing player hit a rock solid wall, they were unable to penetrate without being stuck in boring no challenge land for a long time. Whereas in diablo 2 you could get in the challenge areas and do some damage, but anything there could kill you in a couple of easy hits - so your play focused on controlling the field so you can soak your attackers with damage, without giving them much room to retaliate. That allows people who want a challenge, to try it. Everybody else who don't want hardship can always go back to the lower/safer/easier areas and re-grind - but being unable to challenge harder mobs due to the brick wall scaling of difficulty injects massive boredom into gameplay.

Few people really ever understand damage is all about pacing and threat.

# Answer
> 2 votes
**ActualDamage = Damage\*(0.99^Armor)**

This gives a diminishing return. With any amount of armor, the 1st armor reduces damage by 1% and each subsequent armor only reduces damage by **1% OF THE REMAINING damage.**

With this method, when you have 0 armor you take full damage, but no matter how much armor you have, you will never reach 100% damage reduction.

I think you will find this method very elegant and easy to implement. It scales infinitely because you can have millions of armor and still take damage against mobs that deal adequate damage.

# Answer
> 1 votes
You'll need to create some way to control the damage passing through.

For example: light armor has a maximum reduction of 75%, medium 85% and heavy 95%. If the total reduction combined is above the number, use that value instead.

You could also create a weighed reduction: say the player wears one heavy, two medium and one light piece of armor: (95+85+85+75)/4 =85% maximum redudtion.

Thus if the player's combined armor is below 85%, the player's armor is used, otherwise it is capped at 85%.

# Answer
> 1 votes
Don't have the damage reduction be additive, have it multiplicative.

```
Damage = Damage *
         (1.0 - helmetReduction) *
         (1.0 - gloveReduction) *
         (1.0 - trousersReduction) *
         (1.0 - upperArmorReduction)

```

Each layer of armor reduces not the complete damage, but the damage remaining from the previous layer. As long as no *single* layer reaches 1.0, you will always have a bit of rest damage. You can also scale this system upwards and add additional armor slots later without breaking anything.

# Answer
> 0 votes
I think it would make the most sense to use percentage based reduction, if you don't want to remove damage entirely.

For example different pieces could provide different percentages of damage reduction:

* Helmet - 5%
* Gloves - 5%
* Chest - 15%
* Legs - 10%

Total reduction = 35%

Then for example if your character is hit for 40 points of damage you would do the following:

```
40 - ((40 / 100) * 35)

```

This gives you the damage value of 26 that your character would take

Edit: having read the comments of the Op. There will have to be a hard cap on the percentage avoidance if he wants to avoid 100%. The other way to do this would have a maximum avoidance for each type of armor that does not add up to 100%.

As it is also not described how these armor prices come to be. If they are pre determined values then it would be trivial to make sure they don't add up to 100%. If they are randomly generated simply put a cap on the maximum for each type.

# Answer
> 0 votes
I was having the same issues, but after getting sleep, i figured out a method that may work, the way I'm doing it is armor rating that can increase infinitely, monsters damage will always increase as well,

So as for damage reduction i came up with this

For every 5 AR will give +1 to damage reduction divider If the damage that is being dealt to you would be equal or less to your AR it would be divided by said divider value, if damage is higher, the difference would then be included with the divider

Example: AR: 24 (since 5 only goes into 24 4 times, the divider is 4) Vs Damage: 36 (the difference is 12, so the remainder is 24)

Divide the AR by the divider and add it to the difference

24/4 = 6 + 12 = 18 damage taken out of 36

---
Tags: mathematics, game-design, rpg
---


# Question
Title: Direct3D & Assimp Texture is inverted weirdly!
I'm working on a rendering engine but even on the first mesh is something wrong. I use assimp for mesh importing! In the Assimp Viewer it looks correct:

And in my software it looks like this:

Look at the text and you will see it is weirdly mirrored. I'm using front counter clockwise vertex winding and the texture is flipped on y coordinate - if I don't then it is completely wrong. I already tried disabling front counter clockwise winding but the texture is still inverted!

Does anybody know what else I can try?

# Answer
> 1 votes
The texture is correct but the model itself is inverted. This is probably at some stage due to changing between right-handed and left-handed co-ordinate systems.

You should try and check which handedness your importer expects, and perhaps change one of the axes to negative values.

---
Tags: c#, c++, textures, directx, directx11
---


title: Save game statistic in simple method?

text:
# Question
Title: Save game statistic in simple method?
I wrote a script to save and load game statistic. It works fine. In this script, two levels have it own score and timer. So, I have to write level by level it own score and timer. The issue is if I have 100 or 200 levels in my game. I have to write for every level. Yes will work, but will take time. So, I was thinking if there any simple method to shift the number of lines like use List or anything else ?

```
public gameStatic dr;

void Awake()    {
    Load_game_end();
}

   public void Save_game_end()  {
    BinaryFormatter bf = new BinaryFormatter();
    FileStream data_file = File.Create(Application.persistentDataPath + "/WarWorld.datt");

    level_static data = new level_static();
    data.level1tv = dr.level1t; // level one
    data.level2tv = dr.level2t; // level two
    //
    data.timer1 = dr.finalTime1; // level one
    data.timer2 = dr.finalTime2; // level two
    //
    data.total_money = dr.total_money;

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

    Debug.Log("Game full saved");

}

public void Load_game_end() {
    if (File.Exists (Application.persistentDataPath + "/WarWorld.datt"))
    {
        BinaryFormatter bf = new BinaryFormatter();
        FileStream data_file = File.Open (Application.persistentDataPath + "/ballworlds.datt", FileMode.Open);
        level_static data = (level_static)bf.Deserialize(data_file);
        data_file.Close();

        dr.level1t= data.level1tv;
        dr.level2t = data.level2tv;
        //
        dr.finalTime1 = data.timer1;
        dr.finalTime2 = data.timer2;
        //
        dr.total_money = data.total_money;

        Debug.Log("Game full loaded");
    }

    else {
        Debug.Log("save not found");
    }

}

public void delete_save_file() {
    File.Delete(Application.persistentDataPath +"/WarWorld.datt");
    Debug.Log("delete save file");

}

[Serializable]
class level_static
{
    public float total_money;
    //
    public float level1tv; // height score level 1
    public float level2tv;

    //
    public float timer1; //  level 1 timer
    public float timer2;

}

```

# Answer
> 2 votes
```
   public void Save_game_end()  {
    BinaryFormatter bf = new BinaryFormatter();
    FileStream data_file = File.Create(Application.persistentDataPath + "/WarWorld.datt");

    level_static data = new level_static();
    data.level1tv = dr.level1t; // level one
    data.level2tv = dr.level2t; // level two
    //
    data.timer1 = dr.finalTime1; // level one
    data.timer2 = dr.finalTime2; // level two
    //
    data.total_money = dr.total_money;

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

    Debug.Log("Game full saved");

}

```

instead of that maybe exclude data.level to params?

```
...Save_game_end(level, finalTime){

```

and for class level\_static create custom constructor to set level, timer, money. Use collection to save all levels and timers.

**Example:**

```
   public gameStatic dr;

public List<level_static>  levelStaticList;

void Awake()
{
    Load_game_end();
}

public void Save_game_end()
{
    BinaryFormatter bf = new BinaryFormatter();
    FileStream data_file = File.Create(Application.persistentDataPath + "/WarWorld.datt");

    bf.Serialize(data_file, levelStaticList);
    data_file.Close();

    Debug.Log("Game full saved");
}

public void Load_game_end()
{
    if (File.Exists(Application.persistentDataPath + "/WarWorld.datt"))
    {
        BinaryFormatter bf = new BinaryFormatter();
        FileStream data_file = File.Open(Application.persistentDataPath + "/ballworlds.datt", FileMode.Open);
        List<level_static> data = (List<level_static>)bf.Deserialize(data_file);
        data_file.Close();

        //if you cant return list from file then try something different (deserialize one by one in the foreach for an example and add to list).

        levelStaticList = data;

        Debug.Log("Game full loaded");
    }

    else
    {
        Debug.Log("save not found");
    }

}

public void delete_save_file()
{
    File.Delete(Application.persistentDataPath + "/WarWorld.datt");
    Debug.Log("delete save file");

}

[Serializable]
class level_static
{
    public level_static(float level, float timer, float money)
    {
        this.level = level;
        this.timer = timer;
        total_money = money;
    }

    public float total_money;
    //
    public float level;

    //
    public float timer;
}

```

---
Tags: unity
---


# Question
Title: Unity SphereCast HitInfo Give me an interpolation of the normal surface?
I'm doing a SphereCast for a GroundCheck of a player. I have my Raycast hitInfo, and here in the picture at the left, I Debug.drawRay in black the direction of the hitInfo.normal every frame

It seems like hitInfo.normal give me an interpolation of the normal, not the real normal of the surface...

I only want the real normal of the surface... (red normals I have draw on the right), and may be the green one (the perfect normal between 2 surface), but if I can have only the red one, it would be great

How can I do it ?

Thanks !

# Answer
> 1 votes
Ok, I found an temporary solution that give me the red normal IF I want to keep my SphereCast Test, I have to do a second Raycast for having this surface normal (C'mon Unity, why we haven't a hitInfo.surfaceNormal information ??)

```
//here my sphereCast in someFunction
RaycastHit hitInfo;
Vector3 position;     //origin of the sphereCast
float radiusRayCast;  //radius of the sphereCast
Vector3 dirCast;      //direction of the SphereCast
float magnitudeCast;  //magnitude of my sphereCast
int layerMask;        //layerMask used for both SphereCast & Raycast
float rayCastMargin;  //margin magnitude of the second raycast

if (Physics.SphereCast(position, radiusRayCast, dirCast, out hitInfo,
                               magnitudeCast, layerMask))
{
    //here my second raycast Test
    Vector3 surfaceNormal = GetSurfaceNormal(position,
                                             radiusRayCast,
                                             magnitudeCast,
                                             radiusRayCast,
                                             hitInfo.point,
                                             rayCastMargin,
                                             layerMask);
}

```

And here my static fonction, who calculate:

```
public static Vector3 GetCollisionCenterSphereCast(Vector3 castOrigin, Vector3 direction, float magnitude)
{
    Vector3 collisionCenter = castOrigin + (direction * magnitude);
    return (collisionCenter);
}

public static Vector3 CalculateRealNormal(Vector3 origin, Vector3 direction, float magnitude, float rayCastMargin, int layermask)
{
    //Ray ray = new Ray(origin, direction);
    RaycastHit hit;
    if (Physics.Raycast(origin, direction, out hit, magnitude + rayCastMargin, layermask))
    {
        //Debug.Log("Did Hit");
        return (hit.normal);
    }
    Debug.DrawRay(origin, direction.normalized * (magnitude + rayCastMargin));
    Debug.LogWarning("we are not suppose to miss that one...");
    return (Vector3.zero);
}

public static Vector3 SetSurfaceNormal(Vector3 castOrigin, Vector3 direction,
        float magnitude, float radius, Vector3 hitPoint,
        float rayCastMargin, int layerMask)
{
    Vector3 centerCollision = GetCollisionCenterSphereCast(castOrigin, direction, magnitude);
    Vector3 dirCenterToHit = hitPoint - castOrigin;
    float sizeRay = dirCenterToHit.magnitude;
    Vector3 surfaceNormal = CalculateRealNormal(centerCollision, dirCenterToHit, sizeRay, rayCastMargin, layerMask);

    Debug.DrawRay(centerCollision, surfaceNormal, Color.black, 5f);
    return (surfaceNormal);
}

```

As you see in this pictures below, black Ray are indeed the exacte normal of the surface, and the yellow Ray, the normal created by the SphereCast. It works !

Unfortunatly, it demand a second Raycast, and we can't have the perfect normal Intersection, but for now, it's good enought for me.

---
Tags: unity, raycasting, mesh, meshcollider
---


title: LibGDX: Change Direction

text:
# Question
Title: LibGDX: Change Direction
I want to move an object on screen and when the object intersect with the obstacle he change the position, for example he's going to the right and he found an obstacle, so he change to the left.

```
    directionObj = 2;
    if(Intersector.overlaps(obj, screen)){
        posBall -= directionObj ;
    }else{
        posball += directionObj;
    }

```

but when the object found the obstacle he dont change the direction

---

\[edited\]

this is my render. When the ball intersect with the screen, he dont change the direction

```
public void render () {
    fallSpeed++;
    if (posYBall > 0) {
        posYBall -= fallSpeed;
    }
    spriteBatch.begin();
    spriteBatch.draw(ball[1], posXBall, posYBall);
    spriteBatch.end();
    ballDirection = 2;
    if (Intersector.overlaps(circleBall, screen)) {
        posXBall = ballDirection;
    } else {
        posXBall += ballDirection;
    }

```

# Answer
> 3 votes
Make sure you declare ballDirection somewhere where it will retain its value throughout multiple cycles/frames. For instance, in the "create()" function. If you declare it as a positive value every frame, it will always try to go right first.

```
if(Intersector.overlaps(circleBall, screen))
{
  ballDirection *= -1 ;
}
posXBall += ballDirection;

```

This will always add the speed to the balls current position, and only change the direction when a collision is detected.

---
Tags: libgdx
---


# Question
Title: Unity - Instantiate GameObject from client on Network
I am building a game where a weapon shoots `prefab` bullets. I am trying to make this a multiplayer game, so the bullets need to be spawned into the Network.

What happens right now is that if I shoot a bullet from a `host`, the bullet is shot, but doesn't appear on the `client` screen. If I shoot the bullet from the `client`, the bullet doesn't appear on either screen. In fact, the function `CmdShoot()` isn't even called, as the `Debug.Log("Hello")` is not called. Here is the current code:

```
public class Gun : MonoBehaviour
{

    private GameObject bulletPrefab;

    void Update()
    {
        if (Input.GetMouseButtonDown(0)) {
            owner.GetComponent<PlayerSetup>().CmdShoot(bulletPrefab, transform.position, owner.name, GetComponentInParent<Weapon>().angle);
        }
    }
}

```

```
public class PlayerSetup : NetworkBehaviour
{

    void Start ()
    {
        // Disable components if not local player
    }

    [Command]
    public void CmdShoot(GameObject bulletPrefab, Vector3 position, string playerName, float angle)
    {
        Debug.Log("Hello");
        GameObject bullet = Instantiate(bulletPrefab, position, Quaternion.identity);
        bullet.name = "bullet: " + playerName;
        bullet.GetComponent<Rigidbody>().AddForce(Quaternion.AngleAxis(angle, Vector3.forward) * Vector3.right * bulletPrefab.GetComponent<Bullet>().force);
        Destroy(bullet, 10f);
        NetworkServer.Spawn(bullet);
    }
}

```

**Edit:**

This piece of code doesn't work either, gives the same result. No error, but the function is also not called. The Input is detected though:

<pre><code>    void Update() {
        if (Input.GetMouseButtonDown(0)) {
            CmdShoot();
        }
    }

    [Command]
    void CmdShoot()
    {
        Debug.Log("Shoot");
        GameObject bullet = Instantiate(gunComponent.bulletPrefab, gun.position, Quaternion.identity);
        bullet.name = "bullet: " + transform.name;
        bullet.GetComponent<Rigidbody>().AddForce(Quaternion.AngleAxis(GetComponentInChildren<Weapon>().angle, Vector3.forward) * Vector3.right * gunComponent.bulletPrefab.GetComponent<Bullet>().force);
        Destroy(bullet, 10f);
        NetworkServer.Spawn(bullet);
    }

```
</code></pre>

# Answer
First things first. You should inherit from the proper base class. **NetworkBehavior** is the way to go.

Then there are conditions that your prefab should meet before getting passed to the method. According to documentation the GameObject should have a **NetworkIdentity** attached in order to be transmitted. The complete list of argument restrictions can be found here.

There is also one more catch. The **CommandAttribute** can be used for Players invoking the method on Server side from Client side only. I think the intended usage is input syncing rather than a RPC-like behaviour.

For Server to client transmission use the ClientRpcs.

Hope this pushes you in the right direction. Cheers!
> 1 votes

# Answer
You want to make sure it is the localplayer shooting, and if not then just remove and/or return out of Update()

```
void Update() {
if(!isLocalPlayer){Destroy(gameObject); return; }
    if (Input.GetMouseButtonDown(0)) {
        CmdShoot();
    }
}

```
> 0 votes

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


# Question
Title: how can i set the y rotation of an object equal to another objects y rotation without rotating it on all the rest of the axis
Here is my attempt`transform.rotation = new Vector 3(0,pivot.rotation.y,0);`

I don't know what to do can you help in any way? I have a camera that pivots around the player, but i need the player to rotate around the y axis of the pivot.

thanks in advance .

# Answer
> -1 votes
Just modify `gameObject.transform.rotation.y` to equal the value of `pivot.rotation.y`

```
transform.rotation.y = pivot.rotation.y;

```

This is the best I can come up with. Rotations are quite confusing at times because of the Quaternion stuff they keep using. I don't know why they do it, they just do. It's why I stay away from everything that has a "w axis."

---
Tags: unity, rotation
---


# Question
Title: SDL render surface from byte array efficiently
In my current project I need to fill a 256x224 screen with the pixel values from an array. The array is declared this way:

```
uint8_t *vram = new uint8_t[7168];

```

So as you might have noticed, every bit in this array represent one pixel in the screen (256 x 224 / 8 = 7168). My current attempt to render a screen looks like this: (it is executed at 60hz)

```
int x = 0;
int y = 0;
for (int i = 0; i < 7168; i++)
{
    //read the byte
    uint8_t b = vram[i];
    for (int j = 7; j >= 0; j--)
    {
        //read 1 bit from the original byte
        bool pixel = (b >> j) & 1;
        SetPixel(x, y, pixel);

        //if end of line reached, go to next line
        if (((x + 1) % 256) == 0)
        {
            x = 0;
            y++;
        }
        else
        {
            x++;
        }
    }
}

```

and my `SetPixel` function:

```
void SetPixel(int x, int y, Uint32 pixel)
{
    Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * 4;
    *(Uint32 *)p = pixel;
}

```

My window and surface declarations:

```
window = SDL_CreateWindow("Window", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 256, 224, SDL_WINDOW_OPENGL);
surface = SDL_GetWindowSurface(window);

```

Currently I have two big problems:

* My surface isn't been changed, doesn't matter what I try
* I'm not even sure if this method is efficient, looking at profiling data from Visual Studio it doesn't seem to be

So, how could I render a black and white screen from an byte array in a somewhat efficient way?

Any help will be very appreciated!

# Answer
It seems like you have 2 questions here: 1. Why doesn't this code change the surface? 2. Is there a way to do this faster?

# Why doesn't this code work?

For me, opening a window, grabbing the screen surface, and writing to the pixels with the function you have there works perfectly fine, so the problem is likely not in your `SetPixels` function. Instead, it's likely with your surface. There are a couple of possible problems here; most likely, however, is that you simply forgot to call `SDL_UpdateWindowSurface( window )` after making your changes. If this doesn't fix it, make sure that:

1. Your surface is from your window. Surfaces can come from a lot of different places in SDL, so make sure this surface is indeed the surface that backs the window. You can get this from `SDL_GetWindowSurface( window )`
2. Depending on the surface, you may need to lock it and unlock it with `SDL_LockSurface()` and `SDL_UnlockSurface()`, modifying the pixels in between those two calls.

# How can it be faster?

Ideally, by using more memory. The best thing to do would be to do away with the bit-array altogether and simply use a texture (or `SDL_Surface`) that is the same size as the window surface. Then, copy the whole thing, perhaps with an `SDL_BlitSurface()` or, even better, using an `SDL_Renderer` and `SDL_RenderCopy()`. The main thing slowing down the code is unpacking the bits. If you can store the whole texture at once, you'll be able to skip that step entirely. Then, when copying a giant texture all at once, SDL will be able to take advantage of all the CPU's efficient memory copying features (if using `SDL_Surface`s) or all of the extreme texture-copying might of the GPU (if using an `SDL_Renderer`).

If this isn't possible, the more pixels you can copy at once, the better off you'll be.

The SDL docs demonstrate clearing an entire surface on the CPU using the call `SDL_memset(surface->pixels, 0, surface->h * surface->pitch)` (Source). In your case, `SDL_memcpy` may be a more useful call. You should try to expand the pixels out into a block of memory several bytes long (the more the better), and then call something like `SDL_memcpy(surface->pixels, eightPixels, sizeof(Uint32_t) * 8)` if you were copying eight pixels at once, for example. I don't have an exact working sample of this, but it should give you a useful direction to move in.
> 4 votes

---
Tags: c++, rendering, sdl2, pixel
---


# Question
Title: How do I get an NPC to follow the player(and stop when it gets within range)
I'm making a game where you have a friend follow you. I have a script that partly works, but when the friend exits the trigger, it won't follow the player.

How do I get the friend to follow the player once indefinitely, or until it hits the trigger again?

Here is the script:

```
public Transform friend;
private int movespeed;

public int speed;
public Rigidbody rb;

// Use this for initialization
void Start()
{
    speedup();
}

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

    transform.LookAt(freind);
    Vector3 eulerAngles = transform.rotation.eulerAngles;
    eulerAngles.x = 0;
    eulerAngles.z = 0;
    transform.rotation = Quaternion.Euler(eulerAngles);

    rb.AddRelativeForce(0, 0, movespeed);

}

public void OnTriggerStay(Collider other)
{

    if (other.tag == "Player")
    {
        movespeed = 0;
    }
    else
    {
        speedup();
    }
}

public void speedup()
{
    movespeed = speed;
}

```

# Answer
> 0 votes
I've found the answer! I just had to add an on Trigger exit statement with the speed up function inside:

```
public Transform freind;
private int movespeed;

public int speed;
public Rigidbody rb;
// Use this for initialization
void Start()
{
    speedup();
}

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

    transform.LookAt(freind);
    Vector3 eulerAngles = transform.rotation.eulerAngles;
    eulerAngles.x = 0;
    eulerAngles.z = 0;
    transform.rotation = Quaternion.Euler(eulerAngles);

    rb.AddRelativeForce(0, 0, movespeed);

}

public void OnTriggerStay(Collider other)
{

    if (other.tag == "Player")
    {
        movespeed = 0;
    }

}
public void OnTriggerExit(Collider other)
{
    speedup();
}

public void speedup()
{
    movespeed = speed;
}

```

# Answer
> 3 votes
This code says:

> "As long as I'm still in trigger contact with something...
>
> ...if that thing is tagged 'Player', set move speed to zero
>
> ...otherwise (ie. if that thing is tagged anything else), set move speed to speed"

It looks like you mean that last clause to say "if I'm no longer in trigger contact..." but if we weren't in trigger contact anymore, `OnTriggerStay` wouldn't even be called.

It looks like what you want is something more like:

```
bool isNearPlayer;

void OnTriggerEnter(Collider other) {
    if(other.gameObject.CompareTag("Player"))
        isNearPlayer = true;
}

void OnTriggerExit(Collider other) {
    if(other.gameObject.CompareTag("Player"))
         isNearPlayer = false;
}

```

This toggles a mode flag on & off when we enter & exit trigger range around the player. (Also note that using CompareTag is more efficient than comparing strings with ==)

Then you can use that mode flag in your FixedUpdate method:

```
if(isNearPlayer == false)
    rb.AddRelativeForce...

```

(Even better, since you already have a reference to the player object, you can check its range directly, without waiting to detect trigger contact: `isNearPlayer = (transform.position - friend.Position).sqrMagnitude < stopRange * stopRange);` )

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


# Question
Title: How do i prevent my player from walking through mesh collider
I have a character being moved using rigidbody.moveposition and I have an floating lowpoly island with a mesh collider. When my player walks into a steep slope or a wall, it passes right through. I assume this is because the mesh collider isn't thick enough but there must be a pretty simple fix. If anyone knows how to fix this it would be much appreciated.

Here's the code for the movement of my character.

```
private void Movement()
{
    if (AnimController.GetInteger("AnimPar") != 3)
    {
        if (Input.GetKey(KeyCode.LeftShift))
        {
            walkSpeed = initialWalkSpeed * 2;
        }
        else
        {
            walkSpeed = initialWalkSpeed;
        }

        if ((Forward && Right) || (Forward && Left) || (Backward && Right) || (Backward && Left))
        {
            walkSpeed *= .7f;
        }

        if (Forward)
        {
            Delta += transform.forward * walkSpeed * Time.deltaTime;
        }

        if (Backward)
        {
            Delta -= transform.forward * walkSpeed * Time.deltaTime;
        }

        if (Right)
        {
            Delta += transform.right * walkSpeed * Time.deltaTime;
        }

        if (Left)
        {
            Delta -= transform.right * walkSpeed * Time.deltaTime;

        }

        rb.MovePosition(new Vector3(Delta.x, transform.position.y, Delta.z));
    }
}

```

# Answer
I think you should use `AddForce` instead of `SetPosition` on your rigid body. Setting the position will place the body at the new position, but adding a force will cause the body to move through the simulation steps. Make sure you use continuous collision detection.
> 2 votes

---
Tags: collision-detection, movement, collider, clipping, meshcollider
---


# Question
Title: Is there a way to easily make 3d models and textures for people with no prior experience?
I want to make a game, but I need assets. I am wondering if I should make them by myself even though I never made any textures or 3d models before. Are there technologies that allow you to easily make them? What would you recommend me to do?

# Answer
You can most definitely do this, there are so many great tutorials and books for about every kind of modeling software out there. YouTube, Blender LinkedIn Learning, Pluralsight ect…

I and many others are always browsing and for and buying unique art and models to use in creations. you can then create a sight and or find all the good sites that you can place your content on and they will keep it up and selling for a small cut of profits. Just to name a couple Turbo Squid, and GameDevMarket pretty good options they have pretty wide global advertising ect. people are always browsing for unique stuff whether free or paid. Same with the Unity asset store or unreal engine marketplace those are also great spots to put art and models for creators to buy.

as far as different software options. that will be personal preference but I enjoy working with blender, probuilder in unity, gimp, cinema 4d is pretty great also. But id also get the trials and tutotorials to get some experience with some mainstream stuff like Maya, mudbox ect..

Dive in and make some good stuff and you will live the dream ;)
> 1 votes

# Answer
I'm definitely not a specialist in any aspect of the visual part of game development but I figured if all I did was copy others' assets then I would never learn to model or animate so I took up blender. If I were you that's what I would do. Download blender and take it from there, it's free and it'll teach you the basics of 3D modelling and animation.
> 1 votes

# Answer
I like the procedural approach more, I suggest Houdini or the Grasshopper plugin for Rhino, if you need more refined meshes that need hand modeling, you can polish using zBrush. It will take you longer to learn but you will have a powerful toolset that lets you iterate your geometry just by adjusting some sliders. For texturing I recommend Substance Painter as it is also procedural. There are plenty of tutorials and if you come from a programming background everything will just click, if you don't what you'll learn can definetely be applied to any kind of software development, so in any case is a win win if you go with proceduralism.
> 1 votes

---
Tags: textures, 3d-modeling
---


title: Split tiles into Chunks [2D]

text:
# Question
Title: Split tiles into Chunks [2D]
I'm trying to make a Chunk class for my Tile class creating Chunks of 25 Tiles each, But for some reason it doesn't work correctly Tile.cs extends Sprite.cs

```
  class Tile : Sprite
    {
        public TileType TileType { get; set; }

        public Tile(Texture2D texture, Vector2 position, SpriteBatch spriteBatch) : base(texture, position, spriteBatch)
        {
        }
    }

```

Sprite.cs

```
    class Sprite
    {
        public Vector2 Position { get; set; }

        public Texture2D Texture { get; set; }

        public SpriteBatch SpriteBatch { get; set; }

        public Sprite(Texture2D texture, Vector2 position, SpriteBatch spriteBatch)
        {
            this.Position = position;
            this.Texture = texture;
            this.SpriteBatch = spriteBatch;
        }

        public virtual void Draw()
        {
            SpriteBatch.Draw(Texture, Position, Color.White);
        }
    }

```

My Chunk.cs

```
class Chunk : Sprite
    {
        public Tile[,] Tiles { get; set; }

        public const int CHUNK_SIZE = 25;

        public Chunk(Texture2D texture, Vector2 position, SpriteBatch spriteBatch) : base(texture, position, spriteBatch)
        {
            Tiles = new Tile[CHUNK_SIZE, CHUNK_SIZE];

            GenerateChunks();
        }

        public void GenerateChunks()
        {
            for (int x = 0; x < CHUNK_SIZE; x++)
            {
                for (int y = 0; y < CHUNK_SIZE; y++)
                {
                    Vector2 tilePos = new Vector2(Texture.Width * x, Texture.Height * y);
                    Tiles[x, y] = new Tile(Texture, Position, SpriteBatch);
                }
            }
        }

        public override void Draw()
        {
            foreach (var tile in Tiles)
                tile.Draw();
        }
    }

```

And my World.cs

```
 class World
    {
        float NoiseValues { get; set; }

        public Chunk[,] Chunks { get; set; }

        public SpriteBatch SpriteBatch { get; set; }

        public Texture2D Texture { get; set; }

        public int Height { get; set; }

        public int Width { get; set; }

        public const int CHUNK_TILE_SIZE = 400;

        private float NoiseScale = 0.1f; //Smaller the scale the better caves

        private Random Random;

        public World(SpriteBatch spriteBatch, Texture2D texture, int x, int y)
        {
            this.Height = y;
            this.Width = x;

            this.SpriteBatch = spriteBatch;

            this.Texture = texture;

            Chunks = new Chunk[x, y];

            Random = new Random();

            Simplex.Noise.Seed = Random.Next();

            GenerateBasicWorld();
        }

        public void GenerateBasicWorld()
        {
            for (int x = 0; x < this.Width; x++)
            {
                for (int y = 0; y < this.Height; y++)
                {
                    NoiseValues = Simplex.Noise.CalcPixel2D(x, y, NoiseScale); //Just a simplex noise for further generation doesn't affect current gen

                    Vector2 chunkPos = new Vector2(16 * x, 16 * y);
                    Chunks[x, y] = new Chunk(Texture, chunkPos, SpriteBatch);

                    System.Diagnostics.Debug.WriteLine(NoiseValues);
                }
            }
        }

        public void Draw()
        {
            foreach (var chunk in Chunks)
                chunk.Draw();
        }
    }

```

My initialization goes like this:

```
World world = new World(spriteBatch, tilesTexture[0], 5, 5);

```

What I'm currently getting is 5x5 tile set drawn.

I'm expecting to get 5 chunks on X axis and 5 chunks on Y axis, each chunk has to be made of 25 tiles, am I missing something out? Thanks.

# Answer
Ok I solved it by adding in the size of each chunk not overwriting, @Jay & @Felsir were right about me, redrawing the tiles on each other, thats the final result I'm having in my Chunk.cs

```
        public void GenerateChunks()
        {
            for (int x = 0; x < CHUNK_SIZE; x++)
            {
                for (int y = 0; y < CHUNK_SIZE; y++)
                {
                    Vector2 newPosition = new Vector2(Texture.Width * x, Texture.Height * y);
                    newPosition += Position;
                    Tiles[x, y] = new Tile(Texture, newPosition, SpriteBatch);

                }
            }
        }

```
> 1 votes

---
Tags: monogame
---


# Question
Title: How can the player select his weapon among many?
I'm working on the prototype of my game, I want one of the options to have a very large amount of weapons. I have searched for tutorials, but I have only found weapons changes where the weapons have already been loaded in the scene from the inspector, like this https://youtu.be/Dn\_BUIVdAPg where they are only activated and deactivated. But I want a game like dofus where there are hundreds of weapons, I think I have a data file of the weapons and so, I can load the correct model of the weapon. How can I get the model loaded?

I have read other tutorials regarding the AssetBundle, but I think that is when you need to download the models from a server for example, but I just want to load them from the same project.

sorry for the bad english

# Answer
If you don't want to attach 100 weapon child-objects to your PlayerCharacter game object, then you could have a "Weapon Manager" behaviour in the scene which holds an array of prefabs with every weapon in the game. When a character switches weapons, `Destroy` the weapon it is currently holding and `Instantiate` the new weapon from the list of prefabs in the WeaponManager.

In this case, all weapons are loaded when the scene loads. That means weapon switching will be instantaneous. But the cost for that is a longer scene loading time and more memory consumption. You need to check how much time and memory this is for your particular game and if it's notable. When you are creating a sprite-based game like Dofus, then there is a good chance that this is actually negligible, but you might still be surprised (for example, one thing which is often underestimated are audio clips).

If you want to load the weapon prefabs the moment they are equipped, then you can put those prefabs into the directory `[your Project]/Assets/Resources` and load them at runtime with `Resources.Load()`. But keep in mind that when your weapons are detailed models with high resolution textures and high-quality sound samples, then switching weapons that way might cause a slight hickup. You are also responsible for unloading those weapons when they are no longer needed, or you are going to leak memory.
> 3 votes

---
Tags: unity, assets
---


# Question
Title: Efficient way to go about acquiring game assets
I was thinking about buying assets, but I don't want to waste time and want to acquire assets as fast as possible, and acquire a large amount of them, because I want to make several different games from the assets (rpg, action, shooter, etc.) Also, I want to commercialize the game, so what would you recommend me doing?

# Answer
> 1 votes
I'm not sure if this is on topic, but I'll try to answer anyway: You don't *need* to pay for your game's assets; That's why things like the Unity Assets store, ue4 store etc.. exist ;)

When it comes to commercializing the game, you really want to check for your assets' licence/s (unless you created them yourself of course), because they tell you *if and how* you can use them in your game.

If the assets are not *free for commercial purposes*, you probably need to pay the artist who created them (again check their licence requirements).

If you don't want to create the assets yourself, there are a whole lot of websites that you can find with a simple search on the web, but for a bit of money you can pay an artist that will make *exactly* what you need, *exactly* how you want; That's the main advantage.

---
Tags: assets, asset-workflow
---


# Question
Title: How can I determine that a user actually followed me to give them an in-game reward?
I have seen many apps where they will reward you if you follow them on social media. However, all you need to do is click on the link and then close the browser opened up and you will still be rewarded.

I would like to be able to spread my app through social media. I want people to get a reward only if they follow me so that the game can be spread through social media.

This does nothing if all they have to do is click on a link and then they can close the browser. Is there a way that I can only reward the user if they have actually followed me on social media.

Thanks

# Answer
Theoretically, you could use Twitter's developer API for this. There is a query that will return a given user's followers, which you can then inspect (possibly using the query to convert an ID to a full user object to fill out extra information if needed) to determine if your game's user ID is among the set.

Once you find your game's user ID among the player's followed users, you know they've followed the account you want and can reward them accordingly.

Naturally, you will need to get the user to give you their Twitter ID in order for this to work. Since the results of the API are likely eventually-consistent, you may need to implement the confirmation as a periodic poll while your game is running, rather than expecting it to return the correct data *immediately* after the user comes back from the "follow us on Twitter" flow.

---

Note that I have *no idea* if this sort of usage falls into what is or is not acceptable to Twitter. The front page of their API says one use-case is "\[evaluating\] Twitter data to inform business decisions," which this could conceivably be, but the examples under that category don't really match.

You should read over Twitter's terms of use for their developer API, and have your lawyer do the same with an understanding of your specific business case. I'd check the restrictions section, particularly the part about "off-Twitter matching."
> 2 votes

---
Tags: ios, social
---


title: How is this rotation done?

text:
# Question
Title: How is this rotation done?
There is a video here that shows how the camera rotates around Leon. The camera rotates around Leon in a circle, this is not difficult, but I don't understand the timing logic.

Once given a short push, the camera keeps rotating for a few more milliseconds.

If the camera would only be rotated during the real mouse movement, the camera would not keep rotating a bit after there is no more mouse movement.

However, in this video, the camera rotates a few more milliseconds even after the last mouse movement.

How could this be accomplished?

Specifically, I would like to ask if somebody can tell me if the developers add some extra movement in the direction of the mouse movement which they then "smooth out", or if they "smooth out" the end of the user's mouse movement.

Thank you!

# Answer
Implementing this sort of momentum in camera motion (or really just about anything) can be done with easing functions.

When the actual input to the camera movement system stops, you have (or can compute, depending on your implementation) the speed at which the camera *was* rotating during the input period. Rather than simply set that speed to zero, jerking the camera to a halt, you apply some sort of easing function to slowly reduce that speed to zero, resulting in the gradual settling you see in the video.

This can be done fairly straightforwardly by adding a new state to your camera. Previously you had two states, explicitly or implicitly: moving and stopped. Add a third state, "settling." You can do this as simply as adding a "settling time left" field to your camera that is zero normally, but which you set to a non-zero value representing the number of seconds the camera takes to smoothly come to stop. Implicitly when this value is non-zero the camera is in the "settling" state.

Then, every update, if the camera is settling, keep it moving based on whatever easing function you've chosen and the time remaining, deduct from the remaining time, and there you are.
> 3 votes

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


# Question
Title: Move camera around player while facing player
My player has the following hierarchy:

```
Hero (GameObject)
      Model (child of "Hero", centered at 0-0-0)
      Camera (child of "Hero")

```

The camera should be allowed to

```
- change its position around the Model in a circle ("rotate around the
  center")
- rotate so that it always faces the Model
- move up and down
- move nearer and further from / to the Model

```

I know how to do that using Quaternions, but as I'm doing this in a coroutine and using Lerp, I found myself in situations where the camera would get right through the model as this was the shortest path between the destination and the target vector.

I would now like to use pure angles (Sin and Cos), preferrably without LookAt. Can somebody share how I would position and rotate the camera according to the angle, perhaps even taking a camera height variable into account as the camera should also be able to move up and down, still facing the player?

That would be the bomb!

# Answer
> 1 votes
Have normalized vector from hero towards camera. Rotate the vector. Place camera at multiplied vector by range(distance). Rotate camera towards hero. Basically rotation around is placing object at the same distance but moving that object in some direction.

Transform.RotateAround

Basically point - is hero position, axis is usually up, if your hero is in vertical position, and angle.

```
Camera.transform.RotateAround(hero.position, Vector3.up, rotationAngle * rotationSpeed);

```

Result reference \- basically this is how I made planets rotate around star. You can access the whole project via link under video.

```
public void RotateAround(Transform transform)
{
    this.transform.RotateAround(transform.position, this._rotationAxis, this._rotationSpeed);
}

private void Update()
{
    this.RotateAround(this._star);
}

private void Awake()
{
    this._rotationAxis = Quaternion.Euler(0f, 0f, 90f) * (this.transform.position - this._star.position).normalized;
}

```

If you want to do it manually you can just store rotation angle, and change it. Using this method you can calculate the vector. Though, it's more for Top-Down, you will have to modify the method to suit your needs.

```
public static Vector3 GetDirectionFromAngle(float angleInDegrees, float localRotationAngle = 0)
{
    angleInDegrees += localRotationAngle;
    return new Vector3(Mathf.Sin(angleInDegrees * Mathf.Deg2Rad), 0, Mathf.Cos(angleInDegrees * Mathf.Deg2Rad));
}

```

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


# Question
Title: Instantiating a GameObject at my desired position not working
I'm sure I am misunderstanding something about Unity vectors or something here. I am brand, brand new to Unity so this is part of the problem.

I am trying to make a simple atomic model and I am trying to model valence electrons.

I've got a game object with two children - the symbol (which is working perfectly), and a child electron.

If an atom has more than 1 valence electrons, I add those as additional child objects.

All of this is working just fine - except for one part. I have a default position for the original child valence electron, but when I try to add additional children and set their positions, they're not anywhere near where they should be.

For example:

My Model:

My base electron:

My additional electrons look like this:

And here is my output - obviously not right:

So here's my function to add additional electrons:

```
  void addElectrons(Rigidbody2D atom)
  {
    AtomData.AtomData atomData = atom.GetComponent<Atom>().atomData;

    if (atomData.ValElec > 1)
    {
      for (int i = 1; i < atomData.ValElec; i++)
      {
        GameObject electron = Instantiate(electron_obj, new Vector2(0.2f, 0), Quaternion.identity) as GameObject;
        electron.name = "Electron " + (i + 1).ToString();
        //electron.transform.localPosition = new Vector3(.02f, 0, 0);
        electron.transform.localScale = new Vector3(.05f, .05f, 0);
        electron.transform.parent = atom.transform;
      }
    }
  }

```

I've tried Vector2 (currently shown above), a new Vector3 in transform.localPosition (shown and commented out), as well as in transform.position (not shown, but similar to localPosition).

What exactly am I doing wrong here? I am strongly guessing that I am misunderstanding the vector math or something here.

# Answer
> 2 votes
So the answer was that I needed to set the localPosition **after** setting the parent.

I thought everything was correctly calculated at runtime (taking parental relationships into account), but apparently if you set the localPosition before setting the parent, it does NOT take the future parent into account at all, and uses another reference point (I assume the origin?) to generate the position.

---
Tags: unity, 2d, objects
---


title: Exclude a certain folder from Unity?

text:
# Question
Title: Exclude a certain folder from Unity?
I work with a small team of three people, and we use the collaborate service within Unity to share our progress. One of the folders we have inside our Unity project is an "OffGame" folder, which includes a tool I created specifically to help with the creation of certain assets. It's not actually supposed to be part of the game, but since I'm often making changes to it, I figured I'd include it in the Unity project. The Unity project temporarily makes use of certain files inside said OffGame folder, however, once the game is done, those files will be moved outside of that folder and integrated into the game proper.

Since that OffGame folder is not supposed to be part of the game and I only included it there to share it to my teammates over the collaborate service, I don't want it to be treated like a normal folder for the game. Specifically, I don't want Unity to create a bunch of useless meta files for each file in that folder, or to act like a stray .js file in there is part of the project. I actually got compile errors because Unity kept thinking it had to include all the .js files in that folder.

How can I make Unity ignore that folder?

# Answer
> 8 votes
During the import process, Unity completely ignores the following files and folders in the Assets folder (or a sub-folder within it):

* Hidden folders.
* Files and folder which start with `.`.
* Files and folder which end with `~`.
* Files and folders named `cvs`.
* Files with the extension `.tmp`.

Source

---
Tags: unity
---


# Question
Title: Phaser: How to call a function inside another function?
So I actually have the following code that works:

```
var player;
var box_tnt;

function create (){
    this.physics.add.collider(player, box_tnt, hitTnt, null, this);
}

//the function hitTnt stop the game because the player died
function hitTnt (player, boxes){
   this.physics.pause();
   console.log('Game Over!');
   textGameOver.setText('GAME OVER');
   player.setTint(0xff0000);
   player.anims.play('default');
   gameOver = true;
}

```

and I want to do something like:

```
var player;
var box_tnt;

function create (){
    this.physics.add.collider(player, box_tnt, hitTnt, null, this);
}

//the function hitTnt stop the game because the player died
function hitTnt (player, boxes){
    gameOver();
    //other stuff here
}

function gameOver (){
    this.physics.pause();
    console.log('Game Over!');
    textGameOver.setText('GAME OVER');
    player.setTint(0xff0000);
    player.anims.play('default');
    gameOver = true;
}

```

but I have the following error message:

> TypeError: gameOver is not a function

Do you have please any ideas how to do it properly?

# Answer
> 1 votes
`gameOver = true;` this overwrites `gameOver`; it used to be a function, now it's a boolean holding `true` value.

---
Tags: javascript, platformer, phaser
---


# Question
Title: Should non-power-of-two textures be resized to be a power of two?
I have a texture that is 1024x900. Should I resize it in Photoshop to be 1024x1024 or leave it as it is?

What about a texture sized 1000x900?

# Answer
Making you textures a power of two is very useful for many reasons:

* When it comes to rendering or the computation and usage of mipmaps, making your texture's dimensions powers of two can avoid some gpu headaches, since it could do some optimization internally;
* You (or the software you use) are going to have custom extensions made by your gpu's drivers manufacturer if you want them to work consistently on your machine. Using special gpu extensions decreases the game's compatibility since not every machine it's going to run on is probably going to implement what it needs to run on. if you stick with powers of 2 then you are guaranteed multi-platform support and good performance, otherwise you may have problems when you try and work with a different machine other than the one you started on;

Let's make a simple example:

Let's say we have two textures, one is 64x64 and the other is 60x60 pixels big; We want to find a given texel in the texture:

### 64x64:

```
Texel = 64 * s + t

```

### 60x60:

```
Texel = 60 * s + t

```

But wait, 64 is a power of two isn't it? That means we can do:

### 64x64:

```
Texel = (s<<6) +t //64 is equal to 2 to the power of 6

```

In the case of 60, we can't quite simplify this calculation as *easily*;

Shifting bytes is *always* going to be faster that multiplying by powers of 2, no matter how fast and clever the calculations we make are.

Other than all this performance-related stuff, power of two textures are also easier to maintain overtime.

Nowdays game engines like Unity can totally handle non power of two textures without much trouble, which is why this is not such a huge issue;

In my experience power of two textures are the best way to make 2D art, since that's exactly what your gpu wants (and expects); also, in terms of maintainability and efficency it's probably the best option in 99% of the cases.
> 1 votes

---
Tags: unity, textures, asset-workflow
---


# Question
Title: Planet Surface Rendering: Precision issues
I have been experimenting with C++ and OpenGL, and I am currently writing a program that renders the surface of a planet; specifically, our moon. It's a modified version of the GPU Gems implementation of Geometry Clipmaps which is normalized to the unit sphere and then offset by a heightmap in the terrain's vertex shader. On small scale scale this works rather well:

However, I want to scale this up to the size of the actual moon. Unfortunately, when I do so, stepping artifacts appear:

Now I am (almost) certain that this is simply an issue with floating point precision; 32-bit floats just simply don't have enough precision for planets of this size. However, I am in an interesting situation where I *cannot* simply change one of my numbers to a double to gain more precision. My vertex shader code is this:

```
layout (location = 0) in vec3 VertexPosition;

uniform mat4 MVP; //projection and camera rotation matrix
uniform mat4 PLM; //scale and translation matrix
uniform dmat4 SurfaceRotationMatrix; //transforms vertices to be the correct position on surface

uniform samplerCube bump_map; //heightmap cubemap

uniform dvec3 PlayerLocation;

uniform double PlanetRadius;
uniform double TerrainHeightScalar;

void main(){

    //find the world space position of the flat grid (high precision)
    dvec4 worldSpacePosition = PLM * vec4(VertexPosition, 1.0);

    ...

    //offset the y position by the planets radius
    worldSpacePosition.y += PlanetRadius;

    //vertex position in relation to camera (located at origin)
    dvec4 OriginNormal = normalize(worldSpacePosition);
    //vertex position in relation to planets surface
    dvec4 surfaceHighP = SurfaceRotationMatrix * OriginNormal;
    //also calculate surface normals at this point
    dvec4 tangentHighP = SurfaceRotationMatrix * vec4(1.0, 0.0, 0.0, 1.0);
    dvec4 bitangentHighP = dvec4(cross(surfaceHighP.xyz, surfaceHighP.xyz), 1.0);

    // vvv I think this is the problem vvv
    // dvec4 surfaceHighP has to be cast to a vec3 (float) in order for the
    // shader to compile
    double height = texture(bump_map, vec3(surfaceHighP.xyz)).x;

    //set position by multiplying the normal by the distance the point should be from the surface
    worldSpacePosition.xyz = (PlanetRadius + height * TerrainHeightScalar) * OriginNormal.xyz;

    //move the position back to the origin
    worldSpacePosition.y -= PlanetRadius;

    //offset y position by the player's height (both statements are split for best precision)
    worldSpacePosition.y -= PlayerLocation.y;

    //final position: multiply by projection matrix
    gl_Position = MVP * vec4(worldSpacePosition);
}

```

OpenGL's texture() function only seems to take float parameters as an input. This makes me believe that this stepping is a result of the cast down to a lower-precision vector, where the program cannot distinguish the tiny change in angle between each grid position. At first I thought it might have been a texture precision error, so I tried switching the heightmap texture to an 8-bit copy but I didn't see any difference in step size or quantity. The texture filtering is linear, so the heights should be smoothly blended between one another, and at large scales big landforms like mountains and hills seem to have no associated problems.

Can anyone confirm that this cast in the texture() call is the reason for the stepping? If so, is there a way to pass high-precision numbers into a GLSL texture call, or, failing that, a solution to this problem that doesn't involve a complete redesign? I was thinking about maybe getting a weighted average of each neighboring "step", and then linearly interpolating between them, averaging between the areas where the float breaks down. Would something like that be possible, or is there a better alternative?

# Answer
> 0 votes
You should divide the heightmap into manageable chunks, use precise integer math on the CPU to decide which one to use, load it in the shader and use local coordinates when querying the texture.

---
Tags: shaders, graphics, glsl, planet, precision
---


title: Why do 3D animations have framerates

text:
# Question
Title: Why do 3D animations have framerates
As far as I'm aware, all 3D animation software (Maya, Blender...) has framerates. That is, keyframes can only be placed on discrete points in time. Why is that? Why can't animation keyframes be placed at any point in time?
The animations are interpolated in the game engine anyway, the game framerate is rarely the same as the animation framerate and even then, somethimes the game's frames land inbetween the animation's frames and we see the interpolated animation anyway.

# Answer
> 2 votes
Because 3d (and all other) animations heavily rely on the main frames. Let's say you're trying to animate Mario's ground pound.

(Let's forget the fact, that the jump and ground pound are two separate actions for convenience)

How would you start? In art school they teach you to first create the most defining parts of the animation, and then build everything else up from there, these are the keyframes.

In this case, those probably would be 1.) Pushing the ground 2.) Reaching the top of the jump 3.) Doing a flip 4.) Stop mid-air in a sitting position 5.) Hit the ground

In traditional (2d) animation, the parts between these ("in-betweeners") would be done by less experienced artists or outsourced (mostly to Korea), but in 3d modelling, formulas are used to interpolate between two states. In either case, the quality of those frames are worse, than the keyframes'.

For this reason, it's very important to make sure the keyframes actually get rendered. If you'd put them between two rendering frames, you'd miss them almost every time.

---
Tags: animation
---


# Question
Title: Unity importing Blender models with different orientations
All the models apart from 'Jungle Tree' are facing right which is not a problem, because they still seem to work with my game. But how can I change the 'Jungle Tree' to face right like the other models instead of left? I haven't made the Jungle Tree drastically different to the other models so I don't see why it is doing this

# Answer
As far as I know you can't do that in Unity, when importing an object. You'd have to re-export your object with blender. You can either rotate the object itself, or while exporting, play with the settings on the left. There you can change which axis is "Up" and which one is "Forward".

Alternatively you can make the Jungle Tree child of an `Empty` and rotate that by the required amount, but assuming you want to use other objects in a similar way, it can get messy.
> 2 votes

# Answer
First before exporting if you want to keep the rotation as 0 0 0 . Then you have to apply it.

When exporting to Unity from Blender as fbx. Blender tends to rotate by 90 degrees.

If you use .blend files in Unity, they will be rotated. For other types of files there are other settings. But fbx is a choice of mine because it can save animations, materials, textures data...

You can also try to change up and forward axis.

Related: Importing an object from Blender into a scene, rotation on X axis? .
> 2 votes

# Answer
Follow these steps in blender:

1. Select your model that you want to export to unity
2. Click `R` then `X` and enter in `-90`. This will rotate the model on the x axis by -90 degrees.
3. Click `Ctrl + A` and select `Rotation & Scale`. This will apply the rotation to the model and set its value to 0.
4. Click `R` then `X` and enter in `90`. This will rotate the model back to its original orientation.
5. Export the model as `fbx` into unity.

In Unity you will see that the model is now correctly oriented.
> 1 votes

---
Tags: unity, blender
---


title: Pygame set_colorkey transparency issues

text:
# Question
Title: Pygame set_colorkey transparency issues
I'm having a strange issue that I cannot seem to remedy. I am doing some prototyping with Pygame on a desktop running windows and a laptop running OS X. Both are running python v2.7.3 (installed via homebrew for the Macbook) and pygame v1.9.1.

For transparency, I have been using set\_colorkey with a transparency color of (255, 0, 255). Here is the applicable code:

```
transColor = pygame.Color(255, 0, 255)
image = pygame.image.load(playerPath + "idle.png").convert()
image.set_colorkey(transColor)

```

This works flawlessly on my windows machine. On my laptop, it does not work. It just shows the hideous magenta color. Here's the strange part. If I change the transColor to (0, 0, 0), all black pixels in my images are transparent. Has anyone run into this issue before?

# Answer
Interesting. My guess is that the `Convert` call is changing the image into a form that does not have the 255,0,255 colour in it any more. You may need to read a pixel from the converted image which you know to be the transparent colour, and then set that as the colour key.

eg.:

```
image = pygame.image.load(playerPath + "idle.png").convert()
transColor = image.get_at((0,0))
image.set_colorkey(transColor)

```
> 1 votes

# Answer
After digging around a bit more, I found that only a handful of the images weren't displaying the transparently properly (namely the background images - which made it difficult to see that the foreground images were working). As I'm using PNGs, I know that a lot of people have had issues using set\_colorkey() when there are alpha channels already present. Instead of continuing to troubleshoot this annoying bug, I opted to just drop the colorkey stuff from my code and use the built-in PNG transparency.

I guess that's not really an answer... but it's a resolution!
> 1 votes

# Answer
just try:

```
transColor = (255, 0, 255)
image = pygame.image.load(playerPath + "idle.bmp")
image.set_colorkey(transColor)

```

bmp format without convert

it works!
> 0 votes

---
Tags: python, pygame, transparency, alpha
---


title: How is this camera settling done?

text:
# Question
Title: How is this camera settling done?
For clarification: I don't need to know how to rotate the camera. What I'm asking instead is how the movement of the camera AFTER the mouse move is calculated (the "slow fade out"). I've tried a lot, but it never looks right to me.

The question:

I have uploaded a video here.

This video shows a camera settling behaviour.

In this video, the mouse pointer is moved swiftly from left to right.

The camera however does not abruptly start moving to the other direction, instead it settles in the previous direction before going to the other direction.

I would like to know how this is settling is done. I have tried really much to recreate this behaviour:

Taking into account the overall speed until the next zero mouse movement, fading out the last non-zero mouse movement, just anything that I could think of.

Could anybody tell how he thinks this could be done?

# Answer
> 1 votes
Have you tried `Vector3.Lerp`? i.e. Lerping your current position to the target position calculated by the mouse movement.

Lerp is short for linear interpolation. In this case you'd move part way to the target. The final parameter is what portion of the total distance you want to move (in this case 50%). Lowering this would get a slower camera feel. There's also `Vector2.Lerp`, if you're doing a 2D game.

```
Position = Vector3.Lerp(Position, TargetPosition, 0.5F);

```

https://en.wikipedia.org/wiki/Linear\_interpolation

*Note: I don't use Unity*

---
Tags: unity, camera
---


title: unity - What's the color of empty UV?

text:
# Question
Title: unity - What's the color of empty UV?
Assume I have a model and I don't map the UV for this model and I just apply a texture for the model. I see that Unity will apply a single color to the model, something like this (I took the img from this topic):

I guess the default pixel color it uses maybe at UV (0, 0) or UV (1, 1), but after I test it, I see that my guess is wrong, the colors doesn't match.

color 1: the color of the model when I apply the texture to a non-UV model

color 2: the color of pixel at UV (0, 0) of the texture (`color = myTexture2D.GetPixelBilinear(0.0f, 0.0f);`)

I see `color 1` is lighter than `color 2`.

So how get get the color from the texture that matches `color 1`?

*Edit* I have tried another test:

Here is the texture (4 pixels with 4 different colors):

And I got this color when I apply this texture to a non-UV mapping model:

It seems like they use an algorithm to make the non-UV color (like blend some colors of the texture together)

# Answer
> 1 votes
I figure it out, they blend 4 corner pixel of the texture to make the non-UV color.

I have a 16x16 texture (4 corners is: red, green, blue & black, the rest are yellow)

And when I apply the texture on a non-UV model, I get this color:

But notice that the non-UV color is lighter than the blend color of 4 corners, so here I propose this code to make the non-UV color, it's not perfect but good enough for me:

```
Vector2Int lastIdx = new Vector2Int(
            myTexture2D.width - 1,
            myTexture2D.height - 1);

color = (myTexture2D.GetPixel(0, 0) +
                myTexture2D.GetPixel(lastIdx.x, 0) +
                myTexture2D.GetPixel(lastIdx.x, lastIdx.y) +
                myTexture2D.GetPixel(0, lastIdx.y) +
                Color.white) / 5.0f;

```

---
Tags: unity, uv-mapping
---


# Question
Title: How can I make a trail renderer flat with the normal of the nearest face?
I'm making a basic skid system for a car model using a trail renderer. I have everything setup and working properly except that the trail renderer always faces the camera. I want the trails to be perfectly flat with the ground. So I thought if unity can make the faces all rotate towards the camera, then would it be able to rotate towards the normals of the nearest faces?

# Answer
> 1 votes
Well, the thing is, trail renderers (and the underlying line renderer) are *supposed* to face the camera.

There are a couple ways I can think of doing this, but I'm humming over which one would be the best.

One way would be to buy a decal system (there are a couple on the asset store for under $10, at least one which is free). The tracks left via decals likely aren't the best for a car, but might be "good enough" for your usage. Also search the store for anything purpose-built for tire tracks, I suspect someone's already done it.

Alternatively, you could create your own (vertex) shader to render the lines in the way that you want. You'd want to base it off the trail and line renderer system, although I can't say for sure where to start. The one (and only) time I've done this kind of thing myself was to turn a 3D mesh into a collection of *lines* which *did* face the camera. Doing the reverse would be possible with some effort, though.

(Now that I think about this, I think the LineRenderer component does the mesh construction in the component before it hits the shader: that'd be the better thing to fiddle with than trying to *undo* that with a vertex shader. Thus, idea #3).

Third, you can manually construct a triangle strip yourself. You'll have to weigh the cost/benefits of doing this over buying one off the asset store. $10 vs. 10 hours is heavily in favor of just buying it. But it shouldn't be that hard to compute the points yourself. Just remember to keep the tris slightly above the actual terrain or you'll get Z-Fighting.

# Answer
> 1 votes
The skid system I wrote works like this:

1. When in a skidding condition, every frame capture the contact point of the skid, and the normal of the surface contact point - you would probably already have this from the raycast/contact you used for your physics simulation.
2. When you have two or more points, you can start drawing the skid - to begin with just draw it as a line list or line strip so you can visualize it. See the red line and P0 to P4 in the diagram below.
3. Once you are sure you have your points in the right place, you need to create three basis vectors for each point so that you can create your polygonal data. The first basis vector is the the normal for each contact - this is your UP vector. The second basis vector is the forward vector - this is you point's position subtracted from the next point's position. Use the cross product and normalize to get the third basis vector - the RIGHT vector (or LEFT vector, depending on your coordinate system).
4. With the basis vectors you can now use the RIGHT vector to create two points, one to the RIGHT of the current point and one to the LEFT of the current point. If you were to take those points and draw them you would have to lines parallel to each other (see the black lines in the diagram below). Since the RIGHT vector is a unit vector, your two points are now P\_left = P - RIGHT * half\_width; P\_right = P + RIGHT * half\_width where half\_width is the half width of the skid mark.
5. You now need to take those points and turn them into quads, or triangles (two triangles per quad; see the light-grey lines in the diagram below). How this is done depends on how you draw your data. In the end you want to stitch together each pair of points into a strip of triangles/quads.

You can see in the above diagram the black outlines of the skid mark. The points P0, P1, P2, P3, and P4 have been collected. Note that P4 has no further point so a forward vector cannot be calculated. I normally use the tire direction for the point, or simply use the same forward as the previous point. Here the blue line is the UP vector - assume that the red line lies on the X/Y plane and the Up vector is (0,0,1) - perspective is hard to show in a 2D image.

Hopefully this helps - there are some additional operations to consider to make the pinching at corners work better, but you might not have to do it if you are not turning too quickly. You will also need to consider under what conditions you need to add skids, etc.

# Answer
> 0 votes
I am pretty sure you can make the trail rendered look up instead of at the camera, and since your car is probably not going to be driving with it's right side higher than the left this could work for you.

---
Tags: unity, normals, face, trail-renderer
---


title: Add a tag in Unity editor in code

text:
# Question
Title: Add a tag in Unity editor in code
How to add a tag in editor? I am working on automatic asset generation and I would like to use tags for certain objects.

# Answer
Here is a utility method that allows you to do just that. Just replace `PathUtility.PROJECT_SETTINGS_PATH_NAME` with `"ProjectSettings"` if you don't want to have a constant somewhere.

```
PathUtility.PROJECT_SETTINGS_PATH_NAME = "ProjectSettings";

#if UNITY_EDITOR
public static class TagUtility
{
    public static void AddTag(string tag)
    {
        SerializedObject serializedObject = new SerializedObject(
            AssetDatabase.LoadAssetAtPath<Object>(
                Path.Combine(PathUtility.PROJECT_SETTINGS_PATH_NAME, "TagManager.asset")
            )
        );
        serializedObject.Update(); // Get object current state into stream.

        SerializedProperty tags = serializedObject.FindProperty("tags");

        for (int i = 0; i < tags.arraySize; ++i)
            if (tags.GetArrayElementAtIndex(i).stringValue == tag)
                return;

        tags.InsertArrayElementAtIndex(tags.arraySize);
        tags.GetArrayElementAtIndex(tags.arraySize - 1).stringValue = tag;

        serializedObject.ApplyModifiedProperties(); // Apply changes from stream to object.
    }
}
#endif

```
> 1 votes

---
Tags: unity
---


title: Composing Game Metrics

text:
# Question
Title: Composing Game Metrics
So I'm running into a bit of a roadblock with the way I'm currently keeping track of game metrics. By "metrics", I mean little bits of information that I can compose together to get useful information about my game. My primary application for this being so that I can detect certain events in the game and disperse achievements.

The way my current system works, I have metrics represented as a long value, where each bit represents a certain metric... for example, there's a flag for enemies, a flag for the player, a flag for a kill, a flag for each weapon, a flag for when a wave starts, etc, etc. I can then compose these into a single value to tell me things like "an enemy of this type was just killed by this weapon". My achievements controller looks at each metric posted in the last update and I have state machines that transition to the next state based on what metrics are posted.

The problem with this method is... I'm quickly running out of bits to use for my long value. I have plenty more weapons I want to add, so this hard limitation on the number of bits I can use as flags means it's probably time to find a better way to keep track of these.

Does anyone have a recommendation? Preferably one that would require the least amount of effort to refactor my current metrics and achievement systems to integrate?

**EDIT:** Is there a better term than "metric" to use? I haven't been able to find articles on this topic of game engine design because whenever I use the word "metric", all I find are articles about revenue-related analytical metrics.

# Answer
You are using Java, so you can and should use the power of object-oriented programming. Represent each type of metric event with a different class, where each class has exactly the fields it needs. When all these classes implement the same interface (or extend the same base class) `MetricEvent` you can easily store them in the same data structures and process them in the same way.

For example, the class for a KillEvent could look like this:

```
public class KillEvent implements MetricEvent {
    public EnemyType enemy
    public WeaponType weapon

    // constructor
    public KillEvent(EnemyType enemy, WeaponType weapon) {
         this.enemy = enemy;
         this.weapon = weapon;
    }

    // you might also want to override equals so any counter-implementations can
    // check if two MetricEvents are of the same type and have the same parameters
    @Override public boolean equals(Object others) {
         if (other.getClass() != getClass()) return false;
         KillEvent otherKillEvent = (KillEvent) others;
         return (otherKillEvent.enemy == enemy && otherKillEvent.weapon == weapon);
    }
    // if you override equals you must also override hashCode
    @Override public int hashCode(Object others) {
         // this implementation assumes EnemyType and WeaponType can be converted to 16 bit integers.
         // if this is not the case, you might have to find a different way to calculate a hash code
         return enemy<<16 + weapon;
    }
}

```
> 1 votes

---
Tags: java, architecture, algorithm
---


title: Sum of FoV enemies

text:
# Question
Title: Sum of FoV enemies
so what I need is to calculate the sum of players' Field of view. Put simple, In a 2d space, I want to check how much they cover (in degrees).

So here are a couple of use cases to explain by example: Let's say I have two players (but can be scalable to more) with a FoV of 90°:

1. If they are opposite of each other, the result should be 180°.
2. If they are looking in the exact same direction, the result should be 90°.
3. If they are at 45° of each other, the result should be 135°.

As data, I have the List of players (list), the FoV (degrees), the Position of the players \[x, y\], the direction they are facing (degrees). I can't think of anything else the can be of use. (If there is some extra data that would help I will check if it is something that can be created).

BTW, I am using a custom engine, I think that is a quite important info. :)

Thank you in advance for anyone willing to help.

# Answer
Degrees are a very unusual way to represent directions in game engines. If you really want to use angles, then it is usually more efficient to handle angles in radians. But many engines do not use angles internally. 2d rotations are often most efficiently represented with complex numbers or normalized 2d vectors while the most efficient way to encode a 3d rotation is often a quaternion. But I digress.

Assuming FOV1 is the field of view in degrees of the first player, FOV2 the field of view of the 2nd player and DIFFERENCE the difference in view direction in degree in the shortest direction, then the total field of view covered is either FOV1 plus FOV2 or FOV1 + DIFFERENCE, depending on which one is smaller. Or in pseudocode:

```
totalFOV = FOV1 + min(FOV2, abs(DIFFERENCE));

```

(the abs-function returns the absolute value, also known as the value without minus-sign. This is relevant if player2 looks to the left relative to player 1, because in that case DIFFERENCE would be a negative value).

If returns the correct result for all three of your test cases:

1. `90 + min(90, 180) = 90 + 90 = 180`
2. `90 + min(90, 0) = 90 + 0 = 90`
3. `90 + min(90, 45) = 90 + 45 = 135`
> 1 votes

---
Tags: collision-detection, mathematics, trigonometry, intersection
---


# Question
Title: How to write a PBR Unlit Shader in Unity?
I have a REALLY specific case here:

I have an Texture (a webcam), that is used by a shader to pickup a few `x,y` colors at the cordinates, and renders to a `Custom Render Texture`, that is later fetched (download pixel color information from GPU to CPU), and I can handle the algorithm from there.

The thing is, once I upgraded the project to PBR (Physically Based Rendering), all my Unlit scripts become PINK, and they stopped working.

This is a special case because:

1. It doesn't need to appear on the screen
2. It acts as a "Compute Shader", but with backward compatibility to old phones
3. It works well without PBR, but once PBR is enabled it becomes pink and stops working
4. It doesn't need to reflect, refract, output pixels or anything to the "Screen", only to my Custom Render Texture so that I can fetch it later.
5. The algorithm doesn't fits on a Graph based programming (it has iterations and etc)

Well, I didn't find documentation on how to write custom PBR shaders and here I am.

# Answer
> 0 votes
I had the same problem. I think you need to create a Lightweight Render Pipeline Asset on my Assets folder (r-click -\> create -\> Lightweight Render Pipeline Asset) then dragged it to my Graphics settings (Edit -\> Project Settings -\> drag to Scriptable Render Pipelline settings). After that go to Edit -\> Render Pipeline -\> Upgrade Render Material to LightweightRP Material. Then you napply yout material. Hope this helps even it's not the same scenario.

Edit: adding note: To download Lightweight Render Pipeline you need to go to Window -\> Package Manager and enable Previews under the Advance dropdown.

---
Tags: unity, shaders, rendering, pbr, compute-shader
---


# Question
Title: how do I move an object based on rotation of another object?
This question is related to my other question about camera rotation. I hope its acceptable to ask a second question. I cannot figure out the math of how to calculate moving the camera to stay behind my player, based on the players rotation.

In the image above, the arrow represents a player with the direction of the arrow representing the direction the player is facing. The red object represents camera. I want the camera to always remain behind the player. When the player turns, I want the camera to move behind the player. I cannot figure out the math for calculating where to move to.

Step 1 The arrow is at 0,0 and facing 0 (north). The red circle is at 0,-5

Step 2 the arrow is at 0,0 and turned 90 degrees to the right (facing east). The red circle should move to be "behind the arrow" aka to the left and up and at the same distance from the arrow as when it started. I am guessing that would be -5,0 in this case

Other Scenarios a) The arrow is at 0,0 and turned -30 degrees (turned to the left). The red circle should move right and up.

b) the arrow is at 0,0 facing south (180 degrees opposite of #1) and turns -30 degrees to right (on screen but left if you are the arrow). The red circle should move appropriately.

I have racked my brain over this for days and just cannot find an answer. Thnx Matt

# Answer
> 1 votes
TL;DR

```
camera.position = player.position - player.forward * distanceFromPlayer;

```

`player.position` gives the position of the player

`player.forward` gives the direction the player is looking at. Obviously, when the player rotates, the vector rotates too. `- player.forward` will allow the camera to be placed **behind** the player.

`distanceFromPlayer` is a (positive) `float` whose value represents the distance between the player and the desired position

---
Tags: unity, c#, 3d, mathematics, rotation
---


# Question
Title: My camera does not rotate around player in 3d open world
I want my camera to following behind the player at all times. When the player turns to the left, I would expect the camera would move behind the player while remaining focused on the player.

My camera stays focused on the player. However, it does not rotate to stay behind the player.

I tried following the directions from here, and here. Neither of which seems to help.

Here's my code:

```
public class CameraFollow : MonoBehaviour
{

    private GameObject player;
    private GameObject mainCamera;
    private Vector3 offset;
    private float distance;
    private Vector3 playerPrevPos;
    private Vector3 playerMoveDir;

    // Use this for initialization
    private void Start()
    {
        player = GameObject.FindGameObjectWithTag("Player");
        mainCamera = GameObject.FindGameObjectWithTag("MainCamera");

        //Calculate and store the offset value by getting the distance between the player's position and camera's position.
        offset = transform.position - player.transform.position;

        distance = offset.magnitude;
        playerPrevPos = player.transform.position;
    }

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

    private void LateUpdate()
    {
        playerMoveDir = player.transform.position - playerPrevPos;

        if (playerMoveDir != Vector3.zero)
        {
            playerMoveDir.Normalize();
            transform.position = player.transform.position + offset;
            transform.LookAt(player.transform.position);
            transform.rotation = Quaternion.Lerp(transform.rotation, player.transform.rotation, Time.deltaTime * 1);

            mainCamera.transform.position = player.transform.position + offset;
            mainCamera.transform.LookAt(player.transform.position);
            mainCamera.transform.rotation = Quaternion.Lerp(transform.rotation, player.transform.rotation, Time.deltaTime * 1);

            playerPrevPos = player.transform.position;
        }
    }
}

```

I have done something a little different, per instructions from a online unity class. My main camera is a subobject of a rootobject, as shown in this picture.

I have attached image of the game with the yellow line showing which way the player is facing. The camera is facing in a different direction.

Any help would be appreciated.
Thnx Matt

**Follow-up from answers**: I cannot get either solution to work. @alejandrodlsp solution doesn't compile (I've added a comment to the answer explaining why). If I do not set `offset` on Start (aka its always 0), then the camera rotates. The problem is that is at the feet the player and not behind like I wanted. Once I compute offset, then the camera never rotates behind the player.

# Answer
I have a solution to what I needed. I appreciate everyone's input. The solution was definitely "outside the box". The key to the solution is this property `[gameobject].transform.forward`. My other change was to use `LateUpdate()` as it is called once per frame, rather than `FixedUpdate()`, since that's called during the physics phase.

`[gameobject].transform.forward` gives the direction the player is looking at. Obviously, when the player rotates, the vector rotates too. For more info, see this post.

Here's the code.

```
public class CameraRotateFollow : MonoBehaviour
    {
        private GameObject player;
        private Vector3 distanceVecToPlayer;
        private float distanceToPlayer = 3f;
        private float cameraHeight = 2f;
        private long count = 0;

        // Use this for initialization
        private void Start()
        {
            player = GameObject.FindGameObjectWithTag("Player");

            // Calculate and store the camera arm position relative to player
            // by getting the distance between the player's position and camera arm 's position.
            distanceVecToPlayer = transform.position - player.transform.position;

            // on start, we are assuming player is facing north (rotation 0, 0, 0) (this is design flaw I can live with)
            // therefore transform.position.z is the distance from camera arm to player
            // y Height above player
            // x is left or right of player (and should always be 0)
            distanceToPlayer = distanceVecToPlayer.z;
            cameraHeight = distanceVecToPlayer.y;
        }

        private void LateUpdate()
        {
            Follow();
        }

        private void Follow()
        {
            var forward = player.transform.forward;
            float distanceModifer = distanceToPlayer * -1.0f;

            // compute camera arm location.
            Vector3 setCameraLocation = player.transform.position - distanceModifer * player.transform.forward;

            // camera is set above the player (to look over his shoulder). To keep a consistent height
            // set height (Vector3.y) to player position (which is techincally at the ground) + starting camera height
            setCameraLocation.y = player.transform.position.y + cameraHeight;

            // Set the position of the camera's transform to be the same as the player's, but offset by the calculated offset distance.
            // this keeps the camera on the same axis as the previous update
            transform.position = setCameraLocation;

            // make sure camera arm (and hence the camara) is looking at the player
            transform.LookAt(player.transform);
        }

```

Thnx again. Everyone's help is appreciated. I wouldn't have been able to think through the problem enough without it.

Matt
> 1 votes

# Answer
I would separate the following and rotating functionalities into different functions, and call them both from the fixed Update for the purpose of clarity. I'd also set the follow movement for the parent object and Slerp to the same rotation as the player's; no need to use the transform.LookAt() function.

```
    float rotationSmoothing = 0;
    float followSpeed = 0.1f;

    private GameObject player;
    private GameObject mainCamera;
    private Vector3 offset;

    public void Start(){
       player = GameObject.FindGameObjectWithTag("Player");
       mainCamera = GameObject.FindGameObjectWithTag("MainCamera");

       offset = player.transform.position - mainCamera.transform.position;
    }

    public void FixedUpdate(){
     follow();
     rotate();
    }

    void follow(){
      if(player == null){
        return;
      }

      Vector3 tPos = new Vector3(player.position.x + offset.x,
                                 player.position.y + offset.y,
                                 player.position.z + offset.z,);
      transform.position = Vector3.Lerp(mainCamera.transform.position,
                                      tPos, followSpeed);
    }

 void rotate(){

     float targetRot = Quaternion.Euler(player.transform.rotation).y;   // Creates a from player

     if (rotationSmoothing > 0){
         mainCamera.transform.localRotation = Quaternion.Slerp(transform.localRotation, targetRot, rotationSmoothing * Time.deltaTime); // Slerp between rotation
     }else{
         mainCamera.transform.localRotation= targetRot; // Sets rotation
     }
 }

```

Another option may be to set the camera system to be a child of the player itself, but that path rules out any type of movement smoothing.

I hope this is useful for you and fixes your problem.
> 1 votes

---
Tags: unity, c#, camera, open-world
---