title: Rendering Smooth Text in Libgdx

text:
# Question
Title: Rendering Smooth Text in Libgdx
I am trying to draw text onto the screen but it always ends up being pixelated no matter what I try. A lot of people say that adding the Linear TextureFilter works or offer other solutions but they don't really work for me. This is what I have now (I'm also using a ttf font):

```
public BitmapFont generateFont(String path, double size)
{
    FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal(path));
    FreeTypeFontGenerator.FreeTypeFontParameter parameters = new FreeTypeFontGenerator.FreeTypeFontParameter();

    parameters.genMipMaps = true;
    parameters.color = Color.BLACK;
    parameters.size = (int) Math.ceil(size);
    parameters.magFilter = TextureFilter.Linear;
    parameters.minFilter = TextureFilter.Linear;
    generator.scaleForPixelHeight((int) size);

    return generator.generateFont(parameters);
}

```

I've also changed the parameter size to `(int) Math.ceil(2 * Gdx.graphics.getWidth() / 9);` and while that makes things a little bit smoother, it's nowhere near as crisp as some other texts are.

I'm wondering what I need to do in order to get smooth text along with how I can maintain that smoothness in different text sizes across different resolutions (I'm only targeting desktop right now since I'm really just messing around with Libgdx). It just seems like there are several different ways of doing this but I just want to know what's the best way to go about doing this.

# Answer
This is the only solution for `LibGDX`:

https://libgdx.com/wiki/graphics/2d/fonts/distance-field-fonts

Once you get through all the possibilities of rendering huge text smoothly, you'll end up in this link.

Keep in mind that when you write a game, you have to think of all possible phone/tablet resolutions so you'll need to render a much bigger text on a tablet.

I had a great time with Distance Field Fonts. Here you can find a free generator:

https://evanw.github.io/font-texture-generator/
> 0 votes

# Answer
After doing some testing it seems the problem is caused by a large font size and a large viewport size. Luckily this is easily fixed by following these simple steps:

1. Reduce `Font` size by half.
2. Reduce `Viewport` size by half.
3. Make sure the font `minFilter` is `MipMapLinearNearest` and the `magFilter` is `Linear`.
4. If this doesn't work go to step 1.

(In your case though I think the font size is just fine so I would suggest *just* reducing viewport size at first. If that doesn't work follow the steps above.)

To be clear try reducing your font size to `32` and your viewport size to `(500, 500 * aspectRatio)`, then if that doesn't work try `16` and `(250, 250 * aspectRatio)`.

This method does require you to use a separate viewport to render text with unless you want to change the viewport size of your actual game as well, so just create a new viewport of any type and make sure to apply it before rendering text:

```
gameViewport.apply();
batch.setProjectionMatrix(gameViewport.getCamera().combined);
batch.begin();
// Draw game stuff

textViewport.apply(true); // Center camera
batch.setProjectionMatrix(textViewport.getCamera().combined);
// Draw text
batch.end();

```

For me this produces quite satisfactory results
> 0 votes

---
Tags: java, libgdx
---


# Question
Title: How detect collision between two bodies?
I'm using LibGDX with Box2D and I've two bodies. I just need to know that they have collided.

So, I just need a boolean output.

Example:

```
if (bodyA.collision(bodyB) == true) {
   // Do something
}

```

How can I do this?

If it is too complicated, can I detect if two PolygonShape intersect?

# Answer
> 3 votes
## Answer

What you are looking for is called a *Collision Callback*. There is a great tutorial written by iforce2d on the topic, so I'll just give the key details here.

The strategy in Box2d is to subclass the `ContactListener` class and define the appropriate methods. For example, you could create a subclass called `MyContactListener`, you would define the method `MyContactListener:beginContact`. Then, in your initialization, assign an instance of your `MyContactListener` class to your `b2World` using the function `b2World:setContactListener`. Once this is set up, the code inside your `beginContact` function will be called each and every time two bodies collide! (provided you do not have any contact filters set up)

In the `beginContact` function, you are given access to the `contact` object, from which you can query the `fixture`s involved in the collision, and subsequently the `body`s involved.

## General Advice

I see from the way you phrased your question that you want your code to poll the game state to see if you should do something. This is generally considered poor practice, and this particular example is a great way to start changing your thinking!

What `box2d` is doing, and what you should strive to do as well, is to create triggers/events/callbacks so that when something interesting happens (e.g. a collision) the game will change what it needs to right then and there. It's the difference between the kids in the back seat asking 23,139 times: "Are we there yet?" and patiently waiting for their parent to say "We've arrived!" just 1 time.

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


title: UI gameover score

text:
# Question
Title: UI gameover score
I have gameover canvas and i like in gameover canvas to show finaly distance i make with PlayerPrefs but doesnt work because is on same scene what can i do for this problem.

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

public class Score : MonoBehaviour
{
    public float Distance = 0.0f;
    private int difficultyLevel = 1;
    private int maxDifficultyLevel = 20;
    private int scoreToNextLevel = 20;
    public Text distanceText;
    public carSpawner spawn;
    public carController car;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update ()
    {
        if (Distance >= scoreToNextLevel)
            LevelUp();

        Distance += Time.deltaTime * difficultyLevel;
    }

    void LevelUp()
    {
        if (difficultyLevel == maxDifficultyLevel)
            return;

        scoreToNextLevel *= 2;
        difficultyLevel++;

        spawn.delayTimer -= 0.1f;
        car.carSpeed += 1;
        Debug.Log(difficultyLevel);
    }
}

```

---

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

public class iuManager : MonoBehaviour {

    public AudioManager au;
    public Score score;
    public Button[] buttons;
    public carController car;
    public bool gameOver;
    public Canvas GameoverCanvas;
    public GameObject resumee;
    public GameObject res;
    public GameObject l;
    public GameObject easy;
    public GameObject medium;
    public GameObject hard;
    public GameObject back;
    public GameObject backk;
    public GameObject Shop;

    // Return the app's public key.
    public string AndroidPublicKey
    {
        // In a real app, return public key instead of null.
        get { return null; }
    }

    // Use this for initialization
    void Start () {

        gameOver = false;
        GameoverCanvas.enabled = false;
    }

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

        if (gameOver == false)
        {
            score.distanceText.text = string.Format("Distance : {0}Km", (int)score.Distance);
        }
    }

    public void gameOverActivated(){
        gameOver = true;
        GameoverCanvas.enabled = true;
    }

    public void play (){
        SceneManager.LoadScene("level1");

    }

    public void Pause (){
        if (Time.timeScale == 1) {
            Time.timeScale = 0;
            foreach (Button button in buttons) {
                button.gameObject.SetActive (true);
                res.SetActive (false);
                resumee.SetActive (true);
                Shop.SetActive(true);
                back.SetActive (false);
            }
            au.carSound1.Pause();
            au.carSound2.Pause ();
        }
    }

    public void UnPause(){
        if (Time.timeScale == 0) {
            Time.timeScale = 1;
            foreach (Button button in buttons) {
                button.gameObject.SetActive (false);
                res.SetActive (true);
                resumee.SetActive (false);
                Shop.SetActive(false);
                back.SetActive (false);
            }
            au.carSound1.UnPause();
            au.carSound2.UnPause ();
        }
    }

    public void Replay(){
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
        if (Time.timeScale == 0) {
            Time.timeScale = 1;
        }
    }

    public void Menu(){
        SceneManager.LoadScene("menuScene");
        if (Time.timeScale == 0) {
            Time.timeScale = 1;
        }
    }

    public void Exit(){
        Application.Quit ();
    }

    public void Levels(){

        foreach (Button button in buttons) {
            button.gameObject.SetActive (false);
            resumee.SetActive (false);
            res.SetActive (false);
        }

        easy.SetActive (true);
        medium.SetActive (true);
        hard.SetActive (true);
        back.SetActive (true);
    }

    public void LevelsMenu(){

        foreach (Button button in buttons) {
            button.gameObject.SetActive (false);
        }

        easy.SetActive (true);
        medium.SetActive (true);
        hard.SetActive (true);
        backk.SetActive (true);
    }

    public void Back(){
        foreach (Button button in buttons) {
            button.gameObject.SetActive (true);
            resumee.SetActive (true);
            res.SetActive (false);
        }

        easy.SetActive (false);
        medium.SetActive (false);
        hard.SetActive (false);
        back.SetActive (false);
    }

    public void BackMenu(){

        foreach (Button button in buttons) {
            button.gameObject.SetActive (true);
        }

        easy.SetActive (false);
        medium.SetActive (false);
        hard.SetActive (false);
        backk.SetActive (false);
    }

    public void LevelEasy(){
        SceneManager.LoadScene("level1");
        if (Time.timeScale == 0) {
            Time.timeScale = 1;
        }
    }

    public void LevelMedium(){
        SceneManager.LoadScene("level2");
        if (Time.timeScale == 0) {
            Time.timeScale = 1;
        }
    }

    public void LevelHard(){
        SceneManager.LoadScene("level3");
        if (Time.timeScale == 0) {
            Time.timeScale = 1;
        }
    }

}

```

# Answer
Introduce these fields:

```
public Score _score;
public Text _gameOverCanvasDistanceText;

```

Then edit your `gameOverActivated` method like this:

```
public void gameOverActivated()
{
    gameOver = true;
    _gameOverCanvasDistanceText.text = _score.Distance.ToString();
    GameoverCanvas.enabled = true;
}

```

You also need to assign these newly introduced fields in the inspector.

---

**Offtopic:** I suggest you take a look at .Net naming conventions.
> 0 votes

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


# Question
Title: Perlin noise always produces the same map. How do I generate a different map?
My tile map takes a spritesheet, slices the tiles up based on a resolution, and assigns each tile to an array, which uses an integer. Since perlin noise generates a float between 0 and 1, I multiply the float by the number of tiles I want to use for terrain generation, round (perlin\*tileNum) to a whole number, and then use the whole number integer as the number for the color of the tile.

The code I have to make terrain *works*, but I noticed that no matter the number that `scale` is, it basically generates the same terrain, and just stretches it based off of `scale` to fit the tile map. They essentially are all the same terrain, which is what I don't want.

Here are pictures of what's happening, as well as a pastebin of my tile map engine. I apologize if my wording of the problem is difficult to understand.

What would I need to do to make each generated landscape different? I know I need to reevaluate the Perlin Noise aspect, but I don't know exactly what to fix.

# Answer
> 1 votes
All you need to do is add an offset to your noise lookups.

Effectively, treat (0, 0) like it's (123.4, 987.6) or some other arbitrary shift.

This centers a different part of the noise domain and you'll get different results.

If using multiple octaves of noise, you can even play with different offsets per octave to mix it up further, so it's no longer a simple translation of the whole noise domain.

---
Tags: unity, c#, 2d, tilemap, perlin-noise
---


# Question
Title: Breaking up List into sublists by multiple values
I'm trying to break up a C# `List<InventoryItem>` into multiple lists based on two different values: `InventoryItem.name` and `InventoryItem.isStackable`.

I want the list to be broken up into multiple lists for the purpose of populating my UI with the data - while keeping non-stackable items in their own list (one item per item slot in UI terms.)

If this is the input:

```
{
   InventoryItem - name:apple,  stackable:true
   InventoryItem - name:apple,  stackable:true
   InventoryItem - name:carrot, stackable:true
   InventoryItem - name:knife,  stackable:false
   InventoryItem - name:knife,  stackable:false
 }

```

I should get this output:

```
{
   InventoryItem - name:apple, stackable:true
   InventoryItem - name:apple, stackable:true
 }
 {
   InventoryItem - name:carrot, stackable:true
 }
 {
   InventoryItem - name:knife, stackable:false
 }
 {
   InventoryItem - name:knife, stackable:false
 }

```

I'm successfully separating by name alone (see below), but I'm not sure how to take isStackable into account. I'm also using LINQ which I'd prefer to avoid if possible.

```
var itemsByType     = new List<List<InventoryItem>>();
var inventoryByItem = inventory.GroupBy(x => x.name);
foreach(var v in inventoryByItem)
{
    var itemList = v.ToList();
    itemsByType.Add(itemList);
}

```

# Answer
> 1 votes
I think a better aproach would be to store the quantity of an item, instead of storing the stackable itens repeatdly in a list. Because when we are talking about large amounts of stacking items, it wouldn't work;

```
using UnityEngine;
using System.Collections.Generic;
public class StackExchange : MonoBehaviour
{
    List<InventItem> rawInventory;
    List<InventSlot> groupedInventory;

    void Start () {
        rawInventory = new List<InventItem>();
        rawInventory.Add(new InventItem("apple" , true));
        rawInventory.Add(new InventItem("apple", true));
        rawInventory.Add(new InventItem("carrot", true));
        rawInventory.Add(new InventItem("knife", false));
        rawInventory.Add(new InventItem("knife", false));
        rawInventory.Add(new InventItem("knife", false));

        groupedInventory = new List<InventSlot>();
        foreach (InventItem i in rawInventory){
            proccessItem(i);
        }

        Debug.Log(getPrintableList(rawInventory));
        string s = "Grouped list:\n";
        foreach (InventSlot slot in groupedInventory){
            s += "{\n";
            for (int i = 0; i < slot.quantity; i++)
                s += slot.item.output();
            s += "}\n";
        }
        Debug.Log(s);
    }

    string getPrintableList (List<InventItem> list){
        string output = "{\n";
        foreach (var v in list){
            output += v.output() ;
        }
        output += "}\n";
        return output;
    }

    void proccessItem (InventItem item){
        foreach (var inventSlot in groupedInventory)
            if (inventSlot.item.name == item.name && inventSlot.item.isStackable){
                inventSlot.quantity++;
                return;
            }
        groupedInventory.Add ( new InventSlot (item));
    }

 }

class InventSlot{
    public InventItem item;
    public int quantity;
    public InventSlot (InventItem item){
        this.item = item;
        quantity = 1;
    }
}

class InventItem
{
    public string name;
    public bool isStackable;

    public InventItem (string name , bool isStackable){
        this.name = name;
        this.isStackable = isStackable;
    }

    public string output (){
        return "\tInventoryItem - name:" + name + ", stackable:" + isStackable + "\n";
    }
}

```

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


# Question
Title: Can I create realtime textures with text?
I have a large number of items in my game, that will eventually have a texture associated with them. The problem is, for right now, I have nothing. I would really like to do something with, say, the first 2 letters of the object's name. As my main system will be pure textures, I really don't want to add a text object to the texture, I would really like to just create a texture with the object's first two letters.

Is there a way I can create a texture, realtime, with font rendered on that texture? Preferably without a camera/ render texture, unless I can create them once. I really want to create a unique default texture for each item at runtime, preferably with some kind of font. Can I do this?

# Answer
## **EDIT**

You could find too many approaches for solve your texturing problem, below I’ll share to you two of my favorites solutions based on some prototypes I’ve been working this week.

## **SCRIPT FOR CHANGE MATERIAL TEXTURES**

This is relative easy and straightforward solution; the idea is to create as many textures as needed and then use a script for assign/change those textures in your materials. For further reading in this approach you could start browsing in google:

> Unity script change texture; Material.SetTexture

## **CREATE YOUR CUSTOM FONT BITMAP READER USING SHADERS**

Although this approach could not be as easy as the last is truly generating a “dynamic texture” using a different **render target** in a secondary camera and drawing the generated **render texture** to a plane that is viewing the primary camera. The steps for implement this approach are described below.

> Bold fonts are keywords for search in google (e.g. Unity render target)

**1. Create your bitmap font**

You could create your own bitmap font in software like photoshop.

The previous image has a width and height equal to 512px, so every letter is into an area box of (512/3)\**2.

You also must assign an index for each word in the bitmap (e.g: A has index 0, B has index 1, and so on…).

**2. Setup your Scene**

In the image, you can see how the space being renderer for the **BufferCamera** is projected as texture into the **Plane** (that is viewing the **Main Camera**) If you want more than one word in your texture **Plane** is necessary to create another **BufferCamera** and another **BufferPlane** and project its content to the same **Plane**, then you must create a custom shader that receives the two rendered textures as minimum and play with the scale and offset values.

> Bold fonts are **gameobjects** in the current scene

**3. Create your bitmap font reader shader**

The **BufferPlane** shader is the shader that read from your bitmap font, below I’ll paste for you a first functional prototype I built for that shader while experimenting on your problem last night.

This is probably the hardest part of this solution proposal, the idea here is to draw only parts of your bitmap font texture (those parts associated with and index letter).

```
Shader "Custom/FontbitmapReader" {
Properties {
    _MainTex ("Albedo (RGB)", 2D) = "white" {}
    _Index ("Text index for draw", Range(0, 8)) = 0.0
}
SubShader {
    Tags {
        "RenderType"="Opaque"
    }
    LOD 200

    CGPROGRAM
    #pragma surface surf FontBitMap

    // Use shader model 3.0 target, to get nicer looking lighting
    #pragma target 3.0

    #pragma debug

    sampler2D _MainTex;

    struct Input {
        float2 uv_MainTex;
    };

    int _Index;

    float4 LightingFontBitMap(SurfaceOutput s, float3 lightDir, float atten)
    {
        return float4(s.Albedo, 1.0) * s.Alpha;
    }

    void surf (Input IN, inout SurfaceOutput o)
    {
        /*
            G = 0   H = 1   I = 2
            D = 3   E = 4   F = 5
            A = 6   B = 7   C = 8
        */

        float i = _Index;
        float4 texel = 0;
        float2 uv = IN.uv_MainTex;

        // 1.0 / 3.0 = 0.3
        float uvScale = 1.0 / 3.0;
        float2 uvOffset = float2(fmod(i, 3.0) / 3.0,
                                floor(i / 3.0) / 3.0);
        float2 transformedUV = IN.uv_MainTex * uvScale + uvOffset;
        texel = tex2D(_MainTex, transformedUV);

        o.Albedo = texel.rgb;
        o.Alpha = texel.a;
    }
    ENDCG
}
FallBack "Diffuse"
}

```

**4. Create a script for modyfing your shader material**

This script must input two things:

1. The material to which you attached your custom shader
2. The letters you want to draw

You could use a switch to associate each typed letter with a bitmap font index and then pass that index to your shader material.
> 2 votes

---
Tags: unity, textures, fonts
---


# Question
Title: Unity2d: orthographic camera and z-axis?
I wonder if anyone can help with an explanation of the z-axis and using unity with 2D with an orthographic camera.

Up until now i have only been modifying the x and y values of game objects, thinking this is the correct way. i thought the Z axis didn't exist in 2D space (i.e. unity 2d with orthographic camera) but I do notice that the orthographic camera is placed at -10 on the z axis, if i change this value then the camera disappears. I sort of began to accept that.

Now I cam to a point where I wanted to rotate something, and I notice that rotating eithe on the z or x axis, doesn't seem to do anything, only on the z-axis, there is that z-axis again !

Can anyone tell me when i should be worrying about the z axis in unity using 2D games.

It seems now that it is more important than I once thought :-)

Thanks in advance.

# Answer
> 3 votes
Here are some important points about Z axis in 2D mode:

* An object needs to be in a camera's view frustum in order for the camera to render it. So, if your object is at `-10` Z position and your camera is at `0` Z position, your camera can't render the object properly.
* For 3D objects, Z position determines the visual draw order. Let's say you have 2 3D objects: A and B. If A has a Z value greater than B, that means B will be drawn in front of A.
* For sprites, however, this is not the case. The draw order of sprites is determined by two settings named "Sorting Layer" and "Order in Layer" which can be found under the Sprite Renderer component. The Z position has no effect in visual draw order of sprites.
* 2D physics' collision-resolving ignores the Z coordinate. See the gif:

---
Tags: unity, 2d, rotation
---


# Question
Title: Why does duplicating my object cause its vertex animation shader to distort it?
I used a vertex shader (based on this example) to animate a flag waving. When I have a single flag in my scene, it works correctly.

When I duplicate the flag, all of the copies become wildly distorted after I hit play.

Here is the shader code I'm using:

```
Shader "Custom/Flag" {
    Properties {
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _Speed ("Speed", Range(0, 5.0)) = 1
        _Frequency ("Frequency", Range(0, 1.3)) = 1
        _Amplitude ("Amplitude", Range(0, 5.0)) = 1
    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        Cull off

        Pass {

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            sampler2D _MainTex;
            float4 _MainTex_ST;

            struct v2f {
                float4 pos : SV_POSITION;
                float2 uv : TEXCOORD0;
            };

            float _Speed;
            float _Frequency;
            float _Amplitude;

            v2f vert(appdata_base v)
            {
                v2f o;
                v.vertex.y +=  cos((v.vertex.x + _Time.y * _Speed) * _Frequency) * _Amplitude * (v.vertex.x - 5);
                o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
                o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
                return o;
            }

            fixed4 frag(v2f i) : SV_Target
            {
                return tex2D(_MainTex, i.uv);
            }

            ENDCG

        }
    }
    FallBack "Diffuse"
}

```

How can I make this work with multiple flags using the same material?

Should I use a new material instance for each object like this? It doesn't seem optimal:

```
    material = new Material (Shader); // Create new material
    material.SetFloat ("_Speed", _Speed);
    material.SetFloat ("_Frequency", _Frequency);
    material.SetFloat ("_Amplitude", _Amplitude);
    material.SetTexture ("_MainTex", _MainTex);
    flagObj.GetComponent<MeshRenderer>().sharedMaterial = material; // Set values

```

# Answer
> 9 votes
This is Unity's automatic batching systems at work.

In order to save you draw calls, when Unity sees multiple (small) models using the same material, it combines them into a single mesh so it can render them all together.

To retain each model's individual transformation (translation/rotation/scale) in space, the transforms are baked into the vertex positions in a single shared coordinate system for the whole batch, which might differ greatly from the model's original local coordinate system.

This is usually safe for most materials, since we usually don't care about where our geometry is in local space, only its resulting position in the camera view / orientation to light sources.

But it can wreak havoc with vertex shaders that make assumptions about how the vertices are laid out in the model's local coordinate system — like vertex animations that displace vertices in local space, or scale their intensity based on local position.

A quick fix for these shaders is to add the tag `"DisableBatching"="True"` to the ShaderLab tags at the top of the subshader. This tells Unity that this material is not safe to batch, and it will go back to rendering each model individually with its original coordinate system, at some draw call cost.

If you want to render a lot of these models and still get the benefit of batching, you can modify some shaders to use other sources of information here (eg. using the vertex normal as a displacement direction rather than assuming it points along a particular local axis, or using UV coordinates to scale and offset the effect rather than local position). If you need an additional source of input, you can add a vertex colour or additional UV coordinate channel. These attributes are not modified when batching, so your effect won't change when batched together (though adding more vertex attributes means the maximum number of models that can be batched together will be smaller, since each uses more data now)

---
Tags: unity, shaderlab, vertex-shader
---


title: Unity 5 2d Magnet Power Up

text:
# Question
Title: Unity 5 2d Magnet Power Up
I made a car game with coins and power up but i wrote a code for magnet power up but in start work fine but after i get power up magnet all coin in surface i collect but after this don\`t spawn coin any more and show me this error: Picture 1. And here my code:

```
//Car script
//PowerUp Magnet Sector
    public bool magnetPowerUp = false;
    public float MagnetDuration;

     private void OnCollisionEnter2D(Collision2D col)
    {
        //Magnet
        if (col.gameObject.tag == "Magnet")
        {
            col.gameObject.SetActive(false);
            StartCoroutine(Magnet());
        }
     }

     IEnumerator Magnet()
    {
        magnetPowerUp = true;
        yield return new WaitForSeconds(MagnetDuration);
        magnetPowerUp = false;
    }
```

```
    //CoinScript

    using UnityEngine;
using System.Collections;

public class CoinSpaws : MonoBehaviour
{
    public carController car;
    public GameObject player;
    public GameObject[] coins;
    int coinNo;
    public float maxPos = 1.7f;
    public float delayTimer;
    float timer;

    // Use this for initialization
    void Start()
    {

        timer = delayTimer;

    }

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

        timer -= Time.deltaTime;
        if (timer <= 0)
        {

            Vector3 coinPos = new Vector3(Random.Range(-1.7f, 1.7f), transform.position.y, transform.position.z);
            coinNo = Random.Range(0, 2);
            Instantiate(coins[coinNo], coinPos, transform.rotation);
            timer = delayTimer;

        }

        if (car.magnetPowerUp)
        {
            coins = GameObject.FindGameObjectsWithTag("coin");
            foreach (var treasure in coins)
            {
                treasure.transform.position = Vector2.MoveTowards(treasure.transform.position, player.transform.position, 5.0f * Time.deltaTime);
            }
        }
    }

}
```

# Answer
> 1 votes
You're using your `coins` array to do double duty:

* first, it acts as a list of (2) possible coin prefabs to randomly choose from for spawning new coins.
* then, it acts as a list of all coins currently active in your game scene, so you can attract them to your magnet power.

So think of what happens once your magnet has sucked up all the coins. Now `FindObjectsOfType` gives you an empty array, since there's no coins left in your scene. The next time you try to spawn a coin, you're trying to select the first or second item in an array of zero items, which generates an index out of range error.

To fix this, you should use a separate variable for each job. One variable stores your coin prefabs to use for spawning, and one tracks your currently active coins. Don't overwrite one with the other.

And, ideally, don't search your whole scene for coins every frame. ;) It's much more efficient to just add them to a list as you spawn them, and remove them as they're collected.

---

Since you asked for code examples, I'd recommend refactoring this substantially, to put the responsibility for counting & enumerating coins on the coin objects themselves:

```
using System.Collections.Generic;

public class Coin : MonoBehaviour {

    // The Coin class will keep track of how many of its instances have been spawned.
    static List<Coin> _activeInstances = new List<Coin>;
    static void Add(Coin coin) {
        coin._index = _activeInstances.Count;
        _activeInstances.Add(coin);
    }
    static void Remove(Coin coin) {
        // Swap the last coin into the gap left by this one.
        _activeInstances[coin._index] = _activeInstances[_activeInstances.Count - 1];
        _activeInstances[coin._index]._index = coin._index;
        // Shorten our list of coins by one.
        _activeInstances.RemoveAt(_activeInstances.Length - 1);
    }

    public static void AttractAll(Vector3 target, float speed) {
        foreach(var coin in _activeInstances) {
            // If using physics triggers for coin collection, consider using
            // Rigidbodies & velocity instead of manipulating position directly.
            Vector3 pos = coin.transform.position;
            pos = Vector3.MoveTowards(pos, target, speed * Time.deltaTime);
            coin.transform.position = pos;
        }
    }

    int _index;
    void Awake() {
        Coin.Add(this);
    }
    void OnDestroy() {
        Coin.Remove(this);
    }

    // If you're using OnTriggerEnter or similar messages to trigger
    // coin collection, you can put that here, or on the player.
}

```

Now our Spawner doesn't need to know anything about the kinds of objects it's spawning, or about the car or magnets. It doesn't even need an Update loop anymore, it can just run a periodic coroutine to spawn more coins.

```
public class Spawner : MonoBehaviour {
    public float spawnInterval = 3f;
    public GameObject[] spawnPrefabs;
    Vector2 SpawnVariation = new Vector2(1.7f, 0f);

    void Start() {
        StartCoroutine(Spawn());
    }

    IEnumerator Spawn() {
        while(true) {
            yield return new WaitForSeconds(spawnInterval);

            int spawnIndex = Random.Range(0, spawnPrefabs.Length);
            Vector3 position = transform.position;
            position.x += Random.Range(-1f, 1f) * spawnVariation.x;
            position.y += Random.Range(-1f, 1f) * spawnVariation.x;
            var instance = Instantiate(spawnPrefabs[spawnIndex], position, Quaternion.Identity);
        }
    }
}

```

And the attraction can happen be handled within our magnet powerup script, rather than in the spawners or on the coins, so neither needs to know about the player or magnets.

```
IEnumerator Magnet() {
    magnetPowerUp = true;
    for(float t = 0; t < MagnetDuration; t += Time.deltaTime) {
        Coin.AttractAll(transform.position, 5.0f);
        yield return null;
    }
    magnetPowerUp = false;
}

```

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


# Question
Title: How can I find out which Androids suffer from the Scrolling Button bug?
When developing in Unity, there is a bug where if you put a Button on a Scroll View, the scroll is hyper-sensitive on some Androids. This makes the button depress immediately after pressing it, because it thinks you are trying to scroll. This can be resolved by reducing the scroll sensitivity on the ScrollRect.

I do not want to reduce the sensitivity on all Android devices. For example, on the newer ones such as the Pixel, it works perfectly. Reducing the sensitivity actually makes it feel mildly less responsive.

How can I find out which models/operating systems that this bug exists on? I would prefer to just not release to those versions. (They are far and few between, but enough to make their 1 star reviews hurt badly.)

# Answer
I can't tell you which models have this issue. But here I'm giving you a solution:

Select your active `EventSystem` GameObject:

Find the `Event System` component:

Increase the `Drag Threshold` field.

This field determines the threshold of pointer movement when pressed down before Unity registers it as a drag. By increasing this field we are telling Unity that more pointer movement is required before registering the action as a drag.

The value of `Drag Threshold` is in **pixels**.

---

If you are not satisfied with manual adjustment, I found an article that performs an automatic `Drag Threshold` calculation.

---

**Edit:** Also in this git repository on BitBucket named Unity UI Extensions, there is a module that claims it can correct `Drag Threshold` for high DPI systems. *Looking at the source, I see the script is doing something almost identical with the article I linked above.*

You can find the source code of the DragCorrector script here.
> 2 votes

---
Tags: unity, android, gui, bug
---


title: What does the "static" mean in Java?

text:
# Question
Title: What does the "static" mean in Java?
I'm wondering why do people use "static" for example, `public static final String`

# Answer
> 1 votes
`static` for a member variable means that it is shared across all instances of the class. It also means that you don't need an instance of the class to access the field.

```
public class Foo {
  public int A = 10;
  public static int B = 20;
}

public class Bar {
   public void FooBar() {
      Foo.B = 30; // Valid, sets the static instance
      Foo.A = 40; // Invalid, accessing A not through an instance

      Foo f1 = new Foo();
      Foo f2 = new Foo();

      f1.B = 100;
      f2.B = 200;

      System.out.println("f1.B = " + f1.B); // Prints 200, not 100
      System.out.println("f2.B = " + f2.B); // Prints 200
   }
}

```

People often use `public static final` when creating constant values that are to be easily shared and accessed by many parts of the game.

The Oracle Java Tutorials cover the `static` keyword in more detail.

# Answer
> 0 votes
Really, all functions in all classes are "static" in the sense that they do not change at runtime, and there is one instance in memory of each, regardless of how many instances of that class exist.

If you were ever to write code in C, you'd have better insight into this. C has only one type of function, and does not artificially divide functions ("methods") into distinct types. Yet you can do everything in C that you can in higher level languages like C++, C#, or Java (but with more effort in some cases).

So from the perspective of "why?" - Mainly because OO languages introduced the concept in order to draw a distinction between things (in classes) that always exist (static, compile time stuff) and stuff that is dynamically created (instantiated at runtime). This was done differently because while C assumes there is only one any function of a given name, C++ may have many instances of the same class. At least for class data members, this distinction needs to be drawn - there can be many `myObj.instanceVariable` but only one `MyClass.staticVariable`. The distinction seems to have been made simply to match the way we view methods to the way we view data members, which are their conceptual siblings, OO languages.

---
Tags: java
---


# Question
Title: MonoGame HLSL fx using Multiple Textures
I'm converting an old XNA title to MonoGame and one of the HLSL fx files uses two textures. But no matter what I do, it only ever uses the screen texture while rendering the effect in MonoGame, or else draws nothing.

I can see in debug mode that I'm trying to pass in the correct textures in C#, plus it works correctly in the XNA version. So why is my shader only using the screen texture in Monogame?

**HLSL**

```
Texture2D ScreenTexture;
sampler2D ScreenSampler = sampler_state
{
    Texture = <ScreenTexture>;
};

Texture2D DistortionMap;
sampler2D OffsetSampler = sampler_state
{
    Texture = <DistortionMap>;
    AddressU = Clamp;
    AddressV = Clamp;
};

float4 PixelShaderFunction(float4 pos : SV_POSITION, float4 color1 : COLOR0, float2 texCoord : TEXCOORD0) : COLOR0
{
    // Use the DistortionMap to alter the location of the ScreenSampler output.
    // DistortionMap's rg at a position correspond to that position's xy distortion.
    return tex2D(ScreenSampler, texCoord + (tex2D(OffsetSampler, texCoord).rg * 2 - 1));
}

technique Technique1
{
    pass Pass1
    {
        PixelShader = compile ps_4_0_level_9_1 PixelShaderFunction();
    }
}

```

**C#**

```
public static void Draw(SpriteBatch spriteBatch)
{
    // Update the Offsets map texture.
    UpdateVertices();

    // Set up the current render target to draw to the other render target
    Game1.RenderSetToA = !Game1.RenderSetToA;
    ThisGame.GraphicsDevice.SetRenderTarget(Game1.RenderSetToA ? Game1.RenderTargetA : Game1.RenderTargetB);
    RenderTarget2D renderTargetToDraw = Game1.RenderSetToA ? Game1.RenderTargetB : Game1.RenderTargetA;

    // Draw the old render target with the distortion effect to the new render target.
    DistortionEffect.Parameters["ScreenTexture"].SetValue(renderTargetToDraw);
    DistortionEffect.Parameters["DistortionMap"].SetValue(Offsets);
    spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Opaque, null, null, null, DistortionEffect);
    spriteBatch.Draw(renderTargetToDraw, Vector2.Zero, Color.White);
    spriteBatch.End();
}

```

# Answer
> 1 votes
Figured it out, or at least figured out a workaround, in part with the help of this answer. It seems the tex2D method was not sampling the textures how I wanted it to with sampler2D samplers. I refactored the shader to use SamplerStates and the Texture2D.Sample function, like so:

```
Texture2D ScreenTexture;
Texture2D DistortionMap;
SamplerState Sampler;

float4 PixelShaderFunction(float4 pos : SV_POSITION, float4 color1 : COLOR0,
float2 texCoord : TEXCOORD0) : COLOR0
{
    return ScreenTexture.Sample(Sampler, texCoord + (DistortionMap.Sample(Sampler, texCoord).rg * 2 - 1));
}

technique Technique1
{
    pass Pass1
    {
        PixelShader = compile ps_4_0_level_9_3 PixelShaderFunction();
    }
}

```

Note that I was able to do this with either one or two samplers, so I decided to just use one.

---
Tags: c#, shaders, monogame, hlsl, sampler-state
---


# Question
Title: procedural forest canopy for terrain lighting
I would like to create a forest scene where directional light moves through the trees canopy and is projected onto the terrain and characters underneath like so:

I'm using Unity 5.6. My tree line is not in view of my camera which is set to isometric. I thought because there is no need for the tree models, I would create a quad between my directional light source and terrain. The quad would have a material with a perlin noise texture and cutout transparent shader. A majority of my scene is under the canopy with sporadic light leaking through:

My question, is the a performant way to reproduce the effect or is all the shadow casting expensive? Is there a better way to produce the effect so that my dynamic gameobjects receive real-time lighting? Is there a texture or noise function that better represents a forest canopy?

# Answer
> 7 votes
This sounds like a job for Light Cookies.

These have a number of advantages over the shadow mapping method you describe:

* Cookies can represent intermediate levels of brightness, helping you get those soft bokeh edges and dim partial transparency that can be difficult to achieve with shadow maps.
* The cookie can be tiled and scaled independent of your light's shadow maps, helping you keep fine detail in the dappling without increasing your shadowing workload.

Here's a quick mock-up I made, rendering a particle system into a RenderTexture using a separate camera/layer, and applying that texture to my directional light as a cookie.

With a more sophisticated setup you could ensure the cookie tiles seamlessly over large areas, or layer-together sprites representing clusters of leaves that jiggle around to give a more consistent/structured look rather than the random blobs I've used here.

You could of course render your cookie with a noise-based material and blit it to the texture using pure math to form the shapes, but you might find layering objects in front of a camera makes it easier to fine-tune the look you want, or achieve things like controllable wind.

# Answer
> 0 votes
`is all the shadow casting expensive?`

That all depends on how much detail you're willing to drop. How accurate do you want this to be?

Fully accurate = casting through all individual branches and twigs = fine grained 3D volume grid or CPU-intensive geometric approach = costly. Self occlusion = potentially costly. Desired ground-dappling resolution will also affect the *number* of rays to cast per unit area, affecting cost.

**Some possible solutions...**

1. Treat the canopy as though it were *flat*, and store as a bit map (2D boolean array with each entry being shadowed/occluded or lit/unoccluded). Start the raycast at the level of this canopy bitmap, and cast the few meters / units to the ground. Unless occluded by trunks, rays will always reach the ground, and the distance to cast each ray will be fairly short.
2. Use a quadtree instead of a fixed-resolution 2D array / bitmap. This will allow you to only do many raycasts in areas around each tree's canopy; in open glades, the quadtree will use a coarser resolution, reducing the number of rays. This is conceptually similar to the concept of orthogonal *ray packets*, where several rays are treated as a single ray in certain special circumstances.
3. Enforce a maximum tree / canopy height to ensure the number of ray steps stays reasonable.
4. Reduce the number of "dapples" per square meter, as much as you can while still allowing for a fair visual impact. You can adapt this into a LoD approach that depends on how far camera is.

Ultimately, you either do this using pure geometric approaches, or you break your space down into a regular 3D grid (voxels), even if that is only for purposes of calculating lighting. They both have their pros and cons. Voxels do make this process a little easier for those not very mathematically inclined.

**Your other questions**

We don't encourage multiple questions in one (and these are indeed totally separate problems), but briefly, you don't mention what sort of lighting you're using: forward vs. deferred, screen space vs world space, so it is really impossible to answer that. As for the most accurate pattern production - if I were you, I'd analyse my trees' volumes into an octree, then simply flatten the z aspect of the octree in order to get your flat canopy bitmap from which you can then raycast the forest floor.

P.S. Raycasting a canopy space accurately is a task challenging enough for the best procedural programmers using native languages and GPGPU tech; Unity is no match for these sorts of problems.

---
Tags: unity, lighting
---


# Question
Title: Does pixels per unit property affect performance of the game in Unity?
The Sprite import inspector has a Pixels Per Unit setting that controls the size of the sprite objects when they're added to the scene:

Will Unity resize the sprite at run time or will it be resized after me changing the property and saved for the future?

# Answer
**First, a little clarification:**

the Pixels per Unit setting controls the size of the *geometry* the image is rendered on. It does not rescale the raster image asset in memory or on the disc, like you might be used to when resizing an image in Photoshop or similar programs. Those operations can take some time, because the program needs to walk through every pixel in the new image and calculate its colour by sampling the corresponding pixels in its previous incarnation.

By contrast, the scaling that Pixels per Unit does is dirt cheap, operating on a handful of transformation matrices or vectors that the game was going to have to process anyway when sending them to the GPU to render each frame.

So, you shouldn't worry about the process of scaling itself causing a substantial performance impact.

---

Where pixels per unit can impact performance is in how the resulting size of your scene objects plays with Unity's acceleration structures for rendering and physics. Often these are tuned to assume that the stuff you're interacting with primarily - your player characters, trigger volumes, map tiles, etc - are on a scale between tenths to tens of units in size. If we think of a unit as a meter, then this lets us model interactions with anything from house pets to jumbo jets.

Keeping a pixels per unit setting tuned so that your gameplay happens in this size range lets these systems do their work smoothly. It can also help make your math easy as a developer, sticking to small numbers that are simple to work with and remember ("Map tiles are 1 unit, the player's dash move travels 3 units" etc).

You'll see an occasional tutorial though that says you should set your pixels per unit to 1, so that you can work in pixel coordinates for everything. I do not recommend this approach. Doing it this way, a single screen at 1080p spans 2000 game units, and most objects will be hundreds of units across. This can cause systems like physics to behave poorly because it's outside the range they've been tuned for.

So here again, the scaling itself isn't a significant performance sink, but the consequences it has on the size of your game interactions can be.
> 6 votes

---
Tags: unity, sprites, performance
---


# Question
Title: Server reconciliation for multiplayer games
Reading the usual resources on multiplayer games (, , ); I have started working on my own multiplayer game.

I used a naïve approach that for every input I receive from a client, I immediately run it on the server.

For simple units (soldiers) everything works well, however I have an issue with "always moving" units (such as jet fighters); They require queuing inputs on the server (small delay, less than 100ms) and performing them in delay - and I read elsewhere (, ) that you should allow a window to receive inputs longer than said delay, since latency is variable (and could easily reach over 100ms) and reconcile the player's input.

Now I understand how this works for simple input such as movement, but what about using weapons / more advanced input?

What happens if player input comes with a delay, where he wishes to fire his weapon - what do I do? When do I notify other players of the shot? What about it's result? What if my cool-downs are out of sync due to this reconciliation?

Thanks.

# Answer
> 1 votes
"I used a naive approach that for every input I receive from a client, I immediately run it on the server." Sounds like you are sending the input to the server. This can be great for an anticheat system, but is not well suited for controlling units. I've seen many MMO and RTS games that send the target destination for a selected unit, and then the server handles the rest -- and this works quite well. I'm guessing this game your making is an RTS game, so just send a units destination once.

If your going for no network latency in interface, you can predict what the server will do, then get a confirmation from the server later. IE, send unit 3 to destination X. Client generates and draws a path of motion and starts drawing movement. Server sends actual path later and confirms movement of time, taking precedence.

# Answer
> 1 votes
Your 3rd link answers your question:

> This screenshot was taken on a listen server with 200 milliseconds of lag (using net\_fakelag), right after the server confirmed the hit. The red hitbox shows the target position on the client where it was 100ms \+ interp period ago. Since then, the target continued to move to the left while the user command was travelling to the server. After the user command arrived, the server restored the target position (blue hitbox) based on the estimated command execution time. The server traces the shot and confirms the hit (the client sees blood effects).

**To address your specific questions** (based on the method Source Engine decided to use above):

> What happens if player input came in delay, where he wishes to fire his weapon what do I do?

When the server receives the delayed player input, it calculates where the target was at the time of input.

> When do I notify other players of the shot?

As soon as the server receives the delayed input.

> What about it's result?

The target is hit. The Source Multiplayer Networking docs goes on to admit this might result in some weird "paradoxes." But it seems like the fairest method.

> Network latencies and lag compensation can create paradoxes that seem illogical compared to the real world. For example, you can be hit by an attacker you can't even see anymore because you already took cover. What happened is that the server moved your player hitboxes back in time, where you were still exposed to your attacker. This inconsistency problem can't be solved in general because of the relatively slow packet speeds. In the real world, you don't notice this problem because light (the packets) travels so fast and you and everybody around you sees the same world as it is right now.

---
Tags: networking, multiplayer, lag
---


# Question
Title: Transform values stay zero while catching mouse movement
I am working on a game using GoogleVR, but I don't think that has anything to do with my problem.

Basically, I am testing to see if I can move a stick by using the mouse at the moment.

I am getting mouse movement, as seen from the value of `md`:

```
(-0.5,-1.25)
UnityEngine.Debug:Log(Object)
PlayerMovement:Update() (at Assets/Character Pack/PlayerMovement.cs:30)

```

But the transform is wrong, as seen from the `localRotation`:

```
(0,0,0)
UnityEngine.Debug:Log(Object)
PlayerMovement:Update() (at Assets/Character Pack/PlayerMovement.cs:29)

```

I just want to see my stick move in some predictable way based on the movement of the mouse, and I am not certain why my equation is wrong.

```
public class PlayerMovement : MonoBehaviour {
    Vector2 mouseLook;
    Vector2 smoothV;
    public float sensitivity = 5.0f;
    public float smoothing = 2.0f;

    public GameObject stick;

    // Use this for initialization
    void Start () {
        smoothV.x = 0.5f;
        smoothV.y = 0.5f;
    }

    // Update is called once per frame
    void Update () {
        var md = new Vector2 (Input.GetAxisRaw ("Mouse X"), Input.GetAxisRaw ("Mouse Y"));

        md = Vector2.Scale(md, new Vector2(sensitivity * smoothing, sensitivity * smoothing));
        smoothV.x = Mathf.Lerp (smoothV.x, md.x, 1f / smoothing);
        smoothV.y = Mathf.Lerp (smoothV.y, md.y, 1f / smoothing);

        stick.transform.localRotation = Quaternion.AngleAxis (-mouseLook.y, Vector3.right);
        stick.transform.localRotation = Quaternion.AngleAxis (mouseLook.x, stick.transform.up);
        Debug.Log ("(" + stick.transform.localRotation.x + "," + stick.transform.localRotation.y + "," + stick.transform.localRotation.z + ")");
        Debug.Log ("(" + md.x + "," + md.y + ")");
    }
}

```

# Answer
There are a lot of mistakes in this code, which makes it a bit difficult to sort out what's the root problem you're trying to solve versus what's noise.

Firstly, you're storing your mouse movement in `md`, and debugging its contents to make sure it got set properly, but not using it at all for rotation. Your rotation code is using a completely different variable `mouselook` which so far as I can tell you never populate with any non-zero values.

Then your rotation code sets `localRotation` with your pitch rotation... then immediately overwrites this with a yaw rotation, so the first line setting `localRotation` might as well not be there — the very next line replaces whatever it tried to do. Did you mean to combine these two partial rotations using multiplication or `Quaternion.Euler`?

Your rotation debug only looks at the x, y, and z components of the `localRotation` quaternion, which won't be very informative. These components hold the axis of rotation, scaled by the sine of half the angle — which is very nearly zero for small angles. To get a more intelligible human-readable value, you might want to check `transform.localEulerAngles` instead.

Lastly, you need to be a bit careful when rotating on two axes in sequence, as this can produce unexpected results based on the order of composition.
> 1 votes

---
Tags: unity, c#, transformation, lerp
---


title: Create circular platform out of tiles

text:
# Question
Title: Create circular platform out of tiles
I am creating a 3d game. In this game I have a 3d model for a tile which I render in different locations using instancing.

I want to create a number of these tiles arranged so as to approximate a circle, similar to this:

I need to create an array of 3d vectors representing the position of the tiles in order to create this circle pattern with a given radius.

Here is the code I use to generate a square platform.

ENG\_U is a constant representing a "Unit" in the game.

t is the array of positions passed to the renderer.

```
int rad = 16;

  t = new glm::vec3[(rad+rad+1)*(rad+rad+1)];
  int c = 0;
  for (int i =0;i < (rad+rad)+1;i++)
  {
    for (int j =0;j < (rad+rad)+1;j++)
    {
    t[c] = glm::vec3(i*ENG_U*1.7*2,0,j*ENG_U*1.7*2) - glm::vec3(ENG_U*1.7*2*rad,0,ENG_U*1.7*2*rad);
    c++;
    }
  }

```

# Answer
> 1 votes
Same as the square except you check if the coordinate is within the circle's radius.

```
#include <vector>

int rad = 16;
float thicken = 0.5f; // between 0.0f and 1.0f
int thickened_radius2 = (int)floorf((rad + thicken) * (rad + thicken));

std::vector<glm::vec3> tiles;

tiles.reserve((rad*2+1)*(rad*2+1)); // (optional) reserve enough space for performance reason

for(int z = -rad; z <= rad; ++z){
  for(int x = -rad; x <= rad; ++x){
    if((x*x+z*z) <= thickened_radius2){ // check if tile is within circle
      tiles.push_back(glm::vec3(x, 0, z));
    }
  }
}

tiles.shrink_to_fit(); // (optional) only available in C++11 or newer

```

`tiles.data()` returns a pointer to the array `(glm::vec3 *)`

`tiles.size()` returns the length of the array `(size_t)`

If you need to copy that into a simple array:

```
#include <algorithm>

t = new glm::vec3[tiles.size()];
std::copy(tiles.begin(), tiles.end(), t);

```

But I'd just keep it in an std::vector this way you have the size() readily available. The overhead of std::vector is negligible.

`thicken` is optional but if you don't use this you'll only have 1 tile at each axis "side" of the circle. It makes a prettier circle. (Set it to 0 and see for yourself.)

# Answer
> 0 votes
Here is the algorithm to generate the tile offsets.

```
  std::vector<glm::vec3> ps;
  int rad = 16;
  int r2 = 32;
  int c = 0;
  for (int i =0;i < (rad+rad)+1;i++)
  {
    for (int j =0;j < (rad+rad)+1;j++)
    {
      glm::vec3 p = glm::vec3(i*ENG_U*1.7*2,0,j*ENG_U*1.7*2) - glm::vec3(ENG_U*1.7*2*rad,0,ENG_U*1.7*2*rad);
      bool rm = false;
      if (length(p+glm::vec3(ENG_U*1.7,0,ENG_U*1.7)) > ENG_U*1.7*r2)
      rm = true;
      if (length(p-glm::vec3(ENG_U*1.7,0,ENG_U*1.7)) > ENG_U*1.7*r2)
      rm = true;
      if (length(p+glm::vec3(-ENG_U*1.7,0,ENG_U*1.7)) > ENG_U*1.7*r2)
      rm = true;
      if (length(p+glm::vec3(ENG_U*1.7,0,-ENG_U*1.7)) > ENG_U*1.7*r2)
      rm = true;
      if(!rm)
     ps.push_back(p);
    c++;
    }
  }

```

---
Tags: c++, glm
---


# Question
Title: Preventing Excessive Movement Speed in Visual Studio
I just decided to give coding a go, and I am using C# in Visual Studio 2017. After some online tutorials, I tried to make a Windows Form App with simple movement. The only problem I have is that if you hold down a key for around a second, the player suddenly moves super quickly in that direction.

```
private void inGameKeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.A)
        {
            MoveSpeedX -= 3;
        }

        if (e.KeyCode == Keys.D)
        {
            MoveSpeedX += 3;
        }

        if (e.KeyCode == Keys.W)
        {
            MoveSpeedY -= 3;
        }

        if (e.KeyCode == Keys.S)
        {
            MoveSpeedY += 3;
        }
    }

```

The movement code. How can I fix this issue? Any help would be appreciated! :D

P.S. If you could also show me a way for more efficient movement, that would be greatly appreciated as well! :D

# Answer
> 0 votes
*Note: this is significant overkill for your current Windows Form Application implementation of movement, but if you're going to start getting into game development this is often how movement is managed. For example, I believe the first Unity tutorial covers this with a simple ball-moving game.*

*Note 2: this is a highly OOP implementation. Don't even get started between OOP vs. procedural (answer by S. Tarık Çetin), because all I'm trying to do is present the current game development convention of movement implementations. In the original poster's case, yes, procedural is the easiest, fastest, and most light-weight implementation. In large projects with a framework that has these classes already available, OOP is in my opinion easier and faster.*

*Note 3: this is by no means a perfect implementation, probably not even that good. It was created quickly to illustrate Vector movement.*

---

I'm a bit late to reply, but I would consider starting to work with `Vector` objects. **There is no such object in basic .NET framework to my knowledge, but engines like Unity/Unreal have frameworks that utilize similar implementations.**

The reason I suggest this is because assigning movement is often done by applying a `Vector` value to a position in 2-space, `x` and `y` components, or 3-space `x`, `y`, and `z` components. You're just using 2D movement so I'll stick with that.

Here is a very basic implementation of a `Vector` class you could use (but any framework you'd use for real game development will already have one for your to use):

```
public class Vector2 //the number 2 indicates this only 2-space components
{
    public int X { get; private set; }
    public int Y { get; private set; }
    //this Clamp only covers min/max values being the same magnitude in each dimension
    private Vector2 Clamp;

    public Vector2(int x, int y)
    {
        this.X = x;
        this.Y = y;
    }

    //I've put the clamp in the Vector, but depending on your needs, assigning min/max to the Player may be better
    public void Clamp(int magnitude)
    {
        this.Clamp = new Vector2(Math.Abs(magnitude), Math.Abs(magnitude));
    }
    public void Clamp(Vector2 vector)
    {
        this.Clamp = new Vector2(Math.Abs(vector.X), Math.Abs(vector.Y));
    }

    public void Add(int x, int y)
    {
        this.X += (Clamp != null && Clamp.X > Math.Abs(x)) ? x : Clamp.X;
        this.Y += (Clamp != null && Clamp.Y > Math.Abs(y)) ? y : Clamp.Y;
    }
    public void Add(Vector2 vector)
    {
        Add(vector.X, vector.Y);
    }
}

```

Again, please note that this is overkill for your basic application, this is just to familiarize you with vector movements. Here's an implementation of a player object:

```
public class Player
{
    public Vector2 Position;
    public Vector2 Velocity;

    public Player()
    {
        this.Position = new Vector2(0, 0);
        this.Velocity = new Vector2(0, 0);
    }
    public Player(Vector2 startPosition, Vector2 startVelocity)
    {
        this.Position = startPosition;
        this.Velocity = startVelocity;
    }

    public void Move()
    {
        this.Position.Add(this.Velocity);
    }
}

```

This implementation of `Player` is missing the 'size' of the object, so you'd have to adjust for that in other ways for proper collision/bounds checking.

Then your movement could be handled like this:

```
private void InGameKeyDown(object sender, KeyEventArgs e)
{
    var movement = new Vector(0, 0);

    if (e.KeyCode == Keys.A)
    {
        movement.Add(-1, 0);
    }
    if (e.KeyCode == Keys.D)
    {
        movement.Add(1, 0);
    }
    if (e.KeyCode == Keys.W)
    {
        movement.Add(0, -1);
    }
    if (e.KeyCode == Keys.S)
    {
        movement.Add(0, 1);
    }

    //this is assuming you have the player1 Player object globally assigned, instead of your MoveSpeedX/MoveSpeedY objects
    player1.Velocity.Add(movement);
}

```

Whatever method you're using to move the object (where you're currently applying your `MoveSpeedX` and `MoveSpeedY`) will then only need to do `player1.Move()`, since the `Player` object updates its own position with its own velocity.

This is essentially how movement is being handled (for the value of Player.Position, assume each step # is 1 frame of the game, or tick, or update period for animation/rendering, progressing):

1. Game start:
    * Player.Velocity = (0,0)
    * Player.Position = (0,0)
2. Press 'S' Key:
    * Player.Velocity = (0,1)
    * Player.Position = (0,1)
3. Press 'S' Key:
    * Player.Velocity = (0,2)
    * Player.Position = (0,3)
4. Game time progresses:
    * Player.Velocity = (0,2)
    * Player.Position = (0,5)
5. Press 'W' Key:
    * Player.Velocity = (0,1)
    * Player.Position = (0,6)
6. Press 'D' Key:
    * Player.Velocity = (1,1)
    * Player.Position = (1,7)
7. Press 'W' Key:
    * Player.Velocity = (1,0)
    * Player.Position = (2,7)
8. Game time progresses:
    * Player.Velocity = (1,0)
    * Player.Position = (3,7)
9. Game time progresses:
    * Player.Velocity = (1,0)
    * Player.Position = (4,7)
10. Press 'W' Key:
    * Player.Velocity = (1,-1)
    * Player.Position = (5,6)
11. Press 'W' Key:
    * Player.Velocity = (1,-2)
    * Player.Position = (6,4)
12. Game time progresses:
    * Player.Velocity = (1,-2)
    * Player.Position = (7,2)
13. Game time progresses:
    * Player.Velocity = (1,-2)
    * Player.Position = (8,0)

*(It should be noted, as well, that Windows Forms treats the origin, (0,0), as the top left corner of the window, which is why 'S' increases the y-value and 'W' decreases it.)*

As can be seen in the values I've shown above, this implementation assumes that your object has persistent velocity; like a car, it's moving until decelerated to 0 velocity. If you want it to only move when a key is pressed, change the `player1.Velocity.Add(movement)` to `player1.Position.Add(movement)`.

---

If you *are* interested in game development, definitely check out the Unity tutorials and Learn section. It will help get you started, and provide a much better description than I could, as well as walking you through the steps of creating games.

The best part: it's free! No, I'm not affiliated with Unity in any way (other than using their engine occasionally).

# Answer
> 0 votes
Try this:

```
private void inGameKeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.A)
    {
        MoveSpeedX = -3;
    }

    if (e.KeyCode == Keys.D)
    {
        MoveSpeedX = 3;
    }

    if (e.KeyCode == Keys.W)
    {
        MoveSpeedY = -3;
    }

    if (e.KeyCode == Keys.S)
    {
        MoveSpeedY = 3;
    }
}

```

---

**Explanation**

```
Speed = Distance traveled for the time period / Time passed

```

When you increase speed, you are increasing the amount of distance you travel for a given period of time.

I imagine your `inGameKeyDown` function gets called constantly as you hold down the key. This causes the speed to get incremented over and over again, instead of being clamped between `-3` and `+3`.

There is a little issue: if you press D while pressing down A, your object will travel in the positive X direction instead of staying put. You can fix it like this:

```
private void inGameKeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.A)
    {
        MoveSpeedX -= 3;
        MoveSpeedX = Math.Clamp(MoveSpeedX, -3, +3);
    }

    if (e.KeyCode == Keys.D)
    {
        MoveSpeedX += 3;
        MoveSpeedX = Math.Clamp(MoveSpeedX, -3, +3);
    }

    if (e.KeyCode == Keys.W)
    {
        MoveSpeedY -= 3;
        MoveSpeedY = Math.Clamp(MoveSpeedY, -3, +3);
    }

    if (e.KeyCode == Keys.S)
    {
        MoveSpeedY += 3;
        MoveSpeedY = Math.Clamp(MoveSpeedY, -3, +3);
    }
}

```

There is another problem: The object keeps moving when we release all keys. You can't solve this inside `inGameKeyDown` method because it will not get called if no keys are down.

Inside your game loop, you can reset the speed to `0` every frame before processing speed increments, so when no keys are pressed the speed will be `0` all the time.

Please note that both of these code pieces are not tested and written quickly. There are much better ways to handle this situation.

---
Tags: c#
---


# Question
Title: What is wrong with my Assets class and AssetsManager? App not running
I am not understanding why my application is causing problems whenever I try to run it. There are no errors although whenever I try to run the application it brings up the console with problems and the app wont run. I run "desktop".

Here is part of my **Assets** class ...

```
public class Assets implements Disposable {

public AssetManager manager;

public Assets (){
    init();
}

public void init () {

    manager = new AssetManager();

    manager.load(Constants.TEXTURE_ATLAS_OBJ, TextureAtlas.class);

    manager.finishLoading();
}

```

Here is part of my **main** class ...

```
public class MyGdxGame implements ApplicationListener {

....

private Assets assets;

@Override
public void create() {

...
    assets = new Assets();
...
}

@Override
public void render() {
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

    camera.update();

    batch.begin();
    ...
    batch.end();
    }

```

When I try to run this, is gives me a problem like this in the **console**...

```
Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: com.badlogic.gdx.utils.GdxRuntimeException: com.badlogic.gdx.utils.GdxRuntimeException: File not found: canyonbunny.pack (Internal)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:113)

```

Caused by: com.badlogic.gdx.utils.GdxRuntimeException: com.badlogic.gdx.utils.GdxRuntimeException: File not found: canyonbunny.pack (Internal) at com.badlogic.gdx.assets.AssetManager.handleTaskError(AssetManager.java:471) at com.badlogic.gdx.assets.AssetManager.update(AssetManager.java:316) at com.badlogic.gdx.assets.AssetManager.finishLoading(AssetManager.java:337) at com.me.mygdxgame.Assets.init(Assets.java:26) at com.me.mygdxgame.Assets.(Assets.java:17) at com.me.mygdxgame.MyGdxGame.create(MyGdxGame.java:32) at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:127) at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:110) Caused by: com.badlogic.gdx.utils.GdxRuntimeException: File not found: canyonbunny.pack (Internal) at com.badlogic.gdx.files.FileHandle.read(FileHandle.java:127) at com.badlogic.gdx.graphics.g2d.TextureAtlas$TextureAtlasData.(TextureAtlas.java:97) at com.badlogic.gdx.assets.loaders.TextureAtlasLoader.getDependencies(TextureAtlasLoader.java:59) at com.badlogic.gdx.assets.loaders.TextureAtlasLoader.getDependencies(TextureAtlasLoader.java:34) at com.badlogic.gdx.assets.AssetLoadingTask.handleSyncLoader(AssetLoadingTask.java:103) at com.badlogic.gdx.assets.AssetLoadingTask.update(AssetLoadingTask.java:92) at com.badlogic.gdx.assets.AssetManager.updateTask(AssetManager.java:399) at com.badlogic.gdx.assets.AssetManager.update(AssetManager.java:314) ... 6 more

I tried to locate the problem and I figured out when **i take the manager.finishedLoading() out**, my program runs. I even printed "Test" to the screen. But when I **leave the manager.finishedLoading() in**, it gives me console problems.

For further info, here is my **Constants** class ...

```
public class Constants {

public static final int WIDTH = Gdx.graphics.getWidth();
public static final int HEIGHT = Gdx.graphics.getHeight();
public static final String TEXTURE_ATLAS_OBJ =
        "canyonbunny.pack";

```

}

# Answer
Sorry for the inconvenience, I made a mistake with the Constants.TEXTURE\_ATLAS\_OBJ - I have misspelled "canyon bunny.pack" to "canyonbunny1.pack". I have made a typing error and this question is now closed!
> 1 votes

---
Tags: libgdx
---


# Question
Title: Why does my triangle ray intersection test always return -1.0f?
I'm trying to get the mouse click position on a terrain geometry, but multiple times in each frame; doing it on the CPU was way too slow, so I'm trying to do it with a compute shader. I can't seem to get a valid result back. I guess it's somehow related to my raydirection/rayorigin vectors, because I tried 4 different written DirectX HLSL solutions, but none of them works for my case; though, I did have to modify them. Anyway, this is my code to generate the ray vectors:

```
XMFLOAT3 RayOriginFloat = m_Camera->GetPosition(); //The eye position of the camera. I use this vector in the compute shader.

XMVECTOR worldPos;
XMVECTOR RayOrigin = XMLoadFloat3(&RayOriginFloat);
DirectX::BoundingFrustum frustum;

// I use the DirectXMath XMVector3Unproject method to project the mouse coord to worldspace.
ScreenToWorld(m_mouseX, m_mouseY, &worldPos);

XMVECTOR RayDir = worldPos - RayOrigin;
RayDir = XMVector3Normalize(RayDir); //And finally the normalized direction vector

```

And this is the HLSL code:

```
cbuffer RayBuffer
{
    float3 RayOrigin;
    float3 RayDir;
    matrix view;
};

struct ComputeInputType
{
    float3 position : POSITION;
    float2 tex : TEXCOORD;
    float3 normal : NORMAL;
};

struct ComputeOutputType
{
    float distance;
    float3 position;
};

static const uint ThreadSize = 32;

StructuredBuffer<ComputeInputType> BufferIn : register(t0);
RWStructuredBuffer<ComputeOutputType> BufferOut : register(u0);

[numthreads(ThreadSize, ThreadSize, 1)]
void PickingCSMain(uint3 dispatchThreadID : SV_DispatchThreadID)
{
    float result;
    float3 vertices[3];
    float3 edge[2];

    if (dispatchThreadID.x < 64 && dispatchThreadID.y < 64)
    {
        vertices[0] = BufferIn[(dispatchThreadID.x + dispatchThreadID.y * ThreadSize * 2)].position;
        vertices[1] = BufferIn[(dispatchThreadID.x + (dispatchThreadID.y + 1) * ThreadSize * 2)].position;
        vertices[2] = BufferIn[(dispatchThreadID.x + 1 + (dispatchThreadID.y + 1) * ThreadSize * 2)].position;

        edge[0] = vertices[1].xyz - vertices[0].xyz;
        edge[1] = vertices[2].xyz - vertices[0].xyz;

        float3 normal = normalize(cross(edge[0], edge[1]));
        float b = dot(normal, RayDir);

        float3 w0 = RayOrigin - vertices[0].xyz;
        float a = -dot(normal, w0);
        float t = a / b;

        result = t;

        float3 p = RayOrigin + t * RayDir;
        float uu, uv, vv, wu, wv, inverseD;
        uu = dot(edge[0], edge[0]);
        uv = dot(edge[0], edge[1]);
        vv = dot(edge[1], edge[1]);

        float3 w = p - vertices[0].xyz;
        wu = dot(w, edge[0]);
        wv = dot(w, edge[1]);
        inverseD = uv * uv - uu * vv;
        inverseD = 1.0f / inverseD;

        float u = (uv * wv - vv * wu) * inverseD;
        if (u < 0.0f || u > 1.0f)
        {
            result = -1.0f;
        }

        float v = (uv * wu - uu * wv) * inverseD;
        if (v < 0.0f || (u + v) > 1.0f)
        {
            result = -1.0f;
        }

        BufferOut[(dispatchThreadID.x + dispatchThreadID.y * ThreadSize * 2)].distance = result;
        BufferOut[(dispatchThreadID.x + dispatchThreadID.y * ThreadSize * 2)].position = vertices[0].xyz;
    }
}

```

The result is always -1.0f. I don't get it; I might have made a big mistake, but I can't find where.

Why does my triangle ray intersection test always return -1.0f?

# Answer
I've figured it out, finally. The first mistake i made was that i only tested every second triangle, and the second mistake was that the xyz parameters of the ray direction were offset in the buffer. Not sure how it happened, because I'm pretty sure it was fine earlier. (instead of e.g. (4,5,6) the direction vector on the GPU was (0,4,5). i've added a single float for padding)

It works like a charm now, and it's super fast!

If you took some time to try to help me, I'm sorry to bother you, and thank you for your time!
> 0 votes

---
Tags: hlsl, compute-shader
---


title: Make an animation repeat X times

text:
# Question
Title: Make an animation repeat X times
I am using Unity Mecanim and I would like an animation ( walking animation about 2 seconds longs ) to repeat X times before moving to the next animation. How can I achieve this?

# Answer
You have to :

1. Create an empty state in the Animator (called `Idle` for example), with a transition to your `Walk` state. Uncheck the `Has exit time` of the transition from `Idle` to `Walk` transition, but leave 1 to the transition from `Walk` to `Idle`.
2. Create a `walkCount` integer parameter in the animator and give it the value of your choice (4 if you want your Walk animation to repeat 4 times)
3. Add a new condition between the transition from `Idle` to `Walk` : `walkCount` greater than 0
4. Add a transition between the "Idle" state and your next animation. Add the condition `walkCount` equals 0.
5. Select the `Walk` state and create a new `StateMachineBehaviour` with the following code :

```
using UnityEngine;

public class NAME_OF_YOUR_WALK_STATE: StateMachineBehaviour {

     // OnStateEnter is called when a transition starts and the state machine starts to evaluate this state
    override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) {
        animator.SetInteger( "walkCount", animator.GetInteger("walkCount") - 1 ) ;
    }
}

```

---

EDIT : Summary of the comments and chat :

* 3 states and 4 transitions
* States : \[Idle\] - \[Walk\] - \[NextAnim\]
* Transitions :
    + \[Idle\] → \[Walk\] : No exit time, walkCount \> 0, transition duration = 0
    + \[Walk\] → \[Idle\] : Exit time = 1, walkCount \> 0, transition duration = 0
    + \[Idle\] → \[NextAnim\] : No exit time, walkCount = 0, transition duration = 0
    + \[Walk\] → \[NextAnim\] : Exit time = 1, walkCount = 0, transition duration = 0
> 2 votes

---
Tags: unity, mecanim
---


# Question
Title: SFML Sprite not being rendered when returned from a method
I am trying to use spritesheets in SFML. My Player class inherits from the Creature class which inherits from the Entity class. I only see a white square when I render the player. However, this is not the case when I create the sprite and render it in the same function. It does not work if I return a copy or even a reference or a pointer of the sprite. So, I tried constructing my sprite in the constructor rather than the `init()` method. It still does not work when I return the sprite for drawing via the `draw()` method in entity.cpp. I do not want to load the sprite from the spritesheet in the draw method as that would be fairly inefficient. Please help.

spritehseet.png: https://i.stack.imgur.com/H9JzO.jpg

main.cpp:

```
bool init() {
    /*Code to determine if a player should be added to entities and creatures vectors*/
    case 'P':
                player = new Player(i*64, y*64, 64, 64, sf::IntRect(0, 0, 64, 64), "spritesheet.png", &entities);
                entities.push_back(player);
                creatures.push_back(player);
                break;
 /*more code for quitting and error reporting*/
}

int main() { // vertical sync works well only in full screen mode

    sf::RenderWindow window(sf::VideoMode(0, 0), "My First SFML Game", sf::Style::Fullscreen);
    int frames = 0;
    window.setVerticalSyncEnabled(true);

if(!init()) {
    std::cout << "Could not initialize\n";
    return 1;
}

sf::Clock clock, frameClock;

/*keyboard and event polling code here*/

    if(frameClock.getElapsedTime().asSeconds() >= 1/FPS) {
        update();
        draw(window);
        window.display();
        window.clear();
        frames++;
        frameClock.restart();
    }

    if(clock.getElapsedTime().asSeconds() >= 1) {
        std::cout << frames << " frames per second\n";
        clock.restart();
        frames = 0;
    }
}
    std::cout << "Quitting\n";
    quit();
}

void quit() {
    std::vector<Entity*>::iterator it;
    for(it = entities.begin(); it != entities.end(); it++) {
        delete *it;
        *it = nullptr;
    }
    entities.clear();
    player = nullptr;
    std::vector<Creature*>::iterator it2;
    for(it2 = creatures.begin(); it2 != creatures.end(); it2++) {
        *it2 = nullptr;
    }
}

void update() {
    std::vector<Creature*>::iterator it;
    for(it = creatures.begin(); it != creatures.end(); it++) {
        Creature* creature = *it;
        creature->update();
    }
}

void draw(sf::RenderWindow& window) {
    std::vector<Entity*>::iterator it;
    for(it = entities.begin(); it != entities.end(); it++) {
        Entity* entity = *it;
        window.draw(entity->draw());
    }
}

```

entity.h:

```
#ifndef ENTITY_H
#define ENTITY_H

#include <SFML/Graphics.hpp>

#include <string>

class Entity {
private:
    int _x, _y, _width, _height;
    sf::Sprite _sprite;
public:
    Entity(int x, int y, int width, int height, sf::IntRect rect, std::string path);

int getX() { return _x; }
int getY() { return _y; }
int getWidth() { return _width; }
int getHeight() { return _height; }

void setX(int x) { _x = x; }
void setY(int y) { _y = y; }
void setWidth(int width) { _width = width; }
void setHeight(int height) { _height = height; }

sf::Sprite draw();
};

#endif // ENTITY_H

```

entity.cpp:

```
#include <entity.h>

#include <string>
#include <iostream>

#include <SFML/Graphics.hpp>

Entity::Entity(int x, int y, int width, int height, sf::IntRect rect, std::string path) {
_x = x;
_y = y;
_width = width;
_height = height;
sf::Texture texture;
if(!texture.loadFromFile(path, rect)) std::cout << "Could not load intrect " << rect.left << ", "
                                                                             << rect.top << ", "
                                                                             << rect.width << ", "
                                                                             << rect.height << " from" << path;
else std::cout << "loaded texture\n";
_sprite.setTexture(texture);
}

sf::Sprite Entity::draw() {
_sprite.setPosition(sf::Vector2f(_x, _y));
return _sprite;
}

```

The rest of the constructors don't do anything with the sprite.

# Answer
> 1 votes
See this link: https://www.sfml-dev.org/tutorials/2.4/graphics-sprite.php

You're loading in your `sf::texture` to a variable local to the constructor. When the code block for the constructor has finished running, this variable goes out of scope. When this happens, your `sf::texture` is destroyed, which causes the white square. You need to store the texture in a way that won't let it go out of scope, such as allocating it to the heap.

---
Tags: c++, sprites, sfml, spritesheet
---


title: Getting the angle between three points?

text:
# Question
Title: Getting the angle between three points?
I have three points, A, B and C (stored as Vector2 in Unity). I am trying to find the angle at point B if there were a line AB and and a line BC. I know, this should be a simple google search, and I have found several methods but for some reason, they ALL return totally unexpected results with my data set!

I checked to make sure that the three points I pass to compute the angles are indeed the correct (x,y) coordinates, and that same data is used elsewhere in my code without any problems.

Considering that all functions return strange results, it must be that I am not understanding something here...

here is one formula:

```
Vector2 A = //some vector2.normalized
Vector2 B = //some vector2.normalized
Vector2 C = //some vector2.normalized
float Angle = Mathf.Atan2(B.y - A.y, B.x - A.x) - Mathf.Atan2(B.y - C.y, B.x - C.x);

```

Here's another that I tried where p0,p1,and p2 and just vector2's:

```
function findAngle(p0, p1, p2) {
        var a = Math.pow(p1.x - p0.x, 2) + Math.pow(p1.y - p0.y, 2),
            b = Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2),
            c = Math.pow(p2.x - p0.x, 2) + Math.pow(p2.y - p0.y, 2);
        return Math.acos((a + b - c) / Math.sqrt(4 * a * b));
    }

```

The data is a List of Vector2 control points for creating Bezier curves. I want to calculate the angle between index 0,1,2 then 2,3,4 then 4,5,6 etc. with the middle index as the angle needed.

I understand that both formulas return radians, but converting to degrees returns sometimes 180 for all points even though the points are all different and the angles vary greatly, sometimes 0 (if I switch the points around), and in the case of the atan2 function above, it gives numbers that "look" like angles, but plotting the points, one can see that the angles do not correspond to the visual plots... I must be doing something very dumb here and I'm not great with math so any hand-holding is much appreciated.

Here's an image of the output:

# Answer
Just use the built-in Angle method:

`Vector2.Angle(A - B, C - B);`

From the docs:

## Vector2.Angle

`public static float Angle(Vector2 from, Vector2 to);`

**Description**

Returns the angle in degrees between `from` and `to`.
> 4 votes

---
Tags: unity, mathematics
---


# Question
Title: Set rotation on single axis with provided angle using Quaternion
I am using a Quaternion to represent the rotation of some object, and I would like to allow the user to rotate it about a single axis at a time using textbox, so he would write the angle that the object is rotated by (ex. at X-axis), then the object rotation is set to that rotation.
I know that, this operation `q1 * q` will rotate `q` by `q1`, but I don't know how to set the rotation at a single axis, Could any one help me to complete this function?

```
public void SetRotationX(float Angle)
{

}

```

# Answer
Based on your function naming, I take it your just trying to **set** the rotation to a completely new rotation along that angle, as opposed to *offsetting* the rotation by a set amount.

In this case, rather than concatenating a quaternion to the current one, you can just create a new quaternion entirely. Note that you'll still probably want to pass in an `x`, `y` and `z` value to the function, relating to the other text boxes, or the current rotations along those angles.

Here are the outlines for the formulae to working out each axis of a quaternion, assuming no prior code is in place to create these *Euler* conversions already (note, pseudocode to avoid language issues):

```
void EulerAnglesToQuaternion( Quaternion q , double x , double y , double z )
{
    double cx = cos(x*0.5);
    double cy = cos(y*0.5);
    double cz = cos(z*0.5);
    double sx = sin(x*0.5);
    double sy = sin(y*0.5);
    double sz = sin(z*0.5);

    q.w = (cz*cx*cy)+(sz*sx*sy);
    q.x = (cz*sx*cy)-(sz*cx*sy);
    q.y = (cz*cx*sy)+(sz*sx*cy);
    q.z = (sz*cx*cy)-(cz*sx*sy);
}

```
> 1 votes

# Answer
Going from the definition of quaternions as 3D rotations, we can represent a rotation about an arbitrary 3D axis by taking a unit vector in that direction, scaling it by the sine of half the angle of rotation, and using it as the 3 imaginary components of a quaternion. The remaining real component is then the cosine of half the angle, to keep the quaternion of unit length.

```
Quaternion AngleAxis(Vector3 axis, float angle) {

   Vector3 imaginary = axis.normalized * sin(angle/2f);

   Quaternion q;
   q.x = imaginary.x;
   q.y = imaginary.y;
   q.z = imaginary.z;

   q.w = cos(angle/2f);

   return q;
}

```

Rotating around just the x axis is then a simple special case:

```
Quaternion RotationAroundX(float angle) {

    // Equivalent to AngleAxis(new Vector3(1, 0, 0), angle)

    Quaternion q;
    q.x = sin(angle/2f);
    q.y = 0f;
    q.z = 0f;
    q.w = cos(angle/2f);

    return q;
}

```
> 1 votes

---
Tags: quaternion
---


# Question
Title: How can I use vibration of an iPhone for my HTML / Javascript game?
I'm building a web game. I'm trying to use the **iPhone's vibration functionality**. How would I go about doing this seeing I want to package and **deploy** this game **to the App Store**. Is there a secured way to do this?

# Answer
As you have found out, the W3C Vibration API is not supported in the iOS Safari browser (as reported here: https://caniuse.com/#feat=vibration).

However, you've pointed out that you plan to package your app for the iOS App Store. *To do this, you'll need to package your "web game" into an appropriate native container for installation on the phone*.

You could try to write your own app using the WKWebView component and catching JavaScript events to handle the vibration function natively, but there are already several app frameworks that do that for you. Each of them supports accessing the phone's vibration function, either from JavaScript or via native code. I'd recommend experimenting with them both and going with whichever works best for you:

* Adobe PhoneGap
* React Native
> 7 votes

---
Tags: javascript, html5, iphone
---


title: How to increase render distance?

text:
# Question
Title: How to increase render distance?
I've been trying to find the source of why my render distance is so low (I'm new at using LWJGL and don't know the complete basics yet) and I believe it falls down into this code. My idea for my game (Well, this is more of a practice run to get used to coding 3D games.) is going to be a small island with a size of around 800 which seems extremely low however it is only loading a small portion which I'd estimate to be 600. The code for my MasterRenderer class is below. createProjectionMatrix() is called in the constructor and prepare() is called at the beginning of every render.

```
private static final float FOV = 70;
private static final float NEAR_PLANE = 0.01f;
private static final float FAR_PLANE = 1000f;

public void prepare() {
    GL11.glEnable(GL11.GL_DEPTH_TEST);
    GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
    GL11.glClearColor(0.49f, 89f, 0.98f, 1);
}

private void createProjectionMatrix() {
    float aspectRatio = (float) Display.getWidth() / (float) Display.getHeight();
    float y_scale = (float) ((1f / Math.tan(Math.toRadians(FOV / 2f))) * aspectRatio);
    float x_scale = y_scale / aspectRatio;
    float frustum_length = (FAR_PLANE - NEAR_PLANE);

    projectionMatrix = new Matrix4f();
    projectionMatrix.m00 = x_scale;
    projectionMatrix.m11 = y_scale;
    projectionMatrix.m22 = -((FAR_PLANE + NEAR_PLANE) / frustum_length);
    projectionMatrix.m23 = -1;
    projectionMatrix.m32 = -((2 * NEAR_PLANE * FAR_PLANE) / frustum_length);
    projectionMatrix.m33 = 0;
}

```

I've tried altering the FAR\_PLANE and NEAR\_PLANE with no results other than some minor bugs with changing the NEAR\_PLANE to a small number.

# Answer
> I have discovered the problem - my skybox was cutting out the terrain prematurely. A simple increase in the size of said skybox fixed the issue.

No!

First render your skybox, then clear the depth bit after rendering the skybox, and finally render everything else. That way the depth of the skybox won't affect the scene.

**Note**: I am thinking on the old pipeline, thinking on shaders is still alien to me.
> 0 votes

# Answer
I have discovered the problem - my skybox was cutting out the terrain prematurely. A simple increase in the size of said skybox fixed the issue.
> 0 votes

---
Tags: 3d, rendering, lwjgl
---


# Question
Title: collisions: How to handle contact constraints for a rigidbody constrained to a line segment
I'm trying to come up with a strategy to handle a situation in 2D, where a rigidbody moves along a straight line segment, and can collide with other similar bodies and also static tiles.

A naive approach was to handle collisions by projecting the displacement vectors onto the line segment (worked ok for aabb), and then at the end snap the position of the rigidbody back to the line, which had lots of conflicts.

I'm trying to implement impulse based physics, so far only handling contacts, and unsure how to both constrain the rigidbody to a line segment and handle contacts at the same time. Or is it better to do in two separate phases. It's probably easier to allow some displacement from the line and then gradually move the body back to it. Any suggestions?

# Answer
The solution I went with was to treat this like a contact constraint, if the center of the object went beyond either end of the line segment or if it was displaced laterally from the line then I just set a new contact with a normal pointing perpendicularly towards the line or pointing (anti-)parallel to the line. Then solve it together with the other contacts.

```
setDistanceToPath(platform: Platform, manifold: ContactManifold) {
    let p = platform.rb.position;
    let ap = Vec2.subtract(p, platform.path.start);
    let d = platform.path.direction;
    let ap_d = Vec2.dot(ap, d);

    let right = Vec2.perRight(d);
    let dp = Vec2.dot(right, ap);

    const setLateralContact = (dp: number) => {
        if (dp < 0) {
            manifold.setContact(platform.rb.position, -dp, right);
        }
        else if (dp > 0) {
            manifold.setContact(platform.rb.position, dp, Vec2.perLeft(d));
        }
        else {
            manifold.clearContacts();
        }
    };

    if (ap_d < 0) {
        if (Math.abs(dp) > -ap_d) {
            setLateralContact(dp);
        }
        else {
            manifold.setContact(platform.rb.position, -ap_d, d);
        }
    }
    else {
        let bp = Vec2.subtract(p, platform.path.end);
        let inv_d = Vec2.inverse(d);
        let bp_d = Vec2.dot(bp, inv_d);

        if (bp_d < 0) {
            if (Math.abs(dp) > -bp_d) {
                setLateralContact(dp);
            }
            else {
                manifold.setContact(platform.rb.position, -bp_d, inv_d);
            }
        }
        else {
            setLateralContact(dp);
        }
    }
};

```
> 0 votes

---
Tags: physics, collision-resolution
---


# Question
Title: How to make a delay between animations in mecanim?
How to make a delay between animations in mecanim? For example after anim1 ends then there will be a delay then anim2 starts. I tried to increase the exit time but it doesnt work.

# Answer
Another way is to extend the Exit Time of the initial state, longer than the clip duration, unless the clip is in loop mode (or disabling the loop via code at a specific point).

I usually prefer this way because adding states in the Mecanim creates visual cluttering, due to the impossibility so far to zoom out in the Animator window. :|
> 2 votes

# Answer
You will need an"intermediate" state (I will call "Idle") without any motion and a speed set to 1

* States : \[State1\] → \[Idle\] → \[State2\]
* Transitions :
    + \[State1\] → \[Idle\] : Exit time = 1 ; transition duration = 0 ; no condition
    + \[Idle\] → \[State2\] : Exit time = delay ; transition duration = 0 ; no condition
> 0 votes

---
Tags: unity, mecanim
---