# Question
Title: Trying to use yield to wait for a few seconds to avoid the sounds from Interfering with each other
Ok so when my player hits a wall (Enemy tag). My player is destroyed after a certain amount of time. During this time, I disabled the mesh renderer on impact so it "appears" as if the player is destroyed.

I have some sounds I want to play upon impact. One is 'game over" sound and one is an "explosion sound".

right now, when they play at the same time, they interfere with each other, causing the game over not to be heard correctly.

I wanted to delay the output of "game over" by 3 seconds. So the explosion is over. Play the 'Game over sound' and then destroy the player.

This is my code so far, but the compiler tells me that now OnTriggerEnter cannot be an iterator block now that I have a yield function. Is there any way to just delay the output of the game over sound without creating a whole new function for the game over sound and using Play Delayed?

and if I do have to use Play delayed, how do I set the volume of the sound? as right now I am using PlayOneShot

```
     // function to detect whether collision is with a pick-up cube or an emeny wall.
void OnTriggerEnter(Collider other)
{
    if (other.gameObject.CompareTag("PickUp"))
    {
        // if pick-up object. Pick it up!
        float vol = Random.Range(volLowRange, volHighRange);
        playerSource.PlayOneShot(coinSound, vol);
        other.gameObject.SetActive(false);// other.gameObject should destroy here by the way.
        getCount = GameObject.FindGameObjectsWithTag("PickUp");
        count = getCount.Length;
        countCollected = countCollected + 1;
        SetCountText();
        if (count < 10)
        {
            // spawns new pick-up objects
            Invoke("SpawnObject", 2.0f);
        }
    }
    if (other.gameObject.tag == "Enemy")
    {
        // if enemy wall... kill the player it is game over
        rend.enabled = false;
        float vol = Random.Range(volLowRange, volHighRange);
        playerSource.PlayOneShot(deathSound, voldeath);
        playerSource.PlayOneShot(explosion, volex);
        yield return new WaitForSeconds (3);
        playerSource.PlayOneShot(gameOver, volgo);
        deathText.text = "GAME OVER!";
        Destroy(Player.gameObject, deathTime);
    }
}

```

Note: before the addition of yield the code runs perfectly and does everything I want it to.

Thanks for any help you can provide

# Answer
You will need to use IEnumerator to be able to use yield. This can be achieved by moving your "death code" into a method and using Coroutines. Make sure you disable the collider to prevent the trigger from executing more than once.

```
// function to detect whether collision is with a pick-up cube or an emeny wall.
    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag("PickUp"))
        {
            // if pick-up object. Pick it up!
            float vol = Random.Range(volLowRange, volHighRange);
            playerSource.PlayOneShot(coinSound, vol);
            other.gameObject.SetActive(false);// other.gameObject should destroy here by the way.
            getCount = GameObject.FindGameObjectsWithTag("PickUp");
            count = getCount.Length;
            countCollected = countCollected + 1;
            SetCountText();
            if (count < 10)
            {
                // spawns new pick-up objects
                Invoke("SpawnObject", 2.0f);
            }
        }
        if (other.gameObject.tag == "Enemy")
        {
            StartCoroutine ("DieRoutine");
        }
    }

    IEnumerator DieRoutine()
    {
        Debug.Log (string.Format ("Die: {0}", "Start"));

        // if enemy wall... kill the player it is game over
        rend.enabled = false;
        float vol = Random.Range(volLowRange, volHighRange);
        playerSource.PlayOneShot(deathSound, voldeath);
        playerSource.PlayOneShot(explosion, volex);
        yield return new WaitForSeconds (3);

        Debug.Log (string.Format ("Die: {0}", "Complete"));

        playerSource.PlayOneShot(gameOver, volgo);
        deathText.text = "GAME OVER!";
        Destroy(Player.gameObject, deathTime);
    }

```
> 1 votes

# Answer
You already did the trick, use it here once again. To do in that way you have to create your own SoundManager (that is not that big deal, you can do it) and handle everything you required. Well for now you can try

```
if (other.gameObject.tag == "Enemy")
    {
        // if enemy wall... kill the player it is game over
        rend.enabled = false;
        float vol = Random.Range(volLowRange, volHighRange);
        playerSource.PlayOneShot(deathSound, voldeath);
        playerSource.PlayOneShot(explosion, volex);
        Invoke("GameOver",3.0f);
    }

void GameOver()
{
    playerSource.PlayOneShot(gameOver, volgo);
    deathText.text = "GAME OVER!";
    Destroy(Player.gameObject, deathTime);
}

```
> 1 votes

# Answer
If you want wait for thing you can use StartCoroutine.So you need time for waiting , but we haven't time here.right ! you can wait until `audiosource.isPlaying` equal to true.In below code I try play all sound In same time by for loop but you hear sound when finish before sound because I use StartCoroutine.

```
using UnityEngine;
using System.Collections;

[RequireComponent(typeof(AudioSource))] //Attach AudioSource component
public class InterferingManager: MonoBehaviour {
    public AudioClip[] audioclips = new AudioClip[5];//audios
    private AudioSource audiosource;// audiosource component

    void Awake()
    {
        audiosource = GetComponent<AudioSource>();
    }
    void Start()
    {
        //when you want test this audiosource's clip shouldn't be null so I put it default sound
        audiosource.clip = audioclips[0];
        audiosource.Play();

        TestDelaying();// call function.I want test Wait until audio is finished
    }

    void TestDelaying () {
        for (int i = 0; i < audioclips.Length; i++)
        {
            StartCoroutine(WaitForSound(audioclips[i]));//pass sounds to `WaitForSound` for Interfering them with each other
        }
    }

    public IEnumerator WaitForSound(AudioClip Sound)
    {
        yield return new WaitWhile(() => audiosource.isPlaying == true); //if audio finished so it should play next audio
        audiosource.clip = Sound;
        audiosource.Play();
    }
}

```
> 0 votes

---
Tags: c#, software-engineering, unity, audio
---


title: Looking for a dirty pseudo 3D trick

text:
# Question
Title: Looking for a dirty pseudo 3D trick
To be specific I want to do bad sprite scaling like in Operation Thunderbolt. For some reason I'm getting it all wrong so far.

I started over from scratch and I've literally got a sprite that follows the mouse and scales larger as the Y position increases. I've got a horizon line at y128. I don't want the sprite to start scaling until it passes the horizon. I've been through countless examples of pseudo 3d but I want to start simple, one thing at a time so I can get the maths right in my head :S

Right now the code is:

**set scale: Sprite.Y / Scalerate**

Which keeps the scaling even as I move the mouse up and down but now I want to limit it to only growing after the horizon at 128. As if a person is walking down the road at you, or maybe an equation that let's you set a start and end point on the y axis.

I'm totally new at the sprite scaling stuff!

# Answer
Wouldn't something like this do?

```
if y > 128 then:
    set scale: (Sprite.Y - 128) / Scalerate

```
> 2 votes

---
Tags: sprites, scale
---


# Question
Title: Enable debug to show values in the flowchart editor
I am starting to learn to use CryEngine V, and have found documentation lacking, in some aspects.

Following the initial game logic tutorials, I observe the instructor selecting "debug" from the menu. The flow chart instantly comes to life, displaying all of the values going in and out of each function.

Unfortunately, when I follow this instruction, nothing happens. Clicking on the "debug" button results in no apparent action. I have looked around for further instructions, but all I can find is the general assumption that it will just work, without any additional action. As you can see from my recording, this assumption is not accurate to my situation.

Without this working, it is rather difficult to even know if I am following the flowchart creation process properly. How do I enable visual debug in the flowchart editor?

# Answer
> 0 votes
While the tutorials describe "running debug" while simply selecting the button, it appears they are taking additional steps off-screen.

Selecting "debug" does not display debug information as is shown in the tutorials. You still must run the game, either directly, or through enabling physics and AI.

---
Tags: debugging, cryengine
---


title: Problem with RGBA sampled shadowmap

text:
# Question
Title: Problem with RGBA sampled shadowmap
I'm having a problem with the generation of a shadowmap that is converted to RGBA. The following glsl code is used to put the depth into the depthbuffer :

```
/**
 * float/rgba8 encoding/decoding so that we can use an RGBA8
 * shadow map instead of floating point render targets which might
 * not be supported everywhere
 *
 * http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
 * http://www.gamedev.net/topic/486847-encoding-16-and-32-bit-floating-point-value-into-rgba-byte-texture/
 *
 * Only store values between 0.0 and 1.
 */
vec4 encodeDepth(float floatValue) {
    const float toFixed = 255.0 / 256;
    vec4 comp;
    comp.r = fract(floatValue * toFixed * 1);
    comp.g = fract(floatValue * toFixed * 255);
    comp.b = fract(floatValue * toFixed * 255 * 255);
    comp.a = fract(floatValue * toFixed * 255 * 255 * 255);
    return comp;
}

float decodeDepth(vec4 rgba) {
    const float fromFixed = 256.0 / 255;
    float val = rgba.r * fromFixed / (1);
    val += rgba.g * fromFixed / (255);
    val += rgba.b * fromFixed / (255 * 255);
    val += rgba.a * fromFixed / (255 * 255 * 255);
    return val;
}

```

The code that creates the depth buffer is the following:

```
bool DepthBuffer::init(const glm::ivec2& dimension) {
    _dimension = dimension;

    glGenFramebuffers(1, &_fbo);
    GL_setName(GL_FRAMEBUFFER, _fbo, "depthfbo");
    ScopedFrameBuffer scopedFrameBuffer(_fbo);

    glGenTextures(1, &_depthTexture);
    GL_setName(GL_TEXTURE, _depthTexture, "depthtexture");
    glBindTexture(GL_TEXTURE_2D, _depthTexture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, dimension.x, dimension.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
    glBindTexture(GL_TEXTURE_2D, 0);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _depthTexture, 0);
    GL_checkError();

    const GLenum drawBuffers[] = { GL_COLOR_ATTACHMENT0 };
    glDrawBuffers(SDL_arraysize(drawBuffers), drawBuffers);

    const GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
    if (status != GL_FRAMEBUFFER_COMPLETE) {
        Log::error("FB error, status: %i", (int)status);
        return false;
    }

    return true;
}

```

I am calculating the light space positions in the worlds vertex shader like this:

```
v_lightspacepos = u_light * worldpos_vertex;

```

u\_light is a the projection\*view matrix of the sun light camera.

v\_lightspacepos is then used to perform the shadow sampler lookup via:

```
vec2 calculateShadowUV() {
    // convert from -1, 1 to tex coords in the range 0, 1
    vec2 uv = v_lightspacepos.xy / v_lightspacepos.w;
    return uv * 0.5 + 0.5;
}

float calculateShadow(float ndotl) {
    vec2 smUV = calculateShadowUV();
    float depth = v_lightspacepos.z;
    return sampleShadowPCF(u_shadowmap, smUV, u_screensize, depth, ndotl);
}

```

calculateShadow is then used like this:

```
float ndotl = dot(normal, u_lightdir);
float shadow = calculateShadow(ndotl);

```

The sun light camera projection matrix is calculated like this:

```
static const glm::mat4 normalizeDepth = glm::scale(glm::translate(glm::mat4(), glm::backward), glm::vec3(1.0f, 1.0f, 0.5f));
_projectionMatrix = normalizeDepth * glm::ortho(bbox.getMinX(), bbox.getMaxX(), bbox.getMinZ(), bbox.getMaxZ(), nearPlane(), farPlane());

```

Does anyone see anything wrong here? I'm debugging this code since days now and am not able to identify the problem. See the attached screenshot for the error. The black area will move with the camera. Shadows are (somewhat) working except for the black area and the "wrong" shadowmap.

# Answer
> 1 votes
I'm not sure Why are you using RGBA8 for a shadow map... The shadow map algorithm relies on the depth buffer, so you can initialize a texture of type GL\_DEPTH\_COMPONENT and if you want floating point you can GL\_DEPTH\_COMPONENT32F, this should be supported on most platforms including OpenGL ES 3 (at least on ARM GPUs)

I would also advise you to use GL\_COMPARE\_REF\_TO\_TEXTURE when doing the shadow map so you don't have to do the actual comparison yourself in shader code. The superbible explains shadow mapping and provides code, it can also be found here https://github.com/openglsuperbible/sb7code/blob/master/src/shadowmapping/shadowmapping.cpp

---
Tags: opengl, mathematics, glsl, shadow-mapping
---


# Question
Title: Syncing Sprites themselves over a Network
Ok, just found out I can't use \[SyncVar\] for a sprite gameobject. Furthermore that, \[SyncVar\] works only on simple values. My question is How would I go about syncing a Sprite over a network?

To explain the context for where I need it, I have a code for players to select an Avatar to play with. Player 'A' and 'B' are able to change their avatars in their own respective device. But the changes made by player 'A' are not reflected in 'B' and vice versa.

**So the question is How do I sync a Sprite GameObject?**

**Note: I am using unity 5.4 and unity's default multiplayer system.**

# Answer
> 0 votes
It seems like you should not be changing the sprite straight away, instead, change some variable that would represent the avatar, and sync that variable over, then it's a matter of making sure that proper avatar sprites show up based on that variable.

So let's say it's a character selection screen, you have `Player1` and `Player2`, their avatar display would have a variable called `selectedCharacter`, when a player changes character, this updates the `selectedCharacter` variable and syncs it, now it's up to each client to display a sprite based on that variable.

---
Tags: 2d, unity, sprites, multiplayer, synchronization
---


# Question
Title: Run Game on Android Even Removed from Application stack (Unity)
I am trying to develop a single demo in unity using c#, where I've put counter for minutes and seconds. When the game was in background, still it should keep counting minutes and seconds. After research on google, I've found a function to keep running application in background.

```
Application.runInBackground=true;

```

This works exactly when application exist in stack. As soon as it is removed from application stack, it stops every scripts. What should i implement to keep running application all time in background, even when it is not in application stack.

# Answer
> -1 votes
I don't think you'll be able to do this. For performance reasons and to save battery Android will stop every app that is not active and it happens by design. Even if you managed to find a way to do this, your app would drain battery as if it were active so nobody would use it for long :).

If all you need is to do some action after few minutes you can use Android timers to do that - the same way as mail clients check for incoming messages. If you want to get the time between runs of your application you can store current time on exit and compute the delta on the next run, and so on - for most of you needs there is probably some Android-specific way to do this.

BTW: Unity is a generic engine not designed for any specific platform but it needs to work under limits of any platform you target. Because of this not every functionality will always work as you expect - that's the cause of your `runInBackground` issue. Looking for a way to solve such issue don't start from Unity but look at Android SDK to find some Android specific solution, when you have one then you can check how you could do this in Unity.

---
Tags: unity
---


title: How do obj file faces work

text:
# Question
Title: How do obj file faces work
Specifically, I have a faces specified 'f v1/vt1 ... etc '. I understand that there are 3 vertices specified with respective texture coordinates, but how do those 3 textures end up being rendered onto a triangular face?

# Answer
> 3 votes
You don't have 3 textures per face but 3 points on one texture. Connecting them with lines you'll get a triangle on your texture, and this is the exact part that will be used on your face when rendered.

You may look at this answer.

---
Tags: obj
---


# Question
Title: When should one use LibGDX's FrameBuffer and when SpriteCache?
In my game I have some graphics that I want to draw once and only redraw whenever something is changed by the player. Now, I'm wondering, whether I should use the `FrameBuffer` or the `SpriteCache` class. I know that a framebuffer is much more general concept and also works for 3D, while a `SpriteCache` is only for 2D. However it seems to me that they would both make sense in my use case, so I'm wondering..

**What are the differences, drawbacks and advantages of using one over the other?**

# Answer
So, I asked this on the #libgdx IRC channel and got the following response:

> Whereas you may be able to achieve a similar effect with both, they are very different things. SpriteCache is for cacheing sprite geometry on the gpu, allowing you to draw the cache, or elements of the cache without the costly upload to the gpu. All the geometry is still intact. FrameBuffers are render targets, you render to them. You are limited by texture max sizes, and it only contains the texture information, it has no concept of what was rendered to it.
>
> SpriteCache is great for when you have alots of static sprites that dont move, for example a tiled map layer.
>
> FrameBuffers are good for rendering to texture at runtime, for example if you have a widget that is costly to create, but it doesn't change every frame, you can render it to a texture (framebuffer), and simply render that generated asset as a simple quad. Its also good for post processing, or deferred rendering paths.
>
> \[With a FrameBuffer\] you lose the information about the sprites also, so if you had a special shader that did some fancy things with the geometry, you would lose your tile vertices
> 2 votes

---
Tags: libgdx, performance
---


# Question
Title: Add and remove tiles? Or better to have them all loaded off screen?
Which method do you expect would have better performance when stressed? It's a 2D tile map where the camera has view of a small portion of the map. As I pan up/down/left/right, should I be adding and removing tiles from the stage as needed? or have them loaded, offstage, and just change their x/y coords as needed?

I'm using AS3 to code this and I have it working fine. And I know it's not wise to try to optimize early, but since I'm very new at this, I thought maybe someone already knows if one is usually better.

# Answer
In a case like this, you are going to want to Pool your world tiles. The idea is to pre-load a fixed amount of tiles that you will be re-using during the rendering of your world.

When setting a tile into the world, you would typically set certain properties such as its position and texture. The rest of the object is already ready to go in memory.

The idea is to try to retain some tiles on the screen and only return them into your Pool when they are far enough. This way, if you revisit an area that was already set, you probably do not have to process as many tiles.

Some sample code that was used to achieve the effect in the gif above:

```
List<Tile> LoadedTiles = new List<Tile>();

public void Refresh()
{
    // Determine your start/end X and Y coordinates (viewable area)
    // Make sure to add some padding to ensure you don't see any flickering on the sides
    int startx = View.x < 0 ? (int)(View.x + (-View.x % 1)) : (int)(View.x - (View.x % 1));
    int starty = View.y < 0 ? (int)(View.y + (-View.y % 1)) : (int)(View.y - (View.y % 1));
    startx -= 1;
    starty += 1;
    int endx = startx + (int)(View.width) + 2;
    int endy = starty - (int)(View.height) - 2;

    // Keep track of visible tiles in this refresh
    HashSet<Tile> inCurrentView = new HashSet<Tile>();

     // Loop through all the tile indices inside of our current view port
    for (int i = startx; i <= endx; i += 1)
    {
        for (int j = starty; j >= endy; j -= 1)
        {
            int x = i;
            int y = j;

            // Make sure your index values are not negative.
            // In this case we are wrapping the world around on the X-axis.  If you are not wrapping, you need
            // to figure out coordinate system that will not result in negative values.
            x = MathHelper.Mod (x, Generator.Width);
            y = MathHelper.Mod (y, Generator.Height);

            // Fetch the tile data at this index - Store in our hashset
            Tile tile = Generator.GetTile (x, y);
            inCurrentView.Add(tile);

            // If the tile being processed is not loaded, then get a Tile from our Pool and load it into view.
            if (!LoadedTiles.Contains(tile))
            {
                if (tile.PoolableGameObject.Item == null)
                {
                    if (TilePool.AvailableCount > 0)
                    {
                        // Get a tile GameObject from our Tile Pool
                        Pool<PoolableGameObject>.Node node = TilePool.Get();
                        node.Item.Set(tile, new Vector2(i, j));
                        LoadedTiles.Add(tile);
                    }
                }
            }
            else {
                // tile already loaded, refresh it
                tile.PoolableGameObject.Item.Set(tile, new Vector2(i, j));
            }
        }
    }

    // Get list of Tiles that are currently outside our view
    // This will remove every single tile that is not in view.
    // You can refine this to only return tiles when a lower threshold of tiles remaining is met.
    List<Tile> toRemove = new List<Tile>();
    for (int i = 0; i < LoadedTiles.Count; i++) {
        Tile tile = LoadedTiles[i];
        if (!inCurrentView.Contains(tile))
            toRemove.Add(tile);
    }

    // Return tiles that are no longer in view back into our Pool to be re-used
    for (int i = 0; i < toRemove.Count; i++) {
        Tile tile = toRemove[i];
        LoadedTiles.Remove(tile);
        TilePool.Return(tile.PoolableGameObject);
    }

}

```
> 6 votes

# Answer
I personally store my map data in a 2D array.

`map[y][x]`

It doesn't take up that much memory space. I mean, considering the amount of RAM current machines have, a few MBs (10-20 usually, but it depends on the size of the map, of course) is not a big deal.

However I had concerns regarding the CPU usage. When rendering the map, I simply set the code to only render the tiles which are visible. Some pseudo code:

```
for(int i=currentPosY-someAmount;i<=currentPosY+someAmount;i++){
    for(int y=currentPosX-someAmount;y<=currentPosX+someAmount;y++){
       render(map[y][i]);
    }
}

```

With this the CPU usage is around 2-3% from 4-6% (if I remember correctly the original amount).
> 2 votes

---
Tags: 2d, optimization, tiles
---


# Question
Title: Standard unit value for 3d game character height?
Basically I'm building a first person shooter game using DirectX9. And now, I'm working on the modeling side. But before I start modeling, I have to make sure that I create all the models with accurate size. So it doesn't look too big or too small in the game. But I'm having problem deciding the characters height value including the main character and the NPC characters. I think it would be easy to measure other models/houses/walls/doors size if I have the characters height. Otherwise, I will messed up everything.

I assume that all the characters are 1.8 meter in height, including the main one. Though not sure that how to represent that value in DirectX vector ( DirectX unit == ? ) but If I set the camera height that value, it looks too low from the ground ( in my eyes ). Now what is the next value? Should I switch to fit? Which would very big value like 6. Or is there any standard value for that case which I don't know?

I hope you guys have understand my situation. Actually I'm very new to this kind of stuffs. So hopping to get some help or suggestion which would be great for me.

# Answer
There is no "standard," although for reasons of numerical stability you will want to choose some conversation factor between modeling and rendering units that keeps them small (don't make characters 10,000,000 units tall, prefer to make them more like 1 to 10 units tall).

Pick values that work for you, your pipeline, and your game. This means adjusting the modeling units (maybe on export) or rendering units (by adjusting projections and whatnot) accordingly until you find a balance that makes sense for your game and how you think about the problems space.
> 4 votes

---
Tags: directx9, first-person-shooter, 3d-modeling
---


title: Unity - Extending native components

text:
# Question
Title: Unity - Extending native components
I was wondering if it was possible to use the existing native components inside Unity to extend them, and create my own.

For instance, if I wanted to create a component called `Hurtbox`, could I maybe do something like this?

```
class Hurtbox : BoxCollider2D { ... }

```

That would allow me to use the existing logic of the component and enhance it for my purposes.

Currently I have a separated `BoxCollider2D` and a `Hurtbox` components. The latter uses the former, but I thought if I managed to combine them both in a single one, it would be more elegant.

Is it doable? How?

# Answer
It's absolutely possible to extend existing components in the way you describe. Take for example my extension to add a onHold event to the normal unity button.

```
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine.Events;
[AddComponentMenu("UI/Hold Button")]
public class HoldButton : Button
{
    private bool isBeingPressed;
    private float currTime;
    private static float TimeMax = 1;
    private bool startTimer;
    public ButtonHoldEvent onHold { get; set; }
    public override void OnPointerDown(PointerEventData eventData)
    {
        startTimer = true;
        currTime = 0;
    }
    public override void OnPointerUp(PointerEventData eventData)
    {
        startTimer = false;
        currTime = 0;
        isBeingPressed = false;
    }
    void Update()
    {
      if(startTimer)
        {
            currTime += Time.deltaTime;
            if(currTime >= TimeMax)
            {
                isBeingPressed = true;
            }else
            {
                isBeingPressed = false;
            }
        }
        if (isBeingPressed)
        {
            onHold.Invoke();
        }
    }
    public class ButtonHoldEvent : UnityEvent
    {
        public ButtonHoldEvent() : base()
        {

        }
    }
}

```

With this code I get all the features of a normal button with the added onHold functionality that I needed.
> 3 votes

# Answer
It is possible, but I wouldn't take that approach, for two main reasons:

1. If Unity folks change some underlying implementation later on, it may break functionality.
2. You would probably need a custom editor as well.

But instead, you can make custom components and add `RequireComponent` attribute at the top of your class. You will eventually end up with two components instead of a single extended one (*and a bit of tight coupling*), but you will save yourself from some headaches in the long run.
> 2 votes

---
Tags: unity
---


title: (Unity 5) Weird Touch Behavior

text:
# Question
Title: (Unity 5) Weird Touch Behavior
In my (Google Cardboard) Android app I would like to make my camera move on Touch. That movement state should be controlled via a "switch", so when I touch the screen the camera starts to move and when I tap again it stops. To achieve that I appended this script to the camera:

```
using UnityEngine;
using System.Collections;

public class TapControl : MonoBehaviour {

public float speed;
public int state = 0;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if (Input.GetTouch(0).phase == TouchPhase.Began)
    {
        state += 1;
    }
    if (state % 2 == 0)
    {
        transform.Translate(Vector3.forward * speed * Time.deltaTime);
        }
    }
}

```

The state-integer increases every touch. But nonethless, the camera's behavior can be described as a "hold-touch to move" when the state-variable is even.

So, to make it short: Can anyone detect any programming mistakes i made that could cause this strange behavior?

# Answer
Try changing your state integer into a state boolean, as below.

\[Edit\] I added the block to make sure the touch count is greater than zero. All sample code I read does this.

Also, your speed in your code is zero. Just making sure you initialized it to a value.

```
using UnityEngine;
using System.Collections;

public class TapControl : MonoBehaviour {

    public float speed;
    public bool isCameraMoving = false;

    // Update is called once per frame
    void Update () {
        if (Input.touchCount > 0)
        {
            if (Input.GetTouch(0).phase == TouchPhase.Began)
            {
                isCameraMoving = !isCameraMoving; // Toggle moving state
            }
        }

        if (isCameraMoving)
        {
            transform.Translate(Vector3.forward * speed * Time.deltaTime);
        }
    }
}

```
> 1 votes

---
Tags: android, unity, touch
---


# Question
Title: How to automatically delete an object in Unity?
I am new to unity and the other day I was wondering that it would be useful if I could instantiate some objects in my game scene and, as they get instantiated, make it so that they get automatically deleted after a period of time.

I thought about automatically adding a Destroy script to them so that they could be deleted after a period of time using:

```
Destroy(Gameobject, time);

```

I'm not sure that's what I need, and if it is I don't know how I'd go about it.

How could I make it so that my objects get automatically deleted after some time, in the context that I'll have a lot of them?

# Answer
> 2 votes
It is fairly easy to add any component to a game object on instantiation, including classes, using `GameObject.AddComponent<T>()`. If your script is good to go from the start, you can do this ***inline***. If you need to do anything with your script after adding it, you can ***create references*** as you instantiate.

*For further clarity*, note that I say ***classes*** instead of *scripts*. When you create a script, a *class* is created inside that script with the same name. When you drag the script on to an object in the inspector, this is the class that is added. *This is not a coincidence*. While a compiler will not complain if you proceed to change the name of that class, Unity will complain that it can no longer find the original class, and start throwing errors. What you may not realise is that you are free to create additional classes after the first, within the same script file. While you can not simply "drag and drop" these additional classes on to an object via the Unity inspector, you can still add them to a game object using `AddComponent<>`.

### Adding a class inline

Setting it up inline is quicker, but it leaves us with no reference to the game object nor the object destroyer we have created. If they are designed to run by themselves, without need of setup once they have been instantiated, we are fine. If you should need to reference either, later, read below for creating references.

```
using UnityEngine;

public Class ObjectCreator : MonoBehaviour
{
    public GameObject blueprint;

    public void CreateNewGameObject()
    {
        Instantiate<GameObject>(blueprint).AddComponent<ObjectDestroyer>();
    }

}

public Class ObjectDestroyer : MonoBehaviour
{
    public void Destroy(){...}
}

```

### Adding and referencing the class

Sometimes just creating the class won't cut it. The same may go for your instantiated game object. If we create them inline, as the example above shows, we do not create any reference for further manipulation. We might want to create a reference to the game object we make for later use, or even add it to a list of all game objects we have created from the same class. Likewise, we may want to grab a local reference to the added `ObjectDestroyer` class, to perform additional setup.

You are free to only create a reference to the game object, or only create a reference to the class you are adding to the game object. With only referencing the game object, you can still create it inline, like the above example.

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

public Class ObjectCreator : MonoBehaviour
{
    public GameObject blueprint;
    public GameObject lastCreatedObject;
    public List<GameObject> allCreatedObjects;

    public Start()
    {
        /* Lists are like arrays, but more complex. They allow    *
         * you to store a list of data like an array, but         *
         * provide additional features, such as the ability to    *
         * add more data on the fly without potential issues that *
         * arrays may cause. Just make sure that you have         *
         * using System.Collections.Generic; at the top, and      *
         * initialise it in your Start() function.                */
        allCreatedObjects = new List<GameObject>();
    }

    public void CreateNewGameObject()
    {
        // Single reference
        lastCreatedObject = Instantiate<GameObject>(blueprint);
        // Adding to a list
        allCreatedObjects.Add(lastCreatedObject);
        // Adding the ObjectDestroyer class w/ reference
        ObjectDestroyer script = lastCreatedObject.AddComponent<ObjectDestroyer>();
        // Adjusting the ObjectDestroyer on our GameObject
        script.countdownTimer = 5f;
    }
}

public Class ObjectDestroyer : MonoBehaviour
{
    public float countdownTimer;
    public void Destroy(){...}
}

```

### I referenced my GameObject, but not my class! Oh Noeeeeeee!

Of course, you may find that you need to access your `ObjectDestroyer` attached to the game object, but did not create (or otherwise lost) a reference to it. In similar fashion to the above examples, we can use `GetComponent<>()` to grab a reference *after* the initial creation.

```
using UnityEngine;

public Class ObjectCreator : MonoBehaviour
{
    public GameObject blueprint;
    public GameObject gameObject;
    public ObjectDestroyer myObjectDestroyer;

    public void CreateNewGameObject()
    {
        gameObject = Instantiate<GameObject>(blueprint).AddComponent<ObjectDestroyer>();
    }

    public void ReferenceDestroy()
    {
        // This works if we need to create a reference for later...
        myObjectDestroyer = gameObject.GetComponent<ObjectDestroyer>();
    }

    public void PostponeDestroy()
    {
        // But this works if we only need the reference for one call.
        gameObject.GetComponent<ObjectDestroyer>().Postpone();

        // Actually, you could use this for more than one call, but
        // anything more and it will be more efficient and easier
        // to store an actual reference, locally, first.
    }
}

public Class ObjectDestroyer : MonoBehaviour
{
    public void Postpone(){...}
    public void Destroy(){...}
}

```

### One last thing about Types, since you *will* run into it

Since you will run into the **T** type in using the above examples, I felt it would be wise to provide a quick explanation, to avoid potential confusion. When you see a **T** specified (for example, `GetComponent<T>()` or `List<T>()`), it simply means that that method or class is *generic*. That means that you can replace the **T** with a variety of other types, and it will work.

It is more complicated than that, but for a beginner, all you need to know is that `GetComponent<T>()` can be written as `GetComponent<Collider>()` if you want to retrieve an attached collider, or as `GetComponent<Rigidbody>()` if you want to retrieve an attached Rigidbody, or even as `GetComponent<DooHickey>()` if you want to retrieve an attached class called `DooHickey`.

There are limitations to how you can use generics, but in the general sense the above examples should not lead you astray. Just know that if you try `GetComponent<T>()` and the game object does not contain such a component, it will return `null`.

# Answer
> 1 votes
Simply attach this script to your gameObject / prefab, and set the lifeTime variable to how long you want this object to live:

```
using UnityEngine;

public class AutoDestruct : MonoBehaviour {

    // Lifetime of gameObject
    // Destroy this gameObject in this many seconds after being instantiated
    public float lifeTime = 10f;

    void Start() {
        GameObject.Destroy(this.gameObject, lifeTime);
    }

}

```

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


# Question
Title: LibGDX - Centering different sized Tile Map Levels
Suppose I have a Level 1 tilemap which is 32 x 16 tiles in size, and when the player exits into another room, which is on 10 x 6 tiles in size, what's the best way to center the viewport. At the moment I am positioning my game cam as follows:

```
    gameCam = new OrthographicCamera();
    gameCam.setToOrtho(false,320,240);
    gamePort = new FitViewport(Darkcaster.V_WIDTH / Darkcaster.PPM, Darkcaster.V_HEIGHT / Darkcaster.PPM, gameCam);
    gameCam.position.set(gamePort.getWorldWidth() / 2, gamePort.getWorldHeight() / 2, 0);

```

The 320x240 is the screen resolution I wanted, and V\_WIDTH/V\_HEIGHT was also set to 320/240, as this was the size of my first level.

What I want is the smaller level to be centered in the screen (like a mini bonus room) and then I can fill the rest with black, but the scale of the tiles etc needs to stay the same.

I can get the map properties to work out how wide and tall each map is, but can't work out the math I need to get it working.

Obviously on levels which are bigger than the viewport (scrolling levels) the camera would just be centered on the player, but the smaller level would be in the center of the screen and not scroll.

Any ideas on the best way to achieve this?

Thanks

J

# Answer
> I can fill the rest with black, but the scale of the tiles etc needs to stay the same.

So why don't you fill the rest of the map with black ( which implies changing the map size ) , then you can use the default way (you mentioned) for positioning this bigger map.

I'am afraid the the only other possible options is either changing the view-port rectangle or scaling the map.
> 1 votes

---
Tags: libgdx, tilemap
---


# Question
Title: Mobile Game: Google Play no supported dev country and capitalization alternatives (no policies violation or suspicious behavior)?
If my country is listed as not supported as a developer country (for payments), this mean developer can upload app but no make any money with it. If I understood correctly, not even in app ads are allowed (I have my doubts about ads because It has no sense they aren't allowed).

Is there any mean, friendly with Google policies, to monetize the app?

For example:

* Desktop version is free to play. Optional content requires a payment.
* Mobile version is free to play. Optional content requires you to log in with same account you used to purchase it on desktop. No ads and no in-app purchase in mobile version.

Is the above scenario OK? Which are the alternatives?

Notes:

To me, no ads has no sense. After reading Developer Console documentation I assumed that ads are OK but after doing some research It turns on that many people thinks that ads are not OK.

# Answer
If your country is marked red crossed in merchant account then you are not allowed to do any kind of direct bank transaction. Example: In-app purchase of any kind, sell premium app, Ad remove purchase etc. These kinds of transactions use direct bank account which is known as merchant account.

Ads are alright as the transactions are done via a simple ad ID or third party service. This is allowed in every country in that list.

So you will have to depend on only Ads revenue if you publish your apps from your country.

As an alternative, you can establish your company's legal entity in another country where you will have full app store privileges and publish apps from there when you are developing in your country. May need a little legal consultation. Estonian e-residency allows full remote control over your company as well as banking and other stuff.

My reddit thread on similar case and findings.
> 3 votes

---
Tags: android, mobile, google-play, monetization, in-app-purchase
---


# Question
Title: 2d animation on html5 canvas using a vector and speed
Im moving a starship from one location to the other. In creating a vector, normalize and magnitude it.

Lets assume my vector looks like this

```
Vector
    x: 156,
    y: -90,
    m:  180.0000000546,
    nx:  0.8661855860486004,
    ny: -0.49972245348957717,

```

The way im animating the ships movement currently is:

```
            if (! action.animated){
                if (action.type == "move"){
                    if (game.ships[i].actions[j].v.m > 0){
// v is the Vector above !
                       game.ships[i].x += action.v.nx;
                       game.ships[i].y += action.v.ny;
                       game.ships[i].actions[j].v.m--;
                    }
                    else {
                       game.ships[i].actions[j].animated = true;
                    }

```

So basicly, im using `requestanimationframe` and a loop to move the starship by what equals 1 magnitude / **1 unit length (px) per frame**. So far it is working (but for the fact that the vessel animates one more magnitude than it should).

However, assuming i have **two starships** and one has a vector **magnitude of 180 while the other has a magnitude of 200** and im animating both at the same time, how can i create an animation that will move the faster starships quicker, i.e. **both starships should** begin moving and **end moving in the same frame** ?

# Answer
Please don't use the magnitude. Because all it does is complicate things. Use a constant number (aka frameRate) that will determine the speed of change in frames. You can also check out this answer: Sprite Animation Best Practices

The above method will allow you to have the same animation that can be used by multiple sprites. Instead of each sprite having it's own animations. Hope this helps :D
> 1 votes

---
Tags: javascript, animation, vector, html5, html-canvas
---


# Question
Title: Why does my custom network Manager disable the main one
Whenever I add a custom Network Manager to add functionality to and override it's functions, the main NetworkManager got disabled so I could not see the NetworkManager HUD or start matches. It there a way around that?

(EDIT) \[Thanks for the response\] It's not just the HUD that's the issue. The Networking is disabled entirely. Can I change this through a custom HUD?

# Answer
Apparently Network Manager in Unity is implemented using singleton pattern , so you can't have two of them in the scene, naturally after implementing the inherited Network Manager functionality , programmers tend to write a custom HUD.

Here is a one:

```
#if ENABLE_UNET

namespace UnityEngine.Networking
{
[AddComponentMenu("Network/NetworkManagerHUD")]
[RequireComponent(typeof(NetworkManager))]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public class NetworkManagerHUD : MonoBehaviour
{
    public NetworkManager manager;
    [SerializeField] public bool showGUI = true;
    [SerializeField] public int offsetX;
    [SerializeField] public int offsetY;

    // Runtime variable
    bool showServer = false;

    void Awake()
    {
        manager = GetComponent<NetworkManager>();
    }

    void Update()
    {
        if (!showGUI)
            return;

        if (!NetworkClient.active && !NetworkServer.active && manager.matchMaker == null)
        {
            if (Input.GetKeyDown(KeyCode.S))
            {
                manager.StartServer();
            }
            if (Input.GetKeyDown(KeyCode.H))
            {
                manager.StartHost();
            }
            if (Input.GetKeyDown(KeyCode.C))
            {
                manager.StartClient();
            }
        }
        if (NetworkServer.active && NetworkClient.active)
        {
            if (Input.GetKeyDown(KeyCode.X))
            {
                manager.StopHost();
            }
        }
    }

    void OnGUI()
    {
        if (!showGUI)
            return;

        int xpos = 10 + offsetX;
        int ypos = 40 + offsetY;
        int spacing = 24;

        if (!NetworkClient.active && !NetworkServer.active && manager.matchMaker == null)
        {
            if (GUI.Button(new Rect(xpos, ypos, 200, 20), "LAN Host(H)"))
            {
                manager.StartHost();
            }
            ypos += spacing;

            if (GUI.Button(new Rect(xpos, ypos, 105, 20), "LAN Client(C)"))
            {
                manager.StartClient();
            }
            manager.networkAddress = GUI.TextField(new Rect(xpos + 100, ypos, 95, 20), manager.networkAddress);
            ypos += spacing;

            if (GUI.Button(new Rect(xpos, ypos, 200, 20), "LAN Server Only(S)"))
            {
                manager.StartServer();
            }
            ypos += spacing;
        }
        else
        {
            if (NetworkServer.active)
            {
                GUI.Label(new Rect(xpos, ypos, 300, 20), "Server: port=" + manager.networkPort);
                ypos += spacing;
            }
            if (NetworkClient.active)
            {
                GUI.Label(new Rect(xpos, ypos, 300, 20), "Client: address=" + manager.networkAddress + " port=" + manager.networkPort);
                ypos += spacing;
            }
        }

        if (NetworkClient.active && !ClientScene.ready)
        {
            if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Client Ready"))
            {
                ClientScene.Ready(manager.client.connection);

                if (ClientScene.localPlayers.Count == 0)
                {
                    ClientScene.AddPlayer(0);
                }
            }
            ypos += spacing;
        }

        if (NetworkServer.active || NetworkClient.active)
        {
            if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Stop (X)"))
            {
                manager.StopHost();
            }
            ypos += spacing;
        }

        if (!NetworkServer.active && !NetworkClient.active)
        {
            ypos += 10;

            if (manager.matchMaker == null)
            {
                if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Enable Match Maker (M)"))
                {
                    manager.StartMatchMaker();
                }
                ypos += spacing;
            }
            else
            {
                if (manager.matchInfo == null)
                {
                    if (manager.matches == null)
                    {
                        if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Create Internet Match"))
                        {
                            manager.matchMaker.CreateMatch(manager.matchName, manager.matchSize, true, "", manager.OnMatchCreate);
                        }
                        ypos += spacing;

                        GUI.Label(new Rect(xpos, ypos, 100, 20), "Room Name:");
                        manager.matchName = GUI.TextField(new Rect(xpos+100, ypos, 100, 20), manager.matchName);
                        ypos += spacing;

                        ypos += 10;

                        if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Find Internet Match"))
                        {
                            manager.matchMaker.ListMatches(0,20, "", manager.OnMatchList);
                        }
                        ypos += spacing;
                    }
                    else
                    {
                        foreach (var match in manager.matches)
                        {
                            if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Join Match:" + match.name))
                            {
                                manager.matchName = match.name;
                                manager.matchSize = (uint)match.currentSize;
                                manager.matchMaker.JoinMatch(match.networkId, "", manager.OnMatchJoined);
                            }
                            ypos += spacing;
                        }
                    }
                }

                if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Change MM server"))
                {
                    showServer = !showServer;
                }
                if (showServer)
                {
                    ypos += spacing;
                    if (GUI.Button(new Rect(xpos, ypos, 100, 20), "Local"))
                    {
                        manager.SetMatchHost("localhost", 1337, false);
                        showServer = false;
                    }
                    ypos += spacing;
                    if (GUI.Button(new Rect(xpos, ypos, 100, 20), "Internet"))
                    {
                        manager.SetMatchHost("mm.unet.unity3d.com", 443, true);
                        showServer = false;
                    }
                    ypos += spacing;
                    if (GUI.Button(new Rect(xpos, ypos, 100, 20), "Staging"))
                    {
                        manager.SetMatchHost("staging-mm.unet.unity3d.com", 443, true);
                        showServer = false;
                    }
                }

                ypos += spacing;

                GUI.Label(new Rect(xpos, ypos, 300, 20), "MM Uri: " + manager.matchMaker.baseUri);
                ypos += spacing;

                if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Disable Match Maker"))
                {
                    manager.StopMatchMaker();
                }
                ypos += spacing;
            }
        }
    }
}
};
#endif //ENABLE_UNET

```
> 2 votes

---
Tags: unity, multiplayer, software-engineering, matchmaking
---


# Question
Title: Why can't I change the size of my spheres in Unity?
I started to learn Unity. Now I make something like a solar system. I have one problem. What are the min and max sizes of the sphere? E.g. I have a radius of the Sun - 1.5 but it shows like the Sun has radius 1, I can't make bigger. But also I have the Earth with 0.01 size and the Moon with 0.009. But I can't make the Mercury with 0.03 radius. So why when I'm creating a new sphere now I have only radius 1 and can't change it in Scene window?

# Answer
You appear to be changing the collider, not the actual transform. The transform reflects the position, rotation ***and size*** of your game object. The *collider* reflects the invisible barrier around your object that flags potential collision events.

## The Transform - the position, scale and size of our object

The transform is where you want to be directing changes to the overall size of your spheres. You can see the obvious distinction, below. The sphere mesh, itself, is the blue mesh made up of triangles.

In case you find yourself in a different predicament of confusion, the transform values also inherit from parent game objects. In the above example, you can see that the sphere has a scale of (2,1,1). This make the object extend 2 unit along the X-axis, and 1 unit along the Y-axis and Z-axis. Un-parented, we can say that it multiplies its values by 1. Parented to another game object, the transform values multiply by the transform values of the parent. Hopefully this does not sound too confusing, as it is an important feature. It allows you to easily lock objects together, create deliberate rotational pivots, or any number of useful reliance. It is also a common concept in general 3D design.

In the example, below, we have a second sphere with the scale of (0.5, 0.5, 0.5). When I parent our original sphere to the second sphere, its scale changes to (4, 2, 2) to retain the same size. This is because it now inherits from the second sphere, making its *world* transform (0.5\*4, 0.5\*2, 0.5\*2), or the original (2, 1, 1). You will see this is also reflected in the position and rotation, with the parent values acting as the origin, or local (0, 0, 0) position/rotation.

# The Collider - the collision barrier around your object

The collider is an invisible barrier around your object, used to calculate collision. Ideally you would want to wrap this around your object, as tight as possible. There is often some allowance in how loose the collider is, generally in favour of using simpler shapes. Simpler shapes are quicker for calculating collision.

The Collider dimensions are relative to the actual object. In the above example, we see the collider as a perfect circle around our actual sphere. With a radius of 0.5, a sphere collider will *always* wrap around your sphere mesh. In the case of not having a perfect sphere, due to having different X,Y and Z scale values, the collider will wrap to the largest axis. We can see this in the above picture, where the collider has wrapped to the X-axis, and extended past the spheres Y-axis and (unseen in the example) Z-axis. For this reason, you should generally never have to alter the sphere collider, in the project described above.

## Unity Default Values

It is worth mentioning that by default, 1 unit is intended to represent 1 meter or 1 kilogram, depending on the context being distance or weight. It certainly does not have to, after all, its your project. That said, its worth knowing that this is the default interpretation Unity will take into account when calculating things such as physics.

If you find any abnormalities in your project, as a result, it is recommended that you play around with your project settings to find a comfortable balance. You can access your project settings by going to the top menu bar, and selecting **Edit \> Project Settings**. From there, you can select **Physics** for 3D physics, **Physics2D** for 2D physics, or **Audio** for related audio settings such as Doppler effect.
> 3 votes

# Answer
From the image i see that you're changing the sphere collider not the sphere scale , sphere collider has nothing to do with sphere rendering, Try to change the Scale instead.
> 2 votes

# Answer
To change the size of an object, change the X, Y and Z scale in the `Transform` component. The `Collider` component governs how the object interacts with other objects. When you want the *physical* surface of your sphere to be identical to its *visual* surface, leave its radius at 1.0.
> 1 votes

---
Tags: unity
---


# Question
Title: How to properly give Image source for multiple sources?
I'm writing a script to change the image on the button based on previous selection. Another script is giving the `CurrentAvatar` variable once previous button is pressed.

My problem is i can't seem to load an image for the button using:

```
AvatarSprite = Resources.Load<Sprite>("Assets/Images/FireMonsters/Lamor_Icon");

```

Could someone please enlighten me on the proper code?

All from assets, or is it even possible?

Also looking to have multiple options in `if` statements, don't know a better method.

---

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

public class SelectedAvatar : MonoBehaviour {

    Button CurrentHeroSprite;
    static Sprite AvatarSprite;
    public static string CurrentAvatar;

    // Use this for initialization
    void Start () {
        CurrentHeroSprite = GetComponent<Button>();
    }

    // Update is called once per frame
    void Update () {
        if (CurrentAvatar == "Lamor") {
            AvatarSprite = Resources.Load<Sprite>("Assets/Images/FireMonsters/Lamor_Icon");
            CurrentHeroSprite.image.sprite = AvatarSprite;
            Debug.Log ("loaded sprite for Lamor");
        }
        //if etc etc etc
    }
}

```

# Answer
For Resources.Load() to work, your assets must be in a folder called Resources, and this becomes the root of the path. For examples you have a folder in Assets called Resources, which has a folder called sprites and a Sprite called Goblin. You would call:

```
Resources.Load<Sprite>("sprites/Goblin",typeof(Sprite));

```

The files absolutely MUST be nested inside a folder called Resources (which can be anywhere).
> 1 votes

# Answer
If you're having trouble linking the sprite in your script, why don't you just assign your script to the sprite itself? Instead of : `Resources.Load<Sprite>("Assets/Images/FireMonsters/Lamor_Icon");` make a generic script, that will `GetComponent<Sprite>` from the sprite you assign it to, add that sprite to your hierarchy, and run your code then? Or just add the sprite to your scene and instead of using `Resources.Load` you could use `GetComponent<SpriteRenderer>();`
> 0 votes

# Answer
Try this:

```
Resources.Load<Sprite>("Assets/Images/FireMonsters/Lamor_Icon",typeof(Sprite)) as Sprite;

```
> -1 votes

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


# Question
Title: Game loop entering tick more often than expected, and over time delta time seems to decrease.
I am writing a simple ascii game in java. My main loop has a tickrate set to once every 10 seconds, which calls a KeyListener attacked to the JTextArea that the game is displayed in. The KeyListener decides how the game gets updated based on what the user input was.

The delta time for the tick has to be set really high, otherwise instead of moving one space at a time, my character will move 2 or 3 or up to the entire x or y distance in a single click. Also, as the game runs longer, the character begins skipping places anyways, as if the tick rate has been decreased.

Here is my main game loop logic.

```
    long startLoopTime = Calendar.getInstance().getTimeInMillis();
    long updateLoopTime = Calendar.getInstance().getTimeInMillis();
    boolean firstLoop = true;

    while (true) { // keep running
        startLoopTime = Calendar.getInstance().getTimeInMillis();
        long tickCheck = startLoopTime - updateLoopTime;
        if(firstLoop || tickCheck > 10000)
        {
            firstLoop = false;
            listener(board, player, map);
            updateLoopTime = Calendar.getInstance().getTimeInMillis();
        }
    }

```

Going through debug mode, I can see that the tick check is always \> 10,000 when entering the conditional, and takes about 10 seconds to get there. However, even when the game is not in the tick check, the KeyListener is still active.

Here is my KeyListener code:

```
    public static void listener (JTextArea board, Player player, Map map)
{

    board.addKeyListener(new KeyListener(){
        @Override
        public void keyPressed(KeyEvent e){
            Map reMap = new Map();
            switch (e.getKeyCode()){
            case KeyEvent.VK_W:
                if(player.getInInventory())
                {
                    //do some stuff
                }
                else{
                reMap = moveMapUp(map, player);
                board.setText(map.getMapString());
                }
                return;
            case KeyEvent.VK_S:
                if(player.getInInventory())
                {
                    //do some stuff
                }
                else{
                reMap = moveMapDown(map, player);
                board.setText(map.getMapString());
                }
                return;
            case KeyEvent.VK_A:
                if(player.getInInventory())
                {
                    //do some stuff
                }
                else{
                reMap = moveMapToLeft(map, player);
                board.setText(map.getMapString());
                }
                return;
            case KeyEvent.VK_D:
                if(player.getInInventory())
                {
                    //do some stuff
                }
                else{
                reMap = moveMapToRight(map, player);
                board.setText(map.getMapString());
                }
                return;
            case KeyEvent.VK_I:
                if(!player.getInInventory()){
                    board.setText(inventoryString(player));
                    player.setInInventory(true);
                }
                else{
                    board.setText(map.getMapString());
                    player.setInInventory(false);
                }
                return;
            case KeyEvent.VK_SPACE:
                if(player.getInInventory())
                {
                    //do some stuff
                }
                else
                {
                    interact(map, player);
                }
            }
        }
        @Override
        public void keyTyped(KeyEvent e) {
        }
        @Override
        public void keyReleased(KeyEvent e) {
        }
    });
}

```

I dont really understand why the game is able to update more frequently than the tickrate, while still being tied to it. I also dont understand why as the game goes on, the apparent tick rate seems to drop, and my character begins speeding across the map on a single key press, instead of just moving one space like it had before. Any help or explanations would be appreciated.

# Answer
> 3 votes
Your code has more than one issue.

**Issue**: Do not call listener() inside the "while" loop. Because this adds a new key listener each time it is called, resulting in a new listener each time. This produces multiple updates of the map, more updates each 10 seconds because listener() inserts a new listener each time.

**Solution**: Move the call to listener() function out of the "while" loop.

```
long startLoopTime = Calendar.getInstance().getTimeInMillis();
long updateLoopTime = Calendar.getInstance().getTimeInMillis();
boolean firstLoop = true;
listener(board, player, map);

while (true) { // keep running
    startLoopTime = Calendar.getInstance().getTimeInMillis();
    long tickCheck = startLoopTime - updateLoopTime;
    if(firstLoop || tickCheck > 10000)
    {
        firstLoop = false;
        updateLoopTime = Calendar.getInstance().getTimeInMillis();
    }
}

```

**Issue**: Even doing the fix proposed above, you're missing that event listeners callback functions are fired in the event dispatch thread that is not the main Thread. Your game has now at least two threads, I know this because with that code, if the main loop were in the same thread than the UI, then the application would hang, trapped in the main loop without never reaching the line where the key press event is handled.

As the event is being handled, I assume that your main loop is in the main thread (that is not the UI thread if you are using awt/swing, the presence of a JTextArea suggests you are). Because of this is that you get the event processed as soon as you press a key and not once each 10 seconds as you want.

You can confirm my theory by inserting calls to `System.out.println("Thread ID = " + Thread.currentThread().getId())`. Insert one right before entering the "while" loop and other in the `keyPressed()` function of the key listener. You will see then that the key listener callback functions are called in a different thread than your main loop.

**Solution**: A classic game programming approach is to move the key handling to the main loop. To do this and at the same time benefit from all UI API goodies as are the listeners system, I suggest you to set some key state variable inside the key listener callback function and then check that state variable in the main loop. Problem solved.

Example, modify to adapt to your needs:

Change listener code to this (I didn't tried to compile):

```
// We need a new private variable, either in the main class or the JFrame derived
private boolean [] keysDown = new boolean [KeyEvent.KEY_LAST];

```

And when we create the anonymous KeyListener:

```
board.addKeyListener(new KeyListener(){
    @Override
    public void keyPressed(KeyEvent e){
        keysDown[e.getKeyCode()] = true;
    }
});

```

*Note that I only including the `keyPressed` callback. You must add `keyTyped` and `keyReleased`.*

And then, process the key in the main loop and set that key as not pressed, if the player maintains it pressed, or release and press it again, it will get marked as pressed again by the key listener code.

```
long startLoopTime = Calendar.getInstance().getTimeInMillis();
long updateLoopTime = Calendar.getInstance().getTimeInMillis();
boolean firstLoop = true;
listener(board, player, map);

while (true) { // keep running
    startLoopTime = Calendar.getInstance().getTimeInMillis();
    long tickCheck = startLoopTime - updateLoopTime;
    if(firstLoop || tickCheck > 10000)
    {
        firstLoop = false;
        updateLoopTime = Calendar.getInstance().getTimeInMillis();
    }

    if (keysDown[KeyEvent.VK_W] == true)
    {
        // Move to here the code previously in the key listener.

        keysDown[KeyEvent.VK_W] = false;
    } else
    if (keysDown[KeyEvent.VK_S] == true)
    {
        // Move to here the code previously in the key listener.

        keysDown[KeyEvent.VK_S] = false;
    }
    // And so on...
}

```

You don't have to use a boolean array, it's only an example. You can use a List, a Map, or what works best for you. You don't have to use booleans, you can collect as many information as you need about the key events. For example you can save the whole KeyEvent object (I think that may be a bit extreme, but you can).

There are other ways of doing it, like let the boolean stay as true and set it to false only when a keyReleased for that key code is detected.

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


# Question
Title: Any major perf (or otherwise) concerns with rendering to/from big partial texture rather than multiple?
I have a very low res mobile game I'm working on that takes multiple rendering passes followed by a pass the composes them. Currently, I have a tex for each pass- each of which gets given to the shader for final composition.

I want to keep # of textures used low, and I'm only able to sample from so many textures per-shader anyways (esp. for mobile). So I'm thinking each render pass would instead render to a portion of a single, bigger texture. Then the composition pass would sample the same texture from multiple places. Are there any red flags that pop out regarding this strategy?

My biggest worry is it would totally thrash the texel cache (since every frame, every pixel samples the exact same texels for all the textures (each texture is a 1 to 1 mapping of the screen) = incredibly predictable/efficient caching. However, I really only have a very basic understanding of how that works so I could be totally wrong.

Also, note that my game is incredibly low resolution (128x256), so a single "giant" texture that could hold maybe 6 screens would still be pretty small at the end of the day.

Any insight is helpful! Thanks!

# Answer
Ok- so I've tried it out. So far, so good. No noticeable performance losses yet. The one hangup I hadn't considered was that I have to manually implement what was previously taken care of by GL\_CLAMP regarding texture bleeding. So I think the answer so far is "yep, this is a good thing". (Unless this is just a ticking time bomb waiting to bite me in the butt...)
> 0 votes

# Answer
The fewer buffers you use, the better the performance will be but obviously it is more work to use fewer, larger buffers instead of smaller ones (as you are finding).
> 0 votes

---
Tags: opengl, textures, graphics, performance, mobile
---


# Question
Title: Unity2D: Pressing my mute button twice in order for it to set music back to 1
So far my mute button works, its just that I have to press my button twice (when game is restarted) in order for it to put my volume back to 1. Does anyone knows the problem. Anyway this is my script:

```
public bool mute;

void Start()
{
    // check if the player has a music volume preference
    if (PlayerPrefs.HasKey("musicVolume"))
    {
        // if yes, apply it.
        GetComponent<AudioSource>().volume = PlayerPrefs.GetFloat("musicVolume");
    }
}

private void Muted ()
{
    AudioSource audioSource = gameObject.GetComponent<AudioSource>();

    mute = !mute;
    if (mute) {
        gameObject.GetComponent<AudioSource> ().volume = 0;
       // PlayerPrefs.SetFloat("mute", 0);
    }
    else
    {
        gameObject.GetComponent<AudioSource> ().volume = 1;
       // PlayerPrefs.SetFloat("mute", 1);
    }
    // write new music volume preference to persistent storage
    PlayerPrefs.SetFloat("musicVolume", audioSource.volume);
}

```

Thank you. :)

# Answer
The reason is that you aren't setting the initial value for mute. Let's say you load up with the volume already muted (the float set to 0) as you described.

1. The bool is initially defaults to false (not muted) so when you press space, it first mutes your volume (already muted, so no effect.) *Boolean values default to false on declaration, as you did on the top of your code.*
2. In turn, you must press space again to go back unmuted.

I suggest putting this in your Start() method somewhere:

```
mute = (PlayerPrefs.GetFloat("musicVolume") == 0);

```

If the pref for volume is already muted, then it will set the initial value of bool to the appropriate value.

@smkplus also has a good implementation.
> 1 votes

# Answer
you shouldn't save volume value , you need save Boolean , because in your condition check boolean.so you can try this method for saving Boolean value.

```
using UnityEngine;
using System.Collections;

public class SoundManager : MonoBehaviour
{
    public bool mute;

    void Start()
    {
        //Get bool value
        mute = PlayerPrefs.GetInt("mute") > 0;
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            mute = !mute;
        }
        if (mute)
        {
            //Set bool value
            PlayerPrefs.SetInt("mute", mute ? 1 : 0);
            gameObject.GetComponent<AudioSource>().volume = 1;
        }
        else
        {
            //Set bool value
            PlayerPrefs.SetInt("mute", mute ? 1 : 0);
            gameObject.GetComponent<AudioSource>().volume = 0;
        }
    }
}

```
> 0 votes

---
Tags: unity, audio
---


title: How to merge fiber subtools in Zbrush

text:
# Question
Title: How to merge fiber subtools in Zbrush
I just started learning Zbrush.

While using Fibermesh, I notice that the "fiber" subtools are different from the normal ones. For example, they can be exported as curves, and BPR renders them differently.

However, when I try to merge two fiber subtools, they become a normal subtool, i.e. all fibers become normal polygons. I can no longer treat it as fibers, nor can I export it as curves.

Is there a way to merge multiple fiber subtools into one?

A related question might be: is there a way to import an obj file into Zbrush, so that it becomes a fiber subtool?

# Answer
> 1 votes
I find a way to overcome this.

While using "merge down" will destroy the fibers, using "merge visible" seems to keep them still as fibers.

---
Tags: models, 3d-modeling, zbrush
---


# Question
Title: Drawing a circle in OpenGL ES Android, squiggly boundaries
I am new to OpenGL ES and facing a hard time drawing a circle on my GLSurfaceView. Here's what I have so far.

**The circle class**

```
public class MyGLBall {

private int points=40;
private float vertices[]={0.0f,0.0f,0.0f};
private FloatBuffer vertBuff;

//centre of circle

public MyGLBall(){

    vertices=new float[(points+1)*3];
    for(int i=3;i<(points+1)*3;i+=3){
      double rad=(i*360/points*3)*(3.14/180);
      vertices[i]=(float)Math.cos(rad);
      vertices[i+1]=(float) Math.sin(rad);
      vertices[i+2]=0;
    }
      ByteBuffer bBuff=ByteBuffer.allocateDirect(vertices.length*4);
      bBuff.order(ByteOrder.nativeOrder());
      vertBuff=bBuff.asFloatBuffer();
      vertBuff.put(vertices);
      vertBuff.position(0);

}

public void draw(GL10 gl){
    gl.glPushMatrix();
    gl.glTranslatef(0, 0, 0);
//  gl.glScalef(size, size, 1.0f);
    gl.glColor4f(1.0f,1.0f,1.0f, 1.0f);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertBuff);
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, points/2);
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glPopMatrix();
 }

 }

```

I couldn't retrieve the screenshot of my image but here's what it looks like

As you can see the border has **crests** and **troughs** thereby rendering it squiggly, which I do not want. All I want is a simple curve.

# Answer
> 4 votes
I can't imagine how your code would produce the image you linked. I could however, imagine how it might produce an image like this:

With flat sides. So really what you want to do is increase the number of sides. Try setting:

```
private int points=40;

```

to something larger like

```
private int points=360;

```

If you wanted a loop like your image instead of a circle you can do something like this:

```
public float[] DrawLoop(float centerX, float centerY, float sides, float innerRadius, float outerRadius) {
    float[] vertices = new float[(sides+1)*4];
    for (int i = 0; i <= sides; i+=4) {
        verticies[i+0] = centerX + (sin(toRadians(360f * (i / sides))) * innerRadius);
        verticies[i+1] = centerY - (cos(toRadians(360f * (i / sides))) * innerRadius);
        verticies[i+2] = centerX + (sin(toRadians(360f * (i / sides))) * outerRadius);
        verticies[i+3] = centerY - (cos(toRadians(360f * (i / sides))) * outerRadius);
    }
    return vertices;
}

```

# Answer
> 3 votes
I believe there's a bug in your code in this line:

```
double rad=(i*360/points*3)*(3.14/180);

```

... which would cause the kind of error you described.

I think the line should look like this instead:

```
double rad=(i*360/(points*3))*(3.14/180);

```

Note the parentheses `()` around `points*3`

If you fix your code, I believe your output will no longer be 'squiggly'.

# Answer
> 0 votes
To draw circle, one can make use of the code snippet below:

```
 public Circle() {
   int c=0;

   int n_seg=360; // number of segments
   float[] vertices = new float[n_seg*2+2];
    for (int i=0; i<n_seg;i++){
       float radius=2.0f ; // circle radius unit
        double rad=(Math.PI*2*i/n_seg);
        vertices[c]=(float)Math.cos(rad)*radius;
        vertices[c+1]=(float) Math.sin(rad)*radius;
        c+=2;
    }

// Setup vertex-array buffer. Vertices in float. An float has 4 bytes
    ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
    vbb.order(ByteOrder.nativeOrder()); // Use native byte order
    vertexBuffer = vbb.asFloatBuffer(); // Convert from byte to float
    vertexBuffer.put(vertices);         // Copy data into buffer
    vertexBuffer.position(0);           // Rewind

public void draw(GL10 gl) {
    gl.glFrontFace(GL10.GL_CCW);  // Front face in counter-clockwise orientation
    gl.glTranslatef(0,0,0);

    // Enable arrays and define their buffers
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glVertexPointer(2, GL10.GL_FLOAT, 0, vertexBuffer);

    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);

    gl.glColor4f(1.0f,0.0f,0.0f, 1.0f);
    gl.glDrawArrays(GL10.GL_TRIANGLE_FAN,0,vertices.length/2);

    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
}

```

---
Tags: android, rendering, opengl-es
---


# Question
Title: Given a grid system where some coordinates are marked as impassable, how to find natural-looking car driving path between two locations?
I can compute an A\* path, but I get only cardinal directions from that. A 45˚ path would look like "up 1 left 1 up 1 left 1 up 1 left 1..."

My specific question is, given a grid with a pathing solution involving non-90˚ paths, how do you figure out those paths?

I have curves working as described here: https://gamedev.stackexchange.com/a/121016/66189

but I just don't know how to combine it with areas that block the path. I've seen a little bit about "pulling the string", but very little detail.

Another issue I have is that A\* will suggest that I immediately go "backwards" for the facing of my car or take way too sharp of a turn.

edit: How do I make sure I get the blue line, not the red line, which is unusable, even though A\* loves it:

The issue I'm seeing here is that a block that isn't usable on the red path is usable for the blue path -- but A\* would mark it as unusable or as having a very bad score when checking the red path.

# Answer
> 1 votes
like in RTS games you Can tag some areas in your solution with a value , representing the cost of traveling that path, so that A\* can find the shortest , less costly path , or take a look at this article on Gamasutra

Toward More Realistic Pathfinding: Adding Realistic Turns

which uses "postprocessing solutions for smoothing the path"

quote:

"For a better solution, the first thing we need to know is the turning radius for our unit. Turning radius is a fairly simple concept: if you're in a big parking lot in your car, and turn the wheel to the left as far as it will go and proceed to drive in a circle, the radius of that circle is your turning radius. The turning radius of a Volkswagen Beetle will be substantially smaller than that of a big SUV, and the turning radius of a person will be substantially less than that of a large, lumbering bear."

# Answer
> 0 votes
Instead of having a purely 2D grid add a third wrapping dimension with the angle of the car. Then you can add the orientation of the car to the initial position and restrict the turning radius.

Selecting the next possible positions should then be restricted to straight ahead in same orientation, turn to the left with a more leftward orientation and a turn to the right with a more rightward orientation. (add reverse paths as needed)

---
Tags: algorithm, path-finding, geometry
---


# Question
Title: NavMesh.SamplePosition() fails after rebaking NavMesh?
So today I was refurbishing a scene when this happened. After baking a new Navmesh the SamplePosition() returned only infinity. I tried a lot of things out but eventually went back to an older version of my project. Sooner or later I will have to bake a new Navmesh though, so I'd really like to know what happened there.

Here is the part of the code that appears to cause trouble:

```
Vector3 randomDirection = Random.insideUnitSphere * roamRadius;
NavMeshHit hit;
NavMesh.SamplePosition(randomDirection, out hit, roamRadius, 1);
direction = hit.position;

```

And of course this, since it tries to look into infinity I suppose:

```
transform.LookAt(transform.position - direction, Vector3.up);

```

Again, this code works fine. Only after baking a Navmesh this fails horribly.

# Answer
Better later than never with an answer: 5.3.5 here, I had the same issue.
The solution was to "bake" (got the joke?) the last parameter for `SamplePosition()` to "1". Everything else fails.
I tried:
`NavMesh.GetAreaFromName([anything])` **FAIL**
`NavMesh.AllAreas` **FAIL**
`1 << NavMesh.GetNavMeshLayerFromName("Default")` (from an old post, also tried with "Walkable" and without shifting) **FAIL**, etc.
The only thing worked was this:
`**NavMesh.SamplePosition(transform.position, out nHit, 0.1f, 1);**`
(The distance parameter -*0.1f in the example*\- can be anything, that param actually works...).
Hope this helps! If too late for an answer, well, hope it saves a few hours for a random visitor! :)
Cheers!
> 1 votes

---
Tags: unity, rotation, navmesh
---


# Question
Title: Planar mapping/projecting UV coordinates from normal
I've got set of vertices, and would like to calculate their UV coordinates by projecting them by a given normal. Similar to what "planar mapping" does in 3ds max.

Another way of looking at it is that I want to flatten the vertex positions from a given normal direction, so that I can simply use their X & Y (or X & Z depending on your preference) coordinates as UV coordinates.

I'm thinking it's a simple matter of a mathematical Vector function, basically rotating vertex positions along the normal, but I can't figure out the math behind it. I'm using C# and XNA, so I've got Vector3, Matrix and Quaternions. Preferably as cheap as possible.

Any help?

# Answer
> 1 votes
First you construct two basis vectors perpendicular to your projection axis `P`.

Because of the Hairy Ball Theorem, there's no standard & completely continuous way to do this, but we can hack around it something like...

```
U = cross(P, (0, 0, 1));
if (dot(U, U) < 0.001)
    U = (1, 0, 0);
else
    normalize(U);

V = normalize(cross(P, U));

```

Then for each point `Q` in your mesh, you can construct a `u,v` coordinate by projecting it onto each basis vector:

```
uv = (dot(Q, U), dot(Q, V)) * uvscale;

```

With a scalar multiply if you want your uvs larger/smaller.

This is equivalent to a matrix multiplication, where `U` and `V` are the first two rows of a rotation matrix, and the third row `P` is omitted.

I may have gotten the handedness wrong above, so if your uvs come out mirrored from what you expect, flip the arguments to `cross()`

---
Tags: c#, xna, 3d, vertex, uv-mapping
---


# Question
Title: Unity networking, make player disappear for all clients
As title says I need to make the player disappear when he gets in car. Right now, it works as a single-player, but since I am new to unet I don't really know how to achieve this, I tried some ways, but they didn't work. Here is script:

```
 [Client]
 void OnControllerColliderHit(ControllerColliderHit hit)
 {
     //so if we hit car
     if(hit.collider.tag == "Vehicle")
     {
         //if we pressed "E"
         if (Input.GetKeyDown(KeyCode.E))
         {
             //call method to disable some stuff taht should be disabled, like: controller, shoot, weapons etc.
             if (isServer)
                 CmdCall(inVehicle, hit);
             else
                 RpcCall(inVehicle, hit);
         }
     }
 }
 [Command]
 void CmdCall(bool invehicle, ControllerColliderHit hit){

     RpcCall(inVehicle, hit);
     }
 [ClientRpc]
 void RpcCall(bool invehicle, ControllerColliderHit hit)
 {

     disable(inVehicle, hit);
 }

```

> *I can't see any errors in console but I cant enter play mode cause there are some compiler errors, which again i cant see in console. thank you for any tip, comment, downvote, upvote, or hint :)*

--Nick.

# Answer
> 1 votes
In your code you call the Command if you are the server, and call the RpcCall if you are not the server. It works the other way around:

* Commands are issued from the **client to the server**.
* RpcCalls are called **from the server to all clients**.

So if you are the server, you should call the RpcCall. And if you are the client, you should send a command to the server, requesting the RpcCall.

Just change:

```
if (isServer)

```

To:

```
if (!isServer)

```

As you are currently using them the other way around.

I'd suggest also suggest, if possible, implement the RpcCall and Command in the `ControllerColliderHit` class, so you don't have to pass the component as a parameter, which might increase the size of the messages between clients and the server. Also the code would be clearer to read IMO.

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


title: Finding correct index of triangles

text:
# Question
Title: Finding correct index of triangles
I'm generating a basic terrain and it looks something like this:

```
// Load the vertex and index array with the terrain data.
    for (j = 0; j<(m_terrainHeight - 1); j++)
    {
        for (i = 0; i<(m_terrainWidth - 1); i++)
        {
            index1 = (m_terrainHeight * j) + i;          // Top left.
            index2 = (m_terrainHeight * (j + 1)) + i;      // Bottom left.
            index3 = (m_terrainHeight * j) + (i + 1);      // Top right.
            index4 = (m_terrainHeight * (j + 1)) + (i + 1);  // Bottom right.

            // Top left
            vertices[index].position = glm::vec3(m_heightMap[index1].x, m_heightMap[index1].y, m_heightMap[index1].z);
            vertices[index].texture = glm::vec2(m_heightMap[index1].tu = 0.0f, m_heightMap[index1].tv = 0.0f);
            indices[index] = index;
            index++;

            // Bottom left.
            vertices[index].position = glm::vec3(m_heightMap[index2].x, m_heightMap[index2].y, m_heightMap[index2].z);
            vertices[index].texture = glm::vec2(m_heightMap[index2].tu = 0.0f, m_heightMap[index2].tv = 1.0f);
            indices[index] = index;
            index++;

            // Top right.
            vertices[index].position = glm::vec3(m_heightMap[index3].x, m_heightMap[index3].y, m_heightMap[index3].z);
            vertices[index].texture = glm::vec2(m_heightMap[index3].tu = 1.0f, m_heightMap[index3].tv = 0.0f);
            indices[index] = index;
            index++;

            // Top right.
            vertices[index].position = glm::vec3(m_heightMap[index3].x, m_heightMap[index3].y, m_heightMap[index3].z);
            vertices[index].texture = glm::vec2(m_heightMap[index3].tu = 1.0f, m_heightMap[index3].tv = 0.0f);
            indices[index] = index;
            index++;

            // Bottom left.
            vertices[index].position = glm::vec3(m_heightMap[index2].x, m_heightMap[index2].y, m_heightMap[index2].z);
            vertices[index].texture = glm::vec2(m_heightMap[index2].tu = 0.0f, m_heightMap[index2].tv = 1.0f);
            indices[index] = index;
            index++;

            // Bottom right
            vertices[index].position = glm::vec3(m_heightMap[index4].x, m_heightMap[index4].y, m_heightMap[index4].z);
            vertices[index].texture = glm::vec2(m_heightMap[index4].tu = 1.0f, m_heightMap[index4].tv = 1.0f);
            indices[index] = index;
            index++;
        }
    }

```

Now If I wanted to find which grid square the player is on, we could simply (if the camera position is relative to the terrain)

```
    //Grid square the camera is on
    int gridX = (int)std::floor(cameraX / gridSquareSize);
    int gridZ = (int)std::floor(cameraZ / gridSquareSize);

```

Continuing, we know that each face consists of two triangles, and the top triangle is represented by three vertices which index corresponds to top left, bottom left and top right. The bottom triangle would then be top right, bottom left and bottom right. Now I'm having a hard time trying to find height values (y-values) at these points because if I try to do

```
//Top left triangle
glm::vec3(0, vertices[(m_terrainHeight * gridZ) + gridX].position.y, 0) //Top left
glm::vec3(0, vertices[(m_terrainHeight * (gridZ) + 1) + gridX].position.y, 1) //Bottom left
glm::vec3(1, vertices[((m_terrainHeight * gridZ)) + (gridX + 1)].position.y, 0) //Top right

```

we conclude that the top left and bottom left position will be okay, but the top right position won't get the correct index, because as it is now (if we say that gridX = 0 and gridZ = 0), the index will generate a value of 1, which is not the correct height value at that position because the index we want should be 2 (top right). So, is there a way I could write the code so I would get the correct index for the triangles of the terrain?

# Answer
> 2 votes
You are storing 6 values for each "square": 3 vertex for each of the 2 triangles from the square.

For each square, you should advance 6 positions, and in each of those positions you have the info of each vertex.

Change the lines:

```
 vertices[(m_terrainHeight * gridZ) + gridX]    //Top left
 vertices[(m_terrainHeight * (gridZ) + 1) + gridX] //Bottom left
 vertices[((m_terrainHeight * gridZ)) + (gridX + 1)] // Top right

```

To:

```
 vertices[6*((m_terrainHeight * gridZ) + gridX)]   //Top left
 vertices[6*((m_terrainHeight * gridZ) + gridX)+1] //Bottom left
 vertices[6*((m_terrainHeight * gridZ) + gridX)+2] // Top right

```

---
Tags: opengl, c++, collision-detection, terrain
---


title: How do I design API-agnostic classes?

text:
# Question
Title: How do I design API-agnostic classes?
I am writing a game engine in C++, or rather, a framework of reusable classes. So far, I have created low-level wrappers for OpenGL constructs. For example, a VBO class, a VAO class, and a texture class. I figure it would be a better idea to design my engine/framework to be agnostic of the API backends used below - so basically, make higher-level classes like `Texture` and `Mesh`, which are then implemented differently depending on if you use OpenGL or Direct3D.

The problem I'm having is that I can't quite figure out a good way to do this. How would I structure my classes? How high-level is enough?

I'm aware that OGRE3D uses the above mentioned approach, but I find the way Ogre does this to be confusing, to say the least. Can anybody provide me with good information on how to create an API agnostic game framework, or at least *briefly* explain how Ogre does it?

# Answer
> 2 votes
> i figure it would be a better idea to design my engine/framework to be agnostic of the API backends used below

The very first question you need to ask yourself is *why* do this at all? Unless you're actually planning to port your code to D3D or some other API today, this kind of architecture astronaut thinking will likely just waste your time. And if you are planning to port to D3D today, why? You have code that works for OpenGL already, which works on every major desktop platform. What concrete benefit is your game going to get out of the ability to switch rendering backends?

> Now the problem i'm having is that i can't quite figure out a good way to do this. How high-level is enough? Does anybody have a guideline to this, or good examples?

This is usually because you don't have a clear set of requirements about what this abstraction should provide. You should figure that out for yourself (it's not really possible for others to tell you what your usage goals should be).

What I'd recommend you do to tackle this is think of the lowest-level of abstraction you want *the rest of your code* to interact with, graphics-wise. For me, this is basically "textures, shaders and geometry" where "geometry" is "a collection of vertex and index buffers." To that end I'd write an abstraction that bundles up a collection of buffers and calls it `Geometry`. I would *not* write a `Buffer` class and implement it as `D3DBuffer` and `OpenGLBuffer`. That way lies madness: there are a lot of subtle differences between the buffer (and other similar) concepts in both APIs, and that can result in a very leaky abstraction.

It's very hard to say how high-level is good enough. That's got to be up to you and your needs. What is easier is to say how how low-level is *not* good enough. You need to provide some actual abstraction over these rendering APIs, some actual distance between them and the rest of your code. If your implementation of your abstraction ends up looking a lot like

```
void SomeFunction() {
  #ifdef OPENGL
    glSomeFunction();
  #else
    SomeD3DFunction();
}

```

then your abstraction is probably too low-level. Think bigger. Look at the where your gameplay code interacts with your rendering code and identify points where you think there's too much boilerplate, push those into your rendering abstraction.

Make it actually *do some useful work for you* rather than just translate calls from one API to another.

---
Tags: c++, architecture
---


title: Does Amazon Lumberyard support AR yet?

text:
# Question
Title: Does Amazon Lumberyard support AR yet?
I would like some help regarding whether Amazon Lumberyard supports augmented reality (AR) or not. It clearly mentions VR is supported but nothing about AR support. It looks as if we just have to attach an AR plugin on engines like unreal, unity, etc. So will it work here?

# Answer
> 2 votes
As of September 2016 there is no native, in-engine support specifically for augmented reality in Lumberyard.

You'd have to build it yourself or use a third-party solution.

---
Tags: augmented-reality, plugin, lumberyard-engine
---


title: Saving Skin weights Issue

text:
# Question
Title: Saving Skin weights Issue
I have Skinned the character using rig simulator and now wanted to add Bendy controls.. How can I export the skin weights and apply on modified rig?

# Answer
In Maya this requires using the scripting language or the API and takes a lot of work to do properly.

Download the comet scripts, they have this functionality and it is very handy.

http://comet-cartoons.com/melscript.php
> 0 votes

---
Tags: animation, maya, rigging
---


# Question
Title: Limiting interaction between certain RigidBodies
I'm developing a 2D game in Unity and have been tasked with building a particular feature I'm not sure how to accomplish with Unity's physics engine. To simplify, a bunch of objects of type **X** and **O** are filled into a pit:

```
XXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXX
XXoXXXoXXXoX

```

Both objects have Rigidbody2Ds and colliders. Objects of type **X** have normal gravity and should settle into place. Objects of type **O** have inverse gravity and should float.

However, O should not be able to *push* X, and X should not be able to push O. Another way of looking at it is that O should only be able to move upward, and X should only be able to move downward. If we remove some of the Xs directly above an O, the O should float upwards as the Xs fall downwards until the Xs settle on top of the O and everything stops moving:

```
XXXXXXXXXXXX        XX XXXXXXXXX
XX XXXXXXXXX   -->  XXXXXXXXXXXX
XX XXXXXXXXX   -->  XXoXXXXXXXXX
XXoXXXoXXXoX        XX XXXoXXXoX

```

(In the actual game Xs and Os can be different sizes; their movement is continuous and they are not constrained into rows or columns).

The Os should be able to support the weight of any arbitrary number of Xs without sinking.

```
XXXXXXXXXXXX
XXXXXXXXXXXX
XooooooooooX
X          X

```

Lastly, the Os should be able to float diagonally if there is a space available:

```
XXXX XXXXXXX      XXX       XX
XXXXX     XX  --> XXXXX   XXXX
XXXX    XXXX  --> XXXXoXXXXXXX
XXXo XXXXXXX      XXXX XXXXXXX

```

I can't solve this problem simply by adjusting the mass of the Xs or Os since the number of Xs on top of an O may vary. I can't use the built-in RigidBody constraints since they don't allow you to disable only one direction along an axis (e.g. saying an object can move upward but not downward).

What's the proper way to handle this? I could do something like this:

```
void FixedUpdate() {
    if (movementDirection == Direction.UP) {
        if (transform.position.y < lastYCoordinate) {
            Vector3 position = transform.position;
            position.y = lastYCoordinate;
            transform.position = position;
        }
    }
    lastYCoordinate = transform.position.y;
}

```

but that feels hacky to me and I suspect it will keep the objects from sleeping. Are there better solutions here?

# Answer
You could try to use a script to check the velocity of the rigid bodies, and in case they have a velocity in the Y axis in a direction you don't want, set it to zero.

For example:

***OnlyDown.cs***

```
void FixedUpdate()
{
    if (GetComponent<Rigidbody2D>().velocity.y > 0)
    {
        GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, 0);
    }
}

```

***OnlyUp.cs***

```
void FixedUpdate()
{
    if (GetComponent<Rigidbody2D>().velocity.y < 0)
    {
        GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, 0);
    }
}

```

Also, for the gameObjects that have to go up, just change the gravity scale to -1.
> 1 votes

# Answer
You can use OnCollisionStay2D:

```
void OnCollisionStay2D (Collision2D coll)
{
    if(coll.gameObject.tag == "Y" || coll.gameObject.tag == "X")
    {
        GetComponent<Rigidbody2D>().velocity = Vector2.zero;
    }
}

```
> 1 votes

---
Tags: unity, physics, rigidbody
---