# Question
Title: Unity2D: Delete spawn objects once it exits camera's view
does anyone know how to delete/destoy a spawn object when it exit out of the camera view. I tried using:

```
   void OnBecameVisible() {
      Destroy (gameObject);
     }

```

But it didn't work. Maybe I'm doing something wrong, I don't know. Oh just a friendly advice my spawned object may enter form any point of the screen. Thank you :).

# Answer
Try with `OnBecameInvisible` instead.
> 3 votes

# Answer
Try this:

```
var obj : Transform;
if (raycast.transform != obj)
    Destroy(obj.gameObject);

```

where `obj` is your object. This needs to be applied to your camera. This should work.
> -3 votes

---
Tags: unity, camera
---


# Question
Title: Unity2D: Repeating of code makes game lag (Spawnning script)
does anyone knows how to shorten down this script and that I can edit the amount of enemies I want to spawn in, so that I don't have to keep on copying and pasting the same method below again and again, my code is also making my game a bit laggy. Which isn't a good sign. This is my code:

```
    public bool fromTop = false;

public GameObject enemy1;
public float enemy1Time = 2f;

public GameObject enemy2;
public float enemy2Time = 2f;

public GameObject enemy3;
public float enemy3Time = 2f;

public GameObject enemy4;
public float enemy4Time = 2f;

// Variable to know how fast we should create new enemies

void Start() {
    InvokeRepeating ("Enemy1", enemy1Time, enemy1Time);
    InvokeRepeating ("Enemy2", enemy2Time, enemy2Time);
    InvokeRepeating ("Enemy3", enemy3Time, enemy3Time);
    InvokeRepeating ("Enemy4", enemy4Time, enemy4Time);
}

void Enemy1() {
    Vector2 spawnPoint = new Vector2 (transform.position.x, transform.position.y);

    if (fromTop)
    {
        float x1 = transform.position.x - GetComponent<Renderer> ().bounds.size.x / 2;
        float x2 = transform.position.x + GetComponent<Renderer> ().bounds.size.x / 2;

        // Randomly pick a x point within the spawn object
        spawnPoint.x = Random.Range (x1, x2);
    }
    else
    {
        float y1 = transform.position.y - GetComponent<Renderer> ().bounds.size.y / 2;
        float y2 = transform.position.y + GetComponent<Renderer> ().bounds.size.y / 2;

        // Randomly pick a y point within the spawn object
        spawnPoint.y = Random.Range (y1, y2);
    }
    Instantiate (enemy1, spawnPoint, Quaternion.identity);
}
void Enemy2() {
    Vector2 spawnPoint = new Vector2 (transform.position.x, transform.position.y);

    if (fromTop)
    {
        float x1 = transform.position.x - GetComponent<Renderer> ().bounds.size.x / 2;
        float x2 = transform.position.x + GetComponent<Renderer> ().bounds.size.x / 2;

        // Randomly pick a x point within the spawn object
        spawnPoint.x = Random.Range (x1, x2);
    }
    else
    {
        float y1 = transform.position.y - GetComponent<Renderer> ().bounds.size.y / 2;
        float y2 = transform.position.y + GetComponent<Renderer> ().bounds.size.y / 2;

        // Randomly pick a y point within the spawn object
        spawnPoint.y = Random.Range (y1, y2);
    }
    Instantiate (enemy2, spawnPoint, Quaternion.identity);
}
void Enemy3() {
    Vector2 spawnPoint = new Vector2 (transform.position.x, transform.position.y);

    if (fromTop)
    {
        float x1 = transform.position.x - GetComponent<Renderer> ().bounds.size.x / 2;
        float x2 = transform.position.x + GetComponent<Renderer> ().bounds.size.x / 2;

        // Randomly pick a x point within the spawn object
        spawnPoint.x = Random.Range (x1, x2);
    }
    else
    {
        float y1 = transform.position.y - GetComponent<Renderer> ().bounds.size.y / 2;
        float y2 = transform.position.y + GetComponent<Renderer> ().bounds.size.y / 2;

        // Randomly pick a y point within the spawn object
        spawnPoint.y = Random.Range (y1, y2);
    }
    Instantiate (enemy3, spawnPoint, Quaternion.identity);
}
void Enemy4() {
    Vector2 spawnPoint = new Vector2 (transform.position.x, transform.position.y);

    if (fromTop)
    {
        float x1 = transform.position.x - GetComponent<Renderer> ().bounds.size.x / 2;
        float x2 = transform.position.x + GetComponent<Renderer> ().bounds.size.x / 2;

        // Randomly pick a x point within the spawn object
        spawnPoint.x = Random.Range (x1, x2);
    }
    else
    {
        float y1 = transform.position.y - GetComponent<Renderer> ().bounds.size.y / 2;
        float y2 = transform.position.y + GetComponent<Renderer> ().bounds.size.y / 2;

        // Randomly pick a y point within the spawn object
        spawnPoint.y = Random.Range (y1, y2);
    }
    Instantiate (enemy4, spawnPoint, Quaternion.identity);
}

```

Please and Thank you. :)

# Answer
> 1 votes
In your code all spawn times are the same. If they can be different, things get more complicated, but I assume, that is what you are going for. Unfortunatley it seems to be impossible to pass parameters to the `InvokeRepeating` method (Unity Answers). So we do not use this method and handle the timed spawning on our own:

```
public bool fromTop = false;

public GameObject[] enemies;
public float[] enemySpawnTimes;
private float[] lastSpawnTimes;    // stores the time an enemy was spawned the last time

void Start()
{
    enemies = ...          // fill with enemies
    enemySpawnTimes = ...  // fill with corresponding times

    lastSpawnTimes = new float[enemies.Length];
}

void Update()
{
    for (int i = 0; i < enemies.Length; i++)
    {
        lastSpawnTimes[i] += Time.deltaTime;

        if (lastSpawnTimes[i] >= enemySpawnTimes[i])
        {
            lastSpawnTimes[i] = 0;
            SpawnEnemy(enemies[i]);
        }
    }
}

void SpawnEnemy(GameObject enemy)
{
    var spawnPoint = new Vector2(transform.position.x, transform.position.y);

    if (fromTop)
    {
        var x1 = transform.position.x - GetComponent<Renderer> ().bounds.size.x / 2;
        var x2 = transform.position.x + GetComponent<Renderer> ().bounds.size.x / 2;

        spawnPoint.x = Random.Range (x1, x2);
    }
    else
    {
        var y1 = transform.position.y - GetComponent<Renderer> ().bounds.size.y / 2;
        var y2 = transform.position.y + GetComponent<Renderer> ().bounds.size.y / 2;

        spawnPoint.y = Random.Range (y1, y2);
    }
    Instantiate (enemy, spawnPoint, Quaternion.identity);
}

```

# Answer
> 0 votes
You need to put it in the Update. Here is how you're code will be-

```
float time; float counter;
void Update()
{
    time = Time.deltaTime;
    if (time > 3)
    {
        //spawn enemy//
        time = 0;
        counter++;
    }
    if (counter == //the limit of enemies//)
        time = 0;
}

```

The counter if keeping track of the number of enemies. With this, a enemy is spawned every 3 seconds. I hope this helps

---
Tags: unity, spawning
---


# Question
Title: Rotate arrow without using Unity3d physics engine
I have this code that simulates the movement of a projectile without using the unity physics engine

```
IEnumerator LaunchProjectile(int angle, float speed)
{

    // Move projectile to the position of throwing object + add some offset if needed.
    Projectile.position = transform.position + new Vector3(0, 0f, 0);
    Projectile.rotation = transform.root.rotation;
    Debug.Log(transform.root.eulerAngles);

    // Calculate distance to target
    float target_Distance = speed * (Mathf.Sin(2 * firingAngle * Mathf.Deg2Rad) / gravity);

    // Extract the X  Y componenent of the velocity
    float Vx = Mathf.Sqrt(speed) * Mathf.Cos(firingAngle * Mathf.Deg2Rad);
    float Vy = Mathf.Sqrt(speed) * Mathf.Sin(firingAngle * Mathf.Deg2Rad);

    // Calculate flight time.
    float flightDuration = target_Distance / Vx;

    this.arrowSimulationScript = Projectile.gameObject.GetComponentInChildren<ArrowSimulation>();

    float elapse_time = 0;

    while (!arrowSimulationScript.Collided())
    {
        Projectile.Translate(0, (Vy - (gravity * elapse_time)) * Time.deltaTime, Vx * Time.deltaTime);

        Projectile.LookAt(Projectile.position - new Vector3(0,  (Vy - (gravity * elapse_time)) * Time.deltaTime, Vx * Time.deltaTime));

        arrowSimulationScript.Velocity = new Vector3(0, (Vy - (gravity * elapse_time)) * Time.deltaTime, Vx * Time.deltaTime).magnitude;

        elapse_time += Time.deltaTime;

        yield return null;
    }
}

```

The arrow is fired in the direction of the object which has this script attached. To make the arrow rotate I use this line of code:

```
Projectile.LookAt(Projectile.position - new Vector3(0,  (Vy - (gravity * elapse_time)) * Time.deltaTime, Vx * Time.deltaTime));

```

The arrow moves towards the right direction but with the tip facing the z axis direction, instead of the direction of the bow. Here is a video of the problem: https://www.youtube.com/watch?v=cyK6DXxTw\_E

If I comment out that line of code the arrow fly with the tip facing the direction of the bow, but it doesn't rotate.

# Answer
> 1 votes
try **adding** the delatV to current position, to get the next step position

```
  Projectile.LookAt(Projectile.position + new Vector3(0,  (Vy - (gravity * elapse_time)) * Time.deltaTime, Vx * Time.deltaTime));

```

other than, an advice, calculate only once

```
new Vector3(0, (Vy - (gravity * elapse_time)) * Time.deltaTime, Vx * Time.deltaTime)

```

and store in a temp variable .

# Answer
> 0 votes
This code might help you since it turns the object according to its movement direction.

```
 public class OrientTowardsDirection : MonoBehaviour {

        Vector3 prevLoc = Vector3.zero;
        Vector3 moveDirection = Vector3.zero;
        public Transform cube;
        private float MaxTurnSpeed = 100;

        void Update () {

            Orient();
        }
        void Orient()
        {
             moveDirection = transform.TransformDirection(moveDirection);// Turns the direction from local to world space
             moveDirection = (transform.position - prevLoc);// calculate direction vector;
             Quaternion wanted_rotation = Quaternion.LookRotation(moveDirection);//create the rotation
             transform.rotation = Quaternion.RotateTowards(transform.rotation, wanted_rotation,MaxTurnSpeed* Time.deltaTime);// apply the rotation with a max turn speed so its smooth
             prevLoc = transform.position;// change our prev pos.
        }
    }

```

Note that for a arrow you might want to skip the `Quaternion.RotateTowards` step and set the object's rotation to `wanted_rotation` directly. Let me know how this works out ;)

# Answer
> 0 votes
I believe in your original code you want to switch the operands in your LookAt.

This:

```
  Projectile.LookAt(Projectile.position - new Vector3(0,  (Vy - (gravity * elapse_time)) * Time.deltaTime, Vx * Time.deltaTime));

```

Should be:

```
  Projectile.LookAt(new Vector3(0,  (Vy - (gravity * elapse_time)) * Time.deltaTime, Vx * Time.deltaTime) - Projectile.position);

```

Also, as @dnk pointed out, you should store your new vector in a variable so you're not computing it three times.

---
Tags: unity, rotation, projectile-physics
---


title: Trying to make a character jump

text:
# Question
Title: Trying to make a character jump
I'm trying to learn Android, so I'm creating a basic 2D game which using a background scrolling image, I've already made it and the character is already walking with animation my current goal is to make it jump. I've also created the character class btw am I going to put it on ontouchevent?

```
  import android.annotation.SuppressLint;
  import android.app.Activity;
  import android.content.Context;
  import android.content.SharedPreferences;
  import android.graphics.Bitmap;
  import android.graphics.BitmapFactory;
  import android.graphics.Canvas;
  import android.graphics.Paint;
  import android.graphics.Rect;
  import android.view.Display;
  import android.view.MotionEvent;
  import android.view.SurfaceHolder;
  import android.view.SurfaceView;

  import java.util.ArrayList;
  import java.util.Random;

public class GamePanel extends SurfaceView implements SurfaceHolder.Callback {

public static final int WIDTH = 856;
public static final int HEIGHT = 480;
public static int Score = 0;
public static int Highscore;
private MainThread thread;
private Background bg;
private Deer deer;

public GamePanel (Context context) {
    super(context);
    getHolder().addCallback(this);
    setFocusable(true);

}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {

    boolean retry = true;
    while (retry) {
        try {
            thread.setRunning(false);
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
            retry = false;
        }
    }
}

@Override
public void surfaceCreated(SurfaceHolder holder) {
    bg = new Background(BitmapFactory.decodeResource(getResources(), R.drawable.gamebg));
    deer = new Deer(BitmapFactory.decodeResource(getResources(), R.drawable.deer), 48,60,3);
    bg.setVector(-5);

    thread = new MainThread(getHolder(), this);
    thread.setRunning(true);
    thread.start();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
    return super.onTouchEvent(event);
}
public void update() {
    Score += 2;
    if (Score > Highscore) {
        Highscore = Score;
    }
    bg.update();
    deer.update();
}

@SuppressLint("MissingSuperCall")
@Override
public void draw (Canvas canvas)  {

    final float scaleFactorX = (float)getWidth()/WIDTH;
    final float scaleFactorY = (float)getHeight()/HEIGHT;
    if(canvas !=null) {
        final int savedState = canvas.save();
        canvas.scale(scaleFactorX, scaleFactorY);
        bg.draw(canvas);
        deer.draw(canvas);

        canvas.restoreToCount(savedState);

        Paint textpaint = new Paint();
        textpaint.setTextSize(30);
        canvas.drawText("Score:" +String.valueOf(Score), 0, 32, textpaint);
        canvas.drawText("High Score: "+String.valueOf(Highscore), 0, 64, textpaint);

    }
}
}

```

# Answer
> I've already made it and the character is already walking with animation my current goal is to make it jump. I've also created the character class btw am I going to put it on ontouchevent?

To clarify (correct me if I'm wrong):
\- You have the character moving horizontally perfectly fine
\- You want to make it jump and want to know how.
\- You are wondering if you should put the "jump" code in ontouchevent.

Jumping behavior generally goes like this: "Jump" (object given upwards velocity), a bunch of update ticks (move object according to velocity & reduce upward velocity), and a landing -- detecting that your object has collided / will collide with another level element, and thus setting vertical velocity back to zero.

The way I'd implement jump functionality would be to:

* Give the player (and enemies too, if you want them to jump) two new fields: "onGround" (boolean) and "velocity" (double).
* When you want the character to jump, set onGround to false and set the velocity to some initial value. If onGround is already false, don't do anything (unless you want double+ jump, in which case you need to keep track of how many jumps have been made since the last landing).
* Each update step, check if onGround is false, and if so move the character a bit (according to the velocity) and decrease the velocity by some amount to simulate gravity.
* When you detect that the player is about to land on the ground, set the vertical velocity to 0 and onGround to true. If needed, adjust the player's position such that he/she is no longer colliding with the ground.

As for putting this code directly into onTouchEvent: I'd say to call a method to initiate the jump from onTouchEvent, for 2 reasons.

1. Most of the code requires to be run every frame, so you can't put it in a function that (I would assume) is only called when you tap the screen.
2. By encapsulating a startJump() method away from the ontouchevent you gain one layer of abstraction between game code and UI code. If the game needs to make the player jump for some reason besides a screen-tap, it can by simply calling that method.
> 2 votes

---
Tags: java, android
---


title: LWJGL version problems

text:
# Question
Title: LWJGL version problems
Is it possible to create VAO's while my computer doesn't support openGL 3.0 or higher? I managed to create a vertex buffer object and draw a rectangle. But then I changed my lwjgl libraries to the latest version, and now I'm using GLFW for creating my display.

Thw problem is: when i create a rectangle using a simple VBO, it has no errors. When I follow tutorials and start using a VAO, I get a *function not available* exception on glGenVertexArrays(). After searching on Google, a came to the conclusion that some devices do not support openGl 3.0 or higher. And I also tried a few configuration things, but I can't get to work with VAO's. Is there another way of using them in a lower version?

# Answer
VAOs were introduced in OpenGL 3.0, so if your computer doesn't support OpenGL 3.0 then you're probably out of luck.

*However*, they were available as an extension slightly before that - called ARB\_vertex\_array\_object. If your card supports ARB\_vertex\_array\_object then you should be able to use that extension instead.
> 1 votes

# Answer
You could just try leaving VAO calls out of your code and bind VBOs etc. where VAOs are bound in the tutorials.
> 0 votes

# Answer
If your hardware is below a needed version of OpenGL but still supports the extension that has the capability you need then you can use them, otherwise there is really no way. With LWJGL you can check if the extension is available by getting an instance of GLCapabilities and then the value of the field named after the extension. If it is true (it's just a boolean) then you can use it, but have to use the right class for it. In your case you are looking for the ARBVertexArrayObject extension.
> 0 votes

---
Tags: opengl, java, lwjgl, vbo, glfw
---


# Question
Title: How do I use Couroutines for spawning and spawn certain amount of enemy AI in the scene?
I have made a spawn function for spawning enemy AIs, and it didn't work well in my scene. I have the enemy AIs spawning in the update function, and it initially works fine, but it's spawning too many enemy AIs in the scene.

I want to do 3 6 9 enemy AIs at a time, and not spawn too many at a time. Here is my script :

```
using UnityEngine;
using System.Collections;

public class EnemiesSpawner : MonoBehaviour
{
    public GameObject enemy;
    public Transform [] spawnPoints;
    public float spawnTime = 20f;
    public Vector3 spawnValues;

    void Start ()
    {
        // Call the "Spawn" function every 10 seconds
        InvokeRepeating("Spawn", spawnTime, spawnTime);
    }

    void Update ()
    {
        int spawnPointIndex = Random.Range (0, spawnPoints.Length);

        for(int spawnCount = spawnPoints.Length - 1 ; spawnCount >= 0 ; --spawnCount)
        {
            Instantiate(enemy, spawnPoints[spawnPointIndex].position,
                spawnPoints[spawnPointIndex].rotation);
        }

        Vector3 spawnPosition = new Vector3 (Random.Range (-spawnValues.x, spawnValues.x),
            1, Random.Range (-spawnValues.z, -spawnValues.z));
    }
}

```

# Answer
Limiting how many of a certain object you spawn can be quite simple. You could either instantiate them into an *array*, and check the size of the array before loading each AI, or you could simply keep a count of how many AIs are in play, directly.

## Keeping Count

If you only wish to keep a simple count, I would probably recommend using a simple `int` variable to keep a record of the current number. If you have to manage the enemy AI currently in play, it might be better to set up a `List<>` reference, to hold a reference to all of your current enemy AI in play.

### Using a list to store your enemy objects

If you use a `List<>` array to store all of your enemy AI, you could check its size to determine how many enemy AI are in play prior to spawning more enemy AI. It is also fairly easy to remove the enemy AI from this list as you need to.

```
using UnityEngine;
using System.Collections;
using System.Collections.Generic;  // LIST LIBRARY: DON'T FORGET IT

public class EnemiesSpawner : MonoBehaviour
{
    public List<GameObject> enemyArray;
    public int enemyMax = 9;

    void Start()
    {
        enemyArray = new List<GameObject>(); // DON'T FORGET TO INITIALISE
    }

    void SpawnEnemy()
    {
        if(enemyArray.Count < enemyMax)
        {
            GameObject enemy = new GameObject();

            // Instantiate and set up your enemy

            enemyArray.Add(enemy);
        }
        else
        {
            Debug.Log("WARNING: Trying to load an enemy. Too many enemies: | Current: "
                + enemyArray.Count + " | Maximum allowed: " + enemyMax);
        }
    }
}

```

It might be worth storing your enemy AI as the script type, not the `GameObject` type. Say your enemy AI use the script `EnemyAI`; storing them using `List<EnemyAI>() enemyList` still lets you reference the `GameObject` with `enemyList[i].gameObject`. However, you also have direct access to any `public` functions you have on your `EnemyAI` script. This is especially useful if you ever need to iterate through your `EnemyAI` objects and perform a specific function.

### Manually keeping count

Another alternative, if you do not wish to keep a reference to all of your enemy AI in play, is to simply keep a manual count in the spawner.

```
float maxEnemies = 9;
float currentEnemies = 0;

void SpawnEnemy()
{
    if(currentEnemies < enemyMax)
    {
        // Instantiate and set up your enemy

        currentEnemies ++;
    }
    else
    {
        Debug.Log("WARNING: Trying to load an enemy. Too many enemies: | Current: "
            + currentEnemies + " | Maximum allowed: " + maxEnemies);
    }
}

```

## Reporting back to `EnemiesSpawner`

Of course, your still going to have to report back to your `EnemiesSpawner` script, whenever you destroy an enemy AI. If you do not, you will not be able to spawn any more enemy AI once you reach the maximum count - even when the other enemy AI are removed from play. If you only have a single instance of `EnemiesSpawner`, a static self-reference is probably the best option. Alternativley, you could set up a reference to the parent `EnemiesSpawner` in the `EnemyAI` script, itself.

### Static self-reference

A static self-reference is far easier to communicate with, but it has its limitations. For one, it requires the assumption that there is only one instance of `EnemiesSpawner` in place. If there are multiple `EnemiesSpawner` scripts in operation, this will have undesirable results, and will not work. Once you set up the reference, any script can access your `EnemiesSpawner` from anywhere, using this reference. While it is a shortcut, it can lead to other undesirable consequences, as a result.

```
public class EnemiesSpawner: MonoBehaviour
{
    public static EnemiesSpawner selfReference;
    public int currentEnemies;

    void Start()
    {
        selfReference = this
    }
}

public class EnemyAI : Monobehaviour
{
    void RemoveEnemy()
    {
        EnemiesSpawner.selfReference.currentEnemies --;
        Destroy(this);
    }
}

```

### Providing a reference to the parent `EnemiesSpawner` when instantiating `EnemyAI`

If you have multiple `EnemiesSpawner` scripts in play, or just want a more secure reference for communicating back from the enemies, providing a reference directly to the `EnemyAI` is a good option.

```
public class EnemyAI : Monobehaviour
{
    EnemiesSpawner parentSpawner;

    // the option to pass in the EnemiesSpawner on instantiation
    // EnemyAI = new EnemyAI(this) from inside EnemiesSpawner
    public EnemyAI(EnemiesSpawner parentSpawner)
    {
        this.parentSpawner = parentSpawner;
    }

    void RemoveEnemy()
    {
        parentSpawner.currentEnemies --;
        Destroy(this);
    }

    void SetParentSpawner(EnemiesSpawner parentSpawner)
    {
        this.parentSpawner = parentSpawner;
    }
}

public class EnemiesSpawner: MonoBehaviour
{
    public int currentEnemies;

    void SpawnEnemy()
    {
        // after checking that we actually can spawn an enemy..
        GameObject enemy;
        // instantiate enemy
        enemy.GetComponent<EnemyAI>().SetParentSpawner(this);
    }
}

```
> 0 votes

---
Tags: unity, gameobject, coroutines
---


title: how to use 3rd axis input in unity?

text:
# Question
Title: how to use 3rd axis input in unity?
I'm currently using a xbox 360 controller on my windows 10 computer. I've been trying to find how to use the LT and RT buttons on my controller to shoot and aim. Can some one give me an example on how to receive and use input with these buttons? I am using javascript, so it would be helpful to have it in that programming language! Thank you in advance!

# Answer
> 1 votes
You can not directly reference *axis* via programming. The `InputManager` requires you to set them up, manually. You can then reference the axis via their `string` identifiers.

Once set up like this, you can use `Input.GetAxis([Name])`. To grab **LT** (9th Axis), given the above setup, you would use `Input.GetAxis("LeftTrigger")`.

---
Tags: unity, javascript, joystick
---


# Question
Title: OnCollisionEnter not called when two colliders collide
In my 2D game, there is a ball with a circle collider ,and a platform with a box collider.

The ball has a material for bounciness and a rigidbody2D. The platform only has the box collider.

I find it to be as simple as could be, but it's not working for some reason, so apparently it's not that simple. Here's the C# code snippet found in the ball class which is attached to the ball game object:

```
void OnCollisionEnter(Collision other)
{
    Debug.Log("Hit");
    animator.Play("Bounce");
}

```

Why isn't the function being called on collision? Any idea would be appreciated.

# Answer
Use collision events for 2D. You are using the events for 3D collision detection where your colliders and rigidbody components are for 3D.

```
void OnCollisionEnter2D(Collision2D other)
{
    Debug.Log("Hit");
    animator.Play("Bounce");
}

```
> 5 votes

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


# Question
Title: Central logic in entity-component-architectures
I've build a architecture based on the entity-component-system-idea. So I got

* Components - Just store Data
* Systems - Operates isolated on Components
* Scripts - Which are just objects from type Script and attached to a ScriptComponent. A ScriptSystem will execute the init() and update() functions on the scripts then.

However, I'm wondering where to place the central game logic since the I have to check a few things about the overall game process, holding the map, counting the points, checks the points if they are enough for the end-screen, etc. ...

Should I create a single entitiy with just such a script attached to it or are there better solutions out there?

# Answer
> 1 votes
Given what you've described of your architecture, a script seems like a reasonable option.

However, it's also possible that you can put this central logic in regular code (that is, not part of the entity system). Just because you have entities and components does not mean that *everything has to be one*.

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


# Question
Title: FPS Android game that moves the gun as user swipes the screen
I am Making a First Person shooter game for android. Gun moves in all directions I swipe left right up or down. But the speed is so slow. How can i increase it's Speed.Here is my code.

```
void FixedUpdate ()
{
    foreach (Touch t in Input.touches)
        if (t.phase == TouchPhase.Began)
        {
            initialTouch = t;
        }
        else if (t.phase == TouchPhase.Moved && !hasSwiped)
        {
            float deltaX = initialTouch.position.x - t.position.x;
            float deltaY = initialTouch.position.y - t.position.y;
                //distance formula
            distance = Mathf.Sqrt((deltaX * deltaX) +(deltaY * deltaY));
            bool swipeSideways = Mathf.Abs (deltaX) > Mathf.Abs (deltaY);
            if (distance > 100f)
            {
                if (swipeSideways && deltaX > 0) {
                    this.transform.Rotate (new Vector3 (0, 30f, 0), rotationSpeed * Time.deltaTime);
                }

                else if (swipeSideways && deltaX <=0)// swipe right
                {
                    this.transform.Rotate (new Vector3 (0, 30f, 0), -rotationSpeed * Time.deltaTime);
                }

                hasSwiped = true;
            }

        }

        else if (t.phase == TouchPhase.Ended)
        {
            initialTouch = new Touch ();
            hasSwiped = false;
        }

}

```

# Answer
First create a global float called `speed` at set it to some number, and let's set it to 10 for starters(the higher the number, the higher the speed that the gun moves). And then replace this:

```
rotationSpeed * Time.deltaTime

```

with this:

```
rotationSpeed * Time.deltaTime * speed

```

and this:

```
-rotationSpeed * Time.deltaTime

```

with this:

```
-rotationSpeed * Time.deltaTime * speed

```
> 1 votes

---
Tags: animation, unityscript
---


# Question
Title: DirectX11, how do I manage and update multiple shader constant buffers?
Alright, I'm having a hard time grasping how constant buffers are bound to a pipeline stage and updated. I understand that DirectX11 can have up to 15 shader-constant buffers per stage and each buffer can hold up to 4096 constants. However, I don't understand whether the ID3D11Buffer COM used to interact with the constant buffers is just a mechanism (or handle) used for fill these buffer slots or if the object actually references a particular instance of buffer data that is pushed back and forth between the GPU and CPU.

I think my confusion on the topic is the cause of a problem I'm having using two different constant buffers.

Here is some example shader code.

```
cbuffer PerFrame : register(b0) {
    float4x4 view;
};

cbuffer PerObject : register(b1) {
    float4x4 scale;
    float4x4 rotation;
    float4x4 translation;
};

```

The way my code is organized, the camera will be handling updating the relevant per frame data and GameObjects will be updating their own per object data. Both classes have their own ID3D11Buffer that is used to do this (Using a hub architecture, so one GameObject class will handle the rendering of all the instanced GameObjects in the world).

The problem is I can only get one updated at a time, depending on the slot and I presume the update order one buffer gets filled while the other gets zero'd out.

This is essentially my code. Both classes use identical update logic.

```
static PerObjectShaderBuffer _updatedBuffer; // PerFrameShaderBuffer if Camera class
_updatedBuffer.scale       = _rScale;
_updatedBuffer.rotation    = _rRotation;
_updatedBuffer.translation = _rTranslation;
pDeviceContext->UpdateSubresource(pShaderBuffer, 0 , 0, &_updatedBuffer, 0, 0);

pDeviceContext->VSSetShader(pVShader->GetShaderPtr(), 0, 0);
pDeviceContext->PSSetShader(pPShader->GetShaderPtr(), 0, 0);
pDeviceContext->VSSetConstantBuffers(1, 1, &pShaderBuffer);
pDeviceContext->IASetVertexBuffers(0, 1, &pVertexBuffer, &vStride, &_offset );
pDeviceContext->IASetPrimitiveTopology(topologyType);
pDeviceContext->Draw(bufSize, 0);

```

My main questions are -

* Do I need to set or bind the ShaderBuffer in order to update it with the UpdateSubresource call? (Meaning manipulate it only when it is in the pipeline) Or is it a blob of data that will be sent in with the VSSetConstantBuffer call? (Meaning the order of binding and updating data doesn't matter, I can update it in the pipeline or somehow on the cpu)
* When setting or binding the buffer, do I need to reference slot 0 to update the PerFrame buffer and slot 1 to update the PerObject buffer? Could some kind of confusion with this call in my code cause all the buffers to be overwritten?
* How does D3D11 know which buffer I want to update or map? Does it know from the ID3D11Buffer COM used?

Edit -

Changed the constant buffer register tags in the example above. Using (cb#) instead of (b#) was affecting the buffers from updating correctly for some reason. Not sure where I picked up the original syntax or if it's valid at all, but it appears to of been my main problem.

# Answer
The ID3D11Buffer references an actual chunk of memory that holds your data, whether it's a vertex buffer, constant buffer, or whatever.

Constant buffers work the same way as vertex buffers and other kinds of buffers. Namely, the data in them isn't accessed by the GPU until it actually renders the frame, so the buffer has to remain valid until the GPU is done with it. You should double-buffer each constant buffer, so you have one copy to update for the next frame, and one copy for the GPU to read while rendering the current frame. This is similiar to how you would do dynamic vertex buffers for a particle system or suchlike.

The `register(cb0)`, `register(cb1)` settings in the HLSL correspond with the slots in VSSetConstantBuffers. When you update the per-frame constants you'd do `VSSetConstantBuffers(0, 1, &pBuffer)` to set CB0 and when you update the per-object ones you'd do `VSSetConstantBuffers(1, 1, &pBuffer)` to set CB1. Each call updates only the buffers referred to by the start/count parameters, and doesn't touch the others.

You do not need to bind the buffer to update it with UpdateSubresource. In fact, it *shouldn't* be bound when you update it, or this may force the driver to make extra memory copies internally (see the MSDN page for UpdateSubresource, notably the remarks on contention about a page down).

I'm not sure what you mean by "How does D3D11 know which buffer I want to update or map?" It updates or maps the one whose pointer you passed in.
> 18 votes

# Answer
There seems to be a lot of confusion around the topic of needing to re-bind constant buffers after updating them. As I'm learning about this myself I have seen a lot of topics and discussions with opposite opinions on this. Namely the best answer here, recommending calling `XXSetConstantBuffers` after you update via `UpdateSubresource` or `Map/Unmap`.

Also, some D3D MSDN samples and documentation seem to use this pattern, *binding (calling `XXSetConstantBuffers`) on a per frame or even per drawn-object basis, even though they only update an existing buffer, and not change a specific slot with a completely different buffer.*

I think the worst misconception is that `XXSetConstantBuffers` actually "sends the data you previously updated to the GPU or notifies it of the update, so that it takes the new values - which seems to be completely wrong.

Indeed, when using `UpdateSubresource` or `Map/Unmap`, documentation states that internally multiple copies may be made by the GPU if it still needs the old data, but this is not a concern for the user of the API when it comes to updating an already bound buffer. Hence the need to explicitly unbound seems superfluous.

During my experimentation, I have come to the conclusion that it is unnecessary to re-bind buffers via `XXSetConstantBuffers` after updating them, unless they are not already bound! As long as you use the same buffers (shared between shaders, eveny pipeline stages) which are once bound (at the start-up phase, for example), you don't need to re-bind them - just update them.

Some code to better showcase my experiments nature:

```
// Memory double of the buffer (static)
ConstBuffer* ShaderBase::CBuffer = (ConstBuffer*)_aligned_malloc(sizeof(ConstBuffer), 16);
// Hardware resource pointer (static)
ID3D11Buffer* ShaderBase::m_HwBuffer = nullptr;

void ShaderBase::Buffer_init()
{
     // Prepare buffer description etc.
     // Create one global buffer shared across shaders
     result = device->CreateBuffer(&cBufferDesc, NULL, &m_HwBuffer);
     BindConstBuffer();
}

...

void ShaderBase::BindConstBuffer()
{
     // Bind buffer to both VS and PS stages since it's a big global one
     deviceContext->VSSetConstantBuffers(0, 1, &m_HwBuffer);
     deviceContext->PSSetConstantBuffers(0, 1, &m_HwBuffer);
}

...
bool ShaderBase::UpdateConstBuffers()
{
    ...
    D3D11_MAPPED_SUBRESOURCE mappedResource;

    // Lock the constant buffer so it can be written to.
    deviceContext->Map(m_HwBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);

    // Get a pointer to the data in the constant buffer.
    ConstBuffer* dataPtr = (ConstBuffer*)mappedResource.pData;
    memcpy(dataPtr, CBuffer, sizeof(ConstBuffer));

    // Unlock the constant buffer.
    deviceContext->Unmap(m_HwBuffer, 0);
    return true;
}

// May be called multiple times per frame (multiple render passes)
void DrawObjects()
{
    // Simplified version
    for each Mesh _m to be drawn
    {
        // Some changes are per frame - but since we have only one global buffer to which we
        // write with write-discard we need to set all of the values again when we update per-object
        ShaderBase::CBuffer->view = view;
        ShaderBase::CBuffer->projection = projection;
        ShaderBase::CBuffer->cameraPosition = m_Camera->GetPosition();

        ...

        ShaderBase::CBuffer->lightDirection = m_Light->GetDirection();

        ShaderBase::CBuffer->lightView = lightView;
        ShaderBase::CBuffer->lightProjection = lightProjection;
        ShaderBase::CBuffer->world = worldTransform;

        // Only update! No rebind!
        if (ShaderBase::UpdateConstBuffers() == false)
            return false;

        _m->LoadIABuffers(); // Set the vertex and index buffers for the mesh
        deviceContext->DrawIndexed(_m->indexCount, 0, 0);
    }
}

```

Here are some topics from the internet (gamedev forums) which seem to adopt and recommend this approach: http://www.gamedev.net/topic/649410-set-constant-buffers-every-frame/?view=findpost&p=5105032 and http://www.gamedev.net/topic/647203-updating-constant-buffers/#entry5090000

To conlcude, it really seems that **binding is not needed unless you change the buffer entirely but as long as you share buffers and their layout between shaders (recommended practice) binding should be done in these cases:**

* At start-up - initial binding - after creating the buffer for example.
* If you need/have designed to use more than one buffer bound to a specific slot of one or more stages.
* After clearing state of the deviceContext (when resizing buffers/windows)
> 3 votes

---
Tags: shaders, rendering, hlsl, directx11
---


# Question
Title: How to do (or code) so that an array of Bullet objects can meet with an array of Zombie objects?
I just started learning game development using **Java**.

I have created

1. ArrayList of class Zombie
2. ArrayList of class Bullet

Each of the object in the two ArrayList has a variable called *rect* of type Rectangle which surrounds their own graphics on screen.

**My aim is** to make an effect when any bullet meets any zombie.

**My problem is** I don't know how to do "any bullet meets any zombie."

**My method:** I used the *rect* variable to test whether both of the object have collided with each other by using the method *rect.intersect(r)*. I'm testing every single bullet in the Bullet ArrayList to see if it has collided with any zombie in the Zombie ArrayList, which means I run through the two ArrayList completely per frame just to carry this feature out. There must be better ways..??

# Answer
> 1 votes
In general, what you do *is* the basic idea. You check every object from one array against the objects in the other array. If the number of objects is not insanely big this is fine.

But... You can optimise this in several ways to reduce the number of checks by predicting if two objects need a collision check.

Often collision detections are split in a 'broad' phase and a 'narrow' phase. The broad phase is used to eliminate objects that are unlikely to collide, the narrow phase does the actual collision check.

A broad phase method often used is Quadtrees. A quadtree is basically a way to order object by the location. Bullets and Zombies that are close to each other end up in the same 'quad space' and you only need to check bullets and Zombies that are in the same space.

There can be other ways of optimizing collision detections- you could only check bullets against zombies that are in the direction of the bullet. Or only check objects that have moved since the previous frame etc.

However you need to consider if the simple rectangle intersect is more costly than sorting your objects.

# Answer
> 0 votes
I don't have enough reputation to comment on Felsir's answer, but here's a good tutorial that explains what quadtrees are and how to implement one for collision checking in Java.

---
Tags: java, collision-detection
---


# Question
Title: How to make variables restart when the game restarts?
My game is all in one scene so when my player dies and the user clicks restart the game (when it shows the game over screen) the script below doesn't restart with it so the enemies are still going fast when the user is replaying the game. How do I make it restart when the game restarts?

```
if (Score % 10 == 0) {
    //Increment movespeed variable from Movement script
    Movement.movespeed += 4;
}

```

This is used in my score script. The `Movement.movespeed` is a reference to my movement script attach to my enemies making them go faster when the player collects 10 points.

# Answer
While not very Unity-specific, my personal approach to this would be to add a custom `void ResetGame()` method, that you call when the user clicks to restart the game.

In `ResetGame`, you would set all the values that need to be reset to their defaults, and that way all the variables would start again from where they started initially.

So something along the lines of

```
private void ResetGame() {
    Movement.movespeed = 1;  // Or whatever your initial value was.
    ResetScene();
}

```
> 1 votes

---
Tags: unity
---


title: Fixed background on a SurfaceView

text:
# Question
Title: Fixed background on a SurfaceView
I'm currently working on a top-down twin-stick shooter for Android. I've got my player moving around and shooting, but I'm looking to add a large Bitmap background which is larger than the device screen.

I'm looking for a way to position the background at 0,0 in 'world' co-ordinates, and have the view able to pan across the background with the player. I've tried using SurfaceHolder.Callbacks, but these do not seem to play nicely with my SurfaceView class. The view currently follows the player while keeping it centred, until it reaches an edge, where it will stop and the player will continue until he hits a wall.

My current thoughts are to store an offset from view co-ordinates to world co-ordinates in the update loop, and draw the bitmap using these offsets in the draw loop. Is there a more efficient way to do this, or a different way to think about it?

# Answer
> 1 votes
Moving the View is probably not going to work out well -- the Surface part of the SurfaceView is managed by the Window Manager, not the View hierarchy, so updates tend to lag behind (which is why putting a SurfaceView in a ListView works badly). You don't want to be hitting callbacks in your animation loop.

Leave the View and Surface in place and just render the background bitmap with a translation matrix.

# Answer
> 0 votes
I think you need to implement a viewport. Viewport can simply be thought of as a camera which pans around the game world with keeping it's center as the player's position (or, whatever you program it to follow). Here's a good tutorial on it, hope it helps
http://gamecodeschool.com/android/building-a-simple-android-2d-scrolling-shooter/.

---
Tags: android, camera, mobile, view
---


# Question
Title: How to limit the speeding up of enemy movement?
Is there a way of limiting my speeding my enemy script every time my player collects 10 points. I have a movement script attached to my enemies and every time my player collects 10 points my enemies get faster. I want to put a limit on that so that the movement script (attached to my enemies) doesn't increase all the time even if the player continue to collect 10 more points and onwards. I want the limit to be 40, so even if the player continues to collect another 10 points the movement should stay at 40.

This is my speeding up my enemies script (this is used in my score script):

```
if (Score % 10 == 0){
    //Increment movespeed variable  from Movement script
    Movement.movespeed += 4;
}

```

And this is my movement script attached to my enemies:

```
public static int movespeed = 20;
public Vector3 userDirection = Vector3.right;

//public float lifetime;

void Start ()
{
    //Destroy (gameObject, lifetime);
}

public void Update()
{
    transform.Translate (userDirection * movespeed * Time.deltaTime);
}

```

How can I limit the movement speed so that it doesn't exceed the upper limit I want?

# Answer
Yes, this is pretty easy. You want to clamp the movement speed to never exceed your limit 40, so all you have to do is to tweak your increment code a little. Instead of `movespeed += 4;`, you want to change that line to `movespeed = Mathf.Min(movespeed + 4, 40);` That code picks the smallest value out of \[40, movespeed + 4\], which will be the speed to use. If movespeed + 4 is more than 40, 40 is the smaller value and will be used instead.
> 0 votes

---
Tags: unity, movement
---


title: Aim assist (GoldenEye/Perfect Dark)

text:
# Question
Title: Aim assist (GoldenEye/Perfect Dark)
Anyone remember how the aim assist works in GoldenEye on n64? Where the gun model would point at an enemy if he's within a certain area in your field of view. I'm trying to do something like that but have hit a wall. I'm pretty inexperienced in Unity 3D and using this project as a way to learn the ropes.

I've currently got it so that if you're in range of an enemy (facing him or not), your gun model will rotate towards that enemy. But I need to do it so that only happens if that enemy is in front of your facing direction and near the centre of the screen.

Any tips or pointers how to do this? Do I need do a raycast in direction of camera and do some math to figure out which enemy is nearest? If so what Math functions would I need to look into?

# Answer
1. Find out which enemies actually have a clear line of sight. You can do that with a linecast from player to each enemy. When the line-cast hits a collider which is not part of the enemy (level geometry or another game-object), that enemy is not eligible as a target this frame. Make sure that the layerMask of your linecast is set in a way that only those colliders block the linecast which are actually supposed to block auto-aiming. You certainly want to exclude the player-collider and any invisible trigger-areas.
2. Calculate the difference between the direction of the enemy and the direction the player is facing.
    1. Use `Quaternion targetDirection = Quaternion.LookRotation(target.transform.position - player.transform.position)` to calculate the direction of all eligible targets.
    2. Calculate how far the aiming is off for each target: `float aimAngleWrongness = Quaternion.Angle(player.transform.rotation, targetDirection)`
3. Pick the target with the lowest `aimAngleWrongness`. Optionally you can also take the distance to the enemy into account to prefer closer targets to those further away. The distance can be calculate with `(enemy.transform.position - player.transform.position).magnitude`.
4. You can now implement the actual aiming behavior in many different ways. You can simply move the crosshair without moving the sight direction, you can move the sight direction immediately (very simple to do but might feel disorienting for the player) or you can do it smoothly with `Quaternion.Slerp` between `targetDirection` and `player.transform.rotation`.
> 2 votes

---
Tags: unity, mathematics, aiming
---


title: Different kind of stamina problem

text:
# Question
Title: Different kind of stamina problem
I have an object that I interact with physics via:

```
    using UnityEngine;
using System.Collections;

public class PhysicsBall : MonoBehaviour {

    public float speed;

    private Rigidbody rb;

    void Start ()
    {
        rb = GetComponent<Rigidbody> ();
    }

    // Update is called once per frame
    void FixedUpdate () {
        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");

        Vector3 movement = new Vector3 (moveHorizontal, 0, moveVertical);

        rb.AddForce (movement * speed);
    }
}

```

However, now I want to add a "stamina" bar, so if the user holds any of the movement keys which affect the rb, the stamina bar starts depleting. Once empty, the user can no longer affect the rb with the movement buttons.

I've tried viewing some of the classic stamina bar sprint options but they don't use the rigidbody physics like I am doing, so I wonder if anyone knows how I do it in my example?

# Answer
This is roughly how I'd do it to manage the stamina; the idea is to make the player move and consume stamina only if there is stamina left. If there is no stamina and the player tries to move, no stamina is recovered. The only way to recover stamina is to not request for movement.

This code is not tested and might not compile in Unity, view it as pseudo code.

```
public class PhysicsBall : MonoBehaviour {

    public float speed;

    private Rigidbody rb;

    public float maxStamina; // from the editor
    public float staminaReconveryRate; // from the editor
    public float staminaDrainRate; // from the editor
    private float currentStamina;

    void Start ()
    {
        rb = GetComponent<Rigidbody> ();
        currentStamina = maxStamina;
    }

    // Update is called once per frame
    void FixedUpdate () {
        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");

        // player requests to move
        if ( moveHorizontal != 0.0 || moveVertical != 0.0 )
        {
            // and has stamina
            if (maxStamina > 0.0)
            {
                // let them move and consume stamina, and make sure there is no less stamina
                // than the minimum (0)
                Vector3 movement = new Vector3 (moveHorizontal, 0, moveVertical);

                rb.AddForce (movement * speed);

                currentStamina = Mathf.Max( currentStamina - staminaDrainRate, 0.0)
            }
        }
        else
        {
            // the player does not request to move, so we restore the stamina, and make sure
            // they don't go over the max.
            currentStamina = Mathf.Min( currentStamina + staminaReconveryRate, maxStamina );
        }
    }
}

```

For the visual implementation of it, I don't have a clue. Sorry.
> 1 votes

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


# Question
Title: How can I render text with modern OpenGL and stb_truetype, and why are the loaded textures black?
I've spent the past couple of days just desperately trying to get stb\_truetype to render anything using the simple example provided https://github.com/nothings/stb/blob/master/stb\_truetype.h#L242-L281, however, no matter what I tried, the texture being loaded always ends up being completely black.

I've tried writing the generated texture data back to a .png file as

```
lodepng::encode("foopng", temp_bitmap, 512, 512, LCT_GREY);

```

and the font actually gets rendered properly

However, when I inspect the loaded texture in Nsight (or CodeXL), it looks completely black, and upon inspection of the actual data in the texture in CodeXL, it shows zeros basically everywhere, except for one small blob of a few non-zero numbers (which is nothing like the saved PNG).

I also tried changing to a different font and the generated quad geometry does change, as do the generated texture coordintes by `stbtt_GetBakedQuad(...)` (I even tried to manually set the texture coordinates all the way from `0` to `1` on the edges of the quad).

I'm not sure if it's CodeXL and Nsight both mis-interpreting the contents of the texture, even though the data view in the screenshot shows each byte, but when rendering I also get everything rendered with this texture completely black.

Is the texture being loaded incorrectly, or am I doing something else wrong? I'm using OpenGL 4.4.

# Answer
> 5 votes
Recently I've had the same problem using LWJGL/STB and modern OpenGL.

Changing font texture format helped in my case. Try changing:

```
glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512,512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap);

```

to:

```
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, 512,512, 0, GL_RED, GL_UNSIGNED_BYTE, temp_bitmap);

```

I think it works same way as

```
lodepng::encode("foopng", temp_bitmap, 512, 512, LCT_GREY);

```

did, representing the alpha value as GREY(RED) color.

---
Tags: opengl, textures
---


title: Character keeps moving

text:
# Question
Title: Character keeps moving
I'm trying to create a stamina script, where you can only use rb.AddForce (movement) if you have stamina, else you shouldn't be able to move.

Here is my code so far (with help from here):

```
using UnityEngine;
using System.Collections;

public class PhysicsBall : MonoBehaviour {

    public float speed;

    private Rigidbody rb;

    public float maxStamina; // from the editor
    public float staminaReconveryRate; // from the editor
    public float staminaDrainRate; // from the editor
    public float joystickDeadband; // from the editor
    private float currentStamina;
    public float nothing;

    void Start ()
    {
        rb = GetComponent<Rigidbody> ();
        currentStamina = maxStamina;
    }

    // Update is called once per frame
    void FixedUpdate () {
        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");

        // Make sure the player actually ask to move; this is done to avoid spending stamina when
        // not expecting it
        bool hasHorizontal = false;
        bool hasVertical = false;
        if ( moveHorizontal > joystickDeadband )
            hasHorizontal = true;
        else
            moveHorizontal = 0.0f;

        if ( moveVertical > joystickDeadband )
            hasVertical = true;
        else
            moveVertical = 0.0f;

        // player requests to move
        if ( hasHorizontal || hasVertical )
        {
            // and has stamina
            if (maxStamina > 0.0)
            {
                // lets move him and consume stamina
                Vector3 movement = new Vector3 (moveHorizontal, 0, moveVertical);

                rb.AddForce (movement * speed);

                currentStamina -= Time.deltaTime * 70;
            }
        }
        else
        {
            // the player does not request to move, so we restore the stamina.
            moveHorizontal = 0.0f;
            moveVertical = 0.0f;
        }

    }

    void Update () {
        Debug.Log (currentStamina);
    }

}

```

Some of the code may be irrelevant as I'm building it off another answer I got but I can't seem to fix some of the bugs:

* I can see the stamina decreasing to negative figures, which is good, but even after it becomes negative the character is still able to move normally.
* The character can only move UP and to the RIGHT, not BACK and to the LEFT??

# Answer
I think this line:

```
// and has stamina
if (maxStamina > 0.0)

```

Should be written like this:

```
if (currentStamina > 0.0)

```

because `currentStamina`determines if you can move or not.

As for the movement directions, I think these lines:

```
if ( moveHorizontal > joystickDeadband )
        hasHorizontal = true;

```

and

```
if ( moveVertical > joystickDeadband )
        hasVertical = true;

```

should be written as:

```
if ( Mathf.Abs( moveHorizontal ) > joystickDeadband )
        hasHorizontal = true;

```

and

```
if ( Mathf.Abs( moveVertical ) > joystickDeadband )
        hasVertical = true;

```

to get negative values (back and left)
> 1 votes

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


title: Camera rotation in 4D

text:
# Question
Title: Camera rotation in 4D
What practical choices do I have in order to rotate a camera in 4D space? I would like to make it as intuitive as possible.

A camera in 3D space can be represented by

* a point where it is located
* the forward vector (movement using the \[w\] and \[s\] buttons)
* the left (movement using the \[a\] and \[d\] buttons)
* the up vector (eg. \[space\] and \[ctrl\])

In 4D space, the an additional axis is added:

* the fourth axis vector (eg. \[q\] and \[e\])

All of the vectors remain orthogonal to eachother. So the movement is trivial.

# Answer
First of all you have to understand some basics. Rotations are usually given around some axis, but thinking like this wont help here. Rather you should think of a rotation happening on a plane. 2 and 3 dimensions are easy to visualize and the fourth one you should get use to with some time. So in 2D there is one plane of rotation, 3D there's 3 and in 4D there is 6.

If we label the axises x, y, z and w the planes of rotations could be labeled as xy, xz, xw, yz, yw and zw. Id recommend using 5 or 6 buttons. 4 for defing a plane (combination of 2 buttons) and 2 for choosing rotation direction or 1 for simply reversing the direction. This is the most intuitive interface I can think of.

For how to apply these rotations In linear algebra, a rotation matrix is a matrix that is used to perform a rotation in Euclidean space. For example the matrix

```
R_xy=
       |  cos(θ)   -sin(θ)     0    0 |
       |  sin(θ)    cos(θ)     0    0 |
       |       0         0     1    0 |
       |       0         0     0    1 |

```

rotates points in the xy plane counter-clockwise through an angle θ about the origin of the coordinate system. You can reverse the direction by changing the sign of the sine functions.

For the other planes:

```
R_yz=
        | 1         0          0    0 |
        | 0    cos(θ)    -sin(θ)    0 |
        | 0    sin(θ)     cos(θ)    0 |
        | 0         0          0    1 |

R_zw=
        | 1    0         0          0 |
        | 0    1         0          0 |
        | 0    0    cos(θ)    -sin(θ) |
        | 0    0    sin(θ)     cos(θ) |

R_wx=
        |  cos(θ)    0    0    sin(θ) |
        |       0    1    0         0 |
        |       0    0    1         0 |
        | -sin(θ)    0    0    cos(θ) |

R_xz=
        | cos(θ)    0    -sin(θ)    0 |
        |      0    1          0    0 |
        | sin(θ)    0     cos(θ)    0 |
        |      0    0          0    1 |

R_yw=
        | 1         0    0          0 |
        | 0    cos(θ)    0    -sin(θ) |
        | 0         0    1          0 |
        | 0    sin(θ)    0     cos(θ) |

```

I am not certain if the last two rotations are what you could call counter-clockwise, but that does not really carry any meaning as far as I understand(because there are no cross-products in 4 dimensions).

Now that we can rotate objects we need a way to collapse it into a nice 2D picture. For this we won't look at the w component and proceed as if everything was regular 3D. Now there are two things you can actually do with the w component. You can just leave it be and do nothing with it or you can assign a w value to your view frustums near and far plane and only render coordinates in between effectively taking a slice of that dimension(more realistic). I'd also suggest using transparency for better conveying the w dimension (make objects that are between the w dimension clipping values more opaque than those at the edges).

Now the best practice would be to leave the camera at the origin and only translate and rotate the objects. (This can be inferred from what I've established previously)

P.S. I am quite interested about what you intend to do. Do you mind telling me?
> 2 votes

---
Tags: camera, rotation, input, 4d
---


title: Unity2D: Muting audio Clip problems

text:
# Question
Title: Unity2D: Muting audio Clip problems
I'm trying to create a mute button (that goes both way, e.g mute and un-mute) using button onclick

So far I'm not having the greatest luck. I made this:

```
  mute = !mute;
    if (mute){
        gameObject.GetComponent<Gamestartsound>().volume = 0;
    }else
    {
        gameObject.GetComponent<Gamestartsound>().volume = 0;
    }

```

To achieve what I'm trying to do but getting errors:

error CS0118: `UI_ManagerScripts.Gamestartsound' is a`field' but a \`type' was expected

and

error CS0118: `UI_ManagerScripts.Gamestartsound' is a`field' but a \`type' was expected

anyway this is my full UIManager script, I did the audio like that because I was having some issues earlier but it's better now so yeah:

```
public AudioClip Gamestartsound;
public GameObject Music;
public PlayerMovement playerMovementRef;
private bool mute;

public void DisableBoolAnimator(Animator anim)
{
    anim.SetBool ("IsDisplayed", false);
}

public void EnableBoolAnimator(Animator anim)
{
    anim.SetBool ("IsDisplayed", true);
}

public void NavigateTo(int scene)
{
    Application.LoadLevel ("Game Level");
    Movement.Restart ();
}
public void Mute ()
{
    mute = !mute;
    if (mute){
        gameObject.GetComponent<Gamestartsound>().volume = 0;
    }else
    {
        gameObject.GetComponent<Gamestartsound>().volume = 0;
    }
}

public void ExitGame()
{
    Application.Quit ();
}
public void PauseGame()
{
    Time.timeScale = 0;
    playerMovementRef.enabled = false;
}

public void UnPauseGame()
{
    Time.timeScale = 1;
    playerMovementRef.enabled = true;
    AudioSource.PlayClipAtPoint (Gamestartsound, transform.position);
}

```

}

# Answer
> 1 votes
Consider this line:

```
gameObject.GetComponent<Gamestartsound>().volume = 0;

```

`Gamestartsound` is not a component, that's why it doesn't compile. I'd fix this by adding an `AudioSourceComponent` into the game object in inspector and setting its clip to whatever clip `Gamestartsound` refers. Then you can change the line into:

```
gameObject.GetComponent< AudioSource >().volume = 0;

```

You are also setting the volume to 0 in both branches:

```
if (mute){
    gameObject.GetComponent<Gamestartsound>().volume = 0;
}else
{
    gameObject.GetComponent<Gamestartsound>().volume = 0;
}

```

The latter should probably be set to 1.

---
Tags: unity, audio
---


# Question
Title: How to detect collisions of objects in two different arrays?(html canvas)
I am making a canvas game where you shoot at an endless amount of enemies. My problem is that the I am not sure how to make the objects from the bullets array collide with those of the enemy array. Here is what I have:

```
enemies.forEach(hitCheck)

```

Then:

```
var hitCheck = function(object){
  var a = bullets.length

  if (bullets[a].x < object.x + object.width  && bullets[a].x + bullets[a].width  > object.x &&
        bullets[a].y < object.y + object.height && bullets[a].y + bullets[a].height > object.y) {object.x += 400}
}

```

# Answer
I think the problem here is that you're not iterating over the bullets array.

Instead of just setting `a` to `bullets.length`, use a `for` loop inside `hitCheck`:

```
for (var a = 0; a < bullets.length; a++) {
    if (bullets[a].x < object.x + object.width
                  && bullets[a].x + bullets[a].width  > object.x
                  && bullets[a].y < object.y + object.height
                   && bullets[a].y + bullets[a].height > object.y) {
         object.x += 400
    }
}

```
> 0 votes

---
Tags: javascript, html-canvas
---


title: Inventory Item Exist checker

text:
# Question
Title: Inventory Item Exist checker
I have a question regarding declaring my inventory. I made it a string named inventory, with a constant number as its max value. The thing is, I want the user to use an item if he / she gains an item. The problem is, I do not know what syntax should I use to determine if the user has an item and use that item. Here's my code I just started:

so declaring the inventory:

```
    const int MAX_ITEMS = 15;
    string game_inventory [MAX_ITEMS];
    int itemnum = 0;

```

I have some items like potion, antidote, gems and others. I use the:

```
game_inventory[itemnum++] = "Potion"

```

to place items in my inventory. If I want to use the potion, IF I HAVE one, how can i make a function to check whether I have a potion or anything and use it?

# Answer
> 1 votes
The simplest "check inventory array" method in C++ looks like this:

```
#include <vector>
using namespace std;

template<typename array_type, typename item_type>
    bool is_in_inventory(array_type inv, item_type item)
{
        /*
         * Use the following instead ot "auto iter" if your C++ variant is older:
         * array_type::iterator iter
         */
        for ( auto iter = inv.begin(); iter != inv.end(); ++iter )
        {
            if( *iter == item ) { return true; }
        }
        return false;
    }
}

```

This assumes game\_inventory is a standard C++ container, so something like `std::array<std::string, MAX_ITEMS>` or `std::list<std::string>`; but basically anything which implements the iterators properly will work.

Replace `auto` with *type of game\_inventory*\`::iterator if you're dealing with older variants of C++, as per the comment in the code.

You can also use the functions in `<algorithm>` for slightly less verbose (but not really quicker) ways to do several such operations. For example:

```
#include <vector>
#include <algorithm>
using namespace std;

template<typename array_type, typename item_type>
    bool is_in_inventory(array_type inv, item_type item)
{
    return find(inv.begin(), inv.end(), item) != inv.end();
}

```

Behind the scenes, this does *exactly* the same code as the example above.

---

Side note: You should consider using a custom `class` for the items and store element of that class - or at least elements of the "inventory\_item" component of the items - in your inventory array.

# Answer
> 0 votes
Ugly but maybe easier to understand than a templated example (Personally I'd just go with a std::map though ...)

```
for(int i=0;i<MAX_ITEMS;i++)
{
  if(!strcmp(game_inventory[i],"Potion"))
  {
    //use the potion:
    Do thing()...

    //remove item
    game_inventory[i]=NULL;

    //bail out of loop
    i=MAX_ITEMS;
  }
}

```

# Answer
> 0 votes
IMHO it would be far easier to quit using a string for items.

If you just store numbers as items' IDs, you can use an enum like

```
enum EItemID {
    EIID_POTION,
    EIID_SWORD,
    ...
}

```

Then, all you need to do is

```
bool CanUseItemByID(EItemID itemID) {
    bool ret = false;
    //begin looping with iterator or whatever it is
        if (items[i] == itemID)
            ret = true;
    //end loop
}

```

I think it's far easier, and you wouldn't be comparing str everytime you access items, which is far slower than comparing two integers.

I think you could do this, since by what you've showed, your inventory system is quite simple.

Besides that, you could even optimize it more by sorting inventory by ID (again, easier to sort integers than strings) and then doing binary search.

To use items then, you could use a std::map with that numerical ID as your key, and whatever you need to know about it as your value, quite simple too.

Hope it helps.

---
Tags: c++
---


# Question
Title: Animating 2d character which can wear items?
In my game the player can control a character which can wear items. Now it is not visible but I would like to make it visible like for example in Terraria, Starbound, etc.

In my game a player can only face right or left. (right is the mirrored version of left) Only the character's feet and arms are moving during the game.

Is there a simple way in Unity to stick the sprite of the items to "bones"? (like in 3d modelling) Or how could I implement this "equipment on character" system?

I found some assets but I dont have much money.

Thanks in advance! :)

# Answer
The usual way to implement different clothes with two-dimensional sprites is paperdolling.

You have a spritesheet for the "naked" player-character which is fully animated. You then create a separate spritesheet with the exact layout for each piece of equipment. In the game, these spritesheets are drawn on top of each other.

The effort for this is `animation_frames * items` which means it is not much effort when you have few animations of few items, but increases a lot when you have a lot of both. At some point it will be less work to use full-fledged 3d models. With skeleton-based animation you don't need to animate each item individually so the effort to add a new animation or item does not increase depending on how many items or animations you already have.
> 2 votes

# Answer
Besides paperdolling as mentioned by Philipp there are skeletal animation systems for 2D.

The animation is separated from the appearance, thus you create the animation using bones and can map different images on these bones. This way you can have multiple appearances for the same animation. An you only need to create the wardrobe as it should be mapped to the bones. So it takes the least effort to dress you characters.

It is entirely possible to create such a system yourself, however it becomes complex very soon if you want to create more elaborate animations. The general idea is that you define 'bones' that have an anchorpoint and a rotation. The bones are organised in a tree-structure where each child inherits the position and rotation of the parent. Then you create 'keyframes' that store the rotation information related to a time key.

These tools can help you create these animations Spine, Spriter Pro, Dragon Bones (the latter is open source). If you have a look at the various sample videos present for each system you'll get the idea. I believe all of them have runtimes for Unity.
> 2 votes

---
Tags: unity, animation, platformer
---


# Question
Title: Can I drag and drop to a specific place in Unity?
Is possible to drag and drop a game object into a specific place?

For example, I want to put an LED sprite in the hole of a breadboard sprite.

# Answer
> 1 votes
I', going to share my drang n drop code and you can work it out from there. Here it is :

```
    using UnityEngine;
    using UnityEngine.EventSystems;
    public class DropZone : MonoBehaviour, IDropHandler
    {
      public void OnDrop(PointerEventData eventData)
      {
          Debug.Log (eventData.pointerDrag.name + " was dropped on " + gameObject.name);
          //Do checks for what is being drop here
      }
    }

```

Then for the actual item we want to drag we use this:

```
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class Draggable : MonoBehaviour,
          IBeginDragHandler, IDragHandler, IEndDragHandler {

    public void OnBeginDrag(PointerEventData eventData) {}

    public void OnDrag(PointerEventData eventData) {
        //Debug.Log ("OnDrag");
        transform.position = eventData.position;
        }

    public void OnEndDrag(PointerEventData eventData) {}
}

```

For more infromation,solutions and a in-depth look into this problem you can refer to this question on stackoverflow.

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


# Question
Title: Need an example of a HLSL Compute Shader
I'm finding Compute shaders very confusing. I was wondering, if I were to provide an example, and maybe one more later, if someone could demonstrate how to convert it into a Compute shader for D3D11?

Here is the example, it's just a function:

```
void tonemap( out float4 low, out float4 high, float3 rgb, float scale)
{
    rgb = rgb*scale;
    low = rgb.xyzz;
    high = rgb.xyzz-saturate(rgb.xyzz);
}

```

Where would I start with this?

# Answer
> 6 votes
There's little point in converting your example to DirectCompute. It has no need to share data between pixels, so you are actually much better off doing a global tone-map operator in a Pixel Shader.

A more interesting case would be in trying to do a local tone-map operator where pixels need to share data between them (something you can't do in a pixel shader in a single pass). That's what the classic DirectX SDK sample HDRToneMappingCS11 is doing.

Other interesting DirectCompute shaders can be found in FluidCS11, NBodyGravityCS11, and BC6HBC7EncoderCS. There are also a number of compute shaders in the MiniEngine DirectX demo.

> You can look at AdaptiveTessellationCS40 for ideas as well, but it's probably not a good choice for actually implementing tessellation on modern hardware--it was intended as a way to emulate tessellation hardware for Feature Level 10.x cards.

Of course, you can also use DirectCompute for completely non-graphics related tasks. For example, the ComputeShaderSort11 sample which implements a bitonic sort.

Take a look at the BasicCompute11 for a very simple example of using DirectCompute that does a simple sum of two arrays. This sample is really more about how to do all the setup and creating the buffers, so the shader there isn't really all that useful beyond showing how to deal with double-precision data buffers.

---
Tags: shaders, hlsl
---


title: Both are scale 1, one is a lot smaller

text:
# Question
Title: Both are scale 1, one is a lot smaller
Both of these balls are the same scale (1) but one is a lot bigger.

What can cause this? I don't think I've ever scaled the ball anywhere in my code.

# Answer
The scale of the transformation of an object also affects all of its children. Make sure the scale is identical throughout the whole object hierarchy of your scene-graph.
> 2 votes

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


title: Physics feel wrong

text:
# Question
Title: Physics feel wrong
This is how my game looks so far:

I feel the physics are off. The ball is just instantly slowing down instead of flying across that floor.

You can see the drag is turned down so I don't know why the physics look so bad?

Any ideas? The scale is like 3x smaller than a 1x1 cube.

In case it's a script problem, here is the code on the physics I've done to move the player **(note: the GIF does not contain any player input at all)**:

```
    using UnityEngine;
using System.Collections;

public class PhysicsBall : MonoBehaviour {

    public float speed;

    private Rigidbody rb;

    public float maxStamina; // from the editor
    public float staminaReconveryRate; // from the editor
    public float staminaDrainRate; // from the editor
    public float joystickDeadband; // from the editor
    private float currentStamina;
    public float nothing;

    void Start ()
    {
        rb = GetComponent<Rigidbody> ();
        currentStamina = maxStamina;
    }

    // Update is called once per frame
    void FixedUpdate () {
        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");

        // Make sure the player actually ask to move; this is done to avoid spending stamina when
        // not expecting it
        bool hasHorizontal = false;
        bool hasVertical = false;
        if ( Mathf.Abs( moveHorizontal) > joystickDeadband )
            hasHorizontal = true;
        else
            moveHorizontal = 0.0f;

        if ( Mathf.Abs( moveVertical ) > joystickDeadband )
            hasVertical = true;
        else
            moveVertical = 0.0f;

        // player requests to move
        if ( hasHorizontal || hasVertical )
        {
            // and has stamina
            if (currentStamina > 0.0)
            {
                // lets move him and consume stamina
                Vector3 movement = new Vector3 (moveHorizontal, 0, moveVertical);

                rb.AddForce (movement * speed);

                currentStamina -= Time.deltaTime * 70;
            }
        }
        else
        {
            // the player does not request to move, so we restore the stamina.
            moveHorizontal = 0.0f;
            moveVertical = 0.0f;
        }

    }

    void Update () {
        Debug.Log (currentStamina);
    }

}

/* public class PhysicsBall : MonoBehaviour {

    public float speed;

    private Rigidbody rb;

    void Start ()
    {
        rb = GetComponent<Rigidbody> ();
    }

    // Update is called once per frame
    void FixedUpdate () {
        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");

        Vector3 movement = new Vector3 (moveHorizontal, 0, moveVertical);

        rb.AddForce (movement * speed);
    }
}
*/

```

EDIT: I discovered something weird in the project but it's a different question so I made a new question: Both are scale 1, one is a lot smaller

But it's very likely to relate to this problem as the larger ball works fine.

# Answer
My guess is the friction between the ball and the slide isn't high enough so that it's not actually gaining much of a roll. Looks like you have a no friction material applied to the sphere collider? Friction is actually your friend.

When applying physics to a ball, I would use torque on the ball, combined with higher friction, and not translation force. Movement without friction is very unrealistic for a ball and it'll be damned difficult to try to simulate different surfaces like ice, rubber, etc. Looks like you're trying to circumvent the physics system instead of working inside of it, which can cause odd behaviors like you're seeing.

Edit: Can't comment yet so adding this here. If you ever do want immovable objects to work in the physics engine with masses/etc, check the option for IsKinematic. This will allow the mass to influence some of the physics behaviors but force applied to it will not cause any motion. Great for things like programmatically moved platforms. Definitely check out some of the physics tutorials on unity's site.
> 1 votes

# Answer
You mentioned the scale is 3x smaller than a 1x1x1 cube, which doesn't sound that unreasonable, but just to rule this out, maybe try making the scale more representative of the situation you're trying to model. For example, if the ball is supposed to be a soccer ball, and the standard sphere mesh has a 1-unit (in Unity, "1 unit" is "1 meter") diameter, you should scale it down to 0.22 of its original size (soccer ball circumference is 70 cm, so diameter is ~22 cm, which is .22 m).

From http://docs.unity3d.com/Manual/class-Rigidbody.html

> The size of the your GameObject’s mesh is much more important than the mass of the Rigidbody. If you find that your Rigidbody is not behaving exactly how you expect - it moves slowly, floats, or doesn’t collide correctly - consider adjusting the scale of your mesh asset. Unity’s default unit scale is 1 unit = 1 meter, so the scale of your imported mesh is maintained, and applied to physics calculations. For example, a crumbling skyscraper is going to fall apart very differently than a tower made of toy blocks, so objects of different sizes should be modeled to accurate scale.

Good luck.
> 0 votes

# Answer
Problem found:

The ball was a child object to a parent which I had not noticed was scaled severely down. Turns out my ball was very, very tiny and that makes the engine treat it like that.

I scaled the parent up to 1 and the ball behaves normally.
> 0 votes

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


# Question
Title: How do I go about implementing different behaviors on items?
How do I go about implementing different items with different behaviors?

I plan on having an inventory where those items are stored, but I can't figure out how do I go about implementing different functionality for each item. Can somebody help me figure out where to look or how to go about this problem?

(This is not a question about inventory implementation, or specific item implementation, but how to implement functionalities of each usable item.)

# Answer
This sounds like a job for some simple OOP.

Start with a class for each item. Something simple will do. This class' job is to define the basic interface that is used to interact with items.

```
class IItem
{
    String Name;
    Sprite Icon;

    virtual void Use() = 0;
}

```

Now, each item that you want a new behaviour for, should implement this interface, and place the interaction code in the `Use` method. When your player or other object wants to use the item, you simply call the `Use` method from the item wanted, and perhaps destroy the item. You could also allow the item to determine when it wants to be destroyed by adding a `ShouldBeDeleted()` method. Items that have multiple uses would use a counter and determine the deletion state by investigating that counter.

```
class Apple : IItem
{
    Apple()
    {
        Name = "Apple";
        Icon = SpriteManager.Load("Apple.png");
    }

    override void Use(Player player)
    {
        player.hunger -= 5;
    }
}

```

This kind of pattern should work just fine, as long as you don't have very many items. For a basic game this should however work just fine. You also might want to look into the factory pattern, where instead of `Inventory.Add(new Apple());`, you would instead as a factory object to create the item for you, along the lines of `Inventory.Add(ItemFactor.Create(ItemType.Apple));`.
> 1 votes

---
Tags: c#, architecture
---


# Question
Title: Object outlining, stencil is not working WebGL
I can't seem to figure out my problem with stencil buffer in object outlining algo.

```
function init() {
   ...
   gl.enable(gl.STENCIL_TEST);
   gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE);
   ...
}

var mscaled = [];     // scaled model matrix of a cube
function render() {
   gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);

    gl.stencilFunc(gl.ALWAYS, 1, 0xFF);
    gl.stencilMask(0xFF);
     // use program1
     // set attrib pointers
     // bind cube's ebo buffer
     gl.drawElements(gl.TRIANGLES, 36, gl.UNSIGNED_SHORT, 0);

     gl.stencilFunc(gl.NOTEQUAL, 1, 0xFF);
     gl.stencilMask(0x00);

      // set scaled model matrix
      mat4.fromRotationTranslationScale(mscaled, cube.rotation, cube.translation, vec3.fromValues(1.1, 1.1, 1.1));

      // use program2
      // set attrib pointers
      // bind cube's ebo buffer
      gl.drawElements(gl.TRIANGLES, 36, gl.UNSIGNED_SHORT, 0);
}

```

And it just draws the whole second cube on top of the first, like there's no stencil test. I've tested with up-scale and down-scale.

the red cube should be the outliner. In the first image it is scaled up - but WebGL draws it just on top of the first one, in the second image it is scaled down - ideally it shouldn't been even drawn due to stencil test (of course, depth test is disabled in the case of a second image)

# Answer
> 2 votes
**Solved!**

I had pass WebGLContextAttributes object when creating the context, explicitly requesting stencil buffer:

```
canvas.getContext('webgl', {stencil: true});

```

---
Tags: opengl, webgl
---


# Question
Title: How to layer the Worley noise like this?
Recently I'm trying to implement `Siggraph15_Schneider_Real-Time_Volumetric_Cloudscapes_of_Horizon_Zero_Dawn`, you can also find this in GPU Pro 7, (part II Lighting, chapter 4, Real-Time Volumetric Cloudscape).

I can make the first Worley noise above and increase the frequency, I can get another Worley noise, but how to blend the two noise to get the middle noise and finally, the third noise"?

The last image is two single frequence worley noise and the result I blend them.You can try your method with them.

My formula is this:

```
tmp = (worley1 + smoothstep(0, 1, worley1)*worley2*0.5) / (1 + smoothstep(0, 1, worley1)*0.5);
tmp = ReMap(0, 1, 0, 0.7, tmp);

```

ReMap is:

```
double ReMap(double oldMin, double oldMax, double newMin, double newMax, double src);

```

Note that worley1 and worley2 is worley noise range from 0 to 1.The result is close in the first glance,but it's not the same apparently. I think the formula is TOO tricky and maybe I got something wrong.

# Answer
> 1 votes
Using an image editor, I was able to get close as follows:

* layer the image on the right over the top of the image on the left
* reduce the opacity of the top layer to ~66%
* merge layers
* auto level resulting image

I think the equivalent operation would be something like `normalize((A + (0.66*B))`. The contrast was a bit too sharp, so I suspect a full normalization is not quite right. Maybe mellow it back out with something more like:

```
C = A + (0.66*B)
D = (normalize(C) + C) / 2

```

---

If you want to combine two layers such that "the black part in the first image still be black in the result texture", try this instead:

```
C[x] = Min(A[x], B[x])

```

Note: this assumes that black = 0.0 & white = 1.0.

# Answer
> 0 votes
I'm so excited that I found a blog about how to get the awesome cloud.

I download the source code (link below) and read it.

It blends the Worley noise like this:

```
tmp = worley1 - (1-worley2)*0.25;
tmp = saturate(tmp);

```

Frankly speaking,the result is analogous with mine. But the method is quite simple and NOT that tricky. And I prefer this one.

The link is:http://bitsquid.blogspot.com/2016/07/volumetric-clouds.html

The result is like this. It's no doubt that this is the right solution.

Thanks for Jon and Pikalek anyway^\_^.

# Answer
> 0 votes
```
float blend1 = 0.3f;
float blend2 = 0.3f;
//blend worley1 and worley2
float t = worley1 * (1.0f - blend1) + worley1 * worley2 * 1.25f * blend1;
//blend t and worley3
float t2 = t * (1.0f - blend2) + t * worley3 * 1.25f * blend2;
//revert perlin and scale it, enlarge the perlin noise according to the worley noise
float reuslt = ((1.0f - perlin) * 0.65f) / (1.0f - t2 * 0.6f);

```

---
Tags: noise
---


# Question
Title: Passing an SDL KeyboardState(Uint8*) to Lua
I'm working on my first big project and I've decided to integrate Lua with my C++ framework. Everything's worked out so far, but the only way I've managed to pass the `SDL_GetKeyboardState(NULL)` array to Lua is by building a Lua table manually.

```
void passKeyboard(const Uint8* keyboard){
    std::map<std::string,std::string> kmap;
    kmap.clear();
    kmap["UP"]=toString(keyboard[SDL_GetScancodeFromKey(SDLK_UP)]);
    kmap["DOWN"]=toString(keyboard[SDL_GetScancodeFromKey(SDLK_DOWN)]);
    kmap["LEFT"]=toString(keyboard[SDL_GetScancodeFromKey(SDLK_LEFT)]);
    kmap["RIGHT"]=toString(keyboard[SDL_GetScancodeFromKey(SDLK_RIGHT)]);
    ...
    vbind_SetTable("keyboard",kmap);
}

```

Now, the code works and is reasonably fast for my purposes, but it's undeniably ugly. I even feel dirty looking at it. Is there any way I could to this more elegantly?

For reference, `vbind.h`:

```
void vbind_SetTable(const std::string &name,std::map<std::string,std::string> &t){
    lua_newtable(L);
    for(std::map<std::string,std::string>::iterator it=t.begin();it!=t.end();it++){
        lua_pushstring(L,it->first.c_str());
        std::string value=it->second;
        const char* p=value.c_str();
        char* end;
        long t=strtol(value.c_str(),&end,10);
        if(p!=end&&errno!=ERANGE){
            lua_pushnumber(L,t);
        }
        else{
            lua_pushstring(L,value.c_str());
        }
        lua_settable(L,-3);
    }
    lua_setglobal(L,name.c_str());
}

```

# Answer
This is a bit hard on the eyes. And... you are doing a LOT of work just to get a keyboard state. Take a look at the LuaSDL implementation.

https://github.com/Tangent128/luasdl2/blob/master/src/keyboard.c#L128

Follow it to KeysIndex at Line 29. You will probably notice that he used the original function, as well as a checkinteger() function from the Lua library, and compares the data to registered Enums. A pretty simple solution from this code.

```
SDL_GetKeyboardState(int *numkeys)
{
    SDL_Keyboard *keyboard = &SDL_keyboard;

    if (numkeys != (int *) 0) {
        *numkeys = SDL_NUM_SCANCODES;
    }
    return keyboard->keystate;
}

```

So instead of using a map, you can actually just write to a pre-existing table.
> 1 votes

# Answer
First - have you considered Sol2 for lua binding (https://github.com/ThePhD/sol2)? It's very easy to use, I love it.

With it, you could register a function to lua which takes a string and returns bool if the key is pressed:

```
// something like this
bool KeyPressed(const std::string &key_name)
{
    auto key = SDL_GetKeyFromName(key_name.c_str());
    if (key == SDLK_UNKNOWN)
        return false;

    auto state = SDL_GetKeyboardState(NULL);
    return state[SDL_GetScancodeFromKey(key)];
}

```

With Sol2, it is super each to register a function to lua (and you can easily integrate it with plain lua API stuff):

```
// sol2
sol::state lua;
// Or use sol::state_view(lua_State *L) with
// an existing lua_State
// i.e.
//    sol::state_view lua(L);
lua.set_function("keypressed", KeyPressed);

```

Then in your lua code, you can use the KeyPressed function as you would expect:

```
if keypressed("Left") then
    -- do stuff
end

```
> 0 votes

---
Tags: c++, sdl, lua, sdl2
---


title: Why do games have hats?

text:
# Question
Title: Why do games have hats?
I noticed that a lot of games tend to have hats. I was wondering why? Is it some sort of tradition to add hats to your games? What makes this trend so popular in game development?

# Answer
Players like to personalize their characters. Players also like to show off their achievements in the game to other players. Hats are a very easy to implement way to do that.

* Because they are right on top of the character's head, they are a very visible feature. A hat can usually be seen from most angles other players will usually see the character.
* They don't have any joints which require complex animations. You can simply append them statically to the head-bone. That makes them simple to produce for 3d artists.
* Novelty hats can have almost any shape imaginable, so the artists have a lot of creative freedom.
* They are unlikely to interfere with any other features or animations of the character model.
> 101 votes

# Answer
Beyond a game design perspective, the reason a lot of games have hats is mostly due to Team Fortress 2's hat system.

Team Fortress 2 added hats in 2009. The ability to trade hats and hats being at different rarities made them into a very popular feature and somewhat of an inside joke (being that Team Fortress 2 was a hat trading game with a FPS minigame).

Games have had cosmetics in some form or another for a long time, but TF2 certainly popularised the idea of hats being used. Subsequently, other games used hats as cosmetics, often as a reference to TF2.
> 35 votes

# Answer
Hats...

* ... are easy to design/make
* ... don't require much space in an inventory (depends on the game)
* ... are easy to theme according to an in-game event or a away-from-keyboard event (such as Halloween and FIFA World cup)
* ... can show off how long the player has been playing the game, or how dedicated he is
* ... can let the player to show off without masking/hiding the face of the character; or it can be used to mask the player's face, depending on the hat.
> 15 votes

# Answer
### Commercial Reasons for using Hats in Video Games

I want to outline the commercial incentive to game publishers (and distributors) to utilize hats as a cosmetic feature in a video game. This commercial reasoning is directly related to the sentimental value gamers often experience. All points addressed use reference to previously mentioned reasons (which are largely valid reasons).

* Hats give us a feeling of independence and a sense of autonomy while playing a game that we like - particularly in a game with a community that we feel we're a part of. This makes us feel accomplished and gives us a sense of reward.
* *(mentioned earlier - RE: hats showing accomplishment, loyalty)* These attributes keep gamers engaged while playing, and encourage players to continue supporting the game - commercially keeping the game relevant, while satisfying players psychological need for their own ability to display an item that is a statement of their loyalty, or their general position in the game; and in some cases: personal wealth.
* Commercially, these games engage a high number of players, who may continue their subscription with their goal being set on the attainment of a particular "hat" ("cosmetic symbol"). This also contributes to the competitive aspect - further fueling players to play more, and keep the community alive.

Lastly, a note on controversy related to greed and increasing profit margins thru simple additions. I would suspect that many view these game items as a poor, "sell-out" features as many see certain micro-transactions based games that use a "pay to win" model. I'm sure many, as I do - disagree with this logic. The game developers only stay profitable by adding attractive and enticing content that players want. With the addition of hats to a game - it is unarguably a cheap way (little relative expense is needed by the developer) to keep players immersed in the virtual environment,to sustain profits, and even to keep the development team engaged with the community, providing artists with the ability to make decisions about upcoming design content.
> 8 votes

---
Tags: game-design
---


# Question
Title: LibGDX - Managing and starting new levels
I have a Manic Miner style game where you need to collect all the items from a screen before you can advance to the next screen.

I have a screen class called "PlayScreen" wich starts out by loading a tiled map called "Level1.tmx", and contains the render and update loop.

```
public class PlayScreen implements Screen {
    ...
}

```

This screen is loaded by my main Game class, by calling SetScreen

```
setScreen(new PlayScreen(this));

```

So inside my PlayScreen, what is the correct way to restart the game but with a different level? I know I can pass through a new level number to get it to load a new tiled map, but this usually crashes.

Do I need to dispose of the screen and reload it again. I cannot find much information about this. Most LibGDX tutorials only cover a single screen or level, or have a menu screen in between. I just want to switch to the next level or room on demand, but cannot get it working.

Has anyone done this before - can you recommend a good way of doing this?

Regards

James

# Answer
> 1 votes
The `Screen` framework is designed so that you can change to another screen at any time. Your described method of doing do is correct-- by adding a parameter to your `PlayScreen` constructor

```
game.setScreen(new PlayScreen(this,levelNum));

```

The crash that you get when doing this is a different problem and you'll have to figure out where the crash is actually stemming from.

You should call `dispose()` on your `Screens` when you are done with them. In the example on the libgdx wiki they dispose of the screen right as they set the screen to another screen. So in your `PlayScreen` class you could have a restart method like this:

```
public void restart(int levelNum){
    game.setScreen(new PlayScreen(this,levelNum));
    this.dispose();
}

```

Just be sure that your `Screen's` `dispose()` method doesn't dispose any assets shared between screens. Shared assets should be passed into the screens and should be disposed at a later time, most likely when the game exits.

---
Tags: libgdx, levels, tiled
---


# Question
Title: How to communicate with LibGDX HTML5 app?
I'd like to have a HTML form send data to a LibGDX game deployed as HTML5. Ideally as a form in HTML as part of the same page that contains the LibGDX div/canvas, and use the form to set up some data that I can pass into the game, probably using Javascript.

Is this or any other method of sending data to the LibGDX app (when deployed as HTML5) possible?

# Answer
I'm not aware of any reasonably straightforward way to pass form data into an HTML5 LibGDX application on the client side (ie. directly in the browser via HTML and JavaScript only). I would expect any effort to do that would get overcomplicated very quickly since the Java code is compiled down to essentially unreadable JavaScript during the HTML5 build process. There may be something clever that could be done with source maps, but its probably not worth the effort.

This may or may not fit your use case, but if you write a server-side application to handle the form data (in any server-side tech, php, node, java, etc... perhaps storing the form data in a database) then you can communicate with the server-side application from the LibGDX app using the built in networking API of LibGDX such as standard http requests.

A better alternative is probably to just create your HTML forms directly in LibGDX using scene2D UI API and then there's no separation between the input and the game. The downside to this is that if you need to change the forms then you'll have to rebuild and redeploy the game, but if your form data changed significantly enough then you'd probably have to do that anyway in order to process the new data in the game.
> 1 votes

---
Tags: java, libgdx, javascript, html5
---