# Question
Title: Changing the color data of an instance of a shared texture? MonoGame
I want to load multiple instances of a texture on the screen and be able to change the color of each one individually by clicking on it.
I've tried many different ways and currently I'm creating two 2d arrays.
`Tile[,] tiles = new Tile[10,10];` (a class I made, essentially just overrides draw) and `Texture2D[,] squareTex = new Texture2D[10,10];`
Right now I've tried and change the color data but it applies it to every single Tile I have on screen. That doesn't make any sense to me because I am creating 100 different Texture2D's, unless changing color data applies it to the image file itself which seems weird to me. Any ideas?

**Game1**

```
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace AlgorithmMidterm
{
    /// <summary>
    /// This is the main type for your game.
    /// </summary>
    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        Tile[,] tiles = new Tile[10, 10];
        static Texture2D[,] squareTex = new Texture2D[10, 10];

        bool lmbDown = false;

        Point grid = new Point(10, 10);

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            this.IsMouseVisible = true;
            graphics.PreferredBackBufferWidth = 1000;
            graphics.PreferredBackBufferHeight = 1000;
            this.Window.Position = new Point(this.Window.Position.X, 0);
            graphics.ApplyChanges();

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            for (int x = 0; x < grid.X; x++)
            {
                for (int y = 0; y < grid.Y; y++)
                {
                    squareTex[x, y] = Content.Load<Texture2D>("square");
                }
            }
            //squareTex = Content.Load<Texture2D>("square");

            for (int x = 0; x < grid.X; x++)
            {
                for (int y = 0; y < grid.Y; y++)
                {
                    tiles[x, y] = new Tile(squareTex[x, y], new Vector2(x * 100, y * 100));
                }
            }

            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// game-specific content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();

            MouseState ms = Mouse.GetState();

            if (ms.LeftButton == ButtonState.Pressed)
            {
                lmbDown = true;
            }

            if (lmbDown && ms.LeftButton == ButtonState.Released)
            {
                lmbDown = false;
                bool exit = false;
                for (int x = 0; x < grid.X && !exit; x++)
                {
                    for (int y = 0; y < grid.Y && !exit; y++)
                    {
                        if (tiles[x, y].collisionRect.Contains(ms.X, ms.Y))
                        {
                            Color[] data = new Color[squareTex[x,y].Width * squareTex[x, y].Height];
                            squareTex[x,y].GetData(data);
                            Color colorFrom = Color.White;
                            Color colorTo = Color.YellowGreen;
                            for (int i = 0; i < data.Length; i++)
                                if (data[i] == colorFrom)
                                    data[i] = colorTo;
                                else if (data[i] == colorTo)
                                    data[i] = colorFrom;

                            //Texture2D temp = tiles[x, y].textureImage;
                            //temp.SetData(data);
                            squareTex[x, y].SetData(data);
                            exit = true;

                        }
                    }
                }
            }

            // TODO: Add your update logic here

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            spriteBatch.Begin();
            for (int x = 0; x < grid.X; x++)
            {
                for (int y = 0; y < grid.Y; y++)
                {
                    tiles[x, y].Draw(gameTime, spriteBatch);
                }
            }
            spriteBatch.End();

            // TODO: Add your drawing code here

            base.Draw(gameTime);
        }
    }
}

```

**Tile**

```
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace AlgorithmMidterm
{
    class Tile
    {
        public Texture2D textureImage;

        protected Vector2 position;

        //This constructor has no "ms per frame"
        public Tile(Texture2D textureImage, Vector2 position)
        {
            this.textureImage = textureImage;
            this.position = position;
        }

        public virtual void Update(GameTime gameTime, Rectangle clientBounds)
        {

        }

        public virtual void Draw(GameTime gameTime, SpriteBatch spriteBatch)
        {
            // Draw the sprite via the passed SpriteBatch
            spriteBatch.Draw(textureImage, position, Color.White);
        }

        // Gets the collision rect based on position, framesize and collision offset
        public Rectangle collisionRect
        {
            get
            {
                return new Rectangle(
                    (int)position.X,
                    (int)position.Y,
                    textureImage.Width,
                    textureImage.Height
                    );
            }

        }
    }
}

```

# Answer
The color of the tile in the `Tile.cs` draw() method is hardcoded with `Color.White`. That already gives a less possible chance to change it individually.

Try giving the `Tile.cs` a color variable. And then change that color variable in the main method.

In your Tile.cs, add this variable:

```
public Color color = Color.White;

```

Also in your Tile.cs, change inside your draw() method to this:

```
spriteBatch.Draw(textureImage, position, color);

```

Then, in your Game1.cs, change the part where you add the color to this:

```
if (lmbDown && ms.LeftButton == ButtonState.Released)
        {
            lmbDown = false;
            bool exit = false;
            for (int x = 0; x < grid.X && !exit; x++)
            {
                for (int y = 0; y < grid.Y && !exit; y++)
                {
                    if (tiles[x, y].collisionRect.Contains(ms.X, ms.Y))
                    {
                        tiles[x, y].color = Color.YellowGreen; //<--The needed line of code.

                        //Texture2D temp = tiles[x, y].textureImage;
                        //temp.SetData(data);
                        squareTex[x, y].SetData(data);
                        exit = true;

                    }
                }
            }
        }

```

I think that's all you needed, please let me know if you're still having problems.
> 2 votes

---
Tags: c#, xna, textures, monogame, color
---


# Question
Title: Game title having 2 similar words with another game
Hello I'd like to get some advice because we're developing a game called "Dungeon Boss Fight" and we recently discovered that a game named "Dungeon Boss" is already available in mobile by Bigfish Games, the same place we are going to release our game. I've used this website (http://tmsearch.uspto.gov) and found that there isn't a trademark for "Dungeon Boss". Now is it safe to release our game with the current title or should we change it? Or should we trademark our title "Dungeon Boss Fight" and hope for the best? The other game came out 5 years ago btw.

# Answer
Trademark law doesn't offer a yes/no answer in this case.

Can they sue? Yes. Can they win? Yes.

Will they sue? Only one way to find out. Will they win? Only one way to find out.

Will it cost you money if they sue? Yes. Will it cost them money if they sue? Yes.

Here's a case of how far some companies go to "protect" their trademarks.

In my personal opinion, Dungeon Boss Fight is not a great name anyway, so just find a better name.
> 3 votes

---
Tags: copyright, trademark
---


# Question
Title: Should I use attack effect collision to detect when damage is dealt?
I am wondering what a common way for actually dealing damage to different units is. Imagine a game like starcraft for example, should damage be done like this:

> 1) zealot attacks zergling, deal damage to zergling

or

> 2) zealot attacks zergling, create an attack effect on zergling. When this effect collides with the zergling deal damage to said zergling.

The advantage of 2 is for projectiles (like a dragoon attack) will deal damage when the attack collides with the target unit.

What are your thoughts about this in general? Are there other ways of doing this?

# Answer
I would recommend not to use particles or any FX related element to check collisions, as these can be very unreliable. I would recommend to either check the collision using hotboxes on the characters themselves, or define a basic mesh in the general shape of the attack animation to check the collsion with the attack effect. Hopefully that helps :)
> 1 votes

---
Tags: game-design, design-patterns
---


title: Timing a sound effect

text:
# Question
Title: Timing a sound effect
Why does this not work? I'm trying to get the sound effect before the visual, but I don't hear it until I move away from the location. This is part of a routine that is called from Update on the Player. Thanks in advance for any hints.

```
    if (carriedObject.name == "HandTorch") {
        float d =findNearest (o.transform);
        if (d < 0.5f) {
            ASource.clip = woosh;
            ASource.Play ();
            float duration = woosh.length;
            StartCoroutine (WaitForSound (duration));
            o.transform.Find("Flame").gameObject.SetActive(true);
            o.transform.Find ("MyTorch").gameObject.SetActive (true);
        }
    }
}

public IEnumerator WaitForSound(float duration)
{
    yield return new WaitForSeconds(duration);
}

```

# Answer
> 2 votes
It is because what you are doing is starting the coroutine, that independently waits, and then you continue calling all the remaining stuff. What you can do is to either execute all the wanting actions inside the coroutine:

```
    public IEnumerator WaitForSound(float duration)
    {
        yield return new WaitForSeconds(duration);
        o.transform.Find("Flame").gameObject.SetActive(true);
        o.transform.Find ("MyTorch").gameObject.SetActive (true);
    }

```

You could do a more generic coroutine to wait for something, then do a certain sequence encapsulated in an **Action**, with a Lambda Expression:

```
    using System; //You must use this namespace for Actions

    void Start()
    {
        StartCoroutine(WaitForSound(duration,
        ()=>
        {
            Debug.Log("The wait ended, I shall proceed");
        }));
    }

    public IEnumerator WaitForSound(float duration, Action onWaitEnds)
    {
        yield return new WaitForSeconds(duration);
        if(onWaitEnds != null) onWaitEnds();
    }

```

Or you could play with AudioSource's property **isPlaying** which is true while it is playing:

```
    public IEnumerator WaitUntilAudioSourceIsPlaying(AudioSource _source, Action onSourceStopsPlaying)
    {
        while(_source.isPlaying)
        {
            yield return null;
        }

        if(onSourceStopsPlaying != null) onSourceStopsPlaying();
    }

```

Hope it helps.

---
Tags: unity, sound-effects
---


# Question
Title: What is the meaning of this "MuxOMX ctor" log in LibGDX?
I'm developing a game in Java for Android using LibGDX with Android Studio. I'm using the AssetsManager class and I've noticed weird log when finishLoading() is finished:

```
10-17 22:15:17.108 31943-32282/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
10-17 22:15:17.146 31943-32285/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
10-17 22:15:17.182 31943-32291/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
10-17 22:15:17.231 31943-32296/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
10-17 22:15:17.284 31943-32299/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
10-17 22:15:17.330 31943-32302/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
10-17 22:15:17.385 31943-32309/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
10-17 22:15:17.425 31943-32312/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
10-17 22:15:17.462 31943-32315/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
10-17 22:15:17.499 31943-32318/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
10-17 22:15:17.546 31943-32321/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
10-17 22:15:17.607 31943-32324/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
10-17 22:15:17.654 31943-32327/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
    10-17 22:15:17.698 31943-32330/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
    10-17 22:15:17.740 31943-32334/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
    10-17 22:15:17.782 31943-32339/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
    10-17 22:15:17.822 31943-32343/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
    10-17 22:15:17.864 31943-32346/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
    10-17 22:15:17.911 31943-32353/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
    10-17 22:15:17.953 31943-32356/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
    10-17 22:15:17.997 31943-32359/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
    10-17 22:15:18.043 31943-32362/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
    10-17 22:15:18.087 31943-32365/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
    10-17 22:15:18.139 31943-32368/com.gadarts.parashoot.android I/OMXClient: MuxOMX ctor
...

```

Does anybody have any idea what it means? I've searched everywhere and couldn't find anything relevant. It doesn't make any problem, it just blows my Android Monitor with these logs.

Thanks in advance!

# Answer
This looks like a bit of errant logging code left in place by some library. A quick dig around the internet led me to this reference source file, for example, with a constructor implementation that simply does nothing but dumps that log message:

```
MuxOMX::MuxOMX(const sp<IOMX> &mediaServerOMX, const sp<IOMX> &mediaCodecOMX)
    : mMediaServerOMX(mediaServerOMX),
      mMediaCodecOMX(mediaCodecOMX) {
    ALOGI("MuxOMX ctor");
}

```

Further digging finds a bunch of similar threads about the issue, such as this one from some IRC logs, that come to the same conclusion as above: this is a rogue log statement left in some Android library that is harmless, if annoying.

The head version of that file doesn't contain the log statement. So it's possible you could alleviate this by upgrading your Android version.

It's also possible you can configure the log viewer to ignore "information" level levels, which would suppress this visually.
> 1 votes

---
Tags: java, android, libgdx, assets, android-studio
---


title: Recursive Unity Coroutine

text:
# Question
Title: Recursive Unity Coroutine
I have a co-routine which is heavily reliant on calling itself to get the task done. I have tested it and the code works fine, the problem is that the co-routine will return every time that it enters itself recursively.

```
IEnumerator test(arg1, arg2)
{
    // I want to pause here
    yield return null;

    // I don't want to pause on any of these
    yield return test(arg1, arg2);
    yield return test(arg1, arg2);
    yield return test(arg1, arg2);
    yield return test(arg1, arg2);
}

```

In the example above I have a yield return at the top that is hit and pauses the co-routine, thats fine. Then there are the calls to itself below which also pause the co-routine. **How do I avoid pausing the co-routine on the recurcive calls?**

# Answer
Though the comments on this question I was able to find a solution to this. If I transfer it over to the example I posted above it would look like this:

```
//global valiables
private const int Speed = 200; //amount of iterations per frame
private int skipCount = 0; //counter for the iterations

private IEnumerator PropagateSearch(arg0, arg1)
{
    if ((skipCount = ++skipCount % Speed) == 0)
        yield return null;

    //work here

    {
        IEnumerator count = PropagateSearch(arg0, arg1);
        while (count.MoveNext()) if (skipCount % Speed == 0) yield return null;
    }

    {
        IEnumerator count = PropagateSearch(arg0, arg1);
        while (count.MoveNext()) if (skipCount % Speed == 0) yield return null;
    }

    {
        IEnumerator count = PropagateSearch(arg0, arg1);
        while (count.MoveNext()) if (skipCount % Speed == 0) yield return null;
    }

    {
        IEnumerator count = PropagateSearch(arg0, arg1);
        while (count.MoveNext()) if (skipCount % Speed == 0) yield return null;
    }
}

```

This will go through the co-routine and will only break when there it iterates `Speed` amount of times. With that you can fine tune the amount of work that happens per frame.
> 2 votes

---
Tags: unity, c#, coroutines, recursion
---


# Question
Title: Is Frustum Culling by itself enough for Consoles and Mobiles?
Software occlusion culling is often expensive, especially for smaller and older devices.

Is frustum culling alone adequate on systems that can optimally display 10k triangles at most?

If not, are there any relatively fast techniques for determining which objects (both moving and static) occlude others?

# Answer
> 5 votes
One thing to consider is what is the worst-case for your game design. If you're going to be able to go to the top of the hill and see all objects unoccluded at the same time, then an occlusion system will in fact be *slowing* the performance of your game in that scenario.

Another thing to consider is the consequences of not culling for your target platform and game:

* If it is simply a drop in performance, then the performance drop may alrady be acceptable if you still have playable framerates. This is subjective and contingent upon your genre. A turn-based game can be acceptably played at lower frame rates than a fast-paced FPS might for example.
* However, if a lack of culling means that you get polygon dropout then it's a different story. For example on the Nintendo DS, you can get visible artifacts where polygons simply disappear as you exceed your polygon budget.

The latter may necessitate changes to your level design or the inclusion of some polygon reduction technology.

I've had some success with these techniques for reducing polygons:

* precomputed PVS with artist placed sectors for static geometry and with artist placed portals for culling dynamic objects, but then again our project had occlusion characteristics guaranteed by the game design (corridors and rooms with limited outdoor areas). If the camera is in a specific sector, then there will be a limited number of sectors visible from that sector. This means that only the static geometry and dynamic geometry in those sectors needs to be rendered. Of course this only works if your world geometry is amenable to natural occlusion characteristics.
* A level of detail (LOD) system where we simply switched to an imposter/billboard for distant objects. In the cases that we did have lots of objects visible, this helped when some of those objects were guaranteed to be far enough from the camera to be rendered with a lower level of detail with no noticeable quality degradation. Imposters/LOD systems are a nice way to reduce polygon count if you don't hit the worst case where you have thousands of objects in the same room very close to the camera and all rendered at full detail.
* Simply not drawing distant objects. The pop-out can be minimized by fading these objects out as they go further and then simply not drawing them when the alpha reaches zero. You can also tag these on a per object basis. eg. trees may be drawn at a further range than grass, but mountains would always be visible.

# Answer
> 2 votes
I would limit the amount you are doing at runtime. Precompute as much as possible - a PVS is a fairly standard techique for static geometry, and depending on your environment perhaps portals would work (these fairly easily cope with moving objects too).

# Answer
> 2 votes
It really depends on the problem space! If you drawing overhead because you are sending stuff through the pipeline that is occluded, and that overhead is too much, or if you get too much overdraw eating fillrate then you obviously need to investigate other culling methods (or optimizing your render pipeline or shaders). Whether that solves the problem depends on your implementation of the new culler, and the win you gain by not drawing the stuff.
If overdraw is an issue, the culler can be a win because you shift performance from the GPU to the CPU. If your pipeline is the bottleneck then it's basically whether your pipeline is too expensive.
BSP and portals seem obvious culling algorithms that are relatively cheap and reduce overdraw, but they're generally for indoor scenes. ABT or octrees can also alleviate overdraw at a cheap price. Most of them only optimize for static geo though (although you can cull some dynamics away using the knowledge it provides.
As an aside: if shader cost is the issue, make sure you are drawing back to front.

# Answer
> 0 votes
culling objects that are occluded from your view is generally worth it, especially on older GPUs with less dedicated memory (including all integrated chips) and less support for parallel processing pipelining.

This also includes console hardware, that is often more optimized for throughput and more exotic component capabilities, like some non-volatile ram properties, but in return less energy efficient and slower over all.

This older hardware benefits more from all the branches that come with more culling, as culling bounds are basically a bounding volume hierarchy.

Some culling methods benefit more from being less general, and more optimized towards special hardware limits. In return they scale significantly worse, can perform horrible for higher resolutions.

Culling is a good option, nearly essential at some point, for good performance and backwards compatibility and support for older hardware.

---
Tags: 3d, optimization, opengl-es, scene-graph
---


title: How to write a unit test in Unity?

text:
# Question
Title: How to write a unit test in Unity?
is there a tutorial and patterns to write unit tests in Unity ?

Should we use the classical c# way and test the code or should we test the interactions in UI ? If so how?

# Answer
In Unity 2017.2

Unity has a feature called Unity Test Runner which is an integration of NUnit with the Unity Editor.

You can access it through the menu: **Window \> Test Runner**

For more information, see the documentation in the Unity Manual
> 1 votes

---
Tags: unity, testing, unit-testing
---


# Question
Title: How can I improve the display of my png files?
I develop a mini Android game available from my github (also the release apk file). The game is for kids and you are supposed to catch falling object and get points for that. Now I just created png files for the sprites and added alpha channel in gimp. It looks better, before alpha channel:

After:

But I'm not 100 % satisfied with the rough edges of the sprites. Am I correct that if I do the alpha channel more exact then the sprites will look even better (without the edges) or is there some other mistake that I make with the sprites?

Edit: With new background image, it looks like this.

Edit 2: I used jamie the monkey now of BSD license which renders better. It seems to be more exact work in GIMP that is needed.

Edit 3. Now I am satisfied. Thanks.

# Answer
After you Add the alpha channel, how did you remove the background? If there are still visible bits along the edge, you can use the Eraser tool to go over the edges, or the selection tool to select an area covering the edges and press \[Delete\] to remove the selected portion.

Remember, this works differently with images with an alpha channel or without; deleting without an alpha channel can only set the pixels to the background color. so even if you did this before adding alpha, you'd have to do it again.

---

Your image is here: (github link). You can definitely see the shadow pixels that weren't removed (I guess when you used the magic wand to remove the White background?) -- you'll have to erase that part in Gimp.
> 1 votes

---
Tags: libgdx, sprites, image, transparency
---


# Question
Title: How to view 360 degree images in Unreal Engine 4
Is there any way I can view 360 degree images in UE4, Ive read about possibly mapping it onto a hollow sphere however it always seems warped. I am working on a virtual tour and would like to be able to transition between multiple 360 images such as the ones found here : http://www.wpanorama.com/panoramas.php?page=01n . I am new to Unreal Engine and any help would be greatly appreciated. Ideally I would like to have it mapped to a sky sphere with the image on the sky sphere changing based on the "point" the user clicks on however I am not sure how I could go about this.

# Answer
There are multiple ways to map a 360-degree environment to a flat image.

In this case, the WPanorama images look like they were mapped cylindrically, so map it to the sides of a cylinder around your camera and it avoids the "warped" look. As you can see from the source images, they don't include "ground" or "overhead sky" so mapping it to a sphere would distort the image.
> 2 votes

---
Tags: unreal-4, image
---


# Question
Title: How to clamp the rotation between two values in unity 3d
How can i clamp the rotation of cube between two values and then rotate between them gradually

Details Of what i Want When I press A or D keys cube should Rotate On Y Axis from 0 to 13 deg gradually and when key is released cube back to straight position

# Answer
> 1 votes
You could use Mathf.Clamp to constrain your values, to rotate smoothly, transform.Rotate would do the trick, but the problem comes with orientation, as I see it. You may parent that cube to an object that keeps a fixed orientation, so you rotate the cube as a child. I am asuming you want to rotate on the Y-Axis, so here is an example:

```
public Transform cubeChild;
public float minAngle;
public float maxAngle;
public float rotationSpeed;

void Update()
{
    cubeChild.Rotate(transform.up, (rotationSpeed * Time.deltaTime));
    cubeChild.rotation.eulerAngles = new Vector3
                                    (
                                        transform.eulerAngles.x,
                                        Mathf.Clamp(transform.eulerAngles, minAngle, maxAngle),
                                        transform.eulerAngles.z
                                    );
}

```

The code is untested, but I'll try it in a couple of minutes to confirm you.

---
Tags: unity, 3d
---


title: Phaser problem with .damage oneshots

text:
# Question
Title: Phaser problem with .damage oneshots
I am trying to damage player or enemy when they collide.(enemy will be damaged when collided with bullet and player will be damaged when collided with monster)

```
this.game.physics.arcade.overlap(this.laser.bullets, this.zombies, this.hitEnemy, null, this);
this.game.physics.arcade.overlap(this.player, this.zombies, this.playerdmg, null, this);

}

playerdmg(player,zombies){
player.damage(1); //oneshots

}

hitEnemy(bullets,zombies){

zombies.damage(1); // one shots
console.log(zombies.health) // this is -1
console.log("hit");
bullets.kill();

}

```

Collision detection works.but i cant damage player or zombies. this is how i set health after creating player:

this.player.health=10;

how do i set zombies health correctly ? because i create them with for loop like this:

```
this.zombies = this.game.add.group();
this.zombies.enableBody=true;
this.zombies.health = 5;
for (var i = 0; i < 30; i++)
   {
        var zombie = this.zombies.create(this.game.world.randomX, this.game.world.randomY, 'zombie');
        let zombieHealthBar = new HealthBar(this.game, zombie, 25, 10, -20, 0, '#FF0000', '#00FF00');

   }

```

# Answer
`zombies` is a `Group`. You should set health on each individual `zombie`.

By the way, your function signature for `hitEnemy` is misleading. It is a callback that receives one `bullet` and one `zombie`, the pair that have overlapped.
> 1 votes

---
Tags: javascript, html5, phaser
---


# Question
Title: Android Phone Back Button not working Unity
I take an empty gameobject and a script in which I just write below code to handle back button in android phone, but it's not working.

```
if (Input.GetKeyDown (KeyCode.Escape)){
            // Escape button pressed
            print("Escape");
}

```

# Answer
> 1 votes
```
if (Input.GetKeyDown (KeyCode.Escape)){
  // Escape button pressed print("Escape");
}

```

This code is working. Problem was i was testing it through unity remote 5. that's why it was taking input from keyboard not from mobile, When i tested it by making apk its working.

---
Tags: unity, android
---


title: How to make Save/Load system in libgdx?

text:
# Question
Title: How to make Save/Load system in libgdx?
I'm making a game but I don't know how to make it savable. By savable I mean I would like to be able to put a save and load button in the game so you can save it and close it and if you open it again You can load back to where you were.

# Answer
> 4 votes
Yes, it is possible. You can use the `Preferences` interface for that. Here is an example:

```
//This will get your preferences from storage
Preferences prefs = Gdx.app.getPreferences("myprefs");

//If the preference key is empty, create it by putting a value into it
if(!prefs.contains("key")) prefs.putInteger("key", "1337");

//Get value from a preference key "key" (must not be empty)
int val = prefs.getInteger("key");

//Do something with your value and put it back to the preference
val+=something;
prefs.putInteger("key", val);

//This will finally save the changes to storage
prefs.flush();

```

This works equivalent for other data types like float, String, boolean, ...

For reference, take a look at this. It will help you a lot

---
Tags: libgdx
---


title: Interaction Design for Games

text:
# Question
Title: Interaction Design for Games
What is the difference between user interaction for games as opposed to productivity apps?

# Answer
Before my career as a game designer, my training was in industrial design, studying classic interaction design. And at my first studio we spent a fair bit of time building productivity apps as you describe to pay the bills when game work wasn't always reliable. ;)

While most of the same principles of user-centered design apply, there are some useful distinctions I've found:

1. **Your user has to want to be there.** Generally speaking, every interaction we design should be as enjoyable and fulfilling as we can make it, of course. But in productivity apps you can get by with a dry or uninspiring user experience as long as you get the job done. The user is there to accomplish a task.

But players come to games *for the experience itself* \- you can't coast on pure functionality. If the means of interacting with the software isn't enjoyable or satisfying (and this includes well-crafted "negative" experiences like feeling fear / sadness / anger if your game is promising horror / drama / etc..), then players won't play the game and will look elsewhere.

This also means conceiving of your users/players and their needs in a different way. I won't go into all the details of player motivation models we use in games here, but suffice it to say that we often need to consider more of the person's emotional situation and preferences to deliver a game experience that will resonate with them, as opposed to a productivity tool they find handy.
2. **Responsiveness is everything.** In productivity apps and web design, if a change takes effect and presents visual/audio feedback inside a tenth to half a second, it's considered instantaneous from the user's point of view.

In games, every frame matters. A player input that doesn't trigger a perceptible response until a frame or two later (still 3-6x faster than the web designer's "instantaneous") can cause the game's controls to feel "floaty, sluggish, squishy" in a way that's difficult for players to pin down - it's felt in the texture of the interaction rather than consciously detected. This goes double and triple in VR, where maintaining high framerates and snappy interactions are key to maintaining a sense of immersion and minimizing simulation sickness.

This isn't just a problem for engine programmers to minimize input latency and maximize framerate. It's also in the types of feedback we as designers choose to provide to the player. If a character has momentum and can't turn on a dime to respond to a sudden change in input without breaking the physics or the realism of their animation, we can do things like have the character turn their head to look in the new direction, or change their movement sound to signal back to the player "I heard you" immediately, even if the full consequences of the input will manifest over a few more frames.

Keeping this interaction feedback loop tight and the audio-visual-tactile signals rich can create immense toy-like delight in just operating the controls. For more on the power of feedback in interaction design for games, I recommend checking out "Game Feel," "Juice it or Lose it," "The Nuance of Juice," and "Pizzazz First, Polish Later" ;)
3. **Unique interaction vocabulary.** Through iteration in many games, we've developed a shared language of what various controls generally do, at least in the default mapping (customization is important too, but for now I'll focus on the out-of-the-box experience). Your right stick is camera, your left mouse button is main weapon, you move with WASD, the gamepad face button in the "South" position is "Accept" and often "Jump," while "East" is "Cancel," unless you're in Japan where the convention is reversed. etc.

Sticking to these familiar conventions helps a game feel expected / right, and minimizes confusion or error for players with experience from other games. This is in principle the same as following interaction conventions in other disciplines, just specialized to the particular vocabulary we've developed in games.

Note that this can also be a double-edged sword. It's easy as experienced players and game creators to take these conventions completely for granted, and forget that they're not universally known. The first game with dual analog FPS controls that we now consider standard was initially reviewed as "almost unplayably difficult to control" - and those controls didn't get fundamentally easier, we just trained players to get used to them. So some of these conventions can pose a significant barrier to bringing new players into the fold, and it's important to consider how your target audience's past play experience will inform their control expectations.
4. **Friction is fun.** In classic interaction design we'd seek to minimize obstacles in the user's path, so they can get to their goal in as few steps or with as little effort as possible.

But a game is at its most fundamental level, as Bernard Suits defines it, "the voluntary attempt to overcome unnecessary obstacles." If we took out every bump in the road and optimized for getting the player to the victory screen in no time, it's unlikely the player would get to feel they'd "overcome" anything!

So effective game design often means making the interactions *less* effective, as measured in pure task-completion efficiency. A long slow wind-up attack can feel more exciting than one that's instantaneous, and provide more challenge for strategically deciding when to use it / how to react to it, creating more gameplay out of a completely artificial and unnecessary delay. Or if the player needs to drag items together one by one to assemble them manually, this can feel more tactile and satisfying than if the game automated this labour.

Instead of trying to minimize friction and adversity, the challenge comes in tuning its amount, to be approximately proportional to the player's capability and readiness to overcome it, which changes from player to player and over time as they master the game's systems.

Here I haven't even gotten into the design considerations of adversarial interactions, where two users are actively competing to out-perform one another, which I think is just about unique to games.
> 4 votes

---
Tags: game-design, user-experience, usability
---


# Question
Title: What is the difference between a HUD and a GUI in a game?
Does anyone know the difference between a graphical HUD (head-up display) and a GUI (graphical user interface) in a game? Is a HUD part of the GUI and just displaying information? That would mean that I can not technically interact with a HUD while I could with the GUI (e.g. clicking a button)? Or are both terms basically describing the same thing?

Note: I'm talking about these words while being ingame.

See the following example:

What would be described as GUI in this image and what as HUD?

# Answer
I'd argue that HUDs *are* graphical user interfaces: they're ways to present information back to the user graphically.

In contrast to what some other answers say, the term GUI doesn't require that every element be directly interactive - the label next to a control on a form is still part of the GUI, guiding the player in how to interact with the system, even if clicking the label itself doesn't accomplish anything.

What distinguishes HUD elements is the particular *way this information is displayed* to the user: "Heads-Up Display" was coined in contrast to a light or dial on a control panel, where the user would need to look down / away from the window and world in front of them to check on it. The defining feature of being "Heads-Up" is that the information is overlaid over the world, rather than in its own separate dashboard, and it often tracks with the user's camera or head rather than needing them to turn to a particular location to see it (particularly notable in VR games).

So for example, in this StarCraft screenshot, I would argue that the selection and health overlays on the units, and resource counters in the corner, all constitute HUD, being overlaid on the game world. The map, order buttons, and selection readouts in the chrome below would not be HUD because they exist outside the world viewport.

It's more common to see the term HUD applied in 1st person and 3rd person over-the-shoulder perspectives than to top-down/isometric games like this one, but I wanted to find an example that would contrast both styles. First person examples with both HUD and non-HUD chrome are harder to find, but old-school dungeon crawlers sometimes use this kind of mix too. Here the "Small Cave Troll" label, level, and health bar are HUD since they're overlaid on the world, while the rest of the GUI sits (mostly) outside the player's window to the world and isn't "heads-up" in this sense.

Some games will also have floating windows or panels, like inventory management interfaces, that sit on top of the viewport. When these are mostly opaque, I'd generally consider them to be non-HUD GUI elements because they obscure a sizeable chunk of the game world in much the same way as the dashboard chrome examples.
> 79 votes

# Answer
**Interactivity**.

A HUD is not interactive: it displays information only, it cannot be clicked, dragged, closed, etc.

A GUI in a game is like any other UI: it is interactive. It has menus, buttons, scrollbars and other UI elements.

The term Head Up Display refers to fighter jets: displaying information on a canopy means that the pilot does not need to look down at the gauges and indicators on the dashboard.
> 26 votes

# Answer
> Is a HUD part of the GUI and just displaying information?

Yes. Head Up Display (as the name suggests) is just to display information while you are in-game. However in some scenarios HUD may be intractable. For example in a mobile based game there are on screen buttons to perform different actions while you are **in-game**.
> 6 votes

# Answer
GUI and HUD are **inexact terms**, meaning people will know what they mean, *unless they require specifics*. The specific meanings attached to the terms depend on subculture, company, the current project, or the team within that project you're working on. Proof: divergent answers on this very question.

The term HUD in terms of graphics often reminds of Terminator and Robocop. Beyond this, its meaning in games is **not standardized** and if you want to use the term to refer to specifics, you need to explain your use of the term first:

The GUI is *usually* everything you see on screen. It can in- or exclude some things that are not part of the main window, such as system tray menus, application icons, etc. It can include the input handling, but doesn't have to. GUI is sometimes incorrectly used to refer to visual + audio. The better term in these cases would be UI, but sometimes GUI is used.
> 5 votes

# Answer
The gui in a game is pretty much everything gets displayed on the screen except for the game world,such as the player, the gun, the game world etc.. the hud is everything used to show information like the players health, the bullets count etc
> 3 votes

# Answer
The term HUD comes from fighter planes where information to be relayed to the pilot is projected onto the cockpit screen rather than displayed on instruments within the cockpit. The point being that the pilot does not need to look away from the world outside to gather relevant information. It is used by analogy in computer games so it does not have a clear, well-defined, usage.

Typically, the HUD is the part of the user interface that is (a) is not moved with the gameworld (excepting elements that are positioned relative to in-game objects, e.g. health or name labels) and (b) is overlayed onto the game world, so that it can be obscured only by other HUD elements. In most cases the HUD is 2D, but some FPSs (in particular) now have 3D HUD elements.
> 3 votes

# Answer
The GUI is what the user *interacts* with. The HUD is what the game is *displaying* to the player.

I'd say everything in the image is the HUD. If you open the menu, that would be the GUI.
> 1 votes

# Answer
I look at it this way: an HUD displays ongoing information to the user during the game, while a GUI appears in response to certain events and allows the user to *control* some aspect of the game. Usually the user cannot interact with other parts of the game while the GUI is open.

So for example in Minecraft, the health bar and hotbar at the bottom is an HUD, providing information about the player's status at all times. The player's inventory and the inventories for interacting with chests, furnaces, etc. are GUIs that the player opens by pressing a key or right-clicking on the blocks in the world. While the GUIs are open, the player cannot perform other actions or even clearly see what else is happening in the game.

I'd also apply the term "GUI" in game design to menus for controlling the game itself, such as the menus to exit the game or change settings that typically appear when the user presses the escape key. Although these aren't part of the gameplay; they're more part of the surrounding application.
> 0 votes

# Answer
## GUI is a poor term to use in game dev

Classically, GUI meant any visual element that either provided information to the user or could be interacted with in some way.

In (most) games, that means EVERYTHING on the screen falls under this classic description of GUI.

The term HUD exists explicitly to supersede this now useless term (in this field). It displays information on top of the game layer that the player needs to make informed decisions.
> 0 votes

---
Tags: gui, terminology, hud
---


# Question
Title: RaycastHit2D.normal sometimes giving an unexpected direction
I'm working on a little pong clone and trying to implement collisions using triggers.

I have a ball which OnTriggerEnter sends out a raycast from the ball's position towards its velocity. I then take the .normal of the raycast hit and use that to figure out bounce angle.

most of the time this is working, but in a few cases (I can't quite figure out the common element between them) It doesn't work and gives a completely wrong number.

Video example, https://webmshare.com/xAe7X

Full code,

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

public class BallScript : MonoBehaviour {
    public Vector2 velocity;
    public float angularVelocity;
    private Vector2 collisionNormal;

    void FixedUpdate(){
        transform.Translate (velocity.x, velocity.y, 0);
        Debug.DrawRay ((Vector2)transform.position - velocity * 2, velocity * 5,Color.red);
    }

    void OnTriggerEnter2D(Collider2D other) {
        FindCollisionNormal ();
        ReflectVelocity ();
    }

    public void FindCollisionNormal(){
        RaycastHit2D[] hits = Physics2D.RaycastAll ( (Vector2)transform.position - velocity * 2, velocity * 5);
        foreach (RaycastHit2D hit in hits) {
            if (hit.collider.GetType () == typeof(BoxCollider2D)) {
                collisionNormal = hit.normal;
                collisionNormal = new Vector2 (collisionNormal.y, collisionNormal.x);
            }
        }
    }

    public void ReflectVelocity(){
        print (collisionNormal);
        velocity = -velocity + 2 * (Vector2.Dot (velocity, collisionNormal) * collisionNormal);
    }
}

```

# Answer
> 2 votes
The problem here is the use of RaycastAll instead of Raycast.

As its name implies, RaycastAll gives you *all* hits along a given ray - not just the first one.

Taking a screengrab from the video, just before the ball does its first "weird" bounce:

Here RaycastAll says don't stop after the first hit, keep checking for more - so it also finds a second hit where the ray intersects the floor, even though that's much further away.

"But wait, isn't the raycast only covering the red line?" Nope. Check the docs on RaycastAll:

```
public static RaycastHit2D[] RaycastAll(
                             Vector3 origin,
                             Vector3 direction,
                             float distance = Mathf.Infinity, // Aha!
                             int layermask = DefaultRaycastLayers,
                             ...

```

When we provide just the two vector arguments to this raycast method, they're taken as origin and direction (ignoring length), and the third parameter, distance, is taken to be infinite.

This wouldn't be so bad - just needlessly inefficient - if we only grabbed the first hit from the returned array. Since RaycastAll returns the hits in order by distance, that would still get the correct first hit.

But by processing the hits in a loop like this:

```
foreach (RaycastHit2D hit in hits) {
   if (hit.collider.GetType () == typeof(BoxCollider2D)) {
       collisionNormal = hit.normal;
       collisionNormal = new Vector2 (collisionNormal.y, collisionNormal.x);
   }
}

```

the `collisionNormal` variable is left in whatever state it was set to by the *last* entry in the array - the exact opposite of what we want!

You can fix this by using a plain Raycast to get just the closest hit. Or you can use a CircleCast which will behave a bit better in tight corners (since a ray is infinitely thin, it can get deeper into a crevice than the ball itself can, potentially finding the wrong bounce in some cases).

As jgallant says in the earlier answer, you should *also* avoid mixing physics movement/collision checks with direct position changes via transforms. This can lead to teleportation glitches and unnecessary juddering, although it's not the root cause of this particular error. Rigidbody2D.velocity and Rigidbody2D.MovePosition let you keep the motion in the domain of the physics system, avoiding conflicts.

# Answer
> 0 votes
When relying on Rigidbodies for collision response, you cannot use direct position translations like you are doing in your FixedUpdate()

```
 transform.Translate (velocity.x, velocity.y, 0);

```

This will cause your physics engine to fail at some point as you are literally forcing a teleport on each frame. What you need to do instead, is apply the movement to your Rigidbody instead.

You can try something like:

```
transform.GetComponent<RidigBody2D>().position += velocity;

```

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


# Question
Title: How to destroy particles system after its work is over
How can i stop particle system after player get destroyed

# Answer
> 11 votes
First of all, your particle system appears to have looping enabled. You usually don't want that for an explosion effect. When that's not the case, then there is likely something wrong with one of the scripts which control that explosion effect or your particle effect uses a sub-emitter which loops.

In Unity Version 2017.2, the particle system got a new parameter `Stop Action` on the "Main" module. The default value is "None". When you set it to "Destroy", the game object with the particle system will be destroyed as soon as there are no alive particles anymore. But this, of course, won't do much when you still have "Looping" enabled.

When you don't want to update to 2017.2, you can add a "self-destruct" script to the game object with the particle effect which destroys it after a specific time elapsed:

```
public class SelfDestruct : MonoBehaviour {
     public float timeLeft;

     void Update() {
          timeLeft -= Time.deltaTime;
          if (timeLeft <= 0.0f) {
              Destroy(this.gameObject)
          }
     }
}

```

Set "Time Left" in the inspector to the number of seconds you want the object to exist.

---
Tags: unity
---


# Question
Title: Why is there a discrepancy between these two transform.up vectors?
I was trying to implement a feature which required `transform.up`, the result didn't match the green axis gizmo displayed in the editor so I assumed it was being put off by the rotation of the object despite expecting the gizmo to adapt to that. I then modified the prefab such that everything was now child to an empty object and the secondary objects were child to that instead of the rotating model, and wrote a script that simply copies the transform so that it tracks. This still didn't show the values expected from what the gizmo in the editor showed. I then did a `Debug.LogError` in the track script and this time the result was as expected.

Why is `transform.up` showing the value expected from the local y-axis gizmo but when passing a reference to the original script and checking `tracked.transform.up` gives off results?

---

To reproduce in a simpler environment I set up a simple test scene.

Simple default cube with the hierarchy structure shown in the screenshot. The transform values are as follows:

```
parent zeroed
x:0, y:-90, z:0 for cube
x:0, y:-90, z:90 for TrackPoint

```

Scripts are as follows:

test.cs - attached to trackpoint

```
private void Update()
{
    Debug.LogError(transform.up);
}

```

Track.cs - attached to tracker

```
public Transform transformToTrack;

private void Update()
{
    transform.position = transformToTrack.position;
    transform.rotation = transformToTrack.rotation;
    Debug.LogError(transform.up);
}

```

byref.cs - attached to cube

```
public GameObject refObj;

private void Update()
{
    Debug.LogError(refObj.transform.up);
}

```

When run, if you clear the console then click pause you'll see that one of them differs from the others. I don't understand why. My project and this sample scene differ in which it is that is giving unexpected results but the results are inconsistent with what I would expect.

But wouldn't they all give the same result?

# Answer
I called the method that ran the Debug.LogError(obj.transform.up); inside a coroutine, the coroutine essentially had an off by one error and given that the object was moving in 90 degree steps and I didn't see the data transforming I didn't realize my mistake.

My effort to reproduce accidentally had the test script attached to the wrong object giving its actual transform, which is why I mistakenly thought the resulting data backed my error up. I shouldn't work when tired.

In the end I realized my error when I discovered my reproduction was misguided and I changed the Debug.LogError into the Update callback, allowing me to see the data transform, recognise that it was essentially an off by 1 error and fix the call so that it was no longer off by 1 move. This gave the expected results.

Perhaps if you experience a similar problem you should check for race conditions and/or off by one errors.

You should try to see your data as it transforms, could give valuable insight into the problem.
> 1 votes

---
Tags: unity, transformation, direction
---


# Question
Title: What is the size limit to the Unity 2017.2 Tilemap?
I've been digging through the documentation on the Tilemap feature of Unity 2017.2.

Does Unity limit the maximum number of tiles it will support for a particular tilemap mesh?

I know that each tile is instantiated once and used to texture the quads on the Tilemap mesh at runtime, so I would guess that the mesh quad count limit is ultimately dependent on the hardware, and more or less is arbitrarily high.

Is that a correct assumption, or is there a hard cap in the engine?

# Answer
**Your RAM is your limit**.

The following tests were performed on a system with these specs:

* Intel i5-6600
* 16 GB RAM
* NVIDIA GeForce GTX 1070
* Windows 7 Home Premium

Here is a script I ran which grows a tilemap by filling it with a single tile (32x32 pixels). The Method `Grow()` adds another column and another row to the current map. The method gets called 100 times each update.

```
public class TileTest : MonoBehaviour {

    public Tile tile;
    private Tilemap tilemap;

    public int currentSize;

    void Start () {
       tilemap = GetComponent<Tilemap>;
        Grow();
    }

    void Update() {

        for (var i = 0; i < 100; i++) {
            Grow();
        }
        Debug.Log(currentSize);
    }

    private void Grow() {
        for (int x = 0; x < currentSize; x++) {
            tilemap.SetTile(new Vector3Int(x, currentSize, 0), tile);
        }
        for (int y = 0; y < currentSize; y++) {
            tilemap.SetTile(new Vector3Int(currentSize, y, 0), tile);
        }
        tilemap.SetTile(new Vector3Int(currentSize, currentSize, 0), tile);

        currentSize++;
    }
}

```

After a few minutes, my computer ran out of memory and Unity crashed. At that point it was at 8400x8400 (70 million) tiles and Unity.exe was consuming slightly above 11 GB of RAM according to the task manager.

Well, but what about *sparse* maps?

Here is a different script which placed a single tile at increasing x and y coordinates in increments of 100 tiles:

```
public class TileTest : MonoBehaviour {

    public Tile tile;
    private Tilemap tilemap;
    public int currentSize;

    void Start () {
        tilemap = GetComponent<Tilemap>();
    }

    void Update() {
        tilemap.SetTile(new Vector3Int(currentSize, currentSize, 0), tile);
        currentSize+= 100;
    }
}

```

The memory footprint of Unity.exe in fact increased very little, which hints that empty tileset cells require almost no RAM. However, the FPS kept falling as the tileset was growing. It hit 60 Fps at 30000x30000, 30 Fps at 60000x60000 and 15 Fps at 90000x90000. The Fps stayed that low when I removed the script while the test-game was running. So this slowdown was not from changing the tilemap. It was simply from rendering it. So when you want to create a really huge open world game, you might have to use multiple smaller tilemaps which you create and destroy at runtime.

Conclusions: **Huge but mostly empty tilemaps do not use much RAM, but they are a rendering bottleneck**, even when most of it is not in the camera viewport.

I then experimented with this script which generates tilemaps with a given size:

```
public class TileTest : MonoBehaviour {

    public Tile tile;
    public int xSize;
    public int ySize;

    void Start () {
        Tilemap tilemap = GetComponent<Tilemap>();

        for (int x = 0; x < xSize; x++) {
            for (int y = 0; y < ySize; y++) {
                tilemap.SetTile(new Vector3Int(x, y, 0), tile);
            }
        }
    }
}

```

I used this script to generate a 8192x8192 map. It took a few minutes, but when the script was finished, it ran at steady 95 Fps.

Conclusion: **Maps with millions of tiles are feasible, at least on gaming PCs**.
> 29 votes

---
Tags: unity, 2d, tilemap
---


# Question
Title: How can i position a canvas and text child above gameobject?
Better do it automatic by script.

The Display Information in the Hierarchy is the Canvas. Not sure if to change the Canvas Render Mode now it's on World Space. I want the Text to be displayed above one of the Spheres for example the first Sphere.

But to do it in script to move automatic the canvas to be above the sphere or any other gameobject.

The Text

I have 5 Spheres so i want to put above each one a number text: 1,2,3,4,5 Above the first Sphere the number 1 on the second Sphere in the Hierarchy the number 2 and so on.

This is what i tried but it's not changing the canvas position at all:

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

public class canvasui : MonoBehaviour
{
    public Canvas canvas;
    public GameObject[] waypoints;
    public Vector3[] sizes;

    // Use this for initialization
    void Start ()
    {
        waypoints = GameObject.FindGameObjectsWithTag("waypoint");
        sizes = new Vector3[waypoints.Length];
        for (int i = 0; i < waypoints.Length; i++)
        {
            sizes[i] = waypoints[i].GetComponent<Collider>().bounds.size;
        }

        canvas.transform.position = new Vector3(
            waypoints[0].transform.position.x,
            waypoints[0].transform.position.y + sizes[0].y / 2,
            waypoints[0].transform.position.z);
    }
}

```

I attached the script to new empty gameobject.

UPDATE:

I'm using this script now:

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

public class canvasui : MonoBehaviour
{
    public GameObject floatingCanvas;   /// Canvas that you wan to be above your GameObject
    public float yPadding;              /// Padding on the Y-Axis.
    private MeshRenderer renderer;      /// MeshRenderer Component.

    void Awake()
    {
        renderer = GetComponent<MeshRenderer>();
    }

    void Update()
    {
        Vector3 newCanvasPosition = new Vector3
                                    (
                                        transform.position.x,
                                        ((transform.position.y + renderer.bounds.extents.y) + yPadding),
                                        transform.position.z
                                    );
        floatingCanvas.transform.position = newCanvasPosition;
    }
}

```

But the text for example "1" is not above the sphere: It's no the left bottom.

# Answer
> 1 votes
As @Sidar suggested, you could play with the bounding box dimensions of your GameObject, and an offset to have a padding. The **Bounds** are structs, used in **Coliders**, **Mesh** and **Renderers**, you can check more about the struct in the **Bound's API.**

This is a quick example to apply it in code (here I am using MeshRenderer, but again, you can access **Bounds** from the classes previously mentioned):

```
public GameObject floatingCanvas;   /// Canvas that you wan to be above your GameObject
public float yPadding;              /// Padding on the Y-Axis.
private MeshRenderer renderer;      /// MeshRenderer Component.

void Awake()
{
    renderer = GetComponent<MeshRenderer>();
}

void Update()
{
    Vector3 newCanvasPosition = new Vector3
                                (
                                    transform.position.x,
                                    ((transform.position.y + renderer.bounds.extens.y) + yPadding),
                                    transform.position.z
                                );
    floatingCanvas.transform.position = newCanvasPosition;
}

```

Hope it helps with the positioning.

# Answer
> 1 votes
I normally like to just create the Text and then drag the UI text and parent it to the Object.

Next pick center center for the paragraph alignment and then addcomponent Canvas to the text itself.

Change the canvas to screenspace camera and drag the camera in the slot. now switch it back to worldspace and position the text anywhere you want.(switching it like so helps the text just not up and disappear in the game view sometimes)

From there the only scripting you would need is to just set it active when you want to see it or have it always face the camera if needed.

note: if you go this route you may have to adjust the rect scaling also to get a nice crisp view of the text. Or if it is not quite center with the object right click and reset the rect then re-scale to around 0.02-0.03 and it should work good with best fit checked.

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


# Question
Title: How can I make a gameobject snap to something when it gets close to it?
Any idea if there is a way I can make a gameobject snap to something when it gets close to it? Like drag a cube around and when it gets close to something then snap to it.

# Answer
> 2 votes
Any position you want it to snap to as it gets close, you could do something like this (Psuedo code)

(assuming you already have code to move the object) \- Create a parent object, that contains the script SnapOn.
\- That parent object is what moves.
\- The child object should have the visible element, cube for instance. \- In the SnapOn Script, \- - The anchors are used to define positions the object can snap to \- - The "movable" is the child object that actually renders. \- - SnapDistance is how far away to snap.

```
class SnapOn {
public Transform[] anchors;
public Transform movable;
public float SnapDistance = 1f;

Update() {
  // first we find the closest object, but looping through all and saving the shortest distance (and position)
  var distance = float.max;
  var point = vector3.zero;
  foreach(var anchor in anchors)
  {
    var d = Vector3.Distance(transform.position, anchor.position);
    if (d < distance)
    {
      distance = d;
      point = anchor.position;
    }
  }

  // now we decide if there is anything it should snap to.
  if (distance > SnapDistance) // too far, keep renderable with movable.
  {
    movable.position = transform.position;
  }
  else // position is close enough to snap point put it there.
  {
    movable.position = point;
  }
}

```

if you neglect to track the moving position separate from where to render the object, the instance you are on a snap on to a position, you will unlikely be able to move the object far enough in a single frame to allow it to "unsnap"

---
Tags: unity
---


# Question
Title: How can I select a sequence of objects by moving mouse in Unity?
I have a board of tiles in my game in **Unity** and I have to select a sequence of tiles by moving the pressed mouse over the tiles like if I would select letters in a such game like on the screenshot. Please, hint me, how can I implement this functionality. I'm just a newby in Unity.

# Answer
> 0 votes
A solution for my problem is using this two methods `OnMouseEnter()` and `OnMouseExit`.

---
Tags: unity, unityscript
---


# Question
Title: How can I move a 3d object to a known Cartesian point on the surface of a sphere?
I'm trying to figure out how to move an object from one Cartesian point to another located on the surface of a 3D sphere. So that the object will follow the spherical coordinate system (Theta and Phi)

I've a function that converts a Cartesian to Spherical but how can I make it work on the surface of a sphere just like we are using the equation of a line y=mx+b when moving from one point to another on a flat surface?

I'm going to use it to move an object from its point to a selected point somewhere else on the sphere so that the object will move in a straight line but following the curvature.

# Answer
> 0 votes
The general idea between interpolation between two points on a sphere is to use a "Spherical Lerp" function or "slerp" for short.

Some engines have it as a built in function, for others, either it's only available for Quaternions or missing entirely and you'll have to write it yourself. The page on wikipedia provides a good explanation of both the Vector and Quaternion versions of slerp, but to summarize the Vector3 part here:

The basic formula involves finding the spherical combination of the start and end points with a ratio of the sin of the subtended angle.

```
slerp(a , b, t) =
  theta = acos(dot(a, b))
  (sin((1-t)theta) / sin(theta)) * a+ (sin(t * theta)/sin(theta)) * b

```

if you are animating in a loop, you can use a more efficient algorithm by iteratively reflecting each point after you've found the first intermediate point.

```
c = dot(p0, p1) * 2
pk+1 = c pk − pk−1

```

# Answer
> 0 votes
It's very simple. First of all, you need to get the line between the starting and ending point (marked with purple on the following image):

(The green point is the center of the sphere, **a** is the vector from the center to the start point and **b** is the vector from the center to the end point, the red line is the path on the surface of the sphere)

Now to make the object follow the surface of the sphere you simply need to interpolate between the start and endpoint, get the vector between that point and the center (if **c** is the center and **p** is the interpolated position, then the vector is simply **p** \- **c**), normalize it, multiply it by the radius of the sphere, then add the result to the center of the sphere to get the object's position.

Pseudo code:

```
vec3 getPositionOnSphere(vec3 startPos, vec3 endPos, vec3 center, float radius, float time) {
    vec3 pos = (endPos - startPos) * time + startPos
    return normalize(pos - center) * radius + center
}

```

The problem with this approach is that the end result won't be uniform. You should generate the line first, then move the object on that.

---
Tags: 3d, sphere, waypoints
---


# Question
Title: Restructure Voronoi data to custom graph without brute force
I was asking about a very specific method (`MakeCorner`) in another question but we reached to conclusion that changing that single method is not giving the speedup Im hoping for, therefore it requires restructuring on higher level.

---

Im restructuring the data from Voronoi diagram to custom graph structure for my own needs. I made this code as obvious and short as possible (removed validation *etc*).

Voronoi output Im working with is rather standard across all the libraries and languages, most useful ones being:

* list of sites coordinates - `Vector2` in this case
* edges - each edge has 2 endpoints (`Vector2`) and 2 sites (`Vector2`) on both sides

---

Main theme of this code is for each component (site, edge, corner) to directly hold all the data or rather pointers to all the surrounding components, example:

Site knows about:

* all the surrounding corners that form the cell around the site
* all the surrounding edges that form the cell around the site
* all the neighbor sites

**Question:** how to avoid using `MakeCorner` method? How to fuse all the edges endpoints that "meet" to single corner without spending 98-99% of total time to it? 10,000 points, ~2500ms.

```
public class ExampleClass {
    List<Site> sites;
    List<Edge> edges;
    List<Corner> corners;

    void BuildGraph(Voronoi voronoiData) {
        sites = new List<Site>();
        edges = new List<Edge>();
        corners = new List<Corner>();

        List<Vector2> siteCoords = voronoiData.SiteCoords();
        List<VEdge> voronoiEdges = voronoiData.edges;

        // for fast site lookup by Vector2
        Dictionary<Vector2, Site> sitesByV2 = new Dictionary<Vector2, Site>();

        // populate sites
        for (int i = 0; i < siteCoords.Count; i++) {
            Site site = new Site(siteCoords[i]);
            sites.Add(site);
            sitesByV2.Add(siteCoords[i], site);
        }

        // populate edges, corners and relationships between all 3 (site, edge, corner)
        for (int i = 0; i < voronoiEdges.Count; i++) {
            // both edge endpoints
            Vector2 leftEnd = voronoiEdges[i].leftEnd;
            Vector2 rightEnd = voronoiEdges[i].rightEnd;
            // sites on both sides of edge
            Vector2 leftSite = voronoiEdges[i].leftSite;
            Vector2 rightSite = voronoiEdges[i].rightSite;

            Edge edge = new Edge();
            edges.Add(edge);

            // corners to edges (reuse corner if one edge already created it)
            edge.leftEnd = MakeCorner(leftEnd); // MakeCorner is the slow part!
            edge.rightEnd = MakeCorner(rightEnd); // 98-99% of total time

            // sites to edges
            edge.leftSite = sitesByV2[leftSite];
            edge.rightSite = sitesByV2[rightSite];

            // edge to sites
            edge.leftSite.edges.Add(edge);
            edge.rightSite.edges.Add(edge);

            // edge to corners
            edge.leftEnd.protrudes.Add(edge);
            edge.rightEnd.protrudes.Add(edge);

            // sites to sites (neighbor sites)
            AddToList(edge.leftSite.neighbors, edge.rightSite);
            AddToList(edge.rightSite.neighbors, edge.leftSite);

            // corners to corners
            AddToList(edge.leftEnd.adjecent, edge.rightEnd);
            AddToList(edge.rightEnd.adjecent, edge.leftEnd);

            // corners to sites
            AddToList(edge.leftSite.corners, edge.leftEnd);
            AddToList(edge.leftSite.corners, edge.rightEnd);

            AddToList(edge.rightSite.corners, edge.leftEnd);
            AddToList(edge.rightSite.corners, edge.rightEnd);

            // sites to corners
            AddToList(edge.leftEnd.touches, edge.leftSite);
            AddToList(edge.leftEnd.touches, edge.rightSite);

            AddToList(edge.rightEnd.touches, edge.leftSite);
            AddToList(edge.rightEnd.touches, edge.rightSite);
        }
    }

    void AddToList(List<T> v, T x) {
        if (x != null && v.IndexOf(x) < 0) v.Add(x);
    }

    // dictionary bucketed by x coordinate for faster lookup
    Dictionary<int, List<Corner>> lookup = new Dictionary<int, List<Corner>>();

    Corner MakeCorner(Vector2 point) {
        int bucket = (int)point.x;

        for (int i = bucket - 1; i <= (int)point.x + 1; i++) {
            if (lookup.ContainsKey(i)) {
                for (int j = 0; j < lookup[i].Count; j++) {
                    float dx = point.x - lookup[i][j].coords.x;
                    float dy = point.y - lookup[i][j].coords.y;
                    if (dx * dx + dy * dy < 0.000001f) {
                        return lookup[i][j];
                    }
                }
            }
        }

        Corner corner = new Corner(point);
        corners.Add(corner);
        if (!lookup.ContainsKey(bucket)) lookup[bucket] = new List<Corner>();
        lookup[bucket].Add(corner);
        return corner;
    }
}

```

# Answer
> Main theme of this code is for each component (site, edge, corner) to directly hold all the data or rather pointers to all the surrounding components

It's very easy to go from the object graph representation to "list of adjacent Vector2" and relatively hard (most code, much slower, etc) to go from "list of adjacent Vector2" to the object graph.

The best solution is to change the `Voronoi` class that is calculating the graph to return a `VoronoiEdge` class that has pointers to 2 VoronoiSites and 2 VoronoiCorners. Since while calculating the graph, it has access to adjacency information, this is going to be much faster and reliable than any kind of hack we code to address the current API design.

---

The other solution to your stated problem is to find a more performant data structure to find "nearby corners", since it seems you cannot rely on all edges having precisely the same floating point value for their endpoint. You could use a Dictionary that stores both X and Y values to help with lookup.

Alternatively, the simplest change would be to set the width of each "column" in your dictionary be around the size of your delta (0.000001) instead of 1, for better performance. You will have to check 2 columns to avoid missing out on nearby points straddling a boundary though.
> 1 votes

---
Tags: c#
---


# Question
Title: How to compute the area of an irregular shape?
I have a room object defined by a collection of looping line segments that I need to calculate the area for. The classes can be described as follows (in pseudo-code):

```
class Point {
    float x;
    float y;
    ...
    float distanceFrom(Point p);
}

class Segment {
    Point start;
    Point end;
    ...
    float length();
}

class Room {
    List<Segment> walls;
    ...
    float area();
}

```

The walls of a room can never intersect anywhere but at the endpoints of the segments and any "sub-loops" created will also be separated into a new room. The solution does not need to be perfectly accurate (10% margin of error is acceptable) and is also not computed very often (\<1/s).

# Answer
> 34 votes
You can use Gauss' shoelace formula:

You need to take the x coordinate of every point, multiply them by the next point's y coordinate, then subtract the current point's y coordinate multiplied by the next point's x coordinate from the result and add them to the total area. After you did this for every point, halve the total area to get the actual area of the polygon. If the current point's the last one, then the next is the first.

```
A = 0

for (i = 0; i < points.length; i++) do

    A += points[i].x * points[(i + 1) % points.length].y - points[i].y * points[(i + 1) % points.length].x

end

A /= 2

```

# Answer
> 0 votes
We could also use a Monte Carlo method.

Draw a rectangle around the arbitrary shape. Take a uniformly distributted PRNG source eg. mersenne twister, then bound the output by rectangle's X,Y lengths using modulo function. Count the no. of random-points that land inside your shape. Divide by the total amount of points generated. Multiply that quotient by the rectangle's area. With each iteration you will converge to the true area. The algorithm is ridiculously parrallelizable and can used to calculate arbitrary dimensional shape 'volumes', as long as you can determine if an R^N coordinate falls within shape's R^N boundary.

.

> Here someone is using this method find circle area then uses that to calculate pi https://www.youtube.com/watch?v=VJTFfIqO4TU

# Answer
> -1 votes
Another approach: Don't.

Instead:

```
while (Segments.Count > 3)
{
    Segment A = Segments[Segments.Count - 2];
    Segment B = Segments[Segments.Count - 1];
    Segment C = new Segment(B.End, A.Start);
    Triangle T = new Triangle(A, B, C);
    Segments[Segments.Count - 2] = C;
    Segments.RemoveAt(Segments.Count - 1);
    if (B is inside the new shape Segments)
        Area -= T.Area;
    else
        Area += T.Area;
}
Area += new Triangle(Segments[0], Segments[1], Segments[2]).Area;

```

Basically, lop off a triangle. The area of a triangle is simple and in doing so we reduced the segment count of the remainder by one. Repeat until what's left is a triangle.

---
Tags: algorithm, geometry
---


# Question
Title: Is there an easier way to get sprites from a spritesheet
One issue I have when working with API's such as Monogame and SFML unlike with Game Engines like Unity and Unreal is trying to extract sprites from a spritesheet. I know the method of doing it but it becomes really annoying when you use spritesheets for example that have lots of different sized sprites that are scattered all around the spritesheet. Everything seems to need to be perfectly sized and aligned to be able to extract the sprites correctly, unless you're using a game engine like Unity where you can do something like draw boxes around the sprites you want, no matter the size or position, or have this done for you.

What workflow can I use to quickly select the portions of the image corresponding to each sprite and use those extracted sprites right away in code instead of splitting the sprites into seperate .png's and using them?

# Answer
> 1 votes
You can use http://www.spritecow.com/ to do that. You can open an image and click on any part to get the coordinates and the size of sprite you need.

I've been using it for more than a year and it's really nice.

# Answer
> 1 votes
TexturePacker is an awesome tool which is about $40 which packs multiple textures/sprites into one optimized spritesheet. It exports the metadata about position, rotation etc. to generic formats usable right from various engines and it allows you to write own exporters.

Even though the application isn't cheap I highly recommend trying it out since there is a trial available.

# Answer
> 0 votes
From what it sounds like, you only have one spritesheet, and each sprite isn't in the same dimension as the others. In that case, you can try using the Automatic setting in the Sprite Editor.

--

If you have each individual sprite, you can alternatively use Stitches (http://draeton.github.io/stitches/) which is free. TexturePacker has a free version, but it's watermarked.

After you create a sprite sheet that doesn't have scattered sprites (e.g. each sprite is within the same pixel dimensions) you can automatically split them in one go using the Sprite Editor. Just set the slicing type to Grid by Cell Size/Count.

---
Tags: animation, sprites, spritesheet
---


# Question
Title: Networking - How does server fixed-timestep work?
I'm making a server/client model for a top-down 2d shooter. Because I need to calculate collisions with walls & other players using a small delta, I want to use the fixed-timestep model like in this example: https://gafferongames.com/post/fix\_your\_timestep/. Apparently this is a common approach for network games.

Right now my model looks something like this:

* Client connects and is synced to the current server tick (let's say tick is 50)
* Client sends its first input + the time pressed (local tick 50) to the server
* Server receives the message at tick 55. Because the message was for tick 50 which has passed, this request is ignored.

As I understand it, the client and server run at the same rate, but because of latency the client sends messages too late and all get ignored. Am I supposed to let the server run a few ticks behind the client somehow? How do I resolve this?

EDIT: No, this is not a duplicate of that question. What OP is asking in his topic is how to account for lag visually from other players. The answer is mostly you can't, but you can smooth it out with entity interpolation.

My dilemma is that I can't figure out how to process inputs **at all** server-side using a fixed-timestep model. I assume the client sends timestamps which are processed when the server reaches that same frame, but if client+server are always frame synced, that means all messages are from the past and are ignored. If I allowed the server to accept a past input anyway it would have to implement it immediately instead of the original frame it was meant for, which would result in inaccuracy.

I'll make it real clear: If a client sends an input at tick 4 but it reaches the server at tick 7, how does the server go back and process an input meant for tick 4?

# Answer
You send commands that are post-dated into the future.

1. Calculate the average-worse (right-ish side N-percentile of the bell curve) ping time in ticks with a small margin (eg: 10 tick ping +2 ticks variation)
2. Client send input/command to the server scheduled for `(now_tick + ping_ticks)` (eg: now 50 + ping 5 = tick 55)
3. Server receives the command `(ping_ticks / 2)` later, relays it to the clients
4. Clients (hopefully) receive commands before they're due (eg: received on tick 53) and execute command on the tick that was calculated as the post-date (eg: tick 55) so everyone is in sync.

When packets are delayed there is two ways around it:

1. all clients/servers agree that commands will be received at most every N ticks with a delay of M ticks and **will simply wait** if no packet is received (use an empty keep-alive packet when no commands are to be sent). More packets can be sent more frequently.
2. Clients/servers will **rewind in time and recalculate (fast-forward)** once delayed packets are received. So all clients/servers **keep a periodic backup of the entire game state** at N ticks granularity for as far back as M (ping-delay) ticks can be accepted.

Usually a mix of both is used.
> 1 votes

---
Tags: networking
---


title: How Do I Save A Value In c# Unity

text:
# Question
Title: How Do I Save A Value In c# Unity
```
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class AttemptCounter : MonoBehaviour {

    public Text AttemptText;
    public int Attempts = 1;
    public int AddAttempts = 1;

    public void AddAttempt()
    {
        Attempts = Attempts + AddAttempts;
        AttemptText.text = ("Attempts: " + Attempts.ToString(""));
        Attempts = PlayerPrefs.GetInt ("Attempts");
        PlayerPrefs.GetInt ("Attempts");
    }

    void Update()
    {
        AttemptText.text = ("Attempts: " + Attempts.ToString(""));
        PlayerPrefs.SetInt ("Attempts", Attempts);
    }
}

```

I Am Trying To Add a Attempts System In My Game, Every time a user will restart a level the game will add one attempt, however because when restarting the level it uses the code

SceneManager.LoadScene (SceneManager.GetActiveScene ().name);

It doesnt save the int meaning that its keeping the attempt counter on 1, can anyone help, Thanks.

# Answer
Well, you are using the lines of code in the wrong order, since you are first setting Attempts without first loading the value stored on the "Attempts" key.

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

public class AttemptCounter : MonoBehaviour
{

    public Text AttemptText;
    public int Attempts = 1;
    public int AddAttempts = 1;

    public void AddAttempt()
    {
        /// 1.- You should first load the saved "Atempsts" value.
        Attempts = PlayerPrefs.GetInt ("Attempts");
        /// 2.- Then you add the attempts.
        Attempts += AddAttempts;
        /// Now the debug should throw you the expected value.
        AttemptText.text = ("Attempts: " + Attempts.ToString(""));
        /// 3.- You don't need to Save the int on update, just when you add it.
        PlayerPrefs.SetInt ("Attempts", Attempts);
    }

}

```

Now, about other ways of storing data, you could use ScriptableObjects, XML Serialization, or use persistent GameObjects, like this:

```
public class AttemptsHolder : MonoBehaviour
{
    private int attempts;

    void Awake()
    {
        attempts = PlayerPrefs.GetInt("Attempts");
        DontDestroyOnLoad(gameObject); /// With this, the GameObject doesn't go to the Garbage collector when a scene loads.
    }

    public void SetAttempts(int _attempts){ attempts = _attempts; }
    public int GetAttempts(){ return attempts; }

    public void SaveAttempts()
    {
        PlayerPrefs.SetInt("Attempts", attempts);
    }
}

```

Hope it helps.
> 1 votes

---
Tags: unity, c#, savegame, scene
---


# Question
Title: Why does the engine crash when I POST data to a server?
I am working on communications between my game and a cloud database. I'm working on the authentication part but when I try to pass data to the server in a POST the engine crashes. If I pass in a simple string like "username" it does not crash and I get an error response from the server as expected. But when I try to pass in a JSON string the engine crashes. Here is my code:

```
OnAuthCookieResponse = cookieResponseDelegate;
TSharedRef<IHttpRequest> request = FHttpModule::Get().CreateRequest();
FString url = NewObject<UURLBuilder>()
     ->Host(BASE_URL)
     ->Path(SESSION)
     ->Build();

request->SetURL(url);
request->SetVerb("POST");
request->SetContentAsString("{\"username\":xxxxxxxx}");
request->OnProcessRequestComplete().BindUObject(this, &UAClass::ReceivedAuth);
request->ProcessRequest();

```

The stack trace points me to line 559 in CurlHttp.cpp. IsURLEncoded() returns false which causes the check() to fail.

```
check(!GetHeader("Content-Type").IsEmpty() || IsURLEncoded(RequestPayload));

```

However when the engine passes data here, IsURLEncoded() returns true and the check() passes. Here is a sample of some data from the engine that passes. You can see it is a JSON string.

Here is what my data looks like that causes the engine to crash

You can see they are both JSON strings but mine causes the check to fail. I have also tried to completely URL encode the JSON string and the check still fails.

# So why does this fail for me but passes when used by the engine?

# Answer
`{` and `}` are not valid URL characters, so your JSON is not URLEncoded. I bet the engine is sending a content type of `application/json`, which then bypasses the Url-Encoding check.
> 4 votes

---
Tags: c++, unreal-4, http
---


# Question
Title: Mixing DirectX headers with C mod project not working
I'm trying to add a DirectX 11 renderer (not sure if that is even doable in a "simple" manner) to the Return To Castle Wolfenstein source code and I'm having some problems. I have a rendering class in a header that I included in the project, and whenever I include it in one of the RTCW files I get this error:

1\>c:\program files (x86)\windows kits\8.1\include\um\directxmath.h(17): fatal error C1189: #error: DirectX Math requires C++

Now I am wondering what would be a way to use DirectX math functions/classes (and all DirectX classes actually) in a C project such as the RTCW code? Is it possible to change the entire project settings so it compiles as C++? I am using Visual Studio 2017.

This is my renderer class declaration in XD3D.h header:

```
#include <d3d11.h>
#include <DirectXMath.h>
#include "XGeomObject.h"
#include "XCamera.h"

using namespace DirectX;

#define GPA(d3dModule, func) GetProcAddress(d3dModule, func)

class XD3DRenderer
{
protected:
    HMODULE                     m_XD3DModule;
    ID3D11Device*               m_pD3DDevice;
    ID3D11DeviceContext*        m_pDeviceContext;
    IDXGISwapChain*             m_pSwapChain;
    ID3D11RenderTargetView*     m_pRenderTargetView;
    ID3D11Texture2D*            m_pBackBuffer;
    ID3D11Texture2D*            m_pDepthStencilBuffer;
    ID3D11DepthStencilState*    m_pDepthStencilState;
    ID3D11DepthStencilState*    m_pDisabledDepthStencilState;
    ID3D11RasterizerState*      m_pRasterState;
    ID3D11DepthStencilView*     m_pDepthStencilView;

    HWND                        m_wnd;
    int                         m_screenWidth, m_screenHeight;
    bool                        m_fullScreen;
    D3DXMATRIX                  m_world, m_view, m_proj;
    bool                        m_lightMapsOn;

public:
    XD3DRenderer();
    XD3DRenderer(HWND wnd, int screenwidth, int screenheight,bool fullscreen);
    ~XD3DRenderer();

    ID3D11Device* GetD3DDevice() { return m_pD3DDevice; }
    ID3D11DeviceContext* GetDeviceContext() { return m_pDeviceContext; }

    bool LoadDriver();
    bool CreateD3DDevice(HWND wnd, int screenwidth, int screenheight, bool fullscreen );
    bool CreateRenderTargetView();
    bool CreateDepthBuffer();
    bool CreateDepthStencilView();
    bool CreateDisabledDepthStencilState();

    bool Setup();
    bool ClearScene(const D3DXCOLOR& col);
    bool Render(XGeomObject*, XCamera*);
    bool ShowScene();
    void TurnOnZBuffer();
    void TurnOffZBuffer();
};

```

And I include it in the C project in the RTCW win\_glimp.c file like this:

```
#include <assert.h>
#include "../renderer/tr_local.h"
#include "../qcommon/qcommon.h"
#include "resource.h"
#include "glw_win.h"
#include "win_local.h"

#include "../renderer/XD3D.h"

extern void WG_CheckHardwareGamma( void );
extern void WG_RestoreGamma( void );

... rest of win_glimp.c file omitted.

```

# Answer
> 3 votes
The `#error` pragma is there because DirectXMath uses a bunch of C++ functionality that C doesn’t have.

Direct3D itself is a COM API and can be used that way via C, if you like (there are helpful macros for calling functions in many headers). But DirectXMath is not and cannot be used directly in C code. You could create a wrapper: write a C header that declares all the functions you need to use, implement them in a C++ source file that includes DirectXMath and is separately compiled as C++ (or a static library).

But you may be better off finding a C math library and saving yourself the trouble.

You *could* change the whole game project to compile as C++, but that may not work: if the project uses C features that don’t exist in C++, you’ll have to fix those errors instead. And the change may introduce subtle behavioral differences in places that may be hard to track down. It would not be my first choice for so large a codebase.

# Answer
> 1 votes
Well, I was able to find a math library that does not require C++. The D3DX (Direct3D 9) library does the same thing as the DirectXMath, basically.

d3dx9math.h is needed.

Reference:

https://msdn.microsoft.com/en-us/library/windows/desktop/bb147179(v=vs.85).aspx

---
Tags: c++, directx, c, modding
---


# Question
Title: Unity: Controlling animation by switching between a GameObjects children
I bought an asset the other day containing an Atlas of character parts (head, hairs, clothes, body-parts). It's great and allows me to tint each piece any color I want. However, The artist decided to devide up the character like this:

Each child is a fully setup character, facing a certain direction, with an `Animator` attached to it, inside each Animator Controller you find this:

Some sample animations, pretty self-explanatory. However, I have never worked with sprites like this where its several parts, the entire character is maybe 30-40 parts (allowing for some fun animations). I'm used to making `Blend Trees` (on a single `GameObject`) and have one animation for each direction. The best solution for controlling these animations I could think of was something like this:

```
private void AnimControl() //call in update
    {
        if(direction != directionLastFrame) //do not run method if we are moving same direction
        {
            //standing still
            if (direction.x == 0 && direction.y == 0)
            {
                directionLastFrame = direction;
            }
            ////left
            else if (direction.x < 0.5f && direction.y == 0)
            {
                currentCharacterDirection.SetActive(false); //set current gameObject (which is a character facing a certain direction) inactive
                currentCharacterDirection = character.leftDirection; //change to correct direction
                currentCharacterDirection.SetActive(true); //set gameobject active again
                anim = currentCharacterDirection.GetComponent<Animator>(); //set the animation controller to the new gameObject
                directionLastFrame = direction; //set the new direction to check for
            }
            ////right
            else if (direction.x >= 0.5f && direction.y == 0)
            {
                currentCharacterDirection.SetActive(false);
                currentCharacterDirection = character.rightDirection;
                currentCharacterDirection.SetActive(true);
                anim = currentCharacterDirection.GetComponent<Animator>();
                directionLastFrame = direction;
            }
            ////down
            else if (direction.y < 0.5f && direction.x == 0)
            {
                currentCharacterDirection.SetActive(false);
                currentCharacterDirection = character.downDirection;
                currentCharacterDirection.SetActive(true);
                anim = currentCharacterDirection.GetComponent<Animator>();
                directionLastFrame = direction;
            }
            ////up
            else if (direction.y >= 0.5f && direction.x == 0)
            {
                currentCharacterDirection.SetActive(false);
                currentCharacterDirection = character.upDirection;
                currentCharacterDirection.SetActive(true);
                anim = currentCharacterDirection.GetComponent<Animator>();
                directionLastFrame = direction;
            }
        }

        anim.SetBool("Moving", playerMoving);
    }

```

I mean it works, but feels wrong? Anyone that can think of a better Idea here, worried this might be too slow. setting an object to active/inactive too often.

# Answer
The only things I see you could do to optimize your solution are:

* Avoid calling **GetComponent()** on each frame, by adding to the script that have attached your child characters an Animator property, so they have their own animator property
* Your direction assignation could be assigned just once, since in all of you **if-else** cases, direction gets the same value.
* Similarly to the direction assignation, in all your **if-else** cases, you are first deactivating your character, then activating the new character, so you can avoid redundancy by doing those procedures at the start and end, respectively.

Since I don't know the common script both your parent and child characters have, I'll give my example with a custom script (you'd just need to add that on the scripts you know they have):

```
public class AnimatorCharacter : MonoBehaviour
{
    private Animator _animator;

    public Animator GetAnimator() { return _animator; }

    void Awake()
    {
        _animator = GetComponent<Animator>();
    }
}

```

So, in your implementation you'd do something like this:

```
private void AnimControl() //call in update
{
    if(direction != directionLastFrame) //do not run method if we are moving same direction
    {
        currentCharacterDirection.SetActive(false); //set current gameObject (which is a character facing a certain direction) inactive

        //standing still
        if (direction.x == 0 && direction.y == 0)
        {
            //...
        }
        ////left
        else if (direction.x < 0.5f && direction.y == 0)
        {
            currentCharacterDirection = character.leftDirection; //change to correct direction
        }
        ////right
        else if (direction.x >= 0.5f && direction.y == 0)
        {
            currentCharacterDirection = character.rightDirection;
        }
        ////down
        else if (direction.y < 0.5f && direction.x == 0)
        {
            currentCharacterDirection = character.downDirection;
        }
        ////up
        else if (direction.y >= 0.5f && direction.x == 0)
        {
            currentCharacterDirection = character.upDirection;
        }

        currentCharacterDirection.SetActive(true); //set gameobject active again
        directionLastFrame = direction; //set the new direction to check for
    }

    currentCharacterDirection.GetAnimator().SetBool("Moving", playerMoving);
}

```

Setting aside that, your solution seems ok to me (although I don't know that asset's implementation). Hope this helps.
> 2 votes

---
Tags: unity
---


# Question
Title: Finding the closest face normal from a given point in space efficiently
I have a large model (roughly 400k faces) and a large number of points on this model (roughly 2000) and I need to calculate a normal per point based on the closest face on the model. Is there a faster way that isn't `O(n*m)` where `n` is the number of points and `m` is the number of faces (e.g., raycasting or iterating through every face)?

I'm using THREE.js and the target hardware is a Toshiba tablet with Intel integrated graphics so I don't have a lot of power to work with. Currently if I compute this on load it takes about 10+ minutes.

I've been given the requirement that there shouldn't be any model specific information precomputed for each point so that we can use the points on a different model without recomputing everything and then have multiple datasets of point =\> normal mappings. This is currently what we are doing and it works but doesn't scale well to our needs.

# Answer
Maybe you can set a number of raycasts from each point to different directions. Each raycast will return the closest face. You can than iterate through those. I know it is not a 100% satisfying solution, but maybe it will be good enough for your need?
> 1 votes

---
Tags: javascript, three.js
---