title: What is Unity Quaternion range?

text:
# Question
Title: What is Unity Quaternion range?
I've read somewhere that a Quaternion in Unity ranges between \[-1,1\] values. I mean the individual XYZW values. Ex: new Quaternion(.1f,.2f,-.3f,-.4f)

Is this true?

More clearly: I know they take float values therefore the theoretical limit is floating point value limitations, I'm asking the `real` rotation results. For instance when I look up Quaternion values while rotating a GameObject it is usually in the \[-1,1\] limits. But I'm not sure if that's my case or not.

# Answer
> 3 votes
Rotations and orientations in Unity are represented by unit quaternions.

That means a quaternion \\$(w, x, y, z)\\$ where:

$$w^2 + x^2 + y^2 + z^2 = 1$$

You can see this means each component is in the range from -1 to 1, and if any one component is near the edge of that range, the rest of the components will be closer to zero so the sum of their squares doesn't exceed 1.

If you can visualize 4 dimensions, unit quaternions are points on the surface of a 4-dimensional sphere. If your math ends up producing a quaternion outside this range, you can normalize it to snap it back onto the sphere. (`Quaternion.Lerp()` does this to get a quick & dirty blend between quaternions that stays on the unit sphere, more cheaply than a true uniform `Slerp`)

Usually the w component will be greater than 0. This corresponds to the shortest rotation from the initial orientation to the destination orientation. If you negate the whole quarternion so that w is negative (and the axis is reversed), you get the rotation that goes "the long way around" to get to the same output, say turning 270° to the left instead of 90° to the right. If the w component is exactly zero, that's a 180° rotation, so it's the same distance in either direction.

Most quaternion methods will give you a w greater than or equal to zero by default, but if you do a bunch of math to transform quaternions you can sometimes end up with a negative w. If you're using the quarternion as an orientation rather than a relative rotation to travel through, it won't make a difference since you still end up in the same place. But if you're lerping / slerping / rotateTowards-ing then keeping the w positive can ensure you get the shortest travel consistently.

---

As Almo says, you should almost never need to inspect or manipulate a quaternion's individual components directly. But if you find a need to do so, it can help to understand how they're calculated:

* (x, y, z) = axis of rotation (unit vector) times the sine of half the angle of rotation
* w = cosine of half the angle of rotation

So if a quaternion \\$q\\$ is representing a rotation about axis \\$ \vec a \\$ by an angle \\$\Theta\\$ then...

$$q\_w = \cos \frac \Theta 2\\ q\_x = a\_x \cdot \sin \frac \Theta 2\\ q\_y = a\_y \cdot \sin \frac \Theta 2\\ q\_z = a\_z \cdot \sin \frac \Theta 2 $$

So an identity rotation (angle = 0) is just (w = 1, x = 0, y = 0, z = 0)

A rotation of 180 degrees around the y axis is (0, 0, 1, 0)

And a rotation halfway between these two extremes — 90 degrees around the y axis — is \\$( \frac 1 {\sqrt 2}, 0, \frac 1 {\sqrt 2}, 0)\\$

Something you'll notice here is that to invert a quaternion - to make a quaternion that represents the opposite rotation and "undoes" the original rotation - all you have to do is negate the rotation axis components x, y, z, while keeping w unchanged. That makes `Quaternion.Inverse()` dirt cheap compared to inverting an arbitrary matrix - maybe even cheaper than transposing an orthonormal rotation matrix, since you have to touch just three variables, not six. So don't be afraid to invert quaternions on demand. ;)

# Answer
> 1 votes
I can't find anything in either the Unity docs or Quaternions themselves that would indicate the coefficients are limited in range. They are real numbers, but that appears to be the only restriction.

> Quaternions are generally represented in the form:
>
> a + b*i* \+ c*j* \+ d*k*
>
> where a, b, c, and d are real numbers, and i, j, and k are the fundamental quaternion units.

The Unity docs also say that you should never have to mess with a Quaternion's coefficients unless you *really know what you're doing*.

https://docs.unity3d.com/ScriptReference/Quaternion.html

https://en.wikipedia.org/wiki/Quaternion

---
Tags: unity, mathematics, quaternion
---


# Question
Title: What are the steps to instantiate a button in Unity?
Given a Canvas `test_canvas` containing a Button `test_button` and an empty GameObject that manages instantiation and scripts and the like called `test_manager`, what are the steps to instantiate this button through code as opposed to having it already there?

I've tried making the button a prefab and instantiating it as I would any other object but that didn't work. I tried making the canvas a prefab and then trying the button but nothing. I've searched around for quite some time and there's mention of RectTransform and SetParent but steps or specific details would clear up my confusion

# Answer
> 6 votes
Prefab your Canvas and a Button and add this script to the test\_manager gameobject

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

public class TestManagerScript : MonoBehaviour {
public GameObject canvas;
public GameObject button;

    void Start () {
        GameObject newButton = Instantiate(button) as GameObject;
        newButton.transform.SetParent(newCanvas.transform, false);
    }
}

```

be sure to drag the prefab button and prefab canvas to the public field slots this creates on the test\_manager gameobject.

If you are also Instantiating the canvas you want to keep in mind that the UI will display from top to bottom as it is listed in the hierarchy. So you would want something like this.

```
 void Start () {

        GameObject newCanvas = Instantiate(canvas) as GameObject;
        GameObject newButton = Instantiate(button) as GameObject;
        newButton.transform.SetParent(newCanvas.transform, false);
    }

```

# Answer
> 3 votes
You may want to do something like this if you don't want to use prefabs.

```
public void CreateButton(Transform panel ,Vector3 position, Vector2 size,
UnityEngine.Events.UnityAction method)
{
    GameObject button = new GameObject();
    button.transform.parent = panel;
    button.AddComponent<RectTransform>();
    button.AddComponent<Button>();
    button.transform.position = position;
    button.GetComponent<RectTransform>().SetSize(size);
    button.GetComponent<Button>().onClick.AddListener(method);
}

```

# Answer
> 1 votes
Unity provides a built-in API call that makes this easy:

```
GameObject newButton = DefaultControls.CreateButton( new Resources() );

```

...you can then customize it by calling:

```
Button buttonComponent = newButton.GetComponentInChildren<Button>();
... // do things with the Button here.

```

Old, but still a top hit on Google, so ...

# Answer
> 0 votes
Create a Ui Button at runtime, Working example without prefabs.

```
    public static UnityEngine.UI.Button UiTexturedButton(Sprite sprite, Vector2 size, GameObject canvas)
    {
        GameObject go = new GameObject("Textured button (" + sprite.name + ")");

        Image image = go.AddComponent<Image>();
        image.sprite = sprite;

        UnityEngine.UI.Button button = go.AddComponent<UnityEngine.UI.Button>();
        go.transform.SetParent(canvas.transform, false);

        image.rectTransform.sizeDelta = size;

        return button;
    }

```

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


# Question
Title: How can I create a fog-of-war based on character line of sight mesh and a shader?
I've a 3D-game using perspective view, through raycasting, I create a mesh that represents the line of sight of my characters.

I'm looking for a way to "darken" (think old-school Fog of War - Unexplored = pitch black, explored but not in sight = darkened) the entire area outside of this mesh, preferably using a shader?

Black grid above scene doesn't really work well with perspective camera + mesh, as they create the hole based on the camera and not the unit. (i.e, I want the shader to act upon the characters line of sight and not the characters line of sight as seen by the camera - otherwise units can see behind walls).

Anyone have any pointers on how to achieve this?

In the following image, the white area is a mesh created by raycasting, I'd like to create a fog-of-war shader that darkens everything outside the LoS-mesh in screen-space.

The result should be similar to what you'd see in older roguelikes, I think it's called "shadowcasting", but in 3D.

# Answer
Well, it appears to me that you already have part of the solution.

You should accumulate the raycast mesh over time, that gives you a 'memory' of what you've seen. Then you need to render your scene using two different lighting solutions ...

1) The Visible view - what your player character can see now. Use normal lighting such as HSAmbient + Point + Cone

2) The Seen (Memory) view - what your player character has seen. Use a darker lighting solution - eg hemispherical ambient lighting only.

Anything else is not rendered (black).

So looking at your image. You have the Visible mesh but you are making the mistake of rendering Not-Yet-Seen environment with the Visible lighting solution, specific to your image you have a global point/spot light lighting up unexplored environment - You should only render with environmental lighting when that environment is in LOS. So first render Has-Seen environment with ambient lighting solution (including the current visible mesh), then for the environment that intersects with your Visible mesh, render that with full lighting solution (excluding the already computed ambient term). You can then composite the two outputs.
> 1 votes

# Answer
What you need to do is to do a point light based shadow casting with the light being the character. Ie:

1. Take a depth based cubemap at the position of the character (without the character rendering in it), each frame.
2. Bake world position and visibility (that start all black) in a lightmap style texture, each pixel test to see if it's behind the depth of the shadow map.

a. if visible write a grey color to the visibility channel, output a white color to teh screen

b. if invisible they do nothing (if previously visible it will be grey else it's black)
> 0 votes

---
Tags: unity, shaders, line-of-sight, fog-of-war
---


# Question
Title: How to switch between multiple cameras in a Unity Scene, Silent Hill-style
I have 3 cameras in a practice scene that I want to switch between. Currently, I have a meshless cube acting as a trigger with the following script

```
public class CameraSwitch : MonoBehaviour
{
    [SerializeField]
    private GameObject startCamera;
    [SerializeField]
    private GameObject camera2;

    // Start is called before the first frame update

    private void OnTriggerEnter(Collider other)
    {
        if(other.tag == "Player")
        {
            startCamera.SetActive(false);
            camera2.SetActive(true);
        }
    }

}

```

It's switching from the first camera to the second no problem, but it won't switch back if I move my player through the trigger again.

Is there a way I can store multiple different cameras inside one object and just disable every camera besides the one being used so I don't have to keep making triggers?

Any advice is appreciated.

# Answer
> 1 votes
Why not instead of having multiple cameras, have transforms (as waypoints) as reference for each Trigger Box? it would be cheaper on memory (since you are just having normal GameObjects, whereas in the case of cameras you make a little more memory per Camera Component). Example:

```
public class ExampleController : MonoBehaviour
{
    public Camera camera;

    private void OnTriggerEnter(Collider collider)
    {
        if(collider.tag == "Trigger(Or Whatever...)")
        {
            CameraTrigger trigger = collider.GetComponent<CameraTrigger>();
            if(trigger != null) trigger.SetCameraWaypoint(camera.transform);
        }
    }
}

```

With CameraTrigger being another script attached to the Trigger Boxes:

```
public class CameraTrigger : MonoBehaviour
{
    public Transform cameraWaypoint;

    public void SetCameraWaypoint(Transform camera)
    {
        camera.position = cameraWaypoint.position;
        camera.rotation = cameraWaypoint.rotation;
    }
}

```

Of course, there the problem would be to test the cameras on each waypoint, in which case you could make an **Inspector** class for that:

```
using UnityEditor;

[CustomEditor(typeof(CameraTrigger))]
public class CameraTriggerEditor : Editor
{
    public override void OnInspectorGUI()
    {
        CameraTrigger myTarget = (CameraTrigger)target;

        if(GUILayout.Button("Test Camera")) myTarget.SetCameraWaypoint(Camera.main);
    }
}

```

It is a little bit (not so much) more complicated, but also more organized. Hope it gives an idea at least.

# Answer
> 0 votes
You can create a camera manager script and put it in only **one** GameObject (let's call it GameObject A). It will contain all the references to the cameras stored in an **Array**. You will also have an **index** which will indicate which camera is currently on. You can then add a function that will take the index of the camera you want to enable as a parameter, disable the camera on the current index and enable the camera on the new index. Don't forget to update the new current index.

Then you can simply call this function through another GameObject (let's call it GameObject B) in `OnTriggerEnter` method.

# Answer
> 0 votes
I think your triggerbox solution is **efficient** and in this instance it does not require a more complex way to solve it thats why i want to stick with it.

You can create a script which only contains **a Camera reference**.When it triggers it simply sets the **referenced** camera active.

This way you should get a clean solution.Only thing requires is **proper desing** in your scene using your trigger boxes.

---
Tags: unity, c#, 3d, game-mechanics
---


# Question
Title: Opening an XML in Unity3D when the game is built
At the moment, my game can open up an XML file inside the editor when I run it. In my XMLReader.cs I'm loading in my file like so:

```
_xmlDocument.Load(Application.dataPath + "\\HV_Settings\\Settings.xml");

```

This class also deals with what the XML should do once it has been read in.

However, when I build the game and run the exe, this file isn't called. I know that I can store this file in the C drive, but I want to keep everything in one place so when I start to release what I'm working on, the user doesn't need to do anything.

Am I doing something silly which is causing the XML not to be read?

# Answer
> -3 votes
Found a work around:

When I build my project, I need to manually drag my XML file into the Resources folder Unity create in the Game\_Data folder when it builds the exe.

# Answer
> 3 votes
Instead of going for the manual copy solution, you can opt to go for the StreamingAssets route.

Create a folder within your Unity project named "StreamingAssets" and place your XML files in there. Upon build, Unity will then create a verbatim copy of this directory. Your XML files will be accessible at `string path = Application.dataPath + "/StreamingAssets";`

# Answer
> 1 votes
To load files on runtime you must use the Resources class. After placing your file inside a folder called "Resources" try something like this:

```
TextAsset propStoreTextAsset = (TextAsset)Resources.Load("resourcename", typeof(TextAsset));

```

Please note, that a TextAsset is not mutable.

# Answer
> 0 votes
StreamingAssets alternative (cross-plateform):

```
public static string BundleFilePath(string filename) {
    string result;
    #if UNITY_EDITOR || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX
    result = Path.Combine(string.Format("file://{0}", Application.streamingAssetsPath), filename);
    #elif UNITY_ANDROID
    result = System.IO.Path.Combine(Application.streamingAssetsPath, filename);
    #elif UNITY_IPHONE
    result = System.IO.Path.Combine(Application.dataPath, string.Format("Raw/{0}", filename));
    #elif UNITY_WEBPLAYER
    result = System.IO.Path.Combine("StreamingAssets/", filename)); // untested
    #endif
    return result;
}

```

# Answer
> 0 votes
Just add XML in Unity create in the Game\_Data folder when it builds the game exe, not Resource.

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


# Question
Title: Player sometimes doesn't jump up while moving and jumping at the same time
My issue is that the player sometimes (occasionally) doesn't jump up while moving. It sometimes works, sometimes don't. It's weird, and I am not sure whether it's the code problem, or the tile collider's problem, here's the code:

```
using UnityEngine;

public class PlayerController : MonoBehaviour
{

    [SerializeField] private LayerMask platformsLayerMask;

    public Rigidbody2D rb;

    public float MovementSpeed = 100f;

    public float JumpingHeight = 100f;

    public BoxCollider2D bc;

    public float fallMultiplier = 2.5f;
    public float lowJumpMultiplier = 2f;

    void Awake()
    {
        rb = transform.GetComponent<Rigidbody2D>();
        bc = transform.GetComponent<BoxCollider2D>();
    }

    void FixedUpdate()
    {
        if (IsGrounded() && Input.GetKeyDown(KeyCode.Space))
        {
            rb.velocity = new Vector2(rb.velocity.x, JumpingHeight * Time.deltaTime);
            Debug.Log("Jumping");
        }
        HandleMovement();

    }

    private bool IsGrounded()
    {
        RaycastHit2D raycastHit2d = Physics2D.BoxCast(bc.bounds.center, bc.bounds.size, 0f, Vector2.down, 1f, platformsLayerMask);
        Debug.Log(raycastHit2d.collider);
        return raycastHit2d.collider != null;
    }

    void HandleMovement()
    {
        if (Input.GetKey(KeyCode.A))
        {
            rb.velocity = new Vector2(-MovementSpeed * Time.deltaTime, rb.velocity.y);
            Debug.Log("Going Left");
        }
        else
        {
            if (Input.GetKey(KeyCode.D))
            {
                rb.velocity = new Vector2(+MovementSpeed * Time.deltaTime, rb.velocity.y);
                Debug.Log("Going Right");
            }
            else
            {
                //no keys pressed
                rb.velocity = new Vector2(0, rb.velocity.y);
                Debug.Log("No key pressed");
            }
        }
        if (rb.velocity.y < 0) //reponsive jumping and falling
        {
            rb.velocity += Vector2.up * Physics2D.gravity.y * (fallMultiplier - 1) * Time.deltaTime;
        }
        else if (rb.velocity.y > 0 && Input.GetKeyDown(KeyCode.Space))
        {
            rb.velocity += Vector2.up * Physics2D.gravity.y * (lowJumpMultiplier - 1) * Time.deltaTime;
        }

    }

}

```

# Answer
> 1 votes
This happens because `FixedUpdate()` is not meant for input handling, as it runs every a certain amount of time (specified in settings) and not in every frame so it's not guaranteed to run every frame. You should add it to the `Update()` method instead, which is guaranteed to run every frame.

---
Tags: 2d, movement, tiles
---


# Question
Title: The jumping height changes randomly, and it is not due to the fact that I press the space bar longer. It is just random
Sometimes, the jump height will be so high, and sometimes it jumps normally. How do I solve this? Code:

```
using UnityEngine;

public class PlayerController : MonoBehaviour
{

    [SerializeField] private LayerMask platformsLayerMask;

    public Rigidbody2D rb;

    public float MovementSpeed = 100f;

    public float JumpingHeight = 100f;

    public BoxCollider2D bc;

    public float fallMultiplier = 2.5f;
    public float lowJumpMultiplier = 2f;

    public Animator anim;

    void Awake()
    {
        rb = transform.GetComponent<Rigidbody2D>();
        bc = transform.GetComponent<BoxCollider2D>();
    }

    void Update()
    {
        if (IsGrounded() && Input.GetKeyDown(KeyCode.Space))
        {
            rb.velocity = new Vector2(rb.velocity.x, JumpingHeight * Time.deltaTime);
            Debug.Log("Jumping");
        }
        HandleMovement();

    }

    private bool IsGrounded()
    {
        RaycastHit2D raycastHit2d = Physics2D.BoxCast(bc.bounds.center, bc.bounds.size, 0f, Vector2.down, 1f, platformsLayerMask);
        Debug.Log(raycastHit2d.collider);
        return raycastHit2d.collider != null;
    }

    void HandleMovement()
    {
        if (Input.GetKey(KeyCode.A))
        {
            rb.velocity = new Vector2(-MovementSpeed * Time.deltaTime, rb.velocity.y);
            Debug.Log("Going Left");
            transform.localScale = new Vector2(-1, 1);
        }
        else
        {
            if (Input.GetKey(KeyCode.D))
            {
                rb.velocity = new Vector2(+MovementSpeed * Time.deltaTime, rb.velocity.y);
                Debug.Log("Going Right");
                transform.localScale = new Vector2(1, 1);
            }
            else
            {
                //no keys pressed
                rb.velocity = new Vector2(0, rb.velocity.y);
                Debug.Log("No key pressed");
            }
        }
        if (rb.velocity.y < 0) //reponsive jumping and falling
        {
            rb.velocity += Vector2.up * Physics2D.gravity.y * (fallMultiplier - 1) * Time.deltaTime;
        }
        else if (rb.velocity.y > 0 && Input.GetKeyDown(KeyCode.Space))
        {
            rb.velocity += Vector2.up * Physics2D.gravity.y * (lowJumpMultiplier - 1) * Time.deltaTime;
        }

    }

}

```

# Answer
> 2 votes
Don't scale your jump velocity by `Time.deltaTime`

What that says is "If I running at a low framerate, jump higher" which is not what you want. You want a consistent change in velocity no matter whether the button was pressed on a short frame or a long frame.

For consistency, you'll want to put your falling acceleration in `FixedUpdate`, so you get the same falling arc at any framerate.

---
Tags: unity, 2d, movement
---


# Question
Title: What are the disadvantages and/or limitations of navigation meshes?
I have a lot of materials on navigation meshes, what they are, their advantages over graphs made up of waypoints, etc. However, I haven't seen much information regarding the limitations and the disadvantages of using navigation meshes, other than the obvious time they take to be created manually (which is relatively solved by Recast).

Surely this isn't a completely "magical" technique that presents itself without any drawbacks? Could someone please explain what the limitations and disadvantages of using a navigation mesh over, let's say, a graph made up of waypoints? Or point me in the right direction?

# Answer
Nav meshes are a qualitative improvement over waypoint graphs, in the same way that A\* is a natural progression over Dijkstra's algorithm. In each case, the former has evolved due to the shortcomings of the latter, and is an entirely more useful algorithm for most applications. The shortcoming is, of course, complexity (time and/or space). But I would have to say the tradeoff is small for nav meshes vs. waypoint graphs (i.e. computational complexity may increase, but not by an order of magnitude).

The only practical benefit to using waypoint graphs is where you indeed wish to restrict movement to exact lines rather than areas. Waypoint graphs = infinitesimal points and lines, whereas nav meshes are much the same thing just with (convex) polygonal areas attached which describe a valid space considered to be "this cell's territory ". Either way you are interpolating an AI entity's position from one node to another; the only difference with navmeshes is that you are doing it from one locus of points to another, whereas with waypoint graphs you are doing it from one point to another, and potentially giving due consideration to the edge separating nodes A and B. And of course from a complexity perspective, it's easy to see that waypoint graphs are moderately cheaper to operate.

As time passes, improvements do come seemingly "for free" (from the individual perspective). That's why a computer you buy today for $X is many times faster than a computer you could buy ten years ago for the same price. The point is, it's not really free -- somebody, somewhere, has put R&D effort into that. Same with algorithms. And that's why older tech mostly falls by the wayside.
> 9 votes

# Answer
Navigation meshes are restricted to surfaces, while waypoints can be placed anywhere and can do any number of connections (edges) towards any direction. Thus, waypoints can provide a more generalized and flexible solution to, for example games with abstract or extraordinary units or environments.
> 0 votes

---
Tags: path-finding, navmesh
---


# Question
Title: How can I smooth my voxels similar to 7 Days to Die?
7 Days to Die is a voxel space game like Minecraft. However unlike Minecraft, the ground blocks, sand, ore and stone are smoothed so they blend into each other and hills and tunnels appear more rolling and smooth than the blocky Minecraft style.

When you create one of these blocks, you get an octahedron shape object but when you place it, it fills in a smoothed area covering a whole block.

I want to implement something like this in my Unity game. What kind of algorithm can I use to smooth out my blocks, making them blend into each other?

Since I can't start the game right now, I add a screenshot from steamcommunity which shows the block boundaries with the "smoothed" (highlighted) dirt block inside. When the dirt/sand/gravel/ore block falls, it looks the same just not glowing.

The screenshot also shows that the surrounding blocks on that trench wall are forming a slope not a clean edge; They are blended into each other.

# Answer
> 9 votes
---

## It is not simply Marching Cubes

With marching cubes, a block would expand into the surrounding ones. In fact, with the default configurations for the Marching Cubes algorithm the result is a Rhombicuboctahedron, depicted below.

That is the result of considering all the eight vertices of a cubic block set as input for the marching cubes algorithm.

---

## It is Marching Cubes

*Wait, what?*

We do not need to set cubes and see what vertices are covered or exposed. Instead, we can set vertices directly.

See the video marching cubes algorithm for a demonstration. Notice that the set of vertices used as input for the marching cube algorithm do not form cubes. It is instead just three vertices (one isolated, two contiguous).

The linked video shows how the following input:

Results in the following output:

As you can see we end up with a octahedron (similar to the one shown in the question) which comes from the isolated vertex. Plus an elongated square bipyramid that comes which comes from the two contiguous vertices.

---

See the 15 configurations from the original Marching Cubes paper:

The tetrahedron is formed by the second configuration of the 15 shown above (the one with a single highlighted vertex), being applied on the eight cubes that surround the isolated vertex.

---

## The other algorithms

I want to bring attention to the fact that Marching Cubes is not the only solution. There is also Marching Octahedra and Marching Tetrahedra. Sadly information on these is less abundant.

# Answer
> 1 votes
```
function Smooth(solid,air) {
 return Mathf.Lerp(1.0-(solid-surface)/(1.0-surface),1.0-air/surface,(solid-surface)/(solid-air));
}

```

solid and air are points weights, surface is the minimum weight to become ground, this is my way to generate vertices in voxel edges

example: `v=Vector3.Lerp(a,b,Smooth(aWeight,bWeight));`

https://estantaya.itch.io/elsa-simulator

# Answer
> 0 votes
7 days to die uses custom Marching Cubes implementation. With some smoothing applied, and a floating point density cloud with vertex offsets. I have almost the same algorithm implemented manually, and will release it on Github someday, the project is named TileVox.

---
Tags: unity, voxels, terrain-rendering
---


title: Sticky Conveyor Belt

text:
# Question
Title: Sticky Conveyor Belt
I'm working on having a sticky conveyor belt, so that objects can also go around it. But my objects currently get stuck half way, as seen in the picture.

This is the movement code of the conveyor belt.

```
private void HandleCargo()
{
    var _speed = speed * Time.deltaTime;
    foreach (var cargo in _cargo)
    {
        var change = cargo.Key.transform.right * _speed;
        cargo.Key.transform.Translate(change);
    }
}

```

And the code taking care of the rotation to the surface.

```
private void Update()
{
    Debug.DrawRay(transform.position, -transform.up, Color.black);

    if (!Physics.Raycast(transform.position, -transform.up, out var hit, _distance)) return;
    var normal = hit.normal;

    transform.up -= (transform.up - hit.normal) * 0.05f;
}

```

If someone has pointers as to why this happens, that would be great. I kind of have an idea, since the transform right of the conveyor code is pointing inwards at this angles so the movement doesn't happen around the belt anymore, but I exhausted my attempts to fix it...

Edit: After DMGregory answer a new issue appeared. As soon as the cube starts to adjust to the spheric surface it is not exactly on the mesh anymore, which triggers my on collision exit code and stops movement on the object. I have some code that is supposed to stick the object to the belt, but that doesn't seem to work?

The sticky code

```
private void Update()
{
    Debug.DrawRay(transform.position, -transform.up, Color.black);

    if (!Physics.Raycast(transform.position, -transform.up, out var hit, _distance)) return;

    transform.rotation = Quaternion.FromToRotation(transform.up, hit.normal) * transform.rotation;
    transform.position = new Vector3(transform.position.x, hit.point.y + 0.5f, transform.position.z);
}

```

# Answer
Remember that transform.Translate operates in the object's local space by default.

So you either want to specify you're moving in world space:

```
var change = cargo.Key.transform.right * _speed;
cargo.Key.transform.Translate(change, Space.World);

```

...or simpler, just translate locally:

```
cargo.Key.transform.Translate(_speed, 0, 0);

```

As an aside, I'd recommend renaming your `_speed` variable to something like shift, offset, or travel. After multiplying by delta time to integrate it over the frame, it's no longer a rate of change over time (speed) — now it's an absolute increment.
> 0 votes

---
Tags: unity, rotation
---


title: Alpha-Beta pruning for simple card game

text:
# Question
Title: Alpha-Beta pruning for simple card game
I've been playing Final Fantasy 8's Triple Triad and figured it's a simple enough game I could write a quick script to solve for the best move in any given position. I quickly realized a brute-force solution actually took too long given the surprising number of game states such a simple game could have, and did some research to find alpha-beta pruning as a way to effectively solve such a game efficiently.

For those not familiar with the game it's quite simple.

**Setup:**

* Start with a 3x3 grid
* You and your opponent are both dealt 5 cards, each card has a number on it's north south east and west

**Rules:**

* First player is determined randomly (for my code I let the AI always go first)
* Players take turns placing a cards in the 3x3 grid
* When placing a card adjacent to another card, compare the two facing values (ie: you place a card on the west side of a card, compare your east facing number to it's west one). If your card is higher you take control of that card
* Play until the entire grid is filled, the person with the most cards in their control wins the game (note since it's a 3x3 grid with 10 cards, 1 card is always controlled by the player that went second safely in his hand)

The algorithm described below seems to play coherently, but in my testing of trying to play against it, it's definitely not playing optimally, I'm trying to figure out why. This is my first attempt at an alpha-beta pruning algorithm so I may have made some false assumptions.

The code:

Game.cs: this is a class I made to model a game, and many of the functions I would run on it.

Notes:

* There's some oddities I wrote simply because I was serializing this object down to an angular app to play through the game visually to understand the algorithm, most of them stem from the fact that 2-d arrays in c# serialize strangely
* I hold both the 2-D array of cards and a 2-D array of bools to hold the state of the board, true meaning the alpha player is control of that square.
* I feel like LINQ just doesn't work for jagged arrays in c#, but they have to be declared that way because that's how json gets deserialized, I will accept any random tips here though as the number of old school for loops felt dated.
* I tried to add comments to help explain my thought process

--

```
public class Game
{
    public Card[][] board { get; set; }
    public bool?[][] boardOwnership { get; set; }
    public Move LastMove { get; set; }

    public Game()
    {
        //Ignore how ridiculous these declarations are, I was fighting with a serializer to send the whole game state to an angular app
        //I wrote to visual the results
        board = new Card[3][];
        board[0] = new Card[3];
        board[1] = new Card[3];
        board[2] = new Card[3];

        boardOwnership = new bool?[3][];
        boardOwnership[0] = new bool?[3];
        boardOwnership[1] = new bool?[3];
        boardOwnership[2] = new bool?[3];
    }

    //Used as a short-cut in the recursion to realize we're at a terminal state
    public bool isLastMove()
    {
        int retVal = 0;
        for (int xPos = 0; xPos < 3; xPos++)
        {
            for (int yPos = 0; yPos < 3; yPos++)
            {
                if (board[xPos][yPos] != null)
                {
                    retVal += 1;
                }
            }
        }

        return retVal >= 8;
    }

    public Move makeLastMove(Card card, bool isAlpha)
    {
        int lastX = -1;
        int lastY = -1;
        for (int xPos = 0; xPos < 3; xPos++)
        {
            for (int yPos = 0; yPos < 3; yPos++)
            {
                if (board[xPos][yPos] == null)
                {
                    lastX = xPos;
                    lastY = yPos;
                    break;
                }
            }
        }

        return addCard(card, lastX, lastY, isAlpha);
    }

    //Simply checks if it's possible to play a card in a square
    public bool canPlay(int x, int y)
    {
        return board[x][y] == null;
    }

    //While traversing the recursive tree it becomes necessary to make moves on a cloned board to ensure each branch has it's own reference
    public Game clone()
    {
        Game clone = new Game();
        clone.board = board.Select(s => s.ToArray()).ToArray();
        clone.boardOwnership = boardOwnership.Select(s => s.ToArray()).ToArray();
        return clone;
    }

    //A simple function to convert the A to '10', cards in Triple Triad go from 1-A, A being worth 10
    public int getVal(char num)
    {
        if (num == 'A')
        {
            return 10;
        }
        return int.Parse(num.ToString());
    }

    //Adds the card and captures any cards possible.  Returns a score equal to the number of alpha cards on the board
    //(and the move that produced it).
    public Move addCard(Card card, int x, int y, bool isAlpha)
    {
        board[x][y] = card;
        boardOwnership[x][y] = isAlpha;

        Card westCard = x > 0 ? board[x - 1][y] : null;
        Card eastCard = x < 2 ? board[x + 1][y] : null;

        Card southCard = y < 2 ? board[x][y + 1] : null;
        Card northCard = y > 0 ? board[x][y - 1] : null;

        if (eastCard != null && getVal(eastCard.W) < getVal(card.E))
        {
            boardOwnership[x + 1][y] = isAlpha;
        }

        if (westCard != null && getVal(westCard.E) < getVal(card.W))
        {
            boardOwnership[x - 1][y] = isAlpha;
        }

        if (southCard != null && getVal(southCard.N) < getVal(card.S))
        {
            boardOwnership[x][y + 1] = isAlpha;
        }

        if (northCard != null && getVal(northCard.S) < getVal(card.N))
        {
            boardOwnership[x][y - 1] = isAlpha;
        }

        int score = boardOwnership.SelectMany(o => o).Where(o => o.HasValue && o.Value).Count();
        LastMove = new Move() { X = x, Y = y, Card = card, Score = score };
        return LastMove;
    }
}

```

Some other helper classes:

```
public class Card
{
    public int Id { get; set; }
    public String Name { get; set; }
    public char N { get; set; }
    public char S { get; set; }
    public char E { get; set; }
    public char W { get; set; }
}

public class Move
{
    public int X { get; set; }
    public int Y { get; set; }
    public Card Card { get; set; }
    public int Score { get; set; }

}

```

And lastly the solver class. More notes here:

* I followed a simple algorithm for alpha-beta pruning I found here.
* I struggled a bit to come up with a way to save what initial move got me to where I was calculating a score for. The code basically holds a stack of how it gets there and grabs the bottom of that stack when evaluating a final score, because ultimately we're evaluating the first move.
* I'm certain this can be optimized, however I am confused why it doesn't seem to actually play the best move. However, optimization thoughts are also accepted once I identify the bugs.

--

```
public class GameSolver
{

    public static Move Solve(List<Card> alphaCards, List<Card> betaCards, Game g, bool isAlpha, Move alpha, Move beta)
    {
        return Solve(alphaCards, betaCards, g, isAlpha, alpha, beta, new Stack<Move>());
    }

    public static Move Solve(List<Card> alphaCards, List<Card> betaCards, Game g, bool isAlpha, Move alpha, Move beta, Stack<Move> moves)
    {
        if (g.isLastMove())
        {
            Card lastCard = isAlpha ? alphaCards[0] : betaCards[0];

            Game cloneGame = g.clone();
            Move m = cloneGame.makeLastMove(lastCard, isAlpha);
            int value = m.Score;

            //Grabs the bottom of the stack, effectively the first move that resulted in this score
            Move firstMove = moves.ToArray().Last();
            //the score of the terminal state that resulted
            firstMove.Score = value;
            return firstMove;
        }

        List<Card> currentPlayerHand = isAlpha ? alphaCards : betaCards;

        if (isAlpha)
        {
            Move bestVal = new Move() { Score = int.MinValue };
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    if (!g.canPlay(i, j))
                    {
                        continue;
                    }

                    for (int k = 0; k < currentPlayerHand.Count; k++)
                    {
                        //Clone the list as to not interfere with other trees references
                        List<Card> newHand = new List<Card>(currentPlayerHand);
                        Card playedCard = newHand[k];
                        newHand.RemoveAt(k);

                        //Clone the game to not interfere with other tree's reference to the game
                        Game cloneGame = g.clone();
                        cloneGame.addCard(playedCard, i, j, isAlpha);

                        Move move = new Move() { Card = playedCard, X = i, Y = j };
                        //Record the move as we go down the stack, so the terminal states know how we got here
                        moves.Push(move);
                        Move value = Solve(isAlpha ? newHand : alphaCards, isAlpha ? betaCards : newHand, cloneGame, !isAlpha, alpha, beta, moves);
                        //Pop off the stack as we come back up
                        moves.Pop();

                        //Based on my understanding of the algorithm, take the max between the value and bestVal, and the max between bestVal and alpha
                        bestVal = bestVal.Score > value.Score ? bestVal : value;
                        alpha = bestVal.Score > alpha.Score ? bestVal : alpha;
                        if (beta.Score <= alpha.Score)
                        {
                            goto breakAlpha;
                        }

                    }
                }
            }

            breakAlpha:
            return bestVal;
        }
        else
        {
            Move bestVal = new Move() { Score = int.MaxValue };
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    if (!g.canPlay(i, j))
                    {
                        continue;
                    }
                    for (int k = 0; k < currentPlayerHand.Count; k++)
                    {
                        //Clone the list as to not interfere with other trees references
                        List<Card> newHand = new List<Card>(currentPlayerHand);
                        Card playedCard = newHand[k];
                        newHand.RemoveAt(k);

                        //Clone the game to not interfere with other tree's reference to the game
                        Game cloneGame = g.clone();
                        cloneGame.addCard(playedCard, i, j, isAlpha);

                        Move move = new Move() { Card = playedCard, X = i, Y = j };
                        //Record the move as we go down the stack, so the terminal states know how we got here
                        moves.Push(move);
                        Move value = Solve(isAlpha ? newHand : alphaCards, isAlpha ? betaCards : newHand, cloneGame, !isAlpha, alpha, beta, moves);
                        //Pop off the stack as we come back up
                        moves.Pop();

                        //Based on my understanding of the algorithm, take the min between the value and bestVal, and the min between bestVal and beta
                        bestVal = bestVal.Score < value.Score ? bestVal : value;
                        beta = bestVal.Score < beta.Score ? bestVal : beta;
                        if (beta.Score <= alpha.Score)
                        {
                            goto breakBeta;
                        }

                    }
                }
            }

            breakBeta:
            return bestVal;
        }
    }
}

```

Again there's no errors. I wrote a front end to play against the AI using this and it doesn't play *bad*, but it certainly doesn't play optimally. I would expect if this algorithm were working as expected I would have a very hard time beating such an AI unless my cards were very strong. Let me know if anyone requires more information on the code, I can provide it.

# Answer
> 1 votes
I figured out the issue, following another great article I found on the same site here. The link solves a tic-tac-toe game, and looks very similar to my code, except it pulled the first move out of the recursive tree, scored every first move, and pulled the highest. That seemed way more sane than what I was doing, and almost certainly was the cause of my bugs. Final game solver changed to this:

```
public class GameSolver
{
    public static Move BestMove(List<Card> alphaCards, List<Card> betaCards, Game g)
    {
        List<Move> possibleMoves = new List<Move>();
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                if (!g.canPlay(i, j))
                {
                    continue;
                }

                for (int k = 0; k < alphaCards.Count; k++)
                {
                    //Clone the list as to not interfere with other trees references
                    List<Card> newHand = new List<Card>(alphaCards);
                    Card playedCard = newHand[k];
                    newHand.RemoveAt(k);

                    //Clone the game to not interfere with other tree's reference to the game
                    Game cloneGame = g.clone();
                    cloneGame.addCard(playedCard, i, j, true);

                    int value = Solve(newHand, betaCards, cloneGame, false, int.MinValue, int.MaxValue);
                    Move m = new Move() { X = i, Y = j, Card = playedCard, Score = value };

                    possibleMoves.Add(m);
                }
            }
        }

        return possibleMoves.Where(m => m.Score == possibleMoves.Max(m => m.Score)).First();
    }

    public static int Solve(List<Card> alphaCards, List<Card> betaCards, Game g, bool isAlpha, int alpha, int beta)
    {
        if (g.isLastMove())
        {
            Card lastCard = isAlpha ? alphaCards[0] : betaCards[0];

            Game cloneGame = g.clone();
            Move m = cloneGame.makeLastMove(lastCard, isAlpha);

            return m.Score;
        }

        List<Card> currentPlayerHand = isAlpha ? alphaCards : betaCards;

        if (isAlpha)
        {
            int bestVal = int.MinValue;
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    if (!g.canPlay(i, j))
                    {
                        continue;
                    }

                    for (int k = 0; k < currentPlayerHand.Count; k++)
                    {
                        //Clone the list as to not interfere with other trees references
                        List<Card> newHand = new List<Card>(currentPlayerHand);
                        Card playedCard = newHand[k];
                        newHand.RemoveAt(k);

                        //Clone the game to not interfere with other tree's reference to the game
                        Game cloneGame = g.clone();
                        cloneGame.addCard(playedCard, i, j, isAlpha);

                        int value = Solve(isAlpha ? newHand : alphaCards, isAlpha ? betaCards : newHand, cloneGame, !isAlpha, alpha, beta);

                        bestVal = bestVal > value ? bestVal : value;
                        alpha = bestVal > alpha ? bestVal : alpha;
                        if (beta <= alpha)
                        {
                            goto breakAlpha;
                        }

                    }
                }
            }

            breakAlpha:
            return bestVal;
        }
        else
        {
            int bestVal = int.MaxValue;
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    if (!g.canPlay(i, j))
                    {
                        continue;
                    }
                    for (int k = 0; k < currentPlayerHand.Count; k++)
                    {
                        //Clone the list as to not interfere with other trees references
                        List<Card> newHand = new List<Card>(currentPlayerHand);
                        Card playedCard = newHand[k];
                        newHand.RemoveAt(k);

                        //Clone the game to not interfere with other tree's reference to the game
                        Game cloneGame = g.clone();
                        cloneGame.addCard(playedCard, i, j, isAlpha);

                        int value = Solve(isAlpha ? newHand : alphaCards, isAlpha ? betaCards : newHand, cloneGame, !isAlpha, alpha, beta);

                        bestVal = bestVal < value ? bestVal : value;
                        beta = bestVal < beta ? bestVal : beta;
                        if (beta <= alpha)
                        {
                            goto breakBeta;
                        }

                    }
                }
            }

            breakBeta:
            return bestVal;
        }
    }
}

```

---
Tags: c#
---


# Question
Title: Application.OpenURL in Unity works in inspector (PC) but not in Android
I'm using unity and I've got some simple code that should work but doesn't for some reason and I'm stuck. Basically I am just trying to open up a website through a button click "On Click ()" in an application meant for android but it does not work. The code goes as follows.

```
public string url;

public void Website()
{
    Application.OpenURL(url);
}

public void Website2(string diffURL)
{
    Application.OpenURL(diffURL);
}

public void Website3()
{
    Application.OpenURL("http://www.google.com/");
}

```

As you can see I have three different variations of the same "Application.OpenURL" testing on three different buttons and all three do not work. Some more information:

* I have paid close attention to format the websites properly with quotation marks and "http://"
* I have already set the "Internet Access" to "require" in the player settings,
* and interestingly enough, they work in the game window when testing, it is only when I upload the apk to my android device that it does not work anymore .

The buttons register I am pressing them as evident by the slight darkening of the button press when I press on my android device but nothing happens. I have seen this question asked around but no solution to my issue has been found. Are any other build settings wrong? Any other thing I should change in Unity? API level or what?(currently 19 on min and highest installed on target)

Is there some settings I should change on my android device to allow this to happen? Because as stated earlier it works when testing through the game window on unity but not on android.

(The function "Website3()" begun to work when I rebuilt the app. No changes were made. "Website1()" and "Website2()" however still do not work on android and they work perfectly fine on unity game window.)

# Answer
I found out the problem! So when you type out url for Application.OpenURL there are quotation marks around the URL and so I typed in the url string values (url and diffURL) the same way in the inspector for the "Website1()" and "website2()" examples, with quotation marks and all ("http://www.google.com/"). For some reason it does not work that way. **I took away the quotation marks** in my user string values and boom it worked (http://www.google.com/). However this still doesn't answer why "Website3()" was not working initially and then did work after I rebuilt the app even though I changed nothing. I guess it doesn't matter too much anyway since it works now.

Essentially if you are going to input a url as a string value from the inspector as opposed to hard coded into the script then DO NOT write out the url with quotation marks surrounding it.

Hopefully this helps others who may face the same issue.

Thanks to EdMarty and DMGregory.
> 3 votes

# Answer
## Good for opening website to the browser

```
string baseUri = "https://myawesomewebsite.com"
Application.OpenURL(baseUri + "/faqs.html");
Application.OpenURL(baseUri + "/contactus.html");

```

## Good for opening deployed app to the Play Store

```
string market = "market://details?id="
Application.OpenURL(market + Application.identifier);

```
> 0 votes

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


# Question
Title: Unity shader graph: Texturing optimized voxel terrain mesh
I'm new to shader programming, so I decided to use Unity's shader graph for that.

I have 256x256 texture atlas(like minecraft) with 4 16x16 block textures aligned on X axis

I can successfully assign texture depending on material ID (which is stored in UV.z) to the first block, but I've big issues with trying to make this work correctly for other blocks in the row(or in the 3 rows, cause 3 dimensions).

First block gets textured correctly, but other blocks(even if they are same material) get textures from other part of the atlas. For some reason texture won't repeat itself. (I assume reason is I need to do it myself somehow)

By current optimization, Vertices and UVs are shared between blocks only if they are of the same direction and same material ID.

My shader graph:

Atlas:

As seen in the result, even though all blocks are same material\_ID, only the first one gets atlas aligned properly. Others don't.

How would I make this work with other blocks too using shader graph?

PS: How UVs are assigned:

```
  public static Vector2 ProjectPositionToUV(Vector3 position, Direction normal)
    {
        switch (normal)
        {
            case Direction.Up:
            case Direction.Down:
                return new Vector2(position.x, position.z);
            case Direction.East:
            case Direction.West:
                return new Vector2(position.z, position.y);
            case Direction.North:
            case Direction.South:
                return new Vector2(position.x, position.y);
        }

        // Fallback for an invalid input direction.
        return Vector2.zero;
    }

```

And

```
 uv.z = data.cubeType;

```

# Answer
> 1 votes
Eventually, I've resolved my problem using Texture Arrays(using UV.z coordinate as material\_ID).

My shader:

---
Tags: unity, shaders, voxels
---


# Question
Title: Why isn't more culling being done on the GPU?
I'm interested in game development and 3D graphics; however, I'm not very experienced, so I apologize in advance if this comes across as ignorant or overly general.

The impression I get is that quite often the bottleneck in 3D games comes from the CPU having to make draw calls to the GPU. Culling seems to generally be performed on the CPU and then, for each frame, the CPU has to transfer the culled scene graph over to the GPU memory for rendering and display.

However, why can't culling be done on the GPU? It seems to be a very repetitive and predictable task that has to be done for every frame and would benefit from parallelization. Why not store the whole active scene graph in the GPU RAM; let the CPU just update what needs to be updated each frame (due to physics, animation, scripting, whatever); then fire a single 'draw' call to the GPU and have it cull and render everything? It seems to me it should be more efficient, because it would hugely reduce the amount of data transfer going on between CPU/GPU.

# Answer
> 4 votes
Non-optimality in terms of architecture. Wrong tool for the job.

GPU-optimal tasks are highly parallel: vertex processing, texture processing, computing boid motion, with all kernel-threads running in parallel from start to finish.

Culling, OTOH, is all about questions / conditionals e.g. "is this object in this view at this time given these conditions?". There are severe performance impacts when one GPU thread fails while all the others pass, because GPUs expect all pipelines to execute a kernel in parallel from start to finish.

So culling has tended to be better suited to calculation on the CPU, which is built for branching without stalling the entire pipeline (c.f. branch prediction, which GPUs lack) on a failed branch.

Think of it like this: GPU's processing profile is "many small things at once without branches"; CPU's domain is "give me any problem large or small, conditional or not, and I will crack it quickly."

And every time the GPU pipeline stalls because you were executing non-optimal tasks on it, all those threads are sitting twiddling their thumbs, which is like losing man-years of work you could have been applying to a better-suited problem, with no stalls at all.

# Answer
> 1 votes
To add to Engineer's answer the reason you can't easily parallelize culling is because it's not 'embarrassingly parallel'. If you know the view frustum does not pass x = 5 then you can eliminate everything that does not pass that line pretty easily. And there are even algorithms to do this using an octree and quadtree.

---
Tags: 3d, rendering, gpu, culling
---


# Question
Title: matrices and nesting hierarchy with game objects
Let's say we have some game objects and they are nested to form a tree:

```
- A
  - B
    - C
  - D

```

If each of those have a matrix for the scale, rotation and translation, is it then easier that they inherit the properties from the parent as well or not?

If I **do** make them inherit from the parent then:

**+** If I wan't to test if a point is inside `C` then I can get the inverse matrix and do a test. No need to worry about the matrices of `A` and `B`.

**+** I can draw `C` directly for example without the need of applying the matrix of `A` and `B`.

If I **don't** make them inherit:

**+** rotating C is more easy for example, cause there is no need to subtract from the parent to get correct values.

**+** translating one specific entity is more easy cause there is no need to update the children.

**-** Testing if a point is inside for example is harder, cause all the matrices up to the root of the be applied.

What is more common / recommended? I'm guessing it makes more sense that children don't inherit from the parent but just start with a identity matrix instead. If someone knows how blender is doing this then please tell me.

# Answer
> 2 votes
Inheritance of transformation is the main reason we like to use transformation hierarchies in game scenes.

If I want to move a car, it's convenient that I can simply move the body/root of the car, and it will bring its doors, wheels, passengers, and contents along for the ride. If I rotate the forearm bone of an animated skeleton, it should not leave the tips of the finger bones behind!

So the source of truth for an object's transformation is its local position, orientation, and scale *relative to its parent's* coordinate system. If I transform the parent without changing these local variables to compensate, the object should get carried along with the parent's transformation by default.

To keep this fast for the cases where we do want an object's world transformation — the combined/net effect of its local transformation and all the local transformations of its parent, grandparent, great^n grandparent chain — we cache this matrix as a separate variable.

When I change an object's local transformation inputs — its position/orientation/scale relative to its parent — I can construct a local transformation matrix and multiply it by the parent's world matrix to get a new world matrix for the child. Note that we didn't have to walk up the whole parent tree here, since the parent's world matrix already bakes-in the effect of the grandparents, if any. Then we roll that new world matrix down to our object's children.

If you tend to do a lot of random writes to local transformations, and relatively few reads (like just to build the matrices for rendering once per frame), you can use a dirty flag to quickly mark the world matrix out of date, then update it only on-demand, so a bunch of back-to-back transform changes only incur a single combined update cost.

---
Tags: matrix, hierarchy
---


title: Constraining ActorLocation X

text:
# Question
Title: Constraining ActorLocation X
My question is simple yet it's got me wondering..I'm trying to limit my character's ActorLocation's X movement by checking it each tick. If it's larger or smaller than my desired value I set it back to my desired min/max.

I'm talking about a classical fighting game where I'm setting the "walls". I don't want to use actual walls as it won't let my character go to exactly my desired min/max.. Feels like a cheap way out, which doesn't work correctly anyway.

So I'm doing the tick-trick..

Am I being paranoid or this actually real bad practice? I feel like I might be tearing through CPU inefficiently and I would really want to avoid that.

I get that feeling especially because I'd be constantly getting and setting Y and Z for no reason at all. Since it's a fighting game I'd be doing it twice, too.

Many thanks in advance :)

# Answer
A better way of doing this may well be to use a clamp on your character's movement component to limit where they can go in X.

https://docs.unrealengine.com/en-US/BlueprintAPI/Math/Float/Clamp\_float/index.html

This will remove the need to use the Tick function if that's your end plan.

-

Edit based on comments: As you're using InputAxis and AddMovementInput, after the InputAxis you can use a couple of branches to check the Actor Location and the value of the InputAxis. If calling movement will move your character outside the pre-defined range of X, don't execute movement.
> 1 votes

---
Tags: performance, unreal, blueprints
---


# Question
Title: Is there a way to make the enemy start its pathfinding once the player is in a certain distance than the enemy
I am currently using A stars' pathfinding code here: https://arongranberg.com/astar/. So I didn't create any scripts, and used the scripts provided by astar. But the problem here is that even though my player is very far away from my enemy, the enemy will still move towards the player, which is something I don't want. I want the enemy to only move towards the player once the player is a certain distance from the enemy. Also, I am working in unity 2d. Can anyone help me make a code for this? Edit: I have made a script that makes the enemy pathfind using Brackeys tutorial, and then I manually added a code that checks the distance between the player and the enemy, and if the distance is something like 20f, then force will be added to the enemy. But somehow it still doesn't work, so here is the code:

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

public class EnemyAI : Enemy
{
    public Transform target;
    public Transform eagle;

    public float PlayerToEnemyDistance;

    public float speed = 200f; //speed of eagle
    public float nextWaypointDistance = 3f; //the distance of the next waypoint

    Path path; //the current path we are following
    int currentWaypoint = 0; //the current waypoint along that path we are targetting
    bool reachedEndOfPath = false; //checks whether the eagle has reached the end of path or not

    Seeker seeker; //references our seeker script
    private Rigidbody2D rb;

    void Start()
    {
        seeker = GetComponent<Seeker>(); //referencing seeker script
        rb = transform.GetComponent<Rigidbody2D>(); //referencing rigidbody
        InvokeRepeating("UpdatePath", 0f, .5f); //allows the eagle to keep generating path
        rb.gravityScale = 0.000001f;
        speed = 0f;
    }

    void UpdatePath()
    {
        if(seeker.IsDone()) //so what multiple paths won't be generating at once
            seeker.StartPath(rb.position, target.position, OnPathComplete);
        //generates a path
        //first word in bracket is starting position
        //second word in bracket is ending position
        //third word in bracket is a function we call after we finish calculating the path
    }

    void OnPathComplete(Path p) //generate a path called p
    {
        if (!p.error) //if we didn't get an error for the path
        {
            path = p; //set current path to newly generate path called p
            currentWaypoint = 0; //resets progress along the path
        }
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        PlayerToEnemyDistance = (target.position.x - eagle.position.x);
        //cheks the distance between the player and eagle

        if (path == null) //if there is no path, return
            return;

        if (currentWaypoint >= path.vectorPath.Count) //checks whether eagle has reached the end waypoint
        {
            reachedEndOfPath = true; //reaches end of path
            return;
        }
        else
        {
            reachedEndOfPath = false; //doesn't reach end of path
        }
        //get the direction of the next waypoint along our path
        Vector2 direction = ((Vector2)path.vectorPath[currentWaypoint] - rb.position).normalized;
        Vector2 force = direction * speed * Time.deltaTime;

        if(PlayerToEnemyDistance <= 30)
        {
            rb.gravityScale = 0f;
            speed = 300f;
            rb.AddForce(force); //adds force
        }

        //the below line checks the distance of the next waypoint
        float distance = Vector2.Distance(rb.position, path.vectorPath[currentWaypoint]);

        if(distance < nextWaypointDistance)
        {
            currentWaypoint++;
            //we have reached our current waypoint and ready to move on to the next one
        }

        if (rb.velocity.x >= 0.01f) //flip sprites
        {
            eagle.localScale = new Vector3(-1f, 1f, 1f);
        }
        else if (rb.velocity.x <= -0.01f) //flip sprites
        {
            eagle.localScale = new Vector3(1f, 1f, 1f);
        }
    }
}

```

# Answer
So you're telling us that the AStar pathfinding is 'always active'

In this AStar module you mention, there will undoubtedly be some way to turn it on and off for individual entities (enemies) it is attached to.

What you need to do is twofold.

1. Create a 'trigger' for activating the pathfinding for an individual enemy
2. Activate the pathfinding.

For 1. I recommend that you either do a simple distance check for now, in that the enemy checks his distance from the player, then if the player is within a certain distance, trigger the pathfinding to begin, and stop the distance checking.

* you could improve this at a later date by using collision overlap events, which are usually a feature of many physics simulations in common engines.

For 2. it will be up to you to look through the code of the module, ask for support or look at documentation to find out how to enable and disable the pathfinding.
> 0 votes

---
Tags: 2d, path-finding, entity
---


# Question
Title: Find nearby users by real world location in Unity
I am looking to add a feature to my mobile game (IOS and Android) to let users connect to trade with users nearby in a certain radius based on the real world geolocation. Whats the best approach to find nearby users who are also running the game right now?

I have looked into using bluetooth using assets such as this: https://forum.unity.com/threads/android-bluetooth-multiplayer.188667/ but it seems like there is nothing for bluetooth multiplayer between android and IOS.

There is plenty of AR tools like this one: https://cloud.google.com/maps-platform/gaming however non seem to have the feature I am looking for.

Or perhaps if there is no existing solution for this. I have to share and compare player locations via a game server. However I have no idea what my first steps would be for that.

# Answer
> 1 votes
**Combined Geolocation and game server processing**

Each device (with appropriate permissions) may report its location to the server. This can be done using LocationService

You'll want to update location semi-regularly.

You can then answer polls from the device for a list of nearby players. Be sure to either anonymise or outright hide anything they don't need to know in the request. Just send a list of user-IDs and other information relevant to the trade.

Your server simply scans through its list of active players (most likely generated by looking for users that have sent their locations in the past minute or two) and compares the location data by latitude/longitude to a given decimal precision. If they match, they're in the same area and can trade. Some trial and error may be required to decide what level of precision is needed.

This spits out a list of nearby players, probably only a few at a time, and sends that back to the player who requested it.

The rest is a matter of handling trade-requests.

This is something I've actually done for a game in the past (sadly that game is no longer available).

Our system essentially treated the Trade as a series of communications around a server-side data-class.
* User A tells the server they want to trade with User B.
* The server creates a trade object, assigns the creator as User A, then pings User B with the trade-request.
* If they say yes, they're added as the second party in the trade, if no, the trade object is deleted and User A is notified that they refused.
* Once they're both in place, they can both see the Trade Object in their UI, items can be added or removed from their respective tables, and they can submit that they're happy with it.
* Once they've both agreed, the trade is performed, the items are swapped by the server, notifications are sent and the trade is marked as completed which prevents further interaction.

All of the interactions with the Trade object are handled as server requests, no information is directly sent between users at all at any stage for security reasons. The whole thing must be arbitrated by the server.

The paradigm is that users may only ever read data and make requests to change it, they cannot change the data directly.

---
Tags: unity, multiplayer, geolocation
---


# Question
Title: What is the meaning of >> and & in this code context and what they are trying to accomplish?
I am following a tutorial on YouTube for making a 2D game. There is no clear explanation on what its actually doing.

I get bit-shifting and & operator but I don't know what they mean in this context and I understand basic Java implementation.

I've done some basic trial and error with the below code by seeing how it works, I see the effects happening but don't quite comprehend on what it is supposed to be doing in the code.

Could someone please explain how the lines marked with "//\*******" work in the given context?

```
public class Screen {
    public static final int MAP_WIDTH= 64;
    public static final int MAP_WIDTH_MASK= MAP_WIDTH - 1;
    public static final int PIXEL_SIZE= 8;
    public static final int PIXEL_SIZE_MASK= MAP_WIDTH - 1;
    public int[] tiles = new int[MAP_WIDTH*MAP_WIDTH];
    public int[] colours = new int[MAP_WIDTH*MAP_WIDTH*4];
    public int xOffset = 0;
    public int yOffset = 0;
    public int width;
    public int height;
    public SpriteSheet sheet;
    public Screen(int width, int height, SpriteSheet sheet) {
        this.width = width;
        this.height = height;
        this.sheet = sheet;
        // ************ explain what the for loop is doing
        for(int i=0; i< (tiles.length); i++) {
            colours[i*4+ 0] = 0xff00ff;
            colours[i*4+ 1] = 0x0000ff;
            colours[i*4+ 2] = 0xffff00;
            colours[i*4+ 3] = 0xffffff;
        }
    }
    public void render(int[] pixels, int offset, int row) {
        //current x and y offset is 0 meaning that the player/map isn't moving in either direction - changing them repeats the map
        // >>3 - same as multiplying by 8 (size of pixel)
            //(0 * 8 ) + yOffset,        (height * 8) + yOffset
        // ************ what is the >> doing in this context?
        for(int yTile = (0 + yOffset) >> 3; yTile<=(height + yOffset) >> 3; yTile++) {
            // ************ what actually is yMin?
            int yMin = (yTile * PIXEL_SIZE) - yOffset;
            // ************ what actually is yMax?
            int yMax = yMin + PIXEL_SIZE;
            //sanity check if you go off the map - otherwise would crash
            if (yMin<0) yMin=0; // yMin could be below 0 because of the yOffset variable being changed is greater than (yTile * PIXEL_SIZE)
            if (yMax>height) yMax = height; // yMax could be above height because of the yOffset variable being changed
            // see above; applies to xTile as well
            for(int xTile = (0 + xOffset) >> 3; xTile<=(width + xOffset) >> 3; xTile++) {
                int xMin = (xTile * PIXEL_SIZE) - xOffset;
                int xMax = xMin + PIXEL_SIZE;
                if(xMin<0) xMin=0;
                if (xMax>width) xMax = width;
                 // ************ obviously this gives current tile you're on but what does & do in this context?
                int tileIndex = (xTile &(MAP_WIDTH_MASK)) + (yTile &(MAP_WIDTH_MASK))* MAP_WIDTH;
                for (int y = yMin; y < yMax; y++){
                    // ************ what does & do in this context?
                    int sheetPixel = ((y + yOffset) & PIXEL_SIZE_MASK)*sheet.width + ((xMin + xOffset)& PIXEL_SIZE_MASK);
                    // ************ is the tilePixel individual pixels in the tile?
                    int tilePixel = offset + xMin + y * row;
                    for(int x = xMin; x< xMax; x++) {
                        // ************ what is tileIndex * 4 doing?
                        int colour = tileIndex * 4 + sheet.pixels[sheetPixel++];
                        pixels[tilePixel++] = colours[colour];
                    }
                }
            }
        }
    }
}

```

# Answer
```
for(int i=0; i< (tiles.length); i++) {
        colours[i*4+ 0] = 0xff00ff;
        colours[i*4+ 1] = 0x0000ff;
        colours[i*4+ 2] = 0xffff00;
        colours[i*4+ 3] = 0xffffff;
}

```

The For-Loop at the start is generating groups of four colour entries based on how many tiles you have.

It's a little convoluted to read at a glance and given choice I'd probably not do it that way, but it's pretty efficient nonetheless.

The rest is essentially a way to offset your coordinate system to account for the individual tiles being multiple pixels in size.
The tiles are eight pixels in each axis, so it's going through telling every pixel in each tile what colour it needs to be.

Bitshifting by 3 is essentially taking the number in binary and pushing each number up a slot. eg: 5 \>\> 3 is 101 becoming 101000, which is 40. This is equivalent to multiplying by 8, which is a 1 and three zeros behind it in binary. The bitshift value is the number of 0s being added.

In this case, it serves nicely to calculate how many pixels we've got between steps so we can jump to the start of the next tile with each step of the loop. the individual pixels are handled inside the loop.

Single Ampersands are used in Bitwise operations as well as logical conditions, Wikipedia has the details on this here
> 1 votes

---
Tags: java, 2d, game-design
---


# Question
Title: How can I fix sprite vibrating randomly which is moving towards the mouse while using camera.position set to the sprite as the center?
So, when I use

```
camera.position.x = player.x;
camera.position.y = player.y;

```

to set the center of camera to my sprite, the code doesn't work as intended to. It's slightly hard to explain so i made this video(https://youtu.be/afCamx\_wB\_4) in which I show how it should work and the difference/problem when using camera.position

The code related to this is:

```
function setup() {
  createCanvas(displayWidth,displayHeight);
  level = new Level;
  player = createSprite(100,100,10,10);
  edge = createEdgeSprites();
  player.speed = 5;
}

```

```
function draw() {
  background(255);
  level.play();
  player.rotation = Math.atan2(mouseY-player.y, mouseX-player.x) * 180/PI;
  drawSprites();
}

```

```
player.collide(edge); //this part is from level.play()
var run = mouseX - player.x;
var rise = mouseY - player.y;
var length = sqrt((rise*rise) + (run*run));
var unitX = run / length;
var unitY = rise / length;
player.x += unitX * player.speed;
player.y += unitY * player.speed;

```

Also if you notice, when using camera.position, the vibration happens at specific distance of the sprite from the mouse, and the patter is that the distance is 0 right at the center of the canvas and keeps increasing as you move away from the center.

# Answer
> 0 votes
To be able to get an object to properly follow the mouse pointer and at the same time have a game world that's bigger than 1 screen, by having a camera that scroll through the game world, you'll need to include the camera's position/offset when the vector between an object and the mouse position is to be calculated.

To calculate the mouse' X-position in world space (i.e, its X-position in the game world, relative to the camera), you add the mouse' X-position and the camera's X-position together. The same addition is to be made when the mouse' Y-position in world space should be calculated but the mouse' Y-position and the camera's Y-position is added together instead.

I will make the asumption that (0, 0) is in the upper left corner of the window and that the lower right corner of the window is (window width, window height).

Example:

* If the mouse position is (200, 200) and the camera's position is (0, 0), which means the camera hasn't scrolled anything yet, then the calculated mouse world position will be (200, 200).
* If the mouse position is (200, 200) and the camera's position is (150, 150), which means the camera has scrolled a bit to the right and a bit down, then the calculated mouse world position will be (350, 350).

I'm not very experienced in javascript so the code example below will be a bit pseudo code, which you probably need to adapt to work in your javascript code.

```
camera.position.x = player.x;
camera.position.y = player.y;

/*
The mouse position in local/screen space
This is a position between (0, 0) and (window width, window height)
*/
var mouseX = GetMousePosition().x;
var mouseY = GetMousePosition().y;

/*
The mouse position in world space
This is a position between
(0, 0) and (mouseX + camera.position.x, mouseY + camera.position.y)
*/
var mouseXWorld = mouseX + camera.position.x;
var mouseYWorld = mouseY + camera.position.y;

var run     = mouseXWorld - player.x;
var rise    = mouseYWorld - player.y;
var length  = sqrt((rise * rise) + (run * run));
var unitX   = run   / length;
var unitY   = rise  / length;

player.x += unitX * player.speed;
player.y += unitY * player.speed;

```

By doing the calculations above, the camera will follow the player when the player moves and the player will move towards the mouse pointer.

---
Tags: javascript, rotation, debugging
---


# Question
Title: Modeling the logical structure of a game
I have been working on a game for a while and have encountered a problem stated below. I have been reading Sandi Metz's book on OOP (the Ruby one) and it made me wonder whether there is a way to visually represent all the classes of a program.

**The problem**: the code of the game is slowly but surely becoming harder to maintain, or should I say, to... fathom. To comprehend.

**I need** to know if there is a way to visually model the logical structure of the game's classes, and maybe some standalone pieces of code, and how classes interact with each other, ***OR*** a way to represent game entities from a game design point of view **because** it will be immeasurably easier to work on the game from both a technical and an artistic point of view if I had a visual model of the game's structure.

**I do not need** UML diagrams or a simple flowchart because they have too much info: knowing the fields and methods of my classes or the logical algorithm of my code is not what I need.

**I have thought about** using ARIS or BPMN for it, but I am not entirely sure whether the strict rules of these BPM notations would fit well with the dynamic and ever-changing nature of a game.

I apologize if this stack exchange is not the right place for this question. If no complete solution exists, then I am willing to create my own, perhaps with Qt.

Update: I have read the aforementioned book further and found out about sequence diagrams. They would fit very well, but I'm still interested whether a tool was created specifically for making games.

# Answer
> 2 votes
Honestly?

Just draw it.

Start at a high level view of just your game loop - draw what happens and under what circumstances.

Then, slowly go more into detail with different components of your game loop. Each game is bespoke, and no one rule fits all, so it's going to be best for you to decide in your own diagrams what you include and what you don't.

# Answer
> 0 votes
There have been some good responses in here about dealing with big projects, and I will only give you where my large projects are and how I handle it. Using diagrams is but one part of your toolkit for maintaining a growing code base.

For me, I don't draw that much of the layout as my project grows, but I have as a starting point. And I will say, that this can be definitely something that can be beneficial depending on the type of person you are.

I found that the best way to move forward on projects was to always implement using patterns, standard approaches and consistency that ***I KNOW***. These might not be standard thinking for other people, but if you always do things a certain way, you know that you always structure your heirarchies in a certain way then you at least be able to revisit code knowing you have an idea of how it works or how to use it. And have some level of trust in what changes you are making, this is important and sometimes overlooked. If you know you have done something in a common way, you can trust have a level of trust.

Where something in my code is complex, or requires some detail not apparent to a dev or if I revisit sometime later, I make a comment to highlight why. In games, you're always going to have bespoke components to fulfill something specific, ensuring you capture this will assist in maintaining and growing code.

---
Tags: documentation
---


# Question
Title: How do i put apps on sleep while my game is running in an Android Device
How do i put apps on sleep while my game is running in an Android Device. I m a Game Developer (intermediate Level). And i Wanna know the Can i put apps of phone running in background to sleep to free some ram and make my game run on 1 gb of phone smoothly (Android 9).

# Answer
> 1 votes
The OS on android devices handles this automatically when there is a need for more memory.

Specifically, what you are referring to sleep is moving apps to a standby state where they unload all data caches. After a second pass they will automatically save their data and state so they can shut down all tasks except background listeners and reopen later.

You have no control over this mechanism beyond taking up memory.

If your application is slowing down to declare more memory, try to load as much of the assets and metadata on initial scene load instead of in real time during gameplay. This should resolve most of your issues issues regarding memory heap footprint growth.

Any temporary variable (such as incrementing counters on loops) that will not last longer than the time in the function that creates it should be declared TLAB as to not be allocated from the main heap. This will further reduce memory heap growth.

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


# Question
Title: Why Epic don't release a pre-compiled binary tarball for Linux?
On linux, the 'recommanded' way of installing ue4 on linux is building the engine from github source. It is very time comsuming. For each new version, I need serveral hours to rebuild it. Why don't they just release a pre-compiled tarball so that we can use it right way?

# Answer
I don't know Epics specific reasoning, but the usual reason for not making binaries for "Linux" is that there is to much variation in the ecosystem and making one makes people think it should work out of the box, which creates a lot of support tickets when it doesn't. I hope that explains it.
> 2 votes

---
Tags: unreal-4, linux
---


# Question
Title: What would be the best way to create a cone representing the field of view of an entity in Godot Engine?
I would like to create a game in which PC and NPCs would have a field of view, shown as a cone in the front of the entity (see picture for an example).

As it would be the first game I develop using Godot Engine, I am wondering what would be the best way to implement this feature. Also if possible, in later versions of the game, I would like to be able to make the decor stop the field of view, like what is done in *Monaco: What's yours is mine*.

Would you have any recommendation?

# Answer
> 2 votes
This can be achieved in Godot using a simple Area2D.

First create an area2d node as a new scene and add a sprite and a collisionshape2D as children of the Area2D, rename the Area2D, something like Vision\_Cone for neatness.

Now add the sprite and fill the collisionshape2D with an appropriate shape.

Now with the Vision\_Cone selected, choose Collisions from the inspector and make sure under Mask that both the cone and the player (or what ever object interacts with the cone) are able to interact.

Next create a script for the Vision\_Cone, then close the script interface, so you are looking back at the 2D view and, with the Vision\_Cone selected, open the Node tab on the inspector. Find `body_entered(body, node)` and double click it, then choose `Vision_Cone (connecting from)` from the list.

Your Vision\_Cone.gd script will look like this

```
extends Area2D

func _on_Vision_Cone_body_entered(body: PhysicsBody2D) -> void:
    pass # Replace with function body.

```

Change it to interact with physics objects and not just Nodes, like this

```
extends Area2D

func _on_Vision_Cone_body_entered(body: PhysicsBody2D) -> void:
    pass # Replace with function body.

```

That is it for setup, now what ever you write in that function will happen when a physics object enters the collisionshape2D of the Vision\_Cone.

For a small example, this code will make the cone change colour as a physics body enters and exits the cone

```
func _on_Vision_Cone_body_entered(body: PhysicsBody2D) -> void:
        modulate = Color(0,0,0)

func _on_Vision_Cone_body_exited(body: PhysicsBody2D) -> void:
        modulate = Color(255,255,255)

```

A good tip is that if you want to know exactly which body the Vision\_Cone is interacting with, you can use

```
body.name = ""

```

So for example

```
func _on_Vision_Cone_body_entered(body: PhysicsBody2D) -> void:
    if body.name == "player":
        modulate = Color(0,0,0)

```

will only change the colour when a body with the name "Player" enters it and not when others do, this is very useful.

That is it, you can now attach the Vision\_Cone scene to any object in your game as a child and it will inherit any rotation data from the parent and just work, no need to remake it for every object.

Player is out of the cone:

Player is in the cone:

You can download and review the project for this example from my Google Drive.

# Answer
> 1 votes
I don't have much experience with Godot, so this answer is only about the theory.

---

Think of things in polar coordinates.

You can calculate an absolute angle and radius between any object that "sees" and an object that can be "seen". Using the "seer" as the origin of the polar coordinate system will be ideal.

The "seer" has a facing angle and can see some range of degrees to the left and right. If the angle between the two objects isn't within that range spread about the facing angle, then it is not "seen".
`bool angle_visible = (facing_angle - 30° <= angle_between <= facing_angle + 30°)`

If an object is too far away it can't be "seen" either.
`bool distance_visible = (r <= sight_range)`

If the angle and distance between an object and the entity is within the limits of the cone, then it *might* be "seen" by the entity.

`bool seen = angle_visible && distance_visible && not_obstructed`

To simulate obstruction of vision you can use ray-casting to see if the line between the object and the "seeing" entity is blocked. You'll need to check the distance and angles first to avoid performing ray-casts on objects that aren't in the cone at all.

```
bool CanSee(Entity other)
{
    float x_dist_between = other.X - this.X;
    float y_dist_between = other.Y - this.Y;
    float distance_between = sqrt(x_dist_between^2 + y_dist_between^2);

    if (distance_between <= max_sight_range)
    {
        float angle_between = radtodeg(atan2(y_dist_between, x_dist_between));
        // Be careful of angles near 0/360°
        // You may want to normalize angles around the facing angle
        // so that the angle_between's zero is at the facing_angle
        if (angle_between <= facing_angle + 30 && angle_between >= facing_angle - 30)
        {
            return !RayCastHitsSomething(this, other);
        }
    }

    return false;
}

```

There are more efficient ways than this to implement cone of vision though, this pseudocode was provided just as a quick example.

* Comparing squares of distances is faster than finding the square root first
* The dot product of vectors is a cheap operation that can tell you if two vectors are pointing in the same general direction or not (is object behind or in front)
* The built-in physics may have routines for raising collision events with between a circle or cone positioned at the "seer" and the objects that can be "seen". That could replace the need to implement your own distance check (and maybe angle check) if the collision detection in the game engine is fast too. Then you would only be implementing ray-casting inside the handler for the collision event instead of these checks on a frame-by-frame update.

---
Tags: godot, ui-design, graphics-design, visualization
---


# Question
Title: How can I capture only a part of my sprite sheet in my game for Java?
I have a University Project to create a simple game in Java. To challenge myself am trying to utilise sprite sheets. My issue is that the whole Sprite sheet is being shown rather than the section that I would like, the whole sprite sheet is shown. Below I will show all my classes. Any help would be much appreciated.

The Game class:

```

import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.swing.JFrame;

public class Game extends Canvas implements Runnable {

    private static final long serialVersionUID = 1L;
    public static final int WIDTH = 320; //Declares width of window
    public static final int HEIGHT = WIDTH / 12 * 9;//Declares height
    public static final int SCALE = 2;// Declares scale of window
    public final String TITLE = "2D Space Game";

    private boolean running =false;
    private Thread thread;

    private BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
    //Buffers the display of images, "loads" it.
    private BufferedImage spriteSheet = null;

    private Player p;

    public void init(){ //initialise
        BufferedImageLoader loader = new BufferedImageLoader();
        try {

            spriteSheet = loader.loadImage("/Sprite_Sheet.png");

        }catch(IOException e){
            e.printStackTrace();
            //if image path cannot be found, error produced
        }

        p = new Player(200, 200, this);
    }

    private synchronized void start(){

        if (running)
            return;//if the method is running, leave the method

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

    private synchronized void stop() {

        if(!running)
            return;

        running = false;// stops game loop
        try {
            thread.join();//joins all threads
        } catch (InterruptedException e) { //thread joining can sometimes fail. catch identifies this

            e.printStackTrace();
        }
        System.exit(1);
    }

    public void run() {
        init();
        long lastTime = System.nanoTime(); //long = int, but can store higher positive/lower negative numbers
        final double amountOfTicks = 60.0;//Will lock game at 60fps
        double ns = 1000000000 / amountOfTicks;
        double delta = 0; //calculate time passed, so if fps is behind game can catch up
        int updates = 0;// to check fps
        int frames = 0;// to check fps
        long timer = System.currentTimeMillis();

        while(running) {
            long now = System.nanoTime();
            delta += (now - lastTime) / ns;
            lastTime = now; //This negates the time taken to get from above code to here
            if(delta >= 1) {
                tick();
                updates++;
                delta--;// returns delta to not being >=1
            }
            render();
            frames++;

            if(System.currentTimeMillis() - timer > 1000) {
                timer +=1000;
                System.out.println(updates + "Ticks, Fps " + frames); //This code was used to check the ticks and fps of the game
                updates = 0;
                frames = 0;//resets, so we see ticks and fps per second rather than total
            }
        }
        stop();//calling stop method
    }

    //This game loop allows for slow computers to play the game as there is a maximum tick speed. Standard for all games.

    private void tick() {

        p.tick();

    }

    private void render() {
        //Buffer strategy handles all the buffering behind the scenes.
        BufferStrategy bs = this.getBufferStrategy(); //Returns a buffer strategy to be used by BufferStrategy, or null if one has not been created
        // Above initilises the buffer strategy

        if(bs == null) {

            createBufferStrategy(3);
            return; //If there is no buffer strategy, create 3
            //Three buffer strategy loads 3 images, which will be projected one after another. Increases speed.

        }

        Graphics g = bs.getDrawGraphics(); //creates graphics for buffers
        ///////////////////////////////////
        //Can draw in this area

        g.drawImage(image, 0, 0, getWidth(), getHeight(), this);

        p.render(g);

        ///////////////////////////////////
        g.dispose(); //gets rid of buffer once done with it
        bs.show();

    }

    public static void main(String args[]) {

        Game game = new Game();

        game.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE)); //Creates good aspect ratio
        game.setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
        game.setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));

        JFrame frame = new JFrame(game.TITLE);
        frame.add(game);
        frame.pack();//takes all of the components and sizes the frame to the sizes of its components
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Allows exit button to work
        frame.setResizable(false); //Stops player resizing window
        frame.setLocationRelativeTo(null);//Not run
        frame.setVisible(true);//Window is visible

        game.start();
    }

    public BufferedImage getSpriteSheet() {
        return spriteSheet;

        //setter, so spritesheet doesnt have to be initialised in musltple clasess
    }

}

```

The Player Class:

```

import java.awt.Graphics;
import java.awt.image.BufferedImage;

public class Player {

    private double x;//x coor'd of player
    private double y;//y coor'd of player

    private BufferedImage player;

    public Player(double x, double y, Game game) { //constructor method, will be called when player is initialised

        this.x = x;
        this.y = y;

        //sets the coordinates of the player when initialised

        /* eg p = new Player(100,100); */

        SpriteSheet ss = new SpriteSheet(game.getSpriteSheet());

        player = ss.grabImage(1, 1, 32, 32);
        //Getter is also in this method, calling the spriteSheet method from the G ame class.
    }

    public void tick() {

    }

    public void render(Graphics g) {
        g.drawImage(player, (int)x, (int)y, null);
        //.drawImage only works with integers, but we declared as double, so must cast as int

    }

}

```

The BufferedImageLoader Class:

```

import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;

public class BufferedImageLoader {

    private BufferedImage image;

    public BufferedImage loadImage(String path) throws IOException {

        image =ImageIO.read(getClass().getResource(path));
        return image;

    }
}
//This class is made to load in the buffered images.

```

The Sprite Sheet Class:

```

import java.awt.image.BufferedImage;

public class SpriteSheet {

    private BufferedImage image; // creating another Buffered Image

    public SpriteSheet(BufferedImage image) {
        this.image = image;
    }

    public BufferedImage grabImage(int col, int row, int width, int height) {

        BufferedImage img = image.getSubimage((col * 32) - 32, (row * 32) -32, width, height);
        return image;
        //Selecting the rows and columns of the spritesheet in folder res.
        //This determines what image from the sprite sheet to display, in this case the player.
    }
}

```

I appreciate that here I have dumped alot of code, but it would be challenging for me to pick it apart to just the sprite sheet code lines as the span across multiple classes. I believe the issue lies within the spritesheet class or the player class, but again I cannot be to sure. Thanks for any help!

EDIT

The sprite I would like to capture is 32 by 32, and the sprite sheet as a whole is 256 by 256.

# Answer
I think there is a minor typo in your code, see `SpriteSheet` class

```
public BufferedImage grabImage(int col, int row, int width, int height) {
    BufferedImage img = image.getSubimage((col * 32) - 32, (row * 32) -32, width, height);
    //return image; typo here!
    return img;
}

```

what actually happens:

* you crop a sub image (named `img`) from your spriteSheet image (named `image`).
* but instead of return the cropped image (`img`) you return the original image (named `image`).
* fix it by returning the cropped image (`return img;`)
> 1 votes

---
Tags: java, spritesheet
---


title: rigidbody cube falls off the ground

text:
# Question
Title: rigidbody cube falls off the ground
Inspite my ground and cube contains colliders as i apply rigidbody it falls down....use gravity

# Answer
A mesh collider is not the best solution here.

For one, they're unnecessarily expensive for collision with a flat ground plane. You're searching a polygon soup for a collision when you could be doing a cheap primitive check.

Second, a (non-convex) mesh is infinitely thin — it has no inside/outside that the physics engine can use to detect penetration.

So if your cube spawns even a millimetre below the surface, the physics engine just knows there's an intersection. It doesn't know which way to push the cube to get it "outside". So it's as likely to tunnel through the mesh and fall out the bottom — that's just as valid a way to resolve the intersection from the physics engine's point of view.

Instead, create a box collider under the floor of your market, and give it some thickness so it can catch even a fast-moving object falling into it. A primitive collider like this has a defined interior, so if the cube ends up anywhere inside that volume the physics engine can still detect the penetration and push it back out in the right direction.
> 1 votes

---
Tags: unity, c#, collision-detection, physics
---