# Question
Title: What does a linear transformation preserve?
They say an affine transformation preserves points, lines, parallel lines etc. I can see this if I think in terms of translation \[Is there any other affine transformation you can give as an example, btw\] But, what does a linear transformation preserve? By its definition, it seems like they preserve vector space structure. Geometrically what does that correspond to? For example, some of them preserve angles and distance but not all of them. Some preserve linear independence but I am guessing not all of them. What geometric property all of these linear transformations preserve?

# Answer
**Linear transformations** preserve:

* Collinearity. If three points are collinear before the transformation, they remain collinear afterwards.
* Parallelism. If two lines are parallel before the transformation, they remain parallel afterwards. *This implies that a grid will remain a grid after the transformation.*
* The Origin. The origin point will be the origin after the transformation.
* Any other property that is consequence of the ones mentioned above.

**Note**: Lengths are not preserved, but their ratios are.1 In addition, angles may or may not be preserved.1

Going further, linear transformations also preserve addition and scalar multiplication.

What does that mean?

It means that:

1. Applying the transformation to an addition of *things*, is the same as adding the transformation of those *things*.
2. Applying the transformation to a multiplication of a *thing* a scalar, is the same as doing a multiplication of the transformation of the *thing* and the scalar.

**Note**: I am being vague here when saying "thing". It can be a number, a vector, a matrix, a function, a set of numbers, a set of vectors, a set of matrices, a set of functions... whatever. What matters is that you have addition and scalar multiplication defined for them. For your game, a thing can be a position, a vector (e.g. velocity), a model, a set of models, a scene, etc.

**About ratios of length**: Ratios of lengths will be preserved for objects on a straight line. This means that for two objects on the same orientation, if one has a measure of a factor of the measure of the other, this factor will remain correct after the transformation.

**Addendum about Linear independence**: Mapping all points to the origin is a valid linear transformation. This is a trivial example of linear independence not being preserved.

---

**Affine transformation** preserve the following:

* Collinearity.
* Parallelism.
* Any other property that is consequence of the ones mentioned above.

**Note 1**: Affine transformations may or may not preserve the origin. As a result, there are affine transformations that are not linear transformations.

**Note 2**: Ratios of lengths are preserved on the same conditions as in linear transformations.

The following are the affine transformations for vector spaces:

* Identity (No change).
* Translation.
* Scaling.
* Rotation.
* Shear mapping.
* Reflection (flipping).
* Combinations of the above mentioned ones.

**Note**: Perspective projection is not an affine, nor a linear transformation. *I only mention that because it is of common use in video games. Plenty of other transformation exist that are neither affine nor linear.*

Translation is an affine transformation, but not a linear transformation (notice it does not preserve the origin). Consequently, when you combine it with the rest of operations (by using augmented transformation matrices, for example, which is common practice in game development) you lose commutativity. Thus, the order in which you apply the transformation becomes important.

**Addendum**: As noted by DMGregory, 3D shear and rotations are also non commutative.

1 Note that these statements do not ordinarily make sense in the cases of projections (ratios can become undefined in that case due to division by zero). However, we can slightly refine our definition to say that a ratio a:b is "preserved" after a transformation T to T(a):T(b) if the equations a = c b and T(a) = c T(b) both hold true. In that case, we can say ratios of lengths are preserved after a linear transformation T.
> 8 votes

---
Tags: mathematics, linear-algebra
---


# Question
Title: iOS unity game was ~60mb on testflight but now its +400mb on release, why is that ?
I really have nothing else to add except that bitcode wasn't enabled, the same game was ~60Mb when we were testing it with TestFlight, after uploading it to the store the game just became 422Mb, why is that ?

Thanks!

# Answer
> 1 votes
Enable bitcode. That allows Apple to recompile the app for each chipset, and then they only ship the relevant one to each customer. With bitcode off, all of the different code bundles end up in your app, making it bigger.

Honestly, I'm surprised they let you submit with bitcode off.

# Answer
> 1 votes
turns out the size we see in the appstore is not the "Download size", instead it's the full size of the game after being downloaded **and installed** (which mean decompressed), comparing that to the TestFlight version size (on phone storage) they are pretty similar.

---
Tags: unity, ios
---


# Question
Title: My sweep and prune is giving false positives
My code is just giving false positives. Every frame it reports an imaginary collision.

Here is my code

**Sweep And Prune:**

```
 public static void updateObjects() {

     List<BoundingBox> activeList = new LinkedList<>();
     boolean adding = true;
     for (BoundingBox box : axisList) {
        box.getOverlappingPairs().clear();
        if(adding) {
            activeList.add(box);
            adding = false;
        }else {
            for(BoundingBox e : activeList) {
                if(box.collides(e)) {
                    box.setOverlappingPairs(e);
                    System.out.println("COLLISION " + box + " : " + e);
                }else {
                    activeList.remove(box);
                }

```

**Edit:**

My AABB boxes are colliding with themselves. I have debugged my classes and have narrowed it down to the sweep and prune class.

I would appreciate if someone would help me.

# Answer
I don't know what IDE you are writing your code in, but for Java, both Netbeans and Eclipse allow you to step through code, as does Android Studio. You need to learn how to see where your code is going wrong. Then you can fix this, and many other things, besides, without having to ask others.

Having said this, you need to study (this version of) the algorithm to understand what it's *supposed* to do. Only in this way can you fix it to do what it *should* do. I offer this as an answer as it is unlikely that others are going to try all your code; and without trying it, I doubt anyone will see the fault.
> 0 votes

---
Tags: opengl, java, collision-detection, physics, lwjgl
---


title: Handles.CapFunction with Unity Editor

text:
# Question
Title: Handles.CapFunction with Unity Editor
I searched for hours on google and Unity Documentation & forums for information or tutorials on how to do this, but I can't find anything.

I'm trying to write an editor script who'll allow me to edit a zone in the scene view.

I found a way to do it and it works, BUT I really find this solution not aesthetic at all, here's how it looked :

And that's my code to achieve that :

```
[CustomEditor(typeof(CameraZone))]
public class CameraZoneEditor : Editor
{

    void OnSceneGUI()
    {
        var zone = (CameraZone)target;

        Handles.DrawSolidRectangleWithOutline(new Rect(zone.transform.position, zone.size), zone.editorColor, Color.black);
        Handles.color = Color.white;

        var center = zone.transform.position + ((Vector3)zone.size / 2);

        var handlesPos = new [] {
            new Vector3(center.x + zone.size.x / 2, center.y, center.z),
            new Vector3(center.x - zone.size.x / 2, center.y, center.z),
            new Vector3(center.x, center.y + zone.size.y / 2, center.z),
            new Vector3(center.x, center.y - zone.size.y / 2, center.z)
        };

        var posRight = Handles.Slider(handlesPos[0], Vector2.right);
        var posLeft = Handles.Slider(handlesPos[1], Vector2.left);
        var posUp = Handles.Slider(handlesPos[2], Vector2.up);
        var posDown = Handles.Slider(handlesPos[3], Vector2.down);

        var rect = new Rect(posLeft.x, posDown.y, posRight.x, posUp.y);
        zone.size = rect.size;
    }

}

```

This is working just how I want it to (except that the bottom and left arrows are not resizing the zone but that's not a problem for now).

Now to make it more beautiful, I wanted to replace the arrows with simple cubes, I've seen that I can do that with `Handles.CubeHandleCap` delegates so I made some to test it. It looks exactly how I want them to but I'm unable to resize the zone now, when I try to drag it it just unselect the GameObject.

Here's how it looks now :

And here's the code I wrote to do that :

```
[CustomEditor(typeof(CameraZone))]
public class CameraZoneEditor : Editor
{

    void OnSceneGUI()
    {
        var zone = (CameraZone)target;

        Handles.DrawSolidRectangleWithOutline(new Rect(zone.transform.position, zone.size), zone.editorColor, Color.black);
        Handles.color = Color.white;

        var center = zone.transform.position + ((Vector3)zone.size / 2);

        var handlesPos = new [] {
            new Vector3(center.x + zone.size.x / 2, center.y, center.z),
            new Vector3(center.x - zone.size.x / 2, center.y, center.z),
            new Vector3(center.x, center.y + zone.size.y / 2, center.z),
            new Vector3(center.x, center.y - zone.size.y / 2, center.z)
        };

        Handles.CapFunction rightFunc = (id, position, rotation, size, type) => Handles.CubeHandleCap(0, handlesPos[0], Quaternion.identity, 0.2f, EventType.Repaint);
        Handles.CapFunction leftFunc = (id, position, rotation, size, type) => Handles.CubeHandleCap(0, handlesPos[1], Quaternion.identity, 0.2f, EventType.Repaint);
        Handles.CapFunction upFunc = (id, position, rotation, size, type) => Handles.CubeHandleCap(0, handlesPos[2], Quaternion.identity, 0.2f, EventType.Repaint);
        Handles.CapFunction downFunc = (id, position, rotation, size, type) => Handles.CubeHandleCap(0, handlesPos[3], Quaternion.identity, 0.2f, EventType.Repaint);

        var posRight = Handles.Slider(handlesPos[0], Vector2.right, 0.2f, rightFunc, 0.1f);
        var posLeft = Handles.Slider(handlesPos[1], Vector2.left, 0.2f, leftFunc, 0.1f);
        var posUp = Handles.Slider(handlesPos[2], Vector2.up, 0.2f, upFunc, 0.1f);
        var posDown = Handles.Slider(handlesPos[3], Vector2.down, 0.2f, downFunc, 0.1f);

        var rect = new Rect(posLeft.x, posDown.y, posRight.x, posUp.y);
        zone.size = rect.size;
    }

}

```

# Answer
> 1 votes
Use FreeMoveHandle to draw custom shaped handles. Here you go.

```
using UnityEditor;
using UnityEngine;

[CustomEditor(typeof(CameraZone))]
public class CameraZoneEditor : Editor
{

    void OnSceneGUI()
    {
        var zone = (CameraZone)target;

        var center = zone.transform.position;

        Handles.DrawSolidRectangleWithOutline(new Rect(zone.transform.position - ((Vector3)zone.size / 2), zone.size), zone.editorColor, Color.black);
        Handles.color = Color.white;

        var handlesPos = new [] {
            new Vector3(center.x + zone.size.x / 2, center.y, center.z),
            new Vector3(center.x - zone.size.x / 2, center.y, center.z),
            new Vector3(center.x, center.y + zone.size.y / 2, center.z),
            new Vector3(center.x, center.y - zone.size.y / 2, center.z)
        };

        float size = HandleUtility.GetHandleSize(zone.transform.position) * 0.2f;
        Vector3 snap = Vector3.one * 0.5f;

        EditorGUI.BeginChangeCheck();
        Vector3 hPos0 = Handles.FreeMoveHandle(handlesPos[0], Quaternion.identity, size, snap, Handles.CubeHandleCap);
        if (EditorGUI.EndChangeCheck())
        {
            Undo.RecordObject(zone, "Changed Scale");
            float offset = (hPos0.x - handlesPos [0].x)/2f;
            zone.transform.position += new Vector3 (offset, 0, 0);
            zone.size = new Vector2 (hPos0.x - handlesPos [1].x, handlesPos [2].y - handlesPos [3].y);
        }

        EditorGUI.BeginChangeCheck();
        Vector3 hPos1 = Handles.FreeMoveHandle(handlesPos[1], Quaternion.identity, size, snap, Handles.CubeHandleCap);
        if (EditorGUI.EndChangeCheck())
        {
            Undo.RecordObject(zone, "Changed Scale");
            float offset = (hPos1.x - handlesPos [1].x)/2f;
            zone.transform.position += new Vector3 (offset, 0, 0);
            zone.size = new Vector2 (handlesPos [0].x - hPos1.x, handlesPos [2].y - handlesPos [3].y);

        }
        EditorGUI.BeginChangeCheck();
        Vector3 hPos2 = Handles.FreeMoveHandle(handlesPos[2], Quaternion.identity, size, snap, Handles.CubeHandleCap);
        if (EditorGUI.EndChangeCheck())
        {
            Undo.RecordObject(zone, "Changed Scale");
            float offset = (hPos2.y - handlesPos [2].y)/2f;
            zone.transform.position += new Vector3 (0, offset, 0);
            zone.size = new Vector2 (handlesPos [0].x - handlesPos [1].x, hPos2.y - handlesPos [3].y);
        }
        EditorGUI.BeginChangeCheck();
        Vector3 hPos3= Handles.FreeMoveHandle(handlesPos[3], Quaternion.identity, size, snap, Handles.CubeHandleCap);
        if (EditorGUI.EndChangeCheck())
        {
            Undo.RecordObject(zone, "Changed Scale");
            float offset = (hPos3.y - handlesPos[3].y)/2f;
            zone.transform.position += new Vector3 (0, offset, 0);
            zone.size = new Vector2 (handlesPos [0].x - handlesPos [1].x, handlesPos [2].y - hPos3.y);
        }

    }
}

```

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


# Question
Title: How do I make a background fill the whole screen in Libgdx?
I'm using this code to set a 800x420 image to be full screen:

```
public void show() {
    float w = Gdx.graphics.getWidth();
    float h = Gdx.graphics.getHeight();
    camera = new OrthographicCamera(1, h / w);
    batch = new SpriteBatch();
    texture = new Texture(Gdx.files.internal("images/splashatlas/splashatlas1.png"));
    texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
    TextureRegion region =
    new TextureRegion(texture, 0, 0, 800, 420);
    sprite = new Sprite(region);
    sprite.setSize(0.9f,
            0.9f * sprite.getHeight() / sprite.getWidth() );
            sprite.setOrigin(sprite.getWidth() / 2,
            sprite.getHeight() / 2);
            sprite.setPosition(-sprite.getWidth() / 2,
            -sprite.getHeight() / 2);
}

public void render(float delta) {
    Gdx.gl.glClearColor( 1f, 1f, 1f, 1f );
    Gdx.gl.glClear( GL20.GL_COLOR_BUFFER_BIT );
    batch.setProjectionMatrix(camera.combined);
    batch.begin();
    sprite.draw(batch);
    batch.end();
}

```

But on real device it looks like this:

I tried to `setSize` with different parameters:

```
    sprite.setSize(1.0f,
            1.0f  );

```

Now it's fullscreen, but it's really stretched:

What is the way to set a background to be full screen? I want it to look like this:

# Answer
the problem was in my images size , i set the viewport to be 800x480 but the images size was 800x420 , i just changed the image size to 800x480 and in setSize() i changed it like the following :

```
sprite.setSize(1f,
            1f * sprite.getHeight() / sprite.getWidth() );

```

and its work perfectly now.
> 4 votes

# Answer
In your `render()` method, you could set `Gdx.gl.glClearColor(0, 0, 0, 0);` which will set the background of your game to **Black**

Then you don't need to resize the sprite and the texture won't distort.

Hope this helped.
> 3 votes

# Answer
In screen constructor I use `OrthographicCamera` and `Stage` with `StretchViewport`:

```
camera = new OrthographicCamera(800,420);
camera.setToOrtho(false,800,420);
stage = new Stage(new StretchViewport(800,420, camera));

```

Then in render method of screen class I update the viewport:

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

```

And it fits the screen perfectly. Then you just draw your picture in the render method with your width and height (800 and 420). So it should work. Also I suggest using constants for width and height.

Don't forget to use `super.render();` in your game class.
> 0 votes

---
Tags: android, libgdx, image, transformation
---


# Question
Title: How do I implement a AABB-Sphere collision
i have been trying to implement an aabb-sphere collision.

This is what I tried

```
@Override
public boolean collides(Sphere other) {
    Vector3f axis = Vector3f.sub(Vector3f.sub(max, min, null), other.getCenter(), null);
    float dist = axis.length();

    return dist < (other.getRadius() * other.getRadius());
}

```

# Answer
I'm not sure how your storing your collision data or what language your working with but it looks like your trying to compare the distance from the center of your AABB to the center of your sphere. Is that correct? If so, then that is the formula for sphere to sphere collision. When working with boxes you'll need to account for their shape by measuring distance from the closest point on the edge of box to the sphere. Here is some C++ styled pseudocode with comments for AABB to Sphere collision taken from the book:

*Real Time Collision Detection* by Christer Ericson

Note: I've replaced all of the "out parameters" with returned objects.

```
// Returns true if sphere s intersects AABB b, false otherwise
public bool TestSphereAABB( Sphere s, AABB b )
{
    // Compute squared distance between sphere center and AABB
    // the sqrt(dist) is fine to use as well, but this is faster.
    float sqDist = SqDistPointAABB( s.center, b );

    // Sphere and AABB intersect if the (squared) distance between them is
    // less than the (squared) sphere radius.
    return sqDist <= s.r * s.r;
}

```

For calculating the distance from the closest edge of the box to an outside point you can use:

```
// Returns the squared distance between a point p and an AABB b
float SqDistPointAABB( Point p, AABB b )
{
    float sqDist = 0.0f;
    for( int i = 0; i < 3; i++ ){
        // for each axis count any excess distance outside box extents
        float v = p[i];
        if( v < b.min[i] ) sqDist += (b.min[i] - v) * (b.min[i] - v);
        if( v > b.max[i] ) sqDist += (v - b.max[i]) * (v - b.max[i]);
    }
    return sqDist;
}

```

Although the above code is faster, it may be easier to understand using the code below. And if you could also use the information about the closest point on the box to the sphere this will come in handy. Here is the pseudocode from the same book for finding it:

```
//Given point p, return the point q on or in AABB b that is closest to p
Point ClosestPtPointAABB( Point p, AABB b )
{
    Point q;
    // For each coordinate axis, if the point coordinate value is
    // outside box, clamp it to the box, else keep it as is
    for( int i = 0; i < 3; i++ ) {
        float v = p[i];
        if( v < b.min[i] ) v = b.min[i]; // v = max( v, b.min[i] )
        if( v > b.max[i] ) v = b.max[i]; // v = min( v, b.max[i] )
        q[i] = v;
    }
    return q;
}

```

You can take the point you get from ClosestPtPointAABB() and calculate the distance between it, and the sphere's center and then compare that distance to the sphere's radius to see if it collides.
> 5 votes

---
Tags: collision-detection, physics, aabb, bounding-spheres
---


title: Player Flying after colliding - Unity

text:
# Question
Title: Player Flying after colliding - Unity
I have a Player with a capsule collider on him and i have various objects in the scene. Most of the objects have either mesh collider or box collider enabled. When i move my player and the player collides with any object, my player just starts flying into space, literally. Any way to fix this?

Thanks in Advance.

The code i have on my player is this:

```
using UnityEngine;
using System.Collections;

public class Controller : MonoBehaviour {
Animator anim;
Rigidbody rbody;
float inputH;
float inputV;
int Life=20;
bool Dead=false;
public float sensitivity=10f;
void Start () {
    anim = GetComponent<Animator> ();
    rbody = GetComponent<Rigidbody> ();
}
void Update () {
    if (Dead == false) {
        inputH = Input.GetAxis ("Horizontal") * 50f;
        inputV = Input.GetAxis ("Vertical") * 20f;
        anim.SetFloat ("inputH", inputH);
        anim.SetFloat ("inputV", inputV);
        float moveX = inputV  * Time.deltaTime;
        float moveZ = inputH * 0.5f * Time.deltaTime;
        this.transform.position += this.transform.forward * moveX;
        this.transform.position += this.transform.right * moveZ;
        transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivity, 0);
    }
    if (Input.GetKey (KeyCode.Z))
        Life--;
    if (Life == 0)
        Dead = true;
    anim.SetBool("Dead",Dead);
}
}

```

# Answer
I kinda solved it. I'm not sure whether it is a perfect solution. I just set the values of 'Drag' and 'Angular Drag' to "Infinity". I posted the answer here so that it might be useful to someone else. Thanks for your comments guys.
> 1 votes

# Answer
The solution I've observed with this issue is to simply remove the Rigid Body from one of the collided objects.

In my case a bullet was moving to hit the plane, and the plane was floating into space.(Similar to your issue)

I removed the rigid body of the plane, and this solved my problem. Now OnCollisionEnter is called.
> 0 votes

# Answer
I have found a great answer to this problem - in 1 specific occurrence at least.

My Ex:

I had some cubes that ran back and forth - and when the player (cube) collided with them - they would stop and slowly push on the player though.. - Anyway.. this worked fine until one day it started BOUNCING my player up into the sky out of NOWHERE!!! D : I tried several fixes - only to realize - that my Plane (floor) underneath the cubes had accidentally gotten moved up a few world units (in the z axis) - SOOOO... - now my plane was intersecting with my running cube objects - .. I moved the plane back down - and low and behold .. the problem went away. - so watch out for GROUND and surrounding object's intersecting with your objects that have rigidbodys at start because this can cause a LOT of bad problems. Hope this helps some ppl! : ) Happy GameMaking!'
> 0 votes

---
Tags: unity, collision-detection, meshcollider
---


# Question
Title: opengl bump mapping (normal mapping) problem with VBO and GLSL
hi i am beginner i am trying to implement bump mapping with vbo and glsl. My question is: did i make bump mapping ? if i did why these edges didnt disappear ?

high and low meshes (i used low meshes of course)

# Answer
> 1 votes
That's not how bump mapping works. Bump mapping adds additional detail to a model, but doesn't change the triangles. You need to render a mooth mesh to make the edges invisible (the normals of a vertex shared by 2 triangles must be the same)

---
Tags: opengl, glsl, vbo, normal-mapping, bump-map
---


# Question
Title: SharpDX DirectInput Force feedback actuators are missing
I am using a simple code to read input from a DirectInput device. I would like to add force feedback to the device, however when I run this test, I cannot find any ForceFeedbackActuator, however my device supports rumble effects.

```
public void Test(Joystick joystick)
{
    joystick.SetCooperativeLevel(new WindowInteropHelper(Application.Current.MainWindow).Handle, CooperativeLevel.Background | CooperativeLevel.Exclusive);
    joystick.Properties.AxisMode = DeviceAxisMode.Absolute;
    joystick.Properties.AutoCenter = false;
    joystick.Acquire();

    foreach (var deviceObjectInstance in joystick.GetObjects())
    {
        if (deviceObjectInstance.ObjectId.Flags.HasFlag(DeviceObjectTypeFlags.ForceFeedbackActuator))
        {
        }
    }
}

```

I checked the Microsoft specification but found nothing so far.

However my driver is null as well:

```
deviceInstance.ForceFeedbackDriverGuid

```

But this can be set from registry `HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\MediaProperties\PrivateProperties\Joystick\OEM` adding a new `CLSID` value for the current device.

Any help is appreciated.

# Answer
The CLSID i have used is invalid. I installed the official software of the device, and actuators are available now.
> 0 votes

---
Tags: sharpdx, directinput, force-feedback
---


# Question
Title: VAO and VBO connection and granularity with multiple objects
How general should vertex array objects be?

I'd like to plan ahead and avoid a major revision down the road. I'm having a hard time wrapping my head around a few (possibly conflicting) pieces of wisdom scattered around the internet.

This is what I could gather from a half a year of slowly reading specs and docs, building and abstracting away a somewhat structured piece of a game engine.

* The more state changes the slower the execution (self evident)
* VAO holds state for draw calls (for a simple `bind -> draw`)
* VBOs are bound to a VAO using the attribute location from a shader program (`glGetAttribLocation -> glVertexAttribPointer`)
* These arrays are enabled by location using `glEnableVertexAttribArray`

So for a single VAO, how many or what kinds of objects should it take care of? Should a single VBO contain many objects' e.g. normals and the program use offsets when drawing, or is having separate VBOs for each a viable option?

Also, since we enable the attribute array by location inside the shader program, are the VAO and the shader in some way connected?

Any pointers would be greatly appreciated!

# Answer
In 4.3 onward (or with the `ARB-vertex-attrib-binding` extension) VAOs can change which buffers are used for pulling vertices from without needing to call `glVertexAttribPointer`.

This changes the render meshes loop to:

```
glBindVertexArray(vao);

foreach(mesh: meshes){
    //bind mesh' uniform information:
    //...

    // bind vbos:
    glBindVertexBuffer(0, mesh.vbo, 0, sizeof(vertex));

    glDrawArrays(GL_TRIANGLES, 0, mesh.numVertices);
    // or for indexed:
    // glBindElementBuffer(mesh.ebo);
    // glDrawElements(GL_TRIANGLES, mesh.numIndices, GL_UNSIGNED_INT, 0);
}

```

This means that for each vertex layout there is one VAO to create during init. Usually 4 or so layouts are enough for a game using skeletal animation and shadow mapping. If you have more then adjust your asset pipeline to reduce them.

Pre 4.3 (and without the extension) you can use a vao per set of vbo buffers that get used and use the baseVertex to select a vertex offset.

Behind the scenes some hardware does software vertex pulling, so if the vertex layout changes the driver will need to patch the program. It's much better to keep to a limited set of vertex layouts.

It is better to have interleaved attributes. This improves cache performance.
> 0 votes

---
Tags: opengl, vertex-buffer, vertex-arrays
---


title: Clamping always returns 0

text:
# Question
Title: Clamping always returns 0
I have a class with three fields:

* `StartingAngleOnRotationPlane` is 180
* `MinimumRotatedAngleX` is 0
* `MaximumRotatedAngleX` is 140

Here is the offending code:

```
public virtual float ClampRotatedDegreesWithinAllowedRange()
{
    float rotatedAngle = this.transform.GetRotatedAngleOnXPlane();
    Debug.Log("Rotated " + rotatedAngle);

    float clampedRotatedAngle =
        Mathf.Clamp(
            AngleNormaliser.BetweenNegativeAndPositive180(this.StartingAngleOnRotationPlane + rotatedAngle),
            this.MinimumRotatedAngleX,
            this.MaximumRotatedAngleX);

    return clampedRotatedAngle;
}

```

Here is the debug window:

As you can see, when the breakpoint was hit, `rotatedAngle` was -178.9446.

To calculate `clampedRotatedAngle`, `rotatedAngle` is added to `StartingAngleOnRotationPlane`, supplied to a method called `AngleNormaliser.BetweenNegativeAndPositive180(float input)`, and then clamped between `MinimumRotatedAngleX` (0) and `MaximumRotatedAngleX` (140).

Here is the code for `AngleNormaliser.BetweenNegativeAndPositive180(float input)`:

```
public static float BetweenNegativeAndPositive180(float angleBetween0And360)
{
    while (angleBetween0And360 > 180)
    {
        angleBetween0And360 -= 360;
    }

    while (angleBetween0And360 < -180)
    {
        angleBetween0And360 += 360;
    }

    return angleBetween0And360;
}

```

Here is the debug window when `AngleNormaliser.BetweenNegativeAndPositive180(float input)` was invoked:

By the time the `return` statement was hit, the result 1.055389 should be returned and assigned to the variable `clampedRotatedAngle`, since 1.055389 is within the clamping range (0 - 140).

However, that was not the case:

As you can see, `clampedRotatedAngle` was still zero.

In fact, `clampedRotatedAngle` is always zero, regardless of what I feed into the `Mathf.Clamp` function:

How can I fix this?

# Answer
```
StartingAngleOnRotationPlane is 180
MinimumRotatedAngleX is 0
MaximumRotatedAngleX is 140

```

Are these variables public or serialized? In that case Unity might be taking the values set from editor. In this case I think your MaximumRotatedAngleX is set to 0.
> 2 votes

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


# Question
Title: Can't switch to 3d view in game mode in Unity 3d
When I create a new project in Unity 3d 2017.3, I set the development mode to 3d. Let's take an example now. I create a 3d cube object (everything fine till now) and then click the play button. As soon as I start playing the game, the view changes to 2d. All I see is a square in front of me at the horizon i.e. the view is 2d and from a different perspective instead of from the main camera's perspective. I went to Edit\>Project Settings\>Editor menu and set the default behaviour to 3d (It was already 3d). Unfortunately it didn't work. Any Suggestions?

# Answer
> 1 votes
Your viewpoint in your editor is not your camera's view. I'm working on a 2D game, but routinely view it from a 3D perspective while working on it, because it makes it convenient for stacking objects in z space (if I don't want to use layers).

Anyway, my point is that your game view is going to come from your camera, not the editor interface. It's unlike like some 3D apps, where you are always "looking through" a camera while you work. Try clicking on your camera and see what it's view looks like (you should get a "camera view" window). Also, while in the editor, zoom out and select your camera gizmo in the editor view and try adjusting it's position and/or rotation to get the angle you want in your camera view.

If you can't find your camera in your editor view, make sure your camera isn't accidentally on Orthographic, which will give you an infinitely parallel frustum, and may not be easily accessible from the editor view.

---
Tags: unity, scene2d
---


title: Transfer Codes between OS

text:
# Question
Title: Transfer Codes between OS
I'm making a mobile game and had the idea of using transfer codes for taking one account to another device.

Lately, I've seen this function being used in a lot of mobile games, you go to the game settings, issue a transfer code, input it in the new device and the game account is transferred. However it's not clear for me as to how this works? since many games I have seen with this function can't transfer premium currency between different OS, for example. Or some of them, after transferring the game disable the old device from transferring back the same account before certain time has passed.

I have been looking for some information about this system but haven't been able to find out anything. So I was hoping if anyone could point me into the right direction, specially in the point about currency transfer between different OS.

**Edit:** I'll try to be a little more clear about the issue. I want to have a feature where the user cas generate a code to transfer his account or progress to another device, that's it.

The other question I had was because this kind of systems do exist actually. Mostly on games developed in Asia. They allow you to transfer your progress this way to any other device BUT if you do this from one OS to another normally you can keep your progress intact but not the in-game currency. So I was wondering why

# Answer
It is generally not allowed to transfer currency between payment systems. If the price of Gold is lower on Android by a bit and you can transfer to iOS, Apple loses their 30% cut of any sales made on Android and transferred over.
> 1 votes

# Answer
**Why** is due to platform provide rules. Transfering certain content, is not allowed by Apple in app purchase guidelines:

> 3.1 Payments
>
> 3.1.1 In-App Purchase: If you want to unlock features or functionality within your app, (by way of example: subscriptions, in-game currencies, game levels, access to premium content, or unlocking a full version), you must use in-app purchase. ...

I wasn't able to find anything definitive for Android, but I suspect they have similar restrictions. In general though, any time you have a system that effectively allows real world currency to be moved from one party to another, there tends to be more rules & regulations due to the potential for misuse, such as money laundering. In addition, the platforms don't want to make it easy to do an end run around the % the collect from IAPs.

**How** to actually transfer the content is a broad question & the specifics will vary somewhat depending on the situation. Generally speaking, you need to:

* generate a code, ideally it should be:
    + unique (for instance a GUID) to avoid collisions
    + no longer than necessary to avoid frustrating users
    + unpredictable to avoid scamming exploits
* associate the code with the source account
* when the code is used by a destination account
    + transfer the relevant content between accounts on the server side
    + update the clients to reflect the server side changes
> 1 votes

---
Tags: mobile, data
---


# Question
Title: How can I interpolate between two frames of a sprite-based 2D animation?
For example, I'm looking to animate at 60 frames per second, but clearly my artist isn't going to hand-author 60 frames of art for every second of an animation clip and even if he could, it would only work properly in locked-timestep.

So given two successive frames in a sprite-based animation, I want to smoothly "interpolate" or "morph" between them at runtime to produce a smoother, and higher frame rate animation based on where the update time for the current frame lies between the two frames.

Another way to look at it would be to say that my animation is authored such that the frames occur at regular intervals, much less frequent then 60 FPS. Say I'm 30% between when frame N should appear and when frame N+1 should appear. I want to render an image that looks like it's a 30% the way through a smooth transition from the frame N image and the frame N+1 image.

This paper seems promising, but am interested in other potential solutions I could look at for implementing this. Please do not recommend a tool as a solution.

# Answer
You can bake the "motion vectors" of the sprite-based animation and use this information to morph between frames of the sheet.

Take a look at this: http://www.klemenlozar.com/frame-blending-with-motion-vectors/
> 1 votes

# Answer
Your best bet in this scenario would be to use some sort of interpolate/blend shader since your animation is purely sprite based. It would take the pixels from the current animation frame of the sprite and then blend/interpolate it with the ones from the new frame. This probably wont look as good as an animation that was created purely from sprite sheets with the intermittent frames. But it would probably give you a similar effect as those in the linked document.

But the major concern here would be performance. I'm not a shader expert, so can't really say how practical this is when it comes to games. You might just be able to do a limited number of animations this way.
> 0 votes

---
Tags: 2d, animation
---


# Question
Title: Efficient way to avoid shadow "streaks" beyond bounds of shadow map
BACKGROUND INFO:

Using MonoGame.

To maximize shadow resolution, I've got a shadow map that covers only the area closest to the camera. (I am aware of Cascading shadow maps, but for now, I am willing to simply lose shadows far away, in exchange for higher resolution near the camera.)

Specifically, I am rendering shadows of tree billboards, that are then cast on to a ground terrain.

First version worked great except for one issue. If a shadow is drawn that touches an edge of the shadow map, then that final row (or column) of pixels is REPEATED by the "Clamp" setting of the sampler. Result is a shadow "streak" that continues from the edge of map into the distance on the ground.

---

To eliminate those streaks, give full illumination when "outside" of shadow map, I added test to my lookup function to return full illumination (1.0) if UV outside of valid range:

```
if (texCoord.x < 0 || texCoord.x > 1 || texCoord.y < 0 || texCoord.y > 1)
    return 1.0f;

... followed by the code that looks up in shadow map, returns an illumination in range 0..1.

```

This works.

I have two questions about this:

1. Is there a more efficient way to test these 4 conditions, or to avoid the need to test?
2. Is there an efficient way to solve this *when the shadow map is created*?
The sampler is set to "clamp", so if the first and last row and column of map were all "untouched" (held the *default* depth value or illumination value, depending on the shadowing technique), then I would not need to do any special tests when using the map; "clamp" would retrieve an edge pixel, so if those all were "untouched" by shadows, I would get the desired result.

2.b. It just occurred to me that one solution to (2) is to *write the default value back into the four edge rows/columns.* \[after all shadows are rendered\] What is an efficient way to do that?

# Answer
> 1 votes
You could try using a sampler set up for "border" mode filtering I think (though I never tried it). You can specify a border color for a sampler as well. I guess that out of bounds samples will return the border color automatically. (Ouch and I just read that XNA seems not to support it for some reason)

That said, I think it is good to check if you are actually inside shadow map bounds.

* You can avoid sampling for pixels that are outside the shadow map. If a lot of pixels are outside, this could gain you performance.
* I don't like the abrupt change when going outside the shadow map and all shadows disappear. With the bounds check, you can also choose for example two shadow maps (high res and low res) when close to the border and blend between them smoothly.

Also, for the bounds check I like to use code like this:

```
if(!any(texCoord - saturate(texCoord)))
{
  // we are inside bounds, sample the shadow map...
}

```

My two cents, good luck with this! :)

---
Tags: xna, monogame, shadowmap
---


title: How to smooth rotations?

text:
# Question
Title: How to smooth rotations?
I have a semi-regularly (15fps to 60fps) sampled source of position and orientation to which I am using dead reckoning to fill in gaps.

However, I would like to smooth it further to eliminate any steps due to dead reckoning error.

The x,y,z can easily be smoothed with a small (3pts?, 5pts?) moving average filter. However, I am unsure of how to approach smoothing the orientation.

I have access to Axis angle representations and a decent Quaternion class that I could possibly build a moving average filter with. It has multiply (operator \*) and power (operator ^) which in theory would allow me to effectively average a set of rotations.

Would filtering an axis angle representation work if I simply filtered the 'x','y','z' and 'a' channels and then normalized it?

# Answer
**Yes**, in fact that's what quaternions are often used for - interpolating between two different orientations. Other methods of representing orientation suffer from issues like gimbal lock and wrap-around.

> Left is quaternions, right is Euler angles
>
> https://answers.unity.com/questions/717637/how-do-you-smoothly-transitionlerp-into-a-new-rota.html

For accuracy, you can use **slerp**. However, **lerp** is faster and in most cases is accurate enough.
> 4 votes

---
Tags: 3d, mathematics, quaternion, interpolation, orientation
---


title: Random AI movement in Java

text:
# Question
Title: Random AI movement in Java
I am making a maze game in Java, where you have to escape the maze without being caught by the randomly-moving AI.

The code I am using to decide which direction the enemy moves in causes the character to change direction way too fast. It currently chooses a random number, which corresponds to the direction in which the AI moves.

How can I edit this method so it only chooses a random number every 3 seconds?

```
if(new Random().nextInt(4) == 0){
    xMove = speed;
}
if(new Random().nextInt(4) == 1){
    xMove = -speed;
}
if(new Random().nextInt(4) == 2){
    yMove = speed;
}
if(new Random().nextInt(4) == 3){
    yMove = -speed;
}

```

# Answer
> 3 votes
You need to store the last time it changed direction, let's set this to the currrent time:

```
long lastTurn = System.currentTimeMillis();

```

Each frame you first check the time difference between the current time and the last time. If this is more than 3000 milliseconds, then you change direction and reset the lastTurn variable:

```
if (System.currentTimeMillis() - lastTurn >= 3000) {
    // Change direction here
    lastTurn = System.currentTimeMillis();
}

```

Side note: your currrent way of changing direction is very inefficient. You should store the random somewhere. Also, because you generate a new number each time, there's a chance every if statement gets executed. I'd suggest storing an instance of random somewhere and using a switch instead of couple separate ifs.

# Answer
> 1 votes
Using a timer: Put these IFs into an ActionListener inside a function, like AI, then create a timer (REMEMBER: Import from javax.swing), then define the timer with 3000ms, and launch it. (You need only more, to run this method from ex. Constructor)

---
Tags: java
---


# Question
Title: How to use depth buffer for z-level rendering in roguelikes?
Developer of the game explains how z-buffer works in Dwarf Fortress (loosely quoted):

"If you clear the buffer every single frame, it kills the game. You have sort of a depth of field. You say I need about 20000 integers worth of depth. So your first frame is 0 to 20000. And the next frame is 20000 to 40000, you treat everything lower as garbage. So you go 20 to 40, 40 to 60, 60 to 80. You have to clean it if you dealing with 4 byte integer something like every 100000 times. So the problem goes away."

Source: https://youtu.be/A9g1XMr2TTA?t=1628

His description is not completely clear for me. It seems he is using depth range from lowest z-level to highest and updating only one layer per frame?

# Answer
## What is the Depth Buffer?

The depth buffer stores how far away from the "camera" is what you have rendered. This allows the graphic system (the GPU does this in modern hardware) to check if what you are drawing is in front or behind, for every pixel, and based on that decide if it is drawn (and update the depth buffer) or not. We call that, the depth test.

*I want to note that it is possible to invert the way the depth buffer works (regardless if you are doing it in on CPU or in GPU - as you should). To do that, you can flip your projection matrix along the depth axis and configure the depth test function appropiately.*

I would like to recommend the Computerphile series Triangles and Pixels. The video "The Visibility Problem - Computerphile" (third in the series) explains the motivation of the depth buffer and how it works.

## How was he using the Depth Buffer?

> And so, if you can't clean the buffer, there is a trick I learned back when I was trying to do 3D graphics back in the 90's, before we had (???) cards, and things that would do for us, and OpenGL to do it for us.
>
> You had to, actually, go draw pixel by pixel, via triangle, and you had the texture coordinate and you would be updating them as you went.
>
> And you'd have the kind of the depth of it. You have to update that as you went along the triangle. And then to avoid triangles being printed over each other when they shouldn't be, that depth should be stored in the buffer.
>
> (...)
>
> And so, the big problem with the z-buffer is that you got a screen. (...) You have to clear it every single time, if you were thinking naively about it. And that just kills the game.

He is saying that in on old systems, they had to clear the depth buffer in CPU (drawing pixel by pixel). Consequently, cleaning the depth buffer was slow. That is what he means by it "kills the game" (makes it too slow to be playable).

> So, what you do is you have your sort of depth field, or whatever, and you'd say "Oh, I need about 20000 integers worth of depth here" and then you start your first frame 0 to 20000 and then your next frame you say my values are 20000 to 40000 and you treat anything lower like garbage.

Because of that, for early games, they did a trick: They avoid clearing the depth buffer, but instead they make sure to that everything they are drawing is in front of what was previously there. That means higher depth values in this case.

The idea is that the first frame will have objects in the depth range of 0 to 20000 (because that is how much depth rage he needs), and the next frame will have depth values in the range of 20000 to 40000 it will always draw on top of the previous frame.

**Note**: He seems to be working with an inverted depth buffer (what has a higher value is ontop of what has a lower value). If he is handling the depth buffer in CPU - which seems to be the case - it is not a problem implementing it like that. To be clear: The default depth test function is to overwrite what has a higher value (That is `GL_LESS` in OpenGL). Instead he overwrites what has a lower value.

> You only have to clean it if you dealing with 4 byte integer, you would clean it once like every 100000 times. So, the problem goes away.

Eventually you run out of possible depth values (a 4 bytes signed integer let you count up to 2147483647, then you use 20000 values each frame, meaning that each 107374 frames - roughly each 100000 frames - you have to clean the depth buffer).

## Does Dwarf Fortress render like that?

> And so the path-finding buffer would work like that in Dwarf Fortress. I know what the longest path could be, and then that's the value we work with, and the I had (???) reset the floor. So that we were working from 0 to 200000, and 200 to 400, and 400 to 600...
>
> And I almost never have to clean the path map now; it cleans like every 100000 paths that are made through a section of it.

*It appears he got the figures wrong this time. The steps would be 20000 if you want to clean each 100000 iterations, with a 4 bytes integer.*

He is saying that Dwarf Fortress uses this for path finding (not for rendering). He allocates a path-finding buffer. *I am not sure what he stores there, that is, I do not know how paths are represented*. The gist is that the values stored are left behind and he moves to use a higher range instead of clearing the buffer. By doing that he can minimize the number of times he has to clear it.

---

## Is that good advice for rendering a modern game?

He is NOT currently using it for rendering; he did use it in old hardware. If you are developing for modern*ish* OpenGL or Direct X, do not do what he says there.

I want to quote this from the Common Mistakes page of Khronos Group Wiki:

> **Depth Buffer Precision**
>
> When you select a pixelformat for your window, and you ask for a Depth Buffer, the depth buffer is typically stored as a Normalized Integer with a bitdepth of 16, 24, or 32 bits.
>
> **Note**: You can create images with true floating-point depth formats. But these can only be used with Framebuffer Objects, not the Default Framebuffer.
>
> In OpenGL, all depth values lie in the range \[0, 1\]. The integer normalization process simply converts this floating-point range into integer values of the appropriate precision. It is the integer value that is stored in the depth buffer.
>
> (...)
>
> Now that the misconception about depth buffers being floating point is resolved, what is wrong with this call?
>
> ```
> glReadPixels(0, 0, width, height, GL_DEPTH_COMPONENT, GL_FLOAT, mypixels);
>
> ```
>
> Because the depth format is a normalized integer format, the driver will have to use the CPU to convert the normalized integer data into floating-point values. This is slow.
>
> ---
>
> **Swap Buffers**
>
> A modern OpenGL program should always use double buffering. A modern 3D OpenGL program should also have a depth buffer.
>
> Render sequence should be like this:
>
> ```
> glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
> RenderScene();
> SwapBuffers(hdc);  //For Windows
>
> ```
>
> The buffers should always be cleared. On much older hardware, there was a technique to get away without clearing the scene, but on even semi-recent hardware, this will actually make things slower. So always do the clear.

I want to note that there are scenarios where not clearing the depth buffer makes sense. For example if you are loading a pre-rendered scene each frame, then there is no point to clear it, because you are going to fill it right away with default values. That is a valid optimization.

However, the above quote is the guideline and usually the best practice. So, please start there, and optimize only if you really need it.

I will also link you to the Depth Precision Visualized page from NVIDIA. For an abstract: being the depth a float, it is open to many floating-point precision issues.
> 3 votes

---
Tags: depth-buffer, roguelikes
---


# Question
Title: UI Dropdown - Is it possible to have a custom value type instead of an index?
I'm using the UI Dropdown component which lets you set the text of an option (`OptionData`) only. The value of an option is the index position in the options list, so there is no way to set this.

My problem is that I have a `dictionary<string, tile>` that I use to populate the dropdown options, but I would like the value of the option to be the id of the tile class, not the index position.

---

Edit:

I know I can access elements from the list by using the value (index).

```
list[dropdown.value].id

```

But I wanted to see about extending the dropdown with this small change, as I have some other changes I would like to make, but wanted to start with something simple first just to get an idea of what is possile.

I do not want someone to post a full code solution. Am mostly after some pointers. Looking at the dropdown class, I don't see how I can extend it to modify some things (value in this case), it looks like I would have to implement by own version?

---

Some code will make this a little clearer I think:

```
// All tiles into list.
List<Tile> list = new List<Tile>(mydictionary.Values);

// Sort all tiles based on the tile name.
list.Sort((x,y) => x.name.CompareTo(y.name));

// Current way to add list to dropdown.
for(int i=0; i<list.Count; i++){
    dropdown.options.Add(new Dropdown.OptionData(){
        text = list[i].name // Tile name (string).
    });
});

// What I want to do.
for(int i=0; i<list.Count; i++){
    dropdown.options.Add(new Dropdown.OptionData(){
        text = list[i].name, // Tile name (string).
        value = list[i].id // Unqiue tile id (string).
    });
});

// Getting changed value
dropdown.onValueChanged.AddListener(delegate {
    Debug.Log(dropdown.value); // Instead of the index selected, I want the tile id
});

```

Or if the value is needed internally for some reason, then maybe an extra property that can be set and retrieved.

```
for(int i=0; i<list.Count; i++){
    dropdown.options.Add(new Dropdown.OptionData(){
        text = list[i].name, // Tile name (string).
        tile_id = list[i].id // Unqiue tile id (string).
    });
});

dropdown.onValueChanged.AddListener(delegate {
    Debug.Log(dropdown.tile_id);
});

```

I took a look at the `DropDown` class to see if I could extend it and add the "tile\_id" option in, but I got completely lost on what to do, as I am still quite new to C#.

https://bitbucket.org/Unity-Technologies/ui/src/a3f89d5f7d145e4b6fa11cf9f2de768fea2c500f/UnityEngine.UI/UI/Core/Dropdown.cs

https://docs.unity3d.com/ScriptReference/UI.Dropdown.html

# Answer
What's wrong with doing

```
dropdown.onValueChanged.AddListener(delegate {
    Debug.Log(list[dropdown.value].id);
});

```

You can use that id to index into the list you filled the dropdown with.
> 1 votes

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


# Question
Title: How can I create an outline shader for a plane?
All these toon shaders I have been seeing render an duplicated mesh behind it and extrude the normals of the vectors to make it look like it has a border, but it feels a bit hacky to me.

Basically I am trying to create an outline shader for a plane so these toon shaders do not really work.

It's probably due to my lack of deep knowledge about shaders in particular but I am really confused and would like someone to explain. I'm also a bit worried that rendering an object twice would hit the performance.

Edit: Added picture for reference. (Thanks for the edit Alexandre!)

# Answer
> 3 votes
If all we need is an outline around a rectangle, we can compute this analytically with the math of signed distance fields. :)

```
v2f vert (appdata v)
{
    v2f o;
    // Slightly enlarge our quad, so we have a margin around it to draw the outline.
    float expand = 1.1f;
    v.vertex.xyz *= expand;
    o.vertex = UnityObjectToClipPos(v.vertex);
    // If we want to get fancy, we could compute the expansion
    // dynamically based on line thickness & view angle, but I'm lazy)

    // Expand the texture coordinate space by the same margin, symmetrically.
    o.uv = (v.uv - 0.5f) * expand + 0.5f;
    return o;
}

fixed4 frag (v2f i) : SV_Target
{
    // Texcoord distance from the center of the quad.
    float2 fromCenter = abs(i.uv - 0.5f);
    // Signed distance from the horizontal & vertical edges.
    float2 fromEdge = fromCenter - 0.5f;

    // Use screenspace derivatives to convert to pixel distances.
    fromEdge.x /= length(float2(ddx(i.uv.x), ddy(i.uv.x)));
    fromEdge.y /= length(float2(ddx(i.uv.y), ddy(i.uv.y)));

    // Compute a nicely rounded distance from the edge.
    float distance = abs(min(max(fromEdge.x,fromEdge.y), 0.0f) + length(max(fromEdge, 0.0f)));

    // Sample our texture for the interior.
    fixed4 col = tex2D(_MainTex, i.uv);
    // Clip out the part of the texture outside our original 0...1 UV space.
    col.a *= step(max(fromCenter.x, fromCenter.y), 0.5f);

    // Blend in our outline within a controllable thickness of the edge.
    col = lerp(col, _Color, saturate(_Thickness - distance));

    return col;
}

```

This gives us an outline of constant pixel thickness with nicely rounded corners and antialiased edges (the green box above - the orange is Unity's selection outline, showing how we've expanded the quad relative to its otherwise identical twin below)

---
Tags: unity, shaders, fragment-shader
---


title: Saving total play time could be fine?

text:
# Question
Title: Saving total play time could be fine?
I'm making a game that needs to save total played time into file (using JSON) for comparing & resolving data conflicts between local and cloud. I will override outdated one.

Currently, I'm just adding Time.realtimeSinceStartup, but is that okay? What if the time is really, really big and couldn't be handled in Unity anymore? Could that eventually happen?

If so, what are some alternatives?

# Answer
Floating point precision is unlikely to be the problem here.

Since you're not trying to coordinate simultaneous use, but just determine which of two sequential sessions came earlier/later, you'll generally be looking at differences in timestamps of minutes, not milliseconds.

Even a single precision float can keep precision to one second for about 33 million seconds, according to the precision table I worked out here, and that's a little more than a year of continuous play. Probably safe unless you're making an idle game that you expect players will keep running unattended 24/7.

You do get inaccuracies from adding floats together, especially if they're very different in magnitude, so don't increment your total playtime using deltaTime every frame — accumulate it in chunks when you save. You'll still lose time to imprecision here, but again your precision needs are so low that it's unlikely to add up to anything impactful.

So no, this doesn't appear to be unsafe from a pure precision point of view. The problems you need to solve are likely to be elsewhere.

For instance, if I load my save on two different devices A and B, then play B offline for two days before syncing it to the cloud. Then play A offline for three days before syncing it to the cloud. Now A's total time played is more than the 2 days I'd previously synched to the cloud, so the server overwrites my B save with A. Is that the desired outcome? Should your game detect and warn the player of this branch in the save history before synching?
> 4 votes

---
Tags: unity, timer, floating-point
---


# Question
Title: Creating a large ground texture for mobile
Does anyone has any insight on creating / texturing a large mesh that will be used for a mobile game's level map?

Specifically, I was wondering how games like Vainglory achieve this.

I am familiar with the idea of splat maps, however this is where my knowledge of the subject ends...

Is the use of splats on mobile a good solution? Should the mesh be broken down into small sections which are UV'd and textured separately? Neither of these things?

# Answer
You'll generally want to break up the mesh (and the textures for the mesh) into uniform, grid-like chunks at runtime. You can *author* the mesh as one giant terrain if that's more comfortable for you. But you'll want to have some process that splits it up as you import it into your game.

This will let you cull parts of the terrain that are far offscreen (and thus don't need to be rendered), as well as allow you to stream the terrain in and out of memory as the players move around on it in order to fit within your memory budgets.

Texture splatting is, in this case, mostly irrelevant. It's a good technique to add detail and richness to the appearance of the terrain, but it's not really an optimization technique related to fitting a large map into memory.
> 2 votes

---
Tags: textures, mobile, mesh
---


title: ListBox in Unity: how to do ?

text:
# Question
Title: ListBox in Unity: how to do ?
I'm come from WinForm/.NET development, where there is a lot of 'cool' ready made widget like: combo box, list view with scrolling system included.

Now I'm using Unity and I'm trying to implement user GUI, but i'm facing some trouble because as i can see there aren't much ready made widget.

Specifically, I'm trying to implement a saving/loading system and i'm trying to add a window with a list box containing list of saving file.

What's the best widget / approach to do this ?

Thanks

# Answer
> 2 votes
Looks like you can get this behaviour like so:

1. Create a new UI-\>ScrollView

* Deactivate its horizontal scrolling checkbox
2. Navigate inside the ScrollView's hierarchy to Viewport -\> Content
3. Add 2 components:

* **Vertical Layout Group** (stacks contents vertically)
    * **Content Size Fitter** \- set vertical fit to preferred size (expands container to the size of the list vertically, so it provokes a scroll bar)
4. Add your content items underneath this parent. They'll automatically stack & scroll when needed.

---
Tags: unity, gui
---


# Question
Title: Graphics Raycast not returning GamObject Name
Here is my Graphics RayCast code:

```
void Update()

 {

if (Input.GetMouseButtonDown(0)) {

     PointerEventData cursor = new PointerEventData(EventSystem.current);
     cursor.position = Input.mousePosition;
     List<RaycastResult> objectsHit = new List<RaycastResult>();
     EventSystem.current.RaycastAll(cursor, objectsHit);
     Debug.Log(cursor.pointerPressRaycast.gameObject.name); //line 28
     }
 }

```

My Canvas settings has the "Graphics Raycaster" script enabled and all buttons are "RayCast target" enabled. The Canvas is of the "UI" layer, ignore reversed graphics is OFF and there are no blocking objects or blocking masks.

I receive the following error on runtime when selecting ANY canvas components:

> NullReferenceException: Object reference not set to an instance of an object CivilianUnitPlacement.Update () (at Assets/CivilianUnitPlacement.cs:28)

I'm unsure why this error is being generated. Looks like the RayCaster is registering a hit, so it baffles me that it cannot return the GameObject name at line 28.

# Answer
> 0 votes
I'm not sure if you'd want to use RayCastAll. Here's what should work:

```
    if (Input.GetMouseButtonDown(0))
    {
        //Set up the new Pointer Event
        m_PointerEventData = new PointerEventData(m_EventSystem);
        //Set the Pointer Event Position to that of the mouse position
        m_PointerEventData.position = Input.mousePosition;

        //Create a list of Raycast Results
        List<RaycastResult> results = new List<RaycastResult>();

        //Raycast using the Graphics Raycaster and mouse click position
        m_Raycaster.Raycast(m_PointerEventData, results);

        //For every result returned, output the name of the GameObject on the Canvas hit by the Ray
        foreach (RaycastResult result in results)
        {
            Debug.Log("Hit " + result.gameObject.name);
        }
    }

```

Here's the source: https://docs.unity3d.com/ScriptReference/UI.GraphicRaycaster.Raycast.html

# Answer
> 3 votes
Resolved - invariably, any code relating to Graphics RayCaster should be attached to the Canvas object. Problem solved.

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


# Question
Title: 3D terrain generation: geological slices and noise function
Everyone knows how to use Perlin noise to generate the **surface** of a 3D world. You may use one or several octaves to generate more detail.

It is also known how to use **3D** Perlin noise to generate, to put it simply, a 3D world (including what's below the surface) with "**holes**" in it.

The advantage of Perlin noise is that you don't need to know the entire world to compute **one specific point** in the world. Since it's a **function** (or a sum of them), all you need to know is the input seed and the function, and it gives you the output **wherever** you want. Each point does not depend on its neighbour.

Now I'm wondering how to generate a world which terrain is **a mix of different types of materials**. You may call them geological layers, even though there's not necessarily slices.

I'm having a hard time picturing how Perlin noise (or any function suitable for this) would apply to this specific goal.

Generators commonly generate the world first and ***then*** add individual items (caves, deposits of precious rocks, etc.), but that's not what I want because it would lose the benefit of the **function** thing. Applying post-processing to the terrain makes it impossible to compute **one** specific point or range, with a **pseudo-infinite level of detail**, like a function does.

what's your take on this? (Stick to the mathematical idea, no need for implementation)

# Answer
**(1) Using the same perlin seed (map) as used for terrain**

You could treat ranges in the perlin result as different materials.

Thus at a certain threshold, you transition from air / vacuum to matter, say rock; then at another, higher threshold, you might transition to iron, then to gold etc.

The problem here is that as the values build up in a region, you would always have gold surrounded by iron surrounded by ordinary rock... unless you did some post-processing to remove the surrounds (flood fill, not too hard) leaving only the core material.

**(2) Using one perlin map for terrain, and one for materials**

Wherever there is rock from the terrain (primary) map, there is also a possibility of other materials occurring, provided the intensity at this point in the materials (secondary) map is high enough. In this case you could just say, well, wherever there is a patch of high enough intensity, then we randomise material type. This could be done by calculating the centroid of those cells which were considered to be a special material (in a connected clump, which would need to be determined by flood-fill), and hashing that centroid's xyz combined (by bitshifting) to get some pseudorandom number which would be your index into the materials table, selecting the material for the clump.

Otherwise you could use the same trick as in the first approach: get the local maximum and let *that* decide what the core material is, then expand the core material into the surrounding areas until we reach the threshold where we're back to plain rock again.

**(3) Using one map for terrain and one for each material**

Given that each Perlin noise map / seed gives a 1D value at each point, this is going to be the simplest way to have many materials - have a map per material, and one for (non)solidity of terrain. Then when you exceed the threshold on the map, you can generate that material there, provided there is also solid rock there on the terrain map.

Although this looks the simplest, it probably also costs the most, as in order to get the world layout, you have to sample perlin function for as many materials as there are, plus the base terrain, for every cell in the local zone. Floodfills will probably end up being a bit cheaper, provided you can limit the expanse of each clump by setting thresholds high. But hey, maybe you hash the chunk coords to select only 3 desired materials for the chunk, then sample only these maps?

**(x) Fast interpolation of a coarsely-sampled map**

To reduce the cost of a flood fill, this can be used in conjunction with approaches 1 & 2. Instead of walking the original map (2D for demo purposes):

```
0 123456
1 xx0000
2 xxx00x
3 0xxxxx
4 0x0x00
5 00000x
6 xx0000

```

You could walk / flood fill a reduced map:

```
0 246
2 x0x
4 xx0
6 x00

```

...though this would leave you having to address values in between, to complete the map.

There *is*, however, one way in which those values could be filled in quite rapidly: GPUs do interpolation extremely well. You could interpolate a 3D texture, for instance, to generate all values in between these coarser 0,2,4,6,8 coords... indeed they could even be 0,16,32,48,64... and the GPU could rapidly interpolate all those 15 missing values between, in each axis. Whether you would be interested in *linear* interpolation is another question... you may prefer something like bicubic interpolation, which will still be very fast on GPU, but not as fast.
> 8 votes

---
Tags: unity, procedural-generation, perlin-noise
---


# Question
Title: How to make card movement behave like those in Hearthstone and Eternal CCG?
I'm trying to achieve the same effect that cards in Hearthstone and Eternal CCG does, for example, cards behave as they were a type of "crane", when the cards move, their body is tilted towards the direction they are moving, making it behave like a "crane".

Does anyone have any idea whatsoever on how I could achieve this? I'm trying to do everything manually, e.g., get the card position, detect if the card is moving left or right, change the card Y axis to achieve the tilt effect relative to the direction the card is moving, clamping the value so it doesn't over-rotate, etc., etc.

I would really appreciate and would LOVE to know how I could be doing this. Do I need to create an animation and play after giving it the direction? I don't know you help me out please!

# Answer
I've got the perfect solution, see the scripts at the end of the post.

These scripts are those actually used in Hearthstone client. You need to attach a DragRotator script to the object you want to rotate. In the Awake() function of DragRotator.cd I just added a Reset() that wasn't here, but you need to to a Reset() before using the script anyway. You need to adapt it to your game, in my case when the object move one the y axis, there is a rotation following the x axis, and when it move on the x axis, the rotation follows the y axis (it wasn't the same on the hearthstone script).

You also need a reference to a DragRotatorInfo script, made by the function SetInfo(DragRotatorInfo) info using the script. Personaly, I used a singleton to have one DragRotatorInfo script for all my DragRotator scripts. Thanks to that you can modify the values of the two DragRotatorAxisInfo of the DragRotatorInfos.

These infos are very simple and they control the two rotations (when you move up/down and left/right).

Force multiplier : the more it is, the less you have to move the object quickly to make it rotate. I use values of 10-15.

Min Degrees/Max Degrees : obviously the min & max values of the rotation in degress. I use values of 40-50.

Rest seconds : the time the object take to go back to its original position. I use values of 2-3.

Hope it helps someone!

DragRotator.cs

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

public class DragRotator : MonoBehaviour
{
    private const float EPSILON = 0.0001f;
    private const float SMOOTH_DAMP_SEC_FUDGE = 0.1f;
    private DragRotatorInfo m_info;
    private float m_pitchDeg;
    private float m_rollDeg;
    private float m_pitchVel;
    private float m_rollVel;
    private Vector3 m_prevPos;
    private Vector3 m_originalAngles;

    private void Awake()
    {
        Reset();
        this.m_prevPos = this.transform.position;
        this.m_originalAngles = this.transform.localRotation.eulerAngles;

    }

    private void Update()
    {
        Vector3 position = this.transform.position;
        Vector3 vector3 = position - this.m_prevPos;
        if ((double)vector3.sqrMagnitude > 9.99999974737875E-05)
        {
            this.m_pitchDeg += vector3.y * this.m_info.m_PitchInfo.m_ForceMultiplier;
            this.m_pitchDeg = Mathf.Clamp(this.m_pitchDeg, this.m_info.m_PitchInfo.m_MinDegrees, this.m_info.m_PitchInfo.m_MaxDegrees);
            this.m_rollDeg -= vector3.x * this.m_info.m_RollInfo.m_ForceMultiplier;
            this.m_rollDeg = Mathf.Clamp(this.m_rollDeg, this.m_info.m_RollInfo.m_MinDegrees, this.m_info.m_RollInfo.m_MaxDegrees);
        }
        this.m_pitchDeg = Mathf.SmoothDamp(this.m_pitchDeg, 0.0f, ref this.m_pitchVel, this.m_info.m_PitchInfo.m_RestSeconds * 0.1f);
        this.m_rollDeg = Mathf.SmoothDamp(this.m_rollDeg, 0.0f, ref this.m_rollVel, this.m_info.m_RollInfo.m_RestSeconds * 0.1f);
        this.transform.localRotation = Quaternion.Euler(this.m_originalAngles.x + this.m_pitchDeg, this.m_originalAngles.y + this.m_rollDeg, this.m_originalAngles.z);
        this.m_prevPos = position;
    }

    public DragRotatorInfo GetInfo()
    {
        return this.m_info;
    }

    public void SetInfo(DragRotatorInfo info)
    {
        this.m_info = info;
    }

    public void Reset()
    {
        this.m_prevPos = this.transform.position;
        this.transform.localRotation = Quaternion.Euler(this.m_originalAngles);
        this.m_rollDeg = 0.0f;
        this.m_rollVel = 0.0f;
        this.m_pitchDeg = 0.0f;
        this.m_pitchVel = 0.0f;
    }
}

```

DragRotatorInfo.cs

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

using System;

[Serializable]
public class DragRotatorInfo
{
    public DragRotatorAxisInfo m_PitchInfo;
    public DragRotatorAxisInfo m_RollInfo;
}

```

DragRotatorAxisInfo.cs

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

[Serializable]
public class DragRotatorAxisInfo
{
    public float m_ForceMultiplier;
    public float m_MinDegrees;
    public float m_MaxDegrees;
    public float m_RestSeconds;
}

```
> 1 votes

# Answer
You can use Unity's Physics. "Joints".

Which allows you to move your object like attached to a rope or spring.

Here is a video from Unity, about Physics Joint.

Here is the docs from Unity.

You need to make some adjustments to values in order to get the best effect you want.

I don't know how much Unity's Physics use your resource but this should be the easiest and fastest way.

Hope this helps! Cheers!
> 2 votes

# Answer
Use **SmoothDamp** to create a delay movement toward your mouse position, change the z to the same level of your card to avoid the card stick to the camera.

Create a virtual point by using mouse x,y and the card z - an offset. It is because you want the point in front of your card. Then use **LookAt** or **LookRotation** to make your card look at that virtual point.

```
Vector3 targetPos = new Vector3(point.x, point.y ,CardBaseNode.transform.position.z);
        CardBaseNode.transform.position = Vector3.SmoothDamp(CardBaseNode.transform.position, targetPos, ref velocity, 0.1f);
        CardBaseNode.transform.rotation = Quaternion.LookRotation(CardBaseNode.transform.position - point);

```

The point is a Vector3 with mouse x,y and the card position with z offset already.
> 0 votes

---
Tags: unity, animation, card-game
---


# Question
Title: Java advice (Printing game data to the window)
Does anybody know the best method for taking game data and setting up java to read the data then print it to the window... of which you want the game loop to start the game and read the data...

Here is what my code is right now mabe some advice would be in order..

```
import java.io.File;
import java.util.Scanner;

import DATA_Data.Data.readfile;

public class ReadFile {

private Scanner x;

public void openFile() {

    try {

        x = new Scanner (new File("DATA_1.Pak"));
        x = new Scanner (new File("DATA_2.Pak"));
        x = new Scanner (new File("DATA_3.Pak"));
        x = new Scanner (new File("DATA_4.Pak"));
        x = new Scanner (new File("DATA_5.Pak"));
        x = new Scanner (new File("DATA_6.Pak"));
        x = new Scanner (new File("DATA_7.Pak"));
        x = new Scanner (new File("DATA_8.Pak"));
        x = new Scanner (new File("DATA.Pak"));
        x = new Scanner (new File("DATAA_1.Pak"));
        x = new Scanner (new File("DATAA_2.Pak"));
        x = new Scanner (new File("DATAA_3.Pak"));
        x = new Scanner (new File("DATAA_4.Pak"));
        x = new Scanner (new File("DATAA_5.Pak"));
        x = new Scanner (new File("DATAA_6.Pak"));
        x = new Scanner (new File("DATAA_7.Pak"));
        x = new Scanner (new File("DATAA_8.Pak"));
        x = new Scanner (new File("DATAA.Pak"));
        x = new Scanner (new File("DATAE_1.Pak"));
        x = new Scanner (new File("DATAE_2.Pak"));
        x = new Scanner (new File("DATAE_3.Pak"));
        x = new Scanner (new File("DATAE_4.Pak"));
        x = new Scanner (new File("DATAE_5.Pak"));
        x = new Scanner (new File("DATAE_6.Pak"));
        x = new Scanner (new File("DATAE_7.Pak"));
        x = new Scanner (new File("DATAE_8.Pak"));
        x = new Scanner (new File("DATAE.Pak"));
        x = new Scanner (new File("DATAL_1.Pak"));
        x = new Scanner (new File("DATAL_2.Pak"));
        x = new Scanner (new File("DATAL_3.Pak"));
        x = new Scanner (new File("DATAL_4.Pak"));
        x = new Scanner (new File("DATAL_5.Pak"));
        x = new Scanner (new File("DATAL_6.Pak"));
        x = new Scanner (new File("DATAL_7.Pak"));
        x = new Scanner (new File("DATAL_8.Pak"));
        x = new Scanner (new File("DATAL.Pak"));

    }
    catch (Exception e) {

        System.out.println("Could not read file");

    }

}

    public void readFile() {

        while(x.hasNextLine()) {

            String a = x.next();
            String b = x.next();
            String c = x.next();

                System.out.printf("%s %s %s\n", a,b,c);

        }

    }

        public void closeFile() {

            x.close();

        }

public static void main(String[]args) {

 readfile r = new readfile();

 r.openFile();
 r.readFile();
 r.closeFIle();

}

}

```

# Answer
> 0 votes
You first need to start with creating your game loop. Consider something like this below. It will loop every second by default(60fps), but you're able to adjust this. Now you're able to keep checking for your .Pak file(s) in the render() loop.

```
    public class Game {

 static boolean running = false;
 private Thread thread;

private Game(){

    //no other functions should be here
    initializeGame();
}

private void initializeGame() {
    //Create your game objects and get input
}

private synchronized void startGame() {
    if(running){
        System.out.println("[DEBUG] Already running");
        return;
    }

    thread = new Thread();
    running = true;
    thread.start();
    run();
}

public void run(){
    long lastTime = System.nanoTime();
    final double ticks = 60.0;
    double ns = 1000000000 / ticks;
    double delta = 0;
    int updates = 0;
    int frames = 0;
    long timer = System.currentTimeMillis();

    //Game Loop
    while(running){

        long now = System.nanoTime();
        delta += (now - lastTime)/ns;
        lastTime = now;

        if(delta >= 1){
            tick();
            delta--;
            updates++;
        }
        render();
        frames++;

        if(System.currentTimeMillis() - timer >= 1000){
            timer += 1000;

            frames = 0;
            updates = 0;
        }
    }
    stop();
}

//Everything that updates
private void tick(){

}
//Everything that renders
private void render(){

}

private synchronized void stop() {
    if(!running){
        return;
    }

    running = false;
    try{
        //Pause thread
        thread.join();
    }catch(InterruptedException e){
        e.printStackTrace();
    }
    System.exit(1);

}

public static void main(String []args){

    Game game = new Game();
    game.startGame();

}

```

}

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


# Question
Title: How to design simple turn based combat system with multiple difficulties?
I am developing a small, turn-based game with spaceships. The user-controlled spaceship has two modes, let's call them offense and defense mode. The user can freely switch between modes. There are three types of enemy-ships. Whenever the user's ship meets one or more enemy-ships, a fight calculation should take place, which can have exactly two outcomes: either the user's ship wins (and does not carry away any damage), or the game is over. Encounters are kinda, but not completely random so one can expect a certain enemy and change the mode accordingly.

For reference, multiple enemy encouters at once might happen, and as a rough idea, the userShip usually is expected to lose if it has to fight 2-5 enemies. Like 2 are too much, if the active fight mode is disadvantageous, whereas the userShip can win against up to four ships, if the mode is advantageous. For encounters with multiple enemy types, the numbers shall be somewhere in between.

---

My requirements for the combat system are:

* completely deterministic
* one mode must not be clearly superior to the other mode. Ideally, one mode is advantageous against a certain enemy type, while the other mode is advantageous against another enemy type (not sure what to do about the third enemy type though)
* must be somehow scaleable, i.e. there should be three difficulty settings which shall be taken into account.
* ships have three attributes: Attack, Defense, Speed (however, this isn't set in stone and could be changed at will)

---

My best idea so far:

1. assign each ship type base stats (Attack/Defense/Speed, floating point numbers):

`userShip: (10/10/10)
 enemy 1: (5/10/15)
 enemy 2: (15/5/10)
 enemy 3: (10/15/5)`

2. create a modifier-table that multiplicates the userShip baseStats with a multiplicator depending on a) userShip-mode and b) enemyShip-type.
3. have the combat system compare each of the three stats (if multiple enemies involved, their combined strength), and depending on the difficulty setting, the userShip wins if the difference of at least 2 of the 3 attributes is smaller than . That way, I would have the scalability.

---

However... I was unable to design the modifier table in a way that the modifiers actually make a noticeable difference AND the user has an incentive to switch between modes when he expects a certain enemy in the next turn.

The biggest problem is the nature of the binary combat outcome. This makes it that the floating point multiplicators neglegible most of the time.

Also, I feel like I have way too many parameters (fight mode, attack, defense, speed, difficulty-setting, modifier) for such a simple calculation, but I cannot really remove any other than the modifier, and they all should be at least a little bit relevant for the combat outcome.

Also, I'm not sure how to deal with the third ship type, as there only are two modes. If the mode does not matter at all, that's poor design I think. I could add a third mode for the userShip, however that would introduce even more parameters for the combat. Unsure about that.

Any ideas how to design a combat system under these conditions?

# Answer
Your core combat mechanics seem to be very simplistic. If I understood you correctly, all the player does is pick one of two strategies and hope for the best. There is not much room for skill improvement with so little interactivity. So you might want to look for other aspects of your game where you can tweak the difficulty.

Some suggestions without touching your core combat mechanics:

* **Random encounter design**: You said "Encounters are kinda, but not completely random". So this is where you could tweak using a difficulty modifier. The higher the difficulty, the higher the average difficulty of encounters. You could also tweak the frequency of encounters.
* **Information available to the player:** On lower difficulties, give them all the information they need and warn them when they make a poor decision. On higher difficulties, give them very little information and expect them to make the right decision based on experience.
* **Strength of the AI:** Does the AI also choose a mode? If so, program the AI to make poor decisions on lower difficulties and more smart decisions on higher difficulties.
* **Margin for error:** Tweak what happens if the player loses a combat. It might be an instant game over on the highest difficulty but only a slap on the wrist on the lowest.
* **Resource management:** Does the player accumulate any resources which make them stronger over the course of the game? Then give them less resources or increase the prices when playing on higher difficulties.
> 3 votes

---
Tags: game-design, game-mechanics, combat, difficulty
---


# Question
Title: How can I send commands to only certain clients?
I am building a multiplayer game server with Unity. In the game there are players moving around the map. Now, because this map is quite large compared to the number of players, I was thinking to have the server send each clients' position only when they are nearby, and then slow the rate down when they are far away.

At first I was using the convenient `SyncVar` to do sync everyone's position, until I discovered its shortcomings, that is there is no conditional way to either sync or not a certain value.

I came out with this player synchronization class so far (I removed all optimizations for simplicity):

```
public class PlayerSyncPositionConditional : NetworkBehaviour {

    Vector3 lastPos;

    void FixedUpdate () {
        TransmitPosition();
    }

    [ClientCallback]
    void TransmitPosition () {
        CmdProvidePositionToServer(transform.position);
    }

    [Command]
    void CmdProvidePositionToServer (Vector3 pos){
        transform.position = pos;
    }

}

```

Now, what this code does is nothing more than sending its position to the server: when I am looking at the dedicated server instance, each players' position is correct. Also, as expected, each client will **not** receive any updates.

From my research, I found that instead of `SyncVar`, I can use `Server` and `ClientRpc` to dispatch commands from the server to all clients, so this

```
 [Server]
 public void MoveTo() {
     RpcMoveTo(transform.position);
 }

 [ClientRPC]
 void RpcMoveTo(Vector3 newPosition) {
     transform.position = newPosition; //this will run in all clients
 }

```

would move all clients to the transform current position whenever needed.

Now, the problem is that those commands, apparently affect every client, while I only want to affect ones that are near each other.

I know how to have the server issue the MoveTo at any rate I want, setup more than one interval, etc. but I don't know how to have it send only to certain clients at a single time.

I am not asking for the code itself, but I am getting really confused with all these client/server architecture concepts, which class does what, etc. so any heads-up will be greatly appreciated.

# Answer
Ok, so this is doable, but it's not very simple. For each client, you'd need to divide all other clients into your various tick rates. Then in each tick cycle, you'd send the message through per client. You can send to specific clients using commands like NetworkServer.SendToClient (2017.x)

Instead, what I'd recommend is to "chunk" your environment into various zones. Take a look at Unity's built in Sync Event(2017.x) framework. This allows each client to subscribe to updates for every zone they care about, and never receive things from zones they don't.

So if I'm in zone a, I subscribe to zone a's update event (maybe also adjacent zones' depending on how close I am to the border / how big the zone is). Someone else in zone c doesn't see my movement updates because they don't subscribe to those events until they meet certain conditions.
> 0 votes

---
Tags: unity, networking, unity-networking, unet
---


# Question
Title: Unity - Main manifest has <uses-sdk android:minSdkVersion='9'> but library uses minSdkVersion='17'
I got this error message when trying to build and run for Android.

> Error: \[Temp/StagingArea/AndroidManifest-main.xml:22, /Users/MNurdin/Documents/unity/TangoMotion/Temp/StagingArea/android-libraries/google-unity-wrapper/AndroidManifest.xml:3\] Main manifest has but library uses minSdkVersion='17' UnityEditor.BuildPlayerWindow:BuildPlayerAndRun()

Where I can set `android:minSdkVersion` inside `Unity`? I'm using Unity5 right now. Please advice.

# Answer
There are a couple spots that could be relevant. First off, you can set the Min API Level in Player Settings (click the Player Settings button on the bottom of that screenshot).

But besides that, you can manually provide your own manifest file; it looks like right now you are simply using the manifest that Unity automatically generates if you don't provide one manually. When an Android app is built, Unity puts the generated manifest file in the Temp folder at StagingArea/AndroidManifest.xml; copy that file to manually edit it. Provide one manually by putting it in Plugins/Android/ alongside the plug-in JAR.
> 6 votes

# Answer
I have had trouble with this for days, but now my app works well. Doing like below, may help you.

Read this section of the manual, then change `**TARGETSDKVERSION**` to your desired number in `mainTemplate.gradle`, such as 22, 23, etc.
> 0 votes

---
Tags: unity, android
---


# Question
Title: Which UVs to use when I have more UVs coordinates than vertices Obj
I have a simple sphere exported from 3DS Max in .obj format. I noticed that I have more UVs than vertices. I parsed the file with a simple program I wrote and then I put the various vertices and UVs coordinates and indeces in WebGL buffers. The result is that the texture is mapped to the sphere, but it is highly distorted. I tried using differend UV unwrap methods, but there still is a lot of distortion, all over the model.

So I'm thinking that maybe I'm using the wrong UVs coordinates. Right now I'm really just parsing the coordinates, and then applying them in the order they come. For example, I have 482 vertices and 559 UV coordiantes, so I just match them in the order they come (Vertex 1 gets UV 1, Vertex 2 gets UV 2...) and then the remaining 77 coordinates are unusued (I assume, I just load them in the buffer and let WebGL do its thing really).

So I thought maybe I should use those later coordinates instead of the early ones. Like, if I have a vertex with two or more sets of coordinates, use the last one I find while parsing the file. Or maybe I'm just plain wrong, can you give me some help? Thank you

# Answer
> 3 votes
You are using the wrong UV coordinates and yes, it's normal to have more UVs than positions.

Consider a cube. A cube has 8 positions but for correct normals it needs either 3 normals per position since each face of the cube needs a different normal. Similarly imagine you had a texture atlas with 6 different images, one for each face of the cube. You'd need different UV coordinate for every vertex per face or 24 UV coordinates.

What you usually do when you load a .obj file is load all the positions, load all the UVs, load all the normals, Then when you read the faces you need to generate new vertices where each vertex is a position, a UV, and a normal.

This will give you the correct model.

If you want you can reindex the vertices. As you make each vertex (position & UV & normal) you look in your array of already created vertices. If all three (position & UV & normal) match then you just use the index of that vertex. If they don't match you add the new vertex to the end of the vertices.

# Answer
> 0 votes
Easier way to bypass the different (position,uv, normal) count is to take all triangles and to generate 3 individual (position,uv,normal) vertices. You can then draw triangles without indices or create indices in ascending order starting from 0 (0,1,2,3,4 .... Nr of vertices)

That eliminates the need to create "proper" indices at the cost of more memory usage and some performance. Consider the following example:

```
A-B
|.|
C-D

```

You have 4 positions (A,B,C,D). And you also have 6 uv coordinates:

```
(0.0,0.0)
(0.5,0.5)
(0.5,0.0)

(0.5,0.5)
(1.0,1.0)
(0.0,1.0)

```

Inside the .obj the faces would be described something like this:

`f 0/0 1/1 2/2`

`f 1/3 3/4 2/5`

To create proper indices for this you need to find unique shared vertices. This case has none and the vertex buffer will look something like this:

`(pos-A,uv-0),(pos-B,uv-1),(pos-C,uv-2),(pos-B,uv-3),(pos-D,uv-4),(pos-C,uv-5)`

---
Tags: webgl, obj
---


# Question
Title: Creating single texture for all materials in substance painter with ID map. ID map doesn't bake properly
I am trying to create single texture for multiple materials in substance painter according to this tutorial. https://www.youtube.com/watch?v=HMP2xpGHimY

I have two models made in Blender. One with several materials(for generating ID map), another with one material.

Mesh for ID map:

Main mesh:

Both are totally identical from geometry and scale standpoint.

Generating ID map settings(it is a mobile game so I use only Unlit texture and don't require other maps and channels except for BaseColor):

Painting the model with masks created with ID map and actual problem.

Id map:

Model's materials in Blender (everything is great here):

How can I handle this issue?

# Answer
> 0 votes
I have used unwrap on both meshes instead of Smart UV Project and have them reimported. It helped.

I believe it was some UV issue.

---
Tags: textures, blender, 3d-meshes, 3d-modeling, asset-creation
---


# Question
Title: How can I check if a point(Vector3) is in Matrix4x4
I'm placing random objects in an imaginary cube in front of my target. I am using following code to do this:

```
var center = Vector3.zero;
center.z = (m_size.z / 2) + m_offset.z;
center.x += m_offset.x;
center.y += m_offset.y;
var mat = Matrix4x4.TRS(m_target.position, m_target.rotation, m_target.lossyScale);
Vector3 pos = center + new Vector3(Random.Range(-m_size.x / 2, m_size.x / 2), Random.Range(-m_size.y / 2, m_size.y / 2), Random.Range(-m_size.z / 2, m_size.z / 2));
pos = mat.MultiplyPoint(pos);
m_instantiatedObject.Add(Instantiate(m_object, pos, Quaternion.identity));

```

And it's working as expected. but now my problem is as my target moves, the previously placed objects may not be in this imaginary cube anymore. how can I check if my placed objects are in this imaginary cube and if they are not I can remove them?

# Answer
So I was able to get it to work. This is the code that worked for me:

```
Bounds b = new Bounds(center, m_size);
for(int i= m_instantiatedObject.Count - 1; i >= 0; i--)
{
        if(!b.Contains(rot.inverse.MultiplyPoint3x4(m_instantiatedObject[i].transform.position)))
        {
                var item = m_instantiatedObject[i];
                m_instantiatedObject.RemoveAt(i);
                Destroy(item);
        }
}

```
> 1 votes

# Answer
If I understood you can try something like this:

```
// foreach object get the relative posizion from target
vector3 relPos = m_object.position - m_target.position
if (Mathf.Abs(relPos.x) > m_size.x / 2) ||
   (Mathf.Abs(relPos.y) > m_size.y / 2) ||
   (Mathf.Abs(relPos.z) > m_size.z / 2)
{
 // object is outside the target cube
}

```
> 0 votes

---
Tags: unity
---