# Question
Title: Game Design Lexicon: terminology for gems etc
When a Hero picks up gems or coins or other "collectibles" that add to his wealth in a game, what are those things (gems and coins etc) commonly called and how are they generally referred to in game design terminology?

# Answer
> 5 votes
You should distinguish from a heirarchical set of terms.

**Loot** is the overarching term from anything you would retrieve from a body or a reward for doing a exploration task (like the chest at the bottom of a dungeon). Sometimes quest rewards fall into this definition but are usually different.

A sub-category of loot is **Currency**. Currency is anything that you can spend to acquire something else, but are generally not useful on their own. One classic currency are Justice Points in WoW, which evolved out of Badge of Justice, looted from dead bosses in heroic dungeons. Some currencies are tradable, others are not.

A sub-category of currency is **Money**. Money is, specifically, something you can use to trade with other players or the game to acquire goods. Not all currencies are money, as illustrated above. If it isn't tradable to other players, it probably isn't money. Inherently, money exists as a medium of exchange *in a market*, allowing market prices to dominate. Thus, if the prices are set, even if it's called gold, it's more likely to be considered generic "currency" than it is money.

# Answer
> 8 votes
I would typically refer to them, as you said, as **collectibles**. You could also refer to them as **tokens**, but that may be confused with additional tries.

Collectibles might also refer to other things as well, such as items in an rpg or even overarching level goals. To refer specifically to the type of collectible that's picked up in a level and usually gives something special at 100, you could try referring to them as **coins**, typically from Mario, but that could get people confused if they're not actually coins. Another term is **goodies**, but that could be considered too vague, as well.

# Answer
> 7 votes
I would refer to them as **currency**. You've said yourself it represents wealth. If these are not actual "collectibles" in the sense of a trophy/etc unique item, and especially if they can be bartered for items and the like within the game, currency makes the most sense to me. It works for gems, it works for coins, it works for seashells, it works for bottlecaps... all of the above can be used as currency in the appropriate games :)

# Answer
> 4 votes
Hmm, I would personally say **loot**

# Answer
> 4 votes
These are often referred to as **resources**, if they are something that can be used/spent to accomplish something, and they aren't just a single currency.

# Answer
> 3 votes
Game design is not a rigorous field when it comes to terminology. What we use in the field is more of an ad hoc vernacular than anything else. Often existing English terms capture our use cases just fine, so that's all we use.

This is one of those cases. You'll find as many ways to describe these collectible items as you could probably think of. "Collectibles," "pick-ups," "rewards," "chits," "tokens," "currency," et cetera. While the terms may not vary much within one game, they will across many. The initial term will likely be coined based on the specifics of whatever the designer or designers want to convey about the purpose of the item in the game.

# Answer
> 3 votes
It depends on what you plan on doing with them.

* If you simply collect them and store them as an 'award' or, in your situation, you stack them and it represents your wealth, you can use the term *collectible*.
* If the player will consume them to buy other stuff, i.e. if it used as currency, you should probably refer to it as, well, *currency*.

However I don't think there is a *common* way to name them across all game companies. You should use common sense and what works best for you and your team internally.

What's important though is that what the player sees is consistent across the board: don't use 'collectible' on a specific pane, and 'currency' on another, this would create confusion (you'll probably even end up giving it a specific name like 'Coin' and use only that term everywhere).

---
Tags: game-design, terminology
---


# Question
Title: How can library classes access SpriteBatch?
I have a spritebatch in my primary game component in a game project:

```
public class GameRoot : Game
{
    private SpriteBatch mySriteBatch;
    public SpriteBatch MySpriteBatch
    {
        get { return mySpriteBatch; }
        set { mySpriteBatch = value; }
    }

```

I wish to access MySpriteBatch in a library class:

```
    public override void Draw(GameTime gameTime)
    {
        sprite.Draw(GameRoot.SpriteBatch, gameTime);

```

This does not work since GameRoot is derived from Game, which is passed to the class, and is not known in the library project.

How do I resolve this?

# Answer
> 1 votes
It's kind of hard to understand what you're trying to do here, but for one I would recommend passing instances as parameters anywhere you can, it will lead to clearer code in the end:

```
public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
    ...
}

```

Depending on what you mean by library, you could have a few choices. I am currently using VS 2015 and there is a really cool feature I have taken advantage of for monogame, that is the shared project type. You can learn more about it on c# corner.

You can create a shared project like this one and use it as a library for any platform. As a result, I've been able to create a single project that acts as my core game code, and created individual projects for each platform I am targeting, by leveraging the use of platform-specific markers, such as

```
#IF ANDROID
    DoSomethingSpecific();
    ...
#ENDIF

```

etc.

If you're worried about performance issues from having multiple SpriteBatch objects in separate components, that should not be an issue (from my experience), I have used dozens of components using separate spritebatch objects, and never had any problems.

If you still want to use the SpriteBatch object contained in your Game root, you may be able to access it like this:

```
this.SpriteBatch = (SpriteBatch)game.Services.GetService(typeof(GraphicsResource));

```

But I have not tried it.

Good luck!

---
Tags: c#, monogame
---


title: Desktop launcher Error in Java & LibGDX

text:
# Question
Title: Desktop launcher Error in Java & LibGDX
**What's my problem:**

It says there is a null pointer exception in my desktop launcher class even though I haven't really touched it other than add a title and change the width & height. The weird thing is I haven't touched it and I've called my program before.

Desktop Launcher Code:

```
    package com.kymedgames.poopman.desktop;

    import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
    import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
    import com.kymedgames.poopman.Game;

    public class DesktopLauncher {
public static void main (String[] arg) {
    LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
        config.title = "Poopman Adventures";
        config.width = 800;
        config.height = 600;
    new LwjglApplication(new Game(), config);
}
}

```

My Application Listener class in my core package is named Game.

**What I'm trying to accomplish:**

Run my application on desktop. (Which I have done before.)

**How I'm trying to accomplish it:**

By pressing the run button on Eclipse and not touching my desktop launcher other than add a title, width & height.

**What I need help with:**

Fix this randomly occurring error.

**Am I a noob?**

Kind of.

# Answer
You have (or one of your dependencies has) a static constructor that is failing, and it's failing because it tries to dereference something that is null.

You can see where this is happening by using the Eclipse feature Add Java Exception Breakpoint. This is a way of setting a breakpoint that is hit whenever an exception of a specific type is thrown.

Add an exception breakpoint for `NullPointerException` and it should show you where in the code something is null in a static constructor.
> 1 votes

---
Tags: java, libgdx
---


title: SDL2 and frames per second

text:
# Question
Title: SDL2 and frames per second
I'm diving into the world of SDL2 and C++ and have a few questions after my first few weeks in. Seems like a lot of the tutorials are (from what I understand) limiting the frames per second with a formula that uses the SDL\_GetTicks() function to calculate current and last ticks and setting it back, as to limit the frames per second. I could be wording that wrong. Anyways, I've learned about the SDL\_RENDER\_PRESENTVSYNC flag for SDL\_CreateRenderer() and according to fraps it seems to be working quite nicely and locking my FPS at 60 (instaed of 2000+).

My question is, Is SDL\_RENDER\_PRESENTVSYNC enough to solve the issue or should I also be using that common formula I've been seeing in many tutorials with all the SDL\_GetTicks() stuff? Are both methods doing something different that I'm not aware of? I thought they were both just setting/limiting the FPS.

# Answer
> 4 votes
The synchronization with the VSync, like what you set with `SDL_RENDERER_PRESENTVSYNC`, is tied to the *display* of your game.

So it will be synchronized to the monitor refresh rate.

If you solely rely on this to throttle your frame rate, you *could* run into this kind of issues:

* Visual issues when using multiple monitors
* Different smoothness across multiple devices (i.e. if you run your game on an Oculus Rift, which has a much higher refresh rate, your game will appear smoother than what you'll see on a computer monitor, on a slow phone device)
* Potential lag issues: if your 'update' takes more time than the time between 2 screen refresh, chances are that the frame will wait until the next refresh to update (this is truly an horrible experience)

This is only to show you why you should throttle the frame-rate yourself with one of the other methods that you've seen.

---
Tags: sdl2, vsync
---


# Question
Title: Performance of glDrawElements vs glDrawRangeElements vs glDrawArrays
I've looked around on the web trying to find a good answer to this, but am unable to find one. Different forums mention driver bugs and the likes, but these discussions are usually almost 10 years old, so bugs should probably have been fixed by now. So, to the question!

I'm drawing a mesh that consists of 628 008 vertices, normals and texture coordinates. I also have indices for the mesh, but the indices are the worst kind of indices: they do not re-use vertices, but actually just list the vertices in order (or close to). So we have 628 008 indices as well. Yes, I can re-write this to re-use vertices, but that's not really where my question is going.

The mesh is drawn using VBOs (vertices, normals, texture coords) in a VAO, and two different shaders: one for texturing one part of the mesh, and another shader for another non-textured part. To do this, I'm using the OBJ format and material groups (exported from Blender). The mesh is split into material groups, describing with which material a batch of indices shall be drawn.

The VBOs are set up to be drawn as GL\_STATIC\_DRAW since it is never changed.

I then loop over the material groups and draw the range of indices described in each group, like:

```
  for( const auto& group : mesh)
    if( group should use texturing )
    {
      enable texturing shader with phong material
      set texturing uniforms
      set material stuff
      set mvp, etc
    }
    else
    {
      enable phong material shader
      set material stuff
      set mvp, etc
    }
    draw(group)
  }

```

There are 13 different groups, so the draw command will be called 13 times.

I've tried drawing the mesh in five different ways and the results are quite surprising.

1. glDrawArrays.
2. glDrawElements with indices fed using pointer to index array. (reffered to as CPU-side indices below)
3. glDrawElements using GL\_ELEMENT\_ARRAY\_BUFFER and offset fed to command
4. glDrawRangeElements with indices fed using pointer to index array.
5. glDrawRangeElements using GL\_ELEMENT\_ARRAY\_BUFFER and offset fed to command

The \[start, end\] vertex indices fed to glDrawRangeElements are calculated when reading the mesh at start-up so they are correct and precise. This could be a performance problem otherwise, according to the spec.

The results in ms (measured on CPU side using C++11 timers, using 500 samples and calculated mean value, collecting 3 values since the first frame's timing is huge):

```
glDrawArrays:
            Median: 8.0 Mean: 8.9 Max: 217.0 Total: 4285.0 Samples: 482
            Median: 8.0 Mean: 8.8 Max: 43.0 Total: 4345.0 Samples: 494
            Median: 8.0 Mean: 8.2 Max: 14.0 Total: 4125.0 Samples: 501

glDrawElements:
GPU Indices (ELEMENT_ARRAY):
            Median: 34.0 Mean: 44.1 Max: 597.0 Total: 20388.0 Samples: 462
            Median: 34.0 Mean: 33.9 Max: 63.0 Total: 16973.0 Samples: 500
            Median: 33.0 Mean: 33.5 Max: 80.0 Total: 16797.0 Samples: 501
CPU Indices (pointer to CPU-side indices):
            Median: 9.0 Mean: 10.3 Max: 236.0 Total: 5027.0 Samples: 488
            Median: 9.0 Mean: 9.2 Max: 32.0 Total: 4581.0 Samples: 500

glDrawRangeElements:
CPU Indices (pointer to CPU-side indices):
            Median: 9.0 Mean: 10.1 Max: 221.0 Total: 4640.0 Samples: 459
            Median: 10.0 Mean: 9.6 Max: 22.0 Total: 4780.0 Samples: 500
            Median: 10.0 Mean: 9.5 Max: 32.0 Total: 4774.0 Samples: 501

GPU Indices (ELEMENT_ARRAY):
            Median: 35.0 Mean: 36.9 Max: 597.0 Total: 16101.0 Samples: 436
            Median: 34.0 Mean: 35.0 Max: 55.0 Total: 17517.0 Samples: 500
            Median: 39.0 Mean: 39.1 Max: 64.0 Total: 19448.0 Samples: 497

```

So my huge surprise is: How come GPU-side indices takes so much longer? The frame rate literally drops to less than half (from about 34 fps to 15 fps).

What can be the reason for this? My guess would have been that the performance timings should be in this order (since we have crappy indices and they aren't really re-using anything):

1. glDrawArrays \<- Fastest
2. glDrawRangeElements (using ELEMENT\_ARRAY)
3. glDrawElements (using ELEMENT\_ARRAY)
4. glDrawRangeElements (using pointer to indices)
5. glDrawElements (using pointer to indices) \<- Slowest

Why do you think that the performance is so bad using ELEMENT\_ARRAY\_BUFFER bound to the VAO? Is this driver specific? Is it because there are so many indices and memory have to be swapped around in the driver?

Hardware: MacPro running Windows 8 Dual AMD FirePro D300, 2048 MB dedicated graphics memory

# Answer
> 8 votes
I would expect glDrawArrays to be fastest on both the GPU and CPU for this scenario, primarily because you're saving the GPU memory bandwidth otherwise used for fetching the index data and the CPU cost of managing the index buffer.

I do not expect glDrawRangeElements to be any faster than glDrawElements - in fact, I would expect it to be slightly slower. The range passed to the function is intended to be used to allow a driver to know which sections of the vertex data need to be made available to the GPU. However, if you're using a vertex buffer, this is not useful information. Further, it's also just a hint - drivers are expected (although technically not required) to render correctly even if the range is wrong, and it's surprising how many applications do get it wrong. So, we generally ignore those parameters.

As for why glDrawElements is faster with client index data, that's odd, but really depends on the sequence of calls. You say your overall mesh has 600K+ vertices, but it's broken into groups. What is the size of each group? Each time you switch states (such as binding a new index buffer), the driver needs to validate the contents of the buffer, which takes time. If you're rapidly switching between two states, then this could be where your CPU time is going. When you use an index buffer, each switch is (potentially) a new buffer and is more work for the driver to validate. If you use client indices, even though the driver might be transferring indices to the GPU, it's all technically the same buffer - a gigantic buffer that starts at CPU virtual address 0.

Of course, it's also possible that the driver doing something silly.

Ultimately, 40 FPS is pretty low for drawing 600K vertices. Something bad is happening.

Here are a few things you can try to improve performance:

1) If your fragment shader and fixed function state is basically order independent (depth test on, stencil and blend configured for order independence), sort the groups in the mesh by textured vs. untextured, then draw all of one set followed by all of the other with no state changes in between. You can even sort further - by texture or other parameters, for example.

2) If any state is common between groups (mvp matrix, for example), make sure you're not setting it redundantly.

3) Make sure all groups in the mesh are using the same vertex and index buffers, ideally bound into the same VAO. When you draw, you can use the {first} or {baseVertex} parameters to offset into a larger vertex buffer. You can even use the same buffer object for both index and vertex data - just subdivide it.

4) As a last resort, you could try making all groups use the same shader by simply binding a dummy texture with an opaque white pixel into it for the untextured groups. If you're really CPU bound here, the extra GPU cost of fetching the (unneeded) texture data and a few extra shader instructions probably won't matter.

Once you do get the glDrawElements path going as fast or faster then the glDrawArrays path, do consider optimizing the vertices for reuse. A triangle soup mesh with perfect reuse can perform up to three times better than the same mesh rendered with no reuse.

---
Tags: opengl, performance, vbo, vao
---


# Question
Title: Unity AddExplosionForce to a Navmeshagent
I have a NavMesh agent and I would like forces to be applied to it during an explosion. Currently the NavMesh agent isn't interacting with the exploding object. The explosion occurs and agent takes damage but no pushback occurs on the agent.

```
using UnityEngine;
using System.Collections;

public class explosion : MonoBehaviour {
public LayerMask enemy;
public AudioSource explosionAudio;
public ParticleSystem explosionParticals;
public float maxdamage = 40f;
public float explosionforce = 1000f;
public float maxlifetime = 5f;
public float explosionradius = 5f;
// Use this for initialization
void Start ()
{
    Destroy (gameObject, maxlifetime);
}

private void OnTriggerEnter(Collider other)
{
    Collider[] colliders = Physics.OverlapSphere (transform.position, explosionradius, enemy);
    for (int i = 0; i < colliders.Length; i++)
    {
        Rigidbody targetRigidbody = colliders [i].GetComponent<Rigidbody> ();
        if (!targetRigidbody)
            continue;
        targetRigidbody.AddExplosionForce (explosionforce, transform.position, explosionradius);
        enemyhealth targethealth = targetRigidbody.GetComponent<enemyhealth> ();
        if (!targethealth)
            continue;
        float damage = calculateDamage (targetRigidbody.position);
        targethealth.Takedamage (damage);
    }
    explosionParticals.transform.parent = null;
    explosionParticals.Play ();
    explosionAudio.Play ();
    Destroy (explosionParticals.gameObject, explosionParticals.duration);
    Destroy (gameObject);
}
private float calculateDamage (Vector3 targetPosition)
{

    Vector3 explosiontotarget = targetPosition - transform.position;
    float explosiondistance = explosiontotarget.magnitude;
    float relativedistance = (explosionradius - explosiondistance) / explosionradius;
    float damage = relativedistance * maxdamage;
    damage = Mathf.Max (0f, damage);
    return damage;

}

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

}
}

```

navmesh agent

```
using UnityEngine;
using System.Collections;

public class enmymove : MonoBehaviour {

Transform player;
NavMeshAgent nav;
healthscript Health;
Animator anim;

void Awake ()
{
    player=GameObject.FindGameObjectWithTag ("Player").transform;
    nav = GetComponent<NavMeshAgent>();
    Health =player.GetComponent<healthscript> ();
    anim = GetComponent<Animator>();

}

void Update () {

     if (Health.currenthealth > 0 )
        {
            nav.SetDestination (player.position);
        }
        else
    {
        GetComponent<NavMeshAgent> ().enabled = false;
        anim.SetTrigger ("idle");
    }

    }
  }

```

# Answer
> 0 votes
You need to disable the navagent before applying the explosion and make sure it has a rigidbody attached.

explodingobject:

```
private void OnTriggerEnter(Collider other)
{
    Collider[] colliders = Physics.OverlapSphere (transform.position, explosionradius, enemy);
    for (int i = 0; i < colliders.Length; i++)
    {
        Rigidbody targetRigidbody = colliders [i].GetComponent<Rigidbody> ();
        if (!targetRigidbody)
            continue;

        NavMeshAgent nav = targetRigidbody.GetComponent<NavMeshAgent>();
        nav.enabled = false;
        targetRigidbody.AddExplosionForce (explosionforce, transform.position, explosionradius);
        enemyhealth targethealth = targetRigidbody.GetComponent<enemyhealth> ();
        if (!targethealth)
            continue;
        float damage = calculateDamage (targetRigidbody.position);
        targethealth.Takedamage (damage);
    }
    explosionParticals.transform.parent = null;
    explosionParticals.Play ();
    explosionAudio.Play ();
    Destroy (explosionParticals.gameObject, explosionParticals.duration);
    Destroy (gameObject);
}

```

navagent:

```
using System.Collections;

public class enmymove : MonoBehaviour {

Transform player;
NavMeshAgent nav;
healthscript Health;
Animator anim;
Rigidbody rigidBody;

void Awake ()
{
    player=GameObject.FindGameObjectWithTag ("Player").transform;
    nav = GetComponent<NavMeshAgent>();
    Health =player.GetComponent<healthscript> ();
    anim = GetComponent<Animator>();
    rigidBody =  GetComponent<Rigidbody>();

}

void Update () {

     if (Health.currenthealth > 0 )
        {
            if(nav.isActiveAndEnabled)
               nav.SetDestination (player.position);
        }
        else
        {
           GetComponent<NavMeshAgent> ().enabled = false;
           anim.SetTrigger ("idle");
        }

    }

}

```

Make sure to enable the navagent again after x seconds or whatever is the functionality you desire

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


# Question
Title: Libgdx unable to enter input in TextFields
Hello I am trying to make login screen for my game, I use TextField's.

**1.** I am not satisfied with how they look I want it to look like this but simpler - basically to have a white field next to the name of the field.

**2.** When I run the game it shows just 2 labels, and I can't edit them or anything.

**3.** Here is my code:

```
public class FirstTime implements Screen {
private Stage stage;
private UVeggFruit uVeggFruit;
private Music music;
private MenuStage menuStage;
private TextField.TextFieldStyle textFieldStyle;
private OrthographicCamera camera;
private float densityT = 60 * Gdx.graphics.getDensity();
private BitmapFont bitmapFont;

public FirstTime(UVeggFruit uVeggFruit,Music music){
    this.uVeggFruit = uVeggFruit;
    this.music = music;
}

@Override
public void show() {
    stage = new Stage();
    camera = new OrthographicCamera();
    Viewport vp = new StretchViewport(1280, 720, camera);
    stage = new Stage(vp);
    Gdx.input.setInputProcessor(stage);
    ButtonClickListener buttonClickListener = new ButtonClickListener();
    SceneLoader sc = new SceneLoader();
    CompositeItemVO sceneComposites = new CompositeItemVO(sc.loadScene("Login").composite);
    CompositeActor UI = new CompositeActor(sceneComposites, sc.getRm());
    music.setLooping(true);
    music.play();
    stage.addActor(UI);
    UI.getItem("regisbutton").addListener(buttonClickListener);
    UI.getItem("loginbutton").addListener(buttonClickListener);
    FreeTypeFontGenerator FTFG = new FreeTypeFontGenerator(Gdx.files.internal("Karmakooma.ttf"));
    FreeTypeFontGenerator.FreeTypeFontParameter FTFP = new FreeTypeFontGenerator.FreeTypeFontParameter();
    FTFP.color = Color.WHITE;
    FTFP.size = Math.round(densityT);
    bitmapFont = FTFG.generateFont(FTFP);
    FTFG.dispose();
    textFieldStyle = new TextField.TextFieldStyle();
    textFieldStyle.font = bitmapFont;
    textFieldStyle.fontColor = Color.WHITE;
    TextField username = new TextField("Username",textFieldStyle);
    TextField password = new TextField("Password",textFieldStyle);
    password.setPosition(400, 400);
    username.setPosition(400, 500);
    stage.addActor(username);
    stage.addActor(password);
}

@Override
public void render(float delta) {
    camera.update();
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    stage.act(delta);
    stage.draw();
}

@Override
public void resize(int width, int height) {
    stage.getViewport().update(width, height, true);
}

@Override
public void pause() {

}

@Override
public void resume() {

}

@Override
public void hide() {

}

@Override
public void dispose() {
    bitmapFont.dispose();
    music.dispose();

    }
 }

```

I will be happy if you can answer both of my questions.

# Answer
Are you sure that you can't edit them? I believe that the default background color for a TextField is white and it looks like you are setting your font color to white as well. Since the TextFieldStyle.fontColor is also white, I believe that it will have a white cursor.

As for customizing the look of your text fields, rather than creating a TextFieldStyle in code, I would suggest looking into Libgdx's skins. They are kind of like a CSS file for libgdx elements. Here is the wiki page for skins.

The background parameter of the TextFieldStyle class is a drawable so you should be able to achieve the look you want with a ninepatch drawable.
> 0 votes

---
Tags: libgdx, input, text, ui-design
---


# Question
Title: Are Differing Store Identifiers Necessary with the Unity IAP Plugin?
I am looking at implementing the new Unity In App Purchasing API for the first time.

Through the guide and the tutorial, I see that there is the ability to add different store identifiers for product ids that vary across stores... and all the examples reference that way of doing it.

Eg.:

```
public class MyIAPManager {
    public MyIAPManager () {
        var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());
        builder.AddProduct("100_gold_coins", ProductType.Consumable, new IDs
        {
            {"100_gold_coins_google", GooglePlay.Name},
            {"100_gold_coins_mac", MacAppStore.Name}
        });
    }
}

```

In my case, my product id's DONT differ, so this seems like unnecessary code bloat to implement it this way... but I don't see any other option?

**EDIT**

Argh, I'm using VS Code on OS X, which is getting better, but still has issues, such as having problematic code-completion / API referencing issues, so didn't see the overloaded method option... It's simply enough to do this:

```
var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());
builder.AddProduct("100_gold_coins", ProductType.Consumable);

```

# Answer
There is an overloaded method that simply skips the optional Array of IDs if unnecessary... See Edit to OP.

```
var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());
builder.AddProduct("100_gold_coins", ProductType.Consumable);

```
> 0 votes

---
Tags: unity, in-app-purchase
---


# Question
Title: When should I mark GameObjects as Static?
*Here is the corresponding Unity documentation.*

According to explanations of Unity documentation pages about Static GameObjects, sometimes marking GameObjects as static may affect performance in a bad way *(for example Static Batching causes more memory usage)*.

So when should i exactly want to use these functionalities?

Thanks in advance.

**Footnotes:**
I'm currently developing a 2D top-down game which has lots of Sprites and LineRenderers, but no 3D objects (not even a quad). All GameObjects are being instantiated procedurally from premade prefabs. LineRenderers get updated from scripts each frame. And nearly all Sprites are moving constantly. The majority of Sprites share same material. All LineRenderers also share same material of their own.

# Answer
> 10 votes
There is no hard rule about when you should or should not make GameObjects static.

At the very least, only do it for objects that will never move in their lifetime. But you have to know what it does to evaluate whether or not you should.

It freezes the mesh into the scene data, so you don't have the overhead of the GameObject for the item. This means a performance boost at the cost of altering the scene data at build time and extra memory cost for the final built application.

This is fine in many cases, though it can cause problems, for example with forests. Also, it means that instead of storing the verts for the tree once and the GPU drawing copies, it has to duplicate those verts all over the place. That takes time during the build, and space in the app. Our app went from 3-4 GB to 300-400 MB when we made the trees not static. Build time went from 3-4 hours to 1 hour.

Having said all that! Your game is 2d, and would probably benefit from setting GameObjects in scenes to static, provided you don't have tons of them.

# Answer
> 2 votes
If I say in general then **Everything** which is gonna never move (not even a pixel) in whole app life should mark as static. Usually it is useful for baking lights, baking navmesh paths, so on..

Well, if you are developing with no 3D objects then just relax and get chilled. No need to worry about realtime rendering, shadows or any other issues. Even delete the only light comes with new scene ;)

Well, anybody can correct me if I'm wrong at any place.

---
Tags: performance, unity
---


# Question
Title: Cannot define Public Transform Target On Unity C#
Getting UnityError Saying

> "UnassignedReferenceException: The variable target of Movement\_Script has not been assigned

Which is line 5 "public Transform target"

I've tried a lot of things... I can't define it.

```
using UnityEngine;
using System.Collections;

public class Movement_Script : MonoBehaviour {
  public Transform target;
  public float speed = 1;

  void Update () {

    if(Input.GetKeyDown("up"))
    {
      float step = speed * Time.deltaTime;
      transform.position = Vector3.MoveTowards(transform.position, target.position, step);
    }
    if(Input.GetKeyDown("right"))
    {
      float step = speed * Time.deltaTime * 10;
        transform.position = Vector3.MoveTowards(transform.position, target.position, step);
        transform.Rotate(Time.deltaTime,0 ,-90);
    }
  }
}

```

# Answer
> 1 votes
In case you have not assigned GameObject from the Hierarchy by drag and drop to the script, then you should assign target before you call target.position. For example:

```
void Start(){
    target = GameObject.FindWithTag("Player");
}

```

Then you will be able to get target position from your Update.

---
Tags: c#
---


# Question
Title: How can I render a texture to a polygon in SDL2? A fake 3D problem
I am working on a fake 3D game recently. The game is based on the perspective principle and using angular perspective. Here is a screen shot:

But the problem is that the walls and floor displayed are polygons, not exact rectangles. I draw them preline. Now I want to put some imgs on them. How can I render a texture to a polygon? How do I make texture exactly fill the area? How do I give the plane a more 3D-like feel?

# Answer
> 1 votes
The technique you're looking for is "rasterization."

At the vertices of your triangle, you have parameters like color and texture coordinates. While rasterizing the polygon (e.g. while you determine which pixels are filled) you interpolate these parameters across the polygon. This is also what you do with depth in order to calculate per-pixel depth values, for example.

The interpolated texture coordinates can then be used to sample a source texture, giving you the "correct" texel for each rasterized fragment (pixel) of the output image.

That by itself gives you only a basic result. The texture will be unfiltered, which probably isn't quite what you want, and it also won't be perspective corrected. The result will look a lot like Ps1-era 3D, for what it's worth.

Adding perspective correction isn't the hardest thing. It mostly just involved scaling the interpolations by the inverse of the depth values that you're also interpolating.

Filtering the texture is the harder part. GPUs does this using techniques like mipmaps, among others.

You can find a lot of tutorials online just by Googling "triangle rasterization" though. Many will cover in-depth how to do texturing, including perspective-corrected and filtered texturing.

The first hit I got looks decent, though perhaps a bit math heavy if you're new to the topic: http://www.scratchapixel.com/lessons/3d-basic-rendering/rasterization-practical-implementation/perspective-correct-interpolation-vertex-attributes

---
Tags: c++, 3d, sdl, art
---


# Question
Title: OpenGL/SDL2 How to resize the render area with the window?
After calling `SDL_SetWindowSize`, the area being rendered to doesn't change with the window, so if the window gets bigger, it leaves a black area on the top and right sides. I am adjusting the OpenGL viewport to the new window dimentions. Everything I'm drawing scales correctly but is cut off when the window is bigger.

I've been searching for the solution all day and all I've found is creating a new OpenGL context, but that causes crashes unless I reload all my graphics data which seems ridiculous just to resize the window.

Is it the default framebuffer that needs to be resized? According to the OpenGL wiki,

> All default framebuffer images are automatically resized to the size of the output window, as it is resized.

So if the default framebuffer is being resized, why is it only rendering to the same small area?

I could initialize it to the largest possible resolution and then shrink it, but wouldn't that cause OpenGL to process a bunch of fragments outside the window?

# Answer
> 0 votes
As discussed in the comments, the problem was a scissor region. So for anyone reading, make sure scissor testing is disabled if you're resizing the window.

---
Tags: opengl, sdl2, frame-buffer, window-management
---


# Question
Title: Mesh's triangles don't move properly during skeletal animation
I've been trying to implement skeletal animation in my engine using this tutorial, and I've been having problems. Using the model they provided, I get results like this:

But on some other models, such as Wuson, it isn't fragmented, but the triangles don't seem to move together as precisely as intended.

Both of these models appear correct and proper when static (in their bind pose), and render properly using the Assimp Viewer, so assimp does support them well enough.

What I'm looking for is possible areas of investigation, because this is a complicated task and many parts can go wrong.

I'm fairly certain (like 95%) that I'm binding the data buffers correct for both the per-index bone ID's and weights. I tested this by filling the bone's transformation array with a simple scaled matrix and got the expected uniformly scaled model.

Everything else such as the bone extraction and animation are nearly 99% identical to that of the tutorial, so I would put higher confidence in those being correct. I really don't know why I'm getting the results that I am.

---

## Structs Used:

```
// Info for weight and ID of 4 bones assigned to each vertex
struct VertexBoneData {
    int IDs[NUM_BONES_PER_VEREX];
    float Weights[NUM_BONES_PER_VEREX];
    VertexBoneData()
    {
        Reset();
    };
    void Reset()
    {
        ZERO_MEM(IDs);
        ZERO_MEM(Weights);
    }
    void AddBoneData(int BoneID, float Weight) {
        for (int i = 0; i < ARRAY_SIZE_IN_ELEMENTS(IDs); i++)
            if (Weights[i] == 0.0) {
                IDs[i] = BoneID;
                Weights[i] = Weight;
                return;
            }
        assert(0);
    }
};

// Basic bone information
struct BoneInfo {
    aiMatrix4x4 BoneOffset;
    aiMatrix4x4 FinalTransformation;
};

// basic mesh information
struct MeshInfo {
    int startIndex = 0;
    int meshSize = 0;
    TextureInfo texture;
    MeshInfo() {
        startIndex = 0;
        meshSize = 0;
    }
};

// Holds all of the information a model needs
struct ModelInfo {
    int numMeshes = 0;
    int numBones = 0;
    int skin = -1;
    vector<MeshInfo> meshes;
    vector<BoneInfo> boneTransforms;
    std::map<string, int> boneMap;
    const aiScene* scene = 0;
    Assimp::Importer importer;
    ModelInfo() {
        numMeshes = 0;
        numBones = 0;
        skin = -1;
        scene = 0;
    }
    MeshInfo& at(int x) {
        return meshes.at(x);
    }
};

```

## Model Loading:

```
// Cycle through all the meshes in the model
for (int a = 0, meshCount = scene->mNumMeshes; a < meshCount; ++a) {
        aiMesh* mesh = scene->mMeshes[a];
        MeshInfo currentMeshInfo;
        currentMeshInfo.startIndex = VertexList.size();

        // Cycle through each of this mesh's faces
        for (int b = 0, faceCount = mesh->mNumFaces; b < faceCount; ++b) {
            const aiFace &face = mesh->mFaces[b];

            // Grab information for each of the 3 indices of this face
            for (int y = 0; y < 3; y++) {
                const aiVector3D vertex = mesh->mVertices[face.mIndices[y]];
                VertexList.push_back(vec3(vertex.x, vertex.y, vertex.z));
                // Do same for tangents, normals, etc //
            }
        }

        currentMeshInfo.meshSize = VertexList.size() - currentMeshInfo.startIndex;

        for (int i = 0, numBones = mesh->mNumBones; i < numBones; i++) {
            int BoneIndex = 0;
            string BoneName(mesh->mBones[i]->mName.data);

            if (m_BoneMapping.find(BoneName) == m_BoneMapping.end()) {
                BoneIndex = NumBones;
                NumBones++;
                BoneInfo bi;
                boneInfo.push_back(bi);
            }
            else
                BoneIndex = m_BoneMapping[BoneName];

            boneMap[BoneName] = BoneIndex;
            boneInfo[BoneIndex].BoneOffset = mesh->mBones[i]->mOffsetMatrix;

            // Entire mesh is dumped into single vertex list
            // VertexID is within the mesh's "local space"
            // Thus we add it to the total amount of vertices prior to this mesh
            for (int j = 0; j < mesh->mBones[i]->mNumWeights; j++) {
                int VertexID = currentMeshInfo.startIndex + mesh->mBones[i]->mWeights[j].mVertexId;
                float Weight = mesh->mBones[i]->mWeights[j].mWeight;
                bones[VertexID].AddBoneData(BoneIndex, Weight);
            }
        }
    }
}

```

## Animating:

```
void DModelComponent::Transform(float time)
{
    const aiScene *scene = ModelInformation.scene;
    int &NumBones = ModelInformation.numBones;
    vector<ModelManager::BoneInfo> &BoneInfo = ModelInformation.boneTransforms;
    if (scene != 0) {
        aiMatrix4x4 Identity = aiMatrix4x4();

        float TicksPerSecond = scene->mAnimations[0]->mTicksPerSecond != 0 ?
            scene->mAnimations[0]->mTicksPerSecond : 25.0f;
        float TimeInTicks = glfwGetTime() * TicksPerSecond;
        float AnimationTime = fmod(TimeInTicks, scene->mAnimations[0]->mDuration);

        ReadNodeHeirarchy(AnimationTime, scene->mRootNode, Identity);

        // Collect transforms into a single vector, to be sent to shader
        transforms.resize(NumBones);
        for (int i = 0; i < NumBones; i++)
            transforms[i] = BoneInfo[i].FinalTransformation;
    }
}

void DModelComponent::ReadNodeHeirarchy(float AnimationTime, const aiNode* pNode, const aiMatrix4x4& ParentTransform)
{
    const aiScene* scene = ModelInformation.scene;
    string NodeName(pNode->mName.data);

    const aiAnimation* pAnimation = scene->mAnimations[0];

    aiMatrix4x4 NodeTransformation = pNode->mTransformation;

    const aiNodeAnim* pNodeAnim = FindNodeAnim(pAnimation, NodeName);

    if (pNodeAnim) {
        // Interpolate scaling and generate scaling transformation matrix
        aiVector3D Scaling;
        CalcInterpolatedScaling(Scaling, AnimationTime, pNodeAnim);
        aiMatrix4x4 ScalingM = InitScaleTransform(Scaling.x, Scaling.y, Scaling.z);

        // Interpolate rotation and generate rotation transformation matrix
        aiQuaternion RotationQ;
        CalcInterpolatedRotation(RotationQ, AnimationTime, pNodeAnim);
        aiMatrix4x4 RotationM = aiMatrix4x4(RotationQ.GetMatrix());

        // Interpolate translation and generate translation transformation matrix
        aiVector3D Translation;
        CalcInterpolatedPosition(Translation, AnimationTime, pNodeAnim);
        aiMatrix4x4 TranslationM = InitTranslationTransform(Translation.x, Translation.y, Translation.z);

        // Combine the above transformations
        NodeTransformation = TranslationM * RotationM * ScalingM;
    }

    aiMatrix4x4 GlobalTransformation = ParentTransform * NodeTransformation;
    aiMatrix4x4 GlobalInverseTransform = (scene->mRootNode->mTransformation);
    GlobalInverseTransform.Inverse();
    vector<ModelManager::BoneInfo> &BoneInfo = ModelInformation.boneTransforms;
    map<string, int> &BoneMap = ModelInformation.boneMap;
    if (BoneMap.find(NodeName) != BoneMap.end()) {
        int BoneIndex = BoneMap[NodeName];
        BoneInfo[BoneIndex].FinalTransformation = GlobalInverseTransform * GlobalTransformation * BoneInfo[BoneIndex].BoneOffset;
    }

    for (unsigned int i = 0; i < pNode->mNumChildren; i++) {
        ReadNodeHeirarchy(AnimationTime, pNode->mChildren[i], GlobalTransformation);
    }
}

```

**Methods such as *"CalcInterpolatedRotation()"* and such are completely identical to the ones posted within the tutorial, hyperlinked at the beginning of this post.**

## Rendering:

```
// omitted other shader uniform bindings
GLuint sid = shader->getPID();
GLuint id = glGetUniformLocation(sid, "Bones");
if (transforms.size()>0)
    // Bind array of bone transformations
    glUniformMatrix4fv(id, transforms.size(), GL_TRUE, &transforms[0][0][0]);

    // Render each mesh within the model, defined by its starting index and size
    ModelManager::ModelInfo &model = ModelInformation;
    for (int x = 0, total = model.numMeshes; x < total; x++) {
        ModelManager::MeshInfo &mesh = model.at(x);
        mesh.texture.Bind();
        glDrawArrays(GL_TRIANGLES, mesh.startIndex, mesh.meshSize);
    }

```

## Shader:

During my geometry pass, I do the following:

```
layout(location = 0) in vec3 vertex;
// ... extra ... //
layout(location = 4) in ivec4 BoneIDs;
layout(location = 5) in vec4 Weights;

const int MAX_BONES = 100;

uniform mat4 mMatrix;
uniform mat4 pMatrix;
uniform mat4 vMatrix;
uniform mat4 Bones[MAX_BONES];
uniform bool useBones;

void main(void)
{
    mat4 BoneTransform = mat4(1.0);
    if (useBones) {
        BoneTransform = Bones[BoneIDs[0]] * Weights[0];
        BoneTransform += Bones[BoneIDs[1]] * Weights[1];
        BoneTransform += Bones[BoneIDs[2]] * Weights[2];
        BoneTransform += Bones[BoneIDs[3]] * Weights[3];
    }
    mat4 worldMVP           = pMatrix * vMatrix * mMatrix;
    vec4 v                  = BoneTransform * vec4(vertex,1.0);
    gl_Position             = worldMVP * v;
}

```

# Answer
> 3 votes
All of my issues boiled down to misusing the model's index array.

At first I purposely avoided using the model's indices because I wanted to have *per vertex normals* rather than *per face normals*. However, I completely forgot that the vertex list may not correspond to the correct rendering order, which lead to the results in my opening post.

On my way to solving this I had additional problems, which I unfortunately did not save any images of. Since I needed the model's indices but didn't want to render using an index list, I needed to create a modified vertex/uv/normal/tangent list which would contain their respective information but in the order of the index list:

```
vector<int> &indices = getIndices();
vector<vec3> &oldVertices = getOldVertices();

int total = indices.size();

vector<vec3> newVertices;
newVerticies.reserve(total);

for (int x = 0; x < total; ++x) {
    newVertices.push_Back(oldVertices[indicies[x]]);
}

```

Just doing this alone for each attribute **is not enough!** Since we are dealing with animation, we also have per-vertex bone information, so that list also needed to get adjusted the same way.

These changes alone solved my problem.

---
Tags: opengl, animation, skeletal-animation, assimp
---


# Question
Title: What does it actually mean by World, Window and Viewport?
I am studying Computer Graphics myself. I am stuck with the concept of World, Window and View-port.

As far as I understood:

(1) **World** \- is an abstract and imaginary space that is imagined to exist inside the Graphics rendering software (like Blender, 3D Studio Max, and so on) or a framework/library/engine like OpenGL or Directx, or, Unreal Engine where the objects/models (to be displayed) are measured in units specific to that software or library or engine. We are generally habituated to measure pictures of all geometric objects as the units of integer/real numbers on papers or books. And, in computer monitor screens they are measured in Pixels. But, due to some problems like \________________, developers use a coordinate system imagined and implemented in their software/framework/library/ engine and that is called a World Coordinate system. For example, OpenGL uses fractional values to measure and plot an object which seems to be totally impossible, because, computer screens do not have such abilities, they only understand pixels. So what is the catch? Before displaying on the computer screen, the OpenGL's world coordinate measurements are converted to actual screen pixels (through a mechanism called Graphics Pipeline) and that is how a model or object can be displayed on the computer screen.

(2) **Window** \- Window is the a cut-section area (that we want to display on the computer screen) of the imaginary graphics World.

(3) **Viewport** \- Viewport is the actual image we see on the screen. That is displayed by converting the world coordinate into screen pixels.

Am I correct?

Please, fill in the blank and review my conception thus far.

---

**And, if you do down-vote, or, closed-vote, please, leave a comment so that I can understand the reason.**

# Answer
Consider the real world. We have all kinds of things measured in meters and feet. Now how many, say, meters across is your field of view? Clearly, you need to know more about that question to continue. At what distance? Horizontally? Vertically? Even the arrangement of cells on your retina doesn't indicate how much of the world you can see.

The same problem exists in projection. We have some 3D surfaces in an imaginary world (the unit of its coordinates is just a matter of interpretation - we use different units depending on the scale we're simulating), and we want to project them onto a 2D surface that we will then display on the monitor.

So, we define a 3D surface with some particular size in the world on which to project things onto (in practice the surface is only implied by the matrix) and then scale and translate the 3D vertices so they lie in line with that surface. Imagine drawing a line from every vertex through the surface to some point, then moving them to the point where the intersect with the surface. That is the duty of the projection matrix.

Now that all the 3D stuff is 2D, we just have to scale the surface to the pixel resolution and map the textures' coordinates onto it.

This is a very simplified view, since there's a lot of tweaks like filtering and z-buffering that usually need to happen in between, but that's the problem and a short explanation of the solution.
> 1 votes

# Answer
While trying to understand the subject I found this great book. It's a dense and complete cheat sheet for all spaces you will possibly deal in 3D. Answering your question:

1. "The purpose of world space is to provide some absolute reference for all the objects in your scene."
2. No, `Window` is usually a synonym to `Viewport`. Possibly that you talking about is a clip space.
3. That is somewhat correct, "converting the world coordinate into screen pixels" doesn't sound particularly right because there is no direct transformation, unless you have at least a view point.
> 0 votes

# Answer
I think my basic idea will be helpful here: i found from different material during my study.

A rectangular area specified in world coordinates is called a window. A rectangular area on the display device to which a window is mapped is called a view port. The window defines what is to be viewed; the view port defines where it is to be displayed. Often windows and view ports are rectangles in standard position with rectangle edges parallel to coordinate axes The mapping of a part of world coordinate scene to device coordinate is referred to as viewing transformation. hope this is useful.
> 0 votes

---
Tags: coordinates
---


title: Roofs not appearing in Unity

text:
# Question
Title: Roofs not appearing in Unity
My buildings are fine until I import them to Unity. None of the formats I've come across( FBX, DAE, 3DS Max, Blender Files, any of the Autocad formats, OBJ, PRJ, WRL etc.), have roofs when importing the buildings as one cohesive file into Unity. In Sketchup, Blender etc. they all appear fine. Does anyone have suggestions?

# Answer
> 1 votes
The most likely cause of your problem is with the way your 'normals' are facing in your 3D-modeling program. If you are using Blender, you can select your faces, press w, and select 'flip normals'. It should turn your darker colored faces to a normal lighter color again.

# Answer
> 0 votes
Your roof planers have inverted normals. Try to invert normals of roofs in your model-making software then reimport them in Unity

---
Tags: unity, 3d, models, blender
---


title: Rearranging projects in Git and Unity

text:
# Question
Title: Rearranging projects in Git and Unity
I'm attempting to rearrange a Unity project that is under source control. Two problems:

* In order to maintain the relationships between assets, I need to use Unity's API or interface. But when I move something that way, git loses track of them.
* In order to maintain git tracking, I need to use git commands. But when I move them that way, Unity loses track of how they're related.

Is there an easy way for me to tell one what the other is doing?

# Answer
I would always use the unity tools to modify unity projects, since in the end i want a working game and not just a nice git history.

From my experience git is pretty smart about understanding your moves and renames from the delete/add pairs of nearly identical files, but these only show up once you stage your changes with `git add`. Also make sure no one else works on the repository while you move things are, you might get nasty conflicts otherwise.

The good thing about using git is you can just go ahead and try a small refactoring in unity to see how git would manage it. If you don't like the result, rollback to the last commit.
> 3 votes

---
Tags: unity, version-control, git
---


title: OpenGL dynamic font glyph cache library

text:
# Question
Title: OpenGL dynamic font glyph cache library
I have begun work on an OpenGL application (all on my own and with little knowledge) and started with FTGL, rendering true type fonts, which, with alot of text has a great impact on frames per second.

I believe that to overcome this limitation one needs to generate a font atlas and save glyphs to opengl textures which are then drawn by shaders.

I have done a search of github for such a library and found several, a few of which are incomplete (and by their own admission have memory leaks)

I am looking for, and hoping that one of you can recommend, the most stable opengl font library that you preffer and does the aforementioned. I also need unicode support.

Or a guide to help a noob like me achieve this

Thankyou for reading

# Answer
Personally, I've used the BinPacking by Jukka Jylänki (see http://clb.demon.fi/files/RectangleBinPack.pdf and http://clb.demon.fi/files/RectangleBinPack/) to build a glyph atlas. Combined with the freetype library (http://freetype.org/) for loading glyphs from ttf fonts and a routine to turn utf8 strings into unicode codepoints (RFC3629 is very informative, see https://www.rfc-editor.org/rfc/rfc3629), this makes up my font system.

If you don't want to write your own, I would recommend freetype-gl (https://github.com/rougier/freetype-gl) for being bug free and relatively easy to use. It also has most features you'd want in a text renderer, like outlines, shadows and other effects.
> 1 votes

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


title: Sprite doesn't move

text:
# Question
Title: Sprite doesn't move
Trying to create a 2d Top down random movement. I have the blendtree setup so that it faces the sprite in the right direction. However, I can't get it move right. It just flips back and forth between directions never moving. Unless I use the RidgidBody2d apply force then it just slowly convulses to 0,0.

I guess I wanted it walk in one direction base cardinal direction (no angles) for 3 seconds then change direction.

What Am I doing wrong?

```
public float moveSpeed = 0.75f;
 public Animator anim;
 public Rigidbody2D body;

 private Vector2 enemyMovement;

 void Start () {
     anim = GetComponent<Animator> ();
 }

 void Update () {
     Invoke("randomDirection", 1);
     transform.position = new Vector3(enemyMovement.x,enemyMovement.y,0) * moveSpeed * Time.deltaTime;

     //TRIED THIS TOO
     //body.AddForce (enemyMovement);
 }

 void randomDirection() {
     switch(Random.Range (0,3)){
         case 0:
             Debug.Log ("Moving enemy Up");
              enemyMovement = new Vector2 (0,1);
             break;
         case 1:
             Debug.Log ("Moving enemy Right");
              enemyMovement = new Vector2 (1,0);
             break;
         case 2:
             Debug.Log ("Moving enemy Down");
              enemyMovement = new Vector2 (0,-1);
             break;
         case 3:
             Debug.Log ("Moving enemy Left");
              enemyMovement = new Vector2 (-1,0);
             break;
         default:
              enemyMovement = new Vector2 (0,0);
             break;
     }

 }

```

# Answer
> 0 votes
**Although** you did mark it as answer, but now this code will work 100% correct.

Couple of things are here.

First of all you are calling `Invoke` in `Update`. Which means `Invoke` is executing 60 times per second. That is weird. Instead of that make a `Coroutine` that will executes every second.

Try the below code,

```
 public float moveSpeed = 0.75f;
 public Animator anim;
 public Rigidbody2D body;

 private Vector2 enemyMovement;

 void Start () {
     anim = GetComponent<Animator> ();
     StartCoroutine("ChangeDirection");
 }

 void Update () {
     //Invoke("randomDirection", 1);

     transform.position += new Vector3(enemyMovement.x,enemyMovement.y,0) * moveSpeed * Time.deltaTime;

     //TRIED THIS TOO
     //body.AddForce (enemyMovement);
 }

 IEnumerator ChangeDirection()
 {
     while(true){
         yield return new WaitForSeconds(1.0f);
         RandomDirection();
     }
 }

 void RandomDirection() {
     // HAMZA's: Now I'm sure it will work :)
     switch(Random.Range (0,4)){
         case 0:
             Debug.Log ("Moving enemy Up");
              enemyMovement = new Vector2 (0,1);
             break;
         case 1:
             Debug.Log ("Moving enemy Right");
              enemyMovement = new Vector2 (1,0);
             break;
         case 2:
             Debug.Log ("Moving enemy Down");
              enemyMovement = new Vector2 (0,-1);
             break;
         case 3:
             Debug.Log ("Moving enemy Left");
              enemyMovement = new Vector2 (-1,0);
             break;
         default:
              enemyMovement = new Vector2 (0,0);
             break;
     }

 }

```

# Answer
> 0 votes
Well, you change the movement vector every frame. Invoke just adds one second delay to the call, but you still call it every frame. You could do

```
 if(!IsInvoking("randomDirection"){
    Invoke("randomDirection",1);
 }

```

This way you only schedule a new change if the last one is done. But in my opinion you should not be using Invoke, it leads to very unreadable code. Make a timer yourself like this:

```
float remainingTime=0;
void Update(){
    remainingTime -= Time.deltaTime;
    if(remainingTime <0f){
       remainingTime=1f;
       randomDirection();
    }
    //Move code as you did.
}

```

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


# Question
Title: 2D grid based placement (limited to 1 tile in each direction) in Unity
I've been trying to get my head around this for hours now, I hope one of you is able to help.

I'm trying to make a small game (2D using sprites) that allows you to place blocks (tiles). That is pretty simple in itself, I use ScreenToWorldPoint and mouse position to place the block (no snapping to grid yet).

Now, what I need to do is ensure that the player places blocks on either side of the block that was just placed, and not just some random place on the screen.

A block is just a 1x1 sprite in this case.

For example. Player placed a single block on the screen:

```
            can place here
                  |
can place here - [#] - can place here
                  |
            can place here

```

Player then places another block next to the already placed block:

```
            can place here
                  |  |
can place here - [#][#] - can place here
                  |  |
            can place here

```

As you see, there is always room to place 1 block around each block placed (using the word block too much!). This is in 2D space.

So in the end, the player might make this:

```
                   can place here
                      |  |   |
can place here     - [#] |  [#] - can place here
can place here  - [#][#][#][#][#] - can place here

```

As you also see here, there is always room for 1 block to be placed around the already placed blocks - obviously not when there's already a block placed next to it.

Hope it makes sense.

I guess what I'm after is just: How would I go about creating a grid around a single game object (2D sprite) - I can then use Ray's to figure out if player has pressed one of the grids around it.

Thanks a lot!

**EDIT:**

So, I managed to get something working. I made a game object with 4 parents (1x1 sprites: top, right, left, bottom) - clicking on one of these parents, "replaces" (destroys) the object and inserts another tile with 4 parents.

This seems like a really bad implementation, so please suggest alternative ways of doing this.

Screenshot:

Code:

```
using UnityEngine;
using System.Collections;

public class GameManager : MonoBehaviour {

    public Transform boatObject;
    public GameObject tile;
    public GameObject boatPlank;

    private Vector2 mousePosition;

    void Start ()
    {
        Vector3 position = new Vector3 (boatObject.transform.position.x, boatObject.transform.position.y, 0);
        GameObject gridTile = Instantiate (tile, position, Quaternion.identity) as GameObject;
        gridTile.transform.SetParent (boatObject.transform);
    }

    void Update ()
    {
        // Mouse button 1
        if (Input.GetMouseButton (0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction);

            if (hit.collider.gameObject.tag == "GridItem")
            {
                Vector3 position = new Vector3 (hit.collider.transform.position.x, hit.collider.transform.position.y, 0);

                GameObject gridTile = Instantiate (tile, position, Quaternion.identity) as GameObject;
                gridTile.GetComponent<SpriteRenderer> ().sortingOrder = 10;
                gridTile.transform.SetParent (boatObject.transform);

                // Destroy the grid item that was clicked
                Destroy (hit.collider.gameObject);

                Debug.Log ("Hit something: " + hit.collider.gameObject.tag);
            }
        }
    }
}

```

# Answer
I don't know if this is the best way but it is how I go about it if I have a board which can have a lot of interactions.

Have a class called `BoardManager` which will be in control of the board and what happens to it. This script contains a `List` (or other array type object) which knows where you can place tiles.

```
// In order to use Lists/Dictionaries need,
Using System.Collections.Generic;

public class BoardManager(){
    public GameObject tileObject;
    public GameObject canPlaceObject;

    // List containing positions where tiles can be made.
    private List<Vector2> possibleTiles;
    // List containing positions where tiles already are.
    private List<Vector2> tiledPositions;

    public void AttemptCreateTileAt(Vector2 point){
        // You will need to round the point to the nearest tile point
        if(possibleTiles.Contains(point){
            // Create the tile at the point
            Instantiate(.....);
            possibleTiles.Remove(point);
            tiledPositions.Add(point);
            CanMakeTilesAround(point);
        }
    }

    public void CanMakeTilesAround(Vector2 point){
        // Now iterate through all the possible positions next to the point
        // If there isn't a tile there add it to the possibles and spawn the
        // appropriate gameobject
        if(!tiledPositions.Contains(new Vector2(point.x +1,point.y)){
            possibleTiles.Add(new Vector2(point.x +1,point.y));
            Instantiate(....)
        }
        ....// Add other positions
    }
}

```

Note this is kinda pseudo-code and it will need changing by you.

So when you detected a mouse click you tell the `BoardManager` to try to create a tile there (you could make `AttemptCreateTileAt(Vector2 point)` a bool so you know if it worked). If it can create a tile there it then makes the positions around that tile possible `CanMakeTilesAround(Vector2 point)`.

I like this approach for certain reasons;

* it means all the logic is in the code, I don't need to worry about if an object instantiated correctly to determine if a position can have a tile created at,
* all the information about the board is in one place and protected (can only change it via public functions),
* you can make changes to the code to allow you to get references to the different tiles or parts of the board, or even add functions which can do useful things i.e. get a reference to neighbouring tiles etc.(i.e. make `List<Vector2> tiledPositions` into a dictionary `Dictionary<Vector2,Tile> tiles`).

It does have some drawbacks though,

* it takes a lot longer to set up and get working to a point where you can test it,
* it is code intensive and you may not want to spend all your time debugging the board for your game.

Also I am sorry for the length of the answer I got a little carried away.
> 2 votes

---
Tags: 2d, unity, grid
---


# Question
Title: How can I set a Steam achievement in Steam via LibGDX or native Java?
Is it possible to set or 'unlock' a Steam achievement via LibGDX or with a native Java solution?

If so, how it this possible. Furthermore, what would be a good implementation for 'saving' achieved achievements when you were offline. For example, when I enable the airsafe mode on my laptop and then run the game, be really good at it and unlock an achievement, how can it be saved the next time I have WiFi?

# Answer
Since Steamworks is a C++ API, you'd need to write a wrapper. You can use the Java Native Interface (JNI) for this, or possible the Java Native Access API instead. The JNI is the "classical" method, the JNA thing seems to be newer and I know less about it.

The Steamworks SDK is not public, so I can't link you directly to the interface you'd want to wrap, but all the ones you'd want to wrap are probably located in `ISteamUserStats.h`.

Fortunately, Steamworks is so popular that there are already wrappers other people have written for you, such as steamworks4j.

Steamworks services support an offline mode themselves, so you should not *need* to do anything specific yourself to deal with tracking and recording achievements when the user is offline.
> 3 votes

---
Tags: java, libgdx, steam
---


# Question
Title: Unity's rendering statistics window applied to mobile phones
Unity has the ability to display in game statistics to help developers via the rendering statistics windows. This information shows information such as triangles and verts being rendered, audio level, fps, main and render thread operations time, etc.

I understand the importance of this information yet I'm still struggling to apply it into mobile phones. In this case I want to know how this information can be tied to mobile phones so that I can easily adjust my game to be suitable for low end phones as well as doing the opposite case.

For example, I want to make a big scene for the player, yet I need to keep an eye out on the triangles being drawn, however I don't know a numeric range to keep this triangles in between for the execution of the game.

¿Is there a way to calculate the maximum values that a phone can handle based on the phone's specs? ¿Should I just keep everything at the lowest, sacrificing graphics for better performance? ¿Or should I just do a trial and error on several phones until I find an equilibrium point between graphics and performance?

# Answer
> 0 votes
Btw you have all the answers in your question. According to my experience, that stats window although very help helpful, but it will give you just an idea about experience in mobile device. And you also can set things according to the device specs, you may keep models with heavy shaders off turn on diffuse on low end devices for example.

I also observe sometimes terrain with 250k tris(stats window) running on iphone4 smoothly. It all depends. Well, again, all is my personal experience, its not necessary that everybody will agree with my points.

---
Tags: unity
---


title: Issue with Button component

text:
# Question
Title: Issue with Button component
When I add a Button component, it looks like this:

Normally, it should look like this:

How can I fix this issue?

# Answer
In the top of the window where you see that, you should see a tab named 'Debug'. Normally the tab would be named 'Inspector'. The difference is that at some point you clicked the little menu drop down to the top right of that and switched to Debug mode instead of Normal mode.

Switch back to Normal and it should appear the way you're expecting.

More details here: Inspector Options
> 2 votes

---
Tags: unity, component-based
---


# Question
Title: How can i get object from TMXTiledMap and store it in Dictionary variable ?
I've been following a tutorial to make tiled map in cocos2d x 3.0 , but i couldnt complete the rest of the tutorial because its for coco2d x 2.0 version,

How can i get a value of property that is stored in an object from TMXObjectGroup variable ? and my code is:

```
tileMap = cocos2d::TMXTiledMap::create("ground.tmx");
ground = tileMap->layerNamed("ground");
this->addChild(tileMap);

TMXObjectGroup *objects = tileMap->getObjectGroup("objects");
??? sign = objects->getObject("sign");// it return ValueMap not Dictionary ?!

```

how can i get a Dictionary of that object so i can get its values ??

# Answer
> 0 votes
```
ValueMap sign = objects->getObject("sign");
float x = sign["x"].asFloat();
float y = sign["y"].asFloat();
std::string nameAlias =  sign["name_alias"].asString();

```

ValueMap in cocos2d contains Value type. You can see in CCValue.h for more details.

---
Tags: android, tiles, cocos2d-iphone, tilemap, cocos2d-x
---


# Question
Title: How can i get a value from object in tmx file in Cocos2d x 3.x?
I want to set my sprite in x coordinate based on an object in TMX map file, this is my code:

```
tileMap = cocos2d::TMXTiledMap::create("ground.tmx");
ground = tileMap->layerNamed("ground");
this->addChild(tileMap);

TMXObjectGroup *objects = tileMap->objectGroupNamed("objects");
Dictionary *sign = (Dictionary*)objects->objectNamed("sign");

```

How can i get a value of object in tmx file in Cocos2d x ?

# Answer
```
ValueMap sign = objects->getObject("sign");
float x = sign["x"].asFloat();
float y = sign["y"].asFloat();
std::string nameAlias =  sign["name_alias"].asString();

```

In cocos2d v.3.8, objectNamed("name") will return ValueMap type that contains Value type. You can see in CCValue.h for more details.
> 1 votes

---
Tags: cocos2d-iphone, tilemap, cocos2d-x
---


title: Iris-wipe shader not properly working

text:
# Question
Title: Iris-wipe shader not properly working
I'm working on creating an iris wipe transition, like the ones you see in old cartoons - a fully transparent circle closes on a certain point, leaving a full screen of a solid color. Additionally, the background around the circle fades in from full transparency as well. I decided that shaders would be easier than creating vertices to build the iris effect. I may have been wrong.

**EDIT:** I've made some progress since asking this question - there is now an iris effect, but it opens and closes around a blank `CornflowerBlue` screen before displaying the screen, and the background around the circle is always full transparency.

Shader:

```
sampler TextureSampler : register(s0);
float2 irisCenter;
float radius;
float4 backColor;

float4 PixelShaderFunction(float4 pos : SV_POSITION, float4 color1 : COLOR0, float2 coords: TEXCOORD0) : COLOR0
{
    float4 p = pos;
    float2 c = irisCenter;
    float r = radius;

    float alpha = abs(1 - step(pow(p.x - c.x, 2) + pow(p.y - c.y, 2), r * r));
    return float4(backColor.r, backColor.g, backColor.b, alpha * backColor.a);
}

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

```

The `alpha` variable should be deciding if a pixel is inside the circle and should be transparent, or if the pixel is outside the circle and shouldn't be. `irisCenter`, `radius`, and `backColor` are all set on each frame by:

```
public void Draw()
{
    if (isInitialized && (isRunning || dir == EffectDirection.Backward))
    {
        float r = color.R; // / 255f;
        float g = color.G; // / 255f;
        float b = color.B; // / 255f;
        float a = (color.A * currentFadeLevel); // / 255f;

        var irisEffect = GameServices.Effects["IrisEffect"];
        irisEffect.Parameters["irisCenter"].SetValue(irisCenter);
        irisEffect.Parameters["radius"].SetValue(irisRadius);
        irisEffect.Parameters["backColor"].SetValue(new Vector4(r, g, b, a));

        quadRenderer.Render(irisEffect);
    }
}

```

IrisEffect.cs

QuadRenderer.cs

Instead of behaving as an iris wipe, it first draws a full-screen rectangle for half the effect, and then a full-screen `Color.CornflowerBlue` rectangle (I guess the quad from `QuadRenderer` isn't drawing with transparency). I'm not sure what's wrong as I'm new to HLSL.

Question 1: How can I get the coordinates of the current pixel being processed by the shader?

Question 2: What am I doing wrong?

Question 3: How do I draw the rest of the quad transparently?

# Answer
> 0 votes
Well, turns out I had my draw calls in the wrong order. Drawing the effect last, after everything else in the scene, solves all my issues. Also, the complicated vertice trickery in `QuadRenderer` can be replaced with a simple call to a helper method I have that draws rectangles of arbitrary colors.

---
Tags: shaders, hlsl, monogame
---


# Question
Title: Do you need to have separate companies to publish different kind of games?
I'm planning to make my own indie game company as both developer and publisher. As a publisher, I have some question about branding and reputation.

**1. Quality**:
A publisher have 2 games, they both have good average rating and they want to publish another game, which have less resources and effort. Publisher predicted it won't have as good rating as its previous games, but decided to publish it anyway because it needs money. Is this a bad call? Will having 2 good games and 1 bad games affect reputation? How?

**2. Genre**:
Is genre matters in reputation? For example, a publisher specialized in publishing RPG games, then suddenly, they publish FPS games. Assuming those games all have good ratings in average, will it affect publisher reputation? How?

**3. Age-resctricted content**:
Do you need different publisher name to publish adult games? The game is closer to "porn game" rather than "having adult content"; different from what we've seen in ESRB rated "M" games such as The Witcher 3. If a publisher mix their "normal" and "porn" games under the same name, will it affect its reputation? How?

# Answer
Specilization on a certain genre of games is usually because the staff is specialized on certain genres and rarely for brand identity. *"We know how to create games of a certain genre, so we keep doing it"*. But when you think your team is capable of developing a game in a different genre, don't let your brand identity get in the way. Take Blizzard Entertainment, for example, who jumped from puzzle-platformer to racing to action-platformer to real-time strategy to action-rpg to mmorpg to virtual collectible card game to first person shooter.

Having a good reputation will greatly increase the sales of your next game. You can expect that your name alone will cause some people to buy your next project when they wouldn't have bought it otherwise due to bad ratings.

However, you can expect that after publishing a clunker, your reputation might suffer from then on, and your games after that might sell worse.

Another factor to consider when you release an AO (adults-only rated) title under the same company label as your previous games, you might get trouble to advertise both that game and your non-AO titles together on your company website. It might get your whole company website labeled as porn and get blocked by censorship programs, even those sub-pages which don't mention your pornographic games at all.

Also many payment, advertisement and digital distribution providers refuse to work with pornographers. This might make it more difficult for you when your business model depends on them. (**Edit:** As of September 2018, Steam is now allowing pornographic games. **Edit2:** Although, as of November 2018, they keep delisting some games, apparently if the characters look too young for their comfort. I would recommend anyone who considers to release a pornographic game for Steam to wait a while until Valve made clear where they draw the lines).

And then certain game journalism outlets have become increasingly conscious of sexism lately and might boycot reporting about your non-porn games when your company is also known for producing pornographic titles.

For example, the reason Koei Tecmo stated why they won't release Dead of Alive Xtreme 3 outside of Asia is because that they are afraid of media backlash affecting their brand negatively (and that game isn't even pornographic - just full of bikini babes). Another publisher, HuniePot, responded to this with an offer: "sell the distribution rights to us. We don't care when people call us pervs".
> 2 votes

# Answer
I'm glad you wan to get into the industry as a Publisher. To be honest I don't know why more indie developers haven't turned into publishers. It seemed to work for Digital Revolver. Anyways, a company messing up on one game does hurt it's name and sales. But as long as you haven't become "Digital Homicide Studio" by releasing a bunch of crap games without any sense of mind, then you should be okay. Just remember that people aren't going to want you to publish there game if you haven't made a name for your self or made good games. Also, Genre is a publisher is key. Having different genres isn't something you have to worry about. Just make games that you would buy. Anyways I hope this helped. Sorry for my Bad English
> 0 votes

---
Tags: marketing, publishing
---


# Question
Title: What language do you program in Lumberyard?
I've looked through the FAQ on amazons site and all they mention is C++/Lua for the web service stuff. Can i assume it's C++ for the game content itself or something else (the visual script editor doesn't count)?

# Answer
> 1 votes
The engine uses both Lua and C++ for game development and server scripting. But the visual editor isn't scripted with the visual editor.

---
Tags: lumberyard-engine
---


# Question
Title: What JavaScript and or Html should engine I should use?
I took some classes on JavaScript and I know some html5. I took these classes so I can Learn Game Development!! I want to use JavaScript and not C# or C++ because I want easy cross platform with the browser. So do you guys know any good Java Game Engines? To be more specific: I really just want a Engine that has a good community so I can ask many questions. I like to learn a Engine step by step like asking the engines community how to do user controls or moving backgrounds. I hope someone get what I mean but any JavaScript engine you could name would be Great!! Thank you for Responding or reading! Sorry for my bad English.

# Answer
I am using BabylonJS a lot. If you want to go into 3D Games, it is as of right now the best engine you can get and it's free. In the HTML5 Game Devs Forum the whole community is gathered. They are super nice and helpful. The creators and the main contributers are helping people with questions realy fast!

For 2D games Phaser might be for you. There is also a great community on the HTML5 Game Devs Forum for Phaser. But to be honest I havent really much experience with it.
> 3 votes

---
Tags: javascript, html5
---


# Question
Title: What is the code for panning a camera from touch input? (libGDX + scene2d)
I would like the user to pan around a game world by dragging their finger on a touch screen - just like Google Maps. I tried a few things but I'm not having much success thus far.

Here is where I'm up to.

```
public class Game extends ApplicationAdapter {
    Stage stage;

    @Override
    public void create () {

        stage = new Stage(new ScreenViewport());
        Gdx.input.setInputProcessor(stage);

        // Create world
        Planet planet = new Planet();
        stage.addActor(planet);

        stage.addListener(new ActorGestureListener() {

            public void pan(InputEvent event, float x, float y, float deltaX, float deltaY) {
                ((OrthographicCamera)stage.getCamera()).translate(deltaX, deltaY);
                stage.getCamera().update();
            }
        });

    }

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

        stage.act(Gdx.graphics.getDeltaTime());
        stage.draw();
    }

}

```

# Answer
> 0 votes
I needed to use negatives of the deltas when doing the translate!

The required code changes are just the one line:

```
((OrthographicCamera)stage.getCamera()).translate(-deltaX, -deltaY);

```

It's a bit jumpy when panning though.

I also discovered I can omit stage.getCamera().update(); and it still works

---
Tags: java, libgdx, scene2d
---


# Question
Title: Make Button always be at corner of the screen?
How can I make a button always be at the corner of the screen like so:

Currently I have a button, child of canvas that does this:

# Answer
There are terms called *Anchor/Reference/Pivot Points* on which objects are based, means they will draw respective to their anchor points. For example if you set pivot at very left of the button and you command it to draw at (0,0), then button's left part will be at (0,0).

So in your case when you are using Unity UI, there is also an option to set *pivot* point.

And from there, you can set your pivot. In you case, you have to set your anchor to the top left, as like this,

Actually it will maintain the distance from top-left of the screen
> 1 votes

---
Tags: unity, gui
---


# Question
Title: Slick2D Simple StateBasedGame not working
I recently started trying to work with outside Java libraries like Slick2D. This is my first time doing so, so I basically have no clue what I am doing.

I tried making a simple StateBasedGame that only displays a menu bar showing three options. The problem is that in my 'Game' class, the initStatesList() method isn't being called and I don't know why not. Here's the code:

Game class

```
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.StateBasedGame;

public class Game extends StateBasedGame {
    public Game(String title) {
        super(title);
    }

    public static void main(String[] args) {
        Game game = new Game("Text Based");
    }

    @Override
    public void initStatesList(GameContainer arg0) throws SlickException {
        System.out.println("InitStates");
        addState(new Menu());
    }
}

```

Menu class:

```
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;

public class Menu extends BasicGameState {

    private int ID = 1;

    @Override
    public void init(GameContainer arg0, StateBasedGame arg1) throws SlickException {
    }

    @Override
    public void render(GameContainer container, StateBasedGame game, Graphics g) throws SlickException {
        g.setColor(Color.white);
        g.drawString("Higher or Lower", 50, 10);

        g.drawString("1. Play Game", 50, 100);
        g.drawString("2. High Scores", 50, 120);
        g.drawString("3. Quit", 50, 140);

    }

    @Override
    public void update(GameContainer arg0, StateBasedGame arg1, int arg2) throws SlickException {

    }

    @Override
    public int getID() {
        return ID;
    }

}

```

I have no clue why it doesn't work...

# Answer
You need to use AppGameContainer.
> -2 votes

---
Tags: java, software-engineering, slick
---


title: Custom Terrain Shader Normal Map Issue?

text:
# Question
Title: Custom Terrain Shader Normal Map Issue?
I've been developing a custom terrain shader in Unity. And I've been having problems with my normal maps. Even after hours of fiddling I still haven't fixed it yet. There are 2 noticeable issues: 1. Normal maps don't appear on vertices whose normal points towards the X axis 2. Normals just don't appear "correct", as in they're faint, and don't look as good as standard terrain normals.

The following pictures should help illustrate my point:  Unity's standard terrain shader (Stretched normals but they work perfectly)  My shader (Washed out normals, and normals on the x axis are virtually non-existent)

I have stripped my code down to the bare essentials and I still get this result.

My code:

```
     // Set by terrain engine
        [HideInInspector] _Control ("Control (RGB)", 2D) = "red" {}
        //[HideInInspector] _Splat3 ("Layer 3 (A)", 2D) = "white" {}
        [HideInInspector] _Splat2 ("Layer 2 (B)", 2D) = "white" {}
        [HideInInspector] _Splat1 ("Layer 1 (G)", 2D) = "white" {}
        [HideInInspector] _Splat0 ("Layer 0 (R)", 2D) = "white" {}
        //[HideInInspector] _Normal3 ("Normal 3 (A)", 2D) = "bump" {}
        [HideInInspector] _Normal2 ("Normal 2 (B)", 2D) = "bump" {}
        [HideInInspector] _Normal1 ("Normal 1 (G)", 2D) = "bump" {}
        [HideInInspector] _Normal0 ("Normal 0 (R)", 2D) = "bump" {}
        [HideInInspector] [Gamma] _Metallic0 ("Metallic 0", Range(0.0, 1.0)) = 0.0
        [HideInInspector] [Gamma] _Metallic1 ("Metallic 1", Range(0.0, 1.0)) = 0.0
        [HideInInspector] [Gamma] _Metallic2 ("Metallic 2", Range(0.0, 1.0)) = 0.0
        //[HideInInspector] [Gamma] _Metallic3 ("Metallic 3", Range(0.0, 1.0)) = 0.0
        [HideInInspector] _Smoothness0 ("Smoothness 0", Range(0.0, 1.0)) = 1.0
        [HideInInspector] _Smoothness1 ("Smoothness 1", Range(0.0, 1.0)) = 1.0
        [HideInInspector] _Smoothness2 ("Smoothness 2", Range(0.0, 1.0)) = 1.0
        //[HideInInspector] _Smoothness3 ("Smoothness 3", Range(0.0, 1.0)) = 1.0

        // used in fallback on old cards & base map
        [HideInInspector] _MainTex ("BaseMap (RGB)", 2D) = "white" {}
        [HideInInspector] _Color ("Main Color", Color) = (1,1,1,1)
    }

    SubShader {
        Tags {
            "SplatCount" = "3"
            "Queue" = "Geometry-100"
            "RenderType" = "Opaque"
        }

        CGPROGRAM
        // Physically based Standard lighting model, and enable shadows on all light types
        #pragma surface surf Standard fullforwardshadows
        // Use shader model 3.0 target, to get nicer looking lighting
        #pragma target 3.0
        #pragma multi_compile_fog
        #pragma exclude_renderers gles
        #include "UnityPBSLighting.cginc"
        #include "Tom's Terrain-Helper.cginc"

        // Access the Shaderlab properties
        half _depthThresh;

        uniform sampler2D _Control;

        sampler2D _Splat0,_Splat1,_Splat2;
        //float4 _Splat0_ST;
        //float4 _Splat1_ST;
        //float4 _Splat2_ST;
        sampler2D _Normal0,_Normal1,_Normal2;

        half _Metallic0;
        half _Metallic1;
        half _Metallic2;
        //half _Metallic3;

        half _Smoothness0;
        half _Smoothness1;
        half _Smoothness2;
        //half _Smoothness3;

        half _Height0;
        half _Height1;
        half _Height2;

        float _TextureScale;
        half _NormalStrengh;
        float _TriplanarNormals;

        struct Input {
            float3 worldPos;
            float3 worldNormal;
            float2 uv_MainTex : TEXCOORD0;
            float2 uv_Control : TEXCOORD1;
            float2 uv_Splat0 : TEXCOORD2;
            float2 uv_Splat1 : TEXCOORD3;
            float2 uv_Splat2 : TEXCOORD4;
            //float2 uv_Splat3 : TEXCOORD5;

            //float2 uv_Normal0 : TEXCOORD6;
            //float2 uv_Normal1 : TEXCOORD7;
            //float2 uv_Normal2 : TEXCOORD8;
            //float2 uv_Normal3 : TEXCOORD9;
            INTERNAL_DATA
        };

        void SplatmapVert(inout appdata_full v, out Input data)
        {
            UNITY_INITIALIZE_OUTPUT(Input, data);
            float4 pos = mul (UNITY_MATRIX_MVP, v.vertex);
            //UNITY_TRANSFER_FOG(data, pos);

            v.tangent.xyz = cross(v.normal, float3(0,0,1));
            v.tangent.w = -1;
        }

        half _Glossiness;
        half _Metallic;
        fixed4 _Color;

        void surf (Input IN, inout SurfaceOutputStandard o) {
            fixed4 splatControl = tex2D(_Control, IN.uv_Control);

            fixed4 nrm = 0.0f;
            //nrm += splatControl.r * normal0;
            //nrm += splatControl.g * normal1;
            //nrm += splatControl.b * normal2;
            nrm += splatControl.r * tex2D(_Normal0, IN.uv_Splat0);
            nrm += splatControl.g * tex2D(_Normal1, IN.uv_Splat1);
            nrm += splatControl.b * tex2D(_Normal2, IN.uv_Splat2);
            //nrm /= b1 + b2 + b3;

            nrm.g = nrm.r;

            fixed3 finalNormal = UnpackNormal(nrm);

            //Final output
            o.Normal = finalNormal;
            o.Albedo = 1;
            o.Alpha = 1;
            o.Smoothness =dot(tex2D(_Control, IN.uv_Control), half3(_Smoothness0, _Smoothness1, _Smoothness2));
            o.Metallic = dot(tex2D(_Control, IN.uv_Control), half3(_Metallic0, _Metallic1, _Metallic2));
        }
        ENDCG
    }
    Dependency "AddPassShader" = "Hidden/TerrainEngine/Splatmap/Standard-AddPass"
    Dependency "BaseMapShader" = "Hidden/TerrainEngine/Splatmap/Standard-Base"

    Fallback "Nature/Terrain/Diffuse"
}

```

You might notice that a lot of this code is very similar to unity's code. And even though this code is so similar it still behaves differently.

So my question is; what am I missing?

Thanks in advance.

Some other images to help understand my problem:

# Answer
> 0 votes
It turns out that I had forgotten to declare my vertex shader in the pragma.

This line:

```
 #pragma surface surf Standard fullforwardshadows

```

Becomes, this line:

```
#pragma surface surf Standard vertex:SplatmapVert fullforwardshadows

```

Note the addition of:

```
vertex:SplatmapVert

```

---
Tags: unity, shaders, terrain, normal-mapping
---


# Question
Title: directX rotation of a 3d cube inconsistent
i'm trying to develope a simple 3d cube in directX that can be rotated in any direction by dragging the mouse.

It works in the following way: i drag the mouse to the right or left, and the cube rotates along the Y axis accordingly. The same goes if i drag the mouse up or down (in this case the rotation is along the X axis).

The problem occurs if i rotate my cube 180 degree on X-axis. After this, every rotation along the Y-axis is in the opposite direction, so that if i try to move it towards positive Y-axis it moves in negative Y-axis.

I understand it has something to do with the way i do the transformations, but i can't fix the problem on my own.

```
D3DXMatrixRotationY(&MatRotY, rotation.y);
D3DXMatrixRotationX(&MatRotX, rotation.x);
D3DXMatrixTranslation(&MatTran, position.x, position.y, position.z);

D3DXMatrixMultiply(&MatRotXY, &MatRotY, &MatRotX);
D3DXMatrixMultiply(&MatRotXY, &MatRotXY, &MatTran);
D3DXMatrixMultiply(&worldMatrix, &worldMatrix, &MatRotXY);

```

PS: i know i shouldnt be using D3DX at all, but i'd like to solve this problem before having to switch to a different library.

thanks

# Answer
> 0 votes
For every matrix rotation, there is an axis and an angle. You are trying to marry your rotations to your 3d world's basis axes and applying Euler angles about them. That can invite issues when one of your cube's local axis is not aligned with the world axis and you want to rotate your cube around it or a 2nd world axis.

So the root of your problem is that you are storing your cube's rotation as Euler angles to access and modify the rotation next frame. There are various ways to store a rotation; Euler angles, matrix, quaternion, axis/angle... etc. For what you are doing, Euler angles does not lend itself as the best way. If your were to choose a Matrix to store your cube's orientation/position, you could simply store the rotation in the `worldMatrix` and do not use `rotation` anymore.

---

In your process, you are taking two identity matrices and applying an x rotation to one and a y rotation to the other then trying to combine them.

But what if you didn't start with two identify matrices? Why not simply apply the current frame's mouse x movement to last frame's `worldMatrix` directly and right after that take the current frame's mouse y movement and apply that to the "just modified" `worldMatrix` directly. All rotations will be as expected. The only thing is that you now have no idea what the overall `rotation.X, rotation.Y` is because you aren't modifying `rotation.X & Y` directly, your modifying `worldMatrix` directly. Hopefully the rest of your code can be OK with that. Trying to hang onto those `rotation` values is leading you down an unnecessarily complex path.

All you need to determine to do this is what axis to rotate the cube/`worldMatrix` around for each rotation and how much.

Since your rotations are tied to your mouse movements and the 3d world involvement of the mouse has to do with camera orientation and position, the rotational axes that you want your cube/`worldMatrix` to rotate about are actually stored in the view matrix.

```
//pseudo code

//extract mouse movement for this frame
float mouseX = input.GetMouseXMovementSinceLastFrame();
float moustY = input.GetMouseYMovementSinceLastFrame();
//scale mouseX & Y if necessary for your application

//get rotation axis
Matrix camWorld;
d3dxMatrixTranspose(&camWorld, &view);
d3dxVector3 xAxis;
d3dxVector3 yAxis;

xAxis.X = camWorld._11;
xAxis.Y = camWorld._12;
xAxis.Z = camWorld._13;

yAxis.X = camWorld._21;
yAxis.Y = camWorld._22;
yAxis.Z = camWorld._23;

//set worldMatrix to origin for rotation purposes but save position info
d3dxVector3 cubePosition;
cubePosition.X = worldMatrix._41;
cubePosition.Y = worldMatrix._42;
cubePosition.Z = worldMatrix._43;
worldMatrix._41 = 0;
worldMatrix._42 = 0;
worldMatrix._43 = 0;

//apply rotations

d3dxMatrixRotationAxis(&worldMatrix, yAxis, mouseX);
d3dxMatrixRotationAxis(&worldMatrix, xAxis, mouseY);
d3dxMatrixTranslation(&worldMatrix, cubePosition);

```

Now the `worldMatrix` has had rotations applied to it that are relative to the camera's vertical and horizontal axes and no matter what position the camera is at or what rotational orientation it has while looking at your cube, the cube will always rotate as expected. You just lost the overall rotation of your cube is relative to Euler angles. But that does not matter if the only reason you kept Euler angles anyway was to get `worldMatrix` orientated correctly, because this does that in a simpler fashion for this particular application.

If your camera's position and orientation were locked and never moved, you could calculate the rotation axes once and reuse them each frame simplifying this even more.

---
Tags: c++, 3d, directx
---


# Question
Title: Character doesn't move. I think I've tried everything, so I'm asking [Unity3D]
The animations are playing fine, however I can't manage to move my character. My script:

```
using UnityEngine;
using System.Collections;

public class PlayerMovement : MonoBehaviour {

    public float turnSmoothing = 20f;
    public float speedDampTime = 0.1f;
    public float jumpHeight = 8.0f;

    private Animator anim;
    private Rigidbody rb;
    // Use this for initialization
    void Start () {
        anim = GetComponent<Animator>();
        rb = GetComponent<Rigidbody>();

    }

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

    }

    void FixedUpdate()
    {
        float h =- Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        MovementManagement(h,v);

    }

    void MovementManagement (float horizontal, float vertical)
    {
        if (horizontal != 0.0f || vertical != 0.0f)
        {
            anim.SetBool("Move", true);
            anim.SetFloat("Speed", 6.0f, speedDampTime, Time.deltaTime);
            Rotating(horizontal, vertical);

        }
        else
        {
            anim.SetFloat("Speed", 0.0f);
            anim.SetBool("Move", false);
        }

    }

    void Rotating (float horizontal, float vertical)
    {
        Vector3 targetDirection = new Vector3(horizontal, 0.0f, 0,0f); //2.5D I just want to move on the x-axis atm
        Quaternion targetRotation = Quaternion.LookRotation(targetDirection, Vector3.up);
        Quaternion newRotation = Quaternion.Lerp(rb.rotation, targetRotation, turnSmoothing * Time.deltaTime);
        rb.MoveRotation(newRotation);
    }

}

```

My character's inspector:

# Answer
Well, you only change the rotation of the rigidbody, not the position. See the documentation http://docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html
> 1 votes

---
Tags: movement, unity, third-person-view, single-player
---


title: C# temporary variable error

text:
# Question
Title: C# temporary variable error
I get the following error when running the code below:

> Cannot modify a value type return value of \`UnityEngine.Transform.position'. Consider storing the value in a temporary variable

```
public void Hello () {

    transform.position.y -= 1;
}

```

What's the problem?

# Answer
> 2 votes
The problem is that `x`, `y` and `z` are components of "transform.position", and you are not allowed to make changes to single components of properties. In other words, you can not directly assign a value to `transform.position.x`,`transform.position.y` or `transform.position.z` or similar things. You have to do the following:

```
mynewY = transform.position.y - 1;
transform.position.y = new Vector2(transform.position.x,mynewY);

```

or if you want to do it directly:

```
transform.position.y = new Vector2(transform.position.x,transform.position.y - 1);

```

In 3D cases, the solution is similar:

```
mynewY = transform.position.y - 1;
transform.position.y = new Vector2(transform.position.x,mynewY,ransform.position.z);

```

or if you want to do it directly:

```
transform.position.y = new Vector2(transform.position.x,transform.position.y - 1,ransform.position.z);

```

The same applies in almost all other situations when using C# in Unity.

# Answer
> 2 votes
You cannot change single coordinates of a Vector3 since it is immutable. Assign a new Vector3:

```
transform.position = new Vector3(transform.position.x,
                                 transform.position.y - 1,
                                 transform.position.z);

```

Note that the immutability of a class or struct is a design decision. Structs are not generally immutable. Immutability is realized by making all the properties readonly and making fields private. The initial values are usually passed as constructor parameters. Of course methods are not allowed to change the values.

# Answer
> 2 votes
transform.position is a Vector3. You can find this information by going to the declaration of Vector3 via your IDE or looking up the member in Unity's documentation: http://docs.unity3d.com/ScriptReference/Vector3.html

Structs in C# are call-by-value, which means that you effectively get a copy of them when you get them and any changes to the values will be made on this "copy". You therefore can NOT change a structs values after it has been created. You can read more on structs and their (often weird behavior) on MSDN: https://msdn.microsoft.com/en-us/library/0taef578.aspx

You assign a new instance of a Vector3 to the transform.position member as follows:

```
transform.position = new Vector3(transform.position.x, transform.position.y -1, transform.position.z);

```

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