title: Browser RPG fight calculation formula

text:
# Question
Title: Browser RPG fight calculation formula
I am making a simple browser rpg game, similar to battleknight. To keep the game simple, I have just Strength, Constitution, and Luck, but since Luck is based on randomness, I'm struggling with combat calculations. I need some kind of formula to calculate attacks.

Preview from battleknight:

---

**UPDATE** I was thinking about this model:

---

Strength - base dmg.

---

speed - chance to avoid attacks

---

toughness - increase HP

---

luck - crit. hit chance

---

defence - chance to block attacks.

---

I expect there will be fights between differently ranked players so I want to calculate attack differently. My idea is to sum the stronger player's stats (this will be the cap) so that randomness-based attributes will be divided by this sum. For example:

```
cap = sumOfStrongerPlayerAttributes
player1Luck = player1.luck / cap
player2Luck = player2.luck / cap
// also luck can be divided to ensure that crit. hits will not be so often

```

Also crit. hit dmg. will be calculated from base dmg. like:

```
critHitDmg = player.strength * someConst

```

This model will prevent crits from happening too often, and the player who spends all his resources to level up luck will have low stamina, defence or base dmg (which is also important for crit. hit dmg).

# Answer
Your question can be summarized as "I got a Luck stat in my combat system, please tell me why".

Ask yourself: What game-design goal does the Luck stat fulfill? Do you have an immediate answer? If you don't then I would recommend you to just throw it out.

Now you are just down to two stats: Strength and Constitution. This doesn't seem like much. But you should ask yourself if you actually *need* more than this. Adding complexity just for complexity sake doesn't make a game more interesting, just more confusing. As you develop your game from there, you might discover design problems where these two stats are insufficient and you might consider a solution which adds a 3rd or 4th stat. But then you will know what problem you actually want to solve, so the formulas will come naturally to you.

---

To be honest, I played many games which had some kind of "Luck" stat in one way or another, and it almost always turned out to be a game design flaw. It usually doesn't make you "feel" any more lucky, because it usually doesn't affect the *really* important random number rolls. And neither does it affect any events in the game story where your character is particularly lucky or unlucky for plot reasons ("Your princess is in another castle? How can that be? I got 120 Luck, how is it possible that I picked the wrong castle?!?"). Instead it is usually a stat with a very vaguely defined role. Is there actually any situation your character could be in where "being lucky" is not of an advantage somehow? So what does "luck" actually mean? Is it an offensive stat? A defensive stat? An utility stat? Is it more or less important than other stats? Who knows? You usually need to dive deep into the metagame to understand what it actually does and in which situations it gives you a benefit. When a game mechanic isn't intuitive, then it is usually not a good mechanic.
> 31 votes

# Answer
You essentially want your crit to scale from 0% to 100% with diminishing returns. Here is a formula that is 0% at luck=0 and approaches 100% as luck goes to infinity.

```
f = 2.71; // you can mess with this factor to change how quickly it diminishes
crit = Math.random() > Math.pow(f, -luck); // assuming random is in the range [0.0, 1.0]

```

Then use a multiplier if there was a crit

```
mult = 2; // set for a multiplier of 2

```

Then calculate the base power of the attack. I just set it to strength + 10

```
base_power = strength + 10;

```

Then just use the multiplier if crit was true

```
damage = base_power * (crit ? mult : 1);

```

Let me know if you need something different, and I can update my answer.
> 11 votes

# Answer
## What does Luck mean?

Luck could increase the chance of some combination of:

* Hitting
* Evading
* Blocking
* Crit-ing (also potentially crit damage)
* Getting an item (if there are items)
* Having that item be a good item
* Success of any action you attempt
* Any random (unambiguously) good thing happening
* Any random (unambiguously) bad thing *not* happening

I'd suggest not using Luck for the first few in favour of having dedicated stats for those with less ambiguous name (e.g. accuracy / chance to hit, evasion / dodge, crit chance, block chance, drop rate, drop quality - dexterity has also been known to cover some combination of the first 4).

## How do you calculate with Luck?

There are a few ways Luck can work: (can apply to other stats as well)

* Gives a chance of something happening (that wasn't possible before)
* Increases the chance of something happening (which is also be dependent on other stats)
* Make some non-percentage number bigger (e.g. crit damage)

The last one can simply be a multiplier (e.g. 1 Luck → `x *= 1.01`, 2 Luck → `x *= 1.02` \- it doesn't have to be 0.01 per 1 Luck).

For the first two you'll need to convert your Luck stat into a percentage (0%-100%) (there isn't a "correct" way to do this, you'll need to take into account the points mentioned below).

The second one is probably the most complicated, as you'll need to decide what exactly luck will change - I might suggest having it decrease the chance of failure: e.g. a 60% chance to hit with 50% luck gives you a `(1-0.6)*0.5` = 20% chance of missing (i.e. 80% chance to hit).

For any of them you'll need to consider a few things:

* What kind of scaling do you want? In many games, stats use diminishing returns (grows fast at the beginning at then slows down) - this can make the game more balanced or easier to balance, as the stat bonuses are impactful at first, but don't get out of control.

Note that some linear increases may *already* give you diminishing returns - e.g. if your chance to hit increases from 25% to 50%, that's a 100% damage increase (you're hitting twice as often), but from 50% to 75% would only be a 50% damage increase. If you want to use a linear increase and the stat is unbounded, you'll need to figure out what will happen when you get to 100%.
* What's the maximum value for the stat? Is there a maximum?
* How much of a bonus would it provide at any point, especially compared to the same investment into other stats?

You may want to strive to have any given point provide a comparable benefit no matter which stat you throw it into at which point (with different stats changing your playstyle), or you could have some be significantly better (not one stat as a whole be better than another, but rather the m-th point of one be better than the n-th point of another), to allow for some min-maxing.

## Should you include Luck?

Luck: (especially if it affects many things)

* Adds to the perceived complexity of the game by giving the player more things to put points into, which may be good or bad (this can be good if players can run out of others things to put points into, but this can be addressed in other ways)
* Can make the game harder to balance, unless Luck is mostly useless, in which case you should probably just remove it
* Can be hard for players to see the effects of, making players feel like getting more of it is a waste
* Probably wouldn't clearly and quantifiably explain what it does, making players less likely to want to invest in it
* Generally doesn't really affect a player's playstyle. As mentioned above, different stats could be used to allow the player to change their playstyle, but having one stat just sort of helping all over and not really have a clear focus goes against this.

Overall I'd say: no, you shouldn't include it, but you can possibly include more specific stats (as mentioned above).
> 3 votes

# Answer
Building on Kyy13's answer, if you have a hard cap for stats (max value) then it can become a more simple, linear equation where you want f(x)=min\_crit\_percentage when x=stat\_min and f(x)=max\_crit\_percentage when x=stat\_cap, so you end up with:

crit\_percentage = x * (max\_crit\_percentage / stat\_cap)

and you'll use instead

```
crit = Math.random()*100 > luck*(max_crit/stat_cap);

```

When making formulae for attack results and such you'll want to decide the kind of relationship between the actual stat and the effect in battle; a linear relationship like this one will make every point count, while one with diminishing returns will make it less worth it to spend points on luck when you're close to the cap. Make sure the player knows about this if it's not linear (maybe display the crit percentage or how much they will get by spending an extra point) so they can make an educated choice and don't feel like they're being tricked or they wasted points when they're closer to the cap.
> 0 votes

---
Tags: mathematics, game-design, browser-based-games
---


title: "lazy follow" - term?

text:
# Question
Title: "lazy follow" - term?
For one of my games, I need an enemy that pursues the player in a sort of "lazy" way, where they don't exactly follow the player's movement and instead have somewhat slippery movement. Example: the player does a sharp turn to the right, the enemy will go to that direction too, but it will slightly "overshoot" the distance and go beyond the point where the player turned to the right before going to the new direction. Here is an example:

Some examples from games:

* Missiles (Super Meat Boy)
* Phanto (Super Mario Bros. 2, the USA one)

Is there a term for this kind of "lazy" movement for homing enemies?

# Answer
> 1 votes
I'd just say your enemy entity has momentum.

Usually this means the steering function can only affect the acceleration but not the velocity, so it cannot stop on a dime.

---
Tags: terminology
---


title: Multiple Indices Problem

text:
# Question
Title: Multiple Indices Problem
Recently, I've been trying to use `COLLADA` files in OpenGL. The problem that a lot of people before me have run into is `COLLADA`'s indice structure. It has multiple sets of indices, the first is for position, the second for the normal. I know by now that it is completely impossible for OpenGL to use multiple sets of indices, so I must rearrange my normals so that I can use my position indices for my normals.

I've already made some code for this, but it doesn't seem to turn out right.

```
private static Vector3[] RearrangeNormals(Vector3[] norms, Vector3[] pos, int[] posindices, int[] normindices)
{
    Vector3[] newnorms = new Vector3[norms.Length] ;
    for (var i = 0; i < norms.Length; i++)
    {
            newnorms[posindices[i]] = norms[normindices[i]];
    }
    return newnorms;
}

```

With this function, it seems like half of my Suzanne mesh has it's normals correct, the other half... not so much. Here's an image of what I'm getting with my lighting test.

How should I handle rearranging my normals (or texcoords maybe in the future)?

# Answer
> 1 votes
You are assuming that the number of normals and number of positions is the same. This may not be true.

If there are more positions than normals, then you are accessing newnorms out of bounds.

Before fixing this you need to make a choice. Do you:

1. Want to draw non-indexed.
2. Want to draw indexed.

In case of 1, you simply generate non-indexed data by looking up the norm/pos before feeding it to OpenGL.

In case of 2, you would need to first determine all unique pos+norm values, before you can assign an index to it.

The first option is easier, and would mean using glDrawArrays, not glDrawElements. Some people argue that indexed primitives can be faster, but personally, I have found it not worth the extra effort.

# Answer
> 0 votes
Here's an answer that works for me, although doesn't directly answer the question.

Ready? (*Drum roll*)

**Use .X3D**

This format is actually really great. Unlike COLLADA, you can edit the up axis in Blender so that it is exported as Y-Up, it only has one set of indices and all the data for a single mesh is stored in one child (including the materials).

I was actually quite surprised at the fact that not a lot of people are using this, even though it seems like it was made for OpenGL!

---
Tags: c#, opengl, opentk
---


# Question
Title: How can I switch the lights between red and green to mark when the door can be open or locked?
Under Lights I have a Dim Lights and attached to it a script. Under the Dim Lights I have Point light and a Quad. And another Point light and quad.

In the screenshot the two lights and quads in Red are the one I added. And I want to switch between red and green using this quads and lights.

This is the DimLights script:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DimLights : MonoBehaviour
{
    //Lights Change
    public Light[] lightsToDim = null;

    private GameObject[] myLights;

    private void Start()
    {
        myLights = GameObject.FindGameObjectsWithTag("Light");
        for (int i = 0; i < lightsToDim.Length; i++)
        {
            lightsToDim[i].intensity = 0;
        }
    }

    public void LightsState(bool state)
    {
        foreach (GameObject go in myLights)
        {
            go.GetComponent<Light>().enabled = state;
        }
    }

    public IEnumerator dimLightOverTime(float toIntensity, float duration)
    {
        float counter = 0;
        //Get the current intensity of the Light
        float[] startIntensity = new float[lightsToDim.Length];
        for (int i = 0; i < lightsToDim.Length; i++)
        {
            startIntensity[i] = lightsToDim[i].intensity;
        }

        while (counter < duration)
        {
            counter += Time.deltaTime;

            for (int i = 0; i < lightsToDim.Length; i++)
            {
                lightsToDim[i].intensity = Mathf.Lerp(startIntensity[i], toIntensity, counter / duration);
            }
            yield return null;
        }
    }
}

```

On the door there is a script Door Vert and in the Inspector in the bottom of the script there are two parameters: Door Locked and Locked. And it's not Locked the lights and quads should be in green when running the game. When it's locked they should be in Red.

```
using UnityEngine;
using System.Collections;

public class DoorVert : MonoBehaviour {

    public float translateValue;
    public float easeTime;
    public OTween.EaseType ease;
    public float waitTime;
    public Light[] lt;
    public UnityEngine.Renderer[] renderers;
    public bool doorLocked = false;
    public bool locked = false;

    private Vector3 StartlocalPos;
    private Vector3 endlocalPos;

    private void Start(){
        StartlocalPos = transform.localPosition;
        gameObject.isStatic = false;

        if (doorLocked == true)
        {
            for (int i = 0; i < lt.Length; i++)
            {
                lt[i].color = Color.red;
                renderers[i].material.color = Color.red;
            }
        }
    }

    public void OpenDoor(){
        if (doorLocked == false)
        {
            OTween.ValueTo(gameObject, ease, 0.0f, -translateValue, easeTime, 0.0f, "StartOpen", "UpdateOpenDoor", "EndOpen");
            GetComponent<AudioSource>().Play();
        }
    }

    private void UpdateOpenDoor(float f){
        if (doorLocked == false)
        {
            Vector3 pos = transform.TransformDirection(new Vector3(0, 1, 0));
            transform.localPosition = StartlocalPos + pos * f;
        }

    }

    private void UpdateCloseDoor(float f){
        if (doorLocked == false)
        {
            Vector3 pos = transform.TransformDirection(new Vector3(0, -f, 0));
            transform.localPosition = endlocalPos - pos;
        }

    }

    private void EndOpen(){
        if (doorLocked == false)
        {
            endlocalPos = transform.localPosition;
            StartCoroutine(WaitToClose());
        }
    }

    private IEnumerator WaitToClose(){

        yield return new WaitForSeconds(waitTime);
        OTween.ValueTo( gameObject,ease,0.0f,translateValue,easeTime,0.0f,"StartClose","UpdateCloseDoor","EndClose");
        GetComponent<AudioSource>().Play();
    }

    private void Update()
    {
        if (locked == true)
        {
            doorLocked = true;
            for (int i = 0; i < lt.Length; i++)
            {
                lt[i].color = Color.red;
                renderers[i].material.color = Color.red;
            }
        }
        else
        {
            doorLocked = false;
            for (int i = 0; i < lt.Length; i++)
            {
                lt[i].color = Color.green;
                renderers[i].material.color = Color.green;
            }
        }
    }
}

```

The problem is that no matter what the door state is if it's not Locked it's all the time red when running the game. Never green.

In the Dim Lights script in the inspector I added the two Point lights to the Lights To Dim and both Quad and Quad (1) I changed them to be tagged as Light.

Not sure what I messed but it's not changing it to green when the door state start as unclocked.

On the door script the Door Vert script there is array variable:

```
public Light[] lt;

```

I forgot to fill it so I changed the size in the inspector to 2 and added the two Point lights to it. But still it's not working.

Last is a script I forgot to mention before Objects Manipulation: The script is also using the Dim Lights script.

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectsManipulation : MonoBehaviour
{
    //Camera
    public Camera playerCamera;

    //Scaling
    private Scaling scaling;

    //Lights
    public DimLights dimlights;
    private Coroutine lightCoroutine;

    //Colors
    private Colors colors;

    //Rotating
    public bool stopRotation = false;
    private Rotating rotating;

    private void Start()
    {
        scaling = GetComponent<Scaling>();
        scaling.Inits();

        colors = GetComponent<Colors>();
        colors.Start();

        rotating = GetComponent<Rotating>();
    }

    // Use this for initialization
    void Update()
    {
        //Scaling
        if (Input.GetKeyDown(KeyCode.F))
        {
            //Flip the scale direction when F key is pressed
            scaling.scaleUp = !scaling.scaleUp;

            //Stop old coroutine
            if (scaling.scaleCoroutine != null)
                StopCoroutine(scaling.scaleCoroutine);

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

            //Scale  up
            if (scaling.scaleUp)
            {
                //Start new coroutine and scale up within 5 seconds and return the coroutine reference
                rotating.rotateBack = false;
                scaling.scaleCoroutine = StartCoroutine(scaling.scaleOverTime(scaling.objectToScale, scaling.maxSize, scaling.duration));
                lightCoroutine = StartCoroutine(dimlights.dimLightOverTime(1, scaling.duration));
            }

            //Scale Down
            else
            {
                //Start new coroutine and scale up within 5 seconds and return the coroutine reference
                rotating.rotateBack = true;
                scaling.scaleCoroutine = StartCoroutine(scaling.scaleOverTime(scaling.objectToScale, scaling.minSize, scaling.duration));
                lightCoroutine = StartCoroutine(dimlights.dimLightOverTime(0, scaling.duration)); ;
            }
        }

        //Rotate
        if (Input.GetKey(KeyCode.R) && !scaling.scaleUp)
        {
            rotating.x += Time.deltaTime * rotating.rotationSpeed;
            scaling.objectToScale.transform.localRotation = Quaternion.Euler(0, 0, rotating.x);
            rotating.keyPressed = true;
        }
        if (Input.GetKeyUp(KeyCode.R))
        {
            rotating.keyPressed = false;
        }

        if (!rotating.keyPressed && !scaling.scaleUp && rotating.rotateBack == false
            && DetectInteractable.detected == false)
        {
            scaling.objectToScale.transform.rotation = Quaternion.LookRotation(playerCamera.transform.forward);
        }

        if (DetectInteractable.detected == true && !scaling.scaleUp && stopRotation == false)
        {
            rotating.x += Time.deltaTime * rotating.rotationSpeed;
            scaling.objectToScale.transform.localRotation = Quaternion.Euler(0, 0, rotating.x);
        }
    }
}

```

# Answer
The solution is to change the arrays size in the Door Vert script in the Inspector of the Lt and Renderers to 2.

In the Lt to add the two Point lights and in the Renderers to add the two Quads.

Now when I'm running the game and the door is locked the two quads are in red. And when I press on F and it's scaling the object (NAVI in my case) then it's also turning the lights on. Same when the door is unlocked with the green color.

In this specific scene I wanted some dark room and when the object is scaling fade in the lights turn on when the object is scaling fade out the lights are off.

I and others can play with this scripts a lot.

You can make for example that the lights will be turn on all the time. And then when changing the door state lock/locked it will change the quads and lights colors. You can also make the lights and quads each two a prefab. And much more.

For my needs it's working great.
> 1 votes

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


title: Spine and 2D Unity Weird Light Issue

text:
# Question
Title: Spine and 2D Unity Weird Light Issue
While using spine in unity 2D with a spot light, the light from the spot light will shine on the character if he's facing right but only when the light is in front (in the Z direction) of the character. If the character turns left the light will not have any affect. But, if you turn left and move the light behind (in the Z direction) of the character, then the light will shine on the character. I'm using the Spine/Skeleton Lit or Spine/SkeletonGraphic material with spine 3.6 runtime. I've tried adjusting the alpha and other random settings, but im not sure where to begin.

The Z direction of the character doesn't change when turning left or right in unity, but the spot light only affects in a certain direction.

The environmental light affects the character, but the spot light only affects the character based on the rotation. I want the spot light to affect the character regardless of their X scale or rotation. Culling is off....

# Answer
"When you've been working on a problem for 1 hour, ask a question on a forum, and then solve your problem 3 minutes after asking the question" = SMH.

The problem is that im rotating my character 180 directions when facing left. Therefore, the normals are away from the spot light. I solved the problem by changing the X scale from 1 to -1. This will allow the light to affect the character while facing left or right.
> 1 votes

---
Tags: unity, lighting, materials, normal-mapping, spine
---


# Question
Title: Bad Viewports Using Unity with Google Cardboard VR on iOS
I'm using unity 2017.3.1f1, building for an iPhone SE.

I'm able to build the google HelloVR scene, available from the Google Cardboard VR unity package. However, in the end result, the cameras are giving the wrong display. They aren't lined up to create stereoscopic vision at all, and the image appears distorted.

Here is an example of the output: https://i.stack.imgur.com/MZ95v.jpg

Is there a default setting in the Google Cardboard VR package that can be changed to fix this?

# Answer
It's a known bug, documented here with workaround: https://github.com/googlevr/gvr-unity-sdk/issues/838
> 0 votes

---
Tags: unity, ios, google-cardboard
---


# Question
Title: How do I implement asteriods ship movement?
```
void Draw_Ship()
{
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glPushMatrix();

    glTranslatef(5.0f, 0.0f, 0.0f);

    glRotatef(angle, 0.0f, 0.0f, 1.0f);

    glTranslatef(0.0f, up, 0.0f);

    draw_ship();

    glPopMatrix();

    glPushMatrix();

    glTranslatef(-5.0f, 0.0f, 0.0f);

    glRotatef(angle_two, 0.0f, 0.0f, 1.0f);

    draw_ship_two();

    glPopMatrix();

    glutSwapBuffers();
}

```

I am working on an asteroids clone using c++ and opengl, I want my space ship to rotate around an point and to follow its nose.

# Answer
> 2 votes
You'll need to keep around a value that represents the current rotation of the ship. Let's call it `currentRotation`. When the user presses the left or right arrow keys (or whatever keys you're using for rotate left and rotate right), you need to update the `currentRotation` by some amount. The amount will probably be based on how frequently you draw.

Once you know the orientation you want for a given frame, you can perform ship movement by doing the following. Assume the `anchorPoint` is the point in the ship's local coordinate space that you want it to rotate around. Usually this would be the center of the ship.

```
glTranslatef(-anchor.x, -anchor.y, 0.0);
glRotatef(currentRotation, 0.0, 0.0, 1.0);
glTranslatef(anchor.x, anchor.y, 0.0);

```

If you then want to move it forward in the direction it's facing, you need to calculate the vector for that direction, and then multiply it by the distance you want to travel:

```
direction.x = cos(degreesToRadians(currentRotation)) * distance;
direction.y = sin(degreesToRadians(currentRotation)) * distance;

```

You can now translate it further by using the above vector:

```
glTranslatef(direction.x, direction.y, 0.0);

```

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


# Question
Title: The most efficient and accurate game loop?
Obviously for a game to work you need a game loop... Normally, my game loop would consist of something like this:

```
while(running){
    update();
    render();
    Thread.sleep(10);
}

```

This seemed to work fine at first, but then after I started to make my games a bit more complicated the frame rate of my game dropped by 90% in most cases, sometimes they would hang at around \<10fps on a high spec system just by simply rendering a couple of 2D image. So I thought to myself: "Should I try putting the render loop on a different thead?". With that in mind, I made a system similar to this:

```
new Thread(new Render()).start();
new Thread(new GameLogic()).start();

private class Render implements Runnable{
    public void run(){
       while(running){
          render();
      }
    }

private class GameLogic implements Runnable{
public void run(){
   while(running){
      update();
      Thread.sleep(10);
  }
}
}
}

```

This then caused the graphics to become out of sync with the game update, which then caused the occasional jitter which got quite annoying, later on, I then discovered a use where there is no wait in the loop itself and everything runs as fast as it can, but then you multiply everything in the gameLogic by a deltaTime variable to ensure the game movement is solid. Basically I want to know which way of implementing a game loop is most efficient and whether or not you should render and do gameLogic on the same loop.

# Answer
If your renderer is to slow to handle *"a couple of 2D images"*, it won't help to simply take the game loop into another thread.

But I assume that you are facing another problem. For a smooth frame rate you have around 16 milliseconds per frame. According to the code example you posted, your game loop includes a fixed the delay of 10 milliseconds.

```
Thread.sleep(10);

```

This line costs you 60% of the time you have each frame. So never stop the whole game thread for a fixed delay. With this error, it might even help to use another thread, but that won't solve the cause but the symptoms in your case.

What you want is maybe vertical sync. This is a technique which limit the frame rate to the refresh rate of the monitor, or to a fraction of it. But this feature requires the delay to be dynamically based on the actual frame duration. What it basically does is to let the thread sleep as long as it needs to take the whole 16 milliseconds. Note that most window managers provide an option for vertical sync. I am not familiar with Java but it should have provide it for you, too.

Using vertical sync, it makes sense limit at least to renderer thread and the window thread, since it doesn't make sense to render more frames than the monitor can show. Although it can make sense to run physics simulation in another thread to not slow it down. Despite that, multiple threads in game development are used mainly for the reason of making use of multi core processors. But accessing only one of your cores isn't a bottleneck if you are just working with a couple of sprites.
> 6 votes

# Answer
well this is the game loop for minecraft, hope it helps!Also, I modified it a bit so it matches with your methods (originally it was tick();) :D

```
      this.requestFocus();
      long lastTime = System.nanoTime();
      double amountOfTicks = 60.0;
      double ns = 1000000000 / amountOfTicks;
      double delta = 0;
      long timer = System.currentTimeMillis();
      int frames = 0;
      while(isRunning) {
       long now = System.nanoTime();
       delta += (now - lastTime) / ns;
       lastTime = now;
       while(delta >= 1) {
        update();
        //updates++;
        delta--;
       }
       render();
       frames++;

       if(System.currentTimeMillis() - timer > 1000) {
        timer += 1000;
        frames = 0;
        //updates = 0;
       }
      }
      stop();

```
> 5 votes

---
Tags: java, game-loop
---


# Question
Title: How to interpolate server updates on the client for multiplayer?
I am implementing client-side prediction and an authoritative server multiplayer architecture. I am following along with the series of articles from http://www.gabrielgambetta.com/entity-interpolation.html

I am at a point of confusion and have a few questions.

Within my client game loop I have a sequence of actions that update the local state.

```
applyLocalUpdates(state, loopTime)
reconcileLastRemoteUpdate(state, loopTime)

```
* `applyLocalUpdates`

This updates all the entities positions based on their local physics and game logic simulation.
* `reconcileLastRemoteUpdate`

I am in the process of implementing this and is the point of confusion. My initial naive attempt takes the last received server state and sets each local entities position to that last remote one.

This produces a choppy update effect. When each server update comes in the entities jump to match that last server position.

This is where I am trying to add interpolation...

I have interpolation methods like `vec3.lerp(a,b,t)` and `quat.lerp(a,b,t)` which I use to update the position vector and rotation quaternion.

My unknown points are:

1. **Which values do I pass for `a` and `b` in the interpolation?**

Is this the most recent local state and the last server state?
2. **What value do I pass in for `t` in the interpolation?**

This I'm highly confused. Is this the difference of elapsed time between the last 2 server states?

Is it the difference of elapsed time between the last local update and the last server update?

Additionally, should I swap the order of execution between `applyLocalUpdates` and `reconcileLastRemoteUpdate` ?

# Answer
You want to interpolate between the last two server states, so these should be `a` and `b`. `t` should be a value between 0 and 1; at 0, the lerp is equal to `a`, at 1, it is equal to `b`, anything between that will result in an interpolation between them (reference). It looks like you would want to scroll `t` from 0 to 1 fluently while you wait for the next server state, which requires estimating the time between each update you receive from the server.

Very barebones pseudocode (requires consistent update times, which are not given in practice):

```
float upadteTime = pingServer()
vec3 a
vec3 b

localUpdate {
  if (serverUpdate) {
    a = b
    b = newServerState
    timeSinceLastUpdate = 0
  }

  localState = vec3.lerp(a, b, timeSinceLastUpdate / updateTime)
  timeSinceLastUpdate += deltaTime
}

```

This approach will, of course, double your lag, as your local state will always be between the last two server states. You could try to predict things from local state, which makes matters more complicated.

I am not sure what happens when `t` is not in the range 0 - 1; perhaps it could serve as a rudimentary form of prediction? You might want to try that or research on it.
> 2 votes

---
Tags: networking, multiplayer, client-server
---


# Question
Title: Make the components of an ECS polymorphic
I have implemented an entity component sytsem (ECS) in my game engine (SFML and C++ 17). An entity has an array of components. You can get a components by its type e.g.: `myEntity.GetComponent<RenderComponent>()`. So far so good.

**The problem**

Best to illustrate this point by an (admittedly oversimplified) example:

Some systems or possibly other components might want to be able to call `myEntity.GetComponent<RenderComponent>()` without knowing the type of that render component (e.g. whether it is a house render component with a sprite and a paritcle system for smoke or a character) but knowing that every render component has e.g. a `GetPixelMask()` method.

A more concrete case of this is the collision component that might be implemented as a collision box or a pixel mask that may come from any type of render component. However, every collision component would have a method `bool Contains(Position)`. I would like to be able to loop through all entities with a collition component and check whether e.g. the mouse click lies within them.

I want a clean solution. It must not use polymorphism, it should solve the problem in a neat way.

**Possible Solutions**

* This is bad code smell to me but still its a solution. Screw polymorphic behaivour and just add an if cause to the systems. Something like `If(myEntity.HasComponent<HouseRenderComponent>()) { /*Call method a*/ }` and `If(myEntity.HasComponent<CharacterRenderComponent>()) { /*Also call method a*/ }`
* Another solution would be to make it so that the component are 'configured'. This is my current solution which kinda works but isn't all to clean (I find). This would mean making some `RenderObject` base class and letting the `RenderComponent` manage a dictionary of `RenderObject` pointers. `RenderObject`s would have to be added through a method like AddRenderObject() and accessed through an id which isn't all too efficient (Not my biggest concirn here). However, every `RenderComponent` would have the same methods and the specific type of the `RenderComponent` would be defined through the `RenderObject`s added.

**Question**

I'm pretty sure that adding some kind of real polymorphism to the components would be possible and I could figure out how to do it. The question is: is that good design? - as for me it kind of defeats the point of the ECS. I'd be grateful if you could share your experiences and how you have dealt with this. I can't be the first one to have come across this problem!

Thanks for your help!

# Answer
> 3 votes
Both your possible solutions are unnecessarily complicated or brittle: generally, ill-advised.

**Polymorphism**

Your question title is

> Make the components of an ECS polymorphic

but then you don't want to use polymorphism since you state,

> I basically just want a clean solution. It must not use polymorphism, it should solve the above problem in a neat way.
>
> ...
>
> I'm pretty sure that adding some kind of real polymorphism to the components would be possible and I could figure out how to do it.

So you contradict yourself utterly. You want polymorphism without using polymorphism, is that it?

Since you have given no reason as to why you think polymorphism in an ECS is problematic, I can tell you straight off the cuff that it is, 99% of the time, normal and desirable in engines and ECS. Polymorphism is little more than a function pointer, which is a way to redirect logic without the costly use of conditionals (`if`, `for`, `while`, `for each`, `?` etc.) whose use you suggest in ex. #2. I've implemented polymorphism in C (which lacks it) and it is a very simple and efficient concept.

So, polymorphism *is* the neat and elegant solution. That's why it's such a widespread approach.

**Iteration**

> I would like to be able to loop through all entities with a collision component

OK, then every time you create a new collidable entity, you add that entity to a separate list/vector that contains all collidable entities, OR (better yet), add its component (which has a back-reference to its owning entity) to such a list/vector. Update same whenever an entity / component dies.

**Golden Rule**

Keep things simple in engineering - don't overcomplicate - or you will very quickly get yourself into ruts you cannot easily get out of, and that way lies a loss of motivation to get your project flying.

---
Tags: c++, software-engineering, entity-system, polymorphism
---


# Question
Title: Use heightmaps or direct vertex manipulation for runtime terrain editing in UE4?
I am creating a terrain editor and creator for in our game, in which we should be able to create hills and dales, create different shapes(forms) in the terrain etc. I came up with 2 approaches on achieving what we want,

**1.** modify 2d heightmaps by darkening / lightening colours; update terrain vertices based thereon.

**2.** Create a plane and modify the vertices of the plane to shape what we want.

So my question is, which way would be faster/better for a ingame terrain editor? And why would you recommend that?

Or, if you know of a better way, I would love to hear.

Thanks

# Answer
(1) Provides an intermediate data structure.

(2) Is exactly the same as (1) but it provides no such structure.

Do you need an intermediate tonal heightmap? If you don't, then don't use one. Individual vertex *typically* offers finer control over terrain, which from an aesthetic perspective is preferable. You can also have the heightmap represent the heights of *vertices* and not *tiles*, which you may mean in (1).

For example, a game where the player must be able to stand on a flat tile at every point (think Minecraft) is better off using a heightmap, since otherwise you will have non-flat tiles if you edit vertices individually.
> 0 votes

---
Tags: terrain, unreal-4, vertex, procedural, world-editor
---


# Question
Title: Mix of Procedural and Manual level design / creation in UE4
I'm trying to design a maze using a mix of procedural and manual generation. I have the maze already generated and would like to place other objects in the maze manually in the editor. The issue is the maze object is created on BeginPlay and so I'm unable to view it in the Editor itself while dragging the object to the Outliner. Any suggestions?

I'm thinking of doing something in the Construction Script or the object Constructor but not not sure if that would be the way to go.

I'm still getting familiar with the Engine code base and only have a little experience in Maya or Blender since I'm a programmer.

# Answer
What you want is to run code from within the editor that creates the actors that represent your maze and saves them in the level you have open. Then you can position the maze however you want and place objects within it. Most likely you will do this through an editor plugin.

You'll need to look up how to create an editor module either inside a plugin or alongside your game module. After that creating a property inspector for the maze generation properties and a button to create the actors in the current editor world.

When creating a new plugin from within the UE4 editor there is a dropdown for choosing what sample you want to start with as well. Exploring a few of those options might give you some clues on your way forward.

UE4 Editor Extention Live Training This one is a bit out of date personally but it's great for performing helper tasks when in the editor

There are a ton of resources on UE4 editor extensions. I don't think that I could fit an entire tutorial into an answer. But hopefully it puts you onto the right track.
> 0 votes

---
Tags: procedural-generation, unreal-4, level-design
---


# Question
Title: Equal objects with independent variables in Game Maker?
Think of a situation with two distinct runners with different speeds. They will have to walk a circuit in a straight line with two obstacles (police).

Below is an illustration of the situation:

The problem I'm having is the following:

Assuming that runner two is faster than runner one, it is certain that he will reach the first hurdle earlier. Upon reaching this obstacle (detection event) he will be stopped for five seconds, long enough for the runner to reach him.

However the runner one will go through this obstacle without any loss of time, since the policeman is already taking care of the runner two.

Runner one still manages to get to the second obstacle with runner two still standing ... Then the problem arises because as they are equal objects the game assumes that the policeman is already taking care of the runner two, so the runner one passes straight through.

I would like to know how to do each object independently (detection event).

Sorry for the translation errors! Thanks!!!

---

Codes:

Movement (obj\_control) =\>

```
move_towards_point(obj_runner_01.x,obj_runner_01.y-1,obj_runner_01.manSpeed);
move_towards_point(obj_runner_02.x,obj_runner_02.y-1,obj_runner_02.manSpeed);
```

Collision detection (detector) =\>

event\_colision...

```
if obj_detector.detector_runner_01==false{
    randomize(); //in the original case, there is a chance the runner will not be stopped
    numRandom=irandom(99)+1;
    obj_detector.detector=true;
}

if manColision==false{
    if numRandom<=manAtrat*0{ //test value
        manColision=true;
    }else{
        time_runner_01+=1;
        if time_runner_01<150{
            if obj_detector.stopped==false{ //variable that indicates that there is a stopped runner
                move_towards_point(x,y,0);
            }else{
                time=150;
            }
        }else{
            if pos==1{
                move_towards_point(x,y+1,manSpeed);
            }
            if pos==2{
                move_towards_point(x-1,y,manSpeed);
            }
            if pos==3{
                move_towards_point(x,y-1,manSpeed);
            }
            if pos==4{
                move_towards_point(x+1,y,manSpeed);
            }

            obj_detector.stopped=true;
            manColision=true;
        }
    }
}
```

**OBS- THE ORIGINAL CODE DOES NOT AND SO, CONTAIN OTHER THINGS, I EDITED THE NAMES OF THE VARIABLES TO MAKE SIMPLES THE UNDERSTANDING**

---

To see if it is possible to have independent variables between equal objects I did a test =\>

obj\_detector (box with star) create event =\>

```
test=irandom(10);
```

obj\_detector (draw event) =\>

```
draw_self();
draw_text(x-10,y,test);
```

Three different values for the same variable in the same object!!!

# Answer
> 0 votes
I got the desired result using just one variable from an ini file.

This variable served to feed the detector vector, so that at the time of executing the event, it only performed on what was taking care of a runner.

```
ini_open("info.ini");
    contador=ini_read_real("var", "contador", 1);
    ID=contador;
    parada[ID]=false;
    contador+=1;
    ini_write_real("var", "contador", contador);
ini_close();
```

Detail that one can only modify a vector variable with an event (self). I had to split the collision code with the runner in 3 parts

1 - self =\> code 2 - runner =\> move\_towards\_point (runner) 3 - self =\> reset variables

# Answer
> 1 votes
There are many ways to do it. For example:

`obj_runner` Create

```
spd = 1;
passed = array_create( instance_number(obj_stop) ); // array of passed points
finished = false;

```

`obj_runner` Step

```
if alarm[0] = -1 and !finished
    y -= spd;

```

`obj_runner` Collision with police

```
var point_index = other.index;

if alarm[0] < 0 and passed[point_index] = 0
{
    passed[point_index] = true;
    alarm[0] = other.time;
}

```

`obj_runner` Collision with finish

```
finished = true;

```

`obj_runner` Alarm 0

```
/// empty

```

`obj_stop` (police) Create

```
time = room_speed;  // 1 second

if !variable_global_exists("count_number")
    global.count_number = 0;

index = global.count_number++;

```

I made a small example, check it.

---
Tags: game-maker, objects
---


# Question
Title: Turning a 2D character to face left or right
So far I know of the following ways to turn a 2D character to face the other direction (in my case the char can only walk left or right):

1. Mirror the right walk animation and use that as a separate state in the animation controller.
2. Simply set a 180 rotation on the game object that hold all of my characters parts when he turns the other way.
3. Create a transition animation by blending (I don't know if it's called exactly like this) the left oriented sprite and the right one.
4. Orient the sprite based on its movement direction using this code:

```
void OrientChar()
{
    Vector3 moveDirection = gameObject.transform.position - _origPos;
    if(moveDirection != Vector3.zero)
    {
        float angle = Mathf.Atan2(moveDirection.y, moveDirection.x) * Mathf.Rad2Deg;
        gameObject.transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
    }
}

```

1 and 2 will create a rather abrupt change and might not look smooth. How do I make them or is it possible to make them smooth?

For number 3 I have a very basic idea on how to do it. Can I do it directly Unity?

# Answer
> 1 votes
The best way to rotate a 2D character is to change the localScale from 1 to -1. This will allow you to place normal maps and have dynamic lighting affect your character. You shouldn't rotate your character while using a 2D character unless you want the paper-ish, textbook affect.

---
Tags: unity, character
---


# Question
Title: Is a large-scale simulation of movable land possible?
I was recently reading about a nuclear waste containment area buried far beneath the desert in New Mexico (WIPP), and upon looking at diagrams I wondered if it would be possible to create something of the sort in a game/sandbox.

Imagine a square mile of land with packed yet completely movable sand/soil that can be excavated using any tools you see necessary. Under the soil would be rock that can be drilled or broken through just as in real life. Think Minecraft, but without the blocks and instead particles that behave near how they would in the real world.

What's stopping games/sims like this from being created, and is there any prospect of a realistic earth-moving sandbox in the future?

# Answer
Possible? Heck, I created one!

This video shows an excavator digging and ripping soil. It also has a bulldozer "moving" a hill-side.

Also, it is a real 3D terrain, not just a height map. Which means you can dig overhangs, or tunnels if need be.

https://www.youtube.com/watch?v=54o1fttLqQs

Done with a dual-representation of particles, that are fused into soil by running Marching Cubes over a 3D scalar field.

Note that it is free on steam if you want to try it out for yourself.
> 0 votes

---
Tags: simulations
---


# Question
Title: I have a switch cameras script and two cameras but the switching is not working good. How can I manage all the null exceptions?
when one camera is active the other/s are disabled. Each time only the current switched to the camera is active and the others are disabled.

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class SwitchCameras : MonoBehaviour
{
    private bool cycleAllCameras = false;
    public Camera[] storedCameras;

    public Vector3[] _originalPositions;
    public Vector3[] _lastPositions;
    public Camera[] _currentCameraSequence;
    public Camera[] _allCameras;
    int _currentCameraIndexInCycle;
    int _currentCameraIndexInAll;

    // Rather than store the current camera's index, AND its reference,
    // AND its name, AND its position, AND its original position...
    // let's just store its index, and everything else can be inferred
    // from that, so we don't have redundant data that can go out of sync.
    public Camera currentCamera
    {
        get
        {
            return _currentCameraSequence[_currentCameraIndexInCycle];
        }
    }

    void Start()
    {
        // Cache all cameras enabled at the start of the scene;
        _allCameras = Camera.allCameras;
        _originalPositions = new Vector3[_allCameras.Length];
        _lastPositions = new Vector3[_allCameras.Length];

        // Select the first camera in whichever list we're using
        _currentCameraSequence = cycleAllCameras ? _allCameras : storedCameras;
        Camera currentCamera = this.currentCamera;

        // Disable every camera except the one we're using,
        // and cache their original positions to use later.
        for (int i = 0; i < _allCameras.Length; i++)
        {
            _allCameras[i].enabled = (_allCameras[i] == currentCamera);
            _lastPositions[i] = _originalPositions[i] = _allCameras[i].transform.position;
        }
    }

    void LateUpdate()
    {
        // Update the current camera's last position,
        // before we switch from it to a dormant one.
        _lastPositions[_currentCameraIndexInAll] = currentCamera.transform.position;

        // Use a named input so the user can remap it.
        if (Input.GetKeyDown(KeyCode.G))
            CycleCamera();
    }

    public void SwitchSequence()
    {
        if (_currentCameraSequence.Length > 0)
        {
            cycleAllCameras = !cycleAllCameras;
            CycleCamera();
        }
    }

    // Cycle action is in its own public method, in case you
    // want to trigger it from other scripts or UI buttons.
    public void CycleCamera()
    {
        currentCamera.enabled = false;

        // If we've swapped sequences, re-index the camera.
        if (_currentCameraSequence == storedCameras)
        {
            if (cycleAllCameras == true)
            {
                _currentCameraIndexInCycle = _currentCameraIndexInAll;
                _currentCameraSequence = _allCameras;
            }
        }
        else if (cycleAllCameras == false)
        {
            _currentCameraIndexInCycle = Mathf.Max(0, System.Array.IndexOf(storedCameras, currentCamera));
            _currentCameraSequence = storedCameras;
        }

        // Step to the next camera, and wrap around the sequence.
        _currentCameraIndexInCycle = (_currentCameraIndexInCycle + 1) % _currentCameraSequence.Length;

        // Ensure we have a valid index into the "all" list
        // for looking up original position / last position / etc.
        _currentCameraIndexInAll = System.Array.IndexOf(_allCameras, currentCamera);

        //
        currentCamera.enabled = true;
    }
}

```

I have two problems.

The first is that in the editor in the Inspector of the SwitchCameras script I cant change the size of the storedCameras variable. No matter what value I type in the array in the inspector if it's 2 or 1 or 30 it's all the time turn back to 0. And the game is not running yet. I can drag cameras to the storedCameras but I cant change its size if I'm typing a number.

The second problem is that one of the cameras is First Person and there is a script attached to it: FirstPersonController and this script are using the Main Camera with the variable m\_Camera. The problem is when I'm running the game the first active camera is another camera and the main camera is disabled so I'm getting many exceptions null exceptions since the main camera is disabled(NULL) so also m\_camera is null:

```
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using UnityStandardAssets.Utility;
using Random = UnityEngine.Random;

namespace UnityStandardAssets.Characters.FirstPerson
{
    [RequireComponent(typeof (CharacterController))]
    [RequireComponent(typeof (AudioSource))]
    public class FirstPersonController : MonoBehaviour
    {
        [SerializeField] private bool m_IsWalking;
        [SerializeField] private float m_WalkSpeed;
        [SerializeField] private float m_RunSpeed;
        [SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten;
        [SerializeField] private float m_JumpSpeed;
        [SerializeField] private float m_StickToGroundForce;
        [SerializeField] private float m_GravityMultiplier;
        [SerializeField] private MouseLook m_MouseLook;
        [SerializeField] private bool m_UseFovKick;
        [SerializeField] private FOVKick m_FovKick = new FOVKick();
        [SerializeField] private bool m_UseHeadBob;
        [SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob();
        [SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob();
        [SerializeField] private float m_StepInterval;
        [SerializeField] private AudioClip[] m_FootstepSounds;    // an array of footstep sounds that will be randomly selected from.
        [SerializeField] private AudioClip m_JumpSound;           // the sound played when character leaves the ground.
        [SerializeField] private AudioClip m_LandSound;           // the sound played when character touches back on ground.

        private Camera m_Camera;
        private bool m_Jump;
        private float m_YRotation;
        private Vector2 m_Input;
        private Vector3 m_MoveDir = Vector3.zero;
        private CharacterController m_CharacterController;
        private CollisionFlags m_CollisionFlags;
        private bool m_PreviouslyGrounded;
        private Vector3 m_OriginalCameraPosition;
        private float m_StepCycle;
        private float m_NextStep;
        private bool m_Jumping;
        private AudioSource m_AudioSource;

        // Use this for initialization
        private void Start()
        {
            m_CharacterController = GetComponent<CharacterController>();
            m_Camera = Camera.main;
            m_OriginalCameraPosition = m_Camera.transform.localPosition;
            m_FovKick.Setup(m_Camera);
            m_HeadBob.Setup(m_Camera, m_StepInterval);
            m_StepCycle = 0f;
            m_NextStep = m_StepCycle/2f;
            m_Jumping = false;
            m_AudioSource = GetComponent<AudioSource>();
            m_MouseLook.Init(transform , m_Camera.transform);
        }

        // Update is called once per frame
        private void Update()
        {
            if (Camera.main != null)
            {
                m_Camera = Camera.main;
            }
            else
            {
                return;
            }
            RotateView();
            // the jump state needs to read here to make sure it is not missed
            if (!m_Jump)
            {
                m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
            }

            if (!m_PreviouslyGrounded && m_CharacterController.isGrounded)
            {
                StartCoroutine(m_JumpBob.DoBobCycle());
                PlayLandingSound();
                m_MoveDir.y = 0f;
                m_Jumping = false;
            }
            if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded)
            {
                m_MoveDir.y = 0f;
            }

            m_PreviouslyGrounded = m_CharacterController.isGrounded;
        }

        private void PlayLandingSound()
        {
            m_AudioSource.clip = m_LandSound;
            m_AudioSource.Play();
            m_NextStep = m_StepCycle + .5f;
        }

        private void FixedUpdate()
        {
            if (Camera.main != null)
            {
                m_Camera = Camera.main;
            }
            else
            {
                return;
            }

            float speed;
            GetInput(out speed);
            // always move along the camera forward as it is the direction that it being aimed at
            Vector3 desiredMove = transform.forward * m_Input.y + transform.right * m_Input.x;

            // get a normal for the surface that is being touched to move along it
            RaycastHit hitInfo;
            Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo,
                               m_CharacterController.height / 2f, Physics.AllLayers, QueryTriggerInteraction.Ignore);
            desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized;

            m_MoveDir.x = desiredMove.x * speed;
            m_MoveDir.z = desiredMove.z * speed;

            if (m_CharacterController.isGrounded)
            {
                m_MoveDir.y = -m_StickToGroundForce;

                if (m_Jump)
                {
                    m_MoveDir.y = m_JumpSpeed;
                    PlayJumpSound();
                    m_Jump = false;
                    m_Jumping = true;
                }
            }
            else
            {
                m_MoveDir += Physics.gravity * m_GravityMultiplier * Time.fixedDeltaTime;
            }
            m_CollisionFlags = m_CharacterController.Move(m_MoveDir * Time.fixedDeltaTime);

            ProgressStepCycle(speed);
            UpdateCameraPosition(speed);

            m_MouseLook.UpdateCursorLock();
        }

        private void PlayJumpSound()
        {
            m_AudioSource.clip = m_JumpSound;
            m_AudioSource.Play();
        }

        private void ProgressStepCycle(float speed)
        {
            if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0))
            {
                m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))*
                             Time.fixedDeltaTime;
            }

            if (!(m_StepCycle > m_NextStep))
            {
                return;
            }

            m_NextStep = m_StepCycle + m_StepInterval;

            PlayFootStepAudio();
        }

        private void PlayFootStepAudio()
        {
            if (!m_CharacterController.isGrounded)
            {
                return;
            }
            // pick & play a random footstep sound from the array,
            // excluding sound at index 0
            int n = Random.Range(1, m_FootstepSounds.Length);
            m_AudioSource.clip = m_FootstepSounds[n];
            m_AudioSource.PlayOneShot(m_AudioSource.clip);
            // move picked sound to index 0 so it's not picked next time
            m_FootstepSounds[n] = m_FootstepSounds[0];
            m_FootstepSounds[0] = m_AudioSource.clip;
        }

        private void UpdateCameraPosition(float speed)
        {
            Vector3 newCameraPosition;
            if (!m_UseHeadBob || m_Camera == null)
            {
                return;
            }
            if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded)
            {
                m_Camera.transform.localPosition =
                    m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude +
                                      (speed*(m_IsWalking ? 1f : m_RunstepLenghten)));
                newCameraPosition = m_Camera.transform.localPosition;
                newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset();
            }
            else
            {
                newCameraPosition = m_Camera.transform.localPosition;
                newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset();
            }
            m_Camera.transform.localPosition = newCameraPosition;
        }

        private void GetInput(out float speed)
        {
            // Read input
            float horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
            float vertical = CrossPlatformInputManager.GetAxis("Vertical");

            bool waswalking = m_IsWalking;

#if !MOBILE_INPUT
            // On standalone builds, walk/run speed is modified by a key press.
            // keep track of whether or not the character is walking or running
            m_IsWalking = !Input.GetKey(KeyCode.LeftShift);
#endif
            // set the desired speed to be walking or running
            speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed;
            m_Input = new Vector2(horizontal, vertical);

            // normalize input if it exceeds 1 in combined length:
            if (m_Input.sqrMagnitude > 1)
            {
                m_Input.Normalize();
            }

            // handle speed change to give an fov kick
            // only if the player is going to a run, is running and the fovkick is to be used
            if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0)
            {
                StopAllCoroutines();
                StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown());
            }
        }

        private void RotateView()
        {
            m_MouseLook.LookRotation (transform, m_Camera.transform);
        }

        private void OnControllerColliderHit(ControllerColliderHit hit)
        {
            Rigidbody body = hit.collider.attachedRigidbody;
            //dont move the rigidbody if the character is on top of it
            if (m_CollisionFlags == CollisionFlags.Below)
            {
                return;
            }

            if (body == null || body.isKinematic)
            {
                return;
            }
            body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse);
        }
    }
}

```

I tried to add in the Update and FixedUpdate in both places the same small code:

```
if (Camera.main != null)
            {
                m_Camera = Camera.main;
            }
            else
            {
                return;
            }

```

But it didn't solve the problems. Once I'm switching to the main camera I'm getting null exceptions on m\_camera.

The main goal is to switch between stored cameras for example if I added 2 cameras to stored cameras switch between them. If I clicked on the button Switch Sequence then now I will be able to switch between all the cameras and not only the two stored.

But something here I messed up.

# Answer
> 1 votes
# `m_Camera` is a cached reference; `Camera.main` is not

When you change what camera is enabled, this changes the result of `Camera.main` (as `Camera.main` litterally does an uncached `GameObject.FindWithTag("MainCamera")` call), but you do nothing to update the value of your `m_Camera`.

This is why

```
if (Camera.main != null) //not that this should ever be false...
{
    m_Camera = Camera.main;
}

```

"fixes" your issue: it reassigns the current value of `Camera.main`. If you did this inside `CycleCamera` instead, you wouldn't need your check at all.

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


# Question
Title: How can I check if player is an operator in Forge?
In Minecraft Forge, I would like to know if there is any way to find out if a player currently has vanilla "OP" / "Operator" status. I can't find a method that does this on the EntityPlayer Class.

I'd like something like:

```
EntityPlayer player = (EntityPlayer)sender;
if (player.getOpStatus) {
    [do some stuff]
}

```

# Answer
Using `EntityPlayerMP#canCommandSenderUseCommand(int permLevel, String commandName)` might be a way to find out if a player is an operator.
> 2 votes

---
Tags: minecraft-modding, modding
---


# Question
Title: How to create activity again in Android?
I am making some game and I want to create activity again after click on some Button.

For example: I have activities A (game) and B (after game menu). I want to go back to activity A after clicking "Play again" in activity B. But I don't want to resume it but to create it again, so it starts from the beginning. Is there any way of doing this?

I am using android studio.

# Answer
> 1 votes
When you are finished with an Activity you can destroy it. This means that it won't be running in the background. You can then call a new instance of the activity. This avoids creating and running several instances at the same time. I have created some basic code below and annotated it.

**Menu**

```
public class MenuActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {...}

    //Method called when button is clicked
    public void PlayAgain(View view){

        /*
        Start activity used to create the new activity
        Calling a new Intent to change from this activity to the GameActivity
        */
        startActivity(new Intent(this, GameActivity.class));
        //Telling this to finish - ending the activity
        this.finish();
    }
}

```

**GameActivity**

```
public class GameActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {...}
    /*
    Method called when criteria is met to end the activity
    eg: time limit or score condition
    */
    public void onGameFinish(){
        //Same as the menu button, changing activities.
        startActivity(new Intent(this, MenuActivity.class));
        //Ending this activity when we are done with it.
        this.finish();
    }
}

```

Hope this helps - All the best.

---
Tags: android, android-studio
---


title: Unity Ball moving inside the surface

text:
# Question
Title: Unity Ball moving inside the surface
My ball is jumping on a 3d cylinder, and sometimes the ball gets stuck inside the cylinder. The ball has a rigid body and it's continuously dynamic. The circle also has a mesh collider. Here is the code to make the ball jump:

```
void Update () {

    if(Mathf.Sign(rg.velocity.y)==-1){

        isforceApplied=true;
    }

}

void OnCollisionEnter(Collision collisionInfo)
{

    if(isforceApplied==true){

        isforceApplied=false;
        rg.AddForce(transform.up*forceAmount,ForceMode.Impulse);

    }

}

```

# Answer
Some suggestions:

1. Change your balls' mesh collider to a sphere collider.
2. Instead of bouncing your ball with code i'd just add a physics material to your collider.
3. If your ball is passing through the floors and it has a rigid body and a sphere collider (is Trigger = false) it could be down to an animator, if you're using one.
4. Is your mesh collider Convex?
5. Is your collider to the correct size?
6. check the mesh collider on your floor and see if thats set to convex.

Good luck
> 1 votes

# Answer
Here are a few other checks and changes you could do...

As was said by Nilmag, use a sphere collider set to the same radius as the sphere mesh, instead of a mesh collider.

You should also change Update() to FixedUpdate().

Within OnCollisionEnter(...), you could loop through the collisionInfo.contacts array, and check to make sure that one of the contacts.normal.y is greater than something like 0.5f. This would make sure the sphere would only jump if it's made contact with the ground. However, if you want the sphere to jump from any surface it collides with, you could skip the loop through the contact points, and change 'transform.up * forceAmount' to 'collisionInfo.contacts\[0\].normal * forceAmount'.

Otherwise, make sure that transform.up is always pointing up. For instance if transform is from the object with the rigidbody attached to it, it might rotate if there are no rotation constraints on it.
> 1 votes

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


# Question
Title: Unity: How to cut out a transparent area from a RenderTexture?
After rendering onto a **RenderTexture**, is there a way to make areas of the **RenderTrexture** transparent again? I.e. cutting out a transparent window to see what's behind the **RenderTexture**?

The scene's setup looks like this:

1. **RenderTexture** with **Color Format** set to **ARGB32**.
2. Dedicated **camera** to render onto the **RenderTexture**.
    * **Clear Flags** is set to **Solid Color**
    * **Background** is set to a color with **0x00** Alpha.
3. The **RenderTexture** is mapped onto a **GUI Panel** using a **RawImage** component.

This works pretty well. The content of the **RenderTexture** is composed every frame and shown at the **GUI Panel**. The only difficulty is how to delete/clear parts of the RenderTexture to expose what's behind it.

Ideal would be using an image as mask - where every opaque (or transparent - either one is fine) pixel from the mask gets deleted (fully transparent) on the **RenderTexture**. Do you have any ideas how this can be done?

# Answer
I'd create a depth mask for that.

Follow this tutorial, i've used this one in the past and it would produce your desired result.

https://www.youtube.com/watch?v=uxXEV91xsSc

Code from the video (credits for video: https://www.blog.radiator.debacle.us/2012/08/how-to-dig-holes-in-unity3d-terrains.html)

**Custom Depth Shader**

```
//Place onto the object you want to see things through i.e. window / hole

    Shader "Custom/CustomDepthShader" {
      SubShader {
        Tags {"Queue" = "Geometry+10" }
        Lighting Off
        ZTest LEqual
        ZWrite On
        ColorMask 0
        Pass {}
      }
    }

```

**Custom Depth Shader Terrain**

```
// Unity built-in shader source. Copyright (c) 2016 Unity Technologies. MIT license (see license.txt)
// Unity Standard terrain shader + custom "Queue" = "Geometry+100"

Shader "Custom/CustomDepthShader(Terrain)" {
    Properties {
        [HideInInspector] _Control ("Control (RGBA)", 2D) = "red" {}
        [HideInInspector] _Splat3 ("Layer 3 (A)", 2D) = "white" {}
        [HideInInspector] _Splat2 ("Layer 2 (B)", 2D) = "white" {}
        [HideInInspector] _Splat1 ("Layer 1 (G)", 2D) = "white" {}
        [HideInInspector] _Splat0 ("Layer 0 (R)", 2D) = "white" {}
        [HideInInspector] _Normal3 ("Normal 3 (A)", 2D) = "bump" {}
        [HideInInspector] _Normal2 ("Normal 2 (B)", 2D) = "bump" {}
        [HideInInspector] _Normal1 ("Normal 1 (G)", 2D) = "bump" {}
        [HideInInspector] _Normal0 ("Normal 0 (R)", 2D) = "bump" {}
        // used in fallback on old cards & base map
        [HideInInspector] _MainTex ("BaseMap (RGB)", 2D) = "white" {}
        [HideInInspector] _Color ("Main Color", Color) = (1,1,1,1)
    }

    CGINCLUDE
        #pragma surface surf Lambert vertex:SplatmapVert finalcolor:SplatmapFinalColor finalprepass:SplatmapFinalPrepass finalgbuffer:SplatmapFinalGBuffer noinstancing
        #pragma multi_compile_fog
        #include "TerrainSplatmapCommon.cginc"

        void surf(Input IN, inout SurfaceOutput o)
        {
            half4 splat_control;
            half weight;
            fixed4 mixedDiffuse;
            SplatmapMix(IN, splat_control, weight, mixedDiffuse, o.Normal);
            o.Albedo = mixedDiffuse.rgb;
            o.Alpha = weight;
        }
    ENDCG

    Category {
        Tags {
            "Queue" = "Geometry+100"
            "RenderType" = "Opaque"
        }
        // TODO: Seems like "#pragma target 3.0 _TERRAIN_NORMAL_MAP" can't fallback correctly on less capable devices?
        // Use two sub-shaders to simulate different features for different targets and still fallback correctly.
        SubShader { // for sm3.0+ targets
            CGPROGRAM
                #pragma target 3.0
                #pragma multi_compile __ _TERRAIN_NORMAL_MAP
            ENDCG
        }
        SubShader { // for sm2.0 targets
            CGPROGRAM
            ENDCG
        }
    }

    Dependency "AddPassShader" = "Hidden/TerrainEngine/Splatmap/Diffuse-AddPass"
    Dependency "BaseMapShader" = "Diffuse"
    Dependency "Details0"      = "Hidden/TerrainEngine/Details/Vertexlit"
    Dependency "Details1"      = "Hidden/TerrainEngine/Details/WavingDoublePass"
    Dependency "Details2"      = "Hidden/TerrainEngine/Details/BillboardWavingDoublePass"
    Dependency "Tree0"         = "Hidden/TerrainEngine/BillboardTree"

    Fallback "Diffuse"
}

```

**Hide Object**

```
//Add to any object you want to hide when looking through the depthmask (DOES NOT WORK ON TERRAIN, USE CUSTOM TERRAIN SHADER)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HideObject : MonoBehaviour {

    void  Start (){
        // get all renderers in this object and its children:
        var renders = GetComponentsInChildren<Renderer>();
        foreach(Renderer rendr in renders){
            rendr.material.renderQueue = 3000;
        }
    }
}

```
> 1 votes

---
Tags: unity
---


# Question
Title: How is Unity's GetComponent implemented in C#
I'm just curious that what aspects of the C# language Unity's `GetComponent` method uses.

In the C# language we have reflection that lets programmers access a variable by its type. Is `GetComponent` just some type of reflection C# for certain Unity defined types?

# Answer
> 4 votes
Various users have decompiled the Unity engine to peek at how it works inside, but when you get to the core methods, they tend to just be wrappers calling into native code compiled from C++, rather than being implemented in C# at all.

```
/// <summary>
///   <para>Returns the component of Type type if the game object has one attached, null if it doesn't.</para>
/// </summary>
/// <param name="type">The type of Component to retrieve.</param>
[WrapperlessIcall]
[TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)]
[MethodImpl(MethodImplOptions.InternalCall)]
public Component GetComponent(System.Type type);

[WrapperlessIcall]
[MethodImpl(MethodImplOptions.InternalCall)]
internal void GetComponentFastPath(System.Type type, IntPtr oneFurtherThanResultValue);

[SecuritySafeCritical]
public unsafe T GetComponent<T>()
{
  CastHelper<T> castHelper = new CastHelper<T>();
  this.GetComponentFastPath(typeof (T), new IntPtr((void*) &castHelper.onePointerFurtherThanT));
  return castHelper.t;
}

```

And the `CastHelper` referenced above is just this struct:

```
internal struct CastHelper<T>
{
  public T t;
  public IntPtr onePointerFurtherThanT;
}

```

It appears to use the fact that `onePointerFurtherThanT` comes immediately after `t` in the struct definition to find the address of the reference `t`, so that the native code called in `GetComponentFastPath` can write the appropriate reference in place to be returned.

# Answer
> 2 votes
The sourcecode for the implementation of GetComponent isn't available, so we can only guess how it is actually implemented. So I can only say how **I** would implement this.

You can get the class of an object at runtime using the method `GetType` of `Object`. When an object got multiple components and the caller wants to get the component of a specific type, there are two ways to do this:

1. Each time `GetComponent` is called, iterate all components of the entity until you find one where `component.GetType() == requestedType`
2. Keep a `Dictionary<Type, Component> components` in each entity. When `GetComponent` is called, look it up in the dictionary.

The first method would be faster when there are only very few components on each entity while the latter would be faster if you have many.

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


# Question
Title: Can I publish the games I learnt from tutorials and modified as per my style of game-play?
I am new to the world of making games and all. Well its been a few months or so. There are many tutorials that I have been watching. *On the way, I made a few games that I saw and made. I am not asking about those. In fact I don't want to publish those games in my name ever.* But then there are some small games that I made which are modified version from what I learnt of those games. Like I changed the game-play style, made it simpler and ignored some features from a game. **Can I publish them in play store? Or this would be any break of law or something? or Something that I should not do?**

# Answer
> 2 votes
I am not a lawyer. This is a layman interpretation of copyright law which might be wrong. Also keep in mind that copyright laws might be slightly different in different parts of the world.

---

When you create an own game based on code from a tutorial, you are creating a derivative work. That means you need the permission of the copyright holder of the tutorial. Check if the author says anything about the software license of the example code. When in doubt, contact the author and ask for a confirmation that you have permission. Most people who post tutorials on the internet actually *want* to help people to publish their own games. So they are likely to cooperate with you.

However, I can not deny that there might be people who try to trick people into using their code just so they can then sue them. I haven't heard of this yet in the context of programming tutorials, but it would be far from the scummiest abuse of copyright law I have ever heard of. So be careful if you can not get any implicit consent (through license conditions) or explicit consent (through personal permission).

When you are not actually using any code from the tutorial but rather just use the techniques and knowledge from the tutorial to write your own code, then you won't violate copyrights, but you might be violating software patents.

---

By the way, all code you find on Stack Exchange is licensed under the CC-BY-SA 3.0 license. I alternatively make all my personal code contributions on the SE network available under the terms of the WTFPL 2.0 unless stated otherwise.

# Answer
> 1 votes
https://www.reddit.com/r/Unity3D/comments/81s1qa/is\_it\_morally\_incorrect\_to\_use\_a\_tutorial\_from/

Is this you? I would recommend any new developer against asset flipping, the market is already saturated with this sort of thing. If you want to release the game, which is similar in style to the tutorial, i would suggest taking significant steps in making the game your own to: 1, avoid any legal repercussions. 2, make it stand out from the rest.

---
Tags: android, game-design, copyright, google-play
---


title: Simple openGL code paradox

text:
# Question
Title: Simple openGL code paradox
I'm trying to create the most basic application that will draw a cube using indices and textures for starters, but nothing about it makes any sense whatsoever.

I ran it on my machine with an nVidia card and the display driver (latest, not that it matters) crashes (null ref), along with the program on the `glDrawElements(...)` command (`Renderer.cpp`). Fine. Then I sent it to a friend of mine who has an AMD card to try to debug it because I was unable to find the bug in the code, and the program worked (didn't crash) on his machine.

That surprised me since I only did the most basic openGL stuff, no way it was vendor specific. To get to the bottom of this, I downloaded APItrace (http://apitrace.github.io/) to try to see what's going on under the hood of my machine and why does my driver crash.

Once I dumped the trace after I ran the program, it said that the shader program linker failed because I didn't write to gl\_Position (which I have).

The problem is that the program links just fine in VS debugger and no error is returned there. So it just keeps getting weirder.

If you want to mess with this, you can get the code (commit with issue linked) at https://github.com/Karlovsky120/7DaysWorldEditor/commit/e86b8be40c81511c4416dc5e253b90e42a5a8ec0

I don't think you'd see the bug if I just pasted the code here, there must be a mistake with the setup somewhere.

I really made an effort to make this as hassle free as possible, it's just one click install: clone it, build it, and you're good to go, no additional setup required. You will need to open it with VS2017 though.

There's a lot of classes in the code, but all of the relevant code is in `Scene.cpp` and any of the classes it references.

Thank you for any help you give, even if it's just a guess at what might be wrong because I'm at my wits end here.

# Answer
Right before the draw call, there is a single line of code missing. I failed to bind the index buffer, which resulted in null ref on the card.

The line in question is: `glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 1);`

It should go right before the draw call.
> 1 votes

# Answer
Loader.cpp, line 112:

```
glBufferData(GL_ELEMENT_ARRAY_BUFFER, 3 * indexCount, indices, GL_STATIC_DRAW);

```

Whatever else is going on, that is wrong. You are telling opengl to copy triple the data that is actually available to the index buffer, meaning the final two thirds of it is garbage. I can't categorically say if this is causing the issue, but it's a good place to start.

I've encountered issues before where some errors are treated less strictly by one vendor (It was a while ago so I can't remember which vendor), so that might explain why it doesn't crash on an AMD card.

Honestly this code looks like much of it has been copy/pasted. If I were you, I'd go over all your OpenGL code and double check it.
> 2 votes

---
Tags: opengl
---


# Question
Title: How can I decide when the scaling will be enabled or not depending if switching cameras at the same time?
I know there are 3 scripts here but they are all connected so I can't reduce the amount of code in this question.

I have some scripts. The first one switch between cameras. When I press on G it's switching between the cameras.

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class SwitchCameras : MonoBehaviour
{
    private bool cycleAllCameras = false;
    public Camera[] storedCameras;

    public Vector3[] _originalPositions;
    public Vector3[] _lastPositions;
    public Camera[] _currentCameraSequence;
    public Camera[] _allCameras;
    int _currentCameraIndexInCycle;
    int _currentCameraIndexInAll;

    // Rather than store the current camera's index, AND its reference,
    // AND its name, AND its position, AND its original position...
    // let's just store its index, and everything else can be inferred
    // from that, so we don't have redundant data that can go out of sync.
    public Camera currentCamera
    {
        get
        {
            return _currentCameraSequence[_currentCameraIndexInCycle];
        }
    }

    void Start()
    {
        // Cache all cameras enabled at the start of the scene;
        _allCameras = Camera.allCameras;
        _originalPositions = new Vector3[_allCameras.Length];
        _lastPositions = new Vector3[_allCameras.Length];

        // Select the first camera in whichever list we're using
        _currentCameraSequence = cycleAllCameras ? _allCameras : storedCameras;
        Camera currentCamera = this.currentCamera;

        // Disable every camera except the one we're using,
        // and cache their original positions to use later.
        for (int i = 0; i < _allCameras.Length; i++)
        {
            _allCameras[i].enabled = (_allCameras[i] == currentCamera);
            _lastPositions[i] = _originalPositions[i] = _allCameras[i].transform.position;
        }
    }

    void LateUpdate()
    {
        // Update the current camera's last position,
        // before we switch from it to a dormant one.
        _lastPositions[_currentCameraIndexInAll] = currentCamera.transform.position;

        // Use a named input so the user can remap it.
        if (Input.GetKeyDown(KeyCode.G))
            CycleCamera();
    }

    public void SwitchSequence()
    {
        if (_currentCameraSequence.Length > 0)
        {
            cycleAllCameras = !cycleAllCameras;
            CycleCamera();
        }
    }

    // Cycle action is in its own public method, in case you
    // want to trigger it from other scripts or UI buttons.
    public void CycleCamera()
    {
        currentCamera.enabled = false;

        // If we've swapped sequences, re-index the camera.
        if (_currentCameraSequence == storedCameras)
        {
            if (cycleAllCameras == true)
            {
                _currentCameraIndexInCycle = _currentCameraIndexInAll;
                _currentCameraSequence = _allCameras;
            }
        }
        else if (cycleAllCameras == false)
        {
            _currentCameraIndexInCycle = Mathf.Max(0, System.Array.IndexOf(storedCameras, currentCamera));
            _currentCameraSequence = storedCameras;
        }

        // Step to the next camera, and wrap around the sequence.
        _currentCameraIndexInCycle = (_currentCameraIndexInCycle + 1) % _currentCameraSequence.Length;

        // Ensure we have a valid index into the "all" list
        // for looking up original position / last position / etc.
        _currentCameraIndexInAll = System.Array.IndexOf(_allCameras, currentCamera);

        //
        currentCamera.enabled = true;
    }
}

```

The second script is scaling object. It will scale the object up/down:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Scaling : MonoBehaviour
{
    public GameObject objectToScale;
    public GameObject lookAtTarget;
    public float duration = 1f;
    public Vector3 minSize;
    public Vector3 maxSize;
    public bool scaleUp = false;
    public Coroutine scaleCoroutine;

    public void Inits()
    {
        objectToScale.transform.localScale = minSize;
    }

    public IEnumerator scaleOverTime(GameObject targetObj, Vector3 toScale, float duration)
    {
        float counter = 0;
        Vector3 startScaleSize = targetObj.transform.localScale;

        while (counter < duration)
        {
            counter += Time.deltaTime;
            targetObj.transform.localScale = Vector3.Lerp(startScaleSize, toScale, counter / duration);
            if (scaleUp)
            {
                var lookPos = lookAtTarget.transform.position - objectToScale.transform.position;
                lookPos.y = 0;
                var rotation = Quaternion.LookRotation(lookPos);
                objectToScale.transform.rotation = Quaternion.Slerp(objectToScale.transform.rotation, rotation, counter / duration);
            }
            else
            {
                var lookPos = lookAtTarget.transform.position - objectToScale.transform.position;
                lookPos.y = 0;
                var rotation = Quaternion.LookRotation(Camera.main.transform.forward);
                objectToScale.transform.rotation = Quaternion.Slerp(objectToScale.transform.rotation, rotation, counter / duration);
            }

            yield return null;
        }
    }
}

```

The last script handle the scaling and others:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectsManipulation : MonoBehaviour
{
    //Camera
    public Camera playerCamera;

    //Scaling
    private Scaling scaling;

    //Lights
    public DimLights dimlights;
    private Coroutine lightCoroutine;

    //Colors
    private Colors colors;

    //Rotating
    public bool stopRotation = false;
    private Rotating rotating;

    private void Start()
    {
        scaling = GetComponent<Scaling>();
        scaling.Inits();

        colors = GetComponent<Colors>();
        colors.Start();

        rotating = GetComponent<Rotating>();
    }

    // Use this for initialization
    void Update()
    {
        //Scaling
        if (Input.GetKeyDown(KeyCode.F))
        {
            //Flip the scale direction when F key is pressed
            scaling.scaleUp = !scaling.scaleUp;

            //Stop old coroutine
            if (scaling.scaleCoroutine != null)
                StopCoroutine(scaling.scaleCoroutine);

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

            //Scale  up
            if (scaling.scaleUp)
            {
                //Start new coroutine and scale up within 5 seconds and return the coroutine reference
                rotating.rotateBack = false;
                scaling.scaleCoroutine = StartCoroutine(scaling.scaleOverTime(scaling.objectToScale, scaling.maxSize, scaling.duration));
                if (dimlights.lightsOnOff == false)
                    lightCoroutine = StartCoroutine(dimlights.dimLightOverTime(1, scaling.duration));
            }

            //Scale Down
            else
            {
                //Start new coroutine and scale up within 5 seconds and return the coroutine reference
                rotating.rotateBack = true;
                scaling.scaleCoroutine = StartCoroutine(scaling.scaleOverTime(scaling.objectToScale, scaling.minSize, scaling.duration));
                if (dimlights.lightsOnOff == false)
                    lightCoroutine = StartCoroutine(dimlights.dimLightOverTime(0, scaling.duration)); ;
            }
        }

        //Rotate
        if (Input.GetKey(KeyCode.R) && !scaling.scaleUp)
        {
            rotating.x += Time.deltaTime * rotating.rotationSpeed;
            scaling.objectToScale.transform.localRotation = Quaternion.Euler(0, 0, rotating.x);
            rotating.keyPressed = true;
        }
        if (Input.GetKeyUp(KeyCode.R))
        {
            rotating.keyPressed = false;
        }

        if (!rotating.keyPressed && !scaling.scaleUp && rotating.rotateBack == false
            && DetectInteractable.detected == false)
        {
            scaling.objectToScale.transform.rotation = Quaternion.LookRotation(playerCamera.transform.forward);
        }

        if (DetectInteractable.detected == true && !scaling.scaleUp && stopRotation == false)
        {
            rotating.x += Time.deltaTime * rotating.rotationSpeed;
            scaling.objectToScale.transform.localRotation = Quaternion.Euler(0, 0, rotating.x);
        }
    }
}

```

In the script ObjectsManipulation when I press on F it will scale up/down the object.

The scaling script is using the Camera.main

In the SwitchCameras script I'm using the G key to switch between the cameras.

The problem happens if I press on F and while it's scaling the object I'm pressing on G then I'm getting exception in the Scaling script on the line:

```
var rotation = Quaternion.LookRotation(Camera.main.transform.forward);

```

Since I'm switching cameras then the main one is now null but the scaling not finished yet and is trying to access the main camera.

I'm not sure what logic should I put here and how. My logic I think should be that I will be able to switch between the cameras at any time pressing G and the scaling if I pressed F already the scaling either should be keep working in the background I mean I switched to another camera but the scaling should not stop so when I return back to the main camera I will keep see the scaling in progress or if it's ended.

Or maybe I should pause the scaling wait for switching back to the main camera and then continue the scaling.

Not sure how to do it. I keep getting the exception in the situation. When pressing F and while scaling pressing G to switch cameras.

# Answer
> 2 votes
Why not just expose the switcher's current camera and reference that?

eg. (inside the camera switcher script)

```
// Lazy singleton...
static SwitchCameras _instance;

public static Camera GetCurrentCamera() {
    return _instance.currentCamera;
}

void Awake() {
    _instance = this;
}

```

then you can replace any script trying to read

```
Camera.main

```

with

```
SwitchCameras.GetCurrentCamera()

```

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


# Question
Title: How do I prevent tile tearing effects when using pixel art in XNA/MonoGame while keeping the low velocity of the player?
Most of my Texture2D are pixel art, meaning they're rather small, so my player/character's position has to change using decimal points to keep a realistic movement that matches its walking animation.

But the problem comes when I use my 2D Camera class (using a transformation matrix) to follow the player's position with a scaling/zoom multiplied by 4 (to enlarge all the art). It ends up causing some of the tiles to offset or extra pixels to appear in source rectangles which don't belong in the tile:

Tileset used:

And these are the extra pixels that don't belong in the source rectangle that start appearing when the camera moves with the player:

I realized later that the camera position works better when using int values over floats, but not having it use floats makes the movement of the camera very rigid when zoomed in that much.

So to restate my question, how can I prevent these extra pixels from appearing while keeping the slow velocity of the player to look smooth, all while keeping the camera position fixated on the player?

Edit -- This image shows the few extra lines that gets drawn when they shouldn't when the camera's position is at specific coordinates:

# Answer
I have had this issue before when using floats for my Vectors when passing it into to a spritebatch.draw function. This issue is still present Monogame and was present in xna. **You Can still use floats for velocity** just cast the values as ints.

Try this in your SpriteBatch.Draw().

```
 Vector2 FixedPosition = new Vector2((int)SpritePosition.X, (int)SpritePosition.Y);

 SpriteBacth.Draw(Texture, FixedPosition,....);

```

All you have to do is cast (int) into your sprite positions.

You can reference this post. https://stackoverflow.com/questions/7459149/sprites-flicker-in-xna
> 1 votes

---
Tags: c#, xna, game-design, monogame, game-mechanics
---


# Question
Title: How do I unload a scene after doing LoadLevelAdditive?
I have scene A loaded.

I load scene B with LoadLevelAdditive.

How do I unload scene B and keep scene A loaded?

# Answer
You essentially need to Destroy(..) the GameObjects that came from your 2nd scene, manually.

Quick solution: for your 2nd scene, make an empty root GameObject positioned at global 0,0,0. Any other GameObject in your scene becomes a child of that. After loading the 2nd scene additively, the root will be in the hierarchy. Just Destroy(...) the root, and all GameObjects that came from the 2nd scene will be deleted too.
> 7 votes

# Answer
Just giving an up to date answer. In 2017.1 you use UnloadSceneAsync to unload loaded levels. The tips and tricks section at the bottom of MultiSceneEditing has some guidance.
> 12 votes

# Answer
Usually if you want the current level to unload when the new level has finished loading, you would use LoadLevelAsync instead, as it will unload the current level once the new one is finished loading. This allows you to bring up an animated loading screen or something similar.

If you're loading in multiple levels, you may have to LoadLevelAsync on the first one, and once it's complete, load all others with LoadLevelAdditiveAsync.

If you're trying to stream in and out levels, you will probably have to create a manager to destroy the objects manually once a level needs to be unloaded.

**Reference**: http://answers.unity3d.com/questions/18766/how-to-unload-after-calling-loadleveladditive.html
> 0 votes

# Answer
Applicaton.UnloadLevel("Level name");
> -1 votes

# Answer
On Unity 5.6.1 (Currently using it for a project on work) I'm using: SceneManager.UnloadSceneAsync("SceneName");
> -1 votes

---
Tags: unity
---


# Question
Title: What is the purpose for multiple windows in games?
A lot of game development APIs recently got support for multiple windows (such as SDL 2, and GLFW 3). But why did they add that feature? I've never seen a game in my life use multiple windows (with the exceptions of a launcher, or a messagebox). Is there something I'm missing here? Is there an actual game development purpose to it? I'm very confused of why they did that.

# Answer
> 6 votes
Things like this might not be as obvious or common so far, but it is used.

* With multiple windows you can create UI windows that may be dragged outside the game's main window (e.g. the cancelled MMO **Wish** supported this, although performance has been rather abismal back then).
* You can do other things with a secondary window, e.g. it could be useful when writing some kind of editor, where things such as palette selection or text editors are shown in a different window.
* Also back in the days (Windows 3.11 and Windows 95) it wasn't uncommon for games to use multiple windows and even default OS UI controls, especially for strategy titles, **Deadlock** and **Civilization** comming to my mind immediately.
* With multiple windows you can display different content on different screens without forcing the content to actually be continuous (or rather: it can be easier to handle, plus you can have different resolutions/sizes).

A few current-gen examples:

The **Wii U** and **NDS**, **3DS**, and **2DS** essentially run on two screens each, which could be considered two windows behind the scenes. If you want a non-Nintendo example, take a look at some mobile apps, the **YouTube** Android app. You can connect your tablet or smartphone to a TV and watch YouTube videos in 1080p while controlling playback using the far smaller touch screen device (with a lower resolution).

# Answer
> 3 votes
I can't tell you exactly why they added it, because I'm not privy to their motivations, but the most likely reason is of course that games can use it.

You also asked if there is a purpose to it. There are many game types that could use it. MMOs, RPGS, simulator and RTS games are sometimes so complex that you need to monitor a large amount of information in real time. Multiple-monitors can help with that, but only if the game can make use of that by having multiple windows.

I can give you a concrete example of a game that could make good use of it: Kerbal Space Program. It's a simulator game in which you design and launch rockets and explore space.

This is the screen that shows your rocket and the status of its systems. You need to watch this screen to execute maneuvers and keep your rocket functioning properly. If you look away from this screen for too long you won't be able to intervene in time if there's a problem with your rocket.

This is the screen where you can see your rocket's trajectory. You need to watch this screen so you know where you are headed. During maneuvers you've got to look at this screen to know how your trajectory is changing.

So that's two screens that you need to keep an eye on. Currently, the game allows you to switch between the screens, but not view them both at once. If they could be windowed separately, the player could either give each window half of their primary monitor (or any ratio they want) or move one window to a second monitor.

That's just one example. Basically any game where viewing the game status from multiple perspectives at once can benefit from the feature.

---
Tags: graphics, window-management, multiple-graphics-devices
---