title: How to prevent a duplicated shadow?

text:
# Question
Title: How to prevent a duplicated shadow?
It's a blob shadow which is built in Unity's standard asset package.

As you see in the figure below, a shadow that is created by the Unity Projector is duplicated at the floor below.

How can I prevent this duplicated shadow?

# Answer
> 0 votes
**YES,** you can try with a ray in direction of the shadow that get the altitude or distance and set the maximum shadow projector distance similar to ray result dynamically using physics ray.

For example:

```
Ray ray = new Ray(hit.transform.position, -Vector3.up);

```

Or you can use Unity shadow only for that particular object.

---
Tags: unity, shadows
---


# Question
Title: C++: Strange arithmetic error in adjacent tile checking code
I have a tilesheet from which I draw wall tiles. Each wall tile on the sheet is enumerated from XXXX to ULRD, where each place corresponds to whether there is an adjacent wall above, to the left, to the right, or below the cell in question.

I also have an integer variable called `whatWallmapImageIndex`. How it supposedly works is

1) If the cell is not on the top edge of the world and there is an adjacent wall cell above, index +=1000.

2) If the cell is not on the left edge of the world and there is an adjacent wall cell to the left, index += 100.

3) If the cell is not on the right edge of the world and there is an adjacent wall cell to the right, index += 10.

4) If the cell is not on the bottom edge of the world and there is an adjacent wall cell below, index += 1.

Really simple, right? Each "tens" place should correspond to a direction being true or false, so I'd expect that a cell that has adjacent wall tiles in every direction but left (UXLR) would be 1011.

Now this four-way adjacency check does not work, but I cannot figure out why. In this picture, nearly every corner and 3-way wall tile is incorrectly being drawn as the top left corner wall section.

That tile is the 0th position on the tile sheet, and I've confirmed by doing console output on the player character's cell that the drawing index (`wallmapImageIndex[ whatever the player's cell ID is ]`) is 0 also. That suggests that there is something wrong with the switch statement used to determine the drawing index (see code sample), but the first ten of the cases do work as expected while the six do not.

I've put console output in all the cases that do not work - None of them output the message.

I simply cannot find the error anywhere. Why do cases 1010 through 1111 not work?

```
void Generator::Commit()
{
    /// ### Detail and finalize the layout for output                ###

   for(int i = 0; i < areaCellWidth*areaCellHeight; i++)
   {

        int whatFloormapImageIndex = 0000; /* Whether adjacent cells are floor tiles ,
                                                  * represented in the form 0 0 0 0.  (1 = true)
                                                  *                         U L R D           */
        int whatWallmapImageIndex = 0000;  /* Whether adjacent cells are wall tiles ,
                                                  * represented in the form 0 0 0 0.  (1 = true)
                                                  *                         U L R D           */

    ///                     ########### DETAIL THE WALLS ##########

    if(genLayout[i] > GEN_CELL___WALL_MARKER_BEGIN && genLayout[i] < GEN_CELL___WALL_MARKER_END) // Cell is a type of wall // ***Will be more nuanced later.***
    {

        wallmap[i] = WT_WALL_IMPASSABLE;
        if(i >= areaCellWidth)// Not on the top row
        {
            if(genLayout[i-areaCellWidth] > GEN_CELL___WALL_MARKER_BEGIN && genLayout[i-areaCellWidth] < GEN_CELL___WALL_MARKER_END) // Check above row for wall's existence
            {
                whatWallmapImageIndex += 1000; // U = 1
            }
        }

        if(i%areaCellWidth > 0) // Not the left-edge column
        {
            if(genLayout[i-1] > GEN_CELL___WALL_MARKER_BEGIN && genLayout[i-1] < GEN_CELL___WALL_MARKER_END) // Check to the left for wall's existence
            {
                whatWallmapImageIndex += 0100; // L = 1
            }
        }

        if(i%areaCellWidth < areaCellWidth-1) // Not the right-edge column
        {
            if(genLayout[i+1] > GEN_CELL___WALL_MARKER_BEGIN && genLayout[i+1] < GEN_CELL___WALL_MARKER_END) // Check to the right for wall's existence
            {
                whatWallmapImageIndex += 0010; // R = 1
            }
        }

        if(i/areaCellWidth < areaCellHeight-1) // Not on the bottom row
        {
            if(genLayout[i+areaCellWidth] > GEN_CELL___WALL_MARKER_BEGIN && genLayout[i+areaCellWidth] < GEN_CELL___WALL_MARKER_END) // Check below for wall's existence
            {
                whatWallmapImageIndex += 0001; // D = 1
            }
        }

        switch(whatWallmapImageIndex)
        {
        case 0000: wallmapImageIndex[i] = SI_XXXX_WALL; break; // index correct
        case 0001: wallmapImageIndex[i] = SI_XXXD_WALL; break; // index correct
        case 0010: wallmapImageIndex[i] = SI_XXRX_WALL; break; // index correct
        case 0011: wallmapImageIndex[i] = SI_XXRD_WALL; break; // index = 0 - (But XXRD is supposed to be 0 anyway)
        case 0100: wallmapImageIndex[i] = SI_XLXX_WALL; break; // index correct
        case 0101: wallmapImageIndex[i] = SI_XLXD_WALL; break; // index correct
        case 0110: wallmapImageIndex[i] = SI_XLRX_WALL; break; // index correct
        case 0111: wallmapImageIndex[i] = SI_XLRD_WALL; break; // index correct
        case 1000: wallmapImageIndex[i] = SI_UXXX_WALL; break; // index correct
        case 1001: wallmapImageIndex[i] = SI_UXXD_WALL; break; // index correct
        case 1010: wallmapImageIndex[i] = SI_UXRX_WALL; std::cout << "Message that never shows up at index " << i << ": " << whatWallmapImageIndex << std::endl; break; // Error - index = 0
        case 1011: wallmapImageIndex[i] = SI_UXRD_WALL; std::cout << "Message that never shows up at index " << i << ": " << whatWallmapImageIndex << std::endl; break; // Error - index = 0
        case 1100: wallmapImageIndex[i] = SI_ULXX_WALL; std::cout << "Message that never shows up at index " << i << ": " << whatWallmapImageIndex << std::endl; break; // Error - index = 0
        case 1101: wallmapImageIndex[i] = SI_ULXD_WALL; std::cout << "Message that never shows up at index " << i << ": " << whatWallmapImageIndex << std::endl; break; // Error - index = 0
        case 1110: wallmapImageIndex[i] = SI_ULRX_WALL; std::cout << "Message that never shows up at index " << i << ": " << whatWallmapImageIndex << std::endl; break; // Error - index = 0
        case 1111: wallmapImageIndex[i] = SI_ULRD_WALL; std::cout << "Message that never shows up at index " << i << ": " << whatWallmapImageIndex << std::endl; break; // Possible error, but it's very rare to see a 1111 cell
        }
    }

}

generationPhaseComplete = true;
#ifdef D_GEN_PHASE_CHECK
std::cout << "Layout finalized - Ready to read." << std::endl;
#endif // D_GEN_PHASE_CHECK
}

```

# Answer
You've run into octal literals. A number beginning with `0` is interpreted as base 8, so `whatWallmapImageIndex += 0010;` is equivalent to `whatWallmapImageIndex += 8;`. Try removing the leading zeros as a start.

As an aside, using a bitmask or std::bitset instead of adding powers of 10 is preferable.
> 3 votes

---
Tags: c++, logic
---


title: What is this tracking circle called as?

text:
# Question
Title: What is this tracking circle called as?
I don't know what the circle in the image below used for changing directions and movements of a character is called. Can anyone provide me anything related to it? I want to include it in my game.

# Answer
> 1 votes
It's a **virtual joystick**.

Whether or not you should use one as a controller is debatable, as discussed here.

> * You can't see/feel where the joystick is pointing when you are using it.
> * You can't feel where the 'edge' of the joystick is - meaning, you can't know when you are reaching the maximum in any direction
> * You don't always know when you're pressing the joystick. You can accidentally miss pressing it and not know, because you can't feel
> the joystick under your finger.

---
Tags: movement, gameobject
---


# Question
Title: LibGDX: How to make something like vector rotation sensor with accelerometer and compass values?
So I've tried the vector rotation sensor using the Android API and it works perfectly to do what I want, but LibGDX does not support this sensor. I've been searching and it seems like I can do the same thing as vector rotation sensor using the accelerometer and compass values returned by LibGDX API:

```
Gdx.input.getAccelerometerX();
Gdx.input.getAccelerometerY();
Gdx.input.getAccelerometerZ();

Gdx.input.getAzimuth();
Gdx.input.getPitch();
Gdx.input.getRoll();

```

But I couldn't find out how to do this.

# Answer
> 1 votes
You can get the rotation matrix by calling `Gdx.input.getRotation(float[] matrix)`, it gives you the rotation matrix as per the Android `SensorManager` `getRotationMatrix` call (SensorManager.getRotationMatrix).

From that you can get a `Quaternion` out that is a direction and a rotation around that direction.

So if you you're looking to get the *pitch*, *roll* and *yaw* you can retrieve those from the `Quaternion` directly;

```
    public class MyAndroidStudioSandboxGame extends Game {

        @Override
        public void create () {
        }

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

            float[] mat = new float[4 * 4];
            Gdx.input.getRotationMatrix(mat);

            Matrix4 m = new Matrix4(mat);

            Quaternion q = m.getRotation(new Quaternion());

            Gdx.app.log("SANDBOX", String.format(
                "Pitch=%.2f, Roll=%.2f, Yaw=%.2f",
                q.getPitch(), q.getRoll(), q.getYaw()));
        }
    }

```

The above app will log the orientation (Euler angles) of the device to logcat. There are also `getPitchRad`, `getRollRad` and `getYawRad` that gives you the values in radians.

---
Tags: android, libgdx, rotation, vector, accelerometer
---


# Question
Title: Unity - Read pixels of camera into memory
I am trying to develop a bot in a Unity game that takes actions based on the image produced by the camera.

I have attached a camera to the "face" of the bot, which is the camera I need to get the image of. For instance in the following picture I have run the bot and taken a screenshot. For every frame update I need to read the pixels that would be shown on the screen into memory.

How do I do that?

Ultimately I would like the bot to run in batch mode without graphics if possible, as this would speed up the process of evolving the bot.

Is it possible to read the pixels that a given camera would have shown on the screen even without graphics enabled? If so how?

# Answer
> 7 votes
Have your camera render to a render texture. You can then extract the bitmap-data from it by copying the renderTexture to a Texture2d:

```
// assumes you have your RenderTexture renderTexture
Texture2D tex2d = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.RGB24, false);

RenderTexture.active = renderTexture;
tex2d.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
tex2d.Apply();

```

and then access individual pixels with `tex2d.GetPixel(x, y)` or in bulk with `tex2d.GetPixels()` or `tex2d.GetPixels32()` .

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


# Question
Title: How do you play more than one animation at a time in Unity?
I am trying to have 2 animations on one GameObject, and I want them to play at the same time. I have been looking all over and messing around with the animator controller, but I cant get it working.

How do you play more than one animation at a time in Unity?

# Answer
I realize this question is a few months old, but it seemed wrong to leave it with no answers mentioning Animation Layers.

This is the standard way a Unity game would combine two different animations. (Here I'm assuming you're not trying to blend between similar animations, like different directions & speeds of walk/run, using a conventional blend tree or cross-fading transition)

There are two main ways to use layers:

* An **Override** layer takes complete control of some parts of the object, and completely replaces the animation on those parts while letting the underlying animation continue to play on the rest.

This is often done to separate upper & lower body animations, so the base layer handles all the walking/running/crouching animation for the legs and torso, and an override layer can take control of the arms to do things like holding & manipulating different objects.
* An **Additive** layer stacks its animated movements on top of what the previous layers have produced. This gives you a bit less control over where exactly a body part ends up, since it's a result of two distinct animations.

Additive layers are often used for aiming, or adding small tweaks and variations on top of a more robotic base layer to help it look more natural.

If you'd like more inspirations about ways to use animation layers to combine animations, I'd recommend checking out this GDC presentation about the animation of Drake in Uncharted I & II, which is where I first heard about additive animation.
> 3 votes

# Answer
Are you using "Unity Mecanim" to play these animations, or are you using legacy? If you are using legacy, I don't think it is possible. With Mecanim you should be able to do something like this, even though I have never tried it. Just find some tutorials on it, and try and implement the thing you want to do. I would recommend this tutorial, I used it to get started with animating: https://www.youtube.com/watch?v=bvavLShgR90
> -1 votes

# Answer
So you want for example: Add an animation (change position) of a gameobject and while doing that: Add another animation(change rotation) the game object. (for example a car tire). right?

Or do you want to animate a child of a game object, while animating a game object? (for example: moving the forearm and moving the upper arm )? In both examples you should just do the animation in 1 animation. Mixing animations is not clean and also should not be necessary.

Just set the Keyframes with all of your game objects together . As long as you have parented them corrects, it should behave as planned.

Besides that: I agree with alexo1001. Unitiys standart mecanim "animation-maker" is pretty weak. I stumbled about tons of limitations while using it. I suggest you download other animation addon for unity.
> -2 votes

---
Tags: unity, animation
---


# Question
Title: Is it possible to have a diagonal movement animation in monogame/xna?
Is it possible to have a diagonal movement animation in monogame/xna?

As far as I can tell it's not possible to recognise multiple keypresses (ie "A && W" or "S && D") as unique events - everything I've seen regarding diagonal movement basically goes;

```
if(W)
{
    player.position.x = player.position.x + 1
}
if(S)
{
    player.position.x = player.position.x - 1
}
if(A)
{
    player.position.y = player.position.y - 1
}
if(D)
{
    player.position.y = player.position.y + 1
}

```

And that obviously works in most instances, my problem is I have specific diagonal movement animations that I need to display, my characters are people and I can't just rotate them like a ship or a car - and as far as I can tell....

```
if(W && A)
{
    player.position.x = player.position.x + 1
    player.position.y = player.position.y - 1
}

```

Isn't possible?

The only way I can think to accomplish what I need is to detect diagonal movement after the input handling - ie if both x AND y positions are different or are going to be different to the previous position, set the relevant diagonal to true and show the relevant animation.

Is there a 'correct' or easier way to do this?

# Answer
> 4 votes
Instead of directly modifying the position of the player you could add another Vector2 variable named, for example, Direction. When a player pressed W you set direction to (0,1) and if it was up & left then set it to (-1,1) and you could then apply animation according to the direction you're going.

And then to move it you should calculate a new position of the player using the direction and speed.

Wether or not this is the "correct" way I leave up to you - it's one solution at least.

EDIT: It should be noted that a usual direction vector is normalized so it wouldn't be (-1,1) I just figured it might be easier to use full integers for the animation part of it..

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


# Question
Title: Unity C# - moving objects and Debug.Log; show multiple messages only once (easy but stuck)
**I have the following scenario:**

a sphere is moving towards an object it can see (a cube). The cube is moving randomly through the landscape. The sphere will keep following it. I have a script that will check IF the cube is Within Sight. If it is, it will move towards it and it will keep following it.

**What I want**

I want a Debug.Log message to show when:

1. When the sphere is moving towards a (new) target. it must say: "Searching..."
2. When the sphere has found the cube, I want it to say: "Found the cube."
3. When the cube is found, I want it to continue searching for new cubes. So it must say once more: "Searching..."

**Problem:**

It keeps showing these messages nonstop. I found a solution with a false bool in an IF statement. But, I don't know how to combine 2 messages.

**Code:**

```
using UnityEngine;
using BehaviorDesigner.Runtime;
using BehaviorDesigner.Runtime.Tasks;

public class MoveTowards : Action {

public float speed = 0;
public SharedTransform target;
private bool pietje;

private bool jaap;

void PrintMessage (string message) {
    Debug.Log(message);
}

void Start() {
    pietje = false;
}

public override TaskStatus OnUpdate() {

    if (Vector3.SqrMagnitude (transform.position - target.Value.position) < 0.1f && !pietje) {
        PrintMessage ("Found the cube.");
        pietje = true;
        return TaskStatus.Success;
    }

        transform.position = Vector3.MoveTowards (transform.position, target.Value.position, speed * Time.deltaTime);
        transform.LookAt (target.Value.position);
        return TaskStatus.Running;

}

```

}

I just don't know how to fix the last part where it says: **"Searching..."** I don't know how to implement it with an IF statement (doesn't work somehow) or how to create the IF statement (when I use this, it doesn't work:

```
if (TaskStatus.Running == 1 && !pietje)

```

Anyone that can help me? That would be awesome! Have been trying to fix this for some hours now....

# Answer
> 1 votes
Supposing your `OnUpdate` function always either find or search, you can print your **searching** message when you don't print your **Found the cube** message:

```
if (Vector3.SqrMagnitude (transform.position - target.Value.position) < 0.1f && !pietje) {
    PrintMessage ("Found the cube.");
    pietje = true;
    return TaskStatus.Success;
}

    if (pietje)
    {
        pietje = false;
        PrintMessage ("Searching...");
    }

    transform.position = Vector3.MoveTowards (transform.position, target.Value.position, speed * Time.deltaTime);
    transform.LookAt (target.Value.position);
    return TaskStatus.Running;

```

---
Tags: unity, c#, scripting, messaging
---


title: How To Disable A Select Collider

text:
# Question
Title: How To Disable A Select Collider
I have a character with 2 2D Colliders, one for the head, and one for the feet, How do I Disable only the Head Collider in C#.

# Answer
> 0 votes
Add a script to the Character game object with two public variables:

```
public Collider2d headCollider;
public Collider2d feetCollider;

```

Then go back to the Unity editor and open the Character game object in the inspector. You should now see two slots in the script component named "Head Collider" and "Feet Collider". Drag the two colliders from the hierarchy window into these slots.

You can now switch these two colliders on and off from the same script with `headCollider.enabled = true;` or `headCollider.enabled = false;`.

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


title: How to make level intro (2D)

text:
# Question
Title: How to make level intro (2D)
How do I make it so that when the level starts, the player runs in from off the screen (without input) ready for the player to start moving him and complete the level.

# Answer
> -1 votes
You could set the walk animation of the player and then automatically move them in the update. This might take a smarter script I am guessing you have a player controller that takes input. I would have a boolean that asks if it is in intro mode or not, if it is, then instead of waiting for input, just force it (not sure how you update your player) but you can use code similar to what you use for moving the player and just force it 'on' while doing animation for a specific amount of time or until the player hits a trigger.

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


title: Game optimization and keyboard events

text:
# Question
Title: Game optimization and keyboard events
I've been putting some (a lot) of thought about how to read keyboard input and especially, when.

Looping through all the keycodes on the keyboard and updating the statuses seems like a lot of waste when there are only few keys pressed at one time.

I started to think that if the game gives a player key rebinding ability, why not read only those keys/actions that are currently bound in the game and ignore the rest?

If the "Move forward" action has a key "W" bound to it, then only look for status of key W.

And you can ignore the rest (Of course not ESC and other various game-wide actions).

To me this would make sense, because most of the time games are simple and they only use a few keys on the keyboard.

Does this approach make any sense?

# Answer
> Does this approach make any sense?

Yes. It's nothing new or surprising at all; most games will get keyboard state one of three ways:

* either they will call an OS function (directly or indirectly) that reports the state of the entire keyboard at once or
* they will handle events from the OS indicating "this key is down" and "that key is up" or
* some combination of the above

Both have pros and cons in terms of the semantics you can extract from the key state. For example it is often easier to track continuous, "key is held" actions over several frames if you are using the method that just returns the entire keyboard state. The event-based approach is often more suitable for "instant" key-presses. And of course you can combine both methods for a hybrid solution or track your own key state internally.

Listening for the key events from the OS is the method you're suggesting.

You should make this choice based on the semantics you need. Don't worry about whether or not one option is "slower" or "less efficient" than another, because the little inefficiencies you are thinking of are

* probably not where you think they are and
* absolutely nowhere *near* the critical path of your per-frame performance

In other words, the method you use for keyboard handling is not what is making your game slow, so don't worry about it.
> 0 votes

---
Tags: c++, keyboard
---


title: Minecraft chunk file decompresssion

text:
# Question
Title: Minecraft chunk file decompresssion
First of all, hello everyone,

I'm currently making a program to read Minecraft region files (r.#.#.mca) for a server.
The problem I have is that I can't decompress them, I tried GZip and ZLib decompression but none of them worked. I already searched for solutions but there is little to no information online. It's *really* important that I find a solution to that issue.

Thanks in advance.

# Answer
So I found the `AnvilChunkLoader` class, copied its `loadChunk__Async` method and it worked.
This class can be found at `net.minecraft.world.chunk.storage.AnvilChunkLoader` for Minecraft 1.8.9
You have to find the method `loadChunk__Async(World worldIn, int x, int z)`.
The part I needed was:

```
DataInputStream datainputstream = RegionFileCache.getChunkInputStream(chunkSaveLocation, x, z);
if (datainputstream == null) {
  return null;
}
NBTTagCompound tag = CompressedStreamTools.read(datainputstream);

```

To make it work, you need to specify the path to the region folder that contains the file, then the chunk coordinates `x` and `z`. The `tag` variable should contain the chunk data in NBT format.
> 0 votes

---
Tags: minecraft-modding, file-format, compression
---


# Question
Title: Do shaders still need to be optimized on desktop / laptop platforms
On mobile platforms shader optimization is necessary and improve FPS.

But on desktop platforms is optimization still needed (and will improve FPS) or does the GPU driver handle it ?

# Answer
> 1 votes
You always need to optimize for any platform you're developing on. There are many ways in which you can write a working algorithm that isn't cache friendly or does useless computation.

Also, you should remember that there are many GPUs in existence and all can behave (performance-wise) differently on possibly the same algorithm because the architecture are different and many other factors can make GPUs range from fast to sluggish.

If you want to optimize your shaders, there is a tool called glsl-optimizer that is (mostly) used on mobile platforms and used directly in Unity, but you can still use it on desktop as it performs many optimizations (constants propagation, loop unrolling, etc...) on your code.

Also, if you want to optimize and profile your application, you can use tools such as apitrace, renderdoc or GLSL-Debugger (even though this one seems to be less actively developed).

EDIT: Also, you can look at this page for a comprehensive list of profilers and debuggers.

Hope this helps.

# Answer
> 0 votes
I would recommend optimizing it anyway because you can't just let the GPU do all the magic. Try it out on as many rigs as you can as there will always be these random people that don't have good computers. I had this several times with some of my friends as I use the new macbook pro retina display and they use the old macbook pro with a decreased performance. It definitely helped a lot after I optimized my game for them.

---
Tags: shaders, mobile, gpu, pc
---


# Question
Title: What compatibility checks should i do while creating Direct3D device, swap chain etc
I've done DirectX apps for 1.5 years now, mainly to teach myself but now i would like to make games for public. So i was wondering would it work for others just leaving the values default ie. swap chain's refresh rate to 60 without checking the users monitors refresh rate. Could you tell me what things should not be ignored in situations like this, thanks.

There's no SDL or SFML in my programs just pure C++, DirectX and WinAPI.

# Answer
> 1 votes
The most compatible solution is to use 'windowed' mode and leave all those values at the default. Refresh rate, resolution, etc. only come into play with 'exclusive fullscreen' mode which can be quite challenging to implement robustly. The Universal Windows Platform (UWP) on Windows 10 does not support 'exclusive fullscreen' rendering because of numerous issues with getting it right.

The best solution is to leave the user's display resolution alone and use a borderless window that fills the whole display. You can deal with the performance impacts by using a smaller render target and then scale it up. With UWP you can use `DXGI_SCALING_ASPECT_RATIO_STRETCH` which deals with it automatically, or for classic desktop apps you can use `DXGI_SCALING_STRETCH` or do your own aspect-aware scaling. This is the solution I implement in my Direct3D Game VS Templates.

Another common solution is to use 'fake-fullscreen' where you use a windowed mode with a borderless fullscreen window and change the display resolution. This only works for classic desktop apps, and does have some of the downsides of 'exclusive fullscreen' mode as you have to be careful about exactly what resolution you request, handle an automatic fallback for failure, etc.

> I suggest you take a look at the `DeviceResources` (DX11 or DX12) class as a good starting point. See also Anatomy of Direct3D 11 Create Device and Anatomy of Direct3D 12 Create Device.

---
Tags: c++, directx, directx11, compatibility
---


# Question
Title: How can I turn an open world into a fixed-size array?
I am developing a little game, where I need an A\* path-finding algorithm for enemies who follow the player. I have already learned and tested a path-finding algorithm, but it only works with fixed-size array.

How can I turn an open world into a fixed-size array? I am developing with Irrlicht engine 1.6 version. I know that it is a quite old, but it is the only engine which works for me, on Windows XP.

Here is my A star path-finding code that works on a 2D grid. Additionally , if needed, Here there is a link to a walking person I have created with Irrlicht. You must place the media folder in your local drive.

# Answer
There are two options that come to my mind:

1. You create a fixed size array from your 3D game world. Fixed size is not a problem if your world is finite. You divide the world up into little squares and put information into it whether or not a character can traverse. How this is implemented depends on your game world, the used geometry, the obstacles and so on. You want to go for an automated approach. If you got this you can apply the A\* algorithm.
2. You use a technique that is made for 3D worlds: navigation meshes. There are a lot of results on Google for "C++ navigation mesh" and there are ready to use libraries. A lot has been written and coded for that, do some research and you will surely find a solution fitting your situation.
> 1 votes

---
Tags: c++, path-finding, irrlicht
---


title: LibGDX Tiled Map - Get MapObject ID

text:
# Question
Title: LibGDX Tiled Map - Get MapObject ID
I have a MapLayer with MapObjects and i want to know the ID of the MapObjects in this Layer, any idea how to get the ID?

# Answer
ID is stored as a property on the MapObject. You may be able to pass in `Integer.class` to `properties.get()` instead.

```
MapLayer objectLayer = model.Map.getLayers().get("Objects");

if(objectLayer != null){
    MapObjects objects = objectLayer.getObjects();

    for(MapObject mapObject : objects){

        MapProperties properties = mapObject.getProperties();

        String id = properties.get("id",String.class);
    }
}

```

That being said, I recommend you not use the ID value to identify objects on your map since Tiled does not give you control over this value. If the ID's ever change, then you will need to either edit your code or manually edit the .tmx file to correct this. Instead, you could add a custom property to the objects called "Tag" that will help you identify them.
> 0 votes

---
Tags: libgdx, tiled
---


title: Get device rotation in Y axis

text:
# Question
Title: Get device rotation in Y axis
So using LibGDX accelerometer methods, I'm able to get the rotation of the device in the X and Z axes in degrees with this code:

```
 @Override
public void render(float delta) {
    float accX = Gdx.input.getAccelerometerX(),
            accY = Gdx.input.getAccelerometerY(),
            accZ = Gdx.input.getAccelerometerZ();

    float moduleValue = (float) Math.sqrt(accX * accX + accY * accY + accZ * accZ);

    //Here I do the gravity compensation
    accX /= moduleValue;
    accY /= moduleValue;
    accZ /= moduleValue;

    float xRotation = (float) Math.atan2(accY, accZ) * MathUtils.radiansToDegrees,
            zRotation = (float) Math.atan2(accY, accX) * MathUtils.radiansToDegrees;}

```

However, get the rotation in the Y axis is not that easy to obtain, and if I try to get it by this way, it returns erroneus values.

# Answer
I'm not sure what your gravity compensations are doing, but you may not be taking units into account. The docs for `Input.getAccelerometerY()` say

> The rate of rotation around the y axis. (rad/s)

To convert this to degrees, you have to convert from rad/s to rad then to degrees

```
float accY = Gdx.input.getAccelerometerY();
float degrees = accY * deltaTime * MathUtils.RadiansToDegrees;

```

Then `degrees` is how much the phone rotated on the Y axis this frame. Note that both the X and the Z axes also return in (rad/s).

**Update:**

Thanks to DMGregory for his comment to get to the root of this issue. The docs are indeed mixed up. The `getGyroscope` functions are the ones that give rotation in `rad/s`. The `getAccelerometer` functions give acceleration in `m/s^2`

If you look at the source for the Android implementation of the Input interface all it does it sets up a `SensorEventListener` and then copy the values of each `Sensor.TYPE_ACCELEROMETER` event into an `accelerometerValues[3]` array and returns one of its members on a call to `getAccelerometer`. The same occurs for `Sensor.TYPE_GYROSCOPE` and the `getGyroscope` functions.

For reference on what these android specific values mean, one can look here

**TLDR;**

The docs are wrong. For rotation, use `getGyroscope`. It is the function that will give you rotation around the phone's local axis in `rad/s`
> 1 votes

---
Tags: libgdx, axis, accelerometer
---


# Question
Title: Color spaces: Should colors be converted to linear color before applying premultiplied alpha?
For instance, when loading an image that is SRGB, which of these is correct?

* Simple premultiply:
    + Take SRGB color from file and multiply RGB by alpha

or

* Convert to linear before premultiply:
    + Take SRGB color from and convert RGB to Linear
    + Multiply Linear RGB by alpha
    + Take Linear RGB and convert back to SRGB

# Answer
This article seems to imply that the most efficient method is the latter: multiply by alpha, then convert to SRGB.

As far as correctness, I realized that if your texture and framebuffer are SRGB, the GPU does SRGB conversion and then blends in linear space. Therefore if you are using SRGB textures and framebuffers, you should premultiply alpha in linear space (the latter approach). If you're rolling your own blending, the order of operations shouldn't matter as long as you undo them in the right order.

This also agrees with the findings that led me to this question: When exporting my premultiplied render target to PNG, my colors had greater RGB values than my alpha value, but converting the RGB value to linear made them equal to alpha.
> 2 votes

---
Tags: color, blending
---


# Question
Title: Moving a platform left to right with continuous movement
I made a 2D game with Unity, and I am trying to create a platform that will move from left to right continuously, but I don't know how to make the platform move a greater distance then -1 to 1 units because I use the `Mathf.Sin` function. I can only control the speed of the platform.

Here is my code:

```
private Vector2 startPosition;
private int speed;

void Start ()
{
    startPosition = transform.position;
    speed = 3;
}

void Update()
{
    transform.position =
        new Vector2(startPosition.x + Mathf.Sin(Time.time * speed), transform.position.y);
}

```

Here is what the code actually does:

How can I control the distance that the platform can move to each side? For now, it can only move 1 unit to each side.

# Answer
> 4 votes
As it is, your code gives your platform a movement distance of 2 units; 1 unit in either direction of its starting position. To allow further movement, all you need to do is effectively *multiply* the current movement value.

```
/// <summary>The objects initial position.</summary>
private Vector2 startPosition;
/// <summary>The objects updated position for the next frame.</summary>
private Vector2 newPosition;

/// <summary>The speed at which the object moves.</summary>
[SerializeField] private int speed = 3;
/// <summary>The maximum distance the object may move in either y direction.</summary>
[SerializeField] private int maxDistance = 1;

void Start()
{
    startPosition = transform.position;
    newPosition = transform.position;
}

void Update()
{
    newPosition.x = startPosition.x + (maxDistance * Mathf.Sin(Time.time * speed));
    transform.position = newPosition;
}

```

By multiplying your movement algorithm of `Mathf.Sin(Time.time * speed)` by a distance value of `maxDistance`, you effectivley tell your platform to allow movement of `maxDistance` units in either direction. The above example gives behavior identical to your current movement; 1 unit of distance in either direction, reversing its direction at `-1` and `1`. With `maxDistance = 50`, for example, the platform will move between `-50` and `50`.

Be aware that as `maxDistance` increases, you will likely want a lower `speed`. `speed` effectively controls how much time it takes to complete an entire movement arc, in this context, not the rate in which it moves in that arc. With `maxDistance = 1` and `speed = 3`, the platform moves between `-1` and `1` over 3 seconds. With `maxDistance = 10` and `speed = 3`, the platform moves between `-10` and `10` over 3 seconds. Due to the much greater distance, the platform will move *a lot* faster to cover the ground in the same amount of time. To give the same general speed, you would want something more like `maxDistance = 10` and `speed = 30`. *I would personally rename `speed` to `maxTime`, though I have not done so in the above example.*

I will address the semantic alterations I *have* made, to avoid confusion:

* The addition of `newPosition` gives you a local Vector2 to hold your derived "next position" co-ordinate. We can then work out the updated `newPosition.y` value on the fly, and do not have to worry about `newPosition.x` before passing it into `transform.position`, as this value should not change in the current context.
* Serializing `speed` and `maxDistance` with `[SerializeField]` serialises these values for the Unity Inspector. As a result, they have retained their `private` protection, but you can still change them on the fly from the Inspector.
* Initialising `speed` and `maxDistance` inline with the variable declaration simply prevents any Inspector-altered value from resetting when you hit play, and call `Start()`. You may wish to have these in `Start()`, just remember that these values will then override any values you have provided through the Inspector. For testing purposes, you can still change the values in the Inspector *during* a play-test to see the effects in-game.

As it stands, you also want to remember that this deliberately constrains movement to a specific value in either direction. That means that this would not work accurately if you wanted less symmetrical movement; for example, it would not work accurately if you wanted your platform to move `20` units to the left, but only allow `10` units of movement in the opposite direction. It could only be constrained to `+-10` or `+-20`. There are more advanced implementations you could look at to reach this sort of functionality, if needed, though they appear out of scope for the context of this question.

---
Tags: unity, c#, moving-platforms
---


# Question
Title: When is Micromanagment in games considered fun/boring?
Some players (typically the developer types, but not exclusively) love to control intricate aspects of a game (typically a simulation game) such as how long traffic lights take, how much to tax certain citizens (in sim city style games) when to change gear (in a racing game) exactly what an AI should do etc...

But how far should a developer go to implement micromanagement, when does it stop becoming fun? It would be rather tedious to connect each building to the water, and electrical grid for example in sim city. Whereas issuing city ordinances is considered engaging to the player.

# Answer
> 2 votes
In my opinion, it isn't very beginner-friendly to implement too many functions. Look at dwarf fortress and you'll understand what I say. But as you said, as soon as somebody knows the basics of a game, he'll be curious to learn new things.

I really like games where you can e. g. click on a building and just set what the building should produce (everybody understands that). But there should also be a button "advanced", where you can e. g. set if the workers should take the produced things to the warehouse or if they /the produced things) should stay there until they are needed at another building.

To summarize it: the player will play the game longer if there *is* advaced micromanagment, but he won't start playing it if he *has* to do too much micromanagment at the beginning.

# Answer
> 1 votes
I'd say your premises are off.

**There is no threshold of options where a game becomes boring, unless those options are presented clumsily.**

I would instead say something more like:

* If there are too many options to learn to players when they are still learning, a game can be overwhelming.
* If a game requires many detailed choices when they aren't needed, that game may be wasting the player's time.
* If there is an excessive amount to manage in order for the action to proceed properly (for example, in games which have the player gain more and more units that all need to be given orders at the same time) then the game can become overwhelming, or practically impossible to manage everything (particularly for an un-pausable real-time game), or (in a turn-based game) take a huge amount of time to advance one turn.

While the above issues and others can be problems, they are not always simple matters of too many options being included in a game. Such issues are often problems with the *way* they are presented, included, or required, and the lack of ways to make them *optional*.

**In general, as long as such details are optional, and don't slow or interfere with most play, they can be benefits** that instead of being "boring", actually extend the interestingness of the game. In fact options can often solve problems that might otherwise cause the game to be impossible or annoying or dull, if they were not available.

(All of your examples of excessive detail could be needed and fun in the right context, as long as they don't get in the way of learning and usual play.)

---
Tags: game-design
---


title: What is an animated surface mesh?

text:
# Question
Title: What is an animated surface mesh?
I am reading the paper Animated Mesh Approximation With Sphere-Meshes . The input of the algorithm mentioned in the paper is an animated surface mesh, but I do not know what an animated surface mesh is. I just learn a little about surface mesh, which may be an .off file on the disk.

What is an animated surface mesh? What kind of file format do animated surface meshes have on the disk?

# Answer
> 1 votes
I have got a good answer to this question from https://www.zhihu.com/question/50173048?from=profile\_question\_card.

The paper says:

> Problem statement. We aim at approximating a mesh animation with F frames, (meaning F different triangles meshes having the same connectivity) with an animated sphere-mesh (a mesh where each vertex is associated with a time-varying sphere).

So the animated surface mesh is a mesh animation with F frames.Every frame is a mesh with same connectivity.

And the horse models in the paper can be got from here: Deformation Transfer for Triangle Meshes -- Data. And other models (eg: Capoeira，Samba) in the paper can be got from http\[:\]//people.csail.mit.edu/drdaniel/mesh\_animation/.

Thanks Xia Qing again.

原作者：夏清 来源：知乎 著作权归作者所有，转载请联系作者获得授权。

---
Tags: animation, cg
---


title: Libgdx create rectangle Scence 2D

text:
# Question
Title: Libgdx create rectangle Scence 2D
I want to draw a empty rectangle around my gamescreen, to show "borders" around. I've tried pixmap. Works perfectly fine, but i could not find the option of change stroke width of the rectangle.

I thougt about using texture, but i do not feel it's the best way. Due to there is no artwork into this border. It's just a thick line around the screen.

Remember i want to create the border once and not recreate it everytime i render.

Any suggestions?

# Answer
You could use the `ShapeRenderer` to draw a border using `line`;

```
public class MyAndroidStudioSandboxGame extends Game {
    private ShapeRenderer shapeRenderer;

    @Override
    public void create () {
        shapeRenderer = new ShapeRenderer();
    }

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

    private void renderBorder() {
        shapeRenderer.begin(ShapeRenderer.ShapeType.Line);
        float w = Gdx.graphics.getWidth();
        float h = Gdx.graphics.getHeight();

        int lineWidth = 8;
        Gdx.gl20.glLineWidth(lineWidth);

        shapeRenderer.setColor(Color.RED);
        shapeRenderer.line(0, 0, w, 0);
        shapeRenderer.line(0, h, w, h);
        shapeRenderer.line(0, 0, 0, h);
        shapeRenderer.line(w, 0, w, h);
        shapeRenderer.end();
    }
}

```

Or, if you want a more elaborate border you can use a `NinePatch`, and set the camera accordingly.

```
public class MyAndroidStudioSandboxGame extends Game {
        private SpriteBatch batch;
        private NinePatch border;
        private OrthographicCamera borderCamera;

        @Override
        public void create () {
            batch = new SpriteBatch();
            border = new NinePatch(new Texture("border.png"), 8,8,8,8);

            float borderWidthPercent = 0.1f; // Border width is 10%
            float borderW = (16) / (borderWidthPercent*2); // 16 is 8+8 for the two borders, multiply the percent by 2 because there's a border on each side
            float borderH = borderW * Gdx.graphics.getHeight() / Gdx.graphics.getWidth(); // Maintain the aspect ratio!

            // Set the camera to view an area that is sized to what it needs to be to show the border at the desired size
            borderCamera = new OrthographicCamera(borderW, borderH);
        }

        @Override
        public void render () {
            Gdx.gl.glClearColor(0, 0, 0, 1);
            Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
            batch.begin();
            batch.setProjectionMatrix(borderCamera.combined);
            border.draw(batch,
                    -borderCamera.viewportWidth/2.0f,
                    -borderCamera.viewportHeight/2.0f,
                    borderCamera.viewportWidth,
                    borderCamera.viewportHeight );
            batch.end();
        }
    }

```

Is the above example I've used this image;  Which is 20px by 20px with an 8px border.
> 1 votes

---
Tags: libgdx
---


title: Spawning player at user's end

text:
# Question
Title: Spawning player at user's end
I am working on a 2D mobile multiplayer project. Its going to be a 2 player game for now. So the host and the client are the only players.

I am using Unity 5.4 and the default multiplayer platform by the way. I am able to spawn the character both on client and server. The syncing also works pretty well.

But for the game to be user friendly, obviously I have to spawn the player on his end of the screen and the opponent on the other end. I am unable to achieve this on the client screen. **In the client screen, the client starts from the upper end of the screen making it difficult to play with.**

So, my question: **How would I go about spawning a player in his device on his end of the screen and the opponent on the other side?** The only idea I came up with was switching the spawn points in the client version of the game. Is it possible accessing client's version of the game during runtime? And would it be the right way to go about it? If not please share an alternate solution.

# Answer
> 0 votes
Shouldn't both players be treated like "clients"?

Even if one of the players is the host, the server should still be separated from the host's client, so the server would assign spawn points based on the player number (player 1 or 2, instead of 'me' and 'other player')

---
Tags: unity, multiplayer, mobile, spawning
---


# Question
Title: How to adapt background image size with player score?
I have an image and a text for displaying the player score. They are both displayed through a canvas.

Currently, my textbox remains the same size independent of the score, so when the player gets a big score, it prints outside of the image.

I want keep my score inside the background image, and I also want to change the size of the image along with the number of digits in the score, like "10, 100, 1000, 10000" etc.

How can I adapt the size of my background image on the amount of digits in the current score?

# Answer
1. Make sure the image is imported as an UI sprite. You might want to slice the image in 3x3 divisions to control how it stretches.
2. Set the image as a background of a panel.
3. Make the score text a child of the panel
4. Add a content size fitter to the panel with "preferred fit" on horizontal and/or vertical (depending on which you want to adjust automatically, set to "Unconstrained" to switch off resizing on one axis).
5. Add horizontal (or vertical) layout group to the panel. It doesn't matter which one, unless you add more than one child.

It will then adapt to the size of its child.

This technique is also described in the Unity manual under "UI -\> UI How Tos -\> Making UI elements fit the size of their content".
> 2 votes

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


# Question
Title: Where can I download earlier versions of Oculus? I specifically need Oculus utilities 0.8 so as to use it on RiftCat
I am trying to create a game using the Leap Motion, Oculus and Unity 5. I am using RiftCat to tether it to a mobile. But games built with Oculus versions 0.6 - 0.8 are allowed to be tethered. I have found the Oculus Runtime for 0.8 but I am not able to find the Oculus utilities package. Is there another way to do this? Can anybody provide a link where I can download the Oculus utilities 0.8 for Windows.

# Answer
Go to https://developer3.oculus.com/downloads/

Check 'Game Engines' in a drop-down menu and pick a desired version on the right :)

You should use the latest one
> 1 votes

# Answer
Always download the latest version from here: https://developer3.oculus.com/documentation/game-engines/latest/concepts/unity-downloads/

This is the one that ypu need but uninstall previous ver. first.
> -2 votes

---
Tags: unity, oculus
---


# Question
Title: How to handle a different kinds of weapon in a single component and system in entity system?
A weapon can be used as melee or range weapon, it can be thrown, toss, fired, shoot, cast (a projectile) or use to slash, bash, stab . How do I apply these to entity-system? my first approach is to create an `enum` class of `WeaponType`, a melee or range.

```
public enum WeaponType {
    MELEE,
    RANGE
}

public interface Weapon {
    void use();
}

```

Then I've create a weapon component and add weapon type data, to determine its type. For melee a weapon, it needs to have a method that handles different kind of *"attack motion"* like *slash, bash, stab*. For range weapon, it needs to have a container, factory and a method that handles different kinds of *"projectile motion"* like *shoot, fire, throw, toss etc..* Now the problem is how could I create a method for different kinds of projectile motion, remember I am specifically using Ashley ECS framework

```
public class WeaponComponent implements Component {
    public Weapon weapon;
    public WeaponType type;
    // if weapon type is melee, use the below data
    public Container container // holds the created projectile
    public Factory factory // creates a different kinds of projectile object
}

// or create seperately???

public class MeleeWeaponComponent implements Component {
    ... different kinds of method also like slash, bash, stab
}

public class RangeWeaponComponent implements Component {
    ... Factory and Container
    ... different kinds of projectile motion?
}

```

In this idea, I can use abstract or interface but I think abstraction or is not recommended.

**\[Combined data suggestion\] by @Ryanwhite and me**

* Blue line is area of effect angle covered
* Green line is distance covered
* Red point is the target point

```
public class WeaponComponent implements Component {
    public Ray ray // to handle collisions
    public float aoe; // 0.5 for melee, more than 0.5 for other weapon
    public float aoeAngleCovered;
    public float aoeAngle
    public Ammo[] // 0 for melee, 1 or more for other weapon
}

```

# Answer
> 2 votes
You can use a RayCast for weapons, this allows all weapons to use one set of attributes, so range etc. Now you would have a melee weapon use the range, but set it to set 0.5. This would give the melee weapon a low range, making it seem like its melee (This would be played with allot btw) then from this your weapons all use the same attributes. It saves on creating methods for different types of weapons. Most games use a system like this, as it is really easy to create new weapons on the fly. As for stab and slash and slash just use different animations, and if the player uses that melee type, i.e right clicks a knife to stab, the damage would be different but the animation longer.

*The above is the original comment i made*

To expand on this comment, You can have one set of variables, say range and damage and ammo, then set the variables according to the weapon. For melee just set the ammo to something like -1 (Should cause it to just be unlimited) and the damage for each mouse click to be different, and play different animations.

The raycast will handle most of the calculation for you, you just gotta tell it what to do haha.

*Hope this helps*

*Edit*

\[Combined data suggestion\] by @Ryanwhite and @ronscript

```
Blue line is area of effect angle covered
Green line is distance covered
Red point is the target point

```

```
public class WeaponComponent implements Component {
    public Ray ray // to handle collisions
    public float aoe; // This would be the range of different weapons, you could stagger them for range drop etc.
    public float aoeAngleCovered;
    public float aoeAngle
    public Ammo[] // Set ammo to 0 and give exception to melee weapons to ignore ammo.
}

```

# Answer
> 1 votes
(Do note: this answer looks at the problem from a completely different angle.)

Looking at it another, more abstract way: Ranged weapons are just emitters for projectiles (or, in the case of spears, can be projectiles themselves). Meelee weapons and projectiles are physical objects (or have parts) which cause damage upon colliding with damageable entities (like npcs or crates).

Under a system like that, the swinging animation of a blade causing the blade edge to connect/collide with an damageable entity like an enemy is enough to cause damage.

Similarly, different modes of attack could be mapped to different actions/inputs, e.g. firing a rifle vs. stabbing with the bayonet.

A spear could be used to stab by playing the stab animation (which would thrust it forward), or thrown by removing it from the players inventory and spawning it in the world near the players hand, accelerated towards the direction of view (with a slight angle upwards to compensate for the ballistic curve).

Similarly, armor could be an entity attached to other entities, which cancels or changes a weapons/projectiles attack animation upon collision with a weapon.

Ofc, **using ray casts for everything is a lot easier, both in difficulty and ease of computation**.

---
Tags: java, libgdx, entity-system
---


# Question
Title: MobileSingleStickControl Elements Disabled Unity
I cloned my Unity project on other system. Elements attached to canvas(a prefab) are disabled and when I select an element in inspector, for example **Background** (shown in screenshot) it is showing weird stuff.

I suspect that some file has not been pushed that contains data related to assets, since inspector is showing improper values. For example; Rect Transform showing instance ID instead of showing X, Y value (please refer screenshot).

Please suggest what can be missing in project that hasn't been pushed or loaded properly by Unity? Thanks.

**Note:** I am using Unity v5.0.1. Cloned project made in Windows onto my mac system.

# EDIT

I upgraded unity. Now elements are similarly disabled in prefab in my original project with normal inspector mode, displaying correct components and values. See screenshot below. No element is rendering and canvas is showing empty like the first screenshot.

# Answer
I watched starting minutes of this video. And understand why elements were disabled default. It was because default platform in Build Settings selected was **Web Player** instead of some mobile platform. So I switched to **Android Platform** and all the child elements were enabled again. Please also make sure that **Mobile Input** is *enable* in Menu.
> 1 votes

# Answer
If your prefab icons are white boxes it means they're corrupted. The best option is to retrieve and older working copy from your version control system.
> 0 votes

---
Tags: unity, assets
---


# Question
Title: Heightmap vertex list to vertex + index list
Right now I'm trying to load a heightmap into my LWJGL application. I load it like that into a float\[\]\[\] array and I can read the height value at a given x and z position in the map:

```
public class HeightMap
{

float[][] heightMap;

public HeightMap (String fileName)
{
    int height, width;
    try
    {
        BufferedImage image = ImageIO.read(getClass().getResourceAsStream(fileName));
        heightMap = new float[image.getWidth()][image.getHeight()];
        for (int x = 0; x < image.getHeight(); ++x)
        {
            for (int z = 0; z < image.getWidth(); ++z)
            {
                heightMap[x][z] = new Color(image.getRGB(x, z)).getRed() / 255f;
            }
        }
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}

```

My problem is that I don't understand how to create the float\[\] vertices and byte\[\] indices arrays that I can pass to the vao and iao(and also texture coords (tco)).

Hope you can help me,

bebe

# Answer
Creating the vertices is quite easy. You already have the x and z component, the y component is the height in your heightmap with the given position. You probably want to scale this somehow as heights are often expressed as value between 0 and 1. For the indices you just have to visualize for yourself how the triangles will be made up. You need two triangles per square, so six indices. This question on StackOverflow deals with the generation of these indices.

In your code you traverse the map, place your vertices and calculate the indices along with it. This site has some example code for exactly your case. If you look into it, you will see that the algorithm is not hard. This site even covers how you generate normals for your map.
> 1 votes

---
Tags: heightmap, vertex-arrays, index-buffer, lwjgl3
---


# Question
Title: How do I make Text Mesh appear five seconds later and disappear from the scene in unity3d
I have a text mesh in my scene. I don't want the test to show right when the scene starts . I want to text to show up in the scene five or ten seconds later on the screen and than the text disappear after five seconds. I only got one error . Here is my script :

{

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

   public class oik : MonoBehaviour
   {
       private Text text;
       public float timeShown;

       void ShowMessage(string message, float timeToShow = 10)
       {
           StartCoroutine(ShowMessageCoroutine(message, timeToShow));
       }

       IEnumerator ShowMessageCoroutine(string message, float timeToShow = 10)
       {
           while (timeShown < timeToShow)
           {
               timeShown += Time.deltaTime;
               yield return null;
           }

           text.text = " The Reqiure Score is 1700" ;
       }
   }
```

}

# Answer
> 0 votes
You would call the `ShowMessage` method in your class's `Start` method. That way the timer will start and after ten seconds the text is displayed.

To remove it after another five seconds you add below `text.text = ...`:

```
timeShown += Time.deltaTime;
if (timeShown >= timeToShow + 5)
    text.text = "";

```

---
Tags: unity, unityscript, mesh, text
---


# Question
Title: real-time multiplayer server, interpolation and prediction validation
I'm building a HTML5 / Websockets based multiplayer canvas game for Facebook and I've been working on the server code for a few days now. While the games pretty simple with a 2d top down, WSAD controls and mouseclick fires a projectile to the cursor x/y - I've never had to do real-time multiplayer before. I've read a few great documents but I'm hoping I can overview my general understanding of the topic and someone can validate the approach and/or point out areas for improvement.

**Authoritative multiplayer server, client-side prediction and entity interpolation (and questions below)**

1. Client connects to server
2. Client syncs time to server
3. Server has two main update loops:
    * Update the game physics (or game state) on the server at a frequency of 30 per second (tick rate?)
    * Broadcast the game state to all clients at a frequency of 10 per second
4. Client stores three updates before being allowed to move, this builds up the cache for entity interpolation between update states (old to new with one redundency in case of packet loss)
5. Upon input from the user, the client sends input commands to server at a frequency of 10 per second - these input commands are time stamped with the clients time
6. Client moves player on screen as a prediction of what the server will return as the final (authoritative) position of client
7. Server applies all updates to its physics / state in the previously mentioned update loop
8. Server sends out time stamped world updates.
9. Client (if is behind server time && has updates in the queue) linearly interpolates the old position to the new.

**Questions**

**At 1:** possibility to use NTP time and sync between the two?

**At 5:** time stamped? Is the main purpose here to time-stamp each packet

**At 7:** The input commands that come in will be out of sync per different latencies of the clients. I'm guessing this needs to be sorted before being applied? Or is this overkill?

**At 9:** is the lerp always a fixed amount? 0.5f for example? Should I be doing something smarter?

Lots of questions I know but any help would be appreciated!!

# Answer
> At 1: possibility to use NTP time and sync between the two?

Possible but wrong. NTP is not designed for synchronizing as a game needs. You also don't want to synchronize time anyway. You want to synchronize *ticks*. Time is fuzzy; ticks are clear.

You also don't want to just sync time once. Every packet/message should have a source tick number. Latency should be constantly measured between client and server so that a client can estimate the server's tick (`last_tick_received + time_since_last_message / server_tick_rate`).

This might even be *physics tick* rather than game loop tick.

> At 5: time stamped? Is the main purpose here to time-stamp each packet

As above, tick-stamped. Actual simulation happens in ticks. Ticks are whole numbers. Time can expand or contract around ticks as process get ahead or behind. Time is wibbly-wobbly. Ticks are absolute.

> At 7: The input commands that come in will be out of sync per different latencies of the clients. I'm guessing this needs to be sorted before being applied? Or is this overkill?

This is impossible to solve perfectly.

Ticks help. The second part is to remember that you are constantly measuring/estimating latencies between all clients and server. If a client A and server has a latency of 50 ms then the server knows any message it receives from the client is from 50 ms in the past. If client B and the server has a latency of 100 ms then the client knows that any message it receives from the server is from 100 ms in the past. The server can arbitrate to tell client B that client A moved 50 ms ago, and client B adds its latency to know that client B actually moved 150 ms ago.

> At 9: is the lerp always a fixed amount? 0.5f for example? Should I be doing something smarter?

You could use a steering behavior rather than straight lerping. The further out of sync things are, the stronger correction that needs to be applied. A constant LERP function can result in some odd artifacts.
> 2 votes

---
Tags: networking, multiplayer, mmo, client-server, interpolation
---


# Question
Title: store definition of "blueprint" of object (e.g. mesh)? ... in top header = bad compile time
In my game engine, here is my mesh factory :-

```
//GraphicFactory.h
class GraphicFactory{
    enum blueprint{
        TURRET_01,CUBE,GRASS    //a lot of things
    }
    void initialize();
    BlueprintDatabase db;
}
//GraphicFactory.cpp
void GraphicFactory::initialize{
    db.add(TURRET_01,  very long definition about mesh e.g. material color ...);
    db.add(CUBE,       very long definition about mesh ....   );
}

```

To use, it is easy as :-

```
graphicFactory()->create(TURRET_01 /* happy ctrl+space */, position, rotation, scale);

```

**Here, I have a problem about compile time**:-

The `GraphicFactory` can be seen from most game systems
because they want to create some graphics.
Thus `GraphicFactory.h` must be included into every system's `.cpp` either directly or indirectly.

When one of the systems want a new type of mesh e.g. `IRON_BOX`,
I have to add `IRON_BOX` to `blueprint` in the `GraphicFactory`'s header.
As a result, I have to recompile most of systems.

**Question:** Where should I store the declation / definition of mesh?
I also faces this issue for managing material, physic object, and game object.

**My poor solution:** Use string instead of enum - register by string and query by string.

# Answer
> 1 votes
Enums are just another way to name constants (especially when you use unscoped enums). By having those constants in your GraphicFactory class you are introducing a kind of circular dependency. The users of the GraphicFactory of course have to now about it, but the GraphicFactory also has to know about the details of the needed graphics (i.e. the name of the asset), which I would consider a implementation detail of other code parts.

---

## Solution 1: #define the constants where the assets are used

You could just move the constant definitions out of the `GraphicFactory` class and #define them in the places where they are actually used. That way the GraphicFactory does not need to know about the names of the assets.

This approach has one (big) issue: You need to coordinate the values of the constants manually across the codebase, which will eventually turn out to be unmaintainable.

## Solution 2: Use strings as keys

This is essentially Solution 1, but much more maintainable. Just use strings as keys and define them in the objects where the graphics are needed. This is a lot more maintainable, because you are able to give the constants meaningful names, which is a lot easier to coordinate across a large codebase. It may be a little slower than Solution 1, but this reeks of premature optimization.

## Solution 3: Dynamically create handles to registered graphics.

The handier solution would be to create a dynamic handle to the graphic when you are registering the graphics. This would work in the following way:

1. Objects that need access to specific assets register them with the `GraphicFactory` class with a name (a string). A handle is returned (an integer type) and stored by the registering classes.
2. The name-handle pair is stored somewhere.
3. When another object tries to register an asset under the same name the stored handle is returned.
4. The asset may now be accessed by passing the handle back into the `GraphicFactory`. The requested Asset is returned and may be used.

---
Tags: c++, design-patterns
---


# Question
Title: Procedural terrain generation in cylindrical (2D) world
I'm fairly new to procedural terrain generation. I know that to generate terrain you would use different calculations with the x and y axis (also z if you have one).

But what if you want to generated random terrain on a 2D world that loops around itself? By that I mean a world in which you enter the right side upon leaving the left side (or the other way around). It should also be generated on the fly and not all at once.

One solution I can think of is to just generate ocean along the border, but that is not what I'm looking for. I also seem to remember that Civilization generated such types of worlds, but I'm not quite sure how that worked, it's been quite some time since I played that game.

So how exactly can one generate such a continuous world?

# Answer
> 6 votes
As mentioned in the comment, I figured what you required was wrappable noise. With wrappable noise, you can generate seamless textures and game worlds. You are probably familiar with generating 2D noise already.

What you need to do is sample 3 dimensional noise instead. Instead of sampling a rectangular shaped noise pattern, you are going to sample a cylindrical shaped pattern in 3D space.

The image above is what we will be doing. The idea is that you can cut this cylinder lengthwise at any point, and unroll it, and then use this as your map data. This will effectively wrap your noise around on 1 axis.

In order to do this, sample your noise data like so:

```
for (var x = 0; x < Width; x++) {
    for (var y = 0; y < Height; y++) {

        // Sample noise at smaller intervals
        float s = x / (float)Width;
        float t = y / (float)Height;

        // Calculate our 3D coordinates
        float nx = Mathf.Cos (s * 2 * Mathf.PI) / (2 * Mathf.PI);
        float ny = Mathf.Sin (s * 2 * Mathf.PI) / (2 * Mathf.PI);
        float nz = t;

        // sample noise at coordinate
        float heightValue = (float)HeightMap.Get (nx, ny, nz);

        // save noise value to a noise map
        mapData.Data [x, y] = heightValue;
    }
}

```

If you convert this map data into a texture it would wrap on the x-axis and would look something like:

More information can be found here.

# Answer
> 0 votes
For generating the terrain in chunks, you should look into... well, chunks. An interesting example of that would be the McRegion format that was eventually pulled into Minecraft. You can read a bit about it here: https://bukkit.org/threads/is-it-worth-looking-at-the-mcregion-files.35713/

As to the other part, it depends on what you want the world to look like. You say cylindrical, but I suspect that you don't mean that the world is actually a cylinder. However, if you do mean cylinder, or even sphere, then the best bet would be to generate the world as a flat plane and wrap it. But since you mention 2D, I'll assume that you mean that maxX becomes minX and maxY becomes minY as you move across the edge. In that case, so long as your terrain creation takes that into account (there's isn't a sudden cliff on the edge of one that prevents two-way movement across the border), then it also depends on your engine. You could do this with trick cameras and some scripts that cover your boundaries, making sure it loads the chunk from the other side and "teleports" your character between coordinates, but the camera makes it look smooth.

---
Tags: procedural-generation, maps, open-world
---


# Question
Title: Backup virtual goods to survive game reinstalls
I'm developing a game using Unity3D (for Android and iOS). I would like to save all user's virtual goods, so they are available even if the user remove and reinstall the app, or even if the user install it on a new device.

AFAIK an approach would be to authenticate the user, and save all the data on my backend server. But, to not reinvent the wheel, can you share your approach? i.e.: how do you authenticate users? are you using your own server, or any BaaS?

EDIT: After reading your answers, I think the best approach is to use "Google Play Game Services Saved Games" on Android, using the official plugin for Unity3D. For iOS, there is a similar feature for GameCenter, but I can't find any official plugin for Unity3D. But this plugin may work: https://www.assetstore.unity3d.com/en/#!/content/11626

Soomla plugin can be useful: https://www.assetstore.unity3d.com/en/#!/content/6103

Also, this plugin can be useful too: https://www.assetstore.unity3d.com/en/#!/content/20152

# Answer
> 2 votes
You can save the data on the application user's cloud. This answer is basically my comments put in better form.

On Android, you can rely on Google Drive. Technically, you have access to a storage space in the user's Google Drive. The user can't interact with that storage space (read/write), but he can delete it (to be confirmed, I can't find that option anymore). Also, be careful with the total usage space because it's part of the quota of the user. Of course, the developer documentation is comprehensive. If you use such a data, your application will be listed in something like Google Drive \> parameters \> Automatic application save \> Manage saves (sorry, I don't know the exact words, my phone is not in English).

On iOS, I don't really know because I never owned a cloud-connected Apple device. But from what I searched, I think you can follow the iCloud Design Guice.

# Answer
> 2 votes
My approach is to have my own server (a little one for now) with a REST API on it, and my game communicates with this API.

The authentication is another topic, I think you'll find a lot of things about that on StackExchange, I'm using a private/public key pair for that, creating a hash with private key and timestamp + other data to make sure the request is not a user-forged one and I ship the public key in the request headers to be able to find the user easily.

To implement authentication on client-side, you can simply make an endpoint called `/user/auth`, you request with `GET`, sending the user's credentials, if they are good, you send back the keypair, else you send a `400(Bad Request)`.

The goods are then stored in my database, with a POST method coming from client when it makes a valid purchase, sending me the google/iTunes purchase ID to make me able to ensure the purchase isn't a fake one.

# Answer
> 1 votes
Take a step back, don't treat it as an app or game or whatever. create a database, with fields that include the items \*You know, give each user item an id, link that id to a user etc.

Then just have the application call the database when they log in, match the user id to the log on id, then get the item id's. This process will take milliseconds and is used by a wide range of applications, not just game related.

Just my two cents on trying to simplify it.

---
Tags: unity
---


# Question
Title: How to share Unity High Scores on social media (Facebook , Google+ and Twitter)?
This may be a common question but as a n00b I have some confusion on achieving this .

I am on a small game project and I want the user to share his / her scores on social media after completing the game .

When they post , it should be something like "Hurrayyyy ! I Scored 12345 on -My Game App Name- , Can you beat my score ? Try it ." where '-My Game App Name-' and 'Try it' should be a link directing to Google Play / Windows Store etc .

My Idea is like this :-

Here Share This on Facebook , Share This on Google+ and Share This on Twitter are 3 UI Images with Button component attached to them .

So when the player clicks on those buttons , they should post on social media .

So how to achieve this ? I got something here , but I don't know how to use that . I will prefer not to use Facebook Unity Plugin . So can I achieve this ? I need code in c# , not in JavaScript :)

I hope you will help me to figure this out .

Regards , NB :)

# Answer
> 4 votes
If you are not looking to use the SDKs you can just open a URL and the user would just have to confirm the posting. Just set a button to call the ShareToTW

```
private const string TWITTER_ADDRESS = "http://twitter.com/intent/tweet";
private const string TWEET_LANGUAGE = "en";
public static string descriptionParam;
private string appStoreLink = "http://www.YOUROWNAPPLINK.com";

public void ShareToTW(string linkParameter)
{

    string nameParameter = "YOUR AWESOME GAME MESSAGE!";//this is limited in text length
    Application.OpenURL(TWITTER_ADDRESS +
       "?text=" + WWW.EscapeURL(nameParameter + "\n" + descriptionParam + "\n" + "Get the Game:\n" + appStoreLink));
}

```

# Answer
> 0 votes
I know this is an old post, but just incase people come across this question again, I'll share some of my experience/research for integrating Social Media in Unity so far.

**Facebook SDK**

Platforms: Android and iOS

For anyone wanting to integrate Facebook login/logout, sharing, and invite functionality - or any of those combinations, I would highly recommend the Facebook SDK which is free on the Unity asset store:

Facebook SDK for Unity (beta)

I used this video tutorial to help get started with Facebook Unity integration:

Facebook SDK 7.4 in Unity 5.3

To share a score you can use the ShareLink function and get the score variable and post that in the description or title for ShareLink.

**Let's Tweet In Unity**

Platforms: Android and iOS

I tried to work with the Let's Tweet In Unity plugin, but so far I am having difficulties posting a status update in Twitter. I can get access to the account and verified it for Twitter developer, but no luck yet. It is free though and sounds like it would work well once it has been set up properly:

Let's Tweet In Unity Plugin

**NOTE: With this Twitter plugin to work with Unity v5+, you have to change the HashTables to Dictionary - so instead of Hashtable, you would have Dictionary \< string, string \>**

To share a score here again accessing the score variable, you should be able to pass in the score as the text parameter for the PostTweet function - although, I am having trouble getting this function to work for me, I assume it would be that simple.

**Unishare**

Platforms: Android and iOS

There is also the UniShare plugin, but this one costs $7.99. But seems able to share text as well as in game screenshots - and shares to any sharing media type on mobile:

Unishare Unity Plugin

I am unsure how the code works for this plugin because I have not bought it, but I assume there is a simple way to add a standard text message including your score to the share link.

---
Tags: unity, c#, facebook, social, twitter
---


# Question
Title: How can i rotate the camera around an object, using compass?
I want the camera to rotate around an object in Y axis, when you rotate your phone. how can i do this?

i already have the code to do it using mouse, but i need it to turn with compass. here's the code for movement with mouse:

```
    mouseX = Input.GetAxis("Mouse X");
    offset = (Quaternion.AngleAxis(mouseX * cameraSpeed, Vector3.up) * offset);
    transform.position = point + offset;
    transform.LookAt(point);

```

i know that setting the mouseX value to change with compass direction is my answer, but how can i do it?

# Answer
> 2 votes
```
void Start() {
    // If you need an accurate heading to true north,
    // start the location service so Unity can correct for local deviations:
    Input.location.Start();

    // Start the compass.
    Input.compass.enabled = true;
}

void Update() {
    Quaternion rotation = Quaternion.Euler(0f, input.compass.trueHeading, 0f);
    // You can use compass.magneticHeading instead
    // if you don't need alignment to true north.

    // Position camera at a rotated offset relative to its center point.
    transform.position = point + rotation * offset;

    // Look at the center point.
    transform.LookAt(point);
}

```

---
Tags: unity
---


# Question
Title: How to create an animation from several .obj files in maya?
I have several .obj files. I plan to create an animation from these .obj file. Every mesh in one .obj file is correspond to one frame. And every frame only show one .obj file (meshes in others .obj files are hidden).I use Maya.

Any body has any suggestions?

# Answer
> -1 votes
Just now I got a solution from here:Autodesk Maya Tool - OBJ Sequence Import/Export demo.

This video show a tutorial for importing OBJ Sequences. After importing the obj sequences, I just got an animation composed of the imported obj sequences. Then I could export the animation to a .avi file

Download the script used in the tutorial from:OBJ Sequences Import/Export 2.0.3 (maya script).

Thanks.

---
Tags: animation, 3d-meshes, maya
---


# Question
Title: Scaling and locking SpriteRenderer Image to anchor points
I have a script that uses Index to change an object's sprite using `OnClick` to move through the sprites, like a slideshow. I want the image to scale to the size of my anchor points, because I've noticed that when I stretch the game or put the game on "maximize on play" the image stays the same size and doesn't scale to the size of my anchor points. How would I do that? This is my script:

```
public Sprite[] Images;
//Index starts at one because we are setting the first sprite in Start() method
public int _Index = 1;

void Start() {
    //Set the image to the first one
    this.gameObject.GetComponent<SpriteRenderer>().sprite = Images[0];
}

public void onClick(){
    //Reset back to 0 so it can loop again if the last sprite has been shown
    if (_Index >= Images.Length)
        _Index = 0;

    //Set the image to array at element index, then increment
    this.gameObject.GetComponent<SpriteRenderer>().sprite = Images[_Index++];
}

```

# Answer
> 1 votes
(code updated to integrate yours directly) This covers resizing the image, but it doesn't cover the aspect ratio. The aspect ratio could be easy (`targetHeight = TargetWidth * (height/width)`), or complex if you are trying to use more shaping features/positioning.

```
 public Sprite[] Images;

 //Index starts at one because we are setting the first sprite in Start() method
 public int _Index = 1;

 void Start(){
     //Set the image to the first one
     this.gameObject.GetComponent<SpriteRenderer>().sprite = Images[0];
 }

 public void onClick(){

     var renderer = GetComponent(SpriteRenderer);
     if (renderer == null) return;

     //Reset back to 0 so it can loop again if the last sprite has been shown
     if (_Index >= Images.Length)
         _Index = 0;

     //Set the image to array at element index, then increment
     renderer.sprite = Images[_Index++];

     transform.localScale = Vector3(1,1,1);

     var width = renderer.sprite.bounds.size.x;
     var height = renderer.sprite.bounds.size.y;

     var targetWidth = 16; // replace this with the code to get the width you want
     var targetHeight = 9; // replace this with the code to get the height you want

     transform.localScale.x = targetWidth / width;
     transform.localScale.y = targetHeight / height;
 }

```

However, You could just use the UI Image, which should scale with the screen size by default.

---
Tags: unity, 2d, image, scale
---


# Question
Title: Handling collisions with objects that use vector of unique pointers
```
#pragma once
#include "Entity.h"
#include <iostream>

class Projectile : public Entity
{
public:
    Projectile() {}

    Projectile(float x, float y) {
        load("Graphics/Projectile.png");
        m_sprite.setPosition(x, y);
        m_speed = 400;
    }
};

#pragma once

#include "Entity.h"
#include <iostream>
#include "Projectile.h"

enum class Color {
    red,
    yellow,
    brown,
    blue
};

class Enemy : public Entity
{
public:
    Enemy(const Color& c, const sf::Vector2f& pos) {
        switch (c) {
            case Color::blue:
            {
                load("Graphics/blueEnemy.png");
            }
            break;
            case Color::red:
            {
                load("Graphics/redEnemy.png");
            }
            break;
            case Color::yellow:
            {
                load("Graphics/yellowEnemy.png");
            }
            break;
            case Color::brown:
            {
                load("Graphics/brownEnemy.png");
            }
            break;
        }
        setPos(pos);
        m_speed = 100;
    }
};

  #pragma once
    #include "Entity.h"
    #include "Projectile.h"
    #include <vector>

class Spaceship : public Entity
{
public:
    Spaceship();
    void move(float);
    void shoot(float);
    void update(float);
    void draw(sf::RenderWindow*) override;
private:
    bool wasSpacePressed;
    std::vector<std::unique_ptr<Projectile>> m_projectiles;
    sf::Clock m_clock;
};

class EnemyFleet : public Entity
{
public:
    EnemyFleet();
    ~EnemyFleet();
    void move(float);
    bool isEnemyBottom() const;
    bool isLeftMost() const;
    bool isRightMost() const;
    void moveX(float);
    void moveDown();
    void update(float);
    void draw(sf::RenderWindow*) override;

private:
    std::vector<std::unique_ptr<Enemy>> m_enemyFleet;
    bool m_leftToRight; //motion of the enemyfleet
    float m_speedModifier;
};

```

I want to be able to delete a projectile and enemy when they collide with each other, but I'm not sure how to do this since unique\_ptr cannot be copied into any parameter in some collision manager class bc it has exclusive ownership. Is unique\_ptr still something i should use bc i dont have to call delete (like if its a raw ptr)?

# Answer
> since unique\_ptr cannot be copied into any parameter in some collision manager class bc it has exclusive ownership.

That is correct; however, you can pass *references* to unique pointers, or you could simply pass the underlying bare pointer instead. For example, if you want to have a function that tests if a projectile and a ship intersect, you could declare that function as:

```
bool intersects (const Projectile* projectile, const Enemy* enemy);

```

or

```
bool intersects (const std::unique_ptr<Projectile>& projectile, const const std::unique_ptr<Enemy>& enemy);

```

In the first case, you'd use `unique_ptr`'s `get()` method to recover the bare pointer. In the second case you'd just pass the `unique_ptr` references directly.

If the collision function returns true, you simply remove the projection and enemy from the corresponding arrays; this will delete them.
> 1 votes

---
Tags: collision-detection, sfml, c++
---


# Question
Title: How should you structure your graphics system around your logic system?
## C++ & Cocos2d-x, but I think the issue is language-independent.

I just recently finished up writing the foundational logic for my game. The way I've decided to keep my logic and my graphics decoupled is by simply having two base objects: **LogicBody** and **GraphicsBody**. Any object that needs to show up in the game needs to be comprised of both. So far, so good.

## However, I am struggling with the initialization and interaction framework. I'll explain:

1) How should I make sure the logic body and graphics body stay together (in hopes of maintaining code readability).

Should they? Take the case of object *Monster*. It will need a logic body and a graphics body. But should both of these be contained in one overarching Monster class? Won't accessing either internal structure become unnecessarily verbose (i.e. Monster-\>getGraphicsBody() every time). However, this makes initialization easy:

```
Monster::init();

```

Alternatively, it is possible to initialize both logic and graphics separately:

```
Logic::init(); Graphics::init();

```

How can I then keep them abreast/aware of each other though? This will create clutter too, as I will likely need to call setters on each at initialization to make sure they reference each other:

```
Logic::setGraphicPtr(); Graphics::setLogicPtr();

```

2) What is the appropriate way to change graphics: polling, logic-driven, or both?

In the simplest of cases, updating graphics is as easy as polling *direction*, *isMoving*, *health*, etc. However, let's say that I want to play a particular animation when the Monster gets hit. The easiest way seems to be to call the "getHitAnimation" of the graphics body from within the logic body at the time of being hit. The alternative is to poll, but it seems that a certain point you will be polling twenty different variables, which has the potential to make the graphics implementation indecipherable without reference to the logic class anyways.

3) Should a logic body have reference to its graphics body at all?

I understand how clean it would be to simply have the graphics body reference the logic body for rendering purposes, in which case the logic body has no business with the graphics body. But what about the case where logic body A has met logic body B, and graphics bodies A and B need to interact. How do I let graphics bodies A and B know where to look for another?

**I want to know the best way to implement these parallel systems with the least amount of coupling. Pseudo code welcomed.**

# Answer
> 0 votes
> How should I make sure the logic body and graphics body stay together (in hopes of maintaining code readability).

Stick them together in one overall structure:

```
struct ObjectInTheGame {
  LogicBody* logic;
  GraphicsBody* graphics;
};

```

This is the simplest thing that could work, and you should generally start there and refactor as you discover concrete problem (instead of worrying about future hypothetical ones).

> 2) What is the appropriate way to change graphics: polling, logic-driven, or both?

Both make sense. A system where the logical body "knows about" its corresponding graphics body and can push changes to it is fine. A system where the graphical body "knows about" its corresponding logical body and pulls changes from it is fine. Doing both *at the same time* is potentially confusing, because it further weakens you separation of logic and graphics and makes for a less clear code path. However, if you simply pick a direction you prefer and only work in that direction, it will be sufficiently understandable.

> 3) Should a logic body have reference to its graphics body at all?

If it needs to (for example if you're going to push graphics state changes to the graphics body from the logic body). Otherwise it should not.

In the case of your example with logic bodies A & B, if you have chosen a system where the logic body is responsible for pushing the state to the graphics body, you will be able to get the graphics bodies from A and B at the point of interaction. You can then call a method on one of the graphics bodies and pass the other as a parameter tp that method. For example, if when two objects overlap the should swap their colors around or something:

```
void HandleLogicBodyOverlaps(LogicBody& a, LogicBody& b) {
  GraphicsBody& graphicsA = a.graphicsBody();
  GraphicsBody& graphicsB = b.graphicsBody();
  graphicsA.swapColorsWith(graphicsB);
}

```

---
Tags: c++, architecture, cocos2d-x
---


title: Sending position to .net server unity

text:
# Question
Title: Sending position to .net server unity
I'm working on a multiplayer game, I created a custom C# server using TCPListner.

I can't figure out how to send a players position to the server from the client side. I also couldn't figure out how to broadcast the position received from the client side to the rest of the players. Can someone help me with this?

# Answer
You should use TCPClient. You must first set the tcpClient.

```
    _client = new TcpClient();
    if (_config == null || _config.Host == null) throw new InvalidOperationException();
    _client.Connect(_config.Host, _config.Port);

```

then you will be able to use it to send and receive packet. Sending in asynchroneous way should be something like (in old fashion Async pattern while unity is still in 3.5)

```
       protected virtual void SendAsync(TrackingArgs p_args, object p_userState)
        {
            try
            {
                byte[] l_array = ToByteArray(p_args);
                NetworkStream l_stream = _client.GetStream();
                AsyncInfo l_i = new AsyncInfo(p_args, l_array, l_stream, p_userState);
                // Send the message to the connected TcpServer.
                IAsyncResult l_res = l_stream.BeginWrite(l_array, 0, l_array.Length, new AsyncCallback(WriteCallback), l_i);
            }
            catch (Exception l_e)
            {
                throw l_e;
            }
        }

        private void WriteCallback(IAsyncResult p_ar)
        {
            AsyncInfo l_i = p_ar.AsyncState as AsyncInfo;
            Exception l_e = null ;
            try
            {
                l_i.stream.EndWrite(p_ar);
            }
            catch (IOException)
            {
                l_i.stream.Close();
            }
            if (SendCompleted != null)
            {
                SendCompleted(this, new SendCompletedEventArgs(l_i.args, l_e, false, l_i.userState));
            }
        }

```

from this base, you can also write the ReceiveAsync method. BTW, I do NOT check this code in Unity, this is only to give you a good starting point.

Have fun.
> 1 votes

---
Tags: unity, networking, client-server
---


# Question
Title: I create a 3D character in Blender and animated it. How do I use it in my Game with LWJGL
I have a character and he is animated with the Skeleton or Bone Structure but I don't know how to animate him in my game from scratch.

I am using Java with LWJGL.

I am loading static Objects with the Obj file format but obj does not support bone animation.

# Answer
> 1 votes
There are two ways that you can do this:

**1.** The first method is a bit different from what you might want, but it does work, and it is really simple. Using Blender, you could export all the frames of the animation, each one in a separate obj file, and then load each one using the obj loader you have made. Then, in game you could have a number, that is the number of the current animation frame, which will be incremented each frame.

**Advantages:** Easy to implement.

**Disadvantages:** Takes up a LOT of memory, doesn't give you any control over the animation, apart from the speed of the animation.

**2.** Export the mesh with the animated skeleton data to a COLLADA file(.dae). COLLADA is based on xml, so it should be that hard to implement a parser. Also COLLADA provides material data along side with animation and mesh data.

**Advantages:** Total control over animation. Doesn't take up much space.

**Disadvantages:** Harder to implement.

**My suggestion:** Use the first method for small, low detail models and the second one for more complex model and for those that you want full control over, like the player, for things like rag doll physics.

---
Tags: java, animation, lwjgl, skeletal-animation, collada
---


# Question
Title: How do I use Sprite in libgdx ashley ecs framework?
In the libgdx ashley wiki there's an example of `Position` and `Velocity` components, which is pretty easy to understand. My problem now is I don't know how do I integrate `Sprite` class as Component. In below example, If I use it like this the `PositionComponent` will be thrown away? because sprite has x and y fields. Also I want to use the method of `Sprite` `setOriginCenter()`, in that case do I still need to create another component which is `OriginComponent`? or completely leave it to `SpriteComponent`?. Do you think it's recommended to use this class (`Sprite`) in ECS framework?

```
class SpriteComponent implements Component {

    Sprite sprite;

}

```

# Answer
> 3 votes
> My problem now is I don't know how do I integrate Sprite class as Component.

Simple, write it like this:

```
public class SpriteComponent implements Component {
    public Sprite sprite;
}

```

\**Note: implement Poolable as well if you are working with PooledComponents.

---

> In below example, If I use it like this the PositionComponent will be thrown away? because sprite has x and y fields.

There's nothing wrong with having a SpriteComponent and a PositionComponent.

The x and y fields in the sprite are used to know where to position the sprite. Whereas, the x and y fields in your PositionComponent are used to identify the position of your entity.

If you have an entity that can have a position but no sprite then this setup seems logical.

---

> Also I want to use the method of Sprite setOriginCenter(), in that case do I still need to create another component which is OriginComponent? or completely leave it to SpriteComponent?

No. I would not create this component as this data is held in the Sprite already. You can just access it from SpriteComponent.

---

> my problem is I am using TextureComponent too, do I need to completely use SpriteComponent over TextureComponent? or I could use it both?

Depends what you need. If your entities can have either a texture or a sprite then yes, you may use both. However, if all entities that have sprites also have texures you may want to ask yourself what you are doing with both and if both are really needed.

---

Remember, Components are just 'data bags' for entities. So just think like: **Am I ever going to have an entity in my game that can have this particular data**? If so, **will this entity already have this data within another component**?

If you answered **YES** and then **NO**, then you should probably create a Component for it.

If you answered **YES** and then **YES**, then ask yourself: **Do you really require both**?

If you answered a third **YES**, then you should probably create a Component for it.

Cheers ;)

# Answer
> 1 votes
It may seem redundant to have a position component when the `Sprite` class has x and y properties but this is actually a very valid setup.

First, instead of calling it a `SpriteComponent` lets call it a `DisplayComponent` instead and implement it as follows:

```
class DisplayComponent implements Component {
    Sprite display;
}

```

The context of the component is now more explicit, it represents the visual representation of your entity. Now say at some point you wanted your entity to be invisible but you still wanted to track its position. All you need do is remove the `DisplayComponent`.

Also consider how the game loop works in an ECS System. Each System executes in sequence so you may need to do several operations on the entity's position before you actually display it. So keeping the position component separate is crucial. Typically there is a System dedicated to rendering/updating display components and you'd use the position component to update the x an y position of the sprite in the `DisplayComponent`from that System.

---
Tags: java, libgdx, sprites
---