title: Rotated Sprites collision detection

text:
# Question
Title: Rotated Sprites collision detection
I am trying to implement checkCollision function in my game, I used AABB method but the problem is that my sprites are rotated so it's not really precise. I could finely describe my Sprites with rotated ellipses. Is there any more precise way of detecting the collision if I have the following attributes of entities:

```
entity.x
entity.y
entity.width
entity.height
entity.angle

```

Here is what I have coded so far (x and y are in the middle of my sprite):

```
this.checkCollision = function(entity1, entity2) {
  return (entity1.x - (entity1.width*this.COLLISION_EPSILON_WIDTH)/2 < entity2.x + (entity2.width * this.COLLISION_EPSILON_WIDTH)/2 &&
   entity1.x + (entity1.width*this.COLLISION_EPSILON_WIDTH)/2 > entity2.x - (entity2.width * this.COLLISION_EPSILON_WIDTH)/2 &&
   entity1.y - (entity1.height*this.COLLISION_EPSILON_HEIGHT)/2 < entity2.y + (entity2.height*this.COLLISION_EPSILON_HEIGHT)/2 &&
   (entity1.height*this.COLLISION_EPSILON_HEIGHT)/2 + entity1.y > entity2.y - (entity2.height*this.COLLISION_EPSILON_HEIGHT)/2)
}

```

PS: my cousin told me to do it with three circles (which creates a shape very similar to the ellipse) but I do not really know how to do it.

# Answer
> 0 votes
The common method to use is the Separating Axis Theorem. There's an explanation with visuals here:

https://gamedev.stackexchange.com/a/60225/98134

The guys behind N+ created a great interactive tutorial (with code!) about it here:

http://www.metanetsoftware.com/technique/tutorialA.html

# Answer
> -1 votes
I've used the separating axis theorem and I've come up with this huge code:

```
this.checkCollision = function(entity1, entity2) {

  var width1 = (entity1.width * this.COLLISION_EPSILON_WIDTH)/2;
  var height1 = (entity1.height * this.COLLISION_EPSILON_HEIGHT)/2;
  var width2 = (entity2.width * this.COLLISION_EPSILON_WIDTH)/2;
  var height2 = (entity2.height * this.COLLISION_EPSILON_HEIGHT)/2;

   if(typeof entity1.angle == 'undefined')
    entity1.angle = 0;

  if(typeof entity2.angle == 'undefined')
    entity2.angle = 0;

   var radius1 = Math.sqrt((height1 * height1)+(width1 * width1));
   var radius2 = Math.sqrt((height2 * height2)+(width2 * width2));

   var angle1 = Math.asin(height1/radius1);
   var angle2 = Math.asin(height2/radius2);

   var x1 = [];
   var x2 = [];
   var y1 = [];
   var y2 = [];

   x1[0] = entity1.x + radius1 * Math.cos(entity1.angle - angle1);
   y1[0] = entity1.y + radius1 * Math.sin(entity1.angle - angle1);
   x1[1] = entity1.x + radius1 * Math.cos(entity1.angle + angle1);
   y1[1] = entity1.y + radius1 * Math.sin(entity1.angle + angle1);
   x1[2] = entity1.x + radius1 * Math.cos(entity1.angle + Math.PI - angle1);
   y1[2] = entity1.y + radius1 * Math.sin(entity1.angle + Math.PI - angle1);
   x1[3] = entity1.x + radius1 * Math.cos(entity1.angle + Math.PI + angle1);
   y1[3] = entity1.y + radius1 * Math.sin(entity1.angle + Math.PI + angle1);

   x2[0] = entity2.x + radius2 * Math.cos(entity2.angle - angle2);
   y2[0] = entity2.y + radius2 * Math.sin(entity2.angle - angle2);
   x2[1] = entity2.x + radius2 * Math.cos(entity2.angle + angle2);
   y2[1] = entity2.y + radius2 * Math.sin(entity2.angle + angle2);
   x2[2] = entity2.x + radius2 * Math.cos(entity2.angle + Math.PI - angle2);
   y2[2] = entity2.y + radius2 * Math.sin(entity2.angle + Math.PI - angle2);
   x2[3] = entity2.x + radius2 * Math.cos(entity2.angle + Math.PI + angle2);
   y2[3] = entity2.y + radius2 * Math.sin(entity2.angle + Math.PI + angle2);

   var axisx = [];
   var axisy = [];

   axisx[0] = x1[0] - x1[1];
   axisy[0] = y1[0] - y1[1];
   axisx[1] = x1[2] - x1[1];
   axisy[1] = y1[2] - y1[1]

   axisx[2] = x2[0] - x2[1];
   axisy[2] = y2[0] - y2[1];
   axisx[3] = x2[2] - x2[1];
   axisy[3] = y2[2] - y2[1]

   for(var k = 0; k < 4; k++) {

     var proj = x1[0] * axisx[k] + y1[0] * axisy[k];

     var minProj1 = proj;
     var maxProj1 = proj;

     for(var i = 1; i < 4; i++) {
       proj = x1[i] * axisx[k] + y1[i] * axisy[k];

       if(proj < minProj1)
        minProj1 = proj;
       else if(proj > maxProj1)
        maxProj1 = proj;
     }

     proj = x2[0] * axisx[k] + y2[0] * axisy[k];

     var minProj2 = proj;
     var maxProj2 = proj;

     for(var j = 1; j < 4; j++) {
        proj = x2[j] * axisx[k] + y2[j] * axisy[k];

        if(proj < minProj2)
          minProj2 = proj;
        else if(proj > maxProj2)
          maxProj2 = proj;
     }

     if(maxProj2 < minProj1 || maxProj1 < minProj2)
      return false;

   }

   return true;
}

```

---
Tags: collision-detection, javascript
---


# Question
Title: How does ESRB content rating work for games with DLC?
Lets say you have a game rated "Teen" by the ESRB, but later down the line, you release a DLC that would push the game's rating to "Mature". Are the two ratings kept separate for the base game and the DLC or will the base game be "upgraded" to the higher DLC rating?

# Answer
The two ratings are kept separate, and furthermore one only needs to resubmit the DLC if it would exceed the rating given to the base game, as noted in the ESRB's rating guidelines.
> 4 votes

---
Tags: content-rating, esrb
---


title: 360 degree viewer for AR

text:
# Question
Title: 360 degree viewer for AR
I want to implement a 360-degree viewer for Augmented-Reality in Unity. Augmented-Reality means in this case, that I want to place an image like an interface mockup in my viewer which has transparency. The transparency is getting filled with the real world. So the real world part is working without problems, but that is also the reason, why a sky box is not possible since the sky box would block that.

So I already had 2 approaches:

1. A sphere with a shader which rendered only the inside (turned the normals), worked on my MAC, but didn't render anything on my vr/ar device (Samsung GearVR)... Here a picture how it should look like and does look like in the Unity Editor. But nothing of this "crosshair" is showing up on the GearVR
2. A sphere or cylinder where I turned the normals beforehand in Blender, didn't apply the texture correctly and didn't show anything in Unity and on Device except a blank color.

# Answer
> 1 votes
Yes, this is certainly possible. You'd need to use a sphere with inverted normals or a shader that had backface culling disabled.

Depending on the content you wanted to put on the inside, it could be fairly static information like would exist in a texture. Or you can even use Unity's UI by modifying the UI's mesh, first to tessellate it to add vertices, then to reposition the vertices for it to be curved (you can see an example of this in this asset). This will provide a much easier interaction model (using the existing UI system) and allow you to quickly prototype new interactions.

If you're deploying to a mobile device, you'll have to be careful about the shader you use, and make sure it's supported by the platform you want to use it on.

---
Tags: unity, shaders, virtual-reality, augmented-reality
---


title: Finding a moving target in a maze

text:
# Question
Title: Finding a moving target in a maze
I'm making a game that is a bit of a mix of snake and pacman.

Basically, two players go through the maze and each time they pick up a piece of candy, a cube is added to their tail. If one player touches the other's tail, he steals that piece for himself and the game is over when one player has all the pieces.

Right now they both move randomly unless there's a piece of candy one space away that is not their tail.

I'm trying to find a method/algorithm (preferably a different method for each player) for both players to target/avoid the other player. Any advice?

# Answer
> 1 votes
For an algorithm that finds paths for snakes eating fruit, see this related question: How to find a safe path for an AI snake?

As for the adversarial part - snakes eating each other's tails - unfortunately you've created a game where either: **both players can force a draw, or the game will never end**. This is because:

* The game only ends if one player loses their whole tail (i.e. left with just a head)
* The snakes move one grid at a time at the same speed, and they can either:
    + Both move towards each other (reduce distance by 2)
    + One moves towards the other, the other moves away (distance unchanged)
    + Both move away from each other (increase distance by 2)

So the only way a game could end is if the snakes are an **odd** distance away, because that's the only way one snake could eat the other's tail completely, and this happens:

```
..ht    .ht.    hH..     Snake 1: ht (lose)
....    .H..    .T..     Snake 2: HT (win)
TH..    .T..    ....

```

But notice that snake 1 could always force a draw if it also moves towards the other snake, making their heads run into each other. Also note that if the snakes are an **even** distance away, the game could never end.

So you'll need to change your game design, like add other winning conditions, such as:

* Player that eats the most things (candy or tail) wins
* Normal snakes: players can't each other's tails, or only conditionally (after eating a powerup?)
* Snakes can move at variable speeds
* Eliminate the draw condition (e.g. only the larger snake wins if both heads collide)

# Answer
> -1 votes
It depends on how complex you want your AI behaviors to be. If you want the most realistic, do some research on the A\* algorithm. The other easier option would most likely be depth first search. Definitely look into AI pathfinding and you should find your solution.

---
Tags: unity, algorithm, grid, maze
---


title: NullReferenceException in Unity

text:
# Question
Title: NullReferenceException in Unity
Since many users are facing the `NullReferenceException: Object reference not set to an instance of an object` error in Unity, I thought that it would be a good idea to gather from multiple source some explanation and ways to fix this error.

---

### Symptoms

I am getting the error below appearing in my console, what does it mean and how do I fix it?

> NullReferenceException: Object reference not set to an instance of an object

# Answer
### Value type vs Reference type

In many programming languages, variables have what is called a "data type". The two primary data types are value types (int, float, bool, char, struct, ...) and reference type (instance of classes). While value types contains the **value itself**, references contains a **memory address** pointing to a portion of memory allocated to contain a set of values (similar to C/C++).

For example, `Vector3` is a value type (a struct containing the coordinates and some functions) while components attached to your GameObject (including your custom scripts inheriting from `MonoBehaviour`) are reference type.

### When can I have a NullReferenceException?

`NullReferenceException` are thrown when you try to access a reference variable that isn't referencing any object, hence it is null (memory address is pointing to 0).

Some common places a `NullReferenceException` will be raised:

**Manipulating a GameObject / Component that has not been specified in the inspector**

```
// t is a reference to a Transform.
public Transform t ;

private void Awake()
{
     // If you do not assign something to t
     // (either from the Inspector or using GetComponent), t is null!
     t.Translate();
}

```

**Retrieving a component that isn't attached to the GameObject and then, trying to manipulate it:**

```
private void Awake ()
{
    // Here, you try to get the Collider component attached to your gameobject
    Collider collider = gameObject.GetComponent<Collider>();

    // But, if you haven't any collider attached to your gameobject,
    // GetComponent won't find it and will return null, and you will get the exception.
    collider.enabled = false ;
}

```

**Accessing a GameObject that doesn't exist:**

```
private void Start()
{
    // Here, you try to get a gameobject in your scene
    GameObject myGameObject = GameObject.Find("AGameObjectThatDoesntExist");

    // If no object with the EXACT name "AGameObjectThatDoesntExist" exist in your scene,
    // GameObject.Find will return null, and you will get the exception.
    myGameObject.name = "NullReferenceException";
}

```

*Note:* Be carefull, `GameObject.Find`, `GameObject.FindWithTag`, `GameObject.FindObjectOfType` only return gameObjects that are **enabled** in the hierarchy when the function is called.

**Trying to use the result of a getter that's returning `null`:**

```
var fov = Camera.main.fieldOfView;
// main is null if no enabled cameras in the scene have the "MainCamera" tag.

var selection = EventSystem.current.firstSelectedGameObject;
// current is null if there's no active EventSystem in the scene.

var target = RenderTexture.active.width;
// active is null if the game is currently rendering straight to the window, not to a texture.

```

**Accessing an element of a non-initialized array**

```
private GameObject[] myObjects ; // Uninitialized array

private void Start()
{
    for( int i = 0 ; i < myObjects.Length ; ++i )
        Debug.Log( myObjects[i].name ) ;
}

```

**Less common, but annoying if you don't know it about C# delegates:**

```
delegate double MathAction(double num);

// Regular method that matches signature:
static double Double(double input)
{
    return input * 2;
}

private void Awake()
{
    MathAction ma ;

    // Because you haven't "assigned" any method to the delegate,
    // you will have a NullReferenceException
    ma(1) ;

    ma = Double ;

    // Here, the delegate "contains" the Double method and
    // won't throw an exception
    ma(1) ;
}

```

### How to fix ?

If you have understood the previous paragraphes, you know how to fix the error: make sure your variable is referencing (pointing to) an instance of a class (or containing at least one function for delegates).

Easier said than done? Yes, indeed. Here are some tips to **avoid** and **identify** the problem.

The "dirty" way : The try & catch method :

```
Collider collider = gameObject.GetComponent<Collider>();

try
{
    collider.enabled = false ;
}
catch (System.NullReferenceException exception) {
    Debug.LogError("Oops, there is no collider attached", this) ;
}

```

The "cleaner" way (IMHO) : The check

```
Collider collider = gameObject.GetComponent<Collider>();

if(collider != null)
{
    // You can safely manipulate the collider here
    collider.enabled = false;
}
else
{
    Debug.LogError("Oops, there is no collider attached", this) ;
}

```

---

When facing an error you can't solve, it's **always** a good idea to find the cause of the problem. If you are "lazy" (or if the problem can be solved easily), use `Debug.Log` to show on the console information which will help you identify what could cause the problem. A more complex way is to use the Breakpoints and the Debugger of your IDE.

Using `Debug.Log` is quite useful to determine which function is called first for example. Especially if you have a function responsible for initializing fields. But don't forget to remove those `Debug.Log` to avoid cluttering your console (and for performance reasons).

Another advice, don't hesitate to "cut" your function calls and add `Debug.Log` to make some checks.

Instead of :

```
 GameObject.Find("MyObject").GetComponent<MySuperComponent>().value = "foo" ;

```

Do this to check if every references are set :

```
GameObject myObject = GameObject.Find("MyObject") ;

Debug.Log( myObject ) ;

MySuperComponent superComponent = myObject.GetComponent<MySuperComponent>() ;

Debug.Log( superComponent ) ;

superComponent.value = "foo" ;

```

Even better :

```
GameObject myObject = GameObject.Find("MyObject") ;

if( myObject != null )
{
   MySuperComponent superComponent = myObject.GetComponent<MySuperComponent>() ;
   if( superComponent != null )
   {
       superComponent.value = "foo" ;
   }
   else
   {
        Debug.Log("No SuperComponent found onMyObject!");
   }
}
else
{
   Debug.Log("Can't find MyObject!", this ) ;
}

```

### Sources:

1. http://answers.unity3d.com/questions/47830/what-is-a-null-reference-exception-in-unity.html
2. https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it/218510#218510
3. https://support.unity3d.com/hc/en-us/articles/206369473-NullReferenceException
4. https://unity3d.com/fr/learn/tutorials/topics/scripting/data-types
> 17 votes

# Answer
While we can easily just do a check to ensure we are not trying to access a null reference, this is not always a suitable solution. Many times, in Unity programming, our problem may derive from the fact that the reference *should not* be null. In some situations, simply ignoring null references can break our code.

For example, it might be a reference to our input controller. It is great that the game does not crash due to the null reference exception, but we need to figure out *why* there is no input controller, and fix *that* problem. Without it, we have a game that may not crash, but can not take input, either.

Below, I will list possible reasons and solutions, as I come across them in other questions.

---

***Are you trying to access a "manager" class?***

If your trying to access a class that acts as a "manager" (that is, a class that should only ever have one instance running at a time), you might be better off using the Singleton approach. A Singleton class can ideally be accessed from anywhere, directly, by keeping a `public static` reference to itself. In this way, a Singleton can contain a reference to the active instance, which would be accessible without the trouble of setting up the actual reference every time.

***Are you referencing the instance of your object?***

It is common to simply mark a reference as `public`, so we can set the reference to the instance via the inspector. Always check that you *have* set the reference to an instance, via the inspector, as it is not uncommon to miss this step.

***Are you instantiating your instance?***

If we are setting up our object in code, it is important to ensure that we *instantiate* the object. This can be carried out using the `new` keyword and the constructor methods. For example, consider the following:

```
private GameObject gameObject;

```

We have created a reference to a `GameObject`, but it does not point to anything. Accessing this reference *as is* will result in a *null reference exception*. Before we reference our `GameObject` instance, we may call a default constructor method as follows:

```
gameObject = new GameObject();

```

The Unity tutorial on classes explains the practice of creating and using constructors.

***Are you using the `GetComponent<t>()` method with the assumption that the component exists?***

First, ensure that we always call `GetComponent<t>()` before we call methods from the component instance.

For reasons not worth going in to, we may assume our local game object contains a particular component, and try to access it with `GetComponent<t>()`. If the local game object does *not* contain that particular component, we will return a `null` value.

You could easily check if the returning value is `null`, prior to accessing it. However, if your game object *should* have the required component, it may be better to ensure that it at least has a *default* version of that component. We can tag a `MonoBehaviour` as `[RequireComponent(typeof(t))]` to ensure we always have that type of component.

Here is an example of a `MonoBehaviour` for a game object that should always contain a `Rigidbody`. If the script is added to a game object that does *not* contain a `Rigidbody`, a default `Rigidbody` will be created.

```
[RequireComponent(typeof(Rigidbody))]
public class AlwaysHasRigidbody : MonoBehaviour
{
    Rigidbody myRigidbody;

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

```

***Have you tried to re-build your project?***

There are some cases where Unity may cause problems by trying to reference a *cached* version of a game object. In line with the age old "turn it off and on again" solution, try deleting your *Library* folder, and re-open Unity. Unity will be forced to re-build your project. This can solve some very peculiar instances of this problem, and should point to issues that would not come up in a final build.
> 5 votes

# Answer
I see that there's an accepted answer. But, there is a better answer or suggestion for you for handling `NullReferenceException`. If you can relate programming in Java language like me, you can prevent from sending a null error by using the `try-catch` block. Try it for yourself! ;-)

If you're using in C#, check if you have `using System;` at the top of your script file. If not, add it. Now, you can use all sorts of `Exception` classes while try-catching a line of code.

If your're using UnityScript, use `import System;`

Here's an example:

```
using System; // --> This exact line of code. That's it.
using UnityEngine;

public class Test : MonoBehaviour {

    public GameObject player; // --> Example to check if there's a null content;

    public void Update() {

        // You may now catch null reference here.
        try {

            player.transform.Translate(0, 0, 2);

        } catch(NullReferenceException e) { // --> You may use this type of exception class

        }

    }
}

```

Also remember, you can catch also other exceptions such as `MissingReferenceException`, `MissingComponentException`, `IndexOutOfRangeException`, or any other exception classes as long as you include `using System` in your script.

That is all.
> -5 votes

---
Tags: unity, debugging, exceptions
---


title: How to add a logo to a captured image?

text:
# Question
Title: How to add a logo to a captured image?
I have a plane which contain a `WebCamTexture` and a button to capture the image

script to capture the image

```
void CaptureAndSave () {
    Debug.Log (Camera_panel_script.webCameraTexture);
    Texture2D snap = new Texture2D(Camera_panel_script.webCameraTexture.width, Camera_panel_script.webCameraTexture.height);
    snap.SetPixels(Camera_panel_script.webCameraTexture.GetPixels());
    snap.Apply();
    Debug.Log (Application.persistentDataPath.ToString());
    System.IO.File.WriteAllBytes(
        Application.persistentDataPath+"/my_image.png",
        snap.EncodeToPNG()
        );
}

```

this is the resulted image

how can i modify my code to add `the image` logo to my resulted picture ? so the captured image would look like this :

**EDIT:** i tried to do a code to change the pixels in the of the webcameTexture like this :

```
public static Texture2D CombineTextures(GameObject obj, Texture2D background, Texture2D TodrawLogo)
{
    Vector3 v = obj.transform.position;// obj is TodrawLogo gameobject
    int width = TodrawLogo.width;
    int height = TodrawLogo.height;
    for (int x =(int)v.x; x < width; x++){
        background.SetPixel(x,(int)v.y,TodrawLogo.GetPixel(x,(int)v.y));
    }
    background.Apply();
    return background;
}

```

but i am out of luck also

# Answer
> 2 votes
I made some changes for your `CombineTextures` method,

```
public static Texture2D CombineTexture(GameObject obj, Texture2D background, Texture2D TodrawLogo)
{
    int width = TodrawLogo.width;
    int height = TodrawLogo.height;

    int backWidth = background.width;
    int backHeight = background.height;
    // bottom right corner
    int startX = backWidth - width;
    int startY = backHeight - height;
    // create new texture
    Texture2D t = new Texture2D(backWidth,backHeight);
    // right corner
    int y = 0;
    while (y < backHeight) {
        int x = 0;
        while (x < backWidth) {
            // set normal pixels
            background.SetPixel(x,y,background.GetPixel(x,y));
            // if we are at bottom right apply logo
            //TODO also check alpha, if there is no alpha apply it!
            if(x >= startX && y < backHeight- startY)
                background.SetPixel(x,y,TodrawLogo.GetPixel(x-startX,y-startY));
            ++x;
        }
        ++y;
    }
    background.Apply();
    return background;
}

```

You can change the values inside while loop to place your texture where you want.

# Answer
> 0 votes
You can easily achieve that effect by using a **Second Camera**.

Assuming that your Main Camera has `Depth` -1, add a second camera with `Depth` 0. Doing this will make the Second Camera render after the first.

You can then apply a specific layer Layer to your *watermark* object and then configure your Second Camera (`Culling Mask` property) to render only the *watermark*.

This way you will have your Main Camera render the whole scene, while the Second Camera will render only the watermark object, on top of what the Main Camera outputs.

As for the capturing part, try take a screenshot:

```
public class ExampleClass : MonoBehaviour {
    void OnMouseDown() {
        Application.CaptureScreenshot("Screenshot.png");
    }
}

```

# Answer
> 0 votes
Here's my version which uses `Color32` rather than Color so we can utilize more integer math. My watermark was done in PNG which uses integers only. I also created an array of floats to prevent any floating point arithmetic when applying the watermark. And I used a premature optimization technique of going backwards in a loop but that's just my habit. This also handles transparency from an alpha channel.

```
// Initialize transparency map.  You can have this in a utility class
// if preferred
private static float[] TRANSPARENCY_MAP;

static MyClass() {
  TRANSPARENCY_MAP = new float[256];
  for (var i = 255 ; i >= 0; --i) {
    TRANSPARENCY_MAP[i] = (float)i/255;
  }
}

void AddWatermark(Texture2D target, Texture2D watermark) {
  // If your watermark is going to be reused a lot you may want to
  // store the GetPixels(), width and height as class variables.
  var watermarkPixels = watermark.GetPixels32();

  var pix = target.GetPixels32();

  for (var y = watermark.height - 1; y >= 0; --y) {
    for (var x = watermark.width - 1; x >= 0; --x) {
      var originInPix =
        (y * target.width) + (target.width - watermark.width);
      var p1 = originInPix + x;
      var p2 = y * watermarkTexture.width + x;
      // Guard condition in case the watermark is larger than the image.
      if (p1 >= pix.Length || p2 >= watermarkPixels.Length)
      {
        continue;
      }
      var a = pix[p1];
      var b = watermarkPixels[p2];
      float l = TRANSPARENCY_MAP[b.a];
      pix[originInPix + x] = Color32.Lerp(a, b, l);
    }
  }
  target.SetPixels32(pix);
}

```

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


title: Problems with the Unity text field

text:
# Question
Title: Problems with the Unity text field
Let say I have this list and currently there are three animals inside the list. These names below are displayed on the text field in the scene.

Cat

Bird

Goat

If there is a new animal is added to the list, for example a 'dog', the code will add 'dog' below the 'Goat' inside the text field above. Now I have a problem when the same animal is added to the list. I don't know how to actually display the updated text field if the same type of animal is added to the list and will not messing up the text field or duplicating the same name inside the text field. Please help.

This is the code

```
foreach (var animalnames in newComp)
        {
            if((componentName.text.Length !=0)&&(animal.transform.name != animalnames.name))
            {
                componentName.text = oldName+('\n')+('\n')+('\n')+animal.transform.name;
            }
            if((componentName.text.Length !=0)&&(animal.transform.name == animalnames.name))
            {
                Debug.Log("same");
                animalnames.name = animal.transform.name;
                //componentName.text = ('\n')+animalnames.name;
            }
        }
        oldName = componentName.text;

```

# Answer
You should probably use StringBuilder for creating text field content something like this:

```
// somewhere in component constructor
this.sb = new StringBuilder()
this.animalNamesList = new List<string>()

// when adding new name
if (!this.animalNamesList.Contains(name)) {
    this.animalNamesList.Add(name)
}

// and in update text field content
this.sb.clear()
foreach (string animalName in this.animalNamesList) {
    this.sb.AppendLine(animalName)
}
this.textField.text = this.sb.ToString()

```

Check more about String builder:

https://msdn.microsoft.com/pl-pl/library/system.text.stringbuilder(v=vs.110).aspx

and List:

https://msdn.microsoft.com/pl-pl/library/6sh2ey19(v=vs.110).aspx
> 1 votes

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


# Question
Title: Why are my network players only able to shoot horizontally in my first person shooter?
I am quite new to the Unity community, but I can code in C#. I am testing Unity networking using a standard FPS. I am stuck while testing out multiplayer shooting, not using raycasts. The host can shoot wherever he wants, but other players can only shoot along the Y axis (left and right).

Video describing my problem

The way I handle rotations, the body only rotates left and right, and then I rotate the camera up and down; I don't want the body to rotate in that direction. I instantiate a bullet in front of my mesh and add velocity to its rigid body in the direction the camera is facing.

Why are my players only shooting in left or right direction?

---

**Here's my code for shooting:**

```
using UnityEngine;
using UnityEngine.Networking;

public class Shoot : NetworkBehaviour
{
    public GameObject bulletPrefab;
    public float bulletSpeed = 30f;
    public float bulletDecay = 1f;
    public float bulletY = 0;
    public Camera cam;

    void Update()
    {
        if (!isLocalPlayer)
        {
            return;
        }

        if (Input.GetButtonDown("Fire1"))
        {
            CmdFire();
        }
    }

    [Command]
    void CmdFire()
    {
        var bullet = (GameObject)Instantiate(bulletPrefab,
        new Vector3(cam.transform.position.x, cam.transform.position.y + bulletY,
            cam.transform.position.z) + cam.transform.forward, Quaternion.identity);

        // local
        bullet.GetComponent<Rigidbody>().velocity = cam.transform.forward * bulletSpeed;
        // net
        NetworkServer.Spawn(bullet);

        Destroy(bullet, bulletDecay);
    }
}

```

**Here's the movement script:**

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

public class PlayerMove : NetworkBehaviour
{
    public Camera cam; // This object has been set via the inspector
    public GameObject bulletPrefab;
    public GameObject mesh;
    public float spawnX = 0, spawnY = 0;
    public float bulletSpeed = 30f;
    public float bulletDecay = 1f;
    public float bulletY = 0;
    public float moveSpeed = 0.1f;
    public float jumpForce = 1;
    public float rotateSpeed = 1.5f;
    public Vector3 v3Rotate;
    public float rotaceMin = -90, rotaceMax = 90;

    float distToGround;
    bool canJump = true;

    void Start()
    {
        // localplayer start
        if (isLocalPlayer)
        {
            distToGround = GetComponent<Collider>().bounds.extents.y;
            cam.transform.localEulerAngles = v3Rotate;
            return;
        }

        // turn off multiplayer cam and AuLi
        cam.enabled = false;
        cam.GetComponent<AudioListener>().enabled = false;
    }

    void Awake()
    {
        this.name = "Player";
    }

    void Update()
    {
        if (!isLocalPlayer)
        {
            return;
        }

        // get axis
        var x = Input.GetAxis("Horizontal");
        var z = Input.GetAxis("Vertical");

        // rotate left right
        var rotateLR = Input.GetAxis("Mouse X") * rotateSpeed;

        // rotate up down
        v3Rotate.x -= Input.GetAxis("Mouse Y") * rotateSpeed;

        //rotate calculate limit up down
        v3Rotate.x = Mathf.Clamp(v3Rotate.x, rotaceMin, rotaceMax);
        cam.transform.localEulerAngles = v3Rotate;

        // move
        var inputModifyFactor = (x != 0.0f && z != 0.0f)? .7071f : 1.0f;
        x *= inputModifyFactor;
        z *= inputModifyFactor;
        transform.Translate(x*moveSpeed,0,z*moveSpeed);

        // calculate rotation left right
        transform.Rotate(new Vector3(0, rotateLR, 0));

        if (Input.GetButtonDown("Fire1"))
        {
            Cursor.lockState = CursorLockMode.Locked;
        }

        if (Input.GetButtonDown("Jump"))
        {
            //if(IsGrounded())
            if (canJump)
            {
                GetComponent<Rigidbody>()
                    .AddForce(0, jumpForce, 0, ForceMode.VelocityChange);
                canJump = false;
            }
            else
            {
                // make sure he is grounded
                if (IsGrounded())
                {
                    canJump = true;
                }
            }
        }

        if (Input.GetKeyDown(KeyCode.Escape))
        {
            Cursor.lockState = CursorLockMode.Confined;
        }
    }

    public override void OnStartLocalPlayer()
    {
        // turn off local mesh of player
        this.GetComponentInChildren<MeshRenderer>().enabled = false;
    }

    public bool IsGrounded()
    {
        return Physics.Raycast(transform.position, -Vector3.up, distToGround + 0.1f);
    }

    void OnTriggerEnter()
    {
        canJump = true;
    }
}

```

# Answer
So after few days I was thinking maybe I did nothing wrong so I started looking into other posibilities than "mistake in the code". It felt like the player shoot script doesnt know about that camera rotation. So I tried to add **NetworkTransformChild** to a **Player prefab** and targeted the camera of the prefab and **it worked**...

I am not sure if it is not too much of an overkill trying to send so many transform data just for one prefab but I guess we will see later. If anyone see any problem with this solution like network overflow or something please let me know!

I will play with it now and see if I can for example send only X axis rotation.

***Thank you all for so much help and good edits on my question.***
> 1 votes

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


# Question
Title: How to solve this component based events response issue?
I'm working on a new game architecture and I have issues with the handling of events in our component-based approach.

We have a component *Match*. When a match ends, an event *Match\_end* is sent. There are two components that are listening to this event, *Ads* and *Store*.

The behaviour that we'd like is the following: when the match ends, an ad is displayed, and when it's closed (or if it's not available), the store is displayed.

With the current setup of events and listeners, both the *Ads* and the *Store* will be displayed simultaneously.

We're thinking about specifying some order on subscribing (but it looks wrong to me).

Who should resolve the event processing order? Is it *Nobody* and we should use an other approach?

# Answer
You have a few options here and its really a matter of taste.

**Multiple Listeners - Ordered Invocation**

As you mentioned, you could specify some *order* that defines how the listeners are to be invoked when the event is raised. Generally speaking, I've almost always see the listener expose some numeric value to determine its placement. Sometimes systems expose a set of constants that dictate magic values to represent specific points in the list such as `START`, `END`, or `AFTER_SYSTEM`.

Then it is the responsibility of the subject the listeners are registered with to read and adhere to the specified order in a deterministic way. Then its just the normal listener dispatch by looping over an already pre-sorted list and invoke the listeners one-by-one.

**Single Listener Dispatch**

Another solution would be that your system only allows the registration of a single `Match_End` handler of which you then manually compose the dispatch order yourself in code.
> 0 votes

# Answer
Add another event.

1. Register only *Ads* to listen to *Match\_end*.
2. Register *Store* to listen to *Ads\_end*.

Then, when the match ends, *Match\_end* is sent; then *Ads* take over, which sends *Ads\_end* when the add is closed or when it realizes it can't be displayed; then *Store* takes over.
> 0 votes

---
Tags: architecture, component-based, events
---


# Question
Title: Execute a function for ten seconds and disable it for two seconds
I have a particular function which I am calling in Update function. For the first ten seconds, the function should get called in Update function, then it should get disabled for next two seconds, then again enable it for next ten seconds. This cycle should keep repeating? How can I execute it?

# Answer
Alternatively, there is one-liner using modulus:

```
void Update()
{
    //if you want it loop from specific start time rather than from start of the game,
    //subtract said time value from Time.time argument value
    if(Mathf.Repeat(Time.time, execDuration + sleepDuration) < execDuration)
        executeFunction();
}

```
> 15 votes

# Answer
I haven't tested the following code, but you will get the idea :

```
public float wakeUpDuration = 10.0f ;
public float sleepDuration = 2.0f;
private bool callFunction = true ;
private float time = 0 ;

void Update()
{
    time += Time.deltaTime;
    if( callFunction )
    {
         if( time >= wakeUpDuration )
         {
             callFunction = false;
             time = 0 ;
         }
         else
         {
             foo(); // Your function
         }
    }
    if( !callFunction && time >= sleepDuration )
    {
        callFunction = true;
        time = 0 ;
    }
}

```
> 5 votes

# Answer
You can do this with a coroutine also. Something like

```
public class Comp : MonoBehaviour
{
  private bool _shouldCall;

  Start()
  {
    StartCoroutine(UpdateShouldCall)
  }

  Update()
  {
    if(_shouldCall)
        CallTheFunction();
  }

  IEnumerator UpdateShouldCall()
  {
    while(true)
    {
        _shouldCall = true;
        yield return new WaitForSeconds(10);
        _shouldCall = false;
        yield return new WaitForSeconds(2);
    }
  }

}

```
> 4 votes

---
Tags: unity
---


title: Edit Part of a Texture

text:
# Question
Title: Edit Part of a Texture
Lets suppose that I have a large, 2048 by 2048 pixel texture uploaded to the GPU.

I'd like to occasionally be able to edit parts of it, e.g. a 64x64 area.

Re-uploading the entire texture would be a huge waste of resources so is there any other way of doing this?

# Answer
> 2 votes
glTexSubImage2D will do exactly what you wish.

Assume that you have already created the base texture:

```
glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA8, 2048, 2048, 0, GL_RGBA, GL_UNSIGNED_BYTE, dataPtr);

```

Assume that you have a 64x64 region of the data that you wish to replace and you have the new data ready in a system memory array:

```
unsigned int newData[64][64];

```

Assume that you wish to transfer this data to a 64x64 rectangle in the original texture positioned at xofs, yofs from it's origin (and remembering that the origin in OpenGL is at bottom-left).

Using glTexSubImage2D to transfer this to the texture, you would make the following calls:

```
// tell OpenGL that each row of the original texture is 2048 texels wide
// so that it can correctly transfer a smaller width rectangle to it
glPixelStorei (GL_UNPACK_ROW_LENGTH, 2048);

// transfer the data
glTexSubImage2D (GL_TEXTURE_2D, 0, xofs, yofs, 64, 64, GL_RGBA, GL_UNSIGNED_BYTE, newData);

// reset to default behaviour
glPixelStorei (GL_UNPACK_ROW_LENGTH, 0);

```

---

If your new data is **not** in GL\_RGBA format (typically problem cases occur if you use GL\_RGB and your source data may therefore not be aligned to 4 bytes) then you **may** need to also make the following call **before** glTexSubImage2D:

```
// source data may not be aligned to 4 bytes
glPixelStorei (GL_UNPACK_ALIGNMENT, 1);

```

And the following **after** glTexSubImage2D.

```
// reset to default behaviour
glPixelStorei (GL_UNPACK_ALIGNMENT, 4);

```

It doesn't otherwise matter where these calls are made with respect to your other glPixelStorei calls.

---

Note that this answer assumes a full conformant desktop OpenGL.

If you are targetting older hardware (and by this I mean 1990s vintage 3DFX hardware) then you will need to be aware that these typically did not use a full OpenGL driver and their mini-driver may or may not support the required calls (particularly the glPixelStorei stuff).

If you're only interested in hardware from this century you'll be OK: even Microsoft's default software OpenGL fully supports the glPixelStorei stuff.

OpenGL ES is more interesting; GL\_UNPACK\_ROW\_LENGTH only became available with ES 3.0 so if you're targetting ES 2.0 or below you'll need to find alternate solutions (maybe upload the full width of the texture).

---

**Performance**

Depending on how you manage this kind of texture update, it can have anything from an insignificant to a catastrophic impact on performance. I can only provide general guidelines.

* It used to be the case that using GL\_BGRA and GL\_UNSIGNED\_INT\_8\_8\_8\_8\_REV for your format and type parameters gave the most consistent performance across all hardware. This required OpenGL 1.2 or higher which shouldn't be a problem. On any hardware from the past 10 years this is no longer as relevant as it once was.
* If you find yourself doing multiple small updates per frame try to batch them into few large updates instead.
* If you update a texture that has pending draw calls on it, your driver may need to stall the pipeline for the draw calls to complete before it can perform the update (some drivers might copy off the data so that they can perform the update later).
* Typical advice for the next step with this kind of texture updating is to "use a PBO"; your texture updates will become faster for sure, but now you need to carefully manage your PBO updates instead. You're better off, if you already have acceptable peformance, to not complicate things.

---
Tags: opengl, opengl-es
---


# Question
Title: How to make noise-generated terrain more square?
I use a perlin noise generator to create a map. All works fine and dandy. It uses the following formula:

* Generate perlin noise
* Posterize the height values to be an integer between 0 and 5.

What I get works well. Just, the terrain is TOO organic for my purposes. Is there a way to make it a little more square and chunky?

# Answer
> 3 votes
Try using nearest neighbor scaling.

Here's my reference 100x100 noise texture & the same noise texture after posterizing to 4 levels:

Now here's the same noise, starting at lower 10x10 resolution.

Next, scale the texture up using nearest neighbor & then posterize to 4 levels.

The key here is to use the blockiness of nearest neighbor to your advantage. If you have access to your noise generator source, you might be able to use it directly. If not, you can easily add it as a post process. Since nearest neighbor is not very expensive & you're starting with a much smaller texture from your noise generator, the overall cost of handling it in post should be reasonable.

# Answer
> 3 votes
If you really want the terrain to look blocky you can use value noise which is blockier than perlin noise

*(image source — attributed to Inigo Quilez)*

# Answer
> 2 votes
Here's what you do:

1. Take standard output from a Perlin Noise function, this should be a float in the range (0-1)1
2. Multiply by 5. This will range from (0-5)
3. Round to nearest integer

All those values that were *slightly* in between your integer values will get clamped to one or the other, resulting in squared off results

If you want it to be blocky on the other two directions (the X and Y screenspace, rather than just height value) you need to use a scalar there as well, and one that's designed to perform no interpolation between values.

Something like this should work:

```
int getHeight(int x, int y) {
    float p1 = perlinNoise(x<<2, y<<2) * 5;
    int p2 = Mathf.RoundToInt(p1);
    return p2;
 }

```

Technically `Mathf.RoundToInt` is a Unity specific, but the function is named with the desired intent. Convert to your language as needed.

By dividing x and y by 4 (bitwise) it means that `x`, `x+1`, `x+2`, and `x+3` all return the same perlin noise value, making the result blocky in screenspace (not just height). Blocks will be 4x4 pixels. Increase the bitwise operator or use integer division for larger blocks.

1Inclusive or exclusive doesn't really matter. Perlin Noise tends to never actually hit the upper and lower bounds, although technically possible. Heavily dependent on the implementation (GIMP's Perlin Noise has an effective actual range of \[0.2-0.8\], for example).

# Answer
> 1 votes
The best way would be to mess with the perlin layers, and the actual functions that generate the layers. But there's an easier way:

Draw the squares and chunks you want, then overlay the perlin noise on top of them.

---
Tags: procedural-generation, perlin-noise, noise
---


# Question
Title: How to stop an animation on last frame until condition is met in Unity?
I have an animation (fishing) I want to play backwards when the player catches something or cancels the action.

Playing the animation backwards is as simple as setting the speed to -1, ie:

```
anim.SetFloat("direction", -1.0f);

```

However, my fishing animation keeps playing until I have caught something, or cancel the animation. This means that the last frame of the animation is showing, but the time of the animation is still going.

So

* the animation reaches the last frame
* then I stand there for 8 seconds,
* I catch something, so I change anim speed to -1
* anim will now reverse those 8 seconds I was "standing still" first, before it even reaches the actual animation.

I need to stop the animation time on the last frame (without leaving the animation), so that reverse will be instant. And to not exit the animation until the reverse is finished. Maybe there is some other way to do it, but I can't figure it out.

I could create a seperate animation for when I want it to go backwards, but that seems sloppy.

# Answer
> 0 votes
Have you considered having a Boolean of fishing and catching. You will want separate animations for different states such as cast, fish, catch, snag and then blend nicely between them.

The fishing can endlessly loop and then blend into various catch animations or other states like cancel when the parameters are met or lost.

```
//create parameters in the animator and update from a player state or some sort of controller script.
    anim.SetBool("myfishingparameter", isFishing);

```

You can achieve your original question by either triggering or invoking a method or event during the -1 playback and just end it before the standing part of the animation. I think you will prefer to blend between animations once you set them up.

---
Tags: unity, animation
---


title: Unity Touch problem

text:
# Question
Title: Unity Touch problem
Learning from some tutorials. Made Swipe touch scene. Have UI(virtual joystick) on canvas screen overlay. The problem is,when I am rotating character by joystick, my camera rotating too. If I've pressed on my UI, swiping script turning my camera around and I can't move the right way. How can I solve this problem?
**@Byte56** **So your camera is rotating, when you're trying to steer using your on screen joystick?**
***Yes***

# Answer
This is a common problem, a common solution is to use a global flag. Basically, when your UI accepts input, you set a global flag (something like `UIConsumingInput`) to true. If you have any other inputs, like your camera rotation, you have it test to see if `UIConsumingInput` is set to true, if `UIConsumingInput` is true, you don't process input.
> 1 votes

---
Tags: unity, movement, gui
---


# Question
Title: What is the "correct" way to render to a cubemap using Vulkan?
After searching far and wide for the solution to this, the only one I have been able to find that verifiably works is to the render a face to a framebuffer and then use a memcpy to copy that framebuffer over to the respective part of the cubemap image.

This sounds stupid.

So I ask: Surely there must be some way to render directly to one face of a cubemap image, seeing as it's such an important feature in a whole lot of 3D rendering techniques. **How do you do it?**

# Answer
> 1 votes
There is nothing in the Vulkan specification that prevents you from using an image of a cubemap texture as a color attachment image in a `VkFramebuffer` in a render pass instance. So you would simply do that: create a cubemap image, and use it in the framebuffer of a render pass instance.

---
Tags: 3d, graphics-programming, vulkan
---


# Question
Title: How do I get the touch event on a body in JBox2d
I have various bodies rotated at some angle with the help of Box2d in LibGDX. What I want is to destroy the body when I click on it, but the problem is that I am not able to get the area definition of the body so that I can check whether my touch point lies inside the body. I tried using actor and its `hit()` method but it's working only if I don't rotate it. As far as I know, once I rotate the body, its bounds are not rotated. How can I check the Touch event in a Body?

# Answer
Create Box2d fixture for your touch (and attach it to body), set it to be a sensor, place it where your touch event occurred. From now on, you can check every body that collides with your sensor. And because you are using sensor, simulation will not respond to such collision(s), but will report them instead. Here's Box2d manual, look at chapter 6.3 about sensors.
> 2 votes

# Answer
You could assign a sprite to your box2d body.

Form example I created a circle dynamic body with a radius of 1f, than I assigned to it a sprite (a red ball) that fits exactly the box2d body. Now it simply checks if the touch lies into sprite width and height.

Example Code:

```
   private void checkInput () {
                   Vector3 touchPos = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
                   camera.unproject(touchPos);
                             if (touchPos.x > sprite.getX() && touchPos.x < sprite.getX() + sprite.getWidth() && touchPos.y > sprite.getY() && touchPos < sprite.getY() + sprite.getHeight()) {
                body.setActive(false);
              world.destroyBody(body);
}
                      }

```
> 0 votes

# Answer
User touches the body only if he touches some of `Fixture`'s contained into this body. This mean, you can check every `Fixture` of `Body` using `testPoit()` method:

```
public class Player {
    private Body _body;

    public boolean isPointOnPlayer(float x, float y){
        for(Fixture fixture : _body.getFixtureList())
            if(fixture.testPoint(x, y)) return true;
        return false;
    }
}

```

Next, you need to create `InputAdapter` like this:

```
public class PlayerControl extends InputAdapter {
    private final Camera _camera;
    private final Player _player;
    private final Vector3 _touchPosition;

    public PlayerControl(Camera camera, Player player) {
        _camera = camera;
        _player = player;
        // create buffer vector to make garbage collector happy
        _touchPosition = new Vector3();
    }

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        // don't forget to unproject screen coordinates to game world
        _camera.unproject(_touchPosition.set(screenX, screenY, 0F));
        if (_player.isPointOnPlayer(_touchPosition.x, _touchPosition.y)) {
            // touch on the player body. Do some stuff like player jumping
            _player.jump();
            return true;
        } else
            return super.touchDown(screenX, screenY, pointer, button);
    }
}

```

And the last one - setup this processor to listen user input:

```
public class MyGame extends ApplicationAdapter {

    @Override
    public void create () {
    // prepare player and game camera
    Gdx.input.setInputProcessor(new PlayerControl(cam, player));
}

```

Read more about touch handling here
> 0 votes

---
Tags: java, android, box2d, libgdx
---


title: GLSL ES 2.0 alternative for dFdxFine

text:
# Question
Title: GLSL ES 2.0 alternative for dFdxFine
I'm trying to generate normal map on the fly in fragment shader. The implementation I've found is using dFdxFine function, which can't be used in WebGL, is there any alternative for dFdxFine in GLSL ES 2.0?

# Answer
Can you use `dFdx` instead? You may need `#define GL_OES_standard_derivatives 1` in your shader as well.
> 1 votes

---
Tags: glsl, fragment-shader, webgl
---


# Question
Title: How can I make players move diagonally at equal speeds?
In a tile-based 2D RPG, a character is supposed to walk into all eight directions.

However, if we blindly tell the player to move in the direction (1, 1), he will be around 41% (√2-fold) faster. Thus, my next idea was to normalize the direction vector before moving.

Unfortunately, since the vector (1, 1) normalizes to (√2 / 2, √2 / 2) ≈ (0.71, 0.71), but the game functions on a whole-pixel basis, this will make the player reach invalid 2D locations. My next idea was that I should just make diagonal movement slower by √2 somehow.

So next, I tried another approach: When I receive an input and the player isn't already walking, I set the player's destination point. Then, I compute how much of his way to the destination the player can actually walk in one frame, given the player's velocity in "pixels per frame". I will repeat the player position update every frame, until the destination is reached.

So for example, if the player needs to move from the origin (0, 0) in the direction (1, 1) at speed 1, his sprite will be displayed at (0.71, 0.71) after one frame, and in the next frame it snaps to his destination (1, 1). This is okay, because the player ends up at a valid coordinate.

While this last approach sounds okay, it has only created more problems, because now diagonal movement takes two frames, and orthogonal movement takes only one frame. In other words, the walking speeds are still not equal.

How do you usually solve this?

# Answer
> 1 votes
There are multiple workarounds.

* Don't base movement on screen pixels. Base movement on a finer grid (e.g. use float), and only snap to pixels for display.
* Declare faster diagonal movement a "feature" of the game.
* Use a hex grid.

# Answer
> 0 votes
Sounds like it's working fine to me. The real issue here is that, for some moves, you arrive at the destination with "extra time" in the frame. In that, if you were moving farther, you could, for example, move 1.5 units in two frames. Essentially, it's a rounding issue. For the example you picked, it appears that the player would arrive at the same time, two frames, even if they moved left then up as compared to moving diagonally left+up. However, it only appears that way because you've reached the bottom of your time resolution. You can't have sub-frames, so you have no choice but to waste the "half a frame" you saved by going diagonal.

I think in practice, you're likely not going to be dealing with examples so close to your time resolution. This is what @Charanor is getting at when they suggest you determine if it's even a problem. It's not likely a problem because you're likely not going to moving at 1 unit per *frame*. You'll be moving something much slower than that, so the frame resolution is much less of an issue.

---
Tags: movement, vector, coordinates, linear-algebra
---


# Question
Title: Large-Scale Case Handling for 2D Procedural Environment
I am creating a procedurally generated side scroller and I have a question regarding proper code structure/Architecture when it comes to connecting different platforms and large scale cases. There are various platform types I need to connect (e.g. a hill which leads into a tunnel which then leads into a cave, etc). I can successfully generate and connect the meshes using a bezier curve. My problem is that the way I am handling each platform connection case seems very clunky/inelegant the more I expand.

Currently I am using switch statements to handle each scenario like the above mentioned. Below is a small snippet of how I am handling each case.

```
public void SetTransition(int PrevPlatform, int CurrPlatform , Vector3 LastPosition)
{
    switch (PrevPlatform) {
    case 0:
        GroundTransition (CurrPlatform,LastPosition);
        break;
    case 1:
        CaveTransition (CurrPlatform,LastPosition);
        break;
    case 2:
        WaterTransition (CurrPlatform,LastPosition);
        break;
    case 3:
        TunnelTransition (CurrPlatform,LastPosition);
        break;
    case 4:
        WallJumpTransition (CurrPlatform,LastPosition);
        break;
    }
}

```

From here I have separate functions that handle the cases using more switch statements. The problem now is that I am starting to have a large number of branching functions that are relying each case. My code structure is becoming this large tree of switch statements. For the most part it works but I wanted to reach out to other developers before I continued this route. Is there a more effective, organized methodology to handling large scale cases?

# Answer
Typical OO design would avoid switch statements in favour of polymorphism, and if you absolutely have to use switch statements, prefer using just one in your entire program, over an enum.

I'm not sure where your `PrevPlatform` is coming from, but suppose you have a `Platform` class:

```
class Platform {
    abstract void Transition(int CurrPlatform, Vector3 LastPosition);
}

```

Then you simply override the `Transition()` method, like:

```
class GroundPlatform : Platform {
    override void Transition(int CurrPlatform, Vector3 LastPosition) {
        GroundTransition(CurrPlatform, LastPosition);
    }
}

```

So that you call it like this:

```
public void SetTransition(Platform PrevPlatform, int CurrPlatform , Vector3 LastPosition)
{
    PrevPlatform.Transition(CurrPlatform, LastPosition);
}

```
> 4 votes

# Answer
A switch statement is actually not that bad in terms of performance Switch statement O(n) is the worst case, though it can be O(1) in your case, it can grow really big, thus hard to maintain.

As @congusbongus earlier suggested, you can go with OOP. That is great approach and should be used everywhere.

But if you later would like to have multiple possible platforms that could be chosen at random for every previous platform - I suggest you place them all in an array(functions array in your case). Then you can access them by making `int PrevPlatform` \- index of that array of platforms.

Although, if you are going to have different random platforms for different types of platforms, then stick with OOP approach from the start.
> 2 votes

---
Tags: unity, architecture, procedural-generation
---


# Question
Title: Shader to see silhouette through alpha blended sprites
I want to achieve in Unity a see through effect like the one in these examples:

In my specific scenario there are a couple of requirements:

* Sprites are using alpha blending, and sprites have transparent areas.
* There are 2 kind of elements that occlude the character. One should create the silhouette effect, and the other one should behave like normal.

For occluding elements that create the silhouette I enable ZWrite, and disable it for elements that doesn't.

For the character I tried setting the queue of the shader to transparent+1, and added this pass:

```
Pass
{
    ZTest Greater
    Lighting Off
    Color [_Color]
}

```

And the effect works partially:

* The silhouette is drawn all over the character, even the parts that are transparent. Transparent parts shouldn't create a silhouette.
* The silhouette is created when the character is behind a sprite, even if that part of the sprite is transparent. Being behind a transparent part of the sprite shouldn't create the silhouette.
* The character appears infront the rest of the elements, even if it is behind them. I guess this is because setting the queue to Transparent+1. But if I leave it as Transparent, the character is drawn in the correct order, but the silhouette is never seen.

I tried to follow these tips someone gave me, but I'm unable to get it to work:

> 1) Leave the pass that renders the sprites as is.
>
> 2) Add a pass that writes to the z-buffer, but has a shader that uses clip() to discard pixels based on alpha. You can't use the z-buffer to make soft z-tests without using MSAA and alpha-to coverage. The quality of that won't be great, but it's the best you can do. A faster alternative is a pattern or noise dither, or a good old fashioned threshold if your sprites all have fairly sharp edges.
>
> 3) Add third pass to occludable objects that draws the occlusion color using the z-test and make sure it's drawn as a final pass.

I'm kind of new to shaders, specially in Unity, and I just can't figure out how to make it work properly.

# Answer
> 1 votes
Does this video cover the basics? It's an illustration of creating a few different styles of outline and silhouette from the shaders that people have already published.

https://www.youtube.com/watch?v=00qMZlacZQo

It's an example of using a shader published in the Unity Wiki to do pretty much what you're after. Content of the shader is below, although I think the outlining part of the shader may not be functioning as expected in U5.

```
Shader "Outlined/Silhouetted Diffuse" {
Properties {
    _Color ("Main Color", Color) = (.5,.5,.5,1)
    _OutlineColor ("Outline Color", Color) = (0,0,0,1)
    _Outline ("Outline width", Range (0.0, 0.03)) = .005
    _MainTex ("Base (RGB)", 2D) = "white" { }
}

CGINCLUDE
#include "UnityCG.cginc"

struct appdata {
    float4 vertex : POSITION;
    float3 normal : NORMAL;
};

struct v2f {
    float4 pos : POSITION;
    float4 color : COLOR;
};

uniform float _Outline;
uniform float4 _OutlineColor;

v2f vert(appdata v) {
// just make a copy of incoming vertex data but scaled according to normal direction
    v2f o;
    o.pos = mul(UNITY_MATRIX_MVP, v.vertex);

    float3 norm   = mul ((float3x3)UNITY_MATRIX_IT_MV, v.normal);
    float2 offset = TransformViewToProjection(norm.xy);

    o.pos.xy += offset * o.pos.z * _Outline;
    o.color = _OutlineColor;
    return o;
}
ENDCG

SubShader {
    Tags { "Queue" = "Transparent" }

    // note that a vertex shader is specified here but its using the one above
    Pass {
        Name "OUTLINE"
        Tags { "LightMode" = "Always" }
        Cull Off
        ZWrite Off
        ZTest Always
        ColorMask RGB // alpha not used

        // you can choose what kind of blending mode you want for the outline
        Blend SrcAlpha OneMinusSrcAlpha // Normal
        //Blend One One // Additive
        //Blend One OneMinusDstColor // Soft Additive
        //Blend DstColor Zero // Multiplicative
        //Blend DstColor SrcColor // 2x Multiplicative

CGPROGRAM
#pragma vertex vert
#pragma fragment frag

half4 frag(v2f i) :COLOR {
    return i.color;
}
ENDCG
    }

    Pass {
        Name "BASE"
        ZWrite On
        ZTest LEqual
        Blend SrcAlpha OneMinusSrcAlpha
        Material {
            Diffuse [_Color]
            Ambient [_Color]
        }
        Lighting On
        SetTexture [_MainTex] {
            ConstantColor [_Color]
            Combine texture * constant
        }
        SetTexture [_MainTex] {
            Combine previous * primary DOUBLE
        }
    }
}

SubShader {
    Tags { "Queue" = "Transparent" }

    Pass {
        Name "OUTLINE"
        Tags { "LightMode" = "Always" }
        Cull Front
        ZWrite Off
        ZTest Always
        ColorMask RGB

        // you can choose what kind of blending mode you want for the outline
        Blend SrcAlpha OneMinusSrcAlpha // Normal
        //Blend One One // Additive
        //Blend One OneMinusDstColor // Soft Additive
        //Blend DstColor Zero // Multiplicative
        //Blend DstColor SrcColor // 2x Multiplicative

        CGPROGRAM
        #pragma vertex vert
        #pragma exclude_renderers gles xbox360 ps3
        ENDCG
        SetTexture [_MainTex] { combine primary }
    }

    Pass {
        Name "BASE"
        ZWrite On
        ZTest LEqual
        Blend SrcAlpha OneMinusSrcAlpha
        Material {
            Diffuse [_Color]
            Ambient [_Color]
        }
        Lighting On
        SetTexture [_MainTex] {
            ConstantColor [_Color]
            Combine texture * constant
        }
        SetTexture [_MainTex] {
            Combine previous * primary DOUBLE
        }
    }
}

Fallback "Diffuse"
}

```

---
Tags: unity, shaders, graphics-programming
---


# Question
Title: Problem about underground block generation for voxels
I've been working at a voxel sandbox game and have already implemented chunk generation and stuff. But I just found that generating underground blocks with the surface ones is impossible, since that causes lag. My game only generates surface blocks for now. Are there any available chunk generation algorithms that covers the solution for my problem? Please give a link or clearly state the method. Thanks

# Answer
> 1 votes
Don't render unexposed blocks; only render those that are not entirely surrounded/covered by blocks. This includes surface blocks as well as the surface of caves in the underground.

There are more tips in this related answer: https://gamedev.stackexchange.com/a/32933/26250

---
Tags: c++, voxels
---


title: How to avoid spaghetti in the animator?

text:
# Question
Title: How to avoid spaghetti in the animator?
I am working with animations in Unity and so far I have made only four (Up Down Left and Right) and my animation window looks following...

Problem is that if I was moving Up I want hero to stay looking Up not go to 'neutral idle' (or however he started), but that means I have 4 Idle positions... and each of them can transition to Up, Down, Left or Right and they go exponentially with each additional action...

Which makes me feel like I am doing something wrong....

**Is there a better way of making transitions between different actions?**

# Answer
> 9 votes
You can solve this type of problem with BlendTrees (in general its wise idea to often rely on blend trees). Blend tree is kind of a multi-animation state that based on a (float) parameter(s) decides which of the animations it contains to be currently active (or alternatively the resulting animation can be a blend of several animations). Even when the animations are not blended, but swapped, the swap happens mid-animation (i.e if the "exiting" animation is at 35% the new one is played from 35% forward). From the "outside" all this is hidden as if it's one simple/single state.

For example you have a blend tree with 8 sprite animations (idle with 4 main and 4 diagonal directions). There are 2 parameters in this blend tree - "horizontal" and "vertical". And based on those 2 parameters the blend tree will decide what animation to play. Based on "horizontal" parameter the blend tree will choose between left/right animation and "vertical" parameter will decide the top/down animation. Then when combined you will have all 8 animations with diagonals (it's the same idea that's behind joypads/joysticks).

It's a bit confusing so, even if StackExchange doesn't like links, I will link short example video I made. Notice the top-right part of the screen. The gray dots are the "states"/animations and the active one is the one closes to the red dot. As said in the beginning, it can be even more complex and each animation to have an influence/strength based on its distance to the red dot, resulting in a blend between several animations.

From the outside its just one state(blend tree) and when you apply the same concept for walk and attack you will have only 3 states linked.

Blend Trees are created with right click on an empty Animator area Create State -\> From New Blend Tree. From there it's all in the Inspector. With the blend tree selected you can pick the type of the blend tree (1D, 2D, etc.), add animations, position them (relative to parameter values) and select the controlling parameters.

If you want more info on Blend Trees next are videos from Unity - Unite 2016 and Unity Tutorials.

# Answer
> 2 votes
The problem here is you're trying to tie everything together instead of using a trigger to switch between idles. You should be picking the idle animation using an if-else or a switch-case type of conditional. I've made a diagram that looks much neater (assume one of them is the default case):

Additional info:

Take a look at Animation Parameters on how to set parameters for the animator to recognize, State Machines for combining animations together, State Machine Behaviors for how to check the variables you've set.

---
Tags: unity, 2d, animation
---


# Question
Title: How do I copy the depth buffer to CPU memory in Direct3D 9?
I have code in **OpenGL** that uses `glReadPixels` to copy the depth buffer to a CPU memory buffer:

```
glReadPixels(0, 0, w, h, GL_DEPTH_COMPONENT, GL_FLOAT, dbuf);

```

How do I achieve the same in Direct3D?

I have looked at a similar question which gives a solution for copying the *color* buffer. I've tried to write similar code to copy the depth buffer:

```
IDirect3DSurface9* d3dSurface;
d3dDevice->GetDepthStencilSurface(&d3dSurface);

D3DSURFACE_DESC d3dSurfaceDesc;
d3dSurface->GetDesc(&d3dSurfaceDesc);

IDirect3DSurface9* d3dOffSurface;
  d3dDevice->CreateOffscreenPlainSurface(
  d3dSurfaceDesc.Width,
  d3dSurfaceDesc.Height,
  D3DFMT_D32F_LOCKABLE,
  D3DPOOL_SCRATCH,
  &d3dOffSurface,
  NULL
);

// FAILS: D3DERR_INVALIDCALL
D3DXLoadSurfaceFromSurface(
  d3dOffSurface,
  NULL,
  NULL,
  d3dSurface,
  NULL,
  NULL,
  D3DX_FILTER_NONE,
  0
);

// Copy from offscreen surface to CPU memory ...

```

The code fails on the call to `D3DXLoadSurfaceFromSurface`. It returns the error value `D3DERR_INVALIDCALL`.

So, is something wrong with my code? How can I copy the depth buffer contents?

# Answer
Per the documentation, you can acquire a reference to the depth-stencil surface for the device (if one exists for that device) by calling `GetDepthStencilSurface`. If the method returns successfully, you can lock the bits of the resulting surface using the `LockRect` method of the surface interface.

This gives you a locked rectangle with the bits of the surface accessible via the `pBits` member. You will need to use the `Pitch` as well as surface format information obtained from `GetDesc` to interpret the bits correctly.

I don't know why you are trying to use the surface-copying routines as you are, but I don't believe they are necessary.
> 2 votes

# Answer
For the sake of completeness, the copy is necessary because in general you cannot lock the depth buffer. As far as I know you need your depth buffer to use a lockable format to be able to copy the contained data directly into your own containers. D24S8 for example is a format which prevents locking the depth buffer. (I am not allowed to add comments, so as an answer ...)
> 0 votes

---
Tags: directx, depth-buffer
---


title: Modelling meteoroid to scale in Maya LT

text:
# Question
Title: Modelling meteoroid to scale in Maya LT
I have just recently started using Maya LT so forgive me if I am asking a silly question.

I am trying to model a meteoroid in Maya LT of about 8km in diameter and I am trying to model it to scale. Now I know this sounds like crazy-talk but I don't want a procedurally generated model or a model using a UV-map.

The largest (metric) unit type in Maya is meters, so I have set this to meters and try to create the model at its actual size.

For starters I created a sphere of 2 units in diameter and set the scale to 4000. This results in me seeing nothing. When I try to frame the object I just get a gray screen and I am unable to edit it properly. I feel that my model might be getting a bit to big for the application.

What is the best approach for modelling such large environments. Should I scale it down, add smaller details and scale it up in Unity? How would I best go about this?

# Answer
For the sake of answering the question I have also put up a post in the (Maya forums) and they've come up with the following solutions.

**Option 1. Change camera settings**

Go to Settings \> Cameras and change the Near- and Far-clip plane of the camera to accommodate the model size. On thing to keep in account with this solution is that when creating large models floating point precision won't always allow to model to the detail level that might be preferred.

**Option 2. Scaling**

Scale down the model in maya for example 1:10 and then increase the scale of the model in Unity.
> 1 votes

---
Tags: unity, maya, 3d-modeling
---


title: Room lighting in Unity

text:
# Question
Title: Room lighting in Unity
I am trying to make a plain white room in Unity. I used six planes for the walls, but I can't figure out how to get the lighting to not look so harsh and uneven. The top picture is my best attempt using two directional lights, and the bottom picture is the look that I am trying to replicate. It is from a demo scene in the Google VR SDK 1.50 for Unity. It uses only a single point light, but when I turn it off in the scene view, it doesn't change the appearance of the room at all. How can I make my room look more like the Google VR demo?

EDIT: I made a big improvement by changing all my walls to be static so that they receive indirect lighting, and adding a single point light above the roof.

# Answer
You have two lights in your scene. One of them is probably the default Directional Light, which is causing your scene to look unevenly lit.

The demo scene only has a single Point Light at the top of the room.
> 2 votes

---
Tags: unity, lighting
---


# Question
Title: How can I cast a std::shared_ptr<Component> to the correct derived class?
I'm trying to implement a component based design for a game I'm making. I decided to write it in C++, but I'm not very good at it. Coming from a Java background I encountered a problem when trying to manage the `std::vector` for the components. Right now each entity has a vector of components that can be of different derived classes such as "Transform Component" which has an `x` and `y` field that I will access later. From what I've read I have to use a `std::shared_ptr` for each component, and that has worked fine except when I retrieve a component and try to cast it I start getting errors.

The code looks like this:

Component.hpp

```
class Component
{
public:
    virtual ComponentType getType() = 0;

    virtual ~Component() { }
};

```

Transfrom.hpp

```
class Transform : public Component
{
public:
    float x, y;

    virtual ComponentType getType() { return ComponentType::TRANSFORM; }
};

```

Entity.hpp

```
class Entity
{
public:
    Entity() : m_components() { }

    Component& getComponent(ComponentType type);
    void addComponent(std::shared_ptr<Component> comp);
    bool hasComponent(ComponentType type);

private:
    std::vector<std::shared_ptr<Component>> m_components;
};

```

And when I try to use it:

```
// This gives an error!
Transform comp = std::dynamic_pointer_cast<Transform>(entity.getComponent(ComponentType::TRANSFORM));

```

How can I fix this?

# Answer
> -1 votes
Your implementation is a bit off of the other Entity-Component systems I've seen. I recommend taking a look at EntityX. It should give a good idea of what a working implementation looks like.

You could also read these which may help:

Role of systems in entity systems architecture

Component - Game Programming Patterns

Understanding Component-Entity-Systems

As for some specific code critiques:

* Using templates to manage your component types, not an `enum`. This will make for cleaner code. I'd only use an `enum` (or any numerical type or string) if you were implementing scripting or any runtime-based component system, but that's a whole different issue. Templates just offer better type safety.
* Using `std::unique_ptr` instead of `std::shared_ptr`. If you're making copies of entites for whatever reason, you don't want them to share a pointer to the same component. If you're not copying them, you're wasting performance.
* Using an ID for an entity and a central system (that holds components tied to a specific ID) instead of `Entity` objects that hold the components themselves.

# Answer
> 0 votes
`std::dynamic_pointer_cast<Transform>` doesn't return a `Transform`, it returns a `std::shared_ptr<Transform>` so your cast should look something like:

```
std::shared_ptr<Transform> comp = std::dynamic_pointer_cast<Transform>(entity.getComponent(ComponentType::TRANSFORM));

```

Also, if the compiler can statically deduce the type of your r-value you could just use the auto keyword:

```
auto comp = std::dynamic_pointer_cast<Transform>(entity.getComponent(ComponentType::TRANSFORM));

```

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


# Question
Title: Is knowing Microsoft Office programs a plus for game producers or do they have to know them well?
I've been told that they should know them, but I've also been told that it's a plus.

# Answer
Yes, it is.

However, *how much* knowing Office matters, or what level of knowledge is considered "knowing," is going to depend very much on the specific company looking to fill a production role and even potentially on what that actual role will be doing a the studio.

If the role is at a studio that exclusively uses Office and related products and infrastructure for its production management pipeline, then knowing it at some level will likely be a requirement and knowing it in great depth will likely be a plus.

If the role is at a studio that exclusively uses Google Documents and related products and infrastructure for its production management pipeline, then knowing Office will probably not be a requirement, but might be a minor perk if you don't know anything about Google's systems because you could (presumably) use your knowledge of Office to make educated guesses about how Google's stuff worked.
> 2 votes

---
Tags: project-management, career
---


# Question
Title: How can I spawn only two objects, instead of spawning an infinite number of them?
I have a problem spawning a object twice throughout the game. This is my code:

```
alarm[0]event of Obj_game
randomize()
var wrongitems,righitems,xpos,ypos;

xpos = random_range(100,room_width-100);
ypos = -100

if irandom(50)=1
{
  wrongitems = instance_create(xpos, ypos, obj_stew)
  wrongitems.sprite_index= choose(
    sprCarrot,
    spr_bread,
    spr_apple,
    spr_aubergine,
    spr_cabbage,
    spr_cake,
    spr_orange,
    spr_banana,
  )
}
if irandom(50)=1
{
  wrongitems = instance_create(xpos, ypos, obj_stew)
  wrongitems.sprite_index= choose(
    spr_onion,
    spr_pepper,
    spr_oil,
    spr_beef,
    spr_salt,
    spr_tomatoes,
  )
}

```

This spawns the right items randomly an infinite number of times as long as nothing is happening but how can I make it spawn the right objects just 2 times each

# Answer
Thanks guys! A swell developer helped me out with this.

He approached the problem using ds lists to pick the sprites used for spawning the objects then using the for statement to specify how many times each sprite should be used in an object.

This is what he did.

```
wrongfruit = ds_list_create();
item_number = 5;
for(var i = 0; i < item_number; i++)
{
    ds_list_add(wrongfruit, sprCarrot);
    ds_list_add(wrongfruit, spr_bread);
    ds_list_add(wrongfruit, spr_apple);
    ds_list_add(wrongfruit, spr_aubergine);
    ds_list_add(wrongfruit, spr_cabbage);
    ds_list_add(wrongfruit, spr_cake);
    ds_list_add(wrongfruit, spr_orange);
    ds_list_add(wrongfruit, spr_banana);
}

```
> 0 votes

# Answer
***WARNING: REALLY BIG POST. THERE'S A LOT OF CODE HERE.***

Now if you are familiar a lot with the language C, this answer will make a lot of sense to you at the low level. Otherwise, do not worry about the exact functions. Some of them are fairly complicated.

Ok so basically going off of your self answer that isn't just a failed commenting attempt (whoops), I can see you want some kind of list data structure for your thingy. I should be quite clear at this point and clarify that sprites are the actual internal image files. So generating them isn't quite what you think. Spawning them doesn't really make sense as a good term either. So perhaps what you should say is that you want to randomly draw images around a room, but never use the same one more than so many times. Anyway, that's a minor rant on your terminology. At this point, it's probably irrelevant...

Now there are two built-in ways to make a linked list\* in game maker.

1. The built in "DS" functions.
2. Manually by using objects as nodes and a main linked list class (I'd suggest googling the architecture of a linked list in the Java language to understand what I mean)

Both of these attempts will fundamentally fail. Here is why.

In the documentation for data structures it states the following in the 4th paragraph:

> Please note that data structures and their content are not saved when you save the game using the actions or functions for that. If you use data structures and want to allow for saves you have to create your own mechanism for that.

Considering that I've taken quite a few computer science classes and used a lot of languages other than Game Maker, I can confidently say that avoiding to write a custom save mechanism is quite desirable if we can do it without compromising quality.

Regarding the use of object IDs being used to create complex linked pointer structures the issue can be summed up in the documentation on objects.

> Note that the assignment of the instances to the instance id's changes every step so you cannot use values from previous steps.

So you're basically dealing with shuffling memory locations, which is a pretty horrible setup, imo. I don't know of any other language with such a concept. It's laziness on part of the developers.

These all lead us to the only conclusion I can think of to resolve these issues:

Write a dynamic memory allocator within an array.

You only need the functions of malloc and free which will work within the context of an object. This basically means that data structures made with these will only exist in the context of a particular instance (as they reside within a local array). What follows below are the scripts I wrote to implement such an allocator. Be sure to put them each individually within a script with the name given in the header. These will all be supplementary and necessary only for the purpose of allocating the array indices used for the linked list.

---

**mm\_init**

```
HEAD_NODE = 0;
/*no need to align 0*/
HEAP_SPACE[HEAD_NODE] = 0;
LINKED_LIST_LENGTH = 0;
TAIL_NODE = HEAD_NODE;
return 0;

```

---

**mm\_malloc**

```
newsize = argument[0] + (argument[0] mod 2);
freeP = HEAD_NODE;

if (mm_getLength(freeP) - newsize > 0 && !mm_getFree(freeP))
{
    mm_setFree(freeP,true);
    mm_insert(freeP, newsize);
    return freeP + 1;
}
while (mm_getNext(freeP) < TAIL_NODE)
{
    freeP=mm_getNext(freeP);
    if (mm_getLength(freeP) - newsize > 0 && !mm_getFree(freeP))
    {
        mm_setFree(freeP,true);
        mm_insert(freeP, newsize);
        return freeP + 1;
    }
}

p = TAIL_NODE; /*add to the heap and return the starting position*/
//p = mem_sbrk(newsize + 8); /*add to the heap and return the starting position*/
if (p == -1)
{
    return NULL;
} else
{
    HEAP_SPACE[p] = (newsize) + (1 << 31);
    HEAP_SPACE[mm_getNext(p) - 1] = newsize;
    if (LINKED_LIST_LENGTH == 0)
    {
        HEAD_NODE = p;
    }
    TAIL_NODE = mm_getNext(p);
    LINKED_LIST_LENGTH += 1;
    return (p + 1);
}

```

---

**mm\_free**

```
/* adjust so that ptr points
 * to the node for this block
 */
p = argument[0] - 1;
HEAP_SPACE[p] = mm_getLength(p);

/*did the pointer originate from the heap*/
if (p > HEAD_NODE && p < TAIL_NODE)
{
    if (!mm_getFree(mm_getPrevious(p)))
    {
        /* the previous node
         * can be coalesced
         */
        mm_removeNode(p);
        p = mm_getPrevious(p);
    }

    if (!mm_getFree(mm_getNext(p)) && mm_getNext(p) <= TAIL_NODE)
    {
        /* the next node
         * can be coalesced
         */
        if (mm_getNext(p) == TAIL_NODE)
        {
            TAIL_NODE = p;
        }
        mm_removeNode(mm_getNext(p));
    }
}

```

---

**mm\_getNext**

```
return (argument[0] + mm_getLength(argument[0]) + 2);

```

---

**mm\_getPrevious**

```
return (argument[0] - mm_getLength(argument[0]-1) - 2);

```

---

**mm\_getLength**

```
/*zero out the leftmost bit, reserved for the free value*/
return HEAP_SPACE[argument[0]] & (~(1 << 31));

```

---

**mm\_getFree**

```
return ((HEAP_SPACE[argument[0]] & (1 << 31)) > 0);

```

---

**mm\_setLength**

```
HEAP_SPACE[argument[0]] = argument[1] + (mm_getFree(argument[0]) << 31);
HEAP_SPACE[mm_getNext(argument[0]) - 1] = argument[1];

```

---

**mm\_setFree**

```
HEAP_SPACE[argument[0]] = mm_getLength(argument[0]) + (argument[1] << 31);

```

---

**mm\_removeNode**

```
mm_setLength(mm_getPrevious(argument[0]),mm_getLength(mm_getPrevious(argument[0]))+mm_getLength(argument[0])+2);
LINKED_LIST_LENGTH -= 1;
/*length is in terms of integer words*/

```

---

**mm\_insert**

```
/* the node has to fit to avoid distorting
 * the linked list's heap property
 */
if (argument[1] + 2 < mm_getLength(argument[0]))
{
    node = argument[0] + argument[1] + 2;
    /*ensure the free field is 0*/
    HEAP_SPACE[node] = 0;
    mm_setLength(node,mm_getLength(argument[0])-argument[1]-2);
    mm_setLength(argument[0],argument[1]);
} else
{
    /* all blocks and nodes are 2 byte aligned, so a difference of one
     * would only exist in the case of a system flaw
     */
    HEAP_SPACE[argument[0]] = mm_getLength(argument[0]) + (1 << 31);
}

```

---

That is all of the functions and little utility scripts needed to implement malloc and free. If you understand the wikipedia article I linked or have used malloc and free then you will be able to use them to allocate memory for structs which are basically objects but with nothing but data and no events or methods attached. Note that this is technically a slapped on interface we are just honoring to give the illusion of allocation. Game Maker is oblivious and just presumes this to be array manipulation. The mm\_init script at the beginning basically resets the heap space which is the name conventionally used to describe a region wherein memory is allocated in this manner or something similar. Be sure to call it before allocating or weird things will happen. In fact, call it before any of the scripts I list here are called. Just call it in the creation event of your stew manager thingy mentioned in the question.

Anyways, to build a linked list we need node structs. Here are the scripts used to define generic nodes. These are a sub-object used to build larger things, but basically you can give them a script that will act as a manner of deleting whatever is held within the list, tree, or what-have-you that the nodes are building. You're holding integers AKA sprite indexes so don't worry about it. It will only be useful for more advanced things (better to put it in and not use it then to not put it in and get a memory leak later).

Same principle as before applies:

---

**node\_createNode**

```
argument[0] = mm_malloc(4);
node_setData(argument[0],-1);
node_setNext(argument[0],-1);
node_setPrevious(argument[0],-1);
node_setDataDestructor(argument[0],node_byteDataDestructor);
return argument[0];

```

---

**node\_setData**

```
HEAP_SPACE[argument[0]] = argument[1];

```

---

**node\_setNext**

```
HEAP_SPACE[argument[0]+1] = argument[1];

```

---

**node\_setPrevious**

```
HEAP_SPACE[argument[0]+2] = argument[1];

```

---

**node\_setDataDeconstructor**

```
HEAP_SPACE[argument[0]+3] = argument[1];

```

---

**node\_getData**

```
return HEAP_SPACE[argument[0]];

```

---

**node\_getNext**

```
return HEAP_SPACE[argument[0]+1];

```

---

**node\_getPrevious**

```
return HEAP_SPACE[argument[0]+2];

```

---

**node\_getDataDeconstructor**

```
return HEAP_SPACE[argument[0]+3];

```

---

**node\_deleteNode**

```
script_execute(node_getDataDestructor(argument[0]),node_getData(argument[0]));
mm_free(argument[0]);

```

---

**node\_byteDataDestructor**

```
/*this script intentionally left empty as a destructor for built-in numerical data types*/

```

---

So you have nodes and an allocator. The actual linked list will take a while to write as I haven't actually written it yet. These are all scripts I have in my personal library and have no problem sharing. The linked list coincidentally needs to be written for some stuff of my own anyways. When it is finished I will edit this post with the other scripts and the rewritten version of that segment you had in your self-written answer.

**Technically not a complete answer at this time. I still have to write the linked list functions as well, but this is a start. I should have the rest done very soon (it's not trivial to write and I have a lot to get done).**

---

\*You don't want me to try writing a true arrayList like in Java. I honestly suck at writing that version. We'd be here a while... as in more than a week. Linked lists can also be more efficient at removal. The difference is marginal for you since the list is so tiny.
> -1 votes

---
Tags: game-maker
---


# Question
Title: Trying to make a button in Unity which spawns a character each time it's clicked
I have a simple 2D game, I want a UI button to respawn the character (if it's not already present). The first problem I encountered is that the button only works once. I can't go any further before I solve this, so for now it doesn't spawn anything, I just want it to print debug text every time it's clicked. It only does that once, unfortunately. How do I make it call the function each time I click it?

```
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;

public class Button_Restart : MonoBehaviour
{
    public Canvas Canvas;

    void Awake()
    {

    }

    public void Restart()
    {
        Debug.Log("Restart button was clicked");
        EventSystem.current.SetSelectedGameObject(null);
    }
}

```

# Answer
> 1 votes
Ok I was silly and didn't notice that the console was set to group debug messages together. It is in fact working as intended.

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


# Question
Title: How can I create new Minecraft items in a Spigot plugin?
Is it possible to make a new custom item in a plugin so that in-hand 3D models and textures don't interfere with vanilla Minecraft items? How?

# Answer
No, the Minecraft client-server protocol doesn't support such things,

However, there's a workaround. You can assign different models to different damage values of objects. By using something, that normally can't get damaged (like for example a book) you can technically have new items. The same can't be done with blocks.
> 1 votes

---
Tags: minecraft-modding
---


# Question
Title: How to make compound data in Game Maker?
In other languages, such as Lisp, there is such a thing as "compound data", where several variables are grouped together.

For example, if I want to represent an orbital that rotate around the player without creating a new object, I may use something like this:

```
(define (Orbital rx ry colour))
;; creating a new data type called "Orbital", with 3 var.s

(define ORB1 (make-Orbital 30 -20 "red"))
;; creating a particular orbital at (30, -20) with red as colour,
;; stored under the name "ORB1"

```

Is there a similar mechanism in Game Maker (made in Delphi) that permits such grouping of information under a structure which itself can be considered a single item, and thus such things to be stored in lists?

# Answer
> 3 votes
Because I don't have enough reputation to comment, I'm submitting an answer that further clarifies the previous answer regarding ds\_map.

Here's an example of ds\_map in action:

```
globalvar player;
player = ds_map_create();
ds_map_add( player, "acceleration", 1.0 );
ds_map_add( player, "maxspeed", 5.0 );
ds_map_add( player, "deceleration", 0.5 );
ds_map_add( player, "subBeatFirePoints", "0.5" );

```

This snippet is from an initialization script in a game I'm working on. It creates a global variable named player, which I reference in other scripts (e.g. in my player object's control script).

ds\_map lets you work with key-value pairs. In this case, an example of a key-value pair in my player variable is { "acceleration", 1.0 }.

As you see above, ds\_map\_create() creates the DS map and the ds\_map\_add function adds the key-value pairs.

For your example, you'd probably do something like this:

```
globalvar orbital;
orbital = ds_map_create();
ds_map_add( orbital, "rx", 30 );
ds_map_add( orbital, "ry", -20 );
ds_map_add( orbital, "colour", "red" );

```

# Answer
> 2 votes
GMS doesn't implement compound data natively. By the way, you can use DS Maps as a handy alternative, in which you can store values and retrieve them by keys. It's an actual dictionary data structure, and you can even convert it in JSON format and vice versa. Hope that helps.

# Answer
> 2 votes
If you read up on objects you'll see that references to them (aka instance id's) are shuffled every frame. So those won't cut it. Data structures are flushed from memory when you load a save file using the default mechanism. I only know of one other option:

***C-style Dynamic Memory Allocation Within an Array***

If you are not familiar with structs and whatnot, I would suggest reading up on the concepts. In general, they are little bitty tiny arrays, like your compound data types. In fact, they're probably synonymous, but since I haven't used that language I cannot say for sure. Here are the functions I used to implement malloc and free along with an initialization function used to set up and reset a local heap space. It is local to each game maker object. If you want a global version, just change the array variable to global or make an object with it in it. I personally prefer the local version.

---

**mm\_init**

```
HEAD_NODE = 0;
/*no need to align 0*/
HEAP_SPACE[HEAD_NODE] = 0;
LINKED_LIST_LENGTH = 0;
TAIL_NODE = HEAD_NODE;
return 0;

```

---

**mm\_malloc**

```
newsize = argument[0] + (argument[0] mod 2);
freeP = HEAD_NODE;

if (mm_getLength(freeP) - newsize > 0 && !mm_getFree(freeP))
{
    mm_setFree(freeP,true);
    mm_insert(freeP, newsize);
    return freeP + 1;
}
while (mm_getNext(freeP) < TAIL_NODE)
{
    freeP=mm_getNext(freeP);
    if (mm_getLength(freeP) - newsize > 0 && !mm_getFree(freeP))
    {
        mm_setFree(freeP,true);
        mm_insert(freeP, newsize);
        return freeP + 1;
    }
}

p = TAIL_NODE; /*add to the heap and return the starting position*/
//p = mem_sbrk(newsize + 8); /*add to the heap and return the starting position*/
if (p == -1)
{
    return NULL;
} else
{
    HEAP_SPACE[p] = (newsize) + (1 << 31);
    HEAP_SPACE[mm_getNext(p) - 1] = newsize;
    if (LINKED_LIST_LENGTH == 0)
    {
        HEAD_NODE = p;
    }
    TAIL_NODE = mm_getNext(p);
    LINKED_LIST_LENGTH += 1;
    return (p + 1);
}

```

---

**mm\_free**

```
/* adjust so that ptr points
 * to the node for this block
 */
p = argument[0] - 1;
HEAP_SPACE[p] = mm_getLength(p);

/*did the pointer originate from the heap*/
if (p > HEAD_NODE && p < TAIL_NODE)
{
    if (!mm_getFree(mm_getPrevious(p)))
    {
        /* the previous node
         * can be coalesced
         */
        mm_removeNode(p);
        p = mm_getPrevious(p);
    }

    if (!mm_getFree(mm_getNext(p)) && mm_getNext(p) <= TAIL_NODE)
    {
        /* the next node
         * can be coalesced
         */
        if (mm_getNext(p) == TAIL_NODE)
        {
            TAIL_NODE = p;
        }
        mm_removeNode(mm_getNext(p));
    }
}

```

---

**mm\_getNext**

```
return (argument[0] + mm_getLength(argument[0]) + 2);

```

---

**mm\_getPrevious**

```
return (argument[0] - mm_getLength(argument[0]-1) - 2);

```

---

**mm\_getLength**

```
/*zero out the leftmost bit, reserved for the free value*/
return HEAP_SPACE[argument[0]] & (~(1 << 31));

```

---

**mm\_getFree**

```
return ((HEAP_SPACE[argument[0]] & (1 << 31)) > 0);

```

---

**mm\_setLength**

```
HEAP_SPACE[argument[0]] = argument[1] + (mm_getFree(argument[0]) << 31);
HEAP_SPACE[mm_getNext(argument[0]) - 1] = argument[1];

```

---

**mm\_setFree**

```
HEAP_SPACE[argument[0]] = mm_getLength(argument[0]) + (argument[1] << 31);

```

---

**mm\_removeNode**

```
mm_setLength(mm_getPrevious(argument[0]),mm_getLength(mm_getPrevious(argument[0]))+mm_getLength(argument[0])+2);
LINKED_LIST_LENGTH -= 1;
/*length is in terms of integer words*/

```

---

**mm\_insert**

```
/* the node has to fit to avoid distorting
 * the linked list's heap property
 */
if (argument[1] + 2 < mm_getLength(argument[0]))
{
    node = argument[0] + argument[1] + 2;
    /*ensure the free field is 0*/
    HEAP_SPACE[node] = 0;
    mm_setLength(node,mm_getLength(argument[0])-argument[1]-2);
    mm_setLength(argument[0],argument[1]);
} else
{
    /* all blocks and nodes are 2 byte aligned, so a difference of one
     * would only exist in the case of a system flaw
     */
    HEAP_SPACE[argument[0]] = mm_getLength(argument[0]) + (1 << 31);
}

```

---

Since I don't know exactly what kind of structs you want to make, I cannot help you by making them for you or showing an example. Lists and stuff are best done using linked lists constructed with node sub-classes. so I would suggest reading up on the stuff and making a node class. I have a few data structures I've written so if there is one in particular you need, I can help you by providing it if I have it. Either that or I can help you write your own.

---
Tags: game-maker, data-structure
---